This repository has been archived by the owner on Aug 16, 2023. It is now read-only.
/
TrieMap_5Bits.java
2806 lines (2251 loc) · 72.3 KB
/
TrieMap_5Bits.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*******************************************************************************
* Copyright (c) 2013-2015 CWI
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
*
* * Michael Steindorfer - Michael.Steindorfer@cwi.nl - CWI
*******************************************************************************/
package org.eclipse.imp.pdb.facts.util;
import static org.eclipse.imp.pdb.facts.util.AbstractSpecialisedImmutableMap.entryOf;
import java.text.DecimalFormat;
import java.util.AbstractCollection;
import java.util.AbstractSet;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Deque;
import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
@SuppressWarnings("rawtypes")
public class TrieMap_5Bits<K, V> implements ImmutableMap<K, V> {
@SuppressWarnings("unchecked")
private static final TrieMap_5Bits EMPTY_MAP = new TrieMap_5Bits(CompactMapNode.EMPTY_NODE, 0,
0);
private static final boolean DEBUG = false;
private final AbstractMapNode<K, V> rootNode;
private final int hashCode;
private final int cachedSize;
TrieMap_5Bits(AbstractMapNode<K, V> rootNode, int hashCode, int cachedSize) {
this.rootNode = rootNode;
this.hashCode = hashCode;
this.cachedSize = cachedSize;
if (DEBUG) {
assert checkHashCodeAndSize(hashCode, cachedSize);
}
}
@SuppressWarnings("unchecked")
public static final <K, V> ImmutableMap<K, V> of() {
return TrieMap_5Bits.EMPTY_MAP;
}
@SuppressWarnings("unchecked")
public static final <K, V> ImmutableMap<K, V> of(Object... keyValuePairs) {
if (keyValuePairs.length % 2 != 0) {
throw new IllegalArgumentException(
"Length of argument list is uneven: no key/value pairs.");
}
ImmutableMap<K, V> result = TrieMap_5Bits.EMPTY_MAP;
for (int i = 0; i < keyValuePairs.length; i += 2) {
final K key = (K) keyValuePairs[i];
final V val = (V) keyValuePairs[i + 1];
result = result.__put(key, val);
}
return result;
}
@SuppressWarnings("unchecked")
public static final <K, V> TransientMap<K, V> transientOf() {
return TrieMap_5Bits.EMPTY_MAP.asTransient();
}
@SuppressWarnings("unchecked")
public static final <K, V> TransientMap<K, V> transientOf(Object... keyValuePairs) {
if (keyValuePairs.length % 2 != 0) {
throw new IllegalArgumentException(
"Length of argument list is uneven: no key/value pairs.");
}
final TransientMap<K, V> result = TrieMap_5Bits.EMPTY_MAP.asTransient();
for (int i = 0; i < keyValuePairs.length; i += 2) {
final K key = (K) keyValuePairs[i];
final V val = (V) keyValuePairs[i + 1];
result.__put(key, val);
}
return result;
}
private boolean checkHashCodeAndSize(final int targetHash, final int targetSize) {
int hash = 0;
int size = 0;
for (Iterator<Map.Entry<K, V>> it = entryIterator(); it.hasNext();) {
final Map.Entry<K, V> entry = it.next();
final K key = entry.getKey();
final V val = entry.getValue();
hash += key.hashCode() ^ val.hashCode();
size += 1;
}
return hash == targetHash && size == targetSize;
}
public static final int transformHashCode(final int hash) {
return hash;
}
public boolean containsKey(final Object o) {
try {
@SuppressWarnings("unchecked")
final K key = (K) o;
return rootNode.containsKey(key, transformHashCode(key.hashCode()), 0);
} catch (ClassCastException unused) {
return false;
}
}
public boolean containsKeyEquivalent(final Object o, final Comparator<Object> cmp) {
try {
@SuppressWarnings("unchecked")
final K key = (K) o;
return rootNode.containsKey(key, transformHashCode(key.hashCode()), 0, cmp);
} catch (ClassCastException unused) {
return false;
}
}
public boolean containsValue(final Object o) {
for (Iterator<V> iterator = valueIterator(); iterator.hasNext();) {
if (iterator.next().equals(o)) {
return true;
}
}
return false;
}
public boolean containsValueEquivalent(final Object o, final Comparator<Object> cmp) {
for (Iterator<V> iterator = valueIterator(); iterator.hasNext();) {
if (cmp.compare(iterator.next(), o) == 0) {
return true;
}
}
return false;
}
public V get(final Object o) {
try {
@SuppressWarnings("unchecked")
final K key = (K) o;
final Optional<V> result = rootNode
.findByKey(key, transformHashCode(key.hashCode()), 0);
if (result.isPresent()) {
return result.get();
} else {
return null;
}
} catch (ClassCastException unused) {
return null;
}
}
public V getEquivalent(final Object o, final Comparator<Object> cmp) {
try {
@SuppressWarnings("unchecked")
final K key = (K) o;
final Optional<V> result = rootNode.findByKey(key, transformHashCode(key.hashCode()),
0, cmp);
if (result.isPresent()) {
return result.get();
} else {
return null;
}
} catch (ClassCastException unused) {
return null;
}
}
public ImmutableMap<K, V> __put(final K key, final V val) {
final int keyHash = key.hashCode();
final MapResult<K, V> details = MapResult.unchanged();
final CompactMapNode<K, V> newRootNode = rootNode.updated(null, key, val,
transformHashCode(keyHash), 0, details);
if (details.isModified()) {
if (details.hasReplacedValue()) {
final int valHashOld = details.getReplacedValue().hashCode();
final int valHashNew = val.hashCode();
return new TrieMap_5Bits<K, V>(newRootNode, hashCode + ((keyHash ^ valHashNew))
- ((keyHash ^ valHashOld)), cachedSize);
}
final int valHash = val.hashCode();
return new TrieMap_5Bits<K, V>(newRootNode, hashCode + ((keyHash ^ valHash)),
cachedSize + 1);
}
return this;
}
public ImmutableMap<K, V> __putEquivalent(final K key, final V val, final Comparator<Object> cmp) {
final int keyHash = key.hashCode();
final MapResult<K, V> details = MapResult.unchanged();
final CompactMapNode<K, V> newRootNode = rootNode.updated(null, key, val,
transformHashCode(keyHash), 0, details, cmp);
if (details.isModified()) {
if (details.hasReplacedValue()) {
final int valHashOld = details.getReplacedValue().hashCode();
final int valHashNew = val.hashCode();
return new TrieMap_5Bits<K, V>(newRootNode, hashCode + ((keyHash ^ valHashNew))
- ((keyHash ^ valHashOld)), cachedSize);
}
final int valHash = val.hashCode();
return new TrieMap_5Bits<K, V>(newRootNode, hashCode + ((keyHash ^ valHash)),
cachedSize + 1);
}
return this;
}
public ImmutableMap<K, V> __putAll(final Map<? extends K, ? extends V> map) {
final TransientMap<K, V> tmpTransient = this.asTransient();
tmpTransient.__putAll(map);
return tmpTransient.freeze();
}
public ImmutableMap<K, V> __putAllEquivalent(final Map<? extends K, ? extends V> map,
final Comparator<Object> cmp) {
final TransientMap<K, V> tmpTransient = this.asTransient();
tmpTransient.__putAllEquivalent(map, cmp);
return tmpTransient.freeze();
}
public ImmutableMap<K, V> __remove(final K key) {
final int keyHash = key.hashCode();
final MapResult<K, V> details = MapResult.unchanged();
final CompactMapNode<K, V> newRootNode = rootNode.removed(null, key,
transformHashCode(keyHash), 0, details);
if (details.isModified()) {
assert details.hasReplacedValue();
final int valHash = details.getReplacedValue().hashCode();
return new TrieMap_5Bits<K, V>(newRootNode, hashCode - ((keyHash ^ valHash)),
cachedSize - 1);
}
return this;
}
public ImmutableMap<K, V> __removeEquivalent(final K key, final Comparator<Object> cmp) {
final int keyHash = key.hashCode();
final MapResult<K, V> details = MapResult.unchanged();
final CompactMapNode<K, V> newRootNode = rootNode.removed(null, key,
transformHashCode(keyHash), 0, details, cmp);
if (details.isModified()) {
assert details.hasReplacedValue();
final int valHash = details.getReplacedValue().hashCode();
return new TrieMap_5Bits<K, V>(newRootNode, hashCode - ((keyHash ^ valHash)),
cachedSize - 1);
}
return this;
}
public V put(final K key, final V val) {
throw new UnsupportedOperationException();
}
public void putAll(final Map<? extends K, ? extends V> m) {
throw new UnsupportedOperationException();
}
public void clear() {
throw new UnsupportedOperationException();
}
public V remove(final Object key) {
throw new UnsupportedOperationException();
}
public int size() {
return cachedSize;
}
public boolean isEmpty() {
return cachedSize == 0;
}
public Iterator<K> keyIterator() {
return new MapKeyIterator<>(rootNode);
}
public Iterator<V> valueIterator() {
return new MapValueIterator<>(rootNode);
}
public Iterator<Map.Entry<K, V>> entryIterator() {
return new MapEntryIterator<>(rootNode);
}
@Override
public Set<K> keySet() {
Set<K> keySet = null;
if (keySet == null) {
keySet = new AbstractSet<K>() {
@Override
public Iterator<K> iterator() {
return TrieMap_5Bits.this.keyIterator();
}
@Override
public int size() {
return TrieMap_5Bits.this.size();
}
@Override
public boolean isEmpty() {
return TrieMap_5Bits.this.isEmpty();
}
@Override
public void clear() {
TrieMap_5Bits.this.clear();
}
@Override
public boolean contains(Object k) {
return TrieMap_5Bits.this.containsKey(k);
}
};
}
return keySet;
}
@Override
public Collection<V> values() {
Collection<V> values = null;
if (values == null) {
values = new AbstractCollection<V>() {
@Override
public Iterator<V> iterator() {
return TrieMap_5Bits.this.valueIterator();
}
@Override
public int size() {
return TrieMap_5Bits.this.size();
}
@Override
public boolean isEmpty() {
return TrieMap_5Bits.this.isEmpty();
}
@Override
public void clear() {
TrieMap_5Bits.this.clear();
}
@Override
public boolean contains(Object v) {
return TrieMap_5Bits.this.containsValue(v);
}
};
}
return values;
}
@Override
public Set<java.util.Map.Entry<K, V>> entrySet() {
Set<java.util.Map.Entry<K, V>> entrySet = null;
if (entrySet == null) {
entrySet = new AbstractSet<java.util.Map.Entry<K, V>>() {
@Override
public Iterator<java.util.Map.Entry<K, V>> iterator() {
return new Iterator<Map.Entry<K, V>>() {
private final Iterator<Map.Entry<K, V>> i = entryIterator();
@Override
public boolean hasNext() {
return i.hasNext();
}
@Override
public Map.Entry<K, V> next() {
return i.next();
}
@Override
public void remove() {
i.remove();
}
};
}
@Override
public int size() {
return TrieMap_5Bits.this.size();
}
@Override
public boolean isEmpty() {
return TrieMap_5Bits.this.isEmpty();
}
@Override
public void clear() {
TrieMap_5Bits.this.clear();
}
@Override
public boolean contains(Object k) {
return TrieMap_5Bits.this.containsKey(k);
}
};
}
return entrySet;
}
@Override
public boolean equals(final Object other) {
if (other == this) {
return true;
}
if (other == null) {
return false;
}
if (other instanceof TrieMap_5Bits) {
TrieMap_5Bits<?, ?> that = (TrieMap_5Bits<?, ?>) other;
if (this.cachedSize != that.cachedSize) {
return false;
}
if (this.hashCode != that.hashCode) {
return false;
}
return rootNode.equals(that.rootNode);
} else if (other instanceof Map) {
Map that = (Map) other;
if (this.size() != that.size())
return false;
for (@SuppressWarnings("unchecked")
Iterator<Map.Entry> it = that.entrySet().iterator(); it.hasNext();) {
Map.Entry entry = it.next();
try {
@SuppressWarnings("unchecked")
final K key = (K) entry.getKey();
final Optional<V> result = rootNode.findByKey(key,
transformHashCode(key.hashCode()), 0);
if (!result.isPresent()) {
return false;
} else {
@SuppressWarnings("unchecked")
final V val = (V) entry.getValue();
if (!result.get().equals(val)) {
return false;
}
}
} catch (ClassCastException unused) {
return false;
}
}
return true;
}
return false;
}
@Override
public int hashCode() {
return hashCode;
}
@Override
public boolean isTransientSupported() {
return true;
}
@Override
public TransientMap<K, V> asTransient() {
return new TransientTrieMap_5Bits<K, V>(this);
}
/*
* For analysis purposes only.
*/
protected AbstractMapNode<K, V> getRootNode() {
return rootNode;
}
/*
* For analysis purposes only.
*/
protected Iterator<AbstractMapNode<K, V>> nodeIterator() {
return new TrieMap_5BitsNodeIterator<>(rootNode);
}
/*
* For analysis purposes only.
*/
protected int getNodeCount() {
final Iterator<AbstractMapNode<K, V>> it = nodeIterator();
int sumNodes = 0;
for (; it.hasNext(); it.next()) {
sumNodes += 1;
}
return sumNodes;
}
/*
* For analysis purposes only. Payload X Node
*/
protected int[][] arityCombinationsHistogram() {
final Iterator<AbstractMapNode<K, V>> it = nodeIterator();
final int[][] sumArityCombinations = new int[33][33];
while (it.hasNext()) {
final AbstractMapNode<K, V> node = it.next();
sumArityCombinations[node.payloadArity()][node.nodeArity()] += 1;
}
return sumArityCombinations;
}
/*
* For analysis purposes only.
*/
protected int[] arityHistogram() {
final int[][] sumArityCombinations = arityCombinationsHistogram();
final int[] sumArity = new int[33];
final int maxArity = 32; // TODO: factor out constant
for (int j = 0; j <= maxArity; j++) {
for (int maxRestArity = maxArity - j, k = 0; k <= maxRestArity - j; k++) {
sumArity[j + k] += sumArityCombinations[j][k];
}
}
return sumArity;
}
/*
* For analysis purposes only.
*/
public void printStatistics() {
final int[][] sumArityCombinations = arityCombinationsHistogram();
final int[] sumArity = arityHistogram();
final int sumNodes = getNodeCount();
final int[] cumsumArity = new int[33];
for (int cumsum = 0, i = 0; i < 33; i++) {
cumsum += sumArity[i];
cumsumArity[i] = cumsum;
}
final float threshhold = 0.01f; // for printing results
for (int i = 0; i < 33; i++) {
float arityPercentage = (float) (sumArity[i]) / sumNodes;
float cumsumArityPercentage = (float) (cumsumArity[i]) / sumNodes;
if (arityPercentage != 0 && arityPercentage >= threshhold) {
// details per level
StringBuilder bldr = new StringBuilder();
int max = i;
for (int j = 0; j <= max; j++) {
for (int k = max - j; k <= max - j; k++) {
float arityCombinationsPercentage = (float) (sumArityCombinations[j][k])
/ sumNodes;
if (arityCombinationsPercentage != 0
&& arityCombinationsPercentage >= threshhold) {
bldr.append(String.format("%d/%d: %s, ", j, k, new DecimalFormat(
"0.00%").format(arityCombinationsPercentage)));
}
}
}
final String detailPercentages = bldr.toString();
// overview
System.out.println(String.format("%2d: %s\t[cumsum = %s]\t%s", i,
new DecimalFormat("0.00%").format(arityPercentage),
new DecimalFormat("0.00%").format(cumsumArityPercentage),
detailPercentages));
}
}
}
abstract static class Optional<T> {
private static final Optional EMPTY = new Optional() {
@Override
boolean isPresent() {
return false;
}
@Override
Object get() {
return null;
}
};
@SuppressWarnings("unchecked")
static <T> Optional<T> empty() {
return EMPTY;
}
static <T> Optional<T> of(T value) {
return new Value<T>(value);
}
abstract boolean isPresent();
abstract T get();
private static final class Value<T> extends Optional<T> {
private final T value;
private Value(T value) {
this.value = value;
}
@Override
boolean isPresent() {
return true;
}
@Override
T get() {
return value;
}
}
}
static final class MapResult<K, V> {
private V replacedValue;
private boolean isModified;
private boolean isReplaced;
// update: inserted/removed single element, element count changed
public void modified() {
this.isModified = true;
}
public void updated(V replacedValue) {
this.replacedValue = replacedValue;
this.isModified = true;
this.isReplaced = true;
}
// update: neither element, nor element count changed
public static <K, V> MapResult<K, V> unchanged() {
return new MapResult<>();
}
private MapResult() {
}
public boolean isModified() {
return isModified;
}
public boolean hasReplacedValue() {
return isReplaced;
}
public V getReplacedValue() {
return replacedValue;
}
}
protected static interface INode<K, V> {
}
protected static abstract class AbstractMapNode<K, V> implements INode<K, V> {
static final int TUPLE_LENGTH = 2;
abstract boolean containsKey(final K key, final int keyHash, final int shift);
abstract boolean containsKey(final K key, final int keyHash, final int shift,
final Comparator<Object> cmp);
abstract Optional<V> findByKey(final K key, final int keyHash, final int shift);
abstract Optional<V> findByKey(final K key, final int keyHash, final int shift,
final Comparator<Object> cmp);
abstract CompactMapNode<K, V> updated(final AtomicReference<Thread> mutator, final K key,
final V val, final int keyHash, final int shift,
final MapResult<K, V> details);
abstract CompactMapNode<K, V> updated(final AtomicReference<Thread> mutator, final K key,
final V val, final int keyHash, final int shift,
final MapResult<K, V> details, final Comparator<Object> cmp);
abstract CompactMapNode<K, V> removed(final AtomicReference<Thread> mutator, final K key,
final int keyHash, final int shift, final MapResult<K, V> details);
abstract CompactMapNode<K, V> removed(final AtomicReference<Thread> mutator, final K key,
final int keyHash, final int shift, final MapResult<K, V> details,
final Comparator<Object> cmp);
static final boolean isAllowedToEdit(AtomicReference<Thread> x, AtomicReference<Thread> y) {
return x != null && y != null && (x == y || x.get() == y.get());
}
abstract boolean hasNodes();
abstract int nodeArity();
abstract AbstractMapNode<K, V> getNode(final int index);
@Deprecated
Iterator<? extends AbstractMapNode<K, V>> nodeIterator() {
return new Iterator<AbstractMapNode<K, V>>() {
int nextIndex = 0;
final int nodeArity = AbstractMapNode.this.nodeArity();
@Override
public void remove() {
throw new UnsupportedOperationException();
}
@Override
public AbstractMapNode<K, V> next() {
if (!hasNext())
throw new NoSuchElementException();
return AbstractMapNode.this.getNode(nextIndex++);
}
@Override
public boolean hasNext() {
return nextIndex < nodeArity;
}
};
}
abstract boolean hasPayload();
abstract int payloadArity();
abstract K getKey(final int index);
abstract V getValue(final int index);
abstract Map.Entry<K, V> getKeyValueEntry(final int index);
@Deprecated
abstract boolean hasSlots();
abstract int slotArity();
abstract Object getSlot(final int index);
/**
* The arity of this trie node (i.e. number of values and nodes stored
* on this level).
*
* @return sum of nodes and values stored within
*/
int arity() {
return payloadArity() + nodeArity();
}
int size() {
final Iterator<K> it = new MapKeyIterator<>(this);
int size = 0;
while (it.hasNext()) {
size += 1;
it.next();
}
return size;
}
}
protected static abstract class CompactMapNode<K, V> extends AbstractMapNode<K, V> {
static final int HASH_CODE_LENGTH = 32;
static final int BIT_PARTITION_SIZE = 5;
static final int BIT_PARTITION_MASK = 0b11111;
static final int mask(final int keyHash, final int shift) {
return (keyHash >>> shift) & BIT_PARTITION_MASK;
}
static final int bitpos(final int mask) {
return (int) (1 << mask);
}
abstract int nodeMap();
abstract int dataMap();
static final byte SIZE_EMPTY = 0b00;
static final byte SIZE_ONE = 0b01;
static final byte SIZE_MORE_THAN_ONE = 0b10;
/**
* Abstract predicate over a node's size. Value can be either
* {@value #SIZE_EMPTY}, {@value #SIZE_ONE}, or
* {@value #SIZE_MORE_THAN_ONE}.
*
* @return size predicate
*/
abstract byte sizePredicate();
@Override
abstract CompactMapNode<K, V> getNode(final int index);
boolean nodeInvariant() {
boolean inv1 = (size() - payloadArity() >= 2 * (arity() - payloadArity()));
boolean inv2 = (this.arity() == 0) ? sizePredicate() == SIZE_EMPTY : true;
boolean inv3 = (this.arity() == 1 && payloadArity() == 1) ? sizePredicate() == SIZE_ONE
: true;
boolean inv4 = (this.arity() >= 2) ? sizePredicate() == SIZE_MORE_THAN_ONE : true;
boolean inv5 = (this.nodeArity() >= 0) && (this.payloadArity() >= 0)
&& ((this.payloadArity() + this.nodeArity()) == this.arity());
return inv1 && inv2 && inv3 && inv4 && inv5;
}
abstract CompactMapNode<K, V> copyAndSetValue(final AtomicReference<Thread> mutator,
final int bitpos, final V val);
abstract CompactMapNode<K, V> copyAndInsertValue(final AtomicReference<Thread> mutator,
final int bitpos, final K key, final V val);
abstract CompactMapNode<K, V> copyAndRemoveValue(final AtomicReference<Thread> mutator,
final int bitpos);
abstract CompactMapNode<K, V> copyAndSetNode(final AtomicReference<Thread> mutator,
final int bitpos, final CompactMapNode<K, V> node);
abstract CompactMapNode<K, V> copyAndMigrateFromInlineToNode(
final AtomicReference<Thread> mutator, final int bitpos,
final CompactMapNode<K, V> node);
abstract CompactMapNode<K, V> copyAndMigrateFromNodeToInline(
final AtomicReference<Thread> mutator, final int bitpos,
final CompactMapNode<K, V> node);
static final <K, V> CompactMapNode<K, V> mergeTwoKeyValPairs(final K key0, final V val0,
final int keyHash0, final K key1, final V val1, final int keyHash1,
final int shift) {
assert !(key0.equals(key1));
if (shift >= HASH_CODE_LENGTH) {
// throw new
// IllegalStateException("Hash collision not yet fixed.");
return new HashCollisionMapNode_5Bits<>(keyHash0,
(K[]) new Object[] { key0, key1 },
(V[]) new Object[] { val0, val1 });
}
final int mask0 = mask(keyHash0, shift);
final int mask1 = mask(keyHash1, shift);
if (mask0 != mask1) {
// both nodes fit on same level
final int dataMap = (int) (bitpos(mask0) | bitpos(mask1));
if (mask0 < mask1) {
return nodeOf(null, (int) (0), dataMap, new Object[] { key0, val0, key1, val1 });
} else {
return nodeOf(null, (int) (0), dataMap, new Object[] { key1, val1, key0, val0 });
}
} else {
final CompactMapNode<K, V> node = mergeTwoKeyValPairs(key0, val0, keyHash0, key1,
val1, keyHash1, shift + BIT_PARTITION_SIZE);
// values fit on next level
final int nodeMap = bitpos(mask0);
return nodeOf(null, nodeMap, (int) (0), new Object[] { node });
}
}
static final CompactMapNode EMPTY_NODE;
static {
EMPTY_NODE = new BitmapIndexedMapNode<>(null, (int) (0), (int) (0), new Object[] {});
};
static final <K, V> CompactMapNode<K, V> nodeOf(final AtomicReference<Thread> mutator,
final int nodeMap, final int dataMap, final Object[] nodes) {
return new BitmapIndexedMapNode<>(mutator, nodeMap, dataMap, nodes);
}
@SuppressWarnings("unchecked")
static final <K, V> CompactMapNode<K, V> nodeOf(AtomicReference<Thread> mutator) {
return EMPTY_NODE;
}
static final <K, V> CompactMapNode<K, V> nodeOf(AtomicReference<Thread> mutator,
final int nodeMap, final int dataMap, final K key, final V val) {
assert nodeMap == 0;
return nodeOf(mutator, (int) (0), dataMap, new Object[] { key, val });
}
static final int index(final int bitmap, final int bitpos) {
return java.lang.Integer.bitCount(bitmap & (bitpos - 1));
}
static final int index(final int bitmap, final int mask, final int bitpos) {
return (bitmap == -1) ? mask : index(bitmap, bitpos);
}
int dataIndex(final int bitpos) {
return java.lang.Integer.bitCount(dataMap() & (bitpos - 1));
}
int nodeIndex(final int bitpos) {
return java.lang.Integer.bitCount(nodeMap() & (bitpos - 1));
}
CompactMapNode<K, V> nodeAt(final int bitpos) {
return getNode(nodeIndex(bitpos));
}
boolean containsKey(final K key, final int keyHash, final int shift) {
final int mask = mask(keyHash, shift);
final int bitpos = bitpos(mask);
final int dataMap = dataMap();
if ((dataMap & bitpos) != 0) {
final int index = index(dataMap, mask, bitpos);
return getKey(index).equals(key);
}
final int nodeMap = nodeMap();
if ((nodeMap & bitpos) != 0) {
final int index = index(nodeMap, mask, bitpos);
return getNode(index).containsKey(key, keyHash, shift + BIT_PARTITION_SIZE);
}
return false;
}
boolean containsKey(final K key, final int keyHash, final int shift,
final Comparator<Object> cmp) {
final int mask = mask(keyHash, shift);
final int bitpos = bitpos(mask);
final int dataMap = dataMap();
if ((dataMap & bitpos) != 0) {
final int index = index(dataMap, mask, bitpos);
return cmp.compare(getKey(index), key) == 0;
}
final int nodeMap = nodeMap();
if ((nodeMap & bitpos) != 0) {
final int index = index(nodeMap, mask, bitpos);