Debian Codegraph @

rhino/src/org/mozilla/javascript/ObjToIntMap.java

raw symbols SCIP
1 /* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
2 *
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 package org.mozilla.javascript;
8
9 import java.io.Serializable;
10 import java.io.IOException;
11 import java.io.ObjectInputStream;
12 import java.io.ObjectOutputStream;
13
14 /**
15 * Map to associate objects to integers.
16 * The map does not synchronize any of its operation, so either use
17 * it from a single thread or do own synchronization or perform all mutation
18 * operations on one thread before passing the map to others
19 *
20 * @author Igor Bukanov
21 *
22 */
23
24 public class ObjToIntMap implements Serializable
25 {
26 static final long serialVersionUID = -1542220580748809402L;
27
28 // Map implementation via hashtable,
29 // follows "The Art of Computer Programming" by Donald E. Knuth
30
31 // ObjToIntMap is a copy cat of ObjToIntMap with API adjusted to object keys
32
33 public static class Iterator {
34
35 Iterator(ObjToIntMap master) {
36 this.master = master;
37 }
38
39 final void init(Object[] keys, int[] values, int keyCount) {
40 this.keys = keys;
41 this.values = values;
42 this.cursor = -1;
43 this.remaining = keyCount;
44 }
45
46 public void start() {
47 master.initIterator(this);
48 next();
49 }
50
51 public boolean done() {
52 return remaining < 0;
53 }
54
55 public void next() {
56 if (remaining == -1) Kit.codeBug();
57 if (remaining == 0) {
58 remaining = -1;
59 cursor = -1;
60 }else {
61 for (++cursor; ; ++cursor) {
62 Object key = keys[cursor];
63 if (key != null && key != DELETED) {
64 --remaining;
65 break;
66 }
67 }
68 }
69 }
70
71 public Object getKey() {
72 Object key = keys[cursor];
73 if (key == UniqueTag.NULL_VALUE) { key = null; }
74 return key;
75 }
76
77 public int getValue() {
78 return values[cursor];
79 }
80
81 public void setValue(int value) {
82 values[cursor] = value;
83 }
84
85 ObjToIntMap master;
86 private int cursor;
87 private int remaining;
88 private Object[] keys;
89 private int[] values;
90 }
91
92 public ObjToIntMap() {
93 this(4);
94 }
95
96 public ObjToIntMap(int keyCountHint) {
97 if (keyCountHint < 0) Kit.codeBug();
98 // Table grow when number of stored keys >= 3/4 of max capacity
99 int minimalCapacity = keyCountHint * 4 / 3;
100 int i;
101 for (i = 2; (1 << i) < minimalCapacity; ++i) { }
102 power = i;
103 if (check && power < 2) Kit.codeBug();
104 }
105
106 public boolean isEmpty() {
107 return keyCount == 0;
108 }
109
110 public int size() {
111 return keyCount;
112 }
113
114 public boolean has(Object key) {
115 if (key == null) { key = UniqueTag.NULL_VALUE; }
116 return 0 <= findIndex(key);
117 }
118
119 /**
120 * Get integer value assigned with key.
121 * @return key integer value or defaultValue if key is absent
122 */
123 public int get(Object key, int defaultValue) {
124 if (key == null) { key = UniqueTag.NULL_VALUE; }
125 int index = findIndex(key);
126 if (0 <= index) {
127 return values[index];
128 }
129 return defaultValue;
130 }
131
132 /**
133 * Get integer value assigned with key.
134 * @return key integer value
135 * @throws RuntimeException if key does not exist
136 */
137 public int getExisting(Object key) {
138 if (key == null) { key = UniqueTag.NULL_VALUE; }
139 int index = findIndex(key);
140 if (0 <= index) {
141 return values[index];
142 }
143 // Key must exist
144 Kit.codeBug();
145 return 0;
146 }
147
148 public void put(Object key, int value) {
149 if (key == null) { key = UniqueTag.NULL_VALUE; }
150 int index = ensureIndex(key);
151 values[index] = value;
152 }
153
154 /**
155 * If table already contains a key that equals to keyArg, return that key
156 * while setting its value to zero, otherwise add keyArg with 0 value to
157 * the table and return it.
158 */
159 public Object intern(Object keyArg) {
160 boolean nullKey = false;
161 if (keyArg == null) {
162 nullKey = true;
163 keyArg = UniqueTag.NULL_VALUE;
164 }
165 int index = ensureIndex(keyArg);
166 values[index] = 0;
167 return (nullKey) ? null : keys[index];
168 }
169
170 public void remove(Object key) {
171 if (key == null) { key = UniqueTag.NULL_VALUE; }
172 int index = findIndex(key);
173 if (0 <= index) {
174 keys[index] = DELETED;
175 --keyCount;
176 }
177 }
178
179 public void clear() {
180 int i = keys.length;
181 while (i != 0) {
182 keys[--i] = null;
183 }
184 keyCount = 0;
185 occupiedCount = 0;
186 }
187
188 public Iterator newIterator() {
189 return new Iterator(this);
190 }
191
192 // The sole purpose of the method is to avoid accessing private fields
193 // from the Iterator inner class to workaround JDK 1.1 compiler bug which
194 // generates code triggering VerifierError on recent JVMs
195 final void initIterator(Iterator i) {
196 i.init(keys, values, keyCount);
197 }
198
199 /** Return array of present keys */
200 public Object[] getKeys() {
201 Object[] array = new Object[keyCount];
202 getKeys(array, 0);
203 return array;
204 }
205
206 public void getKeys(Object[] array, int offset) {
207 int count = keyCount;
208 for (int i = 0; count != 0; ++i) {
209 Object key = keys[i];
210 if (key != null && key != DELETED) {
211 if (key == UniqueTag.NULL_VALUE) { key = null; }
212 array[offset] = key;
213 ++offset;
214 --count;
215 }
216 }
217 }
218
219 private static int tableLookupStep(int fraction, int mask, int power) {
220 int shift = 32 - 2 * power;
221 if (shift >= 0) {
222 return ((fraction >>> shift) & mask) | 1;
223 }
224 else {
225 return (fraction & (mask >>> -shift)) | 1;
226 }
227 }
228
229 private int findIndex(Object key) {
230 if (keys != null) {
231 int hash = key.hashCode();
232 int fraction = hash * A;
233 int index = fraction >>> (32 - power);
234 Object test = keys[index];
235 if (test != null) {
236 int N = 1 << power;
237 if (test == key
238 || (values[N + index] == hash && test.equals(key)))
239 {
240 return index;
241 }
242 // Search in table after first failed attempt
243 int mask = N - 1;
244 int step = tableLookupStep(fraction, mask, power);
245 int n = 0;
246 for (;;) {
247 if (check) {
248 if (n >= occupiedCount) Kit.codeBug();
249 ++n;
250 }
251 index = (index + step) & mask;
252 test = keys[index];
253 if (test == null) {
254 break;
255 }
256 if (test == key
257 || (values[N + index] == hash && test.equals(key)))
258 {
259 return index;
260 }
261 }
262 }
263 }
264 return -1;
265 }
266
267 // Insert key that is not present to table without deleted entries
268 // and enough free space
269 private int insertNewKey(Object key, int hash) {
270 if (check && occupiedCount != keyCount) Kit.codeBug();
271 if (check && keyCount == 1 << power) Kit.codeBug();
272 int fraction = hash * A;
273 int index = fraction >>> (32 - power);
274 int N = 1 << power;
275 if (keys[index] != null) {
276 int mask = N - 1;
277 int step = tableLookupStep(fraction, mask, power);
278 int firstIndex = index;
279 do {
280 if (check && keys[index] == DELETED) Kit.codeBug();
281 index = (index + step) & mask;
282 if (check && firstIndex == index) Kit.codeBug();
283 } while (keys[index] != null);
284 }
285 keys[index] = key;
286 values[N + index] = hash;
287 ++occupiedCount;
288 ++keyCount;
289
290 return index;
291 }
292
293 private void rehashTable() {
294 if (keys == null) {
295 if (check && keyCount != 0) Kit.codeBug();
296 if (check && occupiedCount != 0) Kit.codeBug();
297 int N = 1 << power;
298 keys = new Object[N];
299 values = new int[2 * N];
300 }
301 else {
302 // Check if removing deleted entries would free enough space
303 if (keyCount * 2 >= occupiedCount) {
304 // Need to grow: less then half of deleted entries
305 ++power;
306 }
307 int N = 1 << power;
308 Object[] oldKeys = keys;
309 int[] oldValues = values;
310 int oldN = oldKeys.length;
311 keys = new Object[N];
312 values = new int[2 * N];
313
314 int remaining = keyCount;
315 occupiedCount = keyCount = 0;
316 for (int i = 0; remaining != 0; ++i) {
317 Object key = oldKeys[i];
318 if (key != null && key != DELETED) {
319 int keyHash = oldValues[oldN + i];
320 int index = insertNewKey(key, keyHash);
321 values[index] = oldValues[i];
322 --remaining;
323 }
324 }
325 }
326 }
327
328 // Ensure key index creating one if necessary
329 private int ensureIndex(Object key) {
330 int hash = key.hashCode();
331 int index = -1;
332 int firstDeleted = -1;
333 if (keys != null) {
334 int fraction = hash * A;
335 index = fraction >>> (32 - power);
336 Object test = keys[index];
337 if (test != null) {
338 int N = 1 << power;
339 if (test == key
340 || (values[N + index] == hash && test.equals(key)))
341 {
342 return index;
343 }
344 if (test == DELETED) {
345 firstDeleted = index;
346 }
347
348 // Search in table after first failed attempt
349 int mask = N - 1;
350 int step = tableLookupStep(fraction, mask, power);
351 int n = 0;
352 for (;;) {
353 if (check) {
354 if (n >= occupiedCount) Kit.codeBug();
355 ++n;
356 }
357 index = (index + step) & mask;
358 test = keys[index];
359 if (test == null) {
360 break;
361 }
362 if (test == key
363 || (values[N + index] == hash && test.equals(key)))
364 {
365 return index;
366 }
367 if (test == DELETED && firstDeleted < 0) {
368 firstDeleted = index;
369 }
370 }
371 }
372 }
373 // Inserting of new key
374 if (check && keys != null && keys[index] != null)
375 Kit.codeBug();
376 if (firstDeleted >= 0) {
377 index = firstDeleted;
378 }
379 else {
380 // Need to consume empty entry: check occupation level
381 if (keys == null || occupiedCount * 4 >= (1 << power) * 3) {
382 // Too litle unused entries: rehash
383 rehashTable();
384 return insertNewKey(key, hash);
385 }
386 ++occupiedCount;
387 }
388 keys[index] = key;
389 values[(1 << power) + index] = hash;
390 ++keyCount;
391 return index;
392 }
393
394 private void writeObject(ObjectOutputStream out)
395 throws IOException
396 {
397 out.defaultWriteObject();
398
399 int count = keyCount;
400 for (int i = 0; count != 0; ++i) {
401 Object key = keys[i];
402 if (key != null && key != DELETED) {
403 --count;
404 out.writeObject(key);
405 out.writeInt(values[i]);
406 }
407 }
408 }
409
410 private void readObject(ObjectInputStream in)
411 throws IOException, ClassNotFoundException
412 {
413 in.defaultReadObject();
414
415 int writtenKeyCount = keyCount;
416 if (writtenKeyCount != 0) {
417 keyCount = 0;
418 int N = 1 << power;
419 keys = new Object[N];
420 values = new int[2 * N];
421 for (int i = 0; i != writtenKeyCount; ++i) {
422 Object key = in.readObject();
423 int hash = key.hashCode();
424 int index = insertNewKey(key, hash);
425 values[index] = in.readInt();
426 }
427 }
428 }
429
430 // A == golden_ratio * (1 << 32) = ((sqrt(5) - 1) / 2) * (1 << 32)
431 // See Knuth etc.
432 private static final int A = 0x9e3779b9;
433
434 private static final Object DELETED = new Object();
435
436 // Structure of kyes and values arrays (N == 1 << power):
437 // keys[0 <= i < N]: key value or null or DELETED mark
438 // values[0 <= i < N]: value of key at keys[i]
439 // values[N <= i < 2*N]: hash code of key at keys[i-N]
440
441 private transient Object[] keys;
442 private transient int[] values;
443
444 private int power;
445 private int keyCount;
446 private transient int occupiedCount; // == keyCount + deleted_count
447
448 // If true, enables consitency checks
449 private static final boolean check = false;
450
451 /* TEST START
452
453 public static void main(String[] args) {
454 if (!check) {
455 System.err.println("Set check to true and re-run");
456 throw new RuntimeException("Set check to true and re-run");
457 }
458
459 ObjToIntMap map;
460 map = new ObjToIntMap(0);
461 testHash(map, 3);
462 map = new ObjToIntMap(0);
463 testHash(map, 10 * 1000);
464 map = new ObjToIntMap();
465 testHash(map, 10 * 1000);
466 map = new ObjToIntMap(30 * 1000);
467 testHash(map, 10 * 100);
468 map.clear();
469 testHash(map, 4);
470 map = new ObjToIntMap(0);
471 testHash(map, 10 * 100);
472 }
473
474 private static void testHash(ObjToIntMap map, int N) {
475 System.out.print("."); System.out.flush();
476 for (int i = 0; i != N; ++i) {
477 Object key = testKey(i);
478 check(-1 == map.get(key, -1));
479 map.put(key, i);
480 check(i == map.get(key, -1));
481 }
482
483 System.out.print("."); System.out.flush();
484 for (int i = 0; i != N; ++i) {
485 Object key = testKey(i);
486 map.put(key, i);
487 check(i == map.get(key, -1));
488 }
489
490 check(map.size() == N);
491
492 System.out.print("."); System.out.flush();
493 Object[] keys = map.getKeys();
494 check(keys.length == N);
495 for (int i = 0; i != N; ++i) {
496 Object key = keys[i];
497 check(map.has(key));
498 }
499
500
501 System.out.print("."); System.out.flush();
502 for (int i = 0; i != N; ++i) {
503 Object key = testKey(i);
504 check(i == map.get(key, -1));
505 }
506
507 int Nsqrt = -1;
508 for (int i = 0; ; ++i) {
509 if (i * i >= N) {
510 Nsqrt = i;
511 break;
512 }
513 }
514
515 System.out.print("."); System.out.flush();
516 for (int i = 0; i != N; ++i) {
517 Object key = testKey(i * i);
518 map.put(key, i);
519 check(i == map.get(key, -1));
520 }
521
522 check(map.size() == 2 * N - Nsqrt);
523
524 System.out.print("."); System.out.flush();
525 for (int i = 0; i != N; ++i) {
526 Object key = testKey(i * i);
527 check(i == map.get(key, -1));
528 }
529
530 System.out.print("."); System.out.flush();
531 for (int i = 0; i != N; ++i) {
532 Object key = testKey(-1 - i * i);
533 map.put(key, i);
534 check(i == map.get(key, -1));
535 }
536
537 check(map.size() == 3 * N - Nsqrt);
538
539 System.out.print("."); System.out.flush();
540 for (int i = 0; i != N; ++i) {
541 Object key = testKey(-1 - i * i);
542 map.remove(key);
543 check(!map.has(key));
544 }
545
546 check(map.size() == 2 * N - Nsqrt);
547
548 System.out.print("."); System.out.flush();
549 for (int i = 0; i != N; ++i) {
550 Object key = testKey(i * i);
551 check(i == map.get(key, -1));
552 }
553
554 System.out.print("."); System.out.flush();
555 for (int i = 0; i != N; ++i) {
556 Object key = testKey(i);
557 int j = intSqrt(i);
558 if (j * j == i) {
559 check(j == map.get(key, -1));
560 }else {
561 check(i == map.get(key, -1));
562 }
563 }
564
565 System.out.print("."); System.out.flush();
566 for (int i = 0; i != N; ++i) {
567 Object key = testKey(i * i);
568 map.remove(key);
569 check(-2 == map.get(key, -2));
570 }
571
572 System.out.print("."); System.out.flush();
573 for (int i = 0; i != N; ++i) {
574 Object key = testKey(i);
575 map.put(key, i);
576 check(i == map.get(key, -2));
577 }
578
579 check(map.size() == N);
580
581 System.out.print("."); System.out.flush();
582 for (int i = 0; i != N; ++i) {
583 Object key = testKey(i);
584 check(i == map.get(key, -1));
585 }
586
587 System.out.print("."); System.out.flush();
588 ObjToIntMap copy = (ObjToIntMap)writeAndRead(map);
589 check(copy.size() == N);
590
591 for (int i = 0; i != N; ++i) {
592 Object key = testKey(i);
593 check(i == copy.get(key, -1));
594 }
595
596 System.out.print("."); System.out.flush();
597 checkSameMaps(copy, map);
598
599 System.out.println(); System.out.flush();
600 }
601
602 private static void checkSameMaps(ObjToIntMap map1, ObjToIntMap map2) {
603 check(map1.size() == map2.size());
604 Object[] keys = map1.getKeys();
605 check(keys.length == map1.size());
606 for (int i = 0; i != keys.length; ++i) {
607 check(map1.get(keys[i], -1) == map2.get(keys[i], -1));
608 }
609 }
610
611 private static void check(boolean condition) {
612 if (!condition) Kit.codeBug();
613 }
614
615 private static Object[] testPool;
616
617 private static Object testKey(int i) {
618 int MAX_POOL = 100;
619 if (0 <= i && i < MAX_POOL) {
620 if (testPool != null && testPool[i] != null) {
621 return testPool[i];
622 }
623 }
624 Object x = new Double(i + 0.5);
625 if (0 <= i && i < MAX_POOL) {
626 if (testPool == null) {
627 testPool = new Object[MAX_POOL];
628 }
629 testPool[i] = x;
630 }
631 return x;
632 }
633
634 private static int intSqrt(int i) {
635 int approx = (int)Math.sqrt(i) + 1;
636 while (approx * approx > i) {
637 --approx;
638 }
639 return approx;
640 }
641
642 private static Object writeAndRead(Object obj) {
643 try {
644 java.io.ByteArrayOutputStream
645 bos = new java.io.ByteArrayOutputStream();
646 java.io.ObjectOutputStream
647 out = new java.io.ObjectOutputStream(bos);
648 out.writeObject(obj);
649 out.close();
650 byte[] data = bos.toByteArray();
651 java.io.ByteArrayInputStream
652 bis = new java.io.ByteArrayInputStream(data);
653 java.io.ObjectInputStream
654 in = new java.io.ObjectInputStream(bis);
655 Object result = in.readObject();
656 in.close();
657 return result;
658 }catch (Exception ex) {
659 throw new RuntimeException("Unexpected");
660 }
661 }
662
663 // TEST END */
664
665 }