/
SortedSet.cs
2018 lines (1702 loc) · 69 KB
/
SortedSet.cs
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.Numerics;
using System.Runtime.Serialization;
using Interlocked = System.Threading.Interlocked;
namespace System.Collections.Generic
{
// A binary search tree is a red-black tree if it satisfies the following red-black properties:
// 1. Every node is either red or black
// 2. Every leaf (nil node) is black
// 3. If a node is red, the both its children are black
// 4. Every simple path from a node to a descendant leaf contains the same number of black nodes
//
// The basic idea of a red-black tree is to represent 2-3-4 trees as standard BSTs but to add one extra bit of information
// per node to encode 3-nodes and 4-nodes.
// 4-nodes will be represented as: B
// R R
//
// 3 -node will be represented as: B or B
// R B B R
//
// For a detailed description of the algorithm, take a look at "Algorithms" by Robert Sedgewick.
internal enum NodeColor : byte
{
Black,
Red
}
internal delegate bool TreeWalkPredicate<T>(SortedSet<T>.Node node);
internal enum TreeRotation : byte
{
Left,
LeftRight,
Right,
RightLeft
}
[DebuggerTypeProxy(typeof(ICollectionDebugView<>))]
[DebuggerDisplay("Count = {Count}")]
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public partial class SortedSet<T> : ISet<T>, ICollection<T>, ICollection, IReadOnlyCollection<T>, IReadOnlySet<T>, ISerializable, IDeserializationCallback
{
#region Local variables/constants
private Node? root;
private IComparer<T> comparer = default!;
private int count;
private int version;
private SerializationInfo? siInfo; // A temporary variable which we need during deserialization.
private const string ComparerName = "Comparer"; // Do not rename (binary serialization)
private const string CountName = "Count"; // Do not rename (binary serialization)
private const string ItemsName = "Items"; // Do not rename (binary serialization)
private const string VersionName = "Version"; // Do not rename (binary serialization)
internal const int StackAllocThreshold = 100;
#endregion
#region Constructors
public SortedSet()
{
comparer = Comparer<T>.Default;
}
public SortedSet(IComparer<T>? comparer)
{
this.comparer = comparer ?? Comparer<T>.Default;
}
public SortedSet(IEnumerable<T> collection) : this(collection, Comparer<T>.Default) { }
public SortedSet(IEnumerable<T> collection, IComparer<T>? comparer)
: this(comparer)
{
ArgumentNullException.ThrowIfNull(collection);
// These are explicit type checks in the mold of HashSet. It would have worked better with
// something like an ISorted<T> interface. (We could make this work for SortedList.Keys, etc.)
SortedSet<T>? sortedSet = collection as SortedSet<T>;
if (sortedSet != null && !(sortedSet is TreeSubSet) && HasEqualComparer(sortedSet))
{
if (sortedSet.Count > 0)
{
Debug.Assert(sortedSet.root != null);
this.count = sortedSet.count;
root = sortedSet.root.DeepClone(this.count);
}
return;
}
int count;
T[] elements = EnumerableHelpers.ToArray(collection, out count);
if (count > 0)
{
// If `comparer` is null, sets it to Comparer<T>.Default. We checked for this condition in the IComparer<T> constructor.
// Array.Sort handles null comparers, but we need this later when we use `comparer.Compare` directly.
comparer = this.comparer;
Array.Sort(elements, 0, count, comparer);
// Overwrite duplicates while shifting the distinct elements towards
// the front of the array.
int index = 1;
for (int i = 1; i < count; i++)
{
if (comparer.Compare(elements[i], elements[i - 1]) != 0)
{
elements[index++] = elements[i];
}
}
count = index;
root = ConstructRootFromSortedArray(elements, 0, count - 1, null);
this.count = count;
}
}
[Obsolete(Obsoletions.LegacyFormatterImplMessage, DiagnosticId = Obsoletions.LegacyFormatterImplDiagId, UrlFormat = Obsoletions.SharedUrlFormat)]
[EditorBrowsable(EditorBrowsableState.Never)]
protected SortedSet(SerializationInfo info, StreamingContext context) => siInfo = info;
#endregion
#region Bulk operation helpers
private void AddAllElements(IEnumerable<T> collection)
{
foreach (T item in collection)
{
if (!Contains(item))
{
Add(item);
}
}
}
private void RemoveAllElements(IEnumerable<T> collection)
{
T? min = Min;
T? max = Max;
foreach (T item in collection)
{
if (!(comparer.Compare(item, min) < 0 || comparer.Compare(item, max) > 0) && Contains(item))
{
Remove(item);
}
}
}
private bool ContainsAllElements(IEnumerable<T> collection)
{
foreach (T item in collection)
{
if (!Contains(item))
{
return false;
}
}
return true;
}
/// <summary>
/// Does an in-order tree walk and calls the delegate for each node.
/// </summary>
/// <param name="action">
/// The delegate to invoke on each node.
/// If the delegate returns <c>false</c>, the walk is stopped.
/// </param>
/// <returns><c>true</c> if the entire tree has been walked; otherwise, <c>false</c>.</returns>
internal virtual bool InOrderTreeWalk(TreeWalkPredicate<T> action)
{
if (root == null)
{
return true;
}
// The maximum height of a red-black tree is 2 * log2(n+1).
// See page 264 of "Introduction to algorithms" by Thomas H. Cormen
// Note: It's not strictly necessary to provide the stack capacity, but we don't
// want the stack to unnecessarily allocate arrays as it grows.
var stack = new Stack<Node>(2 * (int)Log2(Count + 1));
Node? current = root;
while (current != null)
{
stack.Push(current);
current = current.Left;
}
while (stack.Count != 0)
{
current = stack.Pop();
if (!action(current))
{
return false;
}
Node? node = current.Right;
while (node != null)
{
stack.Push(node);
node = node.Left;
}
}
return true;
}
/// <summary>
/// Does a left-to-right breadth-first tree walk and calls the delegate for each node.
/// </summary>
/// <param name="action">
/// The delegate to invoke on each node.
/// If the delegate returns <c>false</c>, the walk is stopped.
/// </param>
/// <returns><c>true</c> if the entire tree has been walked; otherwise, <c>false</c>.</returns>
internal virtual bool BreadthFirstTreeWalk(TreeWalkPredicate<T> action)
{
if (root == null)
{
return true;
}
var processQueue = new Queue<Node>();
processQueue.Enqueue(root);
Node current;
while (processQueue.Count != 0)
{
current = processQueue.Dequeue();
if (!action(current))
{
return false;
}
if (current.Left != null)
{
processQueue.Enqueue(current.Left);
}
if (current.Right != null)
{
processQueue.Enqueue(current.Right);
}
}
return true;
}
#endregion
#region Properties
public int Count
{
get
{
VersionCheck(updateCount: true);
return count;
}
}
public IComparer<T> Comparer => comparer;
bool ICollection<T>.IsReadOnly => false;
bool ICollection.IsSynchronized => false;
object ICollection.SyncRoot => this;
#endregion
#region Subclass helpers
// Virtual function for TreeSubSet, which may need to update its count.
internal virtual void VersionCheck(bool updateCount = false) { }
// Virtual function for TreeSubSet, which may need the count variable of the parent set.
internal virtual int TotalCount() { return Count; }
// Virtual function for TreeSubSet, which may need to do range checks.
internal virtual bool IsWithinRange(T item) => true;
#endregion
#region ICollection<T> members
public bool Add(T item) => AddIfNotPresent(item); // Hack so the implementation can be made virtual
void ICollection<T>.Add(T item) => Add(item);
internal virtual bool AddIfNotPresent(T item)
{
if (root == null)
{
// The tree is empty and this is the first item.
root = new Node(item, NodeColor.Black);
count = 1;
version++;
return true;
}
// Search for a node at bottom to insert the new node.
// If we can guarantee the node we found is not a 4-node, it would be easy to do insertion.
// We split 4-nodes along the search path.
Node? current = root;
Node? parent = null;
Node? grandParent = null;
Node? greatGrandParent = null;
// Even if we don't actually add to the set, we may be altering its structure (by doing rotations and such).
// So update `_version` to disable any instances of Enumerator/TreeSubSet from working on it.
version++;
int order = 0;
while (current != null)
{
order = comparer.Compare(item, current.Item);
if (order == 0)
{
// We could have changed root node to red during the search process.
// We need to set it to black before we return.
root.ColorBlack();
return false;
}
// Split a 4-node into two 2-nodes.
if (current.Is4Node)
{
current.Split4Node();
// We could have introduced two consecutive red nodes after split. Fix that by rotation.
if (Node.IsNonNullRed(parent))
{
InsertionBalance(current, ref parent!, grandParent!, greatGrandParent!);
}
}
greatGrandParent = grandParent;
grandParent = parent;
parent = current;
current = (order < 0) ? current.Left : current.Right;
}
Debug.Assert(parent != null);
// We're ready to insert the new node.
Node node = new Node(item, NodeColor.Red);
if (order > 0)
{
parent.Right = node;
}
else
{
parent.Left = node;
}
// The new node will be red, so we will need to adjust colors if its parent is also red.
if (parent.IsRed)
{
InsertionBalance(node, ref parent!, grandParent!, greatGrandParent!);
}
// The root node is always black.
root.ColorBlack();
++count;
return true;
}
public bool Remove(T item) => DoRemove(item); // Hack so the implementation can be made virtual
internal virtual bool DoRemove(T item)
{
if (root == null)
{
return false;
}
// Search for a node and then find its successor.
// Then copy the item from the successor to the matching node, and delete the successor.
// If a node doesn't have a successor, we can replace it with its left child (if not empty),
// or delete the matching node.
//
// In top-down implementation, it is important to make sure the node to be deleted is not a 2-node.
// Following code will make sure the node on the path is not a 2-node.
// Even if we don't actually remove from the set, we may be altering its structure (by doing rotations
// and such). So update our version to disable any enumerators/subsets working on it.
version++;
Node? current = root;
Node? parent = null;
Node? grandParent = null;
Node? match = null;
Node? parentOfMatch = null;
bool foundMatch = false;
while (current != null)
{
if (current.Is2Node)
{
// Fix up 2-node
if (parent == null)
{
// `current` is the root. Mark it red.
current.ColorRed();
}
else
{
Node sibling = parent.GetSibling(current);
if (sibling.IsRed)
{
// If parent is a 3-node, flip the orientation of the red link.
// We can achieve this by a single rotation.
// This case is converted to one of the other cases below.
Debug.Assert(parent.IsBlack);
if (parent.Right == sibling)
{
parent.RotateLeft();
}
else
{
parent.RotateRight();
}
parent.ColorRed();
sibling.ColorBlack(); // The red parent can't have black children.
// `sibling` becomes the child of `grandParent` or `root` after rotation. Update the link from that node.
ReplaceChildOrRoot(grandParent, parent, sibling);
// `sibling` will become the grandparent of `current`.
grandParent = sibling;
if (parent == match)
{
parentOfMatch = sibling;
}
sibling = parent.GetSibling(current);
}
Debug.Assert(Node.IsNonNullBlack(sibling));
if (sibling.Is2Node)
{
parent.Merge2Nodes();
}
else
{
// `current` is a 2-node and `sibling` is either a 3-node or a 4-node.
// We can change the color of `current` to red by some rotation.
Node newGrandParent = parent.Rotate(parent.GetRotation(current, sibling))!;
newGrandParent.Color = parent.Color;
parent.ColorBlack();
current.ColorRed();
ReplaceChildOrRoot(grandParent, parent, newGrandParent);
if (parent == match)
{
parentOfMatch = newGrandParent;
}
}
}
}
// We don't need to compare after we find the match.
int order = foundMatch ? -1 : comparer.Compare(item, current.Item);
if (order == 0)
{
// Save the matching node.
foundMatch = true;
match = current;
parentOfMatch = parent;
}
grandParent = parent;
parent = current;
// If we found a match, continue the search in the right sub-tree.
current = order < 0 ? current.Left : current.Right;
}
// Move successor to the matching node position and replace links.
if (match != null)
{
ReplaceNode(match, parentOfMatch!, parent!, grandParent!);
--count;
}
root?.ColorBlack();
return foundMatch;
}
public virtual void Clear()
{
root = null;
count = 0;
++version;
}
public virtual bool Contains(T item) => FindNode(item) != null;
public void CopyTo(T[] array) => CopyTo(array, 0, Count);
public void CopyTo(T[] array, int index) => CopyTo(array, index, Count);
public void CopyTo(T[] array, int index, int count)
{
ArgumentNullException.ThrowIfNull(array);
ArgumentOutOfRangeException.ThrowIfNegative(index);
ArgumentOutOfRangeException.ThrowIfNegative(count);
if (count > array.Length - index)
{
throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall);
}
count += index; // Make `count` the upper bound.
InOrderTreeWalk(node =>
{
if (index >= count)
{
return false;
}
array[index++] = node.Item;
return true;
});
}
void ICollection.CopyTo(Array array, int index)
{
ArgumentNullException.ThrowIfNull(array);
if (array.Rank != 1)
{
throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array));
}
if (array.GetLowerBound(0) != 0)
{
throw new ArgumentException(SR.Arg_NonZeroLowerBound, nameof(array));
}
ArgumentOutOfRangeException.ThrowIfNegative(index);
if (array.Length - index < Count)
{
throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall);
}
T[]? tarray = array as T[];
if (tarray != null)
{
CopyTo(tarray, index);
}
else
{
object?[]? objects = array as object[];
if (objects == null)
{
throw new ArgumentException(SR.Argument_IncompatibleArrayType, nameof(array));
}
try
{
InOrderTreeWalk(node =>
{
objects[index++] = node.Item;
return true;
});
}
catch (ArrayTypeMismatchException)
{
throw new ArgumentException(SR.Argument_IncompatibleArrayType, nameof(array));
}
}
}
#endregion
#region IEnumerable<T> members
public Enumerator GetEnumerator() => new Enumerator(this);
IEnumerator<T> IEnumerable<T>.GetEnumerator() => GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => ((IEnumerable<T>)this).GetEnumerator();
#endregion
#region Tree-specific operations
// After calling InsertionBalance, we need to make sure `current` and `parent` are up-to-date.
// It doesn't matter if we keep `grandParent` and `greatGrandParent` up-to-date, because we won't
// need to split again in the next node.
// By the time we need to split again, everything will be correctly set.
private void InsertionBalance(Node current, ref Node parent, Node grandParent, Node greatGrandParent)
{
Debug.Assert(parent != null);
Debug.Assert(grandParent != null);
bool parentIsOnRight = grandParent.Right == parent;
bool currentIsOnRight = parent.Right == current;
Node newChildOfGreatGrandParent;
if (parentIsOnRight == currentIsOnRight)
{
// Same orientation, single rotation
newChildOfGreatGrandParent = currentIsOnRight ? grandParent.RotateLeft() : grandParent.RotateRight();
}
else
{
// Different orientation, double rotation
newChildOfGreatGrandParent = currentIsOnRight ? grandParent.RotateLeftRight() : grandParent.RotateRightLeft();
// Current node now becomes the child of `greatGrandParent`
parent = greatGrandParent;
}
// `grandParent` will become a child of either `parent` of `current`.
grandParent.ColorRed();
newChildOfGreatGrandParent.ColorBlack();
ReplaceChildOrRoot(greatGrandParent, grandParent, newChildOfGreatGrandParent);
}
/// <summary>
/// Replaces the child of a parent node, or replaces the root if the parent is <c>null</c>.
/// </summary>
/// <param name="parent">The (possibly <c>null</c>) parent.</param>
/// <param name="child">The child node to replace.</param>
/// <param name="newChild">The node to replace <paramref name="child"/> with.</param>
private void ReplaceChildOrRoot(Node? parent, Node child, Node newChild)
{
if (parent != null)
{
parent.ReplaceChild(child, newChild);
}
else
{
root = newChild;
}
}
/// <summary>
/// Replaces the matching node with its successor.
/// </summary>
private void ReplaceNode(Node match, Node parentOfMatch, Node successor, Node parentOfSuccessor)
{
Debug.Assert(match != null);
if (successor == match)
{
// This node has no successor. This can only happen if the right child of the match is null.
Debug.Assert(match.Right == null);
successor = match.Left!;
}
else
{
Debug.Assert(parentOfSuccessor != null);
Debug.Assert(successor.Left == null);
Debug.Assert((successor.Right == null && successor.IsRed) || (successor.Right!.IsRed && successor.IsBlack));
successor.Right?.ColorBlack();
if (parentOfSuccessor != match)
{
// Detach the successor from its parent and set its right child.
parentOfSuccessor.Left = successor.Right;
successor.Right = match.Right;
}
successor.Left = match.Left;
}
if (successor != null)
{
successor.Color = match.Color;
}
ReplaceChildOrRoot(parentOfMatch, match, successor!);
}
internal virtual Node? FindNode(T item)
{
Node? current = root;
while (current != null)
{
int order = comparer.Compare(item, current.Item);
if (order == 0)
{
return current;
}
current = order < 0 ? current.Left : current.Right;
}
return null;
}
/// <summary>
/// Searches for an item and returns its zero-based index in this set.
/// </summary>
/// <param name="item">The item.</param>
/// <returns>The item's zero-based index in this set, or -1 if it isn't found.</returns>
/// <remarks>
/// <para>
/// This implementation is based off of http://en.wikipedia.org/wiki/Binary_Tree#Methods_for_storing_binary_trees.
/// </para>
/// <para>
/// This method is used with the <see cref="BitHelper"/> class. Note that this implementation is
/// completely different from <see cref="TreeSubSet"/>'s, and that the two should not be mixed.
/// </para>
/// </remarks>
internal virtual int InternalIndexOf(T item)
{
Node? current = root;
int count = 0;
while (current != null)
{
int order = comparer.Compare(item, current.Item);
if (order == 0)
{
return count;
}
current = order < 0 ? current.Left : current.Right;
count = order < 0 ? (2 * count + 1) : (2 * count + 2);
}
return -1;
}
internal Node? FindRange(T? from, T? to) => FindRange(from, to, lowerBoundActive: true, upperBoundActive: true);
internal Node? FindRange(T? from, T? to, bool lowerBoundActive, bool upperBoundActive)
{
Node? current = root;
while (current != null)
{
if (lowerBoundActive && comparer.Compare(from, current.Item) > 0)
{
current = current.Right;
}
else
{
if (upperBoundActive && comparer.Compare(to, current.Item) < 0)
{
current = current.Left;
}
else
{
return current;
}
}
}
return null;
}
internal void UpdateVersion() => ++version;
/// <summary>
/// Returns an <see cref="IEqualityComparer{T}"/> object that can be used to create a collection that contains individual sets.
/// </summary>
public static IEqualityComparer<SortedSet<T>> CreateSetComparer() => CreateSetComparer(memberEqualityComparer: null);
/// <summary>
/// Returns an <see cref="IEqualityComparer{T}"/> object, according to a specified comparer, that can be used to create a collection that contains individual sets.
/// </summary>
public static IEqualityComparer<SortedSet<T>> CreateSetComparer(IEqualityComparer<T>? memberEqualityComparer)
{
return new SortedSetEqualityComparer<T>(memberEqualityComparer);
}
/// <summary>
/// Decides whether two sets have equal contents, using a fallback comparer if the sets do not have equivalent equality comparers.
/// </summary>
/// <param name="set1">The first set.</param>
/// <param name="set2">The second set.</param>
/// <param name="comparer">The fallback comparer to use if the sets do not have equal comparers.</param>
/// <returns><c>true</c> if the sets have equal contents; otherwise, <c>false</c>.</returns>
internal static bool SortedSetEquals(SortedSet<T>? set1, SortedSet<T>? set2, IComparer<T> comparer)
{
if (set1 == null)
{
return set2 == null;
}
if (set2 == null)
{
Debug.Assert(set1 != null);
return false;
}
if (set1.HasEqualComparer(set2))
{
return set1.Count == set2.Count && set1.SetEquals(set2);
}
bool found;
foreach (T item1 in set1)
{
found = false;
foreach (T item2 in set2)
{
if (comparer.Compare(item1, item2) == 0)
{
found = true;
break;
}
}
if (!found)
{
return false;
}
}
return true;
}
/// <summary>
/// Determines whether two <see cref="SortedSet{T}"/> instances have the same comparer.
/// </summary>
/// <param name="other">The other <see cref="SortedSet{T}"/>.</param>
/// <returns>A value indicating whether both sets have the same comparer.</returns>
private bool HasEqualComparer(SortedSet<T> other)
{
// Commonly, both comparers will be the default comparer (and reference-equal). Avoid a virtual method call to Equals() in that case.
return Comparer == other.Comparer || Comparer.Equals(other.Comparer);
}
#endregion
#region ISet members
public void UnionWith(IEnumerable<T> other)
{
ArgumentNullException.ThrowIfNull(other);
SortedSet<T>? asSorted = other as SortedSet<T>;
TreeSubSet? treeSubset = this as TreeSubSet;
if (treeSubset != null)
VersionCheck();
if (asSorted != null && treeSubset == null && Count == 0)
{
SortedSet<T> dummy = new SortedSet<T>(asSorted, comparer);
root = dummy.root;
count = dummy.count;
version++;
return;
}
// This actually hurts if N is much greater than M. The / 2 is arbitrary.
if (asSorted != null && treeSubset == null && HasEqualComparer(asSorted) && (asSorted.Count > this.Count / 2))
{
// First do a merge sort to an array.
T[] merged = new T[asSorted.Count + this.Count];
int c = 0;
Enumerator mine = this.GetEnumerator();
Enumerator theirs = asSorted.GetEnumerator();
bool mineEnded = !mine.MoveNext(), theirsEnded = !theirs.MoveNext();
while (!mineEnded && !theirsEnded)
{
int comp = Comparer.Compare(mine.Current, theirs.Current);
if (comp < 0)
{
merged[c++] = mine.Current;
mineEnded = !mine.MoveNext();
}
else if (comp == 0)
{
merged[c++] = theirs.Current;
mineEnded = !mine.MoveNext();
theirsEnded = !theirs.MoveNext();
}
else
{
merged[c++] = theirs.Current;
theirsEnded = !theirs.MoveNext();
}
}
if (!mineEnded || !theirsEnded)
{
Enumerator remaining = (mineEnded ? theirs : mine);
do
{
merged[c++] = remaining.Current;
}
while (remaining.MoveNext());
}
// now merged has all c elements
// safe to gc the root, we have all the elements
root = null;
root = ConstructRootFromSortedArray(merged, 0, c - 1, null);
count = c;
version++;
}
else
{
AddAllElements(other);
}
}
private static Node? ConstructRootFromSortedArray(T[] arr, int startIndex, int endIndex, Node? redNode)
{
// You're given a sorted array... say 1 2 3 4 5 6
// There are 2 cases:
// - If there are odd # of elements, pick the middle element (in this case 4), and compute
// its left and right branches
// - If there are even # of elements, pick the left middle element, save the right middle element
// and call the function on the rest
// 1 2 3 4 5 6 -> pick 3, save 4 and call the fn on 1,2 and 5,6
// now add 4 as a red node to the lowest element on the right branch
// 3 3
// 1 5 -> 1 5
// 2 6 2 4 6
// As we're adding to the leftmost of the right branch, nesting will not hurt the red-black properties
// Leaf nodes are red if they have no sibling (if there are 2 nodes or if a node trickles
// down to the bottom
// This is done recursively because the iterative way to do this ends up wasting more space than it saves in stack frames
// Only some base cases are handled below.
int size = endIndex - startIndex + 1;
Node root;
switch (size)
{
case 0:
return null;
case 1:
root = new Node(arr[startIndex], NodeColor.Black);
if (redNode != null)
{
root.Left = redNode;
}
break;
case 2:
root = new Node(arr[startIndex], NodeColor.Black);
root.Right = new Node(arr[endIndex], NodeColor.Black);
root.Right.ColorRed();
if (redNode != null)
{
root.Left = redNode;
}
break;
case 3:
root = new Node(arr[startIndex + 1], NodeColor.Black);
root.Left = new Node(arr[startIndex], NodeColor.Black);
root.Right = new Node(arr[endIndex], NodeColor.Black);
if (redNode != null)
{
root.Left.Left = redNode;
}
break;
default:
int midpt = ((startIndex + endIndex) / 2);
root = new Node(arr[midpt], NodeColor.Black);
root.Left = ConstructRootFromSortedArray(arr, startIndex, midpt - 1, redNode);
root.Right = size % 2 == 0 ?
ConstructRootFromSortedArray(arr, midpt + 2, endIndex, new Node(arr[midpt + 1], NodeColor.Red)) :
ConstructRootFromSortedArray(arr, midpt + 1, endIndex, null);
break;
}
return root;
}
public virtual void IntersectWith(IEnumerable<T> other)
{
ArgumentNullException.ThrowIfNull(other);
if (Count == 0)
return;
if (other == this)
return;
// HashSet<T> optimizations can't be done until equality comparers and comparers are related
// Technically, this would work as well with an ISorted<T>
SortedSet<T>? asSorted = other as SortedSet<T>;
TreeSubSet? treeSubset = this as TreeSubSet;