-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathPathCopyingPersistentTreeMap.java
More file actions
1569 lines (1330 loc) · 49.7 KB
/
PathCopyingPersistentTreeMap.java
File metadata and controls
1569 lines (1330 loc) · 49.7 KB
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
// This file is part of SoSy-Lab Common,
// a library of useful utilities:
// https://github.com/sosy-lab/java-common-lib
//
// SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
package org.sosy_lab.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.base.Verify.verify;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.Iterators;
import com.google.common.collect.UnmodifiableIterator;
import com.google.errorprone.annotations.Immutable;
import com.google.errorprone.annotations.Var;
import com.google.errorprone.annotations.concurrent.LazyInit;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.io.Serializable;
import java.util.AbstractMap.SimpleImmutableEntry;
import java.util.ArrayDeque;
import java.util.Collections;
import java.util.Comparator;
import java.util.Deque;
import java.util.Iterator;
import java.util.Map;
import java.util.NavigableMap;
import java.util.NavigableSet;
import java.util.Objects;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* This is an implementation of {@link PersistentSortedMap} that is based on left-leaning red-black
* trees (LLRB) and path copying. Left-leaning red-black trees are similar to red-black trees and
* 2-3 trees, but are considerably easier to implement than red-black trees. They are described by
* Robert Sedgewick here: http://www.cs.princeton.edu/~rs/talks/LLRB/RedBlack.pdf
*
* <p>The operations insert, lookup, and remove are guaranteed to run in O(log n) time. Insert and
* remove allocate at most O(log n) memory. Traversal through all entries also allocates up to O(log
* n) memory. Per entry, this map needs memory for one object with 4 reference fields and 1 boolean.
* (This is a little bit less than {@link TreeMap} needs.)
*
* <p>This implementation does not support <code>null</code> keys (but <code>null</code> values) and
* always compares according to the natural ordering. All methods may throw {@link
* ClassCastException} is key objects are passed that do not implement {@link Comparable}.
*
* <p>The natural ordering of the keys needs to be consistent with equals.
*
* <p>As for all {@link PersistentMap}s, all collection views and all iterators are immutable. They
* do not reflect changes made to the map and all their modifying operations throw {@link
* UnsupportedOperationException}.
*
* <p>All instances of this class are fully-thread safe. However, note that each modifying operation
* allocates a new instance whose reference needs to be published safely in order to be usable by
* other threads. Two concurrent accesses to a modifying operation on the same instance will create
* two new maps, each reflecting exactly the operation executed by the current thread, and not
* reflecting the operation executed by the other thread.
*
* @param <K> The type of keys.
* @param <V> The type of values.
*/
@Immutable(containerOf = {"K", "V"})
public final class PathCopyingPersistentTreeMap<K extends Comparable<? super K>, V>
extends AbstractImmutableSortedMap<K, V> implements PersistentSortedMap<K, V>, Serializable {
private static final long serialVersionUID = -5708332286565509457L;
@SuppressWarnings("unused")
@SuppressFBWarnings(
value = "EQ_DOESNT_OVERRIDE_EQUALS",
justification = "Inherits equals() according to specification.")
@Immutable(containerOf = {"K", "V"})
private static final class Node<K, V> extends SimpleImmutableEntry<K, V> {
// Constants for isRed field
private static final boolean RED = true;
private static final boolean BLACK = false;
private static final long serialVersionUID = -7393505826652634501L;
private final @Nullable Node<K, V> left;
private final @Nullable Node<K, V> right;
private final boolean isRed;
// Leaf node
Node(K pKey, V pValue) {
super(pKey, pValue);
left = null;
right = null;
isRed = RED;
}
// Any node
Node(K pKey, V pValue, Node<K, V> pLeft, Node<K, V> pRight, boolean pRed) {
super(pKey, pValue);
left = pLeft;
right = pRight;
isRed = pRed;
}
boolean isLeaf() {
return left == null && right == null;
}
boolean getColor() {
return isRed;
}
static boolean isRed(@Nullable Node<?, ?> n) {
return n != null && n.isRed;
}
static boolean isBlack(@Nullable Node<?, ?> n) {
return n != null && !n.isRed;
}
// Methods for creating new nodes based on current node.
Node<K, V> withColor(boolean color) {
if (isRed == color) {
return this;
} else {
return new Node<>(getKey(), getValue(), left, right, color);
}
}
@SuppressWarnings("ReferenceEquality") // cannot use equals() for check whether tree is the same
Node<K, V> withLeftChild(Node<K, V> newLeft) {
if (newLeft == left) {
return this;
} else {
return new Node<>(getKey(), getValue(), newLeft, right, isRed);
}
}
@SuppressWarnings("ReferenceEquality") // cannot use equals() for check whether tree is the same
Node<K, V> withRightChild(Node<K, V> newRight) {
if (newRight == right) {
return this;
} else {
return new Node<>(getKey(), getValue(), left, newRight, isRed);
}
}
static int countNodes(@Nullable Node<?, ?> n) {
if (n == null) {
return 0;
}
return countNodes(n.left) + 1 + countNodes(n.right);
}
}
@Immutable(containerOf = {"K", "V"})
private static final class ContainerOfNodeWithDiffs<K, V> {
private final Node<K, V> node;
private final int sizeDiff;
private final int hashDiff;
private ContainerOfNodeWithDiffs(Node<K, V> node, int sizeDiff, int hashDiff) {
this.node = node;
this.sizeDiff = sizeDiff;
this.hashDiff = hashDiff;
}
static <V, K extends Comparable<? super K>> ContainerOfNodeWithDiffs<K, V> of(
Node<K, V> node, int sizeDiff, int hashDiff) {
return new ContainerOfNodeWithDiffs<>(node, sizeDiff, hashDiff);
}
Node<K, V> getNode() {
return node;
}
int getSizeDiff() {
return sizeDiff;
}
int getHashDiff() {
return hashDiff;
}
}
// static creation methods
private static final PathCopyingPersistentTreeMap<?, ?> EMPTY_MAP =
new PathCopyingPersistentTreeMap<String, Object>(null, 0, 0);
@SuppressWarnings("unchecked")
public static <K extends Comparable<? super K>, V> PersistentSortedMap<K, V> of() {
return (PersistentSortedMap<K, V>) EMPTY_MAP;
}
public static <K extends Comparable<? super K>, V> PersistentSortedMap<K, V> copyOf(
Map<K, V> map) {
checkNotNull(map);
if (map instanceof PathCopyingPersistentTreeMap<?, ?>) {
return (PathCopyingPersistentTreeMap<K, V>) map;
}
@Var PersistentSortedMap<K, V> result = of();
for (Map.Entry<K, V> entry : map.entrySet()) {
result = result.putAndCopy(entry.getKey(), entry.getValue());
}
return result;
}
/**
* Return a {@link Collector} that accumulates elements into a {@link
* PathCopyingPersistentTreeMap}. Keys and values are the result of the respective functions. If
* duplicate keys appear, the collector throws an {@link IllegalArgumentException}.
*/
public static <T, K extends Comparable<? super K>, V>
Collector<T, ?, PersistentSortedMap<K, V>> toPathCopyingPersistentTreeMap(
Function<? super T, ? extends K> keyFunction,
Function<? super T, ? extends V> valueFunction) {
return toPathCopyingPersistentTreeMap(
keyFunction,
valueFunction,
(k, v) -> {
throw new IllegalArgumentException("Duplicate key " + k);
});
}
/**
* Return a {@link Collector} that accumulates elements into a {@link
* PathCopyingPersistentTreeMap}. Keys and values are the result of the respective functions.
* Duplicate keys are resolved using the given merge function.
*/
public static <T, K extends Comparable<? super K>, V>
Collector<T, ?, PersistentSortedMap<K, V>> toPathCopyingPersistentTreeMap(
Function<? super T, ? extends K> keyFunction,
Function<? super T, ? extends V> valueFunction,
BinaryOperator<V> mergeFunction) {
checkNotNull(keyFunction);
checkNotNull(valueFunction);
checkNotNull(mergeFunction);
return Collectors.collectingAndThen(
Collectors.toMap(
keyFunction,
valueFunction,
mergeFunction,
() -> CopyOnWriteSortedMap.copyOf(PathCopyingPersistentTreeMap.<K, V>of())),
CopyOnWriteSortedMap::getSnapshot);
}
// state and constructor
private final @Nullable Node<K, V> root;
@SuppressWarnings("Immutable")
@LazyInit
private transient @Nullable NavigableSet<Entry<K, V>> entrySet;
private final int size;
private final int hashCode;
private PathCopyingPersistentTreeMap(@Nullable Node<K, V> pRoot, int pSize, int pHashCode) {
root = pRoot;
size = pSize;
hashCode = pHashCode;
}
// private utility methods
@SuppressWarnings("unchecked")
@Nullable
private static <K extends Comparable<? super K>, V> Node<K, V> findNode(
Object key, Node<K, V> root) {
checkNotNull(key);
return findNode((K) key, root);
}
@Nullable
private static <K extends Comparable<? super K>, V> Node<K, V> findNode(K key, Node<K, V> root) {
checkNotNull(key);
@Var Node<K, V> current = root;
while (current != null) {
int comp = key.compareTo(current.getKey());
if (comp < 0) {
// key < current.data
current = current.left;
} else if (comp > 0) {
// key > current.data
current = current.right;
} else {
// key == current.data
return current;
}
}
return null;
}
/**
* Find the node with the smallest key in a given non-empty subtree.
*
* @param root The subtree to search in.
* @return The node with the smallest key.
* @throws NullPointerException If tree is empty.
*/
private static <K extends Comparable<? super K>, V> Node<K, V> findSmallestNode(Node<K, V> root) {
@Var Node<K, V> current = root;
while (current.left != null) {
current = current.left;
}
return current;
}
/**
* Find the node with the largest key in a given non-empty subtree.
*
* @param root The subtree to search in.
* @return The node with the largest key.
* @throws NullPointerException If tree is empty.
*/
private static <K extends Comparable<? super K>, V> Node<K, V> findLargestNode(Node<K, V> root) {
@Var Node<K, V> current = root;
while (current.right != null) {
current = current.right;
}
return current;
}
/**
* Given a key and a tree, find the node in the tree with the given key, or (if {@code inclusive}
* is false or there is no such node) the node with the smallest key that is still greater than
* the key to look for. In terms of {@link NavigableMap} operations, this returns the node for
* {@code map.tailMap(key, inclusive).first()}. Returns null if the tree is empty or there is no
* node that matches (i.e., key is larger than the largest key in the map).
*
* @param key The key to search for.
* @param root The tree to look in.
* @return A node or null.
*/
private static @Nullable <K extends Comparable<? super K>, V> Node<K, V> findNextGreaterNode(
K key, Node<K, V> root, boolean inclusive) {
checkNotNull(key);
@Var Node<K, V> result = null; // this is always greater than key
@Var Node<K, V> current = root;
while (current != null) {
int comp = key.compareTo(current.getKey());
if (comp < 0) {
// key < current.data
// All nodes to the right of current are irrelevant because they are too big.
// current is the best candidate we have found so far, so it becomes the new result
// (current is always smaller than the previous result and still bigger than key).
result = current;
current = current.left;
} else if (comp > 0) {
// key > current.data
// All nodes to the left of current are irrelevant because they are too small.
// current itself is too small, too.
current = current.right;
} else {
// key == current.data
if (inclusive) {
return current;
} else {
// All nodes to the left of current are irrelevant because they are too small.
// current itself is too small, too.
// The left-most node in the right subtree of child is the result.
if (current.right == null) {
// no node smaller than key in this subtree
return result;
} else {
return findSmallestNode(current.right);
}
}
}
if (current == null) {
// We have reached a leaf without finding the element.
return result;
}
}
return null;
}
/**
* Given a key and a tree, find the node in the tree with the given key, or (if {@code inclusive}
* is false or there is no such node) the node with the largest key that is still smaller than the
* key to look for. In terms of {@link NavigableMap} operations, this returns the node for {@code
* map.headMap(key, inclusive).last()}. Returns null if the tree is empty or there is no node that
* matches (i.e., key is smaller than or equal to the smallest key in the map).
*
* @param key The key to search for.
* @param root The tree to look in.
* @return A node or null.
*/
private static @Nullable <K extends Comparable<? super K>, V> Node<K, V> findNextSmallerNode(
K key, Node<K, V> root, boolean inclusive) {
checkNotNull(key);
@Var Node<K, V> result = null; // this is always smaller than key
@Var Node<K, V> current = root;
while (current != null) {
int comp = key.compareTo(current.getKey());
if (comp < 0) {
// key < current.data
// All nodes to the right of current are irrelevant because they are too big.
// current itself is too big, too.
current = current.left;
} else if (comp > 0) {
// key > current.data
// All nodes to the left of current are irrelevant because they are too small.
// current is the best candidate we have found so far, so it becomes the new result
// (current is always bigger than the previous result and still smaller than key).
result = current;
current = current.right;
} else {
// key == current.data
if (inclusive) {
return current;
} else {
// All nodes to the right of current are irrelevant because they are too big.
// current itself is too big, too.
// The right-most node in the left subtree of child is the result.
if (current.left == null) {
// no node smaller than key in this subtree
return result;
} else {
return findLargestNode(current.left);
}
}
}
if (current == null) {
// We have reached a leaf without finding the element.
return result;
}
}
return null;
}
private static <K extends Comparable<? super K>> boolean exceedsLowerBound(
K pKey, K pLowerBound, boolean pLowerInclusive) {
if (pLowerInclusive) {
return pKey.compareTo(pLowerBound) < 0;
} else {
return pKey.compareTo(pLowerBound) <= 0;
}
}
private static <K extends Comparable<? super K>> boolean exceedsUpperBound(
K pKey, K pUpperBound, boolean pUpperInclusive) {
if (pUpperInclusive) {
return pKey.compareTo(pUpperBound) > 0;
} else {
return pKey.compareTo(pUpperBound) >= 0;
}
}
private static <K extends Comparable<? super K>, V> int checkAssertions(Node<K, V> current) {
if (current == null) {
return 0;
}
// check property of binary search tree
if (current.left != null) {
checkState(
current.getKey().compareTo(current.left.getKey()) > 0,
"Tree has left child that is not smaller.");
}
if (current.right != null) {
checkState(
current.getKey().compareTo(current.right.getKey()) < 0,
"Tree has right child that is not bigger.");
}
// Check LLRB invariants
// No red right child.
checkState(!Node.isRed(current.right), "LLRB has red right child");
// No more than two consecutive red nodes.
checkState(
!Node.isRed(current) || !Node.isRed(current.left) || !Node.isRed(current.left.left),
"LLRB has three red nodes in a row.");
// Check recursively.
int leftBlackHeight = checkAssertions(current.left);
int rightBlackHeight = checkAssertions(current.right);
// Check black height balancing.
checkState(
leftBlackHeight == rightBlackHeight,
"Black path length on left is %s and on right is %s",
leftBlackHeight,
rightBlackHeight);
@Var int blackHeight = leftBlackHeight;
if (!current.isRed) {
blackHeight++;
}
return blackHeight;
}
/**
* Check the map for violation of its invariants.
*
* @throws IllegalStateException If any invariant is violated.
*/
@VisibleForTesting
@SuppressWarnings("CheckReturnValue")
void checkAssertions() {
checkAssertions(root);
}
// modifying methods
/**
* Create a map instance with a given root node.
*
* @param pRoot Container of a node or null (meaning the empty tree) with size and hash changes.
* @return A map instance with the given tree.
*/
@SuppressWarnings("ReferenceEquality") // cannot use equals() for check whether tree is the same
private PersistentSortedMap<K, V> mapFromTree(ContainerOfNodeWithDiffs<K, V> pRoot) {
@Var Node<K, V> newRoot = pRoot.getNode();
if (newRoot == root) {
return this;
} else if (newRoot == null) {
return of();
} else {
// Root is always black.
newRoot = newRoot.withColor(Node.BLACK);
return new PathCopyingPersistentTreeMap<>(
newRoot, size + pRoot.getSizeDiff(), hashCode + pRoot.getHashDiff());
}
}
@Override
public PersistentSortedMap<K, V> putAndCopy(K key, V value) {
return mapFromTree(putAndCopy0(checkNotNull(key), value, root, 0, 0));
}
private static <K extends Comparable<? super K>, V> ContainerOfNodeWithDiffs<K, V> putAndCopy0(
K key, V value, @Var Node<K, V> current, @Var int sizeDiff, @Var int hashDiff) {
// Inserting is easy:
// We find the place where to insert,
// and afterwards fix the invariants by some rotations or re-colorings.
if (current == null) {
Node<K, V> node = new Node<>(key, value);
sizeDiff = sizeDiff + 1;
hashDiff = hashDiff + node.hashCode();
return ContainerOfNodeWithDiffs.of(node, sizeDiff, hashDiff);
}
int comp = key.compareTo(current.getKey());
if (comp < 0) {
// key < current.data
ContainerOfNodeWithDiffs<K, V> containerOfNodeWithDiffs =
putAndCopy0(key, value, current.left, sizeDiff, hashDiff);
sizeDiff = containerOfNodeWithDiffs.getSizeDiff();
hashDiff = containerOfNodeWithDiffs.getHashDiff();
Node<K, V> newLeft = containerOfNodeWithDiffs.getNode();
current = current.withLeftChild(newLeft);
} else if (comp > 0) {
// key > current.data
ContainerOfNodeWithDiffs<K, V> containerOfNodeWithDiffs =
putAndCopy0(key, value, current.right, sizeDiff, hashDiff);
sizeDiff = containerOfNodeWithDiffs.getSizeDiff();
hashDiff = containerOfNodeWithDiffs.getHashDiff();
Node<K, V> newRight = containerOfNodeWithDiffs.getNode();
current = current.withRightChild(newRight);
} else {
// replace current node with a new one
hashDiff = hashDiff - current.hashCode();
current = new Node<>(key, value, current.left, current.right, current.getColor());
hashDiff = hashDiff + current.hashCode();
}
// restore invariants
return ContainerOfNodeWithDiffs.of(restoreInvariants(current), sizeDiff, hashDiff);
}
@SuppressWarnings("unchecked")
@Override
public PersistentSortedMap<K, V> removeAndCopy(Object key) {
if (isEmpty()) {
return this;
}
return mapFromTree(removeAndCopy0((K) checkNotNull(key), root, 0, 0));
}
@Nullable
private static <K extends Comparable<? super K>, V> ContainerOfNodeWithDiffs<K, V> removeAndCopy0(
K key, @Var Node<K, V> current, @Var int sizeDiff, @Var int hashDiff) {
// Removing a node is more difficult.
// We can remove a leaf if it is red.
// So we try to always have a red node while going downwards.
// This is accomplished by calling moveRedLeft() when going downwards to the left
// or by calling moveRedRight() otherwise.
// If we found the node and it is a leaf, we can then delete it
// and do the usual adjustments for re-establishing the invariants (just like for insertion).
// If we found the node and it is not a leaf node,
// we can use a trick. We replace the node with the next greater node
// (the left-most node in the right subtree),
// and afterwards delete that node from the right subtree (otherwise it would be duplicate).
@Var int comp = key.compareTo(current.getKey());
if (comp < 0) {
// key < current.data
if (current.left == null) {
// Target key is not in map.
return ContainerOfNodeWithDiffs.of(current, sizeDiff, hashDiff);
}
// Go down leftwards, keeping a red node.
if (!Node.isRed(current.left) && !Node.isRed(current.left.left)) {
// Push red to left if necessary.
current = makeLeftRed(current);
}
// recursive descent
ContainerOfNodeWithDiffs<K, V> containerOfNodeWithDiffs =
removeAndCopy0(key, current.left, sizeDiff, hashDiff);
sizeDiff = containerOfNodeWithDiffs.getSizeDiff();
hashDiff = containerOfNodeWithDiffs.getHashDiff();
Node<K, V> newLeft = containerOfNodeWithDiffs.getNode();
current = current.withLeftChild(newLeft);
} else {
// key >= current.data
if ((comp > 0) && (current.right == null)) {
// Target key is not in map.
return ContainerOfNodeWithDiffs.of(current, sizeDiff, hashDiff);
}
if (Node.isRed(current.left)) {
// First chance to push red to right.
current = rotateClockwise(current);
// re-update comp
comp = key.compareTo(current.getKey());
assert comp >= 0;
}
if ((comp == 0) && (current.right == null)) {
assert current.left == null;
// We can delete the node easily, it's a leaf.
hashDiff = hashDiff - current.hashCode();
sizeDiff = sizeDiff - 1;
return ContainerOfNodeWithDiffs.of(null, sizeDiff, hashDiff);
}
if (!Node.isRed(current.right) && !Node.isRed(current.right.left)) {
// Push red to right.
current = makeRightRed(current);
// re-update comp
comp = key.compareTo(current.getKey());
assert comp >= 0;
}
if (comp == 0) {
// We have to delete current, but is has children.
// We replace current with the smallest node in the right subtree (the "successor"),
// and delete that (leaf) node there.
hashDiff = hashDiff - current.hashCode();
sizeDiff = sizeDiff - 1;
@Var Node<K, V> successor = current.right;
while (successor.left != null) {
successor = successor.left;
}
// Delete the successor
Node<K, V> newRight = removeMininumNodeInTree(current.right);
// and replace current with it
current =
new Node<>(
successor.getKey(),
successor.getValue(),
current.left,
newRight,
current.getColor());
} else {
// key > current.data
// Go down rightwards.
ContainerOfNodeWithDiffs<K, V> containerOfNodeWithDiffs =
removeAndCopy0(key, current.right, sizeDiff, hashDiff);
sizeDiff = containerOfNodeWithDiffs.getSizeDiff();
hashDiff = containerOfNodeWithDiffs.getHashDiff();
Node<K, V> newRight = containerOfNodeWithDiffs.getNode();
current = current.withRightChild(newRight);
}
}
return ContainerOfNodeWithDiffs.of(restoreInvariants(current), sizeDiff, hashDiff);
}
/**
* Unconditionally delete the node with the smallest key in a given subtree.
*
* @return A new subtree reflecting the change.
*/
@Nullable
private static <K, V> Node<K, V> removeMininumNodeInTree(@Var Node<K, V> current) {
if (current.left == null) {
// This is the minium node to delete
return null;
}
if (!Node.isRed(current.left) && !Node.isRed(current.left.left)) {
// Push red to left if necessary (similar to general removal strategy).
current = makeLeftRed(current);
}
// recursive descent
Node<K, V> newLeft = removeMininumNodeInTree(current.left);
current = current.withLeftChild(newLeft);
return restoreInvariants(current);
}
/**
* Fix the LLRB invariants around a given node (regarding the node, its children, and
* grand-children).
*
* @return A new subtree with the same content that is a legal LLRB.
*/
private static <K, V> Node<K, V> restoreInvariants(@Var Node<K, V> current) {
if (Node.isRed(current.right)) {
// Right should not be red in a left-leaning red-black tree.
current = rotateCounterclockwise(current);
}
if (Node.isRed(current.left) && Node.isRed(current.left.left)) {
// Don't have consecutive red nodes.
current = rotateClockwise(current);
}
if (Node.isRed(current.left) && Node.isRed(current.right)) {
// Again, don't have red right children.
// We make both children black and this one red,
// so we pass the potential problem of having a red right upwards in the tree.
current = colorFlip(current);
}
return current;
}
/**
* Flip the colors of current and its two children. This is an operation that keeps the "black
* height".
*
* @param current A node with two children.
* @return The same subtree, but with inverted colors for the three top nodes.
*/
private static <K, V> Node<K, V> colorFlip(Node<K, V> current) {
Node<K, V> newLeft = current.left.withColor(!current.left.getColor());
Node<K, V> newRight = current.right.withColor(!current.right.getColor());
return new Node<>(current.getKey(), current.getValue(), newLeft, newRight, !current.getColor());
}
private static <K, V> Node<K, V> rotateCounterclockwise(Node<K, V> current) {
// the node that is moved between subtrees:
Node<K, V> crossoverNode = current.right.left;
Node<K, V> newLeft =
new Node<>(current.getKey(), current.getValue(), current.left, crossoverNode, Node.RED);
return new Node<>(
current.right.getKey(),
current.right.getValue(),
newLeft,
current.right.right,
current.getColor());
}
private static <K, V> Node<K, V> rotateClockwise(Node<K, V> current) {
// the node that is moved between subtrees:
Node<K, V> crossOverNode = current.left.right;
Node<K, V> newRight =
new Node<>(current.getKey(), current.getValue(), crossOverNode, current.right, Node.RED);
return new Node<>(
current.left.getKey(),
current.left.getValue(),
current.left.left,
newRight,
current.getColor());
}
private static <K, V> Node<K, V> makeLeftRed(@Var Node<K, V> current) {
// Make current.left or one of its children red
// (assuming that current is red and both current.left and current.left.left are black).
current = colorFlip(current);
if (Node.isRed(current.right.left)) {
Node<K, V> newRight = rotateClockwise(current.right);
current =
new Node<>(
current.getKey(), current.getValue(), current.left, newRight, current.getColor());
current = rotateCounterclockwise(current);
current = colorFlip(current);
}
return current;
}
private static <K, V> Node<K, V> makeRightRed(@Var Node<K, V> current) {
// Make current.right or one of its children red
// (assuming that current is red and both current.right and current.right.left are black).
current = colorFlip(current);
if (Node.isRed(current.left.left)) {
current = rotateClockwise(current);
current = colorFlip(current);
}
return current;
}
// read operations
@Override
@SuppressWarnings("ReferenceEquality") // comparing nodes with equals would not suffice
public boolean equals(Object pObj) {
if (pObj instanceof PathCopyingPersistentTreeMap<?, ?>
&& ((PathCopyingPersistentTreeMap<?, ?>) pObj).root == root) {
return true;
}
return super.equals(pObj);
}
@Override
public int hashCode() {
return hashCode;
}
@Override
public @Nullable Entry<K, V> getEntry(Object pKey) {
return findNode(pKey, root);
}
@Override
public Iterator<Entry<K, V>> entryIterator() {
return EntryInOrderIterator.create(root);
}
@Override
public Iterator<Entry<K, V>> descendingEntryIterator() {
return DescendingEntryInOrderIterator.create(root);
}
@Override
public PersistentSortedMap<K, V> empty() {
return of();
}
@Override
public boolean containsKey(Object pObj) {
return findNode(pObj, root) != null;
}
@Override
public V get(Object pObj) {
Node<K, V> node = findNode(pObj, root);
return node == null ? null : node.getValue();
}
@Override
public V getOrDefault(Object pKey, V pDefaultValue) {
Node<K, V> node = findNode(pKey, root);
return node == null ? pDefaultValue : node.getValue();
}
@Override
public boolean isEmpty() {
return root == null;
}
@Override
public int size() {
return size;
}
@Override
public Entry<K, V> firstEntry() {
if (isEmpty()) {
return null;
}
return findSmallestNode(root);
}
@Override
public Entry<K, V> lastEntry() {
if (isEmpty()) {
return null;
}
return findLargestNode(root);
}
@Override
public Entry<K, V> ceilingEntry(K pKey) {
return findNextGreaterNode(pKey, root, /*inclusive=*/ true);
}
@Override
public Entry<K, V> floorEntry(K pKey) {
return findNextSmallerNode(pKey, root, /*inclusive=*/ true);
}
@Override
public Entry<K, V> higherEntry(K pKey) {
return findNextGreaterNode(pKey, root, /*inclusive=*/ false);
}
@Override
public Entry<K, V> lowerEntry(K pKey) {
return findNextSmallerNode(pKey, root, /*inclusive=*/ false);
}
@Override
public Comparator<? super K> comparator() {
return null;
}
@Override
public OurSortedMap<K, V> descendingMap() {
return new DescendingSortedMap<>(this);
}
@Override
public NavigableSet<Entry<K, V>> entrySet() {
if (entrySet == null) {
entrySet = new SortedMapEntrySet<>(this);
}
return entrySet;
}
@Override
public OurSortedMap<K, V> subMap(
K pFromKey, boolean pFromInclusive, K pToKey, boolean pToInclusive) {
checkNotNull(pFromKey);
checkNotNull(pToKey);
return PartialSortedMap.create(root, pFromKey, pFromInclusive, pToKey, pToInclusive);
}
@Override
public OurSortedMap<K, V> headMap(K pToKey, boolean pToInclusive) {
checkNotNull(pToKey);
return PartialSortedMap.create(
root, null, /*pFromInclusive=*/ true, pToKey, /*pToInclusive=*/ pToInclusive);
}
@Override
public OurSortedMap<K, V> tailMap(K pFromKey, boolean pFromInclusive) {
checkNotNull(pFromKey);
return PartialSortedMap.create(
root, pFromKey, /*pFromInclusive=*/ pFromInclusive, null, /*pToInclusive=*/ false);
}
/**
* Tree iterator with in-order iteration returning node objects, with possibility for lower and
* upper bound.
*
* @param <K> The type of keys.
* @param <V> The type of values.
*/
private static class EntryInOrderIterator<K extends Comparable<? super K>, V>