KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > thaiopensource > relaxng > impl > PatternInterner


1 package com.thaiopensource.relaxng.impl;
2
3
4 final class PatternInterner {
5   private static final int INIT_SIZE = 256;
6   private static final float LOAD_FACTOR = 0.3f;
7   private Pattern[] table;
8   private int used;
9   private int usedLimit;
10
11   PatternInterner() {
12     table = null;
13     used = 0;
14     usedLimit = 0;
15   }
16
17   PatternInterner(PatternInterner parent) {
18     table = parent.table;
19     if (table != null)
20       table = (Pattern[])table.clone();
21     used = parent.used;
22     usedLimit = parent.usedLimit;
23   }
24
25   Pattern intern(Pattern p) {
26     int h;
27
28     if (table == null) {
29       table = new Pattern[INIT_SIZE];
30       usedLimit = (int)(INIT_SIZE * LOAD_FACTOR);
31       h = firstIndex(p);
32     }
33     else {
34       for (h = firstIndex(p); table[h] != null; h = nextIndex(h)) {
35     if (p.samePattern(table[h]))
36       return table[h];
37       }
38     }
39     if (used >= usedLimit) {
40       // rehash
41
Pattern[] oldTable = table;
42       table = new Pattern[table.length << 1];
43       for (int i = oldTable.length; i > 0;) {
44     --i;
45     if (oldTable[i] != null) {
46       int j;
47       for (j = firstIndex(oldTable[i]); table[j] != null; j = nextIndex(j))
48         ;
49       table[j] = oldTable[i];
50     }
51       }
52       for (h = firstIndex(p); table[h] != null; h = nextIndex(h))
53     ;
54       usedLimit = (int)(table.length * LOAD_FACTOR);
55     }
56     used++;
57     table[h] = p;
58     return p;
59   }
60
61   private int firstIndex(Pattern p) {
62     return p.patternHashCode() & (table.length - 1);
63   }
64
65   private int nextIndex(int i) {
66     return i == 0 ? table.length - 1 : i - 1;
67   }
68 }
69
Popular Tags