-
Notifications
You must be signed in to change notification settings - Fork 743
/
SpecializedResourceDictionary.cs
1447 lines (1219 loc) · 38.5 KB
/
SpecializedResourceDictionary.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.
// Imported from https://github.com/dotnet/runtime/blob/c7804d5b3c8bd32e35cbb674e8f275fcaf754d93/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/Dictionary.cs
#define TARGET_64BIT // Use runtime detection of 64bits target
#if !NET5_0_OR_GREATER // https://github.com/dotnet/designs/blob/be793b557255c9ed1276ecdd23119b64f45453bf/accepted/2020/or-greater-defines/or-greater-defines.md
#define HAS_CUSTOM_ISNULLREF
#endif
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using Uno.Foundation;
namespace Windows.UI.Xaml
{
/// <summary>
/// Specialized Dictionary for ResourceDictionary values backing, using <see cref="ResourceKey"/> for the dictionary key.
/// </summary>
internal class SpecializedResourceDictionary
{
/// <summary>
/// Represents a key for the source dictionary
/// </summary>
[DebuggerDisplay("Key={Key}")]
public readonly struct ResourceKey
{
public readonly string Key;
public readonly Type TypeKey;
public readonly uint HashCode;
public static ResourceKey Empty { get; } = new ResourceKey(false);
public bool IsEmpty => Key == null;
private ResourceKey(bool dummy)
{
Key = null;
TypeKey = null;
HashCode = 0;
}
/// <summary>
/// Builds a ResourceKey based on an unknown object
/// </summary>
/// <param name="key">The original key to use</param>
public ResourceKey(object key)
{
if (key is string s)
{
Key = s;
TypeKey = null;
HashCode = (uint)s.GetHashCode();
}
else if (key is Type t)
{
Key = t.FullName;
TypeKey = t;
HashCode = (uint)t.GetHashCode();
}
else if (key is ResourceKey)
{
// This should never happen. A ResourceKey should always be passed to a parameter of type ResourceKey via an appropriate method overload,
// rather than being passed as an object, for performance.
throw new InvalidOperationException($"Received {nameof(ResourceKey)} wrapped as object.");
}
else
{
Key = key.ToString();
TypeKey = null;
HashCode = (uint)key.GetHashCode();
}
}
/// <summary>
/// Builds a ResourceKey based on a string for faster creation
/// </summary>
/// <param name="key">A string typed key</param>
public ResourceKey(string key)
{
Key = key;
TypeKey = null;
HashCode = (uint)key.GetHashCode();
}
/// <summary>
/// Builds a ResourceKey based on a Type for faster creation
/// </summary>
/// <param name="key">A string typed key</param>
public ResourceKey(Type key)
{
Key = key.FullName;
TypeKey = key;
HashCode = (uint)key.GetHashCode();
}
/// <summary>
/// Compares this instance with another ResourceKey instance
/// </summary>
public bool Equals(in ResourceKey other)
=> TypeKey == other.TypeKey && Key == other.Key;
public static implicit operator ResourceKey(string key)
=> new ResourceKey(key);
public static implicit operator ResourceKey(Type key)
=> new ResourceKey(key);
}
private int[] _buckets;
private Entry[] _entries;
#if TARGET_64BIT
private ulong _fastModMultiplier;
private static bool Is64Bits = IntPtr.Size >= 8
#if __WASM__
|| WebAssemblyRuntime.IsWebAssembly;
#else
;
#endif
#endif
private int _count;
private int _freeList;
private int _freeCount;
private int _version;
private KeyCollection _keys;
private ValueCollection _values;
private const int StartOfFreeList = -3;
public SpecializedResourceDictionary() : this(0) { }
public SpecializedResourceDictionary(int capacity)
{
if (capacity < 0)
{
throw new ArgumentOutOfRangeException("ExceptionArgument.capacity");
}
if (capacity > 0)
{
Initialize(capacity);
}
}
public void AddRange(SpecializedResourceDictionary source)
{
// Fallback path for IEnumerable that isn't a non-subclassed Dictionary<TKey,TValue>.
foreach (KeyValuePair<ResourceKey, object> pair in source)
{
Add(pair.Key, pair.Value);
}
}
public int Count => _count - _freeCount;
public KeyCollection Keys => _keys ??= new KeyCollection(this);
public ValueCollection Values => _values ??= new ValueCollection(this);
public object this[in ResourceKey key]
{
get
{
ref object value = ref FindValue(key);
#if HAS_CUSTOM_ISNULLREF
if (!IsNullRef(ref value))
#else
if (!Unsafe.IsNullRef(ref value))
#endif
{
return value;
}
throw new KeyNotFoundException("key");
}
set
{
bool modified = TryInsert(key, value, InsertionBehavior.OverwriteExisting);
Debug.Assert(modified);
}
}
public void Add(in ResourceKey key, object 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.
}
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, 0, _buckets.Length);
_count = 0;
_freeList = -1;
_freeCount = 0;
Array.Clear(_entries, 0, count);
}
}
public bool ContainsKey(in ResourceKey key) =>
#if HAS_CUSTOM_ISNULLREF
!IsNullRef(ref FindValue(key));
#else
!Unsafe.IsNullRef(ref FindValue(key));
#endif
public bool ContainsValue(object 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(object).IsValueType)
{
// ValueType: Devirtualize with EqualityComparer<object>.Default intrinsic
for (int i = 0; i < _count; i++)
{
if (entries![i].next >= -1 && EqualityComparer<object>.Default.Equals(entries[i].value, value))
{
return true;
}
}
}
else
{
// Object type: Shared Generic, EqualityComparer<object>.Default won't devirtualize
// https://github.com/dotnet/runtime/issues/10050
// So cache in a local rather than get EqualityComparer per loop iteration
EqualityComparer<object> defaultComparer = EqualityComparer<object>.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<object, object>[] array, int index)
{
if (array == null)
{
throw new ArgumentNullException("ExceptionArgument.array");
}
if ((uint)index > (uint)array.Length)
{
throw new IndexOutOfRangeException("IndexArgumentOutOfRange_NeedNonNegNumException");
}
if (array.Length - index < Count)
{
throw new ArgumentException("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<object, object>(entries[i].key, entries[i].value);
}
}
}
public Enumerator GetEnumerator() => new Enumerator(this, Enumerator.KeyValuePair);
private ref object FindValue(in ResourceKey key)
{
#if HAS_CUSTOM_ISNULLREF
ref Entry entry = ref NullRef<Entry>();
#else
ref Entry entry = ref Unsafe.NullRef<Entry>();
#endif
if (_buckets != null)
{
Debug.Assert(_entries != null, "expected entries to be != null");
uint hashCode = key.HashCode;
int i = GetBucket(hashCode);
Entry[] entries = _entries;
uint length = (uint)entries.Length;
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 >= length)
{
goto ReturnNotFound;
}
entry = ref entries[i];
if (entry.hashCode == hashCode && entry.key.Equals(key))
{
goto ReturnFound;
}
i = entry.next;
collisionCount++;
} while (collisionCount <= 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:
throw new InvalidOperationException("ConcurrentOperationsNotSupported");
ReturnFound:
ref object value = ref entry.value;
Return:
return ref value;
ReturnNotFound:
#if HAS_CUSTOM_ISNULLREF
value = ref NullRef<object>();
#else
value = ref Unsafe.NullRef<object>();
#endif
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
if (Is64Bits)
{
_fastModMultiplier = HashHelpers.GetFastModMultiplier((uint)size);
}
#endif
_buckets = buckets;
_entries = entries;
return size;
}
private bool TryInsert(in ResourceKey key, object value, InsertionBehavior behavior)
{
if (_buckets == null)
{
Initialize(0);
}
Debug.Assert(_buckets != null);
Entry[] entries = _entries;
Debug.Assert(entries != null, "expected entries to be non-null");
uint hashCode = key.HashCode;
uint collisionCount = 0;
ref int bucket = ref GetBucket(hashCode);
int i = bucket - 1; // Value in _buckets is 1-based
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 && entries[i].key.Equals(key))
{
if (behavior == InsertionBehavior.OverwriteExisting)
{
entries[i].value = value;
return true;
}
if (behavior == InsertionBehavior.ThrowOnExisting)
{
throw new InvalidOperationException("AddingDuplicateWithKeyArgumentException(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.
throw new InvalidOperationException("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++;
return true;
}
private void Resize() => Resize(HashHelpers.ExpandPrime(_count), false);
private void Resize(int newSize, bool forceNewHashCodes)
{
// Value types never rehash
Debug.Assert(!forceNewHashCodes || !typeof(object).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);
// Assign member variables after both arrays allocated to guard against corruption from OOM if second fails
_buckets = new int[newSize];
#if TARGET_64BIT
if (Is64Bits)
{
_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(in ResourceKey key)
{
// The overload Remove(object key, out object 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 (_buckets != null)
{
Debug.Assert(_entries != null, "entries should be non-null");
uint collisionCount = 0;
uint hashCode = key.HashCode;
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 && entry.key.Equals(key))
{
if (last < 0)
{
bucket = entry.next + 1; // Value in buckets is 1-based
}
else
{
entries[last].next = entry.next;
}
Debug.Assert((StartOfFreeList - _freeList) < 0, "shouldn't underflow because max hashtable length is MaxPrimeArrayLength = 0x7FEFFFFD(2146435069) _freelist underflow threshold 2147483646");
entry.next = StartOfFreeList - _freeList;
//if (RuntimeHelpers.IsReferenceOrContainsReferences<object>())
{
entry.key = default!;
}
//if (RuntimeHelpers.IsReferenceOrContainsReferences<object>())
{
entry.value = default!;
}
_freeList = i;
_freeCount++;
return true;
}
last = i;
i = entry.next;
collisionCount++;
if (collisionCount > (uint)entries.Length)
{
// The chain of entries forms a loop; which means a concurrent update has happened.
// Break out of the loop and throw, rather than looping forever.
throw new InvalidOperationException("ConcurrentOperationsNotSupported");
}
}
}
return false;
}
public bool Remove(in ResourceKey key, out object value)
{
// This overload is a copy of the overload Remove(object key) 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 (_buckets != null)
{
Debug.Assert(_entries != null, "entries should be non-null");
uint collisionCount = 0;
uint hashCode = key.HashCode;
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 && entry.key.Equals(key))
{
if (last < 0)
{
bucket = entry.next + 1; // Value in buckets is 1-based
}
else
{
entries[last].next = entry.next;
}
value = entry.value;
Debug.Assert((StartOfFreeList - _freeList) < 0, "shouldn't underflow because max hashtable length is MaxPrimeArrayLength = 0x7FEFFFFD(2146435069) _freelist underflow threshold 2147483646");
entry.next = StartOfFreeList - _freeList;
//if (RuntimeHelpers.IsReferenceOrContainsReferences<object>())
{
entry.key = default!;
}
// if (RuntimeHelpers.IsReferenceOrContainsReferences<object>())
{
entry.value = default!;
}
_freeList = i;
_freeCount++;
return true;
}
last = i;
i = entry.next;
collisionCount++;
if (collisionCount > (uint)entries.Length)
{
// The chain of entries forms a loop; which means a concurrent update has happened.
// Break out of the loop and throw, rather than looping forever.
throw new InvalidOperationException("ConcurrentOperationsNotSupported()");
}
}
}
value = default;
return false;
}
public bool TryGetValue(in ResourceKey key, out object value)
{
ref object valRef = ref FindValue(key);
#if HAS_CUSTOM_ISNULLREF
if (!IsNullRef(ref valRef))
#else
if (!Unsafe.IsNullRef(ref valRef))
#endif
{
value = valRef;
return true;
}
value = default;
return false;
}
public bool TryAdd(in ResourceKey key, object value) =>
TryInsert(key, value, InsertionBehavior.None);
/// <summary>
/// Ensures that the dictionary can hold up to 'capacity' entries without any further expansion of its backing storage
/// </summary>
public int EnsureCapacity(int capacity)
{
if (capacity < 0)
{
throw new ArgumentOutOfRangeException("ExceptionArgument.capacity");
}
int currentCapacity = _entries == null ? 0 : _entries.Length;
if (currentCapacity >= capacity)
{
return currentCapacity;
}
_version++;
if (_buckets == null)
{
return Initialize(capacity);
}
int newSize = HashHelpers.GetPrime(capacity);
Resize(newSize, forceNewHashCodes: false);
return newSize;
}
/// <summary>
/// Sets the capacity of this dictionary to what it would be if it had been originally initialized with all its entries
/// </summary>
/// <remarks>
/// This method can be used to minimize the memory overhead
/// once it is known that no new elements will be added.
///
/// To allocate minimum size storage array, execute the following statements:
///
/// dictionary.Clear();
/// dictionary.TrimExcess();
/// </remarks>
public void TrimExcess() => TrimExcess(Count);
/// <summary>
/// Sets the capacity of this dictionary to hold up 'capacity' entries without any further expansion of its backing storage
/// </summary>
/// <remarks>
/// This method can be used to minimize the memory overhead
/// once it is known that no new elements will be added.
/// </remarks>
public void TrimExcess(int capacity)
{
if (capacity < Count)
{
throw new ArgumentOutOfRangeException("ExceptionArgument.capacity");
}
int newSize = HashHelpers.GetPrime(capacity);
Entry[] oldEntries = _entries;
int currentCapacity = oldEntries == null ? 0 : oldEntries.Length;
if (newSize >= currentCapacity)
{
return;
}
int oldCount = _count;
_version++;
Initialize(newSize);
Debug.Assert(!(oldEntries is null));
CopyEntries(oldEntries, oldCount);
}
private void CopyEntries(Entry[] entries, int count)
{
Debug.Assert(!(_entries is null));
Entry[] newEntries = _entries;
int newCount = 0;
for (int i = 0; i < count; i++)
{
uint hashCode = entries[i].hashCode;
if (entries[i].next >= -1)
{
ref Entry entry = ref newEntries[newCount];
entry = entries[i];
ref int bucket = ref GetBucket(hashCode);
entry.next = bucket - 1; // Value in _buckets is 1-based
bucket = newCount + 1;
newCount++;
}
}
_count = newCount;
_freeCount = 0;
}
private static bool IsCompatibleKey(object key)
{
if (key == null)
{
throw new ArgumentNullException("ExceptionArgument.key");
}
return key is object;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private ref int GetBucket(uint hashCode)
{
int[] buckets = _buckets!;
#if TARGET_64BIT
if (Is64Bits)
{
return ref buckets[HashHelpers.FastMod(hashCode, (uint)buckets.Length, _fastModMultiplier)];
}
else
{
return ref buckets[hashCode % (uint)buckets.Length];
}
#else
return ref buckets[hashCode % (uint)buckets.Length];
#endif
}
#if HAS_CUSTOM_ISNULLREF
//
// These two methods are extracted from Unsafe.IsNullRef and Unsafe.NullRef v5.0.0
// to avoid depending on previous versions of the binaries on Xamarin iOS/macOS/Android.
// Those are disabled on net5.0 or greater as the methods exist for those versions.
//
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static unsafe bool IsNullRef<T>(ref T source)
{
return Unsafe.AsPointer(ref source) == null;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe static ref T NullRef<T>()
{
return ref Unsafe.AsRef<T>(null);
}
#endif
private struct Entry
{
public uint hashCode;
/// <summary>
/// 0-based index of next entry in chain: -1 means end of chain
/// also encodes whether this entry _itself_ is part of the free list by changing sign and subtracting 3,
/// so -2 means end of free list, -3 means index 0 but on free list, -4 means index 1 but on free list, etc.
/// </summary>
public int next;
public ResourceKey key; // Key of entry
public object value; // Value of entry
}
public struct Enumerator : IEnumerator<KeyValuePair<ResourceKey, object>>, IEnumerator, IDictionaryEnumerator
{
private readonly SpecializedResourceDictionary _dictionary;
private readonly int _version;
private int _index;
private KeyValuePair<ResourceKey, object> _current;
private readonly int _getEnumeratorRetType; // What should Enumerator.Current return?
internal const int DictEntry = 1;
internal const int KeyValuePair = 2;
internal Enumerator(SpecializedResourceDictionary dictionary, int getEnumeratorRetType)
{
_dictionary = dictionary;
_version = dictionary._version;
_index = 0;
_getEnumeratorRetType = getEnumeratorRetType;
_current = default;
}
public bool MoveNext()
{
if (_version != _dictionary._version)
{
throw new InvalidOperationException("InvalidOperation_EnumFailedVersion()");
}
// Use unsigned comparison since we set index to dictionary.count+1 when the enumeration ends.
// dictionary.count+1 could be negative if dictionary.count is int.MaxValue
while ((uint)_index < (uint)_dictionary._count)
{
ref Entry entry = ref _dictionary._entries![_index++];
if (entry.next >= -1)
{
_current = new KeyValuePair<ResourceKey, object>(entry.key, entry.value);
return true;
}
}
_index = _dictionary._count + 1;
_current = default;
return false;
}
public KeyValuePair<ResourceKey, object> Current => _current;
public void Dispose() { }
object IEnumerator.Current
{
get
{
if (_index == 0 || (_index == _dictionary._count + 1))
{
throw new InvalidOperationException("InvalidOperation_EnumOpCantHappen()");
}
if (_getEnumeratorRetType == DictEntry)
{
return new DictionaryEntry(_current.Key, _current.Value);
}
return new KeyValuePair<object, object>(_current.Key, _current.Value);
}
}
void IEnumerator.Reset()
{
if (_version != _dictionary._version)
{
throw new InvalidOperationException("InvalidOperation_EnumFailedVersion()");
}
_index = 0;
_current = default;
}
DictionaryEntry IDictionaryEnumerator.Entry
{
get
{
if (_index == 0 || (_index == _dictionary._count + 1))
{
throw new InvalidOperationException("InvalidOperation_EnumOpCantHappen()");
}
return new DictionaryEntry(_current.Key, _current.Value);
}
}
object IDictionaryEnumerator.Key
{
get
{
if (_index == 0 || (_index == _dictionary._count + 1))
{
throw new InvalidOperationException("InvalidOperation_EnumOpCantHappen()");
}
return _current.Key;
}
}
object IDictionaryEnumerator.Value
{
get
{
if (_index == 0 || (_index == _dictionary._count + 1))
{
throw new InvalidOperationException("InvalidOperation_EnumOpCantHappen()");
}
return _current.Value;
}
}
}
public sealed class KeyCollection : ICollection<ResourceKey>, ICollection, IReadOnlyCollection<ResourceKey>
{
private readonly SpecializedResourceDictionary _dictionary;
public KeyCollection(SpecializedResourceDictionary dictionary)
{
if (dictionary == null)
{
throw new ArgumentNullException("ExceptionArgument.dictionary");
}
_dictionary = dictionary;
}
public Enumerator GetEnumerator() => new Enumerator(_dictionary);
public void CopyTo(ResourceKey[] array, int index)
{
if (array == null)
{
throw new ArgumentNullException("ExceptionArgument.array");
}
if (index < 0 || index > array.Length)
{
throw new ArgumentOutOfRangeException("NeedNonNegNumException");
}
if (array.Length - index < _dictionary.Count)
{
throw new ArgumentException("ExceptionResource.Arg_ArrayPlusOffTooSmall");
}
int count = _dictionary._count;
Entry[] entries = _dictionary._entries;
for (int i = 0; i < count; i++)
{
if (entries![i].next >= -1) array[index++] = entries[i].key;
}
}
public int Count => _dictionary.Count;
bool ICollection<ResourceKey>.IsReadOnly => true;
void ICollection<ResourceKey>.Add(ResourceKey item) =>
throw new NotSupportedException("ExceptionResource.NotSupported_KeyCollectionSet");
void ICollection<ResourceKey>.Clear() =>
throw new NotSupportedException("ExceptionResource.NotSupported_KeyCollectionSet");
bool ICollection<ResourceKey>.Contains(ResourceKey item) =>
_dictionary.ContainsKey(item);
bool ICollection<ResourceKey>.Remove(ResourceKey item)
{
throw new NotSupportedException("ExceptionResource.NotSupported_KeyCollectionSet");
}
IEnumerator<ResourceKey> IEnumerable<ResourceKey>.GetEnumerator() => new Enumerator(_dictionary);
IEnumerator IEnumerable.GetEnumerator() => new Enumerator(_dictionary);
void ICollection.CopyTo(Array array, int index)
{
if (array == null)
{
throw new ArgumentNullException("ExceptionArgument.array");
}
if (array.Rank != 1)
{
throw new ArgumentException("ExceptionResource.Arg_RankMultiDimNotSupported");
}
if (array.GetLowerBound(0) != 0)
{
throw new ArgumentException("ExceptionResource.Arg_NonZeroLowerBound");
}
if ((uint)index > (uint)array.Length)
{
throw new ArgumentOutOfRangeException("NeedNonNegNumException()");