Repository navigation
Expand file tree
/
Copy pathSetStorage.cs
More file actions
1415 lines (1192 loc) · 47.5 KB
/
Copy pathSetStorage.cs
File metadata and controls
1415 lines (1192 loc) · 47.5 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
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* [email protected]. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
*
* ***************************************************************************/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Text;
using System.Threading;
using Microsoft.Scripting;
using Microsoft.Scripting.Utils;
using IronPython.Runtime.Operations;
using IronPython.Runtime.Types;
namespace IronPython.Runtime {
/// <summary>
/// General-purpose storage used for Python sets and frozensets.
///
/// The set storage is thread-safe for multiple readers or writers.
///
/// Mutations to the set involve a simple locking strategy of locking on the SetStorage object
/// itself to ensure mutual exclusion.
///
/// Reads against the set happen lock-free. When the set is mutated, it adds or removes buckets
/// in an atomic manner so that the readers will see a consistent picture as if the read
/// occurred either before or after the mutation.
/// </summary>
[Serializable]
internal sealed class SetStorage : IEnumerable, IEnumerable<object>, ISerializable, IDeserializationCallback {
internal Bucket[] _buckets;
internal int _count;
private int _version;
internal bool _hasNull;
private Func<object, int> _hashFunc;
private Func<object, object, bool> _eqFunc;
private Type _itemType;
// The maximum item count before resizing must occur. This is precomputed upon resizing
// rather than multiplying by the load factor every time items are added.
private int _maxCount;
private const int InitialBuckets = 8;
private const double Load = 0.7;
private const double MinLoad = 0.5; // dictates Clone() behavior
// marker type to indicate we've gone megamorphic (SetStorage happens to be a a type we'll
// never see as a set element
private static readonly Type HeterogeneousType = typeof(SetStorage);
// marker object used to indicate we have a removed value
internal static readonly object Removed = new object();
/// <summary>
/// Creates a new set storage with no buckets
/// </summary>
public SetStorage() { }
/// <summary>
/// Creates a new set storage with no buckets
/// </summary>
public SetStorage(int count) {
Initialize(count);
}
#if FEATURE_SERIALIZATION
private SetStorage(SerializationInfo info, StreamingContext context) {
// remember the serialization info; we'll deserialize when we get the callback. This
// enables special types like DBNull.Value to successfully be deserialized inside the
// set. We store the serialization info in a single-element bucket array so we don't
// have an extra field just for serialization.
_buckets = new Bucket[] { new Bucket(0, info) };
}
#endif
private void Initialize() {
_maxCount = (int)(InitialBuckets * Load);
_buckets = new Bucket[InitialBuckets];
}
private void Initialize(int count) {
int bucketCount = Math.Max((int)(count / Load) + 1, InitialBuckets);
// convert to a power of 2
bucketCount = 1 << CeilLog2(bucketCount);
_maxCount = (int)(bucketCount * Load);
_buckets = new Bucket[bucketCount];
}
/// <summary>
/// Returns the number of items currently in the set
/// </summary>
public int Count {
get {
int res = _count;
if (_hasNull) {
res++;
}
return res;
}
}
public int Version {
get {
return _version;
}
}
/// <summary>
/// Adds a new item to the set, unless an equivalent item is already present
/// </summary>
public void Add(object item) {
lock (this) {
AddNoLock(item);
}
}
public void AddNoLock(object item) {
if (item != null) {
if (_buckets == null) {
Initialize();
}
if (item.GetType() != _itemType && _itemType != HeterogeneousType) {
UpdateHelperFunctions(item.GetType(), item);
}
AddWorker(item, Hash(item));
} else {
_hasNull = true;
}
}
private void AddWorker(object/*!*/ item, int hashCode) {
Debug.Assert(_buckets != null && _count < _buckets.Length);
if (AddWorker(_buckets, item, hashCode, _eqFunc, ref _version)) {
_count++;
if (_count > _maxCount) {
Grow();
}
}
}
/// <summary>
/// Static helper which adds the given non-null item with a precomputed hash code. Returns
/// true if the item was added, false if it was already present in the set.
/// </summary>
private static bool AddWorker(
Bucket[]/*!*/ buckets, object/*!*/ item, int hashCode,
Func<object, object, bool> eqFunc, ref int version
) {
Debug.Assert(buckets != null);
Debug.Assert(item != null);
for (int index = hashCode & (buckets.Length - 1); ; ProbeNext(buckets, ref index)) {
Bucket bucket = buckets[index];
if (bucket.Item == null || bucket.Item == Removed) {
version++;
buckets[index].HashCode = hashCode;
buckets[index].Item = item;
return true;
} else if (bucket.HashCode == hashCode && eqFunc(item, bucket.Item)) {
return false;
}
}
}
/// <summary>
/// Lock-free helper on a non-null item with a pre-calculated hash code. Removes the item
/// if it is present in the set, otherwise adds it.
/// </summary>
private void AddOrRemoveWorker(object/*!*/ item, int hashCode) {
Debug.Assert(_buckets != null);
Debug.Assert(item != null);
for (int index = hashCode & (_buckets.Length - 1); ; ProbeNext(_buckets, ref index)) {
Bucket bucket = _buckets[index];
if (bucket.Item == null) {
_version++;
_buckets[index].HashCode = hashCode;
_buckets[index].Item = item;
_count++;
if (_count > _maxCount) {
Grow();
}
return;
} else if (
bucket.Item != Removed && bucket.HashCode == hashCode &&
_eqFunc(item, bucket.Item)
) {
_version++;
_buckets[index].Item = Removed;
_count--;
return;
}
}
}
/// <summary>
/// Clears the contents of the set
/// </summary>
public void Clear() {
lock (this) {
ClearNoLock();
}
}
public void ClearNoLock() {
if (_buckets != null) {
_version++;
Initialize();
_count = 0;
}
_hasNull = false;
}
/// <summary>
/// Clones the set, returning a new SetStorage object
/// </summary>
public SetStorage Clone() {
SetStorage res = new SetStorage();
res._hasNull = _hasNull;
if (_count == 0) {
return res;
}
Bucket[] buckets = _buckets;
res._hashFunc = _hashFunc;
res._eqFunc = _eqFunc;
res._itemType = _itemType;
if (_count < _buckets.Length * MinLoad) {
// If the set is sparsely populated, create a cleaner copy
res.Initialize(_count);
for (int i = 0; i < buckets.Length; i++) {
Bucket bucket = buckets[i];
if (bucket.Item != null && bucket.Item != Removed) {
res.AddWorker(bucket.Item, bucket.HashCode);
}
}
} else {
// Otherwise, perform a faster copy
res._maxCount = (int)(buckets.Length * Load);
res._buckets = new Bucket[buckets.Length];
for (int i = 0; i < buckets.Length; i++) {
Bucket bucket = buckets[i];
if (bucket.Item != null) {
res._buckets[i].Item = bucket.Item;
res._buckets[i].HashCode = bucket.HashCode;
res._count++;
}
}
}
return res;
}
/// <summary>
/// Checks to see if the given item exists in the set
/// </summary>
public bool Contains(object item) {
if (item == null) {
return _hasNull;
}
if (_count == 0) {
return false;
}
int hashCode;
Func<object, object, bool> eqFunc;
if (item.GetType() == _itemType || _itemType == HeterogeneousType) {
hashCode = _hashFunc(item);
eqFunc = _eqFunc;
} else {
hashCode = _genericHash(item);
eqFunc = _genericEquals;
}
return ContainsWorker(_buckets, item, hashCode, eqFunc);
}
/// <summary>
/// Checks to see if the given item exists in the set, and tries to hash it even
/// if it is known not to be in the set.
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
public bool ContainsAlwaysHash(object item) {
if (item == null) {
return _hasNull;
}
int hashCode;
Func<object, object, bool> eqFunc;
if (item.GetType() == _itemType || _itemType == HeterogeneousType) {
hashCode = _hashFunc(item);
eqFunc = _eqFunc;
} else {
hashCode = _genericHash(item);
eqFunc = _genericEquals;
}
return _count > 0 && ContainsWorker(_buckets, item, hashCode, eqFunc);
}
private static bool ContainsWorker(
Bucket[]/*!*/ buckets, object/*!*/ item, int hashCode,
Func<object, object, bool> eqFunc
) {
Debug.Assert(item != null);
Debug.Assert(buckets != null);
Debug.Assert(eqFunc != null);
int index = hashCode & (buckets.Length - 1);
int startIndex = index;
do {
Bucket bucket = buckets[index];
if (bucket.Item == null) {
break;
} else if (
bucket.Item != Removed && bucket.HashCode == hashCode &&
eqFunc(item, bucket.Item)
) {
return true;
}
ProbeNext(buckets, ref index);
} while (startIndex != index);
return false;
}
/// <summary>
/// Adds items from this set into the other set
/// </summary>
public void CopyTo(SetStorage/*!*/ into) {
Debug.Assert(into != null);
lock (into) {
into.UnionUpdate(this);
}
}
IEnumerator IEnumerable.GetEnumerator() {
return GetEnumerator();
}
public IEnumerator<object> GetEnumerator() {
if (_hasNull) {
yield return null;
}
if (_count == 0) {
yield break;
}
Bucket[] buckets = _buckets;
for (int i = 0; i < buckets.Length; i++) {
object item = buckets[i].Item;
if (item != null && item != Removed) {
yield return item;
}
}
}
public List/*!*/ GetItems() {
List res = new List(Count);
if (_hasNull) {
res.AddNoLock(null);
}
if (_count > 0) {
Bucket[] buckets = _buckets;
for (int i = 0; i < buckets.Length; i++) {
object item = buckets[i].Item;
if (item != null && item != Removed) {
res.AddNoLock(item);
}
}
}
return res;
}
/// <summary>
/// Removes the first set element in the iteration order.
/// </summary>
/// <returns>true if an item was removed, false if the set was empty</returns>
public bool Pop(out object item) {
item = null;
if (_hasNull) {
_hasNull = false;
return true;
}
if (_count == 0) {
return false;
}
lock (this) {
for (int i = 0; i < _buckets.Length; i++) {
if (_buckets[i].Item != null && _buckets[i].Item != Removed) {
item = _buckets[i].Item;
_version++;
_buckets[i].Item = Removed;
_count--;
return true;
}
}
item = null;
return false;
}
}
/// <summary>
/// Removes an item from the set and returns true if it was present, otherwise returns
/// false
/// </summary>
public bool Remove(object item) {
lock (this) {
return RemoveNoLock(item);
}
}
public bool RemoveNoLock(object item) {
if (item == null) {
return RemoveNull();
}
if (_count == 0) {
return false;
}
return RemoveItem(item);
}
/// <summary>
/// Removes an item from the set and returns true if it was removed. The item will always
/// be hashed, throwing if it is unhashable - even if the set has no buckets.
/// </summary>
internal bool RemoveAlwaysHash(object item) {
lock (this) {
if (item == null) {
return RemoveNull();
}
return RemoveItem(item);
}
}
private bool RemoveNull() {
if (_hasNull) {
_hasNull = false;
return true;
}
return false;
}
/// <summary>
/// Lock-free helper to remove a non-null item
/// </summary>
private bool RemoveItem(object/*!*/ item) {
Debug.Assert(item != null);
int hashCode;
Func<object, object, bool> eqFunc;
if (item.GetType() == _itemType || _itemType == HeterogeneousType) {
hashCode = _hashFunc(item);
eqFunc = _eqFunc;
} else {
hashCode = _genericHash(item);
eqFunc = _genericEquals;
}
return RemoveWorker(item, hashCode, eqFunc);
}
private bool RemoveWorker(
object/*!*/ item, int hashCode, Func<object, object, bool> eqFunc
) {
Debug.Assert(item != null);
if (_count == 0) {
return false;
}
int index = hashCode & (_buckets.Length - 1);
int startIndex = index;
do {
Bucket bucket = _buckets[index];
if (bucket.Item == null) {
break;
} else if (
bucket.Item != Removed && bucket.HashCode == hashCode &&
eqFunc(item, bucket.Item)
) {
_version++;
_buckets[index].Item = Removed;
_count--;
return true;
}
ProbeNext(_buckets, ref index);
} while (index != startIndex);
return false;
}
#region Set Operations
// Each of these set operations mutate the current set lock-free. Synchronization must
// be done by the caller if desired.
/// <summary>
/// Determines whether the current set shares no elements with the given set
/// </summary>
public bool IsDisjoint(SetStorage other) {
return IsDisjoint(this, other);
}
public static bool IsDisjoint(SetStorage self, SetStorage other) {
SortBySize(ref self, ref other);
if (self._hasNull && other._hasNull) {
return false;
}
if (self._count == 0 || other._count == 0) {
return true;
}
Bucket[] buckets = self._buckets;
Bucket[] otherBuckets = other._buckets;
var eqFunc = GetEqFunc(self, other);
for (int i = 0; i < buckets.Length; i++) {
Bucket bucket = buckets[i];
if (bucket.Item != null && bucket.Item != Removed &&
ContainsWorker(otherBuckets, bucket.Item, bucket.HashCode, eqFunc)) {
return false;
}
}
return true;
}
/// <summary>
/// Determines whether the current set is a subset of the given set
/// </summary>
public bool IsSubset(SetStorage other) {
if (_count > other._count ||
_hasNull && !other._hasNull) {
return false;
}
return IsSubsetWorker(other);
}
/// <summary>
/// Determines whether the current set is a strict subset of the given set
/// </summary>
public bool IsStrictSubset(SetStorage other) {
if (_count > other._count ||
_hasNull && !other._hasNull ||
Count == other.Count) {
return false;
}
return IsSubsetWorker(other);
}
private bool IsSubsetWorker(SetStorage other) {
if (_count == 0) {
return true;
}
if (other._count == 0) {
return false;
}
Bucket[] buckets = _buckets;
Bucket[] otherBuckets = other._buckets;
var eqFunc = GetEqFunc(this, other);
for (int i = 0; i < buckets.Length; i++) {
Bucket bucket = buckets[i];
if (bucket.Item != null && bucket.Item != Removed &&
!ContainsWorker(otherBuckets, bucket.Item, bucket.HashCode, eqFunc)) {
return false;
}
}
return true;
}
/// <summary>
/// Mutates this set to contain its union with 'other'. The caller must lock the current
/// set if synchronization is desired.
/// </summary>
public void UnionUpdate(SetStorage other) {
_hasNull |= other._hasNull;
if (other._count == 0) {
return;
}
if (_buckets == null) {
Initialize(other._count);
}
Bucket[] otherBuckets = other._buckets;
UpdateHelperFunctions(other);
for (int i = 0; i < otherBuckets.Length; i++) {
Bucket bucket = otherBuckets[i];
if (bucket.Item != null && bucket.Item != Removed) {
AddWorker(bucket.Item, bucket.HashCode);
}
}
}
/// <summary>
/// Mutates this set to contain its intersection with 'other'. The caller must lock the
/// current set if synchronization is desired.
/// </summary>
public void IntersectionUpdate(SetStorage other) {
if (other._count == 0) {
ClearNoLock();
_hasNull &= other._hasNull;
return;
}
_hasNull &= other._hasNull;
if (_count == 0) {
return;
}
Bucket[] buckets = _buckets;
Bucket[] otherBuckets = other._buckets;
var eqFunc = GetEqFunc(this, other);
for (int i = 0; i < buckets.Length; i++) {
Bucket bucket = buckets[i];
if (bucket.Item != null && bucket.Item != Removed &&
!ContainsWorker(otherBuckets, bucket.Item, bucket.HashCode, eqFunc)) {
_version++;
buckets[i].Item = Removed;
_count--;
}
}
}
/// <summary>
/// Mutates this set to contain its symmetric difference with 'other'. The caller must
/// lock the current set if synchronization is desired.
/// </summary>
public void SymmetricDifferenceUpdate(SetStorage other) {
_hasNull ^= other._hasNull;
if (other._count == 0) {
return;
}
if (_buckets == null) {
Initialize();
}
Bucket[] otherBuckets = other._buckets;
UpdateHelperFunctions(other);
for (int i = 0; i < otherBuckets.Length; i++) {
Bucket bucket = otherBuckets[i];
if (bucket.Item != null && bucket.Item != Removed) {
AddOrRemoveWorker(bucket.Item, bucket.HashCode);
}
}
}
/// <summary>
/// Mutates this set to contain its difference with 'other'. The caller must lock the
/// current set if synchronization is desired.
/// </summary>
public void DifferenceUpdate(SetStorage other) {
_hasNull &= !other._hasNull;
if (_count == 0 || other._count == 0) {
return;
}
Bucket[] buckets = _buckets;
Bucket[] otherBuckets = other._buckets;
var eqFunc = GetEqFunc(this, other);
if (buckets.Length < otherBuckets.Length) {
// iterate through self, removing anything in other
for (int i = 0; i < buckets.Length; i++) {
Bucket bucket = buckets[i];
if (bucket.Item != null && bucket.Item != Removed &&
ContainsWorker(otherBuckets, bucket.Item, bucket.HashCode, eqFunc)) {
RemoveWorker(bucket.Item, bucket.HashCode, eqFunc);
}
}
} else {
// iterate through other, removing anything we find
for (int i = 0; i < otherBuckets.Length; i++) {
Bucket bucket = otherBuckets[i];
if (bucket.Item != null && bucket.Item != Removed) {
RemoveWorker(bucket.Item, bucket.HashCode, eqFunc);
}
}
}
}
/// <summary>
/// Computes the union of self and other, returning an entirely new set. This method is
/// thread-safe and makes no modifications to self or other.
/// </summary>
public static SetStorage Union(SetStorage self, SetStorage other) {
SetStorage res;
// UnionUpdate iterates through its argument, so clone the larger set
if (self._count < other._count) {
res = other.Clone();
res.UnionUpdate(self);
} else {
res = self.Clone();
res.UnionUpdate(other);
}
return res;
}
/// <summary>
/// Computes the intersection of self and other, returning an entirely new set. This
/// method is thread-safe and makes no modifications to self or other.
/// </summary>
public static SetStorage Intersection(SetStorage self, SetStorage other) {
SetStorage res = new SetStorage(Math.Min(self._count, other._count));
res._hasNull = self._hasNull && other._hasNull;
if (self._count == 0 || other._count == 0) {
return res;
}
SortBySize(ref self, ref other);
Bucket[] buckets = self._buckets;
Bucket[] otherBuckets = other._buckets;
var eqFunc = GetEqFunc(self, other);
// if either set is homogeneous, then the resulting set must be
if (other._itemType != HeterogeneousType) {
res.UpdateHelperFunctions(other);
} else {
res.UpdateHelperFunctions(self);
}
for (int i = 0; i < buckets.Length; i++) {
Bucket bucket = buckets[i];
if (bucket.Item != null && bucket.Item != Removed &&
ContainsWorker(otherBuckets, bucket.Item, bucket.HashCode, eqFunc)) {
res.AddWorker(bucket.Item, bucket.HashCode);
}
}
return res;
}
/// <summary>
/// Computes the symmetric difference of self and other, returning an entirely new set.
/// This method is thread-safe and makes no modifications to self or other.
/// </summary>
public static SetStorage SymmetricDifference(SetStorage self, SetStorage other) {
// SymmetricDifferenceUpdate iterates through its arg, so clone the larger set
SortBySize(ref self, ref other);
SetStorage res = other.Clone();
res.SymmetricDifferenceUpdate(self);
return res;
}
/// <summary>
/// Computes the difference of self and other, returning an entirely new set. This
/// method is thread-safe and makes no modifications to self or other.
/// </summary>
public static SetStorage Difference(SetStorage self, SetStorage other) {
SetStorage res;
if (self._count == 0 || other._count == 0) {
res = self.Clone();
res._hasNull &= !other._hasNull;
return res;
}
if (self._buckets.Length <= other._buckets.Length) {
res = new SetStorage(self._count);
res._hasNull &= !other._hasNull;
Bucket[] buckets = self._buckets;
Bucket[] otherBuckets = other._buckets;
var eqFunc = GetEqFunc(self, other);
res.UpdateHelperFunctions(self);
for (int i = 0; i < buckets.Length; i++) {
Bucket bucket = buckets[i];
if (bucket.Item != null && bucket.Item != Removed &&
!ContainsWorker(otherBuckets, bucket.Item, bucket.HashCode, eqFunc)) {
res.AddWorker(bucket.Item, bucket.HashCode);
}
}
} else {
res = self.Clone();
res.DifferenceUpdate(other);
}
return res;
}
#endregion
#region Comparison and Hashing
public static bool Equals(SetStorage x, SetStorage y, IEqualityComparer comparer) {
if (object.ReferenceEquals(x, y)) {
return true;
}
if (x._count != y._count || (x._hasNull ^ y._hasNull)) {
return false;
}
if (x._count == 0) {
// we know y._count == 0
return true;
}
SortBySize(ref x, ref y);
// optimization when we know the behavior of the comparer
if (comparer is PythonContext.PythonEqualityComparer) {
Bucket[] xBuckets = x._buckets;
Bucket[] yBuckets = y._buckets;
var eqFunc = GetEqFunc(x, y);
for (int i = 0; i < xBuckets.Length; i++) {
Bucket bucket = xBuckets[i];
if (bucket.Item != null && bucket.Item != Removed &&
!ContainsWorker(yBuckets, bucket.Item, bucket.HashCode, eqFunc)) {
return false;
}
}
return true;
}
// Set comparison using the provided comparer. Create special SetStorage objects
// which use comparer's hashing and equality functions.
SetStorage ySet = new SetStorage();
ySet._itemType = HeterogeneousType;
ySet._eqFunc = comparer.Equals;
ySet._hashFunc = comparer.GetHashCode;
foreach (object item in y) {
ySet.AddNoLock(item);
}
foreach (object item in x) {
if (!ySet.RemoveNoLock(item)) {
return false;
}
}
return ySet._count == 0;
}
public static int GetHashCode(SetStorage set, IEqualityComparer/*!*/ comparer) {
Assert.NotNull(comparer);
// hash code needs to be stable across collections (even if items are added in
// different order) and needs to be fairly collision-free.
int hash1 = 1420601183;
int hash2 = 674132117;
int hash3 = 393601577;
if (set._count > 0) {
hash1 ^= set._count * 8803;
hash1 = (hash1 << 10) ^ (hash1 >> 22);
hash2 += set._count * 5179;
hash2 = (hash2 << 10) ^ (hash2 >> 22);
hash3 = hash3 * set._count + 784251623;
hash3 = (hash3 << 10) ^ (hash3 >> 22);
}
if (comparer is PythonContext.PythonEqualityComparer) {
// Comparer with known hash behavior - use the precomputed hash codes.
if (set._hasNull) {
hash1 = (hash1 << 7) ^ (hash1 >> 25) ^ NoneTypeOps.NoneHashCode;
hash2 = ((hash2 << 7) ^ (hash2 >> 25)) + NoneTypeOps.NoneHashCode;
hash3 = ((hash3 << 7) ^ (hash3 >> 25)) * NoneTypeOps.NoneHashCode;
}
if (set._count > 0) {
Bucket[] buckets = set._buckets;
for (int i = 0; i < buckets.Length; i++) {
object item = buckets[i].Item;
if (item != null && item != Removed) {
int hashCode = buckets[i].HashCode;
hash1 ^= hashCode;
hash2 += hashCode;
hash3 *= hashCode;
}
}
}
} else {
// Use the provided comparer for hashing.
if (set._hasNull) {
int hashCode = comparer.GetHashCode(null);
hash1 = (hash1 + ((hash1 << 7) ^ (hash1 >> 25))) ^ hashCode;
hash2 = ((hash2 << 7) ^ (hash2 >> 25)) + hashCode;
hash3 = ((hash3 << 7) ^ (hash3 >> 25)) * hashCode;
}
if (set._count > 0) {
Bucket[] buckets = set._buckets;
for (int i = 0; i < buckets.Length; i++) {
object item = buckets[i].Item;
if (item != null && item != Removed) {
int hashCode = comparer.GetHashCode(item);
hash1 ^= hashCode;
hash2 += hashCode;
hash3 *= hashCode;
}
}
}
}
hash1 = (hash1 << 11) ^ (hash1 >> 21) ^ hash2;
hash1 = (hash1 << 27) ^ (hash1 >> 5) ^ hash3;
return (hash1 << 9) ^ (hash1 >> 23) ^ 2001081521;
}
#endregion
/// <summary>
/// Used to store a single hashed item.
///
/// Bucket is not serializable because it stores the computed hash code, which could change
/// between serialization and deserialization.
/// </summary>
internal struct Bucket {
public object Item;
public int HashCode;
public Bucket(int hashCode, object item) {
HashCode = hashCode;
Item = item;
}
}
#region Hash/Equality Delegates
// pre-created delegate instances shared by all homogeneous sets on primitive types
private static readonly Func<object, int>
_primitiveHash = PrimitiveHash,
_intHash = IntHash,
_doubleHash = DoubleHash,
_tupleHash = TupleHash,
_genericHash = GenericHash;
private static readonly Func<object, object, bool>
_stringEquals = StringEquals,
_intEquals = IntEquals,
_doubleEquals = DoubleEquals,
_tupleEquals = TupleEquals,
_genericEquals = GenericEquals,
_objectEquals = object.ReferenceEquals;
private static int PrimitiveHash(object o) {
return o.GetHashCode();
}