forked from dotnet/runtime
/
ImmutableList_1.Node.cs
1609 lines (1437 loc) · 67.2 KB
/
ImmutableList_1.Node.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.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
namespace System.Collections.Immutable
{
public sealed partial class ImmutableList<T>
{
/// <summary>
/// A node in the AVL tree storing this set.
/// </summary>
[DebuggerDisplay("{_key}")]
internal sealed class Node : IBinaryTree<T>, IEnumerable<T>
{
/// <summary>
/// The default empty node.
/// </summary>
internal static readonly Node EmptyNode = new Node();
/// <summary>
/// The key associated with this node.
/// </summary>
private T _key = default!; // Defaulting for EmptyNode, shouldn't be null for non empty nodes so didn't annotated with [MaybeNull]
/// <summary>
/// A value indicating whether this node has been frozen (made immutable).
/// </summary>
/// <remarks>
/// Nodes must be frozen before ever being observed by a wrapping collection type
/// to protect collections from further mutations.
/// </remarks>
private bool _frozen;
/// <summary>
/// The depth of the tree beneath this node.
/// </summary>
private byte _height; // AVL tree max height <= ~1.44 * log2(maxNodes + 2)
/// <summary>
/// The number of elements contained by this subtree starting at this node.
/// </summary>
/// <remarks>
/// If this node would benefit from saving 4 bytes, we could have only a few nodes
/// scattered throughout the graph actually record the count of nodes beneath them.
/// Those without the count could query their descendants, which would often short-circuit
/// when they hit a node that *does* include a count field.
/// </remarks>
private int _count;
/// <summary>
/// The left tree.
/// </summary>
private Node? _left;
/// <summary>
/// The right tree.
/// </summary>
private Node? _right;
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableList{T}.Node"/> class
/// that is pre-frozen.
/// </summary>
private Node()
{
_frozen = true; // the empty node is *always* frozen.
Debug.Assert(this.IsEmpty);
}
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableList{T}.Node"/> class
/// that is not yet frozen.
/// </summary>
/// <param name="key">The value stored by this node.</param>
/// <param name="left">The left branch.</param>
/// <param name="right">The right branch.</param>
/// <param name="frozen">Whether this node is prefrozen.</param>
private Node(T key, Node left, Node right, bool frozen = false)
{
Requires.NotNull(left, nameof(left));
Requires.NotNull(right, nameof(right));
Debug.Assert(!frozen || (left._frozen && right._frozen));
_key = key;
_left = left;
_right = right;
_height = ParentHeight(left, right);
_count = ParentCount(left, right);
_frozen = frozen;
Debug.Assert(!this.IsEmpty);
}
/// <summary>
/// Gets a value indicating whether this instance is empty.
/// </summary>
/// <value>
/// <c>true</c> if this instance is empty; otherwise, <c>false</c>.
/// </value>
public bool IsEmpty
{
get
{
Debug.Assert(!(_left == null ^ _right == null));
return _left == null;
}
}
/// <summary>
/// Gets the height of the tree beneath this node.
/// </summary>
public int Height => _height;
/// <summary>
/// Gets the left branch of this node.
/// </summary>
public Node? Left => _left;
/// <summary>
/// Gets the left branch of this node.
/// </summary>
IBinaryTree? IBinaryTree.Left => _left;
/// <summary>
/// Gets the right branch of this node.
/// </summary>
public Node? Right => _right;
/// <summary>
/// Gets the right branch of this node.
/// </summary>
IBinaryTree? IBinaryTree.Right => _right;
/// <summary>
/// Gets the left branch of this node.
/// </summary>
IBinaryTree<T>? IBinaryTree<T>.Left => _left;
/// <summary>
/// Gets the right branch of this node.
/// </summary>
IBinaryTree<T>? IBinaryTree<T>.Right => _right;
/// <summary>
/// Gets the value represented by the current node.
/// </summary>
public T Value => _key;
/// <summary>
/// Gets the number of elements contained by this subtree starting at this node.
/// </summary>
public int Count => _count;
/// <summary>
/// Gets the key.
/// </summary>
internal T Key => _key;
/// <summary>
/// Gets the element of the set at the given index.
/// </summary>
/// <param name="index">The 0-based index of the element in the set to return.</param>
/// <returns>The element at the given position.</returns>
internal T this[int index]
{
get
{
Requires.Range(index >= 0 && index < this.Count, nameof(index));
Debug.Assert(_left != null && _right != null);
if (index < _left._count)
{
return _left[index];
}
if (index > _left._count)
{
return _right[index - _left._count - 1];
}
return _key;
}
}
/// <summary>
/// Gets a read-only reference to the element of the set at the given index.
/// </summary>
/// <param name="index">The 0-based index of the element in the set to return.</param>
/// <returns>A read-only reference to the element at the given position.</returns>
internal ref readonly T ItemRef(int index)
{
Requires.Range(index >= 0 && index < this.Count, nameof(index));
return ref ItemRefUnchecked(index);
}
private ref readonly T ItemRefUnchecked(int index)
{
Debug.Assert(_left != null && _right != null);
if (index < _left._count)
{
return ref _left.ItemRefUnchecked(index);
}
if (index > _left._count)
{
return ref _right.ItemRefUnchecked(index - _left._count - 1);
}
return ref _key;
}
#region IEnumerable<T> Members
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection.
/// </returns>
public Enumerator GetEnumerator() => new Enumerator(this);
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection.
/// </returns>
[ExcludeFromCodeCoverage] // internal, never called, but here for interface implementation
IEnumerator<T> IEnumerable<T>.GetEnumerator() => this.GetEnumerator();
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection.
/// </returns>
[ExcludeFromCodeCoverage] // internal, never called, but here for interface implementation
IEnumerator IEnumerable.GetEnumerator() => this.GetEnumerator();
#endregion
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <param name="builder">The builder, if applicable.</param>
/// <returns>
/// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection.
/// </returns>
internal Enumerator GetEnumerator(Builder builder) => new Enumerator(this, builder);
/// <summary>
/// Creates a node tree that contains the contents of a list.
/// </summary>
/// <param name="items">An indexable list with the contents that the new node tree should contain.</param>
/// <param name="start">The starting index within <paramref name="items"/> that should be captured by the node tree.</param>
/// <param name="length">The number of elements from <paramref name="items"/> that should be captured by the node tree.</param>
/// <returns>The root of the created node tree.</returns>
internal static Node NodeTreeFromList(IOrderedCollection<T> items, int start, int length)
{
Requires.NotNull(items, nameof(items));
Requires.Range(start >= 0, nameof(start));
Requires.Range(length >= 0, nameof(length));
if (length == 0)
{
return EmptyNode;
}
int rightCount = (length - 1) / 2;
int leftCount = (length - 1) - rightCount;
Node left = NodeTreeFromList(items, start, leftCount);
Node right = NodeTreeFromList(items, start + leftCount + 1, rightCount);
return new Node(items[start + leftCount], left, right, true);
}
/// <summary>
/// Creates a node tree that contains the contents of a span.
/// </summary>
/// <param name="items">A span with the contents that the new node tree should contain.</param>
/// <returns>The root of the created node tree.</returns>
internal static Node NodeTreeFromList(ReadOnlySpan<T> items)
{
if (items.IsEmpty)
{
return EmptyNode;
}
int rightCount = (items.Length - 1) / 2;
int leftCount = (items.Length - 1) - rightCount;
Node left = NodeTreeFromList(items.Slice(0, leftCount));
Node right = NodeTreeFromList(items.Slice(leftCount + 1));
return new Node(items[leftCount], left, right, frozen: true);
}
/// <summary>
/// Adds the specified key to the tree.
/// </summary>
/// <param name="key">The key.</param>
/// <returns>The new tree.</returns>
internal Node Add(T key)
{
if (this.IsEmpty)
{
return CreateLeaf(key);
}
Node newRight = _right!.Add(key);
Node result = this.MutateRight(newRight);
return result.IsBalanced ? result : result.BalanceRight();
}
/// <summary>
/// Adds a value at a given index to this node.
/// </summary>
/// <param name="index">The location for the new value.</param>
/// <param name="key">The value to add.</param>
/// <returns>The new tree.</returns>
internal Node Insert(int index, T key)
{
Requires.Range(index >= 0 && index <= this.Count, nameof(index));
if (this.IsEmpty)
{
return CreateLeaf(key);
}
if (index <= _left!._count)
{
Node newLeft = _left.Insert(index, key);
Node result = this.MutateLeft(newLeft);
return result.IsBalanced ? result : result.BalanceLeft();
}
else
{
Node newRight = _right!.Insert(index - _left._count - 1, key);
Node result = this.MutateRight(newRight);
return result.IsBalanced ? result : result.BalanceRight();
}
}
/// <summary>
/// Adds the specified keys to this tree.
/// </summary>
/// <param name="keys">The keys.</param>
/// <returns>The new tree.</returns>
internal Node AddRange(IEnumerable<T> keys)
{
Requires.NotNull(keys, nameof(keys));
if (this.IsEmpty)
{
return CreateRange(keys);
}
Node newRight = _right!.AddRange(keys);
Node result = this.MutateRight(newRight);
return result.BalanceMany();
}
/// <summary>
/// Adds the specified keys to this tree.
/// </summary>
/// <param name="keys">The keys.</param>
/// <returns>The new tree.</returns>
internal Node AddRange(ReadOnlySpan<T> keys)
{
if (this.IsEmpty)
{
return NodeTreeFromList(keys);
}
Node newRight = _right!.AddRange(keys);
Node result = this.MutateRight(newRight);
return result.BalanceMany();
}
/// <summary>
/// Adds the specified keys at a given index to this tree.
/// </summary>
/// <param name="index">The location for the new keys.</param>
/// <param name="keys">The keys.</param>
/// <returns>The new tree.</returns>
internal Node InsertRange(int index, IEnumerable<T> keys)
{
Requires.Range(index >= 0 && index <= this.Count, nameof(index));
Requires.NotNull(keys, nameof(keys));
if (this.IsEmpty)
{
return CreateRange(keys);
}
Node result;
if (index <= _left!._count)
{
Node newLeft = _left.InsertRange(index, keys);
result = this.MutateLeft(newLeft);
}
else
{
Node newRight = _right!.InsertRange(index - _left._count - 1, keys);
result = this.MutateRight(newRight);
}
return result.BalanceMany();
}
/// <summary>
/// Removes a value at a given index to this node.
/// </summary>
/// <param name="index">The location for the new value.</param>
/// <returns>The new tree.</returns>
internal Node RemoveAt(int index)
{
Requires.Range(index >= 0 && index < this.Count, nameof(index));
Debug.Assert(_left != null && _right != null);
Node result;
if (index == _left._count)
{
// We have a match. If this is a leaf, just remove it
// by returning Empty. If we have only one child,
// replace the node with the child.
if (_right.IsEmpty && _left.IsEmpty)
{
result = EmptyNode;
}
else if (_right.IsEmpty && !_left.IsEmpty)
{
result = _left;
}
else if (!_right.IsEmpty && _left.IsEmpty)
{
result = _right;
}
else
{
// We have two children. Remove the next-highest node and replace
// this node with it.
ImmutableList<T>.Node successor = _right;
while (!successor._left!.IsEmpty)
{
successor = successor._left;
}
ImmutableList<T>.Node newRight = _right.RemoveAt(0);
result = successor.MutateBoth(left: _left, right: newRight);
}
}
else if (index < _left._count)
{
ImmutableList<T>.Node newLeft = _left.RemoveAt(index);
result = this.MutateLeft(newLeft);
}
else
{
ImmutableList<T>.Node newRight = _right.RemoveAt(index - _left._count - 1);
result = this.MutateRight(newRight);
}
return result.IsEmpty || result.IsBalanced ? result : result.Balance();
}
/// <summary>
/// Removes all the elements that match the conditions defined by the specified
/// predicate.
/// </summary>
/// <param name="match">
/// The <see cref="Predicate{T}"/> delegate that defines the conditions of the elements
/// to remove.
/// </param>
/// <returns>
/// The new node tree.
/// </returns>
internal Node RemoveAll(Predicate<T> match)
{
Requires.NotNull(match, nameof(match));
ImmutableList<T>.Node result = this;
var enumerator = new Enumerator(result);
try
{
int startIndex = 0;
while (enumerator.MoveNext())
{
if (match(enumerator.Current))
{
result = result.RemoveAt(startIndex);
enumerator.Dispose();
enumerator = new Enumerator(result, startIndex: startIndex);
}
else
{
startIndex++;
}
}
}
finally
{
enumerator.Dispose();
}
Debug.Assert(result != null);
return result;
}
/// <summary>
/// Replaces a value at a given index.
/// </summary>
/// <param name="index">The location for the new value.</param>
/// <param name="value">The new value for the node.</param>
/// <returns>The new tree.</returns>
internal Node ReplaceAt(int index, T value)
{
Requires.Range(index >= 0 && index < this.Count, nameof(index));
Debug.Assert(!this.IsEmpty);
Node result;
if (index == _left!._count)
{
// We have a match.
result = this.MutateKey(value);
}
else if (index < _left._count)
{
ImmutableList<T>.Node newLeft = _left.ReplaceAt(index, value);
result = this.MutateLeft(newLeft);
}
else
{
ImmutableList<T>.Node newRight = _right!.ReplaceAt(index - _left._count - 1, value);
result = this.MutateRight(newRight);
}
return result;
}
/// <summary>
/// Reverses the order of the elements in the entire <see cref="ImmutableList{T}"/>.
/// </summary>
/// <returns>The reversed list.</returns>
internal Node Reverse() => this.Reverse(0, this.Count);
/// <summary>
/// Reverses the order of the elements in the specified range.
/// </summary>
/// <param name="index">The zero-based starting index of the range to reverse.</param>
/// <param name="count">The number of elements in the range to reverse.</param>
/// <returns>The reversed list.</returns>
internal Node Reverse(int index, int count)
{
Requires.Range(index >= 0, nameof(index));
Requires.Range(count >= 0, nameof(count));
Requires.Range(index + count <= this.Count, nameof(index));
Node result = this;
int start = index;
int end = index + count - 1;
while (start < end)
{
T a = result.ItemRef(start);
T b = result.ItemRef(end);
result = result
.ReplaceAt(end, a)
.ReplaceAt(start, b);
start++;
end--;
}
return result;
}
/// <summary>
/// Sorts the elements in the entire <see cref="ImmutableList{T}"/> using
/// the default comparer.
/// </summary>
internal Node Sort() => this.Sort(Comparer<T>.Default);
/// <summary>
/// Sorts the elements in the entire <see cref="ImmutableList{T}"/> using
/// the specified <see cref="Comparison{T}"/>.
/// </summary>
/// <param name="comparison">
/// The <see cref="Comparison{T}"/> to use when comparing elements.
/// </param>
/// <returns>The sorted list.</returns>
internal Node Sort(Comparison<T> comparison)
{
Requires.NotNull(comparison, nameof(comparison));
// PERF: Eventually this might be reimplemented in a way that does not require allocating an array.
var array = new T[this.Count];
this.CopyTo(array);
Array.Sort(array, comparison);
return NodeTreeFromList(array.AsOrderedCollection(), 0, this.Count);
}
/// <summary>
/// Sorts the elements in the entire <see cref="ImmutableList{T}"/> using
/// the specified comparer.
/// </summary>
/// <param name="comparer">
/// The <see cref="IComparer{T}"/> implementation to use when comparing
/// elements, or null to use the default comparer <see cref="Comparer{T}.Default"/>.
/// </param>
/// <returns>The sorted list.</returns>
internal Node Sort(IComparer<T>? comparer) => this.Sort(0, this.Count, comparer);
/// <summary>
/// Sorts the elements in a range of elements in <see cref="ImmutableList{T}"/>
/// using the specified comparer.
/// </summary>
/// <param name="index">
/// The zero-based starting index of the range to sort.
/// </param>
/// <param name="count">
/// The length of the range to sort.
/// </param>
/// <param name="comparer">
/// The <see cref="IComparer{T}"/> implementation to use when comparing
/// elements, or null to use the default comparer <see cref="Comparer{T}.Default"/>.
/// </param>
/// <returns>The sorted list.</returns>
internal Node Sort(int index, int count, IComparer<T>? comparer)
{
Requires.Range(index >= 0, nameof(index));
Requires.Range(count >= 0, nameof(count));
Requires.Argument(index + count <= this.Count);
// PERF: Eventually this might be reimplemented in a way that does not require allocating an array.
var array = new T[this.Count];
this.CopyTo(array);
Array.Sort(array, index, count, comparer);
return NodeTreeFromList(array.AsOrderedCollection(), 0, this.Count);
}
/// <summary>
/// Searches a range of elements in the sorted <see cref="ImmutableList{T}"/>
/// for an element using the specified comparer and returns the zero-based index
/// of the element.
/// </summary>
/// <param name="index">The zero-based starting index of the range to search.</param>
/// <param name="count"> The length of the range to search.</param>
/// <param name="item">The object to locate. The value can be null for reference types.</param>
/// <param name="comparer">
/// The <see cref="IComparer{T}"/> implementation to use when comparing
/// elements, or null to use the default comparer <see cref="Comparer{T}.Default"/>.
/// </param>
/// <returns>
/// The zero-based index of item in the sorted <see cref="ImmutableList{T}"/>,
/// if item is found; otherwise, a negative number that is the bitwise complement
/// of the index of the next element that is larger than item or, if there is
/// no larger element, the bitwise complement of <see cref="ImmutableList{T}.Count"/>.
/// </returns>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="index"/> is less than 0.-or-<paramref name="count"/> is less than 0.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="index"/> and <paramref name="count"/> do not denote a valid range in the <see cref="ImmutableList{T}"/>.
/// </exception>
/// <exception cref="InvalidOperationException">
/// <paramref name="comparer"/> is null, and the default comparer <see cref="Comparer{T}.Default"/>
/// cannot find an implementation of the <see cref="IComparable{T}"/> generic interface
/// or the <see cref="IComparable"/> interface for type <typeparamref name="T"/>.
/// </exception>
internal int BinarySearch(int index, int count, T item, IComparer<T>? comparer)
{
Requires.Range(index >= 0, nameof(index));
Requires.Range(count >= 0, nameof(count));
comparer ??= Comparer<T>.Default;
if (this.IsEmpty || count <= 0)
{
return ~index;
}
// If this node is not within range, defer to either branch as appropriate.
int thisNodeIndex = _left!.Count; // this is only the index within the AVL tree, treating this node as root rather than a member of a larger tree.
if (index + count <= thisNodeIndex)
{
return _left.BinarySearch(index, count, item, comparer);
}
else if (index > thisNodeIndex)
{
int result = _right!.BinarySearch(index - thisNodeIndex - 1, count, item, comparer);
int offset = thisNodeIndex + 1;
return result < 0 ? result - offset : result + offset;
}
// We're definitely in the caller's designated range now.
// Any possible match will be a descendant of this node (or this immediate one).
// Some descendants may not be in range, but if we hit any it means no match was found,
// and a negative response would come back from the above code to the below code.
int compare = comparer.Compare(item, _key);
if (compare == 0)
{
return thisNodeIndex;
}
else if (compare > 0)
{
int adjustedCount = count - (thisNodeIndex - index) - 1;
int result = adjustedCount < 0 ? -1 : _right!.BinarySearch(0, adjustedCount, item, comparer);
int offset = thisNodeIndex + 1;
return result < 0 ? result - offset : result + offset;
}
else
{
if (index == thisNodeIndex)
{
// We can't go any further left.
return ~index;
}
int result = _left.BinarySearch(index, count, item, comparer);
return result;
}
}
/// <summary>
/// Searches for the specified object and returns the zero-based index of the
/// first occurrence within the range of elements in the <see cref="ImmutableList{T}"/>
/// that starts at the specified index and contains the specified number of elements.
/// </summary>
/// <param name="item">
/// The object to locate in the <see cref="ImmutableList{T}"/>. The value
/// can be null for reference types.
/// </param>
/// <param name="equalityComparer">The equality comparer to use for testing the match of two elements.</param>
/// <returns>
/// The zero-based index of the first occurrence of <paramref name="item"/> within the entire
/// <see cref="ImmutableList{T}"/>, if found; otherwise, -1.
/// </returns>
internal int IndexOf(T item, IEqualityComparer<T>? equalityComparer) => this.IndexOf(item, 0, this.Count, equalityComparer);
/// <summary>
/// Searches for the specified object and returns <c>true</c> if it is found, <c>false</c> otherwise.
/// </summary>
/// <param name="item">
/// The object to locate in the <see cref="ImmutableList{T}"/>. The value
/// can be null for reference types.
/// </param>
/// <param name="equalityComparer">
/// The equality comparer to use for testing the match of two elements.
/// </param>
/// <returns>
/// <c>true</c> if it is found, <c>false</c> otherwise.
/// </returns>
internal bool Contains(T item, IEqualityComparer<T> equalityComparer) => Contains(this, item, equalityComparer);
/// <summary>
/// Searches for the specified object and returns the zero-based index of the
/// first occurrence within the range of elements in the <see cref="ImmutableList{T}"/>
/// that starts at the specified index and contains the specified number of elements.
/// </summary>
/// <param name="item">
/// The object to locate in the <see cref="ImmutableList{T}"/>. The value
/// can be null for reference types.
/// </param>
/// <param name="index">
/// The zero-based starting index of the search. 0 (zero) is valid in an empty
/// list.
/// </param>
/// <param name="count">
/// The number of elements in the section to search.
/// </param>
/// <param name="equalityComparer">
/// The equality comparer to use in the search.
/// If <c>null</c>, <see cref="EqualityComparer{T}.Default"/> is used.
/// </param>
/// <returns>
/// The zero-based index of the first occurrence of <paramref name="item"/> within the range of
/// elements in the <see cref="ImmutableList{T}"/> that starts at <paramref name="index"/> and
/// contains <paramref name="count"/> number of elements, if found; otherwise, -1.
/// </returns>
internal int IndexOf(T item, int index, int count, IEqualityComparer<T>? equalityComparer)
{
Requires.Range(index >= 0, nameof(index));
Requires.Range(count >= 0, nameof(count));
Requires.Range(count <= this.Count, nameof(count));
Requires.Range(index + count <= this.Count, nameof(count));
equalityComparer ??= EqualityComparer<T>.Default;
using (var enumerator = new Enumerator(this, startIndex: index, count: count))
{
while (enumerator.MoveNext())
{
if (equalityComparer.Equals(item, enumerator.Current))
{
return index;
}
index++;
}
}
return -1;
}
/// <summary>
/// Searches for the specified object and returns the zero-based index of the
/// last occurrence within the range of elements in the <see cref="ImmutableList{T}"/>
/// that contains the specified number of elements and ends at the specified
/// index.
/// </summary>
/// <param name="item">
/// The object to locate in the <see cref="ImmutableList{T}"/>. The value
/// can be null for reference types.
/// </param>
/// <param name="index">The zero-based starting index of the backward search.</param>
/// <param name="count">The number of elements in the section to search.</param>
/// <param name="equalityComparer">The equality comparer to use for testing the match of two elements.</param>
/// <returns>
/// The zero-based index of the last occurrence of <paramref name="item"/> within the range of elements
/// in the <see cref="ImmutableList{T}"/> that contains <paramref name="count"/> number of elements
/// and ends at <paramref name="index"/>, if found; otherwise, -1.
/// </returns>
internal int LastIndexOf(T item, int index, int count, IEqualityComparer<T>? equalityComparer)
{
Requires.Range(index >= 0, nameof(index));
Requires.Range(count >= 0 && count <= this.Count, nameof(count));
Requires.Argument(index - count + 1 >= 0);
equalityComparer ??= EqualityComparer<T>.Default;
using (var enumerator = new Enumerator(this, startIndex: index, count: count, reversed: true))
{
while (enumerator.MoveNext())
{
if (equalityComparer.Equals(item, enumerator.Current))
{
return index;
}
index--;
}
}
return -1;
}
/// <summary>
/// Copies the entire <see cref="ImmutableList{T}"/> to a compatible one-dimensional
/// array, starting at the beginning of the target array.
/// </summary>
/// <param name="array">
/// The one-dimensional <see cref="Array"/> that is the destination of the elements
/// copied from <see cref="ImmutableList{T}"/>. The <see cref="Array"/> must have
/// zero-based indexing.
/// </param>
internal void CopyTo(T[] array)
{
Requires.NotNull(array, nameof(array));
Requires.Range(array.Length >= this.Count, nameof(array));
int index = 0;
foreach (T element in this)
{
array[index++] = element;
}
}
/// <summary>
/// Copies the entire <see cref="ImmutableList{T}"/> to a compatible one-dimensional
/// array, starting at the specified index of the target array.
/// </summary>
/// <param name="array">
/// The one-dimensional <see cref="Array"/> that is the destination of the elements
/// copied from <see cref="ImmutableList{T}"/>. The <see cref="Array"/> must have
/// zero-based indexing.
/// </param>
/// <param name="arrayIndex">
/// The zero-based index in <paramref name="array"/> at which copying begins.
/// </param>
internal void CopyTo(T[] array, int arrayIndex)
{
Requires.NotNull(array, nameof(array));
Requires.Range(arrayIndex >= 0, nameof(arrayIndex));
Requires.Range(array.Length >= arrayIndex + this.Count, nameof(arrayIndex));
foreach (T element in this)
{
array[arrayIndex++] = element;
}
}
/// <summary>
/// Copies a range of elements from the <see cref="ImmutableList{T}"/> to
/// a compatible one-dimensional array, starting at the specified index of the
/// target array.
/// </summary>
/// <param name="index">
/// The zero-based index in the source <see cref="ImmutableList{T}"/> at
/// which copying begins.
/// </param>
/// <param name="array">
/// The one-dimensional <see cref="Array"/> that is the destination of the elements
/// copied from <see cref="ImmutableList{T}"/>. The <see cref="Array"/> must have
/// zero-based indexing.
/// </param>
/// <param name="arrayIndex">The zero-based index in <paramref name="array"/> at which copying begins.</param>
/// <param name="count">The number of elements to copy.</param>
internal void CopyTo(int index, T[] array, int arrayIndex, int count)
{
Requires.NotNull(array, nameof(array));
Requires.Range(index >= 0, nameof(index));
Requires.Range(count >= 0, nameof(count));
Requires.Range(index + count <= this.Count, nameof(count));
Requires.Range(arrayIndex >= 0, nameof(arrayIndex));
Requires.Range(arrayIndex + count <= array.Length, nameof(arrayIndex));
using (var enumerator = new Enumerator(this, startIndex: index, count: count))
{
while (enumerator.MoveNext())
{
array[arrayIndex++] = enumerator.Current;
}
}
}
/// <summary>
/// Copies the elements of the <see cref="ICollection"/> to an <see cref="Array"/>, starting at a particular <see cref="Array"/> index.
/// </summary>
/// <param name="array">The one-dimensional <see cref="Array"/> that is the destination of the elements copied from <see cref="ICollection"/>. The <see cref="Array"/> must have zero-based indexing.</param>
/// <param name="arrayIndex">The zero-based index in <paramref name="array"/> at which copying begins.</param>
internal void CopyTo(Array array, int arrayIndex)
{
Requires.NotNull(array, nameof(array));
Requires.Range(arrayIndex >= 0, nameof(arrayIndex));
Requires.Range(array.Length >= arrayIndex + this.Count, nameof(arrayIndex));
foreach (T element in this)
{
array.SetValue(element, arrayIndex++);
}
}
/// <summary>
/// Converts the elements in the current <see cref="ImmutableList{T}"/> to
/// another type, and returns a list containing the converted elements.
/// </summary>
/// <param name="converter">
/// A <see cref="Func{T, TResult}"/> delegate that converts each element from
/// one type to another type.
/// </param>
/// <typeparam name="TOutput">
/// The type of the elements of the target array.
/// </typeparam>
/// <returns>
/// A node tree with the transformed list.
/// </returns>
internal ImmutableList<TOutput>.Node ConvertAll<TOutput>(Func<T, TOutput> converter)
{
ImmutableList<TOutput>.Node root = ImmutableList<TOutput>.Node.EmptyNode;
if (this.IsEmpty)
{
return root;
}
return root.AddRange(Linq.Enumerable.Select(this, converter));
}
/// <summary>
/// Determines whether every element in the <see cref="ImmutableList{T}"/>
/// matches the conditions defined by the specified predicate.
/// </summary>
/// <param name="match">
/// The <see cref="Predicate{T}"/> delegate that defines the conditions to check against
/// the elements.
/// </param>
/// <returns>
/// true if every element in the <see cref="ImmutableList{T}"/> matches the
/// conditions defined by the specified predicate; otherwise, false. If the list
/// has no elements, the return value is true.
/// </returns>
internal bool TrueForAll(Predicate<T> match)
{
Requires.NotNull(match, nameof(match));
foreach (T item in this)
{
if (!match(item))
{
return false;
}
}
return true;
}
/// <summary>
/// Determines whether the <see cref="ImmutableList{T}"/> contains elements
/// that match the conditions defined by the specified predicate.
/// </summary>
/// <param name="match">
/// The <see cref="Predicate{T}"/> delegate that defines the conditions of the elements