/
PersistentHashMap.java
1606 lines (1406 loc) · 43 KB
/
PersistentHashMap.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) Rich Hickey. All rights reserved.
* The use and distribution terms for this software are covered by the
* Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
* which can be found in the file epl-v10.html at the root of this distribution.
* By using this software in any fashion, you are agreeing to be bound by
* the terms of this license.
* You must not remove this notice, or any other, from this software.
**/
package com.trifork.clj_lang;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicReference;
import com.trifork.clj_ds.PersistentMap;
/*
A persistent rendition of Phil Bagwell's Hash Array Mapped Trie
Uses path copying for persistence
HashCollision leaves vs. extended hashing
Node polymorphism vs. conditionals
No sub-tree pools or root-resizing
Any errors are my own
*/
public class PersistentHashMap<K,V> extends APersistentMap<K,V> implements IEditableCollection<MapEntry<K, V>>, IObj, PersistentMap<K, V> {
final int count;
final INode root;
final boolean hasNull;
final V nullValue;
final IPersistentMap _meta;
final public static PersistentHashMap EMPTY = new PersistentHashMap(0, null, false, null);
final private static Object NOT_FOUND = new Object();
@SuppressWarnings("unchecked")
final public static <K,V> PersistentHashMap<K, V> emptyMap() {
return EMPTY;
}
@SuppressWarnings("unchecked")
static public <K,V> PersistentHashMap<K,V> create(Map<? extends K,? extends V> other){
ITransientMap<K,V> ret = EMPTY.asTransient();
for(Map.Entry<? extends K, ? extends V> e : other.entrySet())
{
ret = ret.assoc(e.getKey(), e.getValue());
}
return (PersistentHashMap<K, V>) ret.persistentMap();
}
/*
* @param init {key1,val1,key2,val2,...}
*/
@SuppressWarnings("unchecked")
public static <K,V> PersistentHashMap<K,V> create(Object... init){
ITransientMap<K,V> ret = EMPTY.asTransient();
for(int i = 0; i < init.length; i += 2)
{
K k = (K) init[i];
V v = (V) init[i+1];
ret = ret.assoc(k, v);
}
return (PersistentHashMap<K,V>) ret.persistentMap();
}
public static <K,V> PersistentHashMap<K,V> createWithCheck(Object... init){
ITransientMap<K, V> ret = EMPTY.asTransient();
for(int i = 0; i < init.length; i += 2)
{
ret = ret.assoc((K) init[i], (V) init[i + 1]);
if(ret.count() != i/2 + 1)
throw new IllegalArgumentException("Duplicate key: " + init[i]);
}
return (PersistentHashMap<K, V>) ret.persistentMap();
}
static public <K,V> PersistentHashMap<K,V> create(ISeq items){
ITransientMap<K,V> ret = EMPTY.asTransient();
for(; items != null; items = items.next().next())
{
if(items.next() == null)
throw new IllegalArgumentException(String.format("No value supplied for key: %s", items.first()));
ret = ret.assoc((K) items.first(), (V) RT.second(items));
}
return (PersistentHashMap<K,V>) ret.persistentMap();
}
static public <K, V> PersistentHashMap<K, V> createWithCheck(ISeq items){
ITransientMap<K, V> ret = EMPTY.asTransient();
for(int i=0; items != null; items = items.next().next(), ++i)
{
if(items.next() == null)
throw new IllegalArgumentException(String.format("No value supplied for key: %s", items.first()));
ret = ret.assoc((K) items.first(), (V) RT.second(items));
if(ret.count() != i + 1)
throw new IllegalArgumentException("Duplicate key: " + items.first());
}
return (PersistentHashMap<K, V>) ret.persistentMap();
}
/*
* @param init {key1,val1,key2,val2,...}
*/
@SuppressWarnings("unchecked")
public static <K,V> PersistentHashMap<K,V> create(IPersistentMap meta, Object... init){
return create(init).withMeta(meta);
}
PersistentHashMap(int count, INode root, boolean hasNull, V nullValue){
this.count = count;
this.root = root;
this.hasNull = hasNull;
this.nullValue = nullValue;
this._meta = null;
}
public PersistentHashMap(IPersistentMap meta, int count, INode root, boolean hasNull, V nullValue){
this._meta = meta;
this.count = count;
this.root = root;
this.hasNull = hasNull;
this.nullValue = nullValue;
}
static int hash(Object k){
return Util.hasheq(k);
}
public boolean containsKey(Object key){
if(key == null)
return hasNull;
return (root != null) ? root.find(0, hash(key), key, NOT_FOUND) != NOT_FOUND : false;
}
public IMapEntry<K,V> entryAt(K key){
if(key == null)
return hasNull ? new MapEntry<K,V>(null, nullValue) : null;
return (root != null) ? root.find(0, hash(key), key) : null;
}
public PersistentMap<K,V> assoc(K key, V val){
if(key == null) {
if(hasNull && val == nullValue)
return this;
return new PersistentHashMap<K,V>(meta(), hasNull ? count : count + 1, root, true, val);
}
Box addedLeaf = new Box(null);
INode newroot = (root == null ? BitmapIndexedNode.EMPTY : root)
.assoc(0, hash(key), key, val, addedLeaf);
if(newroot == root)
return this;
return new PersistentHashMap<K,V>(meta(), addedLeaf.val == null ? count : count + 1, newroot, hasNull, nullValue);
}
public V valAt(K key, V notFound){
if(key == null)
return hasNull ? nullValue : notFound;
return (V) (root != null ? root.find(0, hash(key), key, notFound) : notFound);
}
public V valAt(K key){
return valAt(key, null);
}
public PersistentMap<K,V> assocEx(K key, V val) {
if(containsKey(key))
throw Util.runtimeException("Key already present");
return assoc(key, val);
}
public PersistentMap<K,V> without(K key){
if(key == null)
return hasNull ? new PersistentHashMap<K,V>(meta(), count - 1, root, false, null) : this;
if(root == null)
return this;
INode newroot = root.without(0, hash(key), key);
if(newroot == root)
return this;
return new PersistentHashMap<K,V>(meta(), count - 1, newroot, hasNull, nullValue);
}
public Iterator<Map.Entry<K, V>> iterator2(){
return new Iterator<Map.Entry<K, V>>() {
ISeq<IMapEntry<K, V>> seq = seq();
public boolean hasNext() {
return seq != null;
}
@Override
public Map.Entry<K, V> next() {
Entry<K,V> first = seq.first();
seq = seq.next();
return first;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
public Iterator<Map.Entry<K, V>> iterator(){
final Iterator<Map.Entry<K, V>> s = root != null ? root.nodeIt(false) : new EmptyIterator();
return hasNull ? new Iterator<Map.Entry<K, V>>(){
Iterator<Map.Entry<K, V>> i = s;
boolean nullReady = true;
public boolean hasNext() {
return nullReady || i.hasNext();
}
@Override
public Map.Entry<K, V> next() {
if (nullReady) {
nullReady = false;
return new MapEntry<K,V>(null, PersistentHashMap.this.nullValue);
}
return i.next();
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
} : s;
}
public Iterator<Map.Entry<K, V>> reverseIterator(){
final Iterator<Map.Entry<K, V>> s = root != null ? root.nodeIt(true) : new EmptyIterator();
return hasNull ? new Iterator<Map.Entry<K, V>>(){
Iterator<Map.Entry<K, V>> i = s;
boolean nullReady = true;
public boolean hasNext() {
return nullReady || i.hasNext();
}
@Override
public Map.Entry<K, V> next() {
if (i.hasNext()) {
return i.next();
} else if (nullReady) {
nullReady = false;
return new MapEntry<K,V>(null, PersistentHashMap.this.nullValue);
}
throw new IllegalStateException();
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
} : s;
}
public Object kvreduce(IFn f, Object init){
init = hasNull?f.invoke(init,null,nullValue):init;
if(RT.isReduced(init))
return ((IDeref)init).deref();
if(root != null){
return root.kvreduce(f,init);
}
return init;
}
public Object fold(long n, final IFn combinef, final IFn reducef,
IFn fjinvoke, final IFn fjtask, final IFn fjfork, final IFn fjjoin){
//we are ignoring n for now
Callable top = new Callable(){
public Object call() throws Exception{
Object ret = combinef.invoke();
if(root != null)
ret = combinef.invoke(ret, root.fold(combinef,reducef,fjtask,fjfork,fjjoin));
return hasNull?
combinef.invoke(ret,reducef.invoke(combinef.invoke(),null,nullValue))
:ret;
}
};
return fjinvoke.invoke(top);
}
public int count(){
return count;
}
public ISeq<IMapEntry<K, V>> seq(){
ISeq<IMapEntry<K, V>> s = root != null ? root.nodeSeq() : null;
return hasNull ? new Cons<IMapEntry<K, V>>(new MapEntry<K,V>(null, nullValue), s) : s;
}
public Iterator<Map.Entry<K, V>> iteratorFrom(K key){
if (hasNull) {throw new UnsupportedOperationException("not supported for maps with null entries yet");}
Iterator<Map.Entry<K, V>> s = root != null ? root.nodeItFrom(0, hash(key), key) : new EmptyIterator();
return s;
}
public IPersistentCollection empty(){
return EMPTY.withMeta(meta());
}
static int mask(int hash, int shift){
//return ((hash << shift) >>> 27);// & 0x01f;
return (hash >>> shift) & 0x01f;
}
public PersistentHashMap withMeta(IPersistentMap meta){
return new PersistentHashMap(meta, count, root, hasNull, nullValue);
}
public TransientHashMap asTransient() {
return new TransientHashMap(this);
}
public IPersistentMap meta(){
return _meta;
}
static final class TransientHashMap<K,V> extends ATransientMap<K,V> {
AtomicReference<Thread> edit;
INode root;
int count;
boolean hasNull;
V nullValue;
final Box leafFlag = new Box(null);
TransientHashMap(PersistentHashMap<K,V> m) {
this(new AtomicReference<Thread>(Thread.currentThread()), m.root, m.count, m.hasNull, m.nullValue);
}
TransientHashMap(AtomicReference<Thread> edit, INode root, int count, boolean hasNull, V nullValue) {
this.edit = edit;
this.root = root;
this.count = count;
this.hasNull = hasNull;
this.nullValue = nullValue;
}
TransientHashMap<K,V> doAssoc(K key, V val) {
if (key == null) {
if (this.nullValue != val)
this.nullValue = (V) val;
if (!hasNull) {
this.count++;
this.hasNull = true;
}
return this;
}
// Box leafFlag = new Box(null);
leafFlag.val = null;
INode n = (root == null ? BitmapIndexedNode.EMPTY : root)
.assoc(edit, 0, hash(key), key, val, leafFlag);
if (n != this.root)
this.root = n;
if(leafFlag.val != null) this.count++;
return this;
}
TransientHashMap<K,V> doWithout(K key) {
if (key == null) {
if (!hasNull) return this;
hasNull = false;
nullValue = null;
this.count--;
return this;
}
if (root == null) return this;
// Box leafFlag = new Box(null);
leafFlag.val = null;
INode n = root.without(edit, 0, hash(key), key, leafFlag);
if (n != root)
this.root = n;
if(leafFlag.val != null) this.count--;
return this;
}
PersistentHashMap<K,V> doPersistent() {
edit.set(null);
return new PersistentHashMap<K,V>(count, root, hasNull, nullValue);
}
V doValAt(K key, V notFound) {
if (key == null)
if (hasNull)
return nullValue;
else
return notFound;
if (root == null)
return null;
return (V) root.find(0, hash(key), key, notFound);
}
int doCount() {
return count;
}
void ensureEditable(){
Thread owner = edit.get();
if(owner == Thread.currentThread())
return;
if(owner != null)
throw new IllegalAccessError("Transient used by non-owner thread");
throw new IllegalAccessError("Transient used after persistent! call");
}
public IPersistentCollection persistent() {
// TODO Auto-generated method stub
return persistentMap();
}
}
static interface INode extends Serializable {
INode assoc(int shift, int hash, Object key, Object val, Box addedLeaf);
Iterator nodeIt(boolean reverse);
Iterator nodeItFrom(int shift, int hash, Object key);
INode without(int shift, int hash, Object key);
IMapEntry find(int shift, int hash, Object key);
Object find(int shift, int hash, Object key, Object notFound);
ISeq nodeSeq();
INode assoc(AtomicReference<Thread> edit, int shift, int hash, Object key, Object val, Box addedLeaf);
INode without(AtomicReference<Thread> edit, int shift, int hash, Object key, Box removedLeaf);
public Object kvreduce(IFn f, Object init);
Object fold(IFn combinef, IFn reducef, IFn fjtask, IFn fjfork, IFn fjjoin);
}
final static class ArrayNode implements INode{
int count;
final INode[] array;
final AtomicReference<Thread> edit;
ArrayNode(AtomicReference<Thread> edit, int count, INode[] array){
this.array = array;
this.edit = edit;
this.count = count;
}
public Iterator nodeItFrom(int shift, int hash, Object key) {
return new ArrayNodeIterator(this, shift, hash, key);
}
static class ArrayNodeIterator implements Iterator {
int index;
Iterator current;
INode[] array;
int shift, hash;
Object key;
public ArrayNodeIterator(ArrayNode an) {
array = an.array;
moveCurIfNeeded();
}
public ArrayNodeIterator(ArrayNode an, int shift, int hash, Object key) {
array = an.array;
this.shift = shift;
this.hash = hash;
this.key = key;
moveCurTo();
}
private void moveCurTo() {
index = mask(hash, shift);
INode node = array[index];
if(node == null)
return;
current = node.nodeItFrom(shift + 5, hash, key);
index += 1;
}
public boolean hasNext() {
while (current != null && !current.hasNext()) {
moveCurIfNeeded();
}
return current != null && current.hasNext();
}
private void moveCurIfNeeded() {
if (current != null && current.hasNext()) return;
while (index < array.length && array[index] == null) {index += 1;};
current = (index == array.length) ? null : array[index++].nodeIt(false);
}
@Override
public Object next() {
return current.next();
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
static final class ReverseArrayNodeIterator implements Iterator {
int index;
Iterator current;
INode[] array;
int shift, hash;
Object key;
public ReverseArrayNodeIterator(ArrayNode an) {
this.array = an.array;
this.index = array.length-1;
moveCurIfNeeded();
}
private void moveCurIfNeeded() {
if (current != null && current.hasNext()) return;
while (index >= 0 && array[index] == null) {index -= 1;};
current = (index < 0) ? null : array[index--].nodeIt(true);
}
public boolean hasNext() {
while (current != null && !current.hasNext()) {
moveCurIfNeeded();
}
return current != null && current.hasNext();
}
@Override
public Object next() {
return current.next();
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
public Iterator nodeIt(boolean reverse) {
return reverse?new ReverseArrayNodeIterator(this): new ArrayNodeIterator(this);
}
public INode assoc(int shift, int hash, Object key, Object val, Box addedLeaf){
int idx = mask(hash, shift);
INode node = array[idx];
if(node == null)
return new ArrayNode(null, count + 1, cloneAndSet(array, idx, BitmapIndexedNode.EMPTY.assoc(shift + 5, hash, key, val, addedLeaf)));
INode n = node.assoc(shift + 5, hash, key, val, addedLeaf);
if(n == node)
return this;
return new ArrayNode(null, count, cloneAndSet(array, idx, n));
}
public INode without(int shift, int hash, Object key){
int idx = mask(hash, shift);
INode node = array[idx];
if(node == null)
return this;
INode n = node.without(shift + 5, hash, key);
if(n == node)
return this;
if (n == null) {
if (count <= 8) // shrink
return pack(null, idx);
return new ArrayNode(null, count - 1, cloneAndSet(array, idx, n));
} else
return new ArrayNode(null, count, cloneAndSet(array, idx, n));
}
public IMapEntry find(int shift, int hash, Object key){
int idx = mask(hash, shift);
INode node = array[idx];
if(node == null)
return null;
return node.find(shift + 5, hash, key);
}
public Object find(int shift, int hash, Object key, Object notFound){
int idx = mask(hash, shift);
INode node = array[idx];
if(node == null)
return notFound;
return node.find(shift + 5, hash, key, notFound);
}
public ISeq nodeSeq(){
return Seq.create(array);
}
public Object kvreduce(IFn f, Object init){
for(INode node : array){
if(node != null){
init = node.kvreduce(f,init);
if(RT.isReduced(init))
return ((IDeref)init).deref();
}
}
return init;
}
public Object fold(final IFn combinef, final IFn reducef,
final IFn fjtask, final IFn fjfork, final IFn fjjoin){
List<Callable> tasks = new ArrayList();
for(final INode node : array){
if(node != null){
tasks.add(new Callable(){
public Object call() throws Exception{
return node.fold(combinef, reducef, fjtask, fjfork, fjjoin);
}
});
}
}
return foldTasks(tasks,combinef,fjtask,fjfork,fjjoin);
}
static public Object foldTasks(List<Callable> tasks, final IFn combinef,
final IFn fjtask, final IFn fjfork, final IFn fjjoin){
if(tasks.isEmpty())
return combinef.invoke();
if(tasks.size() == 1){
Object ret = null;
try
{
return tasks.get(0).call();
}
catch(Exception e)
{
//aargh
}
}
List<Callable> t1 = tasks.subList(0,tasks.size()/2);
final List<Callable> t2 = tasks.subList(tasks.size()/2, tasks.size());
Object forked = fjfork.invoke(fjtask.invoke(new Callable() {
public Object call() throws Exception{
return foldTasks(t2,combinef,fjtask,fjfork,fjjoin);
}
}));
return combinef.invoke(foldTasks(t1,combinef,fjtask,fjfork,fjjoin),fjjoin.invoke(forked));
}
private ArrayNode ensureEditable(AtomicReference<Thread> edit){
if(this.edit == edit)
return this;
return new ArrayNode(edit, count, this.array.clone());
}
private ArrayNode editAndSet(AtomicReference<Thread> edit, int i, INode n){
ArrayNode editable = ensureEditable(edit);
editable.array[i] = n;
return editable;
}
private INode pack(AtomicReference<Thread> edit, int idx) {
Object[] newArray = new Object[2*(count - 1)];
int j = 1;
int bitmap = 0;
for(int i = 0; i < idx; i++)
if (array[i] != null) {
newArray[j] = array[i];
bitmap |= 1 << i;
j += 2;
}
for(int i = idx + 1; i < array.length; i++)
if (array[i] != null) {
newArray[j] = array[i];
bitmap |= 1 << i;
j += 2;
}
return new BitmapIndexedNode(edit, bitmap, newArray);
}
public INode assoc(AtomicReference<Thread> edit, int shift, int hash, Object key, Object val, Box addedLeaf){
int idx = mask(hash, shift);
INode node = array[idx];
if(node == null) {
ArrayNode editable = editAndSet(edit, idx, BitmapIndexedNode.EMPTY.assoc(edit, shift + 5, hash, key, val, addedLeaf));
editable.count++;
return editable;
}
INode n = node.assoc(edit, shift + 5, hash, key, val, addedLeaf);
if(n == node)
return this;
return editAndSet(edit, idx, n);
}
public INode without(AtomicReference<Thread> edit, int shift, int hash, Object key, Box removedLeaf){
int idx = mask(hash, shift);
INode node = array[idx];
if(node == null)
return this;
INode n = node.without(edit, shift + 5, hash, key, removedLeaf);
if(n == node)
return this;
if(n == null) {
if (count <= 8) // shrink
return pack(edit, idx);
ArrayNode editable = editAndSet(edit, idx, n);
editable.count--;
return editable;
}
return editAndSet(edit, idx, n);
}
static class Seq extends ASeq {
final INode[] nodes;
final int i;
final ISeq s;
static ISeq create(INode[] nodes) {
return create(null, nodes, 0, null);
}
private static ISeq create(IPersistentMap meta, INode[] nodes, int i, ISeq s) {
if (s != null)
return new Seq(meta, nodes, i, s);
for(int j = i; j < nodes.length; j++)
if (nodes[j] != null) {
ISeq ns = nodes[j].nodeSeq();
if (ns != null)
return new Seq(meta, nodes, j + 1, ns);
}
return null;
}
private Seq(IPersistentMap meta, INode[] nodes, int i, ISeq s) {
super(meta);
this.nodes = nodes;
this.i = i;
this.s = s;
}
public Obj withMeta(IPersistentMap meta) {
return new Seq(meta, nodes, i, s);
}
public Object first() {
return s.first();
}
public ISeq next() {
return create(null, nodes, i, s.next());
}
}
}
final static class BitmapIndexedNode implements INode{
static final BitmapIndexedNode EMPTY = new BitmapIndexedNode(null, 0, new Object[0]);
int bitmap;
Object[] array;
final AtomicReference<Thread> edit;
final int index(int bit){
return Integer.bitCount(bitmap & (bit - 1));
}
BitmapIndexedNode(AtomicReference<Thread> edit, int bitmap, Object[] array){
this.bitmap = bitmap;
this.array = array;
this.edit = edit;
}
public Iterator nodeItFrom(int shift, int hash, Object key) {
return new BitmapIndexedNodeIterator(this, shift, hash, key);
}
public Iterator nodeIt(boolean reverse) {
return reverse? new ReverseBitmapIndexedNodeIterator(this) : new BitmapIndexedNodeIterator(this);
}
static class BitmapIndexedNodeIterator implements Iterator{
BitmapIndexedNode node;
int index;
int N;
Iterator current;
public BitmapIndexedNodeIterator(BitmapIndexedNode node) {
this.node = node;
N = node.array.length;
moveCurIfNeeded();
}
public BitmapIndexedNodeIterator(BitmapIndexedNode bitmapIndexedNode,
int shift, int hash, Object key) {
this.node = bitmapIndexedNode;
N = node.array.length;
moveCurTo(shift, hash, key);
}
private void moveCurTo(int shift, int hash, Object key) {
int bit = bitpos(hash, shift);
if((node.bitmap & bit) == 0)
return;
index = 2*node.index(bit);
Object keyOrNull = node.array[index];
Object valOrNode = node.array[index+1];
if(keyOrNull == null) {
index += 2;
INode val = ((INode) valOrNode);
if (val != null) {
Iterator nodeIt = val.nodeItFrom(shift + 5, hash, key);
if (nodeIt.hasNext()) {
current = nodeIt;
return;
}
}
} else {
if(Util.equals(key, keyOrNull)) {
return;//OK index points to key
} else {
throw new IllegalArgumentException("Key not found: "+key);
}
}
}
public boolean hasNext() {
moveCurIfNeeded();
if (current == null && index >= N) {
return false;
}
return true;
}
//current != null => current.hasNext or index points to a valid key
private void moveCurIfNeeded() {
if (current != null && current.hasNext()) return;
current = null;
while (index < N) {
Object keyOrNull = node.array[index];
Object valOrNode = node.array[index+1];
if (keyOrNull == null) {
index += 2;
INode val = ((INode) valOrNode);
if (val != null) {
Iterator nodeIt = val.nodeIt(false);
if (nodeIt.hasNext()) {
current = nodeIt;
return;
}
}
} else {
return;
}
}
}
@Override
public Object next() {
if (current != null) {
return current.next();
} else {
Object keyOrNull = node.array[index++];
Object valOrNode = node.array[index++];
return new MapEntry(keyOrNull, valOrNode);
}
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
static final class ReverseBitmapIndexedNodeIterator implements Iterator {
BitmapIndexedNode node;
int index;
Iterator current;
public ReverseBitmapIndexedNodeIterator(BitmapIndexedNode node) {
this.node = node;
index = node.array.length-1;
moveCurIfNeeded();
}
public boolean hasNext() {
moveCurIfNeeded();
if (current == null && index < 0) {
return false;
}
return true;
}
//current != null => current.hasNext or index points to a valid key
private void moveCurIfNeeded() {
if (current != null && current.hasNext()) return;
current = null;
while (index >= 0) {
Object valOrNode = node.array[index];
Object keyOrNull = node.array[index-1];
if (keyOrNull == null) {
index -= 2;
INode val = ((INode) valOrNode);
if (val != null) {
Iterator nodeIt = val.nodeIt(true);
if (nodeIt.hasNext()) {
current = nodeIt;
return;
}
}
} else {
return;
}
}
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
@Override
public Object next() {
if (current != null) {
return current.next();
} else {
Object valOrNode = node.array[index--];
Object keyOrNull = node.array[index--];
return new MapEntry(keyOrNull, valOrNode);
}
}
}
public INode assoc(int shift, int hash, Object key, Object val, Box addedLeaf){
int bit = bitpos(hash, shift);
int idx = index(bit);
if((bitmap & bit) != 0) {
Object keyOrNull = array[2*idx];
Object valOrNode = array[2*idx+1];
if(keyOrNull == null) {
INode n = ((INode) valOrNode).assoc(shift + 5, hash, key, val, addedLeaf);
if(n == valOrNode)
return this;
return new BitmapIndexedNode(null, bitmap, cloneAndSet(array, 2*idx+1, n));
}
if(Util.equiv(key, keyOrNull)) {
if(val == valOrNode)
return this;
return new BitmapIndexedNode(null, bitmap, cloneAndSet(array, 2*idx+1, val));
}
addedLeaf.val = addedLeaf;
return new BitmapIndexedNode(null, bitmap,
cloneAndSet(array,
2*idx, null,
2*idx+1, createNode(shift + 5, keyOrNull, valOrNode, hash, key, val)));
} else {
int n = Integer.bitCount(bitmap);
if(n >= 16) {
INode[] nodes = new INode[32];
int jdx = mask(hash, shift);
nodes[jdx] = EMPTY.assoc(shift + 5, hash, key, val, addedLeaf);
int j = 0;
for(int i = 0; i < 32; i++)
if(((bitmap >>> i) & 1) != 0) {
if (array[j] == null)
nodes[i] = (INode) array[j+1];
else
nodes[i] = EMPTY.assoc(shift + 5, hash(array[j]), array[j], array[j+1], addedLeaf);
j += 2;
}
return new ArrayNode(null, n + 1, nodes);
} else {
Object[] newArray = new Object[2*(n+1)];
System.arraycopy(array, 0, newArray, 0, 2*idx);
newArray[2*idx] = key;
addedLeaf.val = addedLeaf;
newArray[2*idx+1] = val;
System.arraycopy(array, 2*idx, newArray, 2*(idx+1), 2*(n-idx));
return new BitmapIndexedNode(null, bitmap | bit, newArray);
}
}
}
public INode without(int shift, int hash, Object key){
int bit = bitpos(hash, shift);
if((bitmap & bit) == 0)
return this;
int idx = index(bit);
Object keyOrNull = array[2*idx];
Object valOrNode = array[2*idx+1];