Repository navigation
Expand file tree
/
Copy pathHashSet.cs
More file actions
1866 lines (1611 loc) · 76.8 KB
/
Copy pathHashSet.cs
File metadata and controls
1866 lines (1611 loc) · 76.8 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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
namespace System.Collections.Generic
{
[DebuggerTypeProxy(typeof(ICollectionDebugView<>))]
[DebuggerDisplay("Count = {Count}")]
[Serializable]
[TypeForwardedFrom("System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public class HashSet<T> : ICollection<T>, ISet<T>, IReadOnlyCollection<T>, IReadOnlySet<T>, ISerializable, IDeserializationCallback
{
// This uses the same array-based implementation as Dictionary<TKey, TValue>.
// Constants for serialization
private const string CapacityName = "Capacity"; // Do not rename (binary serialization)
private const string ElementsName = "Elements"; // Do not rename (binary serialization)
private const string ComparerName = "Comparer"; // Do not rename (binary serialization)
private const string VersionName = "Version"; // Do not rename (binary serialization)
/// <summary>Cutoff point for stackallocs. This corresponds to the number of ints.</summary>
private const int StackAllocThreshold = 100;
/// <summary>
/// When constructing a hashset from an existing collection, it may contain duplicates,
/// so this is used as the max acceptable excess ratio of capacity to count. Note that
/// this is only used on the ctor and not to automatically shrink if the hashset has, e.g,
/// a lot of adds followed by removes. Users must explicitly shrink by calling TrimExcess.
/// This is set to 3 because capacity is acceptable as 2x rounded up to nearest prime.
/// </summary>
private const int ShrinkThreshold = 3;
private const int StartOfFreeList = -3;
private int[]? _buckets;
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 && EffectiveEqualityComparersAreEqual(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);
}
}
[Obsolete(Obsoletions.LegacyFormatterImplMessage, DiagnosticId = Obsoletions.LegacyFormatterImplDiagId, UrlFormat = Obsoletions.SharedUrlFormat)]
[EditorBrowsable(EditorBrowsableState.Never)]
protected HashSet(SerializationInfo info, StreamingContext context)
{
// We can't do anything with the keys and values until the entire graph has been
// deserialized and we have a reasonable estimate that GetHashCode is not going to
// fail. For the time being, we'll just cache this. The graph is not valid until
// OnDeserialization has been called.
HashHelpers.SerializationInfoTable.Add(this, info);
}
/// <summary>Initializes the HashSet from another HashSet with the same element type and equality comparer.</summary>
private void ConstructFrom(HashSet<T> source)
{
Debug.Assert(EffectiveEqualityComparersAreEqual(this, source), "must use identical effective comparers.");
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;
}
/// <summary>Gets a reference to the specified hashcode's bucket, containing an index into <see cref="_entries"/>.</summary>
[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;
}
/// <summary>Gets the number of elements that are contained in the set.</summary>
public int Count => _count - _freeCount;
/// <summary>
/// Gets the total numbers of elements the internal data structure can hold without resizing.
/// </summary>
public int Capacity => _entries?.Length ?? 0;
bool ICollection<T>.IsReadOnly => false;
#endregion
#region AlternateLookup
/// <summary>
/// Gets an instance of a type that may be used to perform operations on the current <see cref="HashSet{T}"/>
/// using a <typeparamref name="TAlternate"/> instead of a <typeparamref name="T"/>.
/// </summary>
/// <typeparam name="TAlternate">The alternate type of instance for performing lookups.</typeparam>
/// <returns>The created lookup instance.</returns>
/// <exception cref="InvalidOperationException">The set's comparer is not compatible with <typeparamref name="TAlternate"/>.</exception>
/// <remarks>
/// The set must be using a comparer that implements <see cref="IAlternateEqualityComparer{TAlternate, T}"/> with
/// <typeparamref name="TAlternate"/> and <typeparamref name="T"/>. If it doesn't, an exception will be thrown.
/// </remarks>
public AlternateLookup<TAlternate> GetAlternateLookup<TAlternate>()
where TAlternate : allows ref struct
{
if (!AlternateLookup<TAlternate>.IsCompatibleItem(this))
{
ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_IncompatibleComparer);
}
return new AlternateLookup<TAlternate>(this);
}
/// <summary>
/// Gets an instance of a type that may be used to perform operations on the current <see cref="HashSet{T}"/>
/// using a <typeparamref name="TAlternate"/> instead of a <typeparamref name="T"/>.
/// </summary>
/// <typeparam name="TAlternate">The alternate type of instance for performing lookups.</typeparam>
/// <param name="lookup">The created lookup instance when the method returns true, or a default instance that should not be used if the method returns false.</param>
/// <returns>true if a lookup could be created; otherwise, false.</returns>
/// <remarks>
/// The set must be using a comparer that implements <see cref="IAlternateEqualityComparer{TAlternate, T}"/> with
/// <typeparamref name="TAlternate"/> and <typeparamref name="T"/>. If it doesn't, the method returns false.
/// </remarks>
public bool TryGetAlternateLookup<TAlternate>(out AlternateLookup<TAlternate> lookup)
where TAlternate : allows ref struct
{
if (AlternateLookup<TAlternate>.IsCompatibleItem(this))
{
lookup = new AlternateLookup<TAlternate>(this);
return true;
}
lookup = default;
return false;
}
/// <summary>
/// Provides a type that may be used to perform operations on a <see cref="HashSet{T}"/>
/// using a <typeparamref name="TAlternate"/> instead of a <typeparamref name="T"/>.
/// </summary>
/// <typeparam name="TAlternate">The alternate type of instance for performing lookups.</typeparam>
public struct AlternateLookup<TAlternate> where TAlternate : allows ref struct
{
/// <summary>Initialize the instance. The set must have already been verified to have a compatible comparer.</summary>
internal AlternateLookup(HashSet<T> set)
{
Debug.Assert(set is not null);
Debug.Assert(IsCompatibleItem(set));
Set = set;
}
/// <summary>Gets the <see cref="HashSet{T}"/> against which this instance performs operations.</summary>
public HashSet<T> Set { get; }
/// <summary>Checks whether the set has a comparer compatible with <typeparamref name="TAlternate"/>.</summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static bool IsCompatibleItem(HashSet<T> set)
{
Debug.Assert(set is not null);
return set._comparer is IAlternateEqualityComparer<TAlternate, T>;
}
/// <summary>Gets the set's alternate comparer. The set must have already been verified as compatible.</summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static IAlternateEqualityComparer<TAlternate, T> GetAlternateComparer(HashSet<T> set)
{
Debug.Assert(IsCompatibleItem(set));
return Unsafe.As<IAlternateEqualityComparer<TAlternate, T>>(set._comparer);
}
/// <summary>Adds the specified element to a set.</summary>
/// <param name="item">The element to add to the set.</param>
/// <returns>true if the element is added to the set; false if the element is already present.</returns>
public bool Add(TAlternate item)
{
HashSet<T> set = Set;
IAlternateEqualityComparer<TAlternate, T> comparer = GetAlternateComparer(set);
if (set._buckets == null)
{
set.Initialize(0);
}
Debug.Assert(set._buckets != null);
Entry[]? entries = set._entries;
Debug.Assert(entries != null, "expected entries to be non-null");
int hashCode;
uint collisionCount = 0;
ref int bucket = ref Unsafe.NullRef<int>();
Debug.Assert(comparer is not null);
hashCode = comparer.GetHashCode(item);
bucket = ref set.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(item, entry.Value))
{
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();
}
}
// Invoke comparer.Map before allocating space in the collection in order to avoid corrupting
// the collection if the operation fails.
T mappedItem = comparer.Create(item);
int index;
if (set._freeCount > 0)
{
index = set._freeList;
set._freeCount--;
Debug.Assert((StartOfFreeList - entries![set._freeList].Next) >= -1, "shouldn't overflow because `next` cannot underflow");
set._freeList = StartOfFreeList - entries[set._freeList].Next;
}
else
{
int count = set._count;
if (count == entries.Length)
{
set.Resize();
bucket = ref set.GetBucketRef(hashCode);
}
index = count;
set._count = count + 1;
entries = set._entries;
}
{
ref Entry entry = ref entries![index];
entry.HashCode = hashCode;
entry.Next = bucket - 1; // Value in _buckets is 1-based
entry.Value = mappedItem;
bucket = index + 1;
set._version++;
}
// 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.
set.Resize(entries.Length, forceNewHashCodes: true);
}
return true;
}
/// <summary>Removes the specified element from a set.</summary>
/// <param name="item">The element to remove.</param>
/// <returns>true if the element is successfully found and removed; otherwise, false.</returns>
public bool Remove(TAlternate item)
{
HashSet<T> set = Set;
IAlternateEqualityComparer<TAlternate, T> comparer = GetAlternateComparer(set);
if (set._buckets != null)
{
Entry[]? entries = set._entries;
Debug.Assert(entries != null, "entries should be non-null");
uint collisionCount = 0;
int last = -1;
int hashCode = item is not null ? comparer!.GetHashCode(item) : 0;
ref int bucket = ref set.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(item, entry.Value))
{
if (last < 0)
{
bucket = entry.Next + 1; // Value in buckets is 1-based
}
else
{
entries[last].Next = entry.Next;
}
Debug.Assert((StartOfFreeList - set._freeList) < 0, "shouldn't underflow because max hashtable length is MaxPrimeArrayLength = 0x7FEFFFFD(2146435069) _freelist underflow threshold 2147483646");
entry.Next = StartOfFreeList - set._freeList;
if (RuntimeHelpers.IsReferenceOrContainsReferences<T>())
{
entry.Value = default!;
}
set._freeList = i;
set._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;
}
/// <summary>Determines whether a set contains the specified element.</summary>
/// <param name="item">The element to locate in the set.</param>
/// <returns>true if the set contains the specified element; otherwise, false.</returns>
public bool Contains(TAlternate item) => !Unsafe.IsNullRef(in FindValue(item));
/// <summary>Searches the set for a given value and returns the equal value it finds, if any.</summary>
/// <param name="equalValue">The value to search for.</param>
/// <param name="actualValue">The value from the set that the search found, or the default value of <typeparamref name="T"/> when the search yielded no match.</param>
/// <returns>A value indicating whether the search was successful.</returns>
public bool TryGetValue(TAlternate equalValue, [MaybeNullWhen(false)] out T actualValue)
{
ref readonly T value = ref FindValue(equalValue);
if (!Unsafe.IsNullRef(in value))
{
actualValue = value;
return true;
}
actualValue = default!;
return false;
}
/// <summary>Finds the item in the set and returns a reference to the found item, or a null reference if not found.</summary>
internal ref readonly T FindValue(TAlternate item)
{
HashSet<T> set = Set;
IAlternateEqualityComparer<TAlternate, T> comparer = GetAlternateComparer(set);
ref Entry entry = ref Unsafe.NullRef<Entry>();
if (set._buckets != null)
{
Debug.Assert(set._entries != null, "expected entries to be != null");
int hashCode = comparer.GetHashCode(item);
int i = set.GetBucketRef(hashCode);
Entry[]? entries = set._entries;
uint collisionCount = 0;
i--; // Value in _buckets is 1-based; subtract 1 from i. We do it here so it fuses with the following conditional.
do
{
// Should be a while loop https://github.com/dotnet/runtime/issues/9422
// Test in if to drop range check for following array access
if ((uint)i >= (uint)entries.Length)
{
goto ReturnNotFound;
}
entry = ref entries[i];
if (entry.HashCode == hashCode && comparer.Equals(item, entry.Value))
{
goto ReturnFound;
}
i = entry.Next;
collisionCount++;
} while (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.
goto ConcurrentOperation;
}
goto ReturnNotFound;
ConcurrentOperation:
ThrowHelper.ThrowInvalidOperationException_ConcurrentOperationsNotSupported();
ReturnFound:
ref readonly T value = ref entry.Value;
Return:
return ref value;
ReturnNotFound:
value = ref Unsafe.NullRef<T>();
goto Return;
}
}
#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 ISerializable methods
[Obsolete(Obsoletions.LegacyFormatterImplMessage, DiagnosticId = Obsoletions.LegacyFormatterImplDiagId, UrlFormat = Obsoletions.SharedUrlFormat)]
[EditorBrowsable(EditorBrowsableState.Never)]
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.info);
}
info.AddValue(VersionName, _version); // need to serialize version to avoid problems with serializing while enumerating
info.AddValue(ComparerName, Comparer, typeof(IEqualityComparer<T>));
info.AddValue(CapacityName, _buckets == null ? 0 : _buckets.Length);
if (_buckets != null)
{
var array = new T[Count];
CopyTo(array);
info.AddValue(ElementsName, array, typeof(T[]));
}
}
#endregion
#region IDeserializationCallback methods
public virtual void OnDeserialization(object? sender)
{
HashHelpers.SerializationInfoTable.TryGetValue(this, out SerializationInfo? siInfo);
if (siInfo == null)
{
// It might be necessary to call OnDeserialization from a container if the
// container object also implements OnDeserialization. We can return immediately
// if this function is called twice. Note we set _siInfo to null at the end of this method.
return;
}
int capacity = siInfo.GetInt32(CapacityName);
_comparer = (IEqualityComparer<T>)siInfo.GetValue(ComparerName, typeof(IEqualityComparer<T>))!;
_freeList = -1;
_freeCount = 0;
if (capacity != 0)
{
_buckets = new int[capacity];
_entries = new Entry[capacity];
#if TARGET_64BIT
_fastModMultiplier = HashHelpers.GetFastModMultiplier((uint)capacity);
#endif
T[]? array = (T[]?)siInfo.GetValue(ElementsName, typeof(T[]));
if (array == null)
{
ThrowHelper.ThrowSerializationException(ExceptionResource.Serialization_MissingKeys);
}
// There are no resizes here because we already set capacity above.
for (int i = 0; i < array.Length; i++)
{
AddIfNotPresent(array[i], out _);
}
}
else
{
_buckets = null;
}
_version = siInfo.GetInt32(VersionName);
HashHelpers.SerializationInfoTable.Remove(this);
}
#endregion
#region HashSet methods
/// <summary>Adds the specified element to the <see cref="HashSet{T}"/>.</summary>
/// <param name="item">The element to add to the set.</param>
/// <returns>true if the element is added to the <see cref="HashSet{T}"/> object; false if the element is already present.</returns>
public bool Add(T item) => AddIfNotPresent(item, out _);
/// <summary>Searches the set for a given value and returns the equal value it finds, if any.</summary>
/// <param name="equalValue">The value to search for.</param>
/// <param name="actualValue">The value from the set that the search found, or the default value of <typeparamref name="T"/> when the search yielded no match.</param>
/// <returns>A value indicating whether the search was successful.</returns>
/// <remarks>
/// This can be useful when you want to reuse a previously stored reference instead of
/// a newly constructed one (so that more sharing of references can occur) or to look up
/// a value that has more complete data than the value you currently have, although their
/// comparer functions indicate they are equal.
/// </remarks>
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;
}
/// <summary>Modifies the current <see cref="HashSet{T}"/> object to contain all elements that are present in itself, the specified collection, or both.</summary>
/// <param name="other">The collection to compare to the current <see cref="HashSet{T}"/> object.</param>
public void UnionWith(IEnumerable<T> other)
{
if (other == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.other);
}
foreach (T item in other)
{
AddIfNotPresent(item, out _);
}
}
/// <summary>Modifies the current <see cref="HashSet{T}"/> object to contain only elements that are present in that object and in the specified collection.</summary>
/// <param name="other">The collection to compare to the current <see cref="HashSet{T}"/> object.</param>
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);
}
/// <summary>Removes all elements in the specified collection from the current <see cref="HashSet{T}"/> object.</summary>
/// <param name="other">The collection to compare to the current <see cref="HashSet{T}"/> object.</param>
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);
}
}
/// <summary>Determines whether a <see cref="HashSet{T}"/> object is a 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 subset of <paramref name="other"/>; otherwise, false.</returns>
public bool IsSubsetOf(IEnumerable<T> other)
{
if (other == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.other);
}
// The empty set is a subset of any set, and a set is a subset of itself.
// Set is always a subset of itself.
if (Count == 0 || other == this)
{
return true;
}
if (other is ICollection<T> otherAsCollection)
{
// If this has more elements then it can't be a subset.
if (Count > otherAsCollection.Count)
{
return false;
}
// 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))
{
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 a set with less or equal number of elements.
if (otherAsCollection.Count <= Count)
{
return false;
}
// The empty set is a proper subset of anything but the empty set.
if (Count == 0)
{
// Based on check above, other is not empty when Count == 0.
return true;
}
// Faster if other is a hashset (and we're using same equality comparer).
if (other is HashSet<T> otherAsSet && EqualityComparersAreEqual(this, otherAsSet))
{
// 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>