package com.xceptance.sitereports.xstream.converter;

import java.util.Map;
import java.util.WeakHashMap;

import com.thoughtworks.xstream.converters.basic.AbstractSingleValueConverter;

/**
 * Converts a String to a String. Well ok, it doesn't <i>actually</i> do any
 * conversion.
 * <p>
 * The converter always uses an external map to reduce the string occurences,
 * because String.intern() is using the PermGenSpace and wasting it. Additionally
 * the call to intern() is a native call and costs performance.
 * </p>
 * 
 * @author Rene Schwietzke
 * @see WeakHashMap
 */
public class SRStringConverter 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<String, String> cache;   

    public SRStringConverter(Map<String, String> cache)
    {
        this.cache = cache;
    }
    
    public boolean canConvert(Class type)
    {
        return type.equals(String.class);
    }

    public Object fromString(String str)
    {
        String s = cache.get(str);
        
        if (s == null)
        {
            // fill cache
            cache.put(str, str);
            
            s = str;
        }

        return s;
    }
}
