/
SortedList.cs
1225 lines (1068 loc) · 41.5 KB
/
SortedList.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.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
namespace System.Collections.Generic
{
// The SortedDictionary class implements a generic sorted list of keys
// and values. Entries in a sorted list are sorted by their keys and
// are accessible both by key and by index. The keys of a sorted dictionary
// can be ordered either according to a specific IComparer
// implementation given when the sorted dictionary is instantiated, or
// according to the IComparable implementation provided by the keys
// themselves. In either case, a sorted dictionary does not allow entries
// with duplicate or null keys.
//
// A sorted list internally maintains two arrays that store the keys and
// values of the entries. The capacity of a sorted list is the allocated
// length of these internal arrays. As elements are added to a sorted list, the
// capacity of the sorted list is automatically increased as required by
// reallocating the internal arrays. The capacity is never automatically
// decreased, but users can call either TrimExcess or
// Capacity explicitly.
//
// The GetKeyList and GetValueList methods of a sorted list
// provides access to the keys and values of the sorted list in the form of
// List implementations. The List objects returned by these
// methods are aliases for the underlying sorted list, so modifications
// made to those lists are directly reflected in the sorted list, and vice
// versa.
//
// The SortedList class provides a convenient way to create a sorted
// copy of another dictionary, such as a Hashtable. For example:
//
// Hashtable h = new Hashtable();
// h.Add(...);
// h.Add(...);
// ...
// SortedList s = new SortedList(h);
//
// The last line above creates a sorted list that contains a copy of the keys
// and values stored in the hashtable. In this particular example, the keys
// will be ordered according to the IComparable interface, which they
// all must implement. To impose a different ordering, SortedList also
// has a constructor that allows a specific IComparer implementation to
// be specified.
//
[DebuggerTypeProxy(typeof(IDictionaryDebugView<,>))]
[DebuggerDisplay("Count = {Count}")]
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public class SortedList<TKey, TValue> :
IDictionary<TKey, TValue>, IDictionary, IReadOnlyDictionary<TKey, TValue> where TKey : notnull
{
private TKey[] keys; // Do not rename (binary serialization)
private TValue[] values; // Do not rename (binary serialization)
private int _size; // Do not rename (binary serialization)
private int version; // Do not rename (binary serialization)
private readonly IComparer<TKey> comparer; // Do not rename (binary serialization)
private KeyList? keyList; // Do not rename (binary serialization)
private ValueList? valueList; // Do not rename (binary serialization)
private const int DefaultCapacity = 4;
// Constructs a new sorted list. The sorted list is initially empty and has
// a capacity of zero. Upon adding the first element to the sorted list the
// capacity is increased to DefaultCapacity, and then increased in multiples of two as
// required. The elements of the sorted list are ordered according to the
// IComparable interface, which must be implemented by the keys of
// all entries added to the sorted list.
public SortedList()
{
keys = Array.Empty<TKey>();
values = Array.Empty<TValue>();
_size = 0;
comparer = Comparer<TKey>.Default;
}
// Constructs a new sorted list. The sorted list is initially empty and has
// a capacity of zero. Upon adding the first element to the sorted list the
// capacity is increased to 16, and then increased in multiples of two as
// required. The elements of the sorted list are ordered according to the
// IComparable interface, which must be implemented by the keys of
// all entries added to the sorted list.
//
public SortedList(int capacity)
{
if (capacity < 0)
throw new ArgumentOutOfRangeException(nameof(capacity), capacity, SR.ArgumentOutOfRange_NeedNonNegNum);
keys = new TKey[capacity];
values = new TValue[capacity];
comparer = Comparer<TKey>.Default;
}
// Constructs a new sorted list with a given IComparer
// implementation. The sorted list is initially empty and has a capacity of
// zero. Upon adding the first element to the sorted list the capacity is
// increased to 16, and then increased in multiples of two as required. The
// elements of the sorted list are ordered according to the given
// IComparer implementation. If comparer is null, the
// elements are compared to each other using the IComparable
// interface, which in that case must be implemented by the keys of all
// entries added to the sorted list.
//
public SortedList(IComparer<TKey>? comparer)
: this()
{
if (comparer != null)
{
this.comparer = comparer;
}
}
// Constructs a new sorted dictionary with a given IComparer
// implementation and a given initial capacity. The sorted list is
// initially empty, but will have room for the given number of elements
// before any reallocations are required. The elements of the sorted list
// are ordered according to the given IComparer implementation. If
// comparer is null, the elements are compared to each other using
// the IComparable interface, which in that case must be implemented
// by the keys of all entries added to the sorted list.
//
public SortedList(int capacity, IComparer<TKey>? comparer)
: this(comparer)
{
Capacity = capacity;
}
// Constructs a new sorted list containing a copy of the entries in the
// given dictionary. The elements of the sorted list are ordered according
// to the IComparable interface, which must be implemented by the
// keys of all entries in the given dictionary as well as keys
// subsequently added to the sorted list.
//
public SortedList(IDictionary<TKey, TValue> dictionary)
: this(dictionary, null)
{
}
// Constructs a new sorted list containing a copy of the entries in the
// given dictionary. The elements of the sorted list are ordered according
// to the given IComparer implementation. If comparer is
// null, the elements are compared to each other using the
// IComparable interface, which in that case must be implemented
// by the keys of all entries in the given dictionary as well as keys
// subsequently added to the sorted list.
//
public SortedList(IDictionary<TKey, TValue> dictionary, IComparer<TKey>? comparer)
: this(dictionary?.Count ?? throw new ArgumentNullException(nameof(dictionary)), comparer)
{
int count = dictionary.Count;
if (count != 0)
{
TKey[] keys = this.keys;
dictionary.Keys.CopyTo(keys, 0);
dictionary.Values.CopyTo(values, 0);
Debug.Assert(count == this.keys.Length);
if (count > 1)
{
comparer = Comparer; // obtain default if this is null.
Array.Sort<TKey, TValue>(keys, values, comparer);
for (int i = 1; i != keys.Length; ++i)
{
if (comparer.Compare(keys[i - 1], keys[i]) == 0)
{
throw new ArgumentException(SR.Format(SR.Argument_AddingDuplicate, keys[i]));
}
}
}
}
_size = count;
}
// Adds an entry with the given key and value to this sorted list. An
// ArgumentException is thrown if the key is already present in the sorted list.
//
public void Add(TKey key, TValue value)
{
ArgumentNullException.ThrowIfNull(key);
int i = Array.BinarySearch<TKey>(keys, 0, _size, key, comparer);
if (i >= 0)
throw new ArgumentException(SR.Format(SR.Argument_AddingDuplicate, key), nameof(key));
Insert(~i, key, value);
}
void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> keyValuePair)
{
Add(keyValuePair.Key, keyValuePair.Value);
}
bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> keyValuePair)
{
int index = IndexOfKey(keyValuePair.Key);
if (index >= 0 && EqualityComparer<TValue>.Default.Equals(values[index], keyValuePair.Value))
{
return true;
}
return false;
}
bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> keyValuePair)
{
int index = IndexOfKey(keyValuePair.Key);
if (index >= 0 && EqualityComparer<TValue>.Default.Equals(values[index], keyValuePair.Value))
{
RemoveAt(index);
return true;
}
return false;
}
// Returns the capacity of this sorted list. The capacity of a sorted list
// represents the allocated length of the internal arrays used to store the
// keys and values of the list, and thus also indicates the maximum number
// of entries the list can contain before a reallocation of the internal
// arrays is required.
//
public int Capacity
{
get
{
return keys.Length;
}
set
{
if (value != keys.Length)
{
if (value < _size)
{
throw new ArgumentOutOfRangeException(nameof(value), value, SR.ArgumentOutOfRange_SmallCapacity);
}
if (value > 0)
{
TKey[] newKeys = new TKey[value];
TValue[] newValues = new TValue[value];
if (_size > 0)
{
Array.Copy(keys, newKeys, _size);
Array.Copy(values, newValues, _size);
}
keys = newKeys;
values = newValues;
}
else
{
keys = Array.Empty<TKey>();
values = Array.Empty<TValue>();
}
}
}
}
public IComparer<TKey> Comparer
{
get
{
return comparer;
}
}
void IDictionary.Add(object key, object? value)
{
ArgumentNullException.ThrowIfNull(key);
if (value == null && default(TValue) != null) // null is an invalid value for Value types
throw new ArgumentNullException(nameof(value));
if (!(key is TKey))
throw new ArgumentException(SR.Format(SR.Arg_WrongType, key, typeof(TKey)), nameof(key));
if (!(value is TValue) && value != null) // null is a valid value for Reference Types
throw new ArgumentException(SR.Format(SR.Arg_WrongType, value, typeof(TValue)), nameof(value));
Add((TKey)key, (TValue)value!);
}
// Returns the number of entries in this sorted list.
public int Count
{
get
{
return _size;
}
}
// Returns a collection representing the keys of this sorted list. This
// method returns the same object as GetKeyList, but typed as an
// ICollection instead of an IList.
public IList<TKey> Keys
{
get
{
return GetKeyListHelper();
}
}
ICollection<TKey> IDictionary<TKey, TValue>.Keys
{
get
{
return GetKeyListHelper();
}
}
ICollection IDictionary.Keys
{
get
{
return GetKeyListHelper();
}
}
IEnumerable<TKey> IReadOnlyDictionary<TKey, TValue>.Keys
{
get
{
return GetKeyListHelper();
}
}
// Returns a collection representing the values of this sorted list. This
// method returns the same object as GetValueList, but typed as an
// ICollection instead of an IList.
//
public IList<TValue> Values
{
get
{
return GetValueListHelper();
}
}
ICollection<TValue> IDictionary<TKey, TValue>.Values
{
get
{
return GetValueListHelper();
}
}
ICollection IDictionary.Values
{
get
{
return GetValueListHelper();
}
}
IEnumerable<TValue> IReadOnlyDictionary<TKey, TValue>.Values
{
get
{
return GetValueListHelper();
}
}
private KeyList GetKeyListHelper() => keyList ??= new KeyList(this);
private ValueList GetValueListHelper() => valueList ??= new ValueList(this);
bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly
{
get { return false; }
}
bool IDictionary.IsReadOnly
{
get { return false; }
}
bool IDictionary.IsFixedSize
{
get { return false; }
}
bool ICollection.IsSynchronized
{
get { return false; }
}
// Synchronization root for this object.
object ICollection.SyncRoot => this;
// Removes all entries from this sorted list.
public void Clear()
{
// clear does not change the capacity
version++;
// Don't need to doc this but we clear the elements so that the gc can reclaim the references.
if (RuntimeHelpers.IsReferenceOrContainsReferences<TKey>())
{
Array.Clear(keys, 0, _size);
}
if (RuntimeHelpers.IsReferenceOrContainsReferences<TValue>())
{
Array.Clear(values, 0, _size);
}
_size = 0;
}
bool IDictionary.Contains(object key)
{
if (IsCompatibleKey(key))
{
return ContainsKey((TKey)key);
}
return false;
}
// Checks if this sorted list contains an entry with the given key.
public bool ContainsKey(TKey key)
{
return IndexOfKey(key) >= 0;
}
// Checks if this sorted list contains an entry with the given value. The
// values of the entries of the sorted list are compared to the given value
// using the Object.Equals method. This method performs a linear
// search and is substantially slower than the Contains
// method.
public bool ContainsValue(TValue value)
{
return IndexOfValue(value) >= 0;
}
// Copies the values in this SortedList to an array.
void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
{
ArgumentNullException.ThrowIfNull(array);
if (arrayIndex < 0 || arrayIndex > array.Length)
{
throw new ArgumentOutOfRangeException(nameof(arrayIndex), arrayIndex, SR.ArgumentOutOfRange_IndexMustBeLessOrEqual);
}
if (array.Length - arrayIndex < Count)
{
throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall);
}
for (int i = 0; i < Count; i++)
{
KeyValuePair<TKey, TValue> entry = new KeyValuePair<TKey, TValue>(keys[i], values[i]);
array[arrayIndex + i] = entry;
}
}
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));
}
if (index < 0 || index > array.Length)
{
throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_IndexMustBeLessOrEqual);
}
if (array.Length - index < Count)
{
throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall);
}
if (array is KeyValuePair<TKey, TValue>[] keyValuePairArray)
{
for (int i = 0; i < Count; i++)
{
keyValuePairArray[i + index] = new KeyValuePair<TKey, TValue>(keys[i], values[i]);
}
}
else
{
object[]? objects = array as object[];
if (objects == null)
{
throw new ArgumentException(SR.Argument_InvalidArrayType, nameof(array));
}
try
{
for (int i = 0; i < Count; i++)
{
objects[i + index] = new KeyValuePair<TKey, TValue>(keys[i], values[i]);
}
}
catch (ArrayTypeMismatchException)
{
throw new ArgumentException(SR.Argument_InvalidArrayType, nameof(array));
}
}
}
// Ensures that the capacity of this sorted list is at least the given
// minimum value. The capacity is increased to twice the current capacity
// or to min, whichever is larger.
private void EnsureCapacity(int min)
{
int newCapacity = keys.Length == 0 ? DefaultCapacity : keys.Length * 2;
// Allow the list to grow to maximum possible capacity (~2G elements) before encountering overflow.
// Note that this check works even when _items.Length overflowed thanks to the (uint) cast
if ((uint)newCapacity > Array.MaxLength) newCapacity = Array.MaxLength;
if (newCapacity < min) newCapacity = min;
Capacity = newCapacity;
}
// Returns the value of the entry at the given index.
public TValue GetValueAtIndex(int index)
{
if (index < 0 || index >= _size)
throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_IndexMustBeLess);
return values[index];
}
// Sets the value of the entry at the given index.
public void SetValueAtIndex(int index, TValue value)
{
if (index < 0 || index >= _size)
throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_IndexMustBeLess);
values[index] = value;
version++;
}
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
{
return new Enumerator(this, Enumerator.KeyValuePair);
}
IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator()
{
return new Enumerator(this, Enumerator.KeyValuePair);
}
IDictionaryEnumerator IDictionary.GetEnumerator()
{
return new Enumerator(this, Enumerator.DictEntry);
}
IEnumerator IEnumerable.GetEnumerator()
{
return new Enumerator(this, Enumerator.KeyValuePair);
}
// Returns the key of the entry at the given index.
public TKey GetKeyAtIndex(int index)
{
if (index < 0 || index >= _size)
throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_IndexMustBeLess);
return keys[index];
}
// Returns the value associated with the given key. If an entry with the
// given key is not found, the returned value is null.
public TValue this[TKey key]
{
get
{
int i = IndexOfKey(key);
if (i >= 0)
return values[i];
throw new KeyNotFoundException(SR.Format(SR.Arg_KeyNotFoundWithKey, key.ToString()));
}
set
{
if (key == null) throw new ArgumentNullException(nameof(key));
int i = Array.BinarySearch<TKey>(keys, 0, _size, key, comparer);
if (i >= 0)
{
values[i] = value;
version++;
return;
}
Insert(~i, key, value);
}
}
object? IDictionary.this[object key]
{
get
{
if (IsCompatibleKey(key))
{
int i = IndexOfKey((TKey)key);
if (i >= 0)
{
return values[i];
}
}
return null;
}
set
{
if (!IsCompatibleKey(key))
{
throw new ArgumentNullException(nameof(key));
}
if (value == null && default(TValue) != null)
throw new ArgumentNullException(nameof(value));
TKey tempKey = (TKey)key;
try
{
this[tempKey] = (TValue)value!;
}
catch (InvalidCastException)
{
throw new ArgumentException(SR.Format(SR.Arg_WrongType, value, typeof(TValue)), nameof(value));
}
}
}
// Returns the index of the entry with a given key in this sorted list. The
// key is located through a binary search, and thus the average execution
// time of this method is proportional to Log2(size), where
// size is the size of this sorted list. The returned value is -1 if
// the given key does not occur in this sorted list. Null is an invalid
// key value.
public int IndexOfKey(TKey key)
{
ArgumentNullException.ThrowIfNull(key);
int ret = Array.BinarySearch<TKey>(keys, 0, _size, key, comparer);
return ret >= 0 ? ret : -1;
}
// Returns the index of the first occurrence of an entry with a given value
// in this sorted list. The entry is located through a linear search, and
// thus the average execution time of this method is proportional to the
// size of this sorted list. The elements of the list are compared to the
// given value using the Object.Equals method.
public int IndexOfValue(TValue value)
{
return Array.IndexOf(values, value, 0, _size);
}
// Inserts an entry with a given key and value at a given index.
private void Insert(int index, TKey key, TValue value)
{
if (_size == keys.Length) EnsureCapacity(_size + 1);
if (index < _size)
{
Array.Copy(keys, index, keys, index + 1, _size - index);
Array.Copy(values, index, values, index + 1, _size - index);
}
keys[index] = key;
values[index] = value;
_size++;
version++;
}
public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value)
{
int i = IndexOfKey(key);
if (i >= 0)
{
value = values[i];
return true;
}
value = default;
return false;
}
// Removes the entry at the given index. The size of the sorted list is
// decreased by one.
public void RemoveAt(int index)
{
if (index < 0 || index >= _size)
throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_IndexMustBeLess);
_size--;
if (index < _size)
{
Array.Copy(keys, index + 1, keys, index, _size - index);
Array.Copy(values, index + 1, values, index, _size - index);
}
if (RuntimeHelpers.IsReferenceOrContainsReferences<TKey>())
{
keys[_size] = default(TKey)!;
}
if (RuntimeHelpers.IsReferenceOrContainsReferences<TValue>())
{
values[_size] = default(TValue)!;
}
version++;
}
// Removes an entry from this sorted list. If an entry with the specified
// key exists in the sorted list, it is removed. An ArgumentException is
// thrown if the key is null.
public bool Remove(TKey key)
{
int i = IndexOfKey(key);
if (i >= 0)
RemoveAt(i);
return i >= 0;
}
void IDictionary.Remove(object key)
{
if (IsCompatibleKey(key))
{
Remove((TKey)key);
}
}
// Sets the capacity of this sorted list to the size of the sorted list.
// This method can be used to minimize a sorted list's memory overhead once
// it is known that no new elements will be added to the sorted list. To
// completely clear a sorted list and release all memory referenced by the
// sorted list, execute the following statements:
//
// SortedList.Clear();
// SortedList.TrimExcess();
public void TrimExcess()
{
int threshold = (int)(keys.Length * 0.9);
if (_size < threshold)
{
Capacity = _size;
}
}
private static bool IsCompatibleKey(object key)
{
ArgumentNullException.ThrowIfNull(key);
return (key is TKey);
}
private struct Enumerator : IEnumerator<KeyValuePair<TKey, TValue>>, IDictionaryEnumerator
{
private readonly SortedList<TKey, TValue> _sortedList;
private TKey? _key;
private TValue? _value;
private int _index;
private readonly int _version;
private readonly int _getEnumeratorRetType; // What should Enumerator.Current return?
internal const int KeyValuePair = 1;
internal const int DictEntry = 2;
internal Enumerator(SortedList<TKey, TValue> sortedList, int getEnumeratorRetType)
{
_sortedList = sortedList;
_index = 0;
_version = _sortedList.version;
_getEnumeratorRetType = getEnumeratorRetType;
_key = default;
_value = default;
}
public void Dispose()
{
_index = 0;
_key = default;
_value = default;
}
object IDictionaryEnumerator.Key
{
get
{
if (_index == 0 || (_index == _sortedList.Count + 1))
{
throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen);
}
return _key!;
}
}
public bool MoveNext()
{
if (_version != _sortedList.version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
if ((uint)_index < (uint)_sortedList.Count)
{
_key = _sortedList.keys[_index];
_value = _sortedList.values[_index];
_index++;
return true;
}
_index = _sortedList.Count + 1;
_key = default;
_value = default;
return false;
}
DictionaryEntry IDictionaryEnumerator.Entry
{
get
{
if (_index == 0 || (_index == _sortedList.Count + 1))
{
throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen);
}
return new DictionaryEntry(_key!, _value);
}
}
public KeyValuePair<TKey, TValue> Current => new KeyValuePair<TKey, TValue>(_key!, _value!);
object? IEnumerator.Current
{
get
{
if (_index == 0 || (_index == _sortedList.Count + 1))
{
throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen);
}
if (_getEnumeratorRetType == DictEntry)
{
return new DictionaryEntry(_key!, _value);
}
else
{
return new KeyValuePair<TKey, TValue>(_key!, _value!);
}
}
}
object? IDictionaryEnumerator.Value
{
get
{
if (_index == 0 || (_index == _sortedList.Count + 1))
{
throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen);
}
return _value;
}
}
void IEnumerator.Reset()
{
if (_version != _sortedList.version)
{
throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
}
_index = 0;
_key = default;
_value = default;
}
}
private sealed class SortedListKeyEnumerator : IEnumerator<TKey>, IEnumerator
{
private readonly SortedList<TKey, TValue> _sortedList;
private int _index;
private readonly int _version;
private TKey? _currentKey;
internal SortedListKeyEnumerator(SortedList<TKey, TValue> sortedList)
{
_sortedList = sortedList;
_version = sortedList.version;
}
public void Dispose()
{
_index = 0;
_currentKey = default;
}
public bool MoveNext()
{
if (_version != _sortedList.version)
{
throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
}
if ((uint)_index < (uint)_sortedList.Count)
{
_currentKey = _sortedList.keys[_index];
_index++;
return true;
}
_index = _sortedList.Count + 1;
_currentKey = default;
return false;
}
public TKey Current => _currentKey!;
object? IEnumerator.Current
{
get
{
if (_index == 0 || (_index == _sortedList.Count + 1))
{
throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen);
}
return _currentKey;
}
}
void IEnumerator.Reset()
{
if (_version != _sortedList.version)
{
throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
}
_index = 0;
_currentKey = default;
}
}
private sealed class SortedListValueEnumerator : IEnumerator<TValue>, IEnumerator
{
private readonly SortedList<TKey, TValue> _sortedList;
private int _index;
private readonly int _version;
private TValue? _currentValue;
internal SortedListValueEnumerator(SortedList<TKey, TValue> sortedList)
{
_sortedList = sortedList;
_version = sortedList.version;
}
public void Dispose()
{
_index = 0;
_currentValue = default;
}
public bool MoveNext()
{
if (_version != _sortedList.version)
{
throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
}
if ((uint)_index < (uint)_sortedList.Count)
{
_currentValue = _sortedList.values[_index];
_index++;
return true;
}
_index = _sortedList.Count + 1;
_currentValue = default;
return false;
}
public TValue Current => _currentValue!;
object? IEnumerator.Current
{
get
{
if (_index == 0 || (_index == _sortedList.Count + 1))
{
throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen);
}
return _currentValue;
}
}
void IEnumerator.Reset()
{
if (_version != _sortedList.version)
{
throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
}
_index = 0;
_currentValue = default;
}
}
[DebuggerTypeProxy(typeof(DictionaryKeyCollectionDebugView<,>))]
[DebuggerDisplay("Count = {Count}")]
[Serializable]
public sealed class KeyList : IList<TKey>, ICollection
{
private readonly SortedList<TKey, TValue> _dict; // Do not rename (binary serialization)