1 19 20 package org.netbeans.editor.ext; 21 22 import org.netbeans.editor.StringMap; 23 24 31 32 public class StringCache { 33 34 private static final int DEFAULT_MAX_SIZE = 300; 35 36 private static final int DEFAULT_INITIAL_CAPACITY = 701; 37 38 int maxSize; 39 40 int size; 41 42 StringMap strMap; 43 44 45 private Entry chain; 46 47 48 private Entry endChain; 49 50 51 private Entry freeEntry; 52 53 public int statQueries; public int statHits; 56 public StringCache() { 57 this(DEFAULT_MAX_SIZE, DEFAULT_INITIAL_CAPACITY); 58 } 59 60 public StringCache(int maxSize) { 61 this(maxSize, 2 * maxSize); 62 } 63 64 public StringCache(int maxSize, int initialMapCapacity) { 65 this.maxSize = maxSize; 66 strMap = new StringMap(initialMapCapacity); 67 } 68 69 private void toStart(Entry e) { 70 if (e != chain) { 71 Entry ep = e.prev; Entry en = e.next; 74 if (en != null) { 75 en.prev = ep; 76 } else { endChain = ep; 78 } 79 ep.next = en; 80 81 if (chain != null) { 83 e.next = chain; 84 chain.prev = e; 85 } 86 chain = e; 87 } 88 } 89 90 public String getString(char[] chars, int offset, int len) { 91 statQueries++; 92 Object o = strMap.get(chars, offset, len); 93 String ret; 94 if (o instanceof Entry) { 95 Entry e = (Entry)o; 96 toStart(e); 97 statHits++; 98 ret = e.str; 99 } else if (o instanceof String ) { 100 statHits++; 101 ret = (String )o; 102 } else { ret = new String (chars, offset, len); 104 storeString(ret); 105 } 106 return ret; 107 } 108 109 110 private void removeString(String s) { 111 Object o = strMap.remove(s); 112 if (o instanceof Entry) { 113 Entry e = (Entry)o; 114 Entry ep = e.prev; 115 Entry en = e.next; 116 117 if (e == chain) { 118 chain = en; 119 if (e == endChain) { 120 endChain = null; 121 } 122 } else { if (en != null) { 124 en.prev = ep; 125 } else { 126 endChain = ep; 127 } 128 } 129 130 freeEntry = e; size--; 132 } 133 137 } 138 139 140 private void storeString(String s) { 141 Entry e; 142 if (size >= maxSize) { 143 e = endChain; 145 toStart(e); 146 strMap.remove(e.str); 147 e.str = s; 148 } else { if (freeEntry != null) { 150 e = freeEntry; 151 freeEntry = null; 152 e.str = s; 153 e.next = chain; 154 } else { 155 e = new Entry(s, chain); 156 } 157 158 if (chain != null) { 159 chain.prev = e; 160 } else { endChain = e; 162 } 163 chain = e; 164 size++; 165 } 166 strMap.put(s, e); 167 } 168 169 172 public void putSurviveString(String s) { 173 removeString(s); 174 strMap.put(s, s); 175 } 176 177 static class Entry { 178 179 Entry(String str, Entry next) { this.str = str; 181 this.next = next; 182 } 183 184 String str; 185 186 Entry next; 187 188 Entry prev; 189 190 } 191 192 public String toString() { 193 String ret = "size=" + size + ", maxSize=" + maxSize + ", statHits=" + statHits + ", statQueries=" + statQueries; if (statQueries > 0) { 196 ret += ", hit ratio=" + (statHits * 100 / statQueries) + "%"; } 198 return ret; 199 } 200 201 } 202 | Popular Tags |