01: /*
02: * All content copyright (c) 2003-2006 Terracotta, Inc., except as may otherwise be noted in a separate copyright notice. All rights reserved.
03: */
04: package com.tc.objectserver.persistence.impl;
05:
06: import com.tc.io.serializer.api.StringIndex;
07: import com.tc.objectserver.persistence.api.StringIndexPersistor;
08:
09: 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,
25: int initialCapacity) {
26: this .persistor = persistor;
27:
28: this .indexToString = new TLongObjectHashMap(initialCapacity);
29: this .stringToIndex = new TObjectLongHashMap(initialCapacity);
30:
31: for (TLongObjectIterator i = persistor.loadMappingsInto(
32: indexToString).iterator(); i.hasNext();) {
33: i.advance();
34: long index = i.key();
35: if (index > counter)
36: counter = index;
37: this .stringToIndex.put(i.value(), index);
38: }
39: }
40:
41: public synchronized long getOrCreateIndexFor(String string) {
42: if (string == null)
43: return NULL;
44: long rv = stringToIndex.get(string);
45: if (rv < 1) {
46: rv = ++counter;
47: indexToString.put(rv, string);
48: stringToIndex.put(string, rv);
49: persistor.saveMapping(rv, string);
50: }
51: return rv;
52: }
53:
54: public synchronized String getStringFor(long index) {
55: if (index == NULL)
56: return null;
57: String rv = (String) indexToString.get(index);
58: if (rv == null)
59: throw new AssertionError("Unknown index: " + index);
60: return rv;
61: }
62:
63: public synchronized String toString() {
64: StringBuffer rv = new StringBuffer();
65: rv.append("[");
66: for (TLongObjectIterator i = indexToString.iterator(); i
67: .hasNext();) {
68: i.advance();
69: rv.append(i.key() + "=>" + i.value());
70: if (i.hasNext())
71: rv.append(", ");
72: }
73: rv.append("]");
74: return rv.toString();
75: }
76:
77: // For Testing
78: public TObjectLongHashMap getString2LongMappings() {
79: return stringToIndex;
80: }
81:
82: }
|