哈希集合
发表于:2025-10-14 | 分类: Dotnet
字数统计: 6.2k | 阅读时长: 38分钟 | 阅读量:

哈希集合

基于 Entry[]? _entries 实现。

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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
// \runtime\src\libraries\System.Private.CoreLib\src\System\Collections\Generic\HashSet.cs
namespace System.Collections.Generic
{
// 和 Dictionary<TKey, TValue> 一样基于array实现
public class HashSet<T> : ICollection<T>, ISet<T>, IReadOnlyCollection<T>, IReadOnlySet<T>, ISerializable, IDeserializationCallback
{
// 栈分配int数据的阈值
private const int StackAllocThreshold = 100;

// 缩容阈值条件,未使用到1/3
private const int ShrinkThreshold = 3;
private const int StartOfFreeList = -3;

// 桶,存放数据所在的index
private int[]? _buckets;
// 实体,具体数据:hashcode next value
private Entry[]? _entries;
#if TARGET_64BIT
private ulong _fastModMultiplier;
#endif
// 数据实体的数量
private int _count;
private int _freeList;
private int _freeCount;
// 版本号,用于标识迭代时确保没有修改集合
private int _version;
private IEqualityComparer<T>? _comparer;

#region Constructors

public HashSet() : this((IEqualityComparer<T>?)null) { }

public HashSet(IEqualityComparer<T>? comparer)
{
// For reference types, we always want to store a comparer instance, either
// the one provided, or if one wasn't provided, the default (accessing
// EqualityComparer<TKey>.Default with shared generics on every dictionary
// access can add measurable overhead). For value types, if no comparer is
// provided, or if the default is provided, we'd prefer to use
// EqualityComparer<TKey>.Default.Equals on every use, enabling the JIT to
// devirtualize and possibly inline the operation.
if (!typeof(T).IsValueType)
{
_comparer = comparer ?? EqualityComparer<T>.Default;

// Special-case EqualityComparer<string>.Default, StringComparer.Ordinal, and StringComparer.OrdinalIgnoreCase.
// We use a non-randomized comparer for improved perf, falling back to a randomized comparer if the
// hash buckets become unbalanced.
if (typeof(T) == typeof(string) &&
NonRandomizedStringEqualityComparer.GetStringComparer(_comparer!) is IEqualityComparer<string> stringComparer)
{
_comparer = (IEqualityComparer<T>)stringComparer;
}
}
else if (comparer is not null && // first check for null to avoid forcing default comparer instantiation unnecessarily
comparer != EqualityComparer<T>.Default)
{
_comparer = comparer;
}
}

public HashSet(int capacity) : this(capacity, null) { }

public HashSet(IEnumerable<T> collection) : this(collection, null) { }

public HashSet(IEnumerable<T> collection, IEqualityComparer<T>? comparer) : this(comparer)
{
if (collection == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.collection);
}

if (collection is HashSet<T> otherAsHashSet && EqualityComparersAreEqual(this, otherAsHashSet))
{
ConstructFrom(otherAsHashSet);
}
else
{
// To avoid excess resizes, first set size based on collection's count. The collection may
// contain duplicates, so call TrimExcess if resulting HashSet is larger than the threshold.
if (collection is ICollection<T> coll)
{
int count = coll.Count;
if (count > 0)
{
Initialize(count);
}
}

UnionWith(collection);

if (_count > 0 && _entries!.Length / _count > ShrinkThreshold)
{
TrimExcess();
}
}
}

public HashSet(int capacity, IEqualityComparer<T>? comparer) : this(comparer)
{
if (capacity < 0)
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.capacity);
}

if (capacity > 0)
{
Initialize(capacity);
}
}

/// <summary>Initializes the HashSet from another HashSet with the same element type and equality comparer.</summary>
private void ConstructFrom(HashSet<T> source)
{
if (source.Count == 0)
{
// As well as short-circuiting on the rest of the work done,
// this avoids errors from trying to access source._buckets
// or source._entries when they aren't initialized.
return;
}

int capacity = source._buckets!.Length;
int threshold = HashHelpers.ExpandPrime(source.Count + 1);

if (threshold >= capacity)
{
_buckets = (int[])source._buckets.Clone();
_entries = (Entry[])source._entries!.Clone();
_freeList = source._freeList;
_freeCount = source._freeCount;
_count = source._count;
#if TARGET_64BIT
_fastModMultiplier = source._fastModMultiplier;
#endif
}
else
{
Initialize(source.Count);

Entry[]? entries = source._entries;
for (int i = 0; i < source._count; i++)
{
ref Entry entry = ref entries![i];
if (entry.Next >= -1)
{
AddIfNotPresent(entry.Value, out _);
}
}
}

Debug.Assert(Count == source.Count);
}

#endregion

#region ICollection<T> methods

void ICollection<T>.Add(T item) => AddIfNotPresent(item, out _);

/// <summary>Removes all elements from the <see cref="HashSet{T}"/> object.</summary>
public void Clear()
{
int count = _count;
if (count > 0)
{
Debug.Assert(_buckets != null, "_buckets should be non-null");
Debug.Assert(_entries != null, "_entries should be non-null");

Array.Clear(_buckets);
_count = 0;
_freeList = -1;
_freeCount = 0;
Array.Clear(_entries, 0, count);
}
}

/// <summary>Determines whether the <see cref="HashSet{T}"/> contains the specified element.</summary>
/// <param name="item">The element to locate in the <see cref="HashSet{T}"/> object.</param>
/// <returns>true if the <see cref="HashSet{T}"/> object contains the specified element; otherwise, false.</returns>
public bool Contains(T item) => FindItemIndex(item) >= 0;

/// <summary>Gets the index of the item in <see cref="_entries"/>, or -1 if it's not in the set.</summary>
private int FindItemIndex(T item)
{
int[]? buckets = _buckets;
if (buckets != null)
{
Entry[]? entries = _entries;
Debug.Assert(entries != null, "Expected _entries to be initialized");

uint collisionCount = 0;
IEqualityComparer<T>? comparer = _comparer;

if (typeof(T).IsValueType && // comparer can only be null for value types; enable JIT to eliminate entire if block for ref types
comparer == null)
{
// ValueType: Devirtualize with EqualityComparer<TValue>.Default intrinsic
int hashCode = item!.GetHashCode();
int i = GetBucketRef(hashCode) - 1; // Value in _buckets is 1-based
while (i >= 0)
{
ref Entry entry = ref entries[i];
if (entry.HashCode == hashCode && EqualityComparer<T>.Default.Equals(entry.Value, item))
{
return i;
}
i = entry.Next;

collisionCount++;
if (collisionCount > (uint)entries.Length)
{
// The chain of entries forms a loop, which means a concurrent update has happened.
ThrowHelper.ThrowInvalidOperationException_ConcurrentOperationsNotSupported();
}
}
}
else
{
Debug.Assert(comparer is not null);
int hashCode = item != null ? comparer.GetHashCode(item) : 0;
int i = GetBucketRef(hashCode) - 1; // Value in _buckets is 1-based
while (i >= 0)
{
ref Entry entry = ref entries[i];
if (entry.HashCode == hashCode && comparer.Equals(entry.Value, item))
{
return i;
}
i = entry.Next;

collisionCount++;
if (collisionCount > (uint)entries.Length)
{
// The chain of entries forms a loop, which means a concurrent update has happened.
ThrowHelper.ThrowInvalidOperationException_ConcurrentOperationsNotSupported();
}
}
}
}

return -1;
}

// 生成hashcode对应的bucket值,64bit平台仅加速%运算
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private ref int GetBucketRef(int hashCode)
{
int[] buckets = _buckets!;
#if TARGET_64BIT
return ref buckets[HashHelpers.FastMod((uint)hashCode, (uint)buckets.Length, _fastModMultiplier)];
#else
return ref buckets[(uint)hashCode % (uint)buckets.Length];
#endif
}

// 移除元素
public bool Remove(T item)
{
if (_buckets != null)
{
Entry[]? entries = _entries;
Debug.Assert(entries != null, "entries should be non-null");

uint collisionCount = 0;
int last = -1;

IEqualityComparer<T>? comparer = _comparer;
Debug.Assert(typeof(T).IsValueType || comparer is not null);
int hashCode =
typeof(T).IsValueType && comparer == null ? item!.GetHashCode() :
item is not null ? comparer!.GetHashCode(item) :
0;

ref int bucket = ref GetBucketRef(hashCode);
int i = bucket - 1; // Value in buckets is 1-based

while (i >= 0)
{
ref Entry entry = ref entries[i];

if (entry.HashCode == hashCode && (comparer?.Equals(entry.Value, item) ?? EqualityComparer<T>.Default.Equals(entry.Value, item)))
{
if (last < 0)
{
bucket = entry.Next + 1; // Value in buckets is 1-based
}
else
{
entries[last].Next = entry.Next;
}

Debug.Assert((StartOfFreeList - _freeList) < 0, "shouldn't underflow because max hashtable length is MaxPrimeArrayLength = 0x7FEFFFFD(2146435069) _freelist underflow threshold 2147483646");
entry.Next = StartOfFreeList - _freeList;

if (RuntimeHelpers.IsReferenceOrContainsReferences<T>())
{
entry.Value = default!;
}

_freeList = i;
_freeCount++;
return true;
}

last = i;
i = entry.Next;

collisionCount++;
if (collisionCount > (uint)entries.Length)
{
// The chain of entries forms a loop; which means a concurrent update has happened.
// Break out of the loop and throw, rather than looping forever.
ThrowHelper.ThrowInvalidOperationException_ConcurrentOperationsNotSupported();
}
}
}

return false;
}

// 元素数量
public int Count => _count - _freeCount;

bool ICollection<T>.IsReadOnly => false;

#endregion

#region IEnumerable methods

public Enumerator GetEnumerator() => new Enumerator(this);

IEnumerator<T> IEnumerable<T>.GetEnumerator() =>
Count == 0 ? SZGenericArrayEnumerator<T>.Empty :
GetEnumerator();

IEnumerator IEnumerable.GetEnumerator() => ((IEnumerable<T>)this).GetEnumerator();

#endregion

#region HashSet methods

// 添加元素,返回true表示添加成功,false表示已存在
public bool Add(T item) => AddIfNotPresent(item, out _);

// 搜索指定值是否存在
public bool TryGetValue(T equalValue, [MaybeNullWhen(false)] out T actualValue)
{
if (_buckets != null)
{
int index = FindItemIndex(equalValue);
if (index >= 0)
{
actualValue = _entries![index].Value;
return true;
}
}

actualValue = default;
return false;
}

// 并集
public void UnionWith(IEnumerable<T> other)
{
if (other == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.other);
}

foreach (T item in other)
{
AddIfNotPresent(item, out _);
}
}

// 交集
public void IntersectWith(IEnumerable<T> other)
{
if (other == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.other);
}

// Intersection of anything with empty set is empty set, so return if count is 0.
// Same if the set intersecting with itself is the same set.
if (Count == 0 || other == this)
{
return;
}

// If other is known to be empty, intersection is empty set; remove all elements, and we're done.
if (other is ICollection<T> otherAsCollection)
{
if (otherAsCollection.Count == 0)
{
Clear();
return;
}

// Faster if other is a hashset using same equality comparer; so check
// that other is a hashset using the same equality comparer.
if (other is HashSet<T> otherAsSet && EqualityComparersAreEqual(this, otherAsSet))
{
IntersectWithHashSetWithSameComparer(otherAsSet);
return;
}
}

IntersectWithEnumerable(other);
}

// 差集:this-other
public void ExceptWith(IEnumerable<T> other)
{
if (other == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.other);
}

// This is already the empty set; return.
if (Count == 0)
{
return;
}

// Special case if other is this; a set minus itself is the empty set.
if (other == this)
{
Clear();
return;
}

// Remove every element in other from this.
foreach (T element in other)
{
Remove(element);
}
}

/// <summary>Modifies the current <see cref="HashSet{T}"/> object to contain only elements that are present either in that object or in the specified collection, but not both.</summary>
/// <param name="other">The collection to compare to the current <see cref="HashSet{T}"/> object.</param>
public void SymmetricExceptWith(IEnumerable<T> other)
{
if (other == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.other);
}

// If set is empty, then symmetric difference is other.
if (Count == 0)
{
UnionWith(other);
return;
}

// Special-case this; the symmetric difference of a set with itself is the empty set.
if (other == this)
{
Clear();
return;
}

// If other is a HashSet, it has unique elements according to its equality comparer,
// but if they're using different equality comparers, then assumption of uniqueness
// will fail. So first check if other is a hashset using the same equality comparer;
// symmetric except is a lot faster and avoids bit array allocations if we can assume
// uniqueness.
if (other is HashSet<T> otherAsSet && EqualityComparersAreEqual(this, otherAsSet))
{
SymmetricExceptWithUniqueHashSet(otherAsSet);
}
else
{
SymmetricExceptWithEnumerable(other);
}
}

// 是否是子集
public bool IsSubsetOf(IEnumerable<T> other)
{
if (other == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.other);
}

if (Count == 0 || other == this)
{
return true;
}

// Faster if other has unique elements according to this equality comparer; so check
// that other is a hashset using the same equality comparer.
if (other is HashSet<T> otherAsSet && EqualityComparersAreEqual(this, otherAsSet))
{
// if this has more elements then it can't be a subset
if (Count > otherAsSet.Count)
{
return false;
}

// already checked that we're using same equality comparer. simply check that
// each element in this is contained in other.
return IsSubsetOfHashSetWithSameComparer(otherAsSet);
}

(int uniqueCount, int unfoundCount) = CheckUniqueAndUnfoundElements(other, returnIfUnfound: false);
return uniqueCount == Count && unfoundCount >= 0;
}

/// <summary>Determines whether a <see cref="HashSet{T}"/> object is a proper subset of the specified collection.</summary>
/// <param name="other">The collection to compare to the current <see cref="HashSet{T}"/> object.</param>
/// <returns>true if the <see cref="HashSet{T}"/> object is a proper subset of <paramref name="other"/>; otherwise, false.</returns>
public bool IsProperSubsetOf(IEnumerable<T> other)
{
if (other == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.other);
}

// No set is a proper subset of itself.
if (other == this)
{
return false;
}

if (other is ICollection<T> otherAsCollection)
{
// No set is a proper subset of an empty set.
if (otherAsCollection.Count == 0)
{
return false;
}

// The empty set is a proper subset of anything but the empty set.
if (Count == 0)
{
return otherAsCollection.Count > 0;
}

// Faster if other is a hashset (and we're using same equality comparer).
if (other is HashSet<T> otherAsSet && EqualityComparersAreEqual(this, otherAsSet))
{
if (Count >= otherAsSet.Count)
{
return false;
}

// This has strictly less than number of items in other, so the following
// check suffices for proper subset.
return IsSubsetOfHashSetWithSameComparer(otherAsSet);
}
}

(int uniqueCount, int unfoundCount) = CheckUniqueAndUnfoundElements(other, returnIfUnfound: false);
return uniqueCount == Count && unfoundCount > 0;
}

/// <summary>Determines whether a <see cref="HashSet{T}"/> object is a proper superset of the specified collection.</summary>
/// <param name="other">The collection to compare to the current <see cref="HashSet{T}"/> object.</param>
/// <returns>true if the <see cref="HashSet{T}"/> object is a superset of <paramref name="other"/>; otherwise, false.</returns>
public bool IsSupersetOf(IEnumerable<T> other)
{
if (other == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.other);
}

// A set is always a superset of itself.
if (other == this)
{
return true;
}

// Try to fall out early based on counts.
if (other is ICollection<T> otherAsCollection)
{
// If other is the empty set then this is a superset.
if (otherAsCollection.Count == 0)
{
return true;
}

// Try to compare based on counts alone if other is a hashset with same equality comparer.
if (other is HashSet<T> otherAsSet &&
EqualityComparersAreEqual(this, otherAsSet) &&
otherAsSet.Count > Count)
{
return false;
}
}

foreach (T element in other)
{
if (!Contains(element))
{
return false;
}
}

return true;
}

/// <summary>Determines whether a <see cref="HashSet{T}"/> object is a proper superset of the specified collection.</summary>
/// <param name="other">The collection to compare to the current <see cref="HashSet{T}"/> object.</param>
/// <returns>true if the <see cref="HashSet{T}"/> object is a proper superset of <paramref name="other"/>; otherwise, false.</returns>
public bool IsProperSupersetOf(IEnumerable<T> other)
{
if (other == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.other);
}

// The empty set isn't a proper superset of any set, and a set is never a strict superset of itself.
if (Count == 0 || other == this)
{
return false;
}

if (other is ICollection<T> otherAsCollection)
{
// If other is the empty set then this is a superset.
if (otherAsCollection.Count == 0)
{
// Note that this has at least one element, based on above check.
return true;
}

// Faster if other is a hashset with the same equality comparer
if (other is HashSet<T> otherAsSet && EqualityComparersAreEqual(this, otherAsSet))
{
if (otherAsSet.Count >= Count)
{
return false;
}

// Now perform element check.
return otherAsSet.IsSubsetOfHashSetWithSameComparer(this);
}
}

// Couldn't fall out in the above cases; do it the long way
(int uniqueCount, int unfoundCount) = CheckUniqueAndUnfoundElements(other, returnIfUnfound: true);
return uniqueCount < Count && unfoundCount == 0;
}

/// <summary>Determines whether the current <see cref="HashSet{T}"/> object and a specified collection share common elements.</summary>
/// <param name="other">The collection to compare to the current <see cref="HashSet{T}"/> object.</param>
/// <returns>true if the <see cref="HashSet{T}"/> object and <paramref name="other"/> share at least one common element; otherwise, false.</returns>
public bool Overlaps(IEnumerable<T> other)
{
if (other == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.other);
}

if (Count == 0)
{
return false;
}

// Set overlaps itself
if (other == this)
{
return true;
}

foreach (T element in other)
{
if (Contains(element))
{
return true;
}
}

return false;
}

/// <summary>Determines whether a <see cref="HashSet{T}"/> object and the specified collection contain the same elements.</summary>
/// <param name="other">The collection to compare to the current <see cref="HashSet{T}"/> object.</param>
/// <returns>true if the <see cref="HashSet{T}"/> object is equal to <paramref name="other"/>; otherwise, false.</returns>
public bool SetEquals(IEnumerable<T> other)
{
if (other == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.other);
}

// A set is equal to itself.
if (other == this)
{
return true;
}

// Faster if other is a hashset and we're using same equality comparer.
if (other is HashSet<T> otherAsSet && EqualityComparersAreEqual(this, otherAsSet))
{
// Attempt to return early: since both contain unique elements, if they have
// different counts, then they can't be equal.
if (Count != otherAsSet.Count)
{
return false;
}

// Already confirmed that the sets have the same number of distinct elements, so if
// one is a subset of the other then they must be equal.
return IsSubsetOfHashSetWithSameComparer(otherAsSet);
}
else
{
// If this count is 0 but other contains at least one element, they can't be equal.
if (Count == 0 &&
other is ICollection<T> otherAsCollection &&
otherAsCollection.Count > 0)
{
return false;
}

(int uniqueCount, int unfoundCount) = CheckUniqueAndUnfoundElements(other, returnIfUnfound: true);
return uniqueCount == Count && unfoundCount == 0;
}
}

public void CopyTo(T[] array) => CopyTo(array, 0, Count);

/// <summary>Copies the elements of a <see cref="HashSet{T}"/> object to an array, starting at the specified array index.</summary>
/// <param name="array">The destination array.</param>
/// <param name="arrayIndex">The zero-based index in array at which copying begins.</param>
public void CopyTo(T[] array, int arrayIndex) => CopyTo(array, arrayIndex, Count);

public void CopyTo(T[] array, int arrayIndex, int count)
{
if (array == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}

ArgumentOutOfRangeException.ThrowIfNegative(arrayIndex);
ArgumentOutOfRangeException.ThrowIfNegative(count);

// Will the array, starting at arrayIndex, be able to hold elements? Note: not
// checking arrayIndex >= array.Length (consistency with list of allowing
// count of 0; subsequent check takes care of the rest)
if (arrayIndex > array.Length || count > array.Length - arrayIndex)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
}

Entry[]? entries = _entries;
for (int i = 0; i < _count && count != 0; i++)
{
ref Entry entry = ref entries![i];
if (entry.Next >= -1)
{
array[arrayIndex++] = entry.Value;
count--;
}
}
}

/// <summary>Removes all elements that match the conditions defined by the specified predicate from a <see cref="HashSet{T}"/> collection.</summary>
public int RemoveWhere(Predicate<T> match)
{
if (match == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
}

Entry[]? entries = _entries;
int numRemoved = 0;
for (int i = 0; i < _count; i++)
{
ref Entry entry = ref entries![i];
if (entry.Next >= -1)
{
// Cache value in case delegate removes it
T value = entry.Value;
if (match(value))
{
// Check again that remove actually removed it.
if (Remove(value))
{
numRemoved++;
}
}
}
}

return numRemoved;
}

/// <summary>Gets the <see cref="IEqualityComparer"/> object that is used to determine equality for the values in the set.</summary>
public IEqualityComparer<T> Comparer
{
get
{
if (typeof(T) == typeof(string))
{
Debug.Assert(_comparer is not null, "The comparer should never be null for a reference type.");
return (IEqualityComparer<T>)IInternalStringEqualityComparer.GetUnderlyingEqualityComparer((IEqualityComparer<string?>)_comparer);
}
else
{
return _comparer ?? EqualityComparer<T>.Default;
}
}
}

/// <summary>Ensures that this hash set can hold the specified number of elements without growing.</summary>
public int EnsureCapacity(int capacity)
{
if (capacity < 0)
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.capacity);
}

int currentCapacity = _entries == null ? 0 : _entries.Length;
if (currentCapacity >= capacity)
{
return currentCapacity;
}

if (_buckets == null)
{
return Initialize(capacity);
}

int newSize = HashHelpers.GetPrime(capacity);
Resize(newSize, forceNewHashCodes: false);
return newSize;
}

private void Resize() => Resize(HashHelpers.ExpandPrime(_count), forceNewHashCodes: false);

private void Resize(int newSize, bool forceNewHashCodes)
{
// Value types never rehash
Debug.Assert(!forceNewHashCodes || !typeof(T).IsValueType);
Debug.Assert(_entries != null, "_entries should be non-null");
Debug.Assert(newSize >= _entries.Length);

var entries = new Entry[newSize];

int count = _count;
Array.Copy(_entries, entries, count);

if (!typeof(T).IsValueType && forceNewHashCodes)
{
Debug.Assert(_comparer is NonRandomizedStringEqualityComparer);
IEqualityComparer<T> comparer = _comparer = (IEqualityComparer<T>)((NonRandomizedStringEqualityComparer)_comparer).GetRandomizedEqualityComparer();

for (int i = 0; i < count; i++)
{
ref Entry entry = ref entries[i];
if (entry.Next >= -1)
{
entry.HashCode = entry.Value != null ? comparer.GetHashCode(entry.Value) : 0;
}
}
}

// Assign member variables after both arrays allocated to guard against corruption from OOM if second fails
_buckets = new int[newSize];
#if TARGET_64BIT
_fastModMultiplier = HashHelpers.GetFastModMultiplier((uint)newSize);
#endif
for (int i = 0; i < count; i++)
{
ref Entry entry = ref entries[i];
if (entry.Next >= -1)
{
ref int bucket = ref GetBucketRef(entry.HashCode);
entry.Next = bucket - 1; // Value in _buckets is 1-based
bucket = i + 1;
}
}

_entries = entries;
}

/// <summary>
/// Sets the capacity of a <see cref="HashSet{T}"/> object to the actual number of elements it contains,
/// rounded up to a nearby, implementation-specific value.
/// </summary>
public void TrimExcess()
{
int capacity = Count;

int newSize = HashHelpers.GetPrime(capacity);
Entry[]? oldEntries = _entries;
int currentCapacity = oldEntries == null ? 0 : oldEntries.Length;
if (newSize >= currentCapacity)
{
return;
}

int oldCount = _count;
_version++;
Initialize(newSize);
Entry[]? entries = _entries;
int count = 0;
for (int i = 0; i < oldCount; i++)
{
int hashCode = oldEntries![i].HashCode; // At this point, we know we have entries.
if (oldEntries[i].Next >= -1)
{
ref Entry entry = ref entries![count];
entry = oldEntries[i];
ref int bucket = ref GetBucketRef(hashCode);
entry.Next = bucket - 1; // Value in _buckets is 1-based
bucket = count + 1;
count++;
}
}

_count = capacity;
_freeCount = 0;
}

#endregion

#region Helper methods

/// <summary>Returns an <see cref="IEqualityComparer"/> object that can be used for equality testing of a <see cref="HashSet{T}"/> object.</summary>
public static IEqualityComparer<HashSet<T>> CreateSetComparer() => new HashSetEqualityComparer<T>();

// 初始化指定容量,返回实际容量(向上取质数)
private int Initialize(int capacity)
{
int size = HashHelpers.GetPrime(capacity);
var buckets = new int[size];
var entries = new Entry[size];

_freeList = -1;
_buckets = buckets;
_entries = entries;
#if TARGET_64BIT
_fastModMultiplier = HashHelpers.GetFastModMultiplier((uint)size);
#endif
return size;
}

// set不包含元素则添加,返回是否添加成功
private bool AddIfNotPresent(T value, out int location)
{
if (_buckets == null)
{
Initialize(0);
}
Debug.Assert(_buckets != null);

Entry[]? entries = _entries;
Debug.Assert(entries != null, "expected entries to be non-null");

IEqualityComparer<T>? comparer = _comparer;
int hashCode;

uint collisionCount = 0;
ref int bucket = ref Unsafe.NullRef<int>();

if (typeof(T).IsValueType && // comparer can only be null for value types; enable JIT to eliminate entire if block for ref types
comparer == null)
{
hashCode = value!.GetHashCode();
bucket = ref GetBucketRef(hashCode);
int i = bucket - 1; // Value in _buckets is 1-based

// ValueType: Devirtualize with EqualityComparer<TValue>.Default intrinsic
while (i >= 0)
{
ref Entry entry = ref entries[i];
if (entry.HashCode == hashCode && EqualityComparer<T>.Default.Equals(entry.Value, value))
{
location = i;
return false;
}
i = entry.Next;

collisionCount++;
if (collisionCount > (uint)entries.Length)
{
// The chain of entries forms a loop, which means a concurrent update has happened.
ThrowHelper.ThrowInvalidOperationException_ConcurrentOperationsNotSupported();
}
}
}
else
{
Debug.Assert(comparer is not null);
hashCode = value != null ? comparer.GetHashCode(value) : 0;
bucket = ref GetBucketRef(hashCode);
int i = bucket - 1; // Value in _buckets is 1-based
while (i >= 0)
{
ref Entry entry = ref entries[i];
if (entry.HashCode == hashCode && comparer.Equals(entry.Value, value))
{
location = i;
return false;
}
i = entry.Next;

collisionCount++;
if (collisionCount > (uint)entries.Length)
{
// The chain of entries forms a loop, which means a concurrent update has happened.
ThrowHelper.ThrowInvalidOperationException_ConcurrentOperationsNotSupported();
}
}
}

int index;
if (_freeCount > 0)
{
index = _freeList;
_freeCount--;
Debug.Assert((StartOfFreeList - entries![_freeList].Next) >= -1, "shouldn't overflow because `next` cannot underflow");
_freeList = StartOfFreeList - entries[_freeList].Next;
}
else
{
int count = _count;
if (count == entries.Length)
{
Resize();
bucket = ref GetBucketRef(hashCode);
}
index = count;
_count = count + 1;
entries = _entries;
}

{
ref Entry entry = ref entries![index];
entry.HashCode = hashCode;
entry.Next = bucket - 1; // Value in _buckets is 1-based
entry.Value = value;
bucket = index + 1;
_version++;
location = index;
}

// Value types never rehash
if (!typeof(T).IsValueType && collisionCount > HashHelpers.HashCollisionThreshold && comparer is NonRandomizedStringEqualityComparer)
{
// If we hit the collision threshold we'll need to switch to the comparer which is using randomized string hashing
// i.e. EqualityComparer<string>.Default.
Resize(entries.Length, forceNewHashCodes: true);
location = FindItemIndex(value);
Debug.Assert(location >= 0);
}

return true;
}

/// <summary>
/// Implementation Notes:
/// If other is a hashset and is using same equality comparer, then checking subset is
/// faster. Simply check that each element in this is in other.
///
/// Note: if other doesn't use same equality comparer, then Contains check is invalid,
/// which is why callers must take are of this.
///
/// If callers are concerned about whether this is a proper subset, they take care of that.
/// </summary>
internal bool IsSubsetOfHashSetWithSameComparer(HashSet<T> other)
{
foreach (T item in this)
{
if (!other.Contains(item))
{
return false;
}
}

return true;
}

/// <summary>
/// If other is a hashset that uses same equality comparer, intersect is much faster
/// because we can use other's Contains
/// </summary>
private void IntersectWithHashSetWithSameComparer(HashSet<T> other)
{
Entry[]? entries = _entries;
for (int i = 0; i < _count; i++)
{
ref Entry entry = ref entries![i];
if (entry.Next >= -1)
{
T item = entry.Value;
if (!other.Contains(item))
{
Remove(item);
}
}
}
}

/// <summary>
/// Iterate over other. If contained in this, mark an element in bit array corresponding to
/// its position in _slots. If anything is unmarked (in bit array), remove it.
///
/// This attempts to allocate on the stack, if below StackAllocThreshold.
/// </summary>
private unsafe void IntersectWithEnumerable(IEnumerable<T> other)
{
Debug.Assert(_buckets != null, "_buckets shouldn't be null; callers should check first");

// Keep track of current last index; don't want to move past the end of our bit array
// (could happen if another thread is modifying the collection).
int originalCount = _count;
int intArrayLength = BitHelper.ToIntArrayLength(originalCount);

Span<int> span = stackalloc int[StackAllocThreshold];
BitHelper bitHelper = intArrayLength <= StackAllocThreshold ?
new BitHelper(span.Slice(0, intArrayLength), clear: true) :
new BitHelper(new int[intArrayLength], clear: false);

// Mark if contains: find index of in slots array and mark corresponding element in bit array.
foreach (T item in other)
{
int index = FindItemIndex(item);
if (index >= 0)
{
bitHelper.MarkBit(index);
}
}

// If anything unmarked, remove it. Perf can be optimized here if BitHelper had a
// FindFirstUnmarked method.
for (int i = 0; i < originalCount; i++)
{
ref Entry entry = ref _entries![i];
if (entry.Next >= -1 && !bitHelper.IsMarked(i))
{
Remove(entry.Value);
}
}
}

/// <summary>
/// if other is a set, we can assume it doesn't have duplicate elements, so use this
/// technique: if can't remove, then it wasn't present in this set, so add.
///
/// As with other methods, callers take care of ensuring that other is a hashset using the
/// same equality comparer.
/// </summary>
/// <param name="other"></param>
private void SymmetricExceptWithUniqueHashSet(HashSet<T> other)
{
foreach (T item in other)
{
if (!Remove(item))
{
AddIfNotPresent(item, out _);
}
}
}

/// <summary>
/// Implementation notes:
///
/// Used for symmetric except when other isn't a HashSet. This is more tedious because
/// other may contain duplicates. HashSet technique could fail in these situations:
/// 1. Other has a duplicate that's not in this: HashSet technique would add then
/// remove it.
/// 2. Other has a duplicate that's in this: HashSet technique would remove then add it
/// back.
/// In general, its presence would be toggled each time it appears in other.
///
/// This technique uses bit marking to indicate whether to add/remove the item. If already
/// present in collection, it will get marked for deletion. If added from other, it will
/// get marked as something not to remove.
///
/// </summary>
/// <param name="other"></param>
private unsafe void SymmetricExceptWithEnumerable(IEnumerable<T> other)
{
int originalCount = _count;
int intArrayLength = BitHelper.ToIntArrayLength(originalCount);

Span<int> itemsToRemoveSpan = stackalloc int[StackAllocThreshold / 2];
BitHelper itemsToRemove = intArrayLength <= StackAllocThreshold / 2 ?
new BitHelper(itemsToRemoveSpan.Slice(0, intArrayLength), clear: true) :
new BitHelper(new int[intArrayLength], clear: false);

Span<int> itemsAddedFromOtherSpan = stackalloc int[StackAllocThreshold / 2];
BitHelper itemsAddedFromOther = intArrayLength <= StackAllocThreshold / 2 ?
new BitHelper(itemsAddedFromOtherSpan.Slice(0, intArrayLength), clear: true) :
new BitHelper(new int[intArrayLength], clear: false);

foreach (T item in other)
{
int location;
if (AddIfNotPresent(item, out location))
{
// wasn't already present in collection; flag it as something not to remove
// *NOTE* if location is out of range, we should ignore. BitHelper will
// detect that it's out of bounds and not try to mark it. But it's
// expected that location could be out of bounds because adding the item
// will increase _lastIndex as soon as all the free spots are filled.
itemsAddedFromOther.MarkBit(location);
}
else
{
// already there...if not added from other, mark for remove.
// *NOTE* Even though BitHelper will check that location is in range, we want
// to check here. There's no point in checking items beyond originalCount
// because they could not have been in the original collection
if (location < originalCount && !itemsAddedFromOther.IsMarked(location))
{
itemsToRemove.MarkBit(location);
}
}
}

// if anything marked, remove it
for (int i = 0; i < originalCount; i++)
{
if (itemsToRemove.IsMarked(i))
{
Remove(_entries![i].Value);
}
}
}

/// <summary>
/// Determines counts that can be used to determine equality, subset, and superset. This
/// is only used when other is an IEnumerable and not a HashSet. If other is a HashSet
/// these properties can be checked faster without use of marking because we can assume
/// other has no duplicates.
///
/// The following count checks are performed by callers:
/// 1. Equals: checks if unfoundCount = 0 and uniqueFoundCount = _count; i.e. everything
/// in other is in this and everything in this is in other
/// 2. Subset: checks if unfoundCount >= 0 and uniqueFoundCount = _count; i.e. other may
/// have elements not in this and everything in this is in other
/// 3. Proper subset: checks if unfoundCount > 0 and uniqueFoundCount = _count; i.e
/// other must have at least one element not in this and everything in this is in other
/// 4. Proper superset: checks if unfound count = 0 and uniqueFoundCount strictly less
/// than _count; i.e. everything in other was in this and this had at least one element
/// not contained in other.
///
/// An earlier implementation used delegates to perform these checks rather than returning
/// an ElementCount struct; however this was changed due to the perf overhead of delegates.
/// </summary>
/// <param name="other"></param>
/// <param name="returnIfUnfound">Allows us to finish faster for equals and proper superset
/// because unfoundCount must be 0.</param>
private (int UniqueCount, int UnfoundCount) CheckUniqueAndUnfoundElements(IEnumerable<T> other, bool returnIfUnfound)
{
// Need special case in case this has no elements.
if (_count == 0)
{
int numElementsInOther = 0;
foreach (T item in other)
{
numElementsInOther++;
break; // break right away, all we want to know is whether other has 0 or 1 elements
}

return (UniqueCount: 0, UnfoundCount: numElementsInOther);
}

Debug.Assert((_buckets != null) && (_count > 0), "_buckets was null but count greater than 0");

int originalCount = _count;
int intArrayLength = BitHelper.ToIntArrayLength(originalCount);

Span<int> span = stackalloc int[StackAllocThreshold];
BitHelper bitHelper = intArrayLength <= StackAllocThreshold ?
new BitHelper(span.Slice(0, intArrayLength), clear: true) :
new BitHelper(new int[intArrayLength], clear: false);

int unfoundCount = 0; // count of items in other not found in this
int uniqueFoundCount = 0; // count of unique items in other found in this

foreach (T item in other)
{
int index = FindItemIndex(item);
if (index >= 0)
{
if (!bitHelper.IsMarked(index))
{
// Item hasn't been seen yet.
bitHelper.MarkBit(index);
uniqueFoundCount++;
}
}
else
{
unfoundCount++;
if (returnIfUnfound)
{
break;
}
}
}

return (uniqueFoundCount, unfoundCount);
}

/// <summary>
/// Checks if equality comparers are equal. This is used for algorithms that can
/// speed up if it knows the other item has unique elements. I.e. if they're using
/// different equality comparers, then uniqueness assumption between sets break.
/// </summary>
internal static bool EqualityComparersAreEqual(HashSet<T> set1, HashSet<T> set2) => set1.Comparer.Equals(set2.Comparer);

#endregion

private struct Entry
{
public int HashCode;
/// <summary>
/// 0-based index of next entry in chain: -1 means end of chain
/// also encodes whether this entry _itself_ is part of the free list by changing sign and subtracting 3,
/// so -2 means end of free list, -3 means index 0 but on free list, -4 means index 1 but on free list, etc.
/// </summary>
public int Next;
public T Value;
}
}
}

枚举器

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
public struct Enumerator : IEnumerator<T>
{
private readonly HashSet<T> _hashSet;
private readonly int _version;
private int _index;
private T _current;

internal Enumerator(HashSet<T> hashSet)
{
_hashSet = hashSet;
_version = hashSet._version;
_index = 0;
_current = default!;
}

public bool MoveNext()
{
if (_version != _hashSet._version)
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion();
}

// Use unsigned comparison since we set index to dictionary.count+1 when the enumeration ends.
// dictionary.count+1 could be negative if dictionary.count is int.MaxValue
while ((uint)_index < (uint)_hashSet._count)
{
ref Entry entry = ref _hashSet._entries![_index++];
if (entry.Next >= -1)
{
_current = entry.Value;
return true;
}
}

_index = _hashSet._count + 1;
_current = default!;
return false;
}

public T Current => _current;

public void Dispose() { }

object? IEnumerator.Current
{
get
{
if (_index == 0 || (_index == _hashSet._count + 1))
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen();
}

return _current;
}
}

void IEnumerator.Reset()
{
if (_version != _hashSet._version)
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion();
}

_index = 0;
_current = default!;
}
}
上一篇:
核心基础
下一篇:
最佳实践