package com.thoughtworks.xstream.converters.basic;

import java.util.Collections;
import java.util.Map;
import java.util.WeakHashMap;

/**
 * Converts a String to a String ;). Well ok, it doesn't
 * <i>actually</i> do any conversion.
 * <p>The converter uses a map to reuse instances. This map is by default a synchronized {@link WeakHashMap}.</p>
 *
 * @author Joe Walnes
 * @author Rene Schwietzke
 * @see String#intern()
 */
public class StringConverter extends AbstractSingleValueConverter {

    /**
     * A Map to store strings as long as needed to map similar strings onto the same
     * instance and conserve memory. The map can be set from the outside during
     * construction, so it can be a lru map or a weak map, sychronised or not.
     */
    private final Map cache;

    public StringConverter(Map map) {
        this.cache = map;
    }

    public StringConverter() {
        this(Collections.synchronizedMap(new WeakHashMap()));
    }

    public boolean canConvert(Class type) {
        return type.equals(String.class);
    }

    public Object fromString(String str) {
        String s = (String)cache.get(str);

        if (s == null) {
            // fill cache
            cache.put(str, str);

            s = str;
        }

        return s;
    }

}

@@ -45,16 +45,52 @@
 basic;%0A%0A
+import java.lang.ref.WeakReference;%0A
 import j
@@ -164,16 +164,17 @@
 shMap;%0A%0A
+%0A
 /**%0A * C
@@ -205,16 +205,26 @@
 ring ;).
+%0A * %3Cp%3E%0A *
  Well ok
@@ -235,19 +235,16 @@
  doesn't
-%0A *
  %3Ci%3Eactu
@@ -270,23 +270,17 @@
 version.
-%0A * %3Cp%3E
+ 
 The conv
@@ -330,16 +330,19 @@
 ap is by
+%0A *
  default
@@ -377,16 +377,20 @@
 ashMap%7D.
+%0A * 
 %3C/p%3E%0A *%0A
@@ -438,16 +438,46 @@
 wietzke%0A
+ * @author J&ouml;rg Schaible%0A
  * @see 
@@ -657,23 +657,16 @@
 the same
-%0A     *
  instanc
@@ -691,16 +691,23 @@
 ory. The
+%0A     *
  map can
@@ -737,23 +737,16 @@
 e during
-%0A     *
  constru
@@ -771,11 +771,11 @@
 e a 
-lru
+LRU
  map
@@ -875,16 +875,22 @@
 nverter(
+final 
 Map map)
@@ -904,13 +904,8 @@
     
-this.
 cach
@@ -1050,16 +1050,22 @@
 Convert(
+final 
 Class ty
@@ -1148,16 +1148,22 @@
 mString(
+final 
 String s
@@ -1180,40 +1180,123 @@
     
-String s = (String)cache
+final WeakReference ref = (WeakReference)cache.get(str);%0A        String s = (String)(ref == null ? null : ref
 .get(
-str
+)
 );%0A%0A
@@ -1373,20 +1373,39 @@
 ut(str, 
+new WeakReference(
 str)
+)
 ;%0A%0A     
@@ -1455,11 +1455,10 @@
 ;%0A    %7D%0A
-%0A
 %7D%0A

Fix cache in StringConverter (XSTR-410).