1 4 package com.tc.objectserver.persistence.impl; 5 6 import com.tc.io.serializer.api.StringIndex; 7 import com.tc.objectserver.persistence.api.StringIndexPersistor; 8 9 import gnu.trove.TLongObjectHashMap; 10 import gnu.trove.TLongObjectIterator; 11 import gnu.trove.TObjectLongHashMap; 12 13 public class StringIndexImpl implements StringIndex { 14 private static final int NULL = 0; 15 private final StringIndexPersistor persistor; 16 private final TLongObjectHashMap indexToString; 17 private final TObjectLongHashMap stringToIndex; 18 private long counter; 19 20 public StringIndexImpl(StringIndexPersistor persistor) { 21 this(persistor, 10); 22 } 23 24 public StringIndexImpl(StringIndexPersistor persistor, int initialCapacity) { 25 this.persistor = persistor; 26 27 this.indexToString = new TLongObjectHashMap(initialCapacity); 28 this.stringToIndex = new TObjectLongHashMap(initialCapacity); 29 30 for (TLongObjectIterator i = persistor.loadMappingsInto(indexToString).iterator(); i.hasNext();) { 31 i.advance(); 32 long index = i.key(); 33 if (index > counter) counter = index; 34 this.stringToIndex.put(i.value(), index); 35 } 36 } 37 38 public synchronized long getOrCreateIndexFor(String string) { 39 if (string == null) return NULL; 40 long rv = stringToIndex.get(string); 41 if (rv < 1) { 42 rv = ++counter; 43 indexToString.put(rv, string); 44 stringToIndex.put(string, rv); 45 persistor.saveMapping(rv, string); 46 } 47 return rv; 48 } 49 50 public synchronized String getStringFor(long index) { 51 if (index == NULL) return null; 52 String rv = (String ) indexToString.get(index); 53 if (rv == null) throw new AssertionError ("Unknown index: " + index); 54 return rv; 55 } 56 57 public synchronized String toString() { 58 StringBuffer rv = new StringBuffer (); 59 rv.append("["); 60 for (TLongObjectIterator i = indexToString.iterator(); i.hasNext();) { 61 i.advance(); 62 rv.append(i.key() + "=>" + i.value()); 63 if (i.hasNext()) rv.append(", "); 64 } 65 rv.append("]"); 66 return rv.toString(); 67 } 68 69 public TObjectLongHashMap getString2LongMappings() { 71 return stringToIndex; 72 } 73 74 } 75 | Popular Tags |