/
HashSet.scala
2102 lines (1764 loc) · 76.9 KB
/
HashSet.scala
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
/*
* Scala (https://www.scala-lang.org)
*
* Copyright EPFL and Lightbend, Inc.
*
* Licensed under Apache License 2.0
* (http://www.apache.org/licenses/LICENSE-2.0).
*
* See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*/
package scala
package collection
package immutable
import java.lang.Integer.{bitCount, numberOfTrailingZeros}
import java.lang.System.arraycopy
import scala.collection.Hashing.improve
import scala.collection.Stepper.EfficientSplit
import scala.collection.generic.DefaultSerializable
import scala.collection.mutable.ReusableBuilder
import scala.runtime.Statics.releaseFence
import scala.util.hashing.MurmurHash3
/** This class implements immutable sets using a Compressed Hash-Array Mapped Prefix-tree.
* See paper https://michael.steindorfer.name/publications/oopsla15.pdf for more details.
*
* @tparam A the type of the elements contained in this hash set.
* @define Coll `immutable.HashSet`
* @define coll immutable champ hash set
*/
final class HashSet[A] private[immutable](private[immutable] val rootNode: BitmapIndexedSetNode[A])
extends AbstractSet[A]
with StrictOptimizedSetOps[A, HashSet, HashSet[A]]
with IterableFactoryDefaults[A, HashSet]
with DefaultSerializable {
def this() = this(SetNode.empty)
// This release fence is present because rootNode may have previously been mutated during construction.
releaseFence()
private[this] def newHashSetOrThis(newRootNode: BitmapIndexedSetNode[A]): HashSet[A] =
if (rootNode eq newRootNode) this else new HashSet(newRootNode)
override def iterableFactory: IterableFactory[HashSet] = HashSet
override def knownSize: Int = rootNode.size
override def size: Int = rootNode.size
override def isEmpty: Boolean = rootNode.size == 0
def iterator: Iterator[A] = {
if (isEmpty) Iterator.empty
else new SetIterator[A](rootNode)
}
protected[immutable] def reverseIterator: Iterator[A] = new SetReverseIterator[A](rootNode)
override def stepper[S <: Stepper[_]](implicit shape: StepperShape[A, S]): S with EfficientSplit = {
import convert.impl._
val s = shape.shape match {
case StepperShape.IntShape => IntChampStepper.from[ SetNode[A]](size, rootNode, (node, i) => node.getPayload(i).asInstanceOf[Int])
case StepperShape.LongShape => LongChampStepper.from[ SetNode[A]](size, rootNode, (node, i) => node.getPayload(i).asInstanceOf[Long])
case StepperShape.DoubleShape => DoubleChampStepper.from[SetNode[A]](size, rootNode, (node, i) => node.getPayload(i).asInstanceOf[Double])
case _ => shape.parUnbox(AnyChampStepper.from[A, SetNode[A]](size, rootNode, (node, i) => node.getPayload(i)))
}
s.asInstanceOf[S with EfficientSplit]
}
def contains(element: A): Boolean = {
val elementUnimprovedHash = element.##
val elementHash = improve(elementUnimprovedHash)
rootNode.contains(element, elementUnimprovedHash, elementHash, 0)
}
def incl(element: A): HashSet[A] = {
val elementUnimprovedHash = element.##
val elementHash = improve(elementUnimprovedHash)
val newRootNode = rootNode.updated(element, elementUnimprovedHash, elementHash, 0)
newHashSetOrThis(newRootNode)
}
def excl(element: A): HashSet[A] = {
val elementUnimprovedHash = element.##
val elementHash = improve(elementUnimprovedHash)
val newRootNode = rootNode.removed(element, elementUnimprovedHash, elementHash, 0)
newHashSetOrThis(newRootNode)
}
override def concat(that: IterableOnce[A]): HashSet[A] =
that match {
case hs: HashSet[A] =>
if (isEmpty) hs
else {
val newNode = rootNode.concat(hs.rootNode, 0)
if (newNode eq hs.rootNode) hs
else newHashSetOrThis(newNode)
}
case hs: collection.mutable.HashSet[A] =>
val iter = hs.nodeIterator
var current = rootNode
while (iter.hasNext) {
val next = iter.next()
val originalHash = hs.unimproveHash(next.hash)
val improved = improve(originalHash)
current = current.updated(next.key, originalHash, improved, 0)
if (current ne rootNode) {
var shallowlyMutableNodeMap = Node.bitposFrom(Node.maskFrom(improved, 0))
while (iter.hasNext) {
val next = iter.next()
val originalHash = hs.unimproveHash(next.hash)
val improved = improve(originalHash)
shallowlyMutableNodeMap = current.updateWithShallowMutations(next.key, originalHash, improved, 0, shallowlyMutableNodeMap)
}
return new HashSet(current)
}
}
this
case _ =>
val iter = that.iterator
var current = rootNode
while (iter.hasNext) {
val element = iter.next()
val originalHash = element.##
val improved = improve(originalHash)
current = current.updated(element, originalHash, improved, 0)
if (current ne rootNode) {
// Note: We could have started with shallowlyMutableNodeMap = 0, however this way, in the case that
// the first changed key ended up in a subnode beneath root, we mark that root right away as being
// shallowly mutable.
//
// since `element` has just been inserted, and certainly caused a new root node to be created, we can say with
// certainty that it either caused a new subnode to be created underneath `current`, in which case we should
// carry on mutating that subnode, or it ended up as a child data pair of the root, in which case, no harm is
// done by including its bit position in the shallowlyMutableNodeMap anyways.
var shallowlyMutableNodeMap = Node.bitposFrom(Node.maskFrom(improved, 0))
while (iter.hasNext) {
val element = iter.next()
val originalHash = element.##
val improved = improve(originalHash)
shallowlyMutableNodeMap = current.updateWithShallowMutations(element, originalHash, improved, 0, shallowlyMutableNodeMap)
}
return new HashSet(current)
}
}
this
}
override def tail: HashSet[A] = this - head
override def init: HashSet[A] = this - last
override def head: A = iterator.next()
override def last: A = reverseIterator.next()
override def foreach[U](f: A => U): Unit = rootNode.foreach(f)
/** Applies a function f to each element, and its corresponding **original** hash, in this Set */
@`inline` private[collection] def foreachWithHash(f: (A, Int) => Unit): Unit = rootNode.foreachWithHash(f)
/** Applies a function f to each element, and its corresponding **original** hash, in this Set
* Stops iterating the first time that f returns `false`.*/
@`inline` private[collection] def foreachWithHashWhile(f: (A, Int) => Boolean): Unit = rootNode.foreachWithHashWhile(f)
def subsetOf(that: Set[A]): Boolean = if (that.isEmpty) true else that match {
case set: HashSet[A] => rootNode.subsetOf(set.rootNode, 0)
case _ => super.subsetOf(that)
}
override def equals(that: Any): Boolean =
that match {
case set: HashSet[_] => (this eq set) || (this.rootNode == set.rootNode)
case _ => super.equals(that)
}
override protected[this] def className = "HashSet"
override def hashCode(): Int = {
val it = new SetHashIterator(rootNode)
val hash = MurmurHash3.unorderedHash(it, MurmurHash3.setSeed)
//assert(hash == super.hashCode())
hash
}
override def diff(that: collection.Set[A]): HashSet[A] = {
if (isEmpty) {
this
} else {
that match {
case hashSet: HashSet[A] =>
if (hashSet.isEmpty) this else {
val newRootNode = rootNode.diff(hashSet.rootNode, 0)
if (newRootNode.size == 0) HashSet.empty else newHashSetOrThis(rootNode.diff(hashSet.rootNode, 0))
}
case hashSet: collection.mutable.HashSet[A] =>
val iter = hashSet.nodeIterator
var curr = rootNode
while (iter.hasNext) {
val next = iter.next()
val originalHash = hashSet.unimproveHash(next.hash)
val improved = improve(originalHash)
curr = curr.removed(next.key, originalHash, improved, 0)
if (curr ne rootNode) {
if (curr.size == 0) {
return HashSet.empty
}
while (iter.hasNext) {
val next = iter.next()
val originalHash = hashSet.unimproveHash(next.hash)
val improved = improve(originalHash)
curr.removeWithShallowMutations(next.key, originalHash, improved)
if (curr.size == 0) {
return HashSet.empty
}
}
return new HashSet(curr)
}
}
this
case other =>
val thatKnownSize = other.knownSize
if (thatKnownSize == 0) {
this
} else if (thatKnownSize <= size) {
/* this branch intentionally includes the case of thatKnownSize == -1. We know that HashSets are quite fast at look-up, so
we're likely to be the faster of the two at that. */
removedAllWithShallowMutations(other)
} else {
// TODO: Develop more sophisticated heuristic for which branch to take
filterNot(other.contains)
}
}
}
}
/** Immutably removes all elements of `that` from this HashSet
*
* Mutation is used internally, but only on root SetNodes which this method itself creates.
*
* That is, this method is safe to call on published sets because it does not mutate `this`
*/
private[this] def removedAllWithShallowMutations(that: IterableOnce[A]): HashSet[A] = {
val iter = that.iterator
var curr = rootNode
while (iter.hasNext) {
val next = iter.next()
val originalHash = next.##
val improved = improve(originalHash)
curr = curr.removed(next, originalHash, improved, 0)
if (curr ne rootNode) {
if (curr.size == 0) {
return HashSet.empty
}
while (iter.hasNext) {
val next = iter.next()
val originalHash = next.##
val improved = improve(originalHash)
curr.removeWithShallowMutations(next, originalHash, improved)
if (curr.size == 0) {
return HashSet.empty
}
}
return new HashSet(curr)
}
}
this
}
override def removedAll(that: IterableOnce[A]): HashSet[A] = that match {
case set: scala.collection.Set[A] => diff(set)
case range: Range if range.length > size =>
filter {
case i: Int => !range.contains(i)
case _ => true
}
case _ =>
removedAllWithShallowMutations(that)
}
override def partition(p: A => Boolean): (HashSet[A], HashSet[A]) = {
// This method has been preemptively overridden in order to ensure that an optimizing implementation may be included
// in a minor release without breaking binary compatibility.
super.partition(p)
}
override def span(p: A => Boolean): (HashSet[A], HashSet[A]) = {
// This method has been preemptively overridden in order to ensure that an optimizing implementation may be included
// in a minor release without breaking binary compatibility.
super.span(p)
}
override protected[collection] def filterImpl(pred: A => Boolean, isFlipped: Boolean): HashSet[A] = {
val newRootNode = rootNode.filterImpl(pred, isFlipped)
if (newRootNode eq rootNode) this
else if (newRootNode.size == 0) HashSet.empty
else new HashSet(newRootNode)
}
override def intersect(that: collection.Set[A]): HashSet[A] = {
// This method has been preemptively overridden in order to ensure that an optimizing implementation may be included
// in a minor release without breaking binary compatibility.
super.intersect(that)
}
override def take(n: Int): HashSet[A] = {
// This method has been preemptively overridden in order to ensure that an optimizing implementation may be included
// in a minor release without breaking binary compatibility.
super.take(n)
}
override def takeRight(n: Int): HashSet[A] = {
// This method has been preemptively overridden in order to ensure that an optimizing implementation may be included
// in a minor release without breaking binary compatibility.
super.takeRight(n)
}
override def takeWhile(p: A => Boolean): HashSet[A] = {
// This method has been preemptively overridden in order to ensure that an optimizing implementation may be included
// in a minor release without breaking binary compatibility.
super.takeWhile(p)
}
override def drop(n: Int): HashSet[A] = {
// This method has been preemptively overridden in order to ensure that an optimizing implementation may be included
// in a minor release without breaking binary compatibility.
super.drop(n)
}
override def dropRight(n: Int): HashSet[A] = {
// This method has been preemptively overridden in order to ensure that an optimizing implementation may be included
// in a minor release without breaking binary compatibility.
super.dropRight(n)
}
override def dropWhile(p: A => Boolean): HashSet[A] = {
// This method has been preemptively overridden in order to ensure that an optimizing implementation may be included
// in a minor release without breaking binary compatibility.
super.dropWhile(p)
}
}
private[immutable] object SetNode {
private final val EmptySetNode = new BitmapIndexedSetNode(0, 0, Array.empty, Array.empty, 0, 0)
def empty[A]: BitmapIndexedSetNode[A] = EmptySetNode.asInstanceOf[BitmapIndexedSetNode[A]]
final val TupleLength = 1
}
private[immutable] sealed abstract class SetNode[A] extends Node[SetNode[A]] {
def contains(element: A, originalHash: Int, hash: Int, shift: Int): Boolean
def updated(element: A, originalHash: Int, hash: Int, shift: Int): SetNode[A]
def removed(element: A, originalHash: Int, hash: Int, shift: Int): SetNode[A]
def hasNodes: Boolean
def nodeArity: Int
def getNode(index: Int): SetNode[A]
def hasPayload: Boolean
def payloadArity: Int
def getPayload(index: Int): A
def size: Int
def foreach[U](f: A => U): Unit
def subsetOf(that: SetNode[A], shift: Int): Boolean
def copy(): SetNode[A]
def filterImpl(pred: A => Boolean, flipped: Boolean): SetNode[A]
def diff(that: SetNode[A], shift: Int): SetNode[A]
def concat(that: SetNode[A], shift: Int): SetNode[A]
def foreachWithHash(f: (A, Int) => Unit): Unit
def foreachWithHashWhile(f: (A, Int) => Boolean): Boolean
}
private final class BitmapIndexedSetNode[A](
var dataMap: Int,
var nodeMap: Int,
var content: Array[Any],
var originalHashes: Array[Int],
var size: Int,
var cachedJavaKeySetHashCode: Int) extends SetNode[A] {
import Node._
import SetNode._
/*
assert(checkInvariantContentIsWellTyped())
assert(checkInvariantSubNodesAreCompacted())
private final def checkInvariantSubNodesAreCompacted(): Boolean =
new SetIterator[A](this).size - payloadArity >= 2 * nodeArity
private final def checkInvariantContentIsWellTyped(): Boolean = {
val predicate1 = TupleLength * payloadArity + nodeArity == content.length
val predicate2 = Range(0, TupleLength * payloadArity)
.forall(i => content(i).isInstanceOf[SetNode[_]] == false)
val predicate3 = Range(TupleLength * payloadArity, content.length)
.forall(i => content(i).isInstanceOf[SetNode[_]] == true)
predicate1 && predicate2 && predicate3
}
*/
def getPayload(index: Int): A = content(index).asInstanceOf[A]
override def getHash(index: Int): Int = originalHashes(index)
def getNode(index: Int): SetNode[A] = content(content.length - 1 - index).asInstanceOf[SetNode[A]]
def contains(element: A, originalHash: Int, elementHash: Int, shift: Int): Boolean = {
val mask = maskFrom(elementHash, shift)
val bitpos = bitposFrom(mask)
if ((dataMap & bitpos) != 0) {
val index = indexFrom(dataMap, mask, bitpos)
return originalHashes(index) == originalHash && element == this.getPayload(index)
}
if ((nodeMap & bitpos) != 0) {
val index = indexFrom(nodeMap, mask, bitpos)
return this.getNode(index).contains(element, originalHash, elementHash, shift + BitPartitionSize)
}
false
}
def updated(element: A, originalHash: Int, elementHash: Int, shift: Int): BitmapIndexedSetNode[A] = {
val mask = maskFrom(elementHash, shift)
val bitpos = bitposFrom(mask)
if ((dataMap & bitpos) != 0) {
val index = indexFrom(dataMap, mask, bitpos)
val element0 = this.getPayload(index)
if (element0.asInstanceOf[AnyRef] eq element.asInstanceOf[AnyRef]) {
return this
} else {
val element0UnimprovedHash = getHash(index)
val element0Hash = improve(element0UnimprovedHash)
if (originalHash == element0UnimprovedHash && element0 == element) {
return this
} else {
val subNodeNew = mergeTwoKeyValPairs(element0, element0UnimprovedHash, element0Hash, element, originalHash, elementHash, shift + BitPartitionSize)
return copyAndMigrateFromInlineToNode(bitpos, element0Hash, subNodeNew)
}
}
}
if ((nodeMap & bitpos) != 0) {
val index = indexFrom(nodeMap, mask, bitpos)
val subNode = this.getNode(index)
val subNodeNew = subNode.updated(element, originalHash, elementHash, shift + BitPartitionSize)
if (subNode eq subNodeNew) {
return this
} else {
return copyAndSetNode(bitpos, subNode, subNodeNew)
}
}
copyAndInsertValue(bitpos, element, originalHash, elementHash)
}
/** A variant of `updated` which performs shallow mutations on the root (`this`), and if possible, on immediately
* descendant child nodes (only one level beneath `this`)
*
* The caller should pass a bitmap of child nodes of this node, which this method may mutate.
* If this method may mutate a child node, then if the updated value is located in that child node, it will
* be shallowly mutated (its children will not be mutated).
*
* If instead this method may not mutate the child node in which the to-be-updated value is located, then
* that child will be updated immutably, but the result will be mutably re-inserted as a child of this node.
*
* @param key the key to update
* @param originalHash key.##
* @param keyHash the improved hash
* @param shallowlyMutableNodeMap bitmap of child nodes of this node, which can be shallowly mutated
* during the call to this method
*
* @return Int which is the bitwise OR of shallowlyMutableNodeMap and any freshly created nodes, which will be
* available for mutations in subsequent calls.
*/
def updateWithShallowMutations(element: A, originalHash: Int, elementHash: Int, shift: Int, shallowlyMutableNodeMap: Int): Int = {
val mask = maskFrom(elementHash, shift)
val bitpos = bitposFrom(mask)
if ((dataMap & bitpos) != 0) {
val index = indexFrom(dataMap, mask, bitpos)
val element0 = getPayload(index)
val element0UnimprovedHash = getHash(index)
if (element0UnimprovedHash == originalHash && element0 == element) {
shallowlyMutableNodeMap
} else {
val element0Hash = improve(element0UnimprovedHash)
val subNodeNew = mergeTwoKeyValPairs(element0, element0UnimprovedHash, element0Hash, element, originalHash, elementHash, shift + BitPartitionSize)
migrateFromInlineToNodeInPlace(bitpos, element0Hash, subNodeNew)
shallowlyMutableNodeMap | bitpos
}
} else if ((nodeMap & bitpos) != 0) {
val index = indexFrom(nodeMap, mask, bitpos)
val subNode = this.getNode(index)
val subNodeSize = subNode.size
val subNodeCachedJavaKeySetHashCode = subNode.cachedJavaKeySetHashCode
var returnNodeMap = shallowlyMutableNodeMap
val subNodeNew: SetNode[A] = subNode match {
case subNodeBm: BitmapIndexedSetNode[A] if (bitpos & shallowlyMutableNodeMap) != 0 =>
subNodeBm.updateWithShallowMutations(element, originalHash, elementHash, shift + BitPartitionSize, 0)
subNodeBm
case _ =>
val subNodeNew = subNode.updated(element, originalHash, elementHash, shift + BitPartitionSize)
if (subNodeNew ne subNode) {
returnNodeMap |= bitpos
}
subNodeNew
}
this.content(this.content.length - 1 - this.nodeIndex(bitpos)) = subNodeNew
this.size = this.size - subNodeSize + subNodeNew.size
this.cachedJavaKeySetHashCode = this.cachedJavaKeySetHashCode - subNodeCachedJavaKeySetHashCode + subNodeNew.cachedJavaKeySetHashCode
returnNodeMap
} else {
val dataIx = dataIndex(bitpos)
val idx = dataIx
val src = this.content
val dst = new Array[Any](src.length + TupleLength)
// copy 'src' and insert 2 element(s) at position 'idx'
arraycopy(src, 0, dst, 0, idx)
dst(idx) = element
arraycopy(src, idx, dst, idx + TupleLength, src.length - idx)
val dstHashes = insertElement(originalHashes, dataIx, originalHash)
this.dataMap |= bitpos
this.content = dst
this.originalHashes = dstHashes
this.size += 1
this.cachedJavaKeySetHashCode += elementHash
shallowlyMutableNodeMap
}
}
def removed(element: A, originalHash: Int, elementHash: Int, shift: Int): BitmapIndexedSetNode[A] = {
val mask = maskFrom(elementHash, shift)
val bitpos = bitposFrom(mask)
if ((dataMap & bitpos) != 0) {
val index = indexFrom(dataMap, mask, bitpos)
val element0 = this.getPayload(index)
if (element0 == element) {
if (this.payloadArity == 2 && this.nodeArity == 0) {
/*
* Create new node with remaining pair. The new node will a) either become the new root
* returned, or b) unwrapped and inlined during returning.
*/
val newDataMap = if (shift == 0) (dataMap ^ bitpos) else bitposFrom(maskFrom(elementHash, 0))
if (index == 0)
return new BitmapIndexedSetNode[A](newDataMap, 0, Array(getPayload(1)), Array(originalHashes(1)), size - 1, improve(originalHashes(1)))
else
return new BitmapIndexedSetNode[A](newDataMap, 0, Array(getPayload(0)), Array(originalHashes(0)), size - 1, improve(originalHashes(0)))
}
else return copyAndRemoveValue(bitpos, elementHash)
} else return this
}
if ((nodeMap & bitpos) != 0) {
val index = indexFrom(nodeMap, mask, bitpos)
val subNode = this.getNode(index)
val subNodeNew = subNode.removed(element, originalHash, elementHash, shift + BitPartitionSize)
if (subNodeNew eq subNode) return this
// cache just in case subNodeNew is a hashCollision node, in which in which case a little arithmetic is avoided
// in Vector#length
val subNodeNewSize = subNodeNew.size
if (subNodeNewSize == 1) {
if (this.size == subNode.size) {
// subNode is the only child (no other data or node children of `this` exist)
// escalate (singleton or empty) result
return subNodeNew.asInstanceOf[BitmapIndexedSetNode[A]]
} else {
// inline value (move to front)
return copyAndMigrateFromNodeToInline(bitpos, elementHash, subNode, subNodeNew)
}
} else if (subNodeNewSize > 1) {
// modify current node (set replacement node)
return copyAndSetNode(bitpos, subNode, subNodeNew)
}
}
this
}
/** Variant of `removed` which will perform mutation on only the top-level node (`this`), rather than return a new
* node
*
* Should only be called on root nodes, because shift is assumed to be 0
*
* @param element the element to remove
* @param originalHash the original hash of `element`
* @param elementHash the improved hash of `element`
*/
def removeWithShallowMutations(element: A, originalHash: Int, elementHash: Int): this.type = {
val mask = maskFrom(elementHash, 0)
val bitpos = bitposFrom(mask)
if ((dataMap & bitpos) != 0) {
val index = indexFrom(dataMap, mask, bitpos)
val element0 = this.getPayload(index)
if (element0 == element) {
if (this.payloadArity == 2 && this.nodeArity == 0) {
val newDataMap = dataMap ^ bitpos
if (index == 0) {
val newContent = Array[Any](getPayload(1))
val newOriginalHashes = Array(originalHashes(1))
val newCachedJavaKeySetHashCode = improve(getHash(1))
this.content = newContent
this.originalHashes = newOriginalHashes
this.cachedJavaKeySetHashCode = newCachedJavaKeySetHashCode
} else {
val newContent = Array[Any](getPayload(0))
val newOriginalHashes = Array(originalHashes(0))
val newCachedJavaKeySetHashCode = improve(getHash(0))
this.content = newContent
this.originalHashes = newOriginalHashes
this.cachedJavaKeySetHashCode = newCachedJavaKeySetHashCode
}
this.dataMap = newDataMap
this.nodeMap = 0
this.size = 1
this
}
else {
val dataIx = dataIndex(bitpos)
val idx = TupleLength * dataIx
val src = this.content
val dst = new Array[Any](src.length - TupleLength)
arraycopy(src, 0, dst, 0, idx)
arraycopy(src, idx + TupleLength, dst, idx, src.length - idx - TupleLength)
val dstHashes = removeElement(originalHashes, dataIx)
this.dataMap = this.dataMap ^ bitpos
this.content = dst
this.originalHashes = dstHashes
this.size -= 1
this.cachedJavaKeySetHashCode -= elementHash
this
}
} else this
} else if ((nodeMap & bitpos) != 0) {
val index = indexFrom(nodeMap, mask, bitpos)
val subNode = this.getNode(index)
val subNodeNew = subNode.removed(element, originalHash, elementHash, BitPartitionSize).asInstanceOf[BitmapIndexedSetNode[A]]
if (subNodeNew eq subNode) return this
if (subNodeNew.size == 1) {
if (this.payloadArity == 0 && this.nodeArity == 1) {
this.dataMap = subNodeNew.dataMap
this.nodeMap = subNodeNew.nodeMap
this.content = subNodeNew.content
this.originalHashes = subNodeNew.originalHashes
this.size = subNodeNew.size
this.cachedJavaKeySetHashCode = subNodeNew.cachedJavaKeySetHashCode
this
} else {
migrateFromNodeToInlineInPlace(bitpos, originalHash, elementHash, subNode, subNodeNew)
this
}
} else {
// size must be > 1
this.content(this.content.length - 1 - this.nodeIndex(bitpos)) = subNodeNew
this.size -= 1
this.cachedJavaKeySetHashCode = this.cachedJavaKeySetHashCode - subNode.cachedJavaKeySetHashCode + subNodeNew.cachedJavaKeySetHashCode
this
}
} else this
}
def mergeTwoKeyValPairs(key0: A, originalKeyHash0: Int, keyHash0: Int, key1: A, originalKeyHash1: Int, keyHash1: Int, shift: Int): SetNode[A] = {
// assert(key0 != key1)
if (shift >= HashCodeLength) {
new HashCollisionSetNode[A](originalKeyHash0, keyHash0, Vector(key0, key1))
} else {
val mask0 = maskFrom(keyHash0, shift)
val mask1 = maskFrom(keyHash1, shift)
if (mask0 != mask1) {
// unique prefixes, payload fits on same level
val dataMap = bitposFrom(mask0) | bitposFrom(mask1)
val newCachedHashCode = keyHash0 + keyHash1
if (mask0 < mask1) {
new BitmapIndexedSetNode[A](dataMap, 0, Array(key0, key1), Array(originalKeyHash0, originalKeyHash1), 2, newCachedHashCode)
} else {
new BitmapIndexedSetNode[A](dataMap, 0, Array(key1, key0), Array(originalKeyHash1, originalKeyHash0), 2, newCachedHashCode)
}
} else {
// identical prefixes, payload must be disambiguated deeper in the trie
val nodeMap = bitposFrom(mask0)
val node = mergeTwoKeyValPairs(key0, originalKeyHash0, keyHash0, key1, originalKeyHash1, keyHash1, shift + BitPartitionSize)
new BitmapIndexedSetNode[A](0, nodeMap, Array(node), Array.emptyIntArray, node.size, node.cachedJavaKeySetHashCode)
}
}
}
def hasPayload: Boolean = dataMap != 0
def payloadArity: Int = bitCount(dataMap)
def hasNodes: Boolean = nodeMap != 0
def nodeArity: Int = bitCount(nodeMap)
def dataIndex(bitpos: Int) = bitCount(dataMap & (bitpos - 1))
def nodeIndex(bitpos: Int) = bitCount(nodeMap & (bitpos - 1))
def copyAndSetNode(bitpos: Int, oldNode: SetNode[A], newNode: SetNode[A]) = {
val idx = this.content.length - 1 - this.nodeIndex(bitpos)
val src = this.content
val dst = new Array[Any](src.length)
// copy 'src' and set 1 element(s) at position 'idx'
arraycopy(src, 0, dst, 0, src.length)
dst(idx) = newNode
new BitmapIndexedSetNode[A](
dataMap = dataMap,
nodeMap = nodeMap,
content = dst,
originalHashes = originalHashes,
size = size - oldNode.size + newNode.size,
cachedJavaKeySetHashCode = cachedJavaKeySetHashCode - oldNode.cachedJavaKeySetHashCode + newNode.cachedJavaKeySetHashCode
)
}
def copyAndInsertValue(bitpos: Int, key: A, originalHash: Int, elementHash: Int) = {
val dataIx = dataIndex(bitpos)
val idx = TupleLength * dataIx
val src = this.content
val dst = new Array[Any](src.length + 1)
// copy 'src' and insert 1 element(s) at position 'idx'
arraycopy(src, 0, dst, 0, idx)
dst(idx) = key
arraycopy(src, idx, dst, idx + 1, src.length - idx)
val dstHashes = insertElement(originalHashes, dataIx, originalHash)
new BitmapIndexedSetNode[A](dataMap | bitpos, nodeMap, dst, dstHashes, size + 1, cachedJavaKeySetHashCode + elementHash)
}
def copyAndSetValue(bitpos: Int, key: A, originalHash: Int, elementHash: Int) = {
val dataIx = dataIndex(bitpos)
val idx = TupleLength * dataIx
val src = this.content
val dst = new Array[Any](src.length)
// copy 'src' and set 1 element(s) at position 'idx'
arraycopy(src, 0, dst, 0, src.length)
dst(idx) = key
new BitmapIndexedSetNode[A](dataMap | bitpos, nodeMap, dst, originalHashes, size, cachedJavaKeySetHashCode)
}
def copyAndRemoveValue(bitpos: Int, elementHash: Int) = {
val dataIx = dataIndex(bitpos)
val idx = TupleLength * dataIx
val src = this.content
val dst = new Array[Any](src.length - 1)
// copy 'src' and remove 1 element(s) at position 'idx'
arraycopy(src, 0, dst, 0, idx)
arraycopy(src, idx + 1, dst, idx, src.length - idx - 1)
val dstHashes = removeElement(originalHashes, dataIx)
new BitmapIndexedSetNode[A](dataMap ^ bitpos, nodeMap, dst, dstHashes, size - 1, cachedJavaKeySetHashCode - elementHash)
}
def copyAndMigrateFromInlineToNode(bitpos: Int, elementHash: Int, node: SetNode[A]) = {
val dataIx = dataIndex(bitpos)
val idxOld = TupleLength * dataIx
val idxNew = this.content.length - TupleLength - nodeIndex(bitpos)
val src = this.content
val dst = new Array[Any](src.length - 1 + 1)
// copy 'src' and remove 1 element(s) at position 'idxOld' and
// insert 1 element(s) at position 'idxNew'
// assert(idxOld <= idxNew)
arraycopy(src, 0, dst, 0, idxOld)
arraycopy(src, idxOld + 1, dst, idxOld, idxNew - idxOld)
dst(idxNew) = node
arraycopy(src, idxNew + 1, dst, idxNew + 1, src.length - idxNew - 1)
val dstHashes = removeElement(originalHashes, dataIx)
new BitmapIndexedSetNode[A](
dataMap = dataMap ^ bitpos,
nodeMap = nodeMap | bitpos,
content = dst, originalHashes = dstHashes,
size = size - 1 + node.size,
cachedJavaKeySetHashCode = cachedJavaKeySetHashCode - elementHash + node.cachedJavaKeySetHashCode
)
}
/** Variant of `copyAndMigrateFromInlineToNode` which mutates `this` rather than returning a new node.
*
* Note: This method will mutate `this`, and will mutate `this.content`
*
* Mutation of `this.content` will occur as an optimization not possible in maps. Since TupleLength == 1 for sets,
* content array size does not change during inline <-> node migrations. Therefor, since we are updating in-place,
* we reuse this.content by shifting data/nodes around, rather than allocating a new array.
*
* @param bitpos the bit position of the data to migrate to node
* @param keyHash the improved hash of the element currently at `bitpos`
* @param node the node to place at `bitpos`
*/
def migrateFromInlineToNodeInPlace(bitpos: Int, keyHash: Int, node: SetNode[A]): this.type = {
val dataIx = dataIndex(bitpos)
val idxOld = TupleLength * dataIx
val idxNew = this.content.length - TupleLength - nodeIndex(bitpos)
arraycopy(content, idxOld + TupleLength, content, idxOld, idxNew - idxOld)
content(idxNew) = node
this.dataMap = this.dataMap ^ bitpos
this.nodeMap = this.nodeMap | bitpos
this.originalHashes = removeElement(originalHashes, dataIx)
this.size = this.size - 1 + node.size
this.cachedJavaKeySetHashCode = this.cachedJavaKeySetHashCode - keyHash + node.cachedJavaKeySetHashCode
this
}
def copyAndMigrateFromNodeToInline(bitpos: Int, elementHash: Int, oldNode: SetNode[A], node: SetNode[A]) = {
val idxOld = this.content.length - 1 - nodeIndex(bitpos)
val dataIxNew = dataIndex(bitpos)
val idxNew = TupleLength * dataIxNew
val src = this.content
val dst = new Array[Any](src.length - 1 + 1)
// copy 'src' and remove 1 element(s) at position 'idxOld' and
// insert 1 element(s) at position 'idxNew'
// assert(idxOld >= idxNew)
arraycopy(src, 0, dst, 0, idxNew)
dst(idxNew) = node.getPayload(0)
arraycopy(src, idxNew, dst, idxNew + 1, idxOld - idxNew)
arraycopy(src, idxOld + 1, dst, idxOld + 1, src.length - idxOld - 1)
val hash = node.getHash(0)
val dstHashes = insertElement(originalHashes, dataIxNew, hash)
new BitmapIndexedSetNode[A](
dataMap = dataMap | bitpos,
nodeMap = nodeMap ^ bitpos,
content = dst,
originalHashes = dstHashes,
size = size - oldNode.size + 1,
cachedJavaKeySetHashCode = cachedJavaKeySetHashCode - oldNode.cachedJavaKeySetHashCode + node.cachedJavaKeySetHashCode
)
}
/** Variant of `copyAndMigrateFromNodeToInline` which mutates `this` rather than returning a new node.
*
* Note: This method will mutate `this`, and will mutate `this.content`
*
* Mutation of `this.content` will occur as an optimization not possible in maps. Since TupleLength == 1 for sets,
* content array size does not change during inline <-> node migrations. Therefor, since we are updating in-place,
* we reuse this.content by shifting data/nodes around, rather than allocating a new array.
*
* @param bitpos the bit position of the node to migrate inline
* @param oldNode the node currently stored at position `bitpos`
* @param node the node containing the single element to migrate inline
*/
def migrateFromNodeToInlineInPlace(bitpos: Int, originalHash: Int, elementHash: Int, oldNode: SetNode[A], node: SetNode[A]): Unit = {
val idxOld = this.content.length - 1 - nodeIndex(bitpos)
val dataIxNew = dataIndex(bitpos)
val element = node.getPayload(0)
arraycopy(content, dataIxNew, content, dataIxNew + 1, idxOld - dataIxNew)
content(dataIxNew) = element
val hash = node.getHash(0)
val dstHashes = insertElement(originalHashes, dataIxNew, hash)
this.dataMap = this.dataMap | bitpos
this.nodeMap = this.nodeMap ^ bitpos
this.originalHashes = dstHashes
this.size = this.size - oldNode.size + 1
this.cachedJavaKeySetHashCode = this.cachedJavaKeySetHashCode - oldNode.cachedJavaKeySetHashCode + node.cachedJavaKeySetHashCode
}
def foreach[U](f: A => U): Unit = {
val thisPayloadArity = payloadArity
var i = 0
while (i < thisPayloadArity) {
f(getPayload(i))
i += 1
}
val thisNodeArity = nodeArity
var j = 0
while (j < thisNodeArity) {
getNode(j).foreach(f)
j += 1
}
}
def subsetOf(that: SetNode[A], shift: Int): Boolean = if (this eq that) true else that match {
case _: HashCollisionSetNode[A] => false
case node: BitmapIndexedSetNode[A] =>
val thisBitmap = this.dataMap | this.nodeMap
val nodeBitmap = node.dataMap | node.nodeMap
if ((thisBitmap | nodeBitmap) != nodeBitmap)
return false
var bitmap = thisBitmap & nodeBitmap
var bitsToSkip = numberOfTrailingZeros(bitmap)
var isValidSubset = true
while (isValidSubset && bitsToSkip < HashCodeLength) {
val bitpos = bitposFrom(bitsToSkip)
isValidSubset =
if ((this.dataMap & bitpos) != 0) {
if ((node.dataMap & bitpos) != 0) {
// Data x Data
val payload0 = this.getPayload(indexFrom(this.dataMap, bitpos))
val payload1 = node.getPayload(indexFrom(node.dataMap, bitpos))
payload0 == payload1
} else {
// Data x Node
val thisDataIndex = indexFrom(this.dataMap, bitpos)
val payload = this.getPayload(thisDataIndex)
val subNode = that.getNode(indexFrom(node.nodeMap, bitpos))
val elementUnimprovedHash = getHash(thisDataIndex)
val elementHash = improve(elementUnimprovedHash)
subNode.contains(payload, elementUnimprovedHash, elementHash, shift + BitPartitionSize)
}
} else {
// Node x Node
val subNode0 = this.getNode(indexFrom(this.nodeMap, bitpos))
val subNode1 = node.getNode(indexFrom(node.nodeMap, bitpos))
subNode0.subsetOf(subNode1, shift + BitPartitionSize)
}
val newBitmap = bitmap ^ bitpos
bitmap = newBitmap
bitsToSkip = numberOfTrailingZeros(newBitmap)
}
isValidSubset
}
override def filterImpl(pred: A => Boolean, flipped: Boolean): BitmapIndexedSetNode[A] = {
if (size == 0) this
else if (size == 1) {
if (pred(getPayload(0)) != flipped) this else SetNode.empty
} else if (nodeMap == 0) {
// Performance optimization for nodes of depth 1: