-
Notifications
You must be signed in to change notification settings - Fork 0
/
Dictionary.cs
1932 lines (1624 loc) · 77.7 KB
/
Dictionary.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;
// using System.Runtime.Serialization;
// namespace System.Collections.Generic
// {
// [DebuggerTypeProxy(typeof(IDictionaryDebugView<,>))]
// [DebuggerDisplay("Count = {Count}")]
// [Serializable]
// [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
// public class Dictionary<TKey, TValue> : IDictionary<TKey, TValue>, IDictionary, IReadOnlyDictionary<TKey, TValue>, ISerializable, IDeserializationCallback where TKey : notnull
// {
// // constants for serialization
// private const string VersionName = "Version"; // Do not rename (binary serialization)
// private const string HashSizeName = "HashSize"; // Do not rename (binary serialization). Must save buckets.Length
// private const string KeyValuePairsName = "KeyValuePairs"; // Do not rename (binary serialization)
// private const string ComparerName = "Comparer"; // Do not rename (binary serialization)
// 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<TKey>? _comparer;
// private KeyCollection? _keys;
// private ValueCollection? _values;
// private const int StartOfFreeList = -3;
// public Dictionary() : this(0, null) { }
// public Dictionary(int capacity) : this(capacity, null) { }
// public Dictionary(IEqualityComparer<TKey>? comparer) : this(0, comparer) { }
// public Dictionary(int capacity, IEqualityComparer<TKey>? comparer)
// {
// if (capacity < 0)
// {
// ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.capacity);
// }
// if (capacity > 0)
// {
// Initialize(capacity);
// }
// if (comparer is not null && comparer != EqualityComparer<TKey>.Default) // first check for null to avoid forcing default comparer instantiation unnecessarily
// {
// _comparer = comparer;
// }
// // 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(TKey) == typeof(string))
// {
// IEqualityComparer<string>? stringComparer = NonRandomizedStringEqualityComparer.GetStringComparer(_comparer);
// if (stringComparer is not null)
// {
// _comparer = (IEqualityComparer<TKey>?)stringComparer;
// }
// }
// }
// public Dictionary(IDictionary<TKey, TValue> dictionary) : this(dictionary, null) { }
// public Dictionary(IDictionary<TKey, TValue> dictionary, IEqualityComparer<TKey>? comparer) :
// this(dictionary != null ? dictionary.Count : 0, comparer)
// {
// if (dictionary == null)
// {
// ThrowHelper.ThrowArgumentNullException(ExceptionArgument.dictionary);
// }
// AddRange(dictionary);
// }
// public Dictionary(IEnumerable<KeyValuePair<TKey, TValue>> collection) : this(collection, null) { }
// public Dictionary(IEnumerable<KeyValuePair<TKey, TValue>> collection, IEqualityComparer<TKey>? comparer) :
// this((collection as ICollection<KeyValuePair<TKey, TValue>>)?.Count ?? 0, comparer)
// {
// if (collection == null)
// {
// ThrowHelper.ThrowArgumentNullException(ExceptionArgument.collection);
// }
// AddRange(collection);
// }
// private void AddRange(IEnumerable<KeyValuePair<TKey, TValue>> collection)
// {
// // It is likely that the passed-in dictionary is Dictionary<TKey,TValue>. When this is the case,
// // avoid the enumerator allocation and overhead by looping through the entries array directly.
// // We only do this when dictionary is Dictionary<TKey,TValue> and not a subclass, to maintain
// // back-compat with subclasses that may have overridden the enumerator behavior.
// // TODO: use `is`
// if (collection.GetType() == typeof(Dictionary<TKey, TValue>))
// {
// Dictionary<TKey, TValue> source = (Dictionary<TKey, TValue>)collection;
// if (source.Count == 0)
// {
// // Nothing to copy, all done
// return;
// }
// // This is not currently a true .AddRange as it needs to be an initalized dictionary
// // of the correct size, and also an empty dictionary with no current entities (and no argument checks).
// Debug.Assert(source._entries is not null);
// Debug.Assert(_entries is not null);
// Debug.Assert(_entries.Length >= source.Count);
// Debug.Assert(_count == 0);
// Entry[] oldEntries = source._entries;
// if (source._comparer == _comparer)
// {
// // If comparers are the same, we can copy _entries without rehashing.
// CopyEntries(oldEntries, source._count);
// return;
// }
// // Comparers differ need to rehash all the entires via Add
// int count = source._count;
// for (int i = 0; i < count; i++)
// {
// // Only copy if an entry
// if (oldEntries[i].next >= -1)
// {
// Add(oldEntries[i].key, oldEntries[i].value);
// }
// }
// return;
// }
// // Fallback path for IEnumerable that isn't a non-subclassed Dictionary<TKey,TValue>.
// foreach (KeyValuePair<TKey, TValue> pair in collection)
// {
// Add(pair.Key, pair.Value);
// }
// }
// protected Dictionary(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 resonable 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);
// }
// public IEqualityComparer<TKey> Comparer
// {
// get
// {
// if (typeof(TKey) == typeof(string))
// {
// return (IEqualityComparer<TKey>)IInternalStringEqualityComparer.GetUnderlyingEqualityComparer((IEqualityComparer<string?>?)_comparer);
// }
// else
// {
// return _comparer ?? EqualityComparer<TKey>.Default;
// }
// }
// }
// public int Count => _count - _freeCount;
// public KeyCollection Keys => _keys ??= new KeyCollection(this);
// ICollection<TKey> IDictionary<TKey, TValue>.Keys => Keys;
// IEnumerable<TKey> IReadOnlyDictionary<TKey, TValue>.Keys => Keys;
// public ValueCollection Values => _values ??= new ValueCollection(this);
// ICollection<TValue> IDictionary<TKey, TValue>.Values => Values;
// IEnumerable<TValue> IReadOnlyDictionary<TKey, TValue>.Values => Values;
// public TValue this[TKey key]
// {
// get
// {
// ref TValue value = ref FindValue(key);
// if (!Unsafe.IsNullRef(ref value))
// {
// return value;
// }
// ThrowHelper.ThrowKeyNotFoundException(key);
// return default;
// }
// set
// {
// bool modified = TryInsert(key, value, InsertionBehavior.OverwriteExisting);
// Debug.Assert(modified);
// }
// }
// public void Add(TKey key, TValue value)
// {
// bool modified = TryInsert(key, value, InsertionBehavior.ThrowOnExisting);
// Debug.Assert(modified); // If there was an existing key and the Add failed, an exception will already have been thrown.
// }
// 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)
// {
// ref TValue value = ref FindValue(keyValuePair.Key);
// if (!Unsafe.IsNullRef(ref value) && EqualityComparer<TValue>.Default.Equals(value, keyValuePair.Value))
// {
// return true;
// }
// return false;
// }
// bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> keyValuePair)
// {
// ref TValue value = ref FindValue(keyValuePair.Key);
// if (!Unsafe.IsNullRef(ref value) && EqualityComparer<TValue>.Default.Equals(value, keyValuePair.Value))
// {
// Remove(keyValuePair.Key);
// return true;
// }
// return false;
// }
// 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);
// }
// }
// public bool ContainsKey(TKey key) =>
// !Unsafe.IsNullRef(ref FindValue(key));
// public bool ContainsValue(TValue value)
// {
// Entry[]? entries = _entries;
// if (value == null)
// {
// for (int i = 0; i < _count; i++)
// {
// if (entries![i].next >= -1 && entries[i].value == null)
// {
// return true;
// }
// }
// }
// else if (typeof(TValue).IsValueType)
// {
// // ValueType: Devirtualize with EqualityComparer<TValue>.Default intrinsic
// for (int i = 0; i < _count; i++)
// {
// if (entries![i].next >= -1 && EqualityComparer<TValue>.Default.Equals(entries[i].value, value))
// {
// return true;
// }
// }
// }
// else
// {
// // Object type: Shared Generic, EqualityComparer<TValue>.Default won't devirtualize
// // https://github.com/dotnet/runtime/issues/10050
// // So cache in a local rather than get EqualityComparer per loop iteration
// EqualityComparer<TValue> defaultComparer = EqualityComparer<TValue>.Default;
// for (int i = 0; i < _count; i++)
// {
// if (entries![i].next >= -1 && defaultComparer.Equals(entries[i].value, value))
// {
// return true;
// }
// }
// }
// return false;
// }
// private void CopyTo(KeyValuePair<TKey, TValue>[] array, int index)
// {
// if (array == null)
// {
// ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
// }
// if ((uint)index > (uint)array.Length)
// {
// ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
// }
// if (array.Length - index < Count)
// {
// ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
// }
// int count = _count;
// Entry[]? entries = _entries;
// for (int i = 0; i < count; i++)
// {
// if (entries![i].next >= -1)
// {
// array[index++] = new KeyValuePair<TKey, TValue>(entries[i].key, entries[i].value);
// }
// }
// }
// public Enumerator GetEnumerator() => new Enumerator(this, Enumerator.KeyValuePair);
// IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator() =>
// new Enumerator(this, Enumerator.KeyValuePair);
// public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
// {
// if (info == null)
// {
// ThrowHelper.ThrowArgumentNullException(ExceptionArgument.info);
// }
// info.AddValue(VersionName, _version);
// info.AddValue(ComparerName, Comparer, typeof(IEqualityComparer<TKey>));
// info.AddValue(HashSizeName, _buckets == null ? 0 : _buckets.Length); // This is the length of the bucket array
// if (_buckets != null)
// {
// var array = new KeyValuePair<TKey, TValue>[Count];
// CopyTo(array, 0);
// info.AddValue(KeyValuePairsName, array, typeof(KeyValuePair<TKey, TValue>[]));
// }
// }
// internal ref TValue FindValue(TKey key)
// {
// if (key == null)
// {
// ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
// }
// ref Entry entry = ref Unsafe.NullRef<Entry>();
// if (_buckets != null)
// {
// Debug.Assert(_entries != null, "expected entries to be != null");
// IEqualityComparer<TKey>? comparer = _comparer;
// if (comparer == null)
// {
// uint hashCode = (uint)key.GetHashCode();
// int i = GetBucket(hashCode);
// Entry[]? entries = _entries;
// uint collisionCount = 0;
// if (typeof(TKey).IsValueType)
// {
// // ValueType: Devirtualize with EqualityComparer<TValue>.Default intrinsic
// 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 && EqualityComparer<TKey>.Default.Equals(entry.key, key))
// {
// 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;
// }
// else
// {
// // Object type: Shared Generic, EqualityComparer<TValue>.Default won't devirtualize
// // https://github.com/dotnet/runtime/issues/10050
// // So cache in a local rather than get EqualityComparer per loop iteration
// EqualityComparer<TKey> defaultComparer = EqualityComparer<TKey>.Default;
// 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 && defaultComparer.Equals(entry.key, key))
// {
// 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;
// }
// }
// else
// {
// uint hashCode = (uint)comparer.GetHashCode(key);
// int i = GetBucket(hashCode);
// Entry[]? entries = _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(entry.key, key))
// {
// 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 TValue value = ref entry.value;
// Return:
// return ref value;
// ReturnNotFound:
// value = ref Unsafe.NullRef<TValue>();
// goto Return;
// }
// private int Initialize(int capacity)
// {
// int size = HashHelpers.GetPrime(capacity);
// int[] buckets = new int[size];
// Entry[] entries = new Entry[size];
// // Assign member variables after both arrays allocated to guard against corruption from OOM if second fails
// _freeList = -1;
// #if TARGET_64BIT
// _fastModMultiplier = HashHelpers.GetFastModMultiplier((uint)size);
// #endif
// _buckets = buckets;
// _entries = entries;
// return size;
// }
// private bool TryInsert(TKey key, TValue value, InsertionBehavior behavior)
// {
// // NOTE: this method is mirrored in CollectionsMarshal.GetValueRefOrAddDefault below.
// // If you make any changes here, make sure to keep that version in sync as well.
// if (key == null)
// {
// ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
// }
// if (_buckets == null)
// {
// Initialize(0);
// }
// Debug.Assert(_buckets != null);
// Entry[]? entries = _entries;
// Debug.Assert(entries != null, "expected entries to be non-null");
// IEqualityComparer<TKey>? comparer = _comparer;
// uint hashCode = (uint)((comparer == null) ? key.GetHashCode() : comparer.GetHashCode(key));
// uint collisionCount = 0;
// ref int bucket = ref GetBucket(hashCode);
// int i = bucket - 1; // Value in _buckets is 1-based
// if (comparer == null)
// {
// if (typeof(TKey).IsValueType)
// {
// // ValueType: Devirtualize with EqualityComparer<TValue>.Default intrinsic
// while (true)
// {
// // Should be a while loop https://github.com/dotnet/runtime/issues/9422
// // Test uint in if rather than loop condition to drop range check for following array access
// if ((uint)i >= (uint)entries.Length)
// {
// break;
// }
// if (entries[i].hashCode == hashCode && EqualityComparer<TKey>.Default.Equals(entries[i].key, key))
// {
// if (behavior == InsertionBehavior.OverwriteExisting)
// {
// entries[i].value = value;
// return true;
// }
// if (behavior == InsertionBehavior.ThrowOnExisting)
// {
// ThrowHelper.ThrowAddingDuplicateWithKeyArgumentException(key);
// }
// return false;
// }
// i = entries[i].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();
// }
// }
// }
// else
// {
// // Object type: Shared Generic, EqualityComparer<TValue>.Default won't devirtualize
// // https://github.com/dotnet/runtime/issues/10050
// // So cache in a local rather than get EqualityComparer per loop iteration
// EqualityComparer<TKey> defaultComparer = EqualityComparer<TKey>.Default;
// while (true)
// {
// // Should be a while loop https://github.com/dotnet/runtime/issues/9422
// // Test uint in if rather than loop condition to drop range check for following array access
// if ((uint)i >= (uint)entries.Length)
// {
// break;
// }
// if (entries[i].hashCode == hashCode && defaultComparer.Equals(entries[i].key, key))
// {
// if (behavior == InsertionBehavior.OverwriteExisting)
// {
// entries[i].value = value;
// return true;
// }
// if (behavior == InsertionBehavior.ThrowOnExisting)
// {
// ThrowHelper.ThrowAddingDuplicateWithKeyArgumentException(key);
// }
// return false;
// }
// i = entries[i].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();
// }
// }
// }
// }
// else
// {
// while (true)
// {
// // Should be a while loop https://github.com/dotnet/runtime/issues/9422
// // Test uint in if rather than loop condition to drop range check for following array access
// if ((uint)i >= (uint)entries.Length)
// {
// break;
// }
// if (entries[i].hashCode == hashCode && comparer.Equals(entries[i].key, key))
// {
// if (behavior == InsertionBehavior.OverwriteExisting)
// {
// entries[i].value = value;
// return true;
// }
// if (behavior == InsertionBehavior.ThrowOnExisting)
// {
// ThrowHelper.ThrowAddingDuplicateWithKeyArgumentException(key);
// }
// return false;
// }
// i = entries[i].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();
// }
// }
// }
// int index;
// if (_freeCount > 0)
// {
// index = _freeList;
// Debug.Assert((StartOfFreeList - entries[_freeList].next) >= -1, "shouldn't overflow because `next` cannot underflow");
// _freeList = StartOfFreeList - entries[_freeList].next;
// _freeCount--;
// }
// else
// {
// int count = _count;
// if (count == entries.Length)
// {
// Resize();
// bucket = ref GetBucket(hashCode);
// }
// index = count;
// _count = count + 1;
// entries = _entries;
// }
// ref Entry entry = ref entries![index];
// entry.hashCode = hashCode;
// entry.next = bucket - 1; // Value in _buckets is 1-based
// entry.key = key;
// entry.value = value;
// bucket = index + 1; // Value in _buckets is 1-based
// _version++;
// // Value types never rehash
// if (!typeof(TKey).IsValueType && collisionCount > HashHelpers.HashCollisionThreshold && comparer is NonRandomizedStringEqualityComparer)
// {
// // If we hit the collision threshold we'll need to switch to the comparer which is using randomized string hashing
// // i.e. EqualityComparer<string>.Default.
// Resize(entries.Length, true);
// }
// return true;
// }
// /// <summary>
// /// A helper class containing APIs exposed through <see cref="Runtime.InteropServices.CollectionsMarshal"/>.
// /// These methods are relatively niche and only used in specific scenarios, so adding them in a separate type avoids
// /// the additional overhead on each <see cref="Dictionary{TKey, TValue}"/> instantiation, especially in AOT scenarios.
// /// </summary>
// internal static class CollectionsMarshalHelper
// {
// /// <inheritdoc cref="Runtime.InteropServices.CollectionsMarshal.GetValueRefOrAddDefault{TKey, TValue}(Dictionary{TKey, TValue}, TKey, out bool)"/>
// public static ref TValue? GetValueRefOrAddDefault(Dictionary<TKey, TValue> dictionary, TKey key, out bool exists)
// {
// // NOTE: this method is mirrored by Dictionary<TKey, TValue>.TryInsert above.
// // If you make any changes here, make sure to keep that version in sync as well.
// if (key == null)
// {
// ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
// }
// if (dictionary._buckets == null)
// {
// dictionary.Initialize(0);
// }
// Debug.Assert(dictionary._buckets != null);
// Entry[]? entries = dictionary._entries;
// Debug.Assert(entries != null, "expected entries to be non-null");
// IEqualityComparer<TKey>? comparer = dictionary._comparer;
// uint hashCode = (uint)((comparer == null) ? key.GetHashCode() : comparer.GetHashCode(key));
// uint collisionCount = 0;
// ref int bucket = ref dictionary.GetBucket(hashCode);
// int i = bucket - 1; // Value in _buckets is 1-based
// if (comparer == null)
// {
// if (typeof(TKey).IsValueType)
// {
// // ValueType: Devirtualize with EqualityComparer<TValue>.Default intrinsic
// while (true)
// {
// // Should be a while loop https://github.com/dotnet/runtime/issues/9422
// // Test uint in if rather than loop condition to drop range check for following array access
// if ((uint)i >= (uint)entries.Length)
// {
// break;
// }
// if (entries[i].hashCode == hashCode && EqualityComparer<TKey>.Default.Equals(entries[i].key, key))
// {
// exists = true;
// return ref entries[i].value!;
// }
// i = entries[i].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();
// }
// }
// }
// else
// {
// // Object type: Shared Generic, EqualityComparer<TValue>.Default won't devirtualize
// // https://github.com/dotnet/runtime/issues/10050
// // So cache in a local rather than get EqualityComparer per loop iteration
// EqualityComparer<TKey> defaultComparer = EqualityComparer<TKey>.Default;
// while (true)
// {
// // Should be a while loop https://github.com/dotnet/runtime/issues/9422
// // Test uint in if rather than loop condition to drop range check for following array access
// if ((uint)i >= (uint)entries.Length)
// {
// break;
// }
// if (entries[i].hashCode == hashCode && defaultComparer.Equals(entries[i].key, key))
// {
// exists = true;
// return ref entries[i].value!;
// }
// i = entries[i].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();
// }
// }
// }
// }
// else
// {
// while (true)
// {
// // Should be a while loop https://github.com/dotnet/runtime/issues/9422
// // Test uint in if rather than loop condition to drop range check for following array access
// if ((uint)i >= (uint)entries.Length)
// {
// break;
// }
// if (entries[i].hashCode == hashCode && comparer.Equals(entries[i].key, key))
// {
// exists = true;
// return ref entries[i].value!;
// }
// i = entries[i].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();
// }
// }
// }
// int index;
// if (dictionary._freeCount > 0)
// {
// index = dictionary._freeList;
// Debug.Assert((StartOfFreeList - entries[dictionary._freeList].next) >= -1, "shouldn't overflow because `next` cannot underflow");
// dictionary._freeList = StartOfFreeList - entries[dictionary._freeList].next;
// dictionary._freeCount--;
// }
// else
// {
// int count = dictionary._count;
// if (count == entries.Length)
// {
// dictionary.Resize();
// bucket = ref dictionary.GetBucket(hashCode);
// }
// index = count;
// dictionary._count = count + 1;
// entries = dictionary._entries;
// }
// ref Entry entry = ref entries![index];
// entry.hashCode = hashCode;
// entry.next = bucket - 1; // Value in _buckets is 1-based
// entry.key = key;
// entry.value = default!;
// bucket = index + 1; // Value in _buckets is 1-based
// dictionary._version++;
// // Value types never rehash
// if (!typeof(TKey).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.
// dictionary.Resize(entries.Length, true);
// exists = false;
// // At this point the entries array has been resized, so the current reference we have is no longer valid.
// // We're forced to do a new lookup and return an updated reference to the new entry instance. This new
// // lookup is guaranteed to always find a value though and it will never return a null reference here.
// ref TValue? value = ref dictionary.FindValue(key)!;
// Debug.Assert(!Unsafe.IsNullRef(ref value), "the lookup result cannot be a null ref here");
// return ref value;
// }
// exists = false;
// return ref entry.value!;
// }
// }
// public virtual void OnDeserialization(object? sender)
// {
// HashHelpers.SerializationInfoTable.TryGetValue(this, out SerializationInfo? siInfo);
// if (siInfo == null)
// {
// // We can return immediately if this function is called twice.
// // Note we remove the serialization info from the table at the end of this method.
// return;
// }
// int realVersion = siInfo.GetInt32(VersionName);
// int hashsize = siInfo.GetInt32(HashSizeName);
// _comparer = (IEqualityComparer<TKey>)siInfo.GetValue(ComparerName, typeof(IEqualityComparer<TKey>))!; // When serialized if comparer is null, we use the default.
// if (hashsize != 0)
// {
// Initialize(hashsize);
// KeyValuePair<TKey, TValue>[]? array = (KeyValuePair<TKey, TValue>[]?)
// siInfo.GetValue(KeyValuePairsName, typeof(KeyValuePair<TKey, TValue>[]));
// if (array == null)
// {
// ThrowHelper.ThrowSerializationException(ExceptionResource.Serialization_MissingKeys);
// }
// for (int i = 0; i < array.Length; i++)
// {
// if (array[i].Key == null)
// {
// ThrowHelper.ThrowSerializationException(ExceptionResource.Serialization_NullKey);
// }
// Add(array[i].Key, array[i].Value);
// }
// }
// else
// {
// _buckets = null;
// }
// _version = realVersion;
// HashHelpers.SerializationInfoTable.Remove(this);
// }
// private void Resize() => Resize(HashHelpers.ExpandPrime(_count), false);
// private void Resize(int newSize, bool forceNewHashCodes)
// {
// // Value types never rehash
// Debug.Assert(!forceNewHashCodes || !typeof(TKey).IsValueType);
// Debug.Assert(_entries != null, "_entries should be non-null");
// Debug.Assert(newSize >= _entries.Length);
// Entry[] entries = new Entry[newSize];
// int count = _count;
// Array.Copy(_entries, entries, count);
// if (!typeof(TKey).IsValueType && forceNewHashCodes)
// {
// Debug.Assert(_comparer is NonRandomizedStringEqualityComparer);
// _comparer = (IEqualityComparer<TKey>)((NonRandomizedStringEqualityComparer)_comparer).GetRandomizedEqualityComparer();
// for (int i = 0; i < count; i++)
// {
// if (entries[i].next >= -1)
// {
// entries[i].hashCode = (uint)_comparer.GetHashCode(entries[i].key);
// }
// }
// if (ReferenceEquals(_comparer, EqualityComparer<TKey>.Default))
// {
// _comparer = null;
// }
// }
// // Assign member variables after both arrays allocated to guard against corruption from OOM if second fails
// _buckets = new int[newSize];
// #if TARGET_64BIT
// _fastModMultiplier = HashHelpers.GetFastModMultiplier((uint)newSize);
// #endif
// for (int i = 0; i < count; i++)
// {
// if (entries[i].next >= -1)
// {
// ref int bucket = ref GetBucket(entries[i].hashCode);
// entries[i].next = bucket - 1; // Value in _buckets is 1-based
// bucket = i + 1;
// }
// }
// _entries = entries;
// }
// public bool Remove(TKey key)
// {
// // The overload Remove(TKey key, out TValue value) is a copy of this method with one additional
// // statement to copy the value for entry being removed into the output parameter.
// // Code has been intentionally duplicated for performance reasons.
// if (key == null)
// {
// ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
// }
// if (_buckets != null)
// {
// Debug.Assert(_entries != null, "entries should be non-null");
// uint collisionCount = 0;
// uint hashCode = (uint)(_comparer?.GetHashCode(key) ?? key.GetHashCode());
// ref int bucket = ref GetBucket(hashCode);
// Entry[]? entries = _entries;
// int last = -1;
// 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.key, key) ?? EqualityComparer<TKey>.Default.Equals(entry.key, key)))
// {
// if (last < 0)
// {
// bucket = entry.next + 1; // Value in buckets is 1-based
// }
// else
// {
// entries[last].next = entry.next;
// }