-
Notifications
You must be signed in to change notification settings - Fork 3
/
ArenaDict.cs
1303 lines (1079 loc) · 55.2 KB
/
ArenaDict.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
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
namespace Arenas {
using static Arenas.UnmanagedListTypes;
using static UnmanagedDictTypes;
// TODO: Custom IEqualityComparer
[DebuggerTypeProxy(typeof(ArenaDictDebugView<,>))]
public unsafe struct ArenaDict<TKey, TValue> : IDictionary<TKey, TValue>, IDisposable where TKey : unmanaged where TValue : unmanaged {
private const int defaultCapacity = 4;
private const uint fibHashMagic = 2654435769;
private const int noneHashCode = 0;
private const int nullOffset = 0;
private static int RebalanceCount(int capacity) {
return capacity * 3 / 4;
}
private UnmanagedRef<UnmanagedDict> info;
private ArenaDict(UnmanagedRef<UnmanagedDict> dictData) {
info = dictData;
}
public ArenaDict(Arena arena, int capacity = defaultCapacity) {
if (arena is null) {
throw new ArgumentNullException(nameof(arena));
}
if (capacity < 0) {
capacity = defaultCapacity;
}
var typeK = TypeInfo.GenerateTypeInfo<TKey>();
var typeV = TypeInfo.GenerateTypeInfo<TValue>();
if (typeK.IsArenaContents) {
throw new NotSupportedException("ArenaList cannot store keys which implement IArenaContents. Please use UnmanagedRef instead.");
}
if (typeV.IsArenaContents) {
throw new NotSupportedException("ArenaList cannot store values which implement IArenaContents. Please use UnmanagedRef instead.");
}
// first allocate our info object
info = arena.Allocate(new UnmanagedDict());
// must have positive power of two capacity
ulong powTwo = (uint)capacity;
if (!MemHelper.IsPowerOfTwo(powTwo)) {
if (capacity <= 0) {
capacity = defaultCapacity;
}
powTwo = MemHelper.NextPowerOfTwo((ulong)capacity);
if (powTwo > int.MaxValue) {
throw new ArgumentOutOfRangeException(nameof(capacity));
}
}
else if (powTwo == 1) {
// capacity 1 doesn't really work since the rebalance count is 0
// so it'll rebalance to 2 items as soon as you use it at all
powTwo = 2;
}
// get the shift amount from the capacity which is now a power of two
// this is used to shift the hashcode into a backing array index after
// multiplying it by our magic fibonacci number
capacity = (int)powTwo;
var shift = 32 - MemHelper.PowerOfTwoLeadingZeros[powTwo];
// because .NET standard can't have composed unmanaged types we cant allocate a memory area
// that is a series of entry structs, and instead have to interleave entry headers with key
// and value manually. we use our type info here in order to get all the offsets and sizes
// and such that are needed
var entryInfo = TypeInfo.GenerateTypeInfo<UnmanagedDictEntry>();
var entrySize = MemHelper.AlignCeil(typeK.Size + typeV.Size + entryInfo.Size, sizeof(ulong));
// Old comment:
// now we know entry size, calculate the actual amount of memory needed
// this needs to be twice the amount in case of a worst case scenario of all items mapping
// to the same hashcode, that way we know we always have enough capacity outside of the
// backing array
// New comment:
// actually we only need as much overflow storage as 75% of the capacity in order to make
// sure that there's always enough room for items before rebalancing, so just use the
// rebalancing amount to determine the extra overflow storage space needed. this is still
// 1 item more than we actually need, because even in the worst case the head is always
// stored inside the backing array, but idk, off by one errors are scary and there's no
// need to ditch the spare bonus item just in case
//
// by keeping the overflow size a little smaller than the power-of-two sized backing array
// we usually wind up with a size a little under a power of 2 in size, which is useful
// for memory efficiency because the arena will dole out chunks of power-of-two minus the
// size of an item header in memory, so requesting a full power of two actually doubles the
// amount allocated but requesting slightly less means we wind up with basically exactly
// the amount we want so overhead becomes way lower
var size = capacity * entrySize;
//size *= 2; // extra space for linked lists
size += RebalanceCount(capacity) * entrySize;
var itemsRef = arena.AllocCount<byte>(size); // alloc memory buffer
var backingArrayLength = capacity;
var overflowLength = itemsRef.Size / entrySize - backingArrayLength;
// set all our props
var self = info.Value;
self->Shift = shift;
self->EntrySize = entrySize;
self->KeyOffset = entryInfo.Size; // key comes after entry struct
self->ValueOffset = self->KeyOffset + typeK.Size; // val comes after key
self->ItemsBuffer = (UnmanagedRef)itemsRef;
self->BackingArrayLength = capacity;
self->OverflowLength = itemsRef.Size / entrySize - backingArrayLength;
//Debug.Assert(self->OverflowLength >= self->BackingArrayLength);
Debug.Assert(self->OverflowLength >= RebalanceCount(self->BackingArrayLength) - 1);
// position our bump allocator to the end of the backing array
// this is used to allocate new entries when the freelist is empty
self->Bump = self->BackingArrayLength * self->EntrySize;
}
// https://probablydance.com/2018/06/16/fibonacci-hashing-the-optimization-that-the-world-forgot-or-a-better-alternative-to-integer-modulo/
private static uint HashToIndex(uint hash, int shift) {
hash ^= hash >> shift; // this line improves distribution but can be commented out
return (fibHashMagic * hash) >> shift;
}
public void Free() {
if (Arena is null) {
throw new InvalidOperationException("Cannot Free ArenaDict<TKey, TValue>: dictionary has not been properly initialized with arena reference");
}
var self = info.Value;
if (self == null) {
throw new InvalidOperationException("Cannot Free ArenaDict<TKey, TValue>: dictionary memory has previously been freed");
}
self->Version++;
var items = self->ItemsBuffer;
Arena.Free(items);
Arena.Free(info);
info = default;
}
public void Dispose() {
if (!IsAllocated) {
return;
}
Free();
}
public void Clear() {
if (Arena is null) {
throw new InvalidOperationException("Cannot Clear ArenaDict<TKey, TValue>: dictionary has not been properly initialized with arena reference");
}
var self = info.Value;
if (self == null) {
throw new InvalidOperationException("Cannot Clear ArenaDict<TKey, TValue>: dictionary memory has previously been freed");
}
var items = self->ItemsBuffer.Value;
if (items == IntPtr.Zero) {
throw new InvalidOperationException("Cannot Clear ArenaDict<TKey, TValue>: dictionary's backing array has previously been freed");
}
self->Version++;
self->Count = 0;
self->Bump = self->BackingArrayLength * self->EntrySize;
self->Head = nullOffset;
// zero backing array memory (Bump has been set to the end of the backing array)
// remaining storage space doesn't need to be zeroed because the bump allocator
// zeroes out newly allocated entries
MemHelper.ZeroMemory(items, self->Bump);
}
// TODO: implement
//public void TrimExcess(int capacity = 0) {
//}
private void AddCapacity(UnmanagedDict* self, ref IntPtr items) {
// copy into new dictionary
var newDict = new ArenaDict<TKey, TValue>(info.Arena, self->BackingArrayLength * 2);
var entryEnumerator = new FastInternalEnumerator(this);
while (entryEnumerator.GetNextEntry(out var entry)) {
newDict.Add(*entry.Key, *entry.Value);
}
// free old items buffer
Arena.Free(items);
// copy new dictionary's info
*self = *newDict.info.Value;
// free new dictionary's info
Arena.Free(newDict.info);
items = self->ItemsBuffer.Value;
}
private int GetHashCode(TKey* key) {
var hashCode = key->GetHashCode();
if (hashCode == noneHashCode) hashCode = 0x1234FEDC; // hashCode cannot be 0
return hashCode;
}
private bool TryGetEntry(UnmanagedDict* self, IntPtr items, TKey* _key, int hashCode, out Entry entry, out Entry? previous) {
var index = (int)HashToIndex((uint)hashCode, self->Shift);
entry = GetIndex(self, items, index);
var key = *_key;
if (entry.HashCode == noneHashCode) {
// no value at index, insert
previous = null;
return true;
}
else if (entry.HashCode == hashCode && EqualityComparer<TKey>.Default.Equals(*entry.Key, key)) {
// found identical key at index
previous = null;
return true;
}
else {
// bucket exists but value wasn't at head, search nodes
var next = entry.Next;
while (next > nullOffset) {
previous = entry;
entry = GetOffset(self, items, next);
if (entry.HashCode == hashCode && EqualityComparer<TKey>.Default.Equals(*entry.Key, key)) {
// found identical key in bucket
return true;
}
next = entry.Next;
}
previous = null;
return false;
}
}
public void Add(TKey key, TValue value) {
if (Arena is null) {
throw new InvalidOperationException("Cannot Add item to ArenaDict<TKey, TValue>: dictionary has not been properly initialized with arena reference");
}
var self = info.Value;
if (self == null) {
throw new InvalidOperationException("Cannot Add item to ArenaDict<TKey, TValue>: dictionary memory has previously been freed");
}
var items = self->ItemsBuffer.Value;
if (items == IntPtr.Zero) {
throw new InvalidOperationException("Cannot Add item to ArenaDict<TKey, TValue>: dictionary's backing array has previously been freed");
}
Set(self, ref items, &key, &value, false);
}
void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> item) {
Add(item.Key, item.Value);
}
public bool TryGetValue(TKey key, out TValue value) {
if (Arena is null) {
throw new InvalidOperationException("Cannot TryGetValue on ArenaDict<TKey, TValue>: dictionary has not been properly initialized with arena reference");
}
var self = info.Value;
if (self == null) {
throw new InvalidOperationException("Cannot TryGetValue on ArenaDict<TKey, TValue>: dictionary memory has previously been freed");
}
var items = self->ItemsBuffer.Value;
if (items == IntPtr.Zero) {
throw new InvalidOperationException("Cannot TryGetValue on ArenaDict<TKey, TValue>: dictionary's backing array has previously been freed");
}
var valRef = Get(self, items, &key, false);
if (valRef == null) {
value = default;
return false;
}
value = *valRef;
return true;
}
public bool ContainsKey(TKey key) {
if (Arena is null) {
throw new InvalidOperationException("Cannot ContainsKey on ArenaDict<TKey, TValue>: dictionary has not been properly initialized with arena reference");
}
var self = info.Value;
if (self == null) {
throw new InvalidOperationException("Cannot ContainsKey on ArenaDict<TKey, TValue>: dictionary memory has previously been freed");
}
var items = self->ItemsBuffer.Value;
if (items == IntPtr.Zero) {
throw new InvalidOperationException("Cannot ContainsKey on ArenaDict<TKey, TValue>: dictionary's backing array has previously been freed");
}
return Get(self, items, &key, false) != null;
}
public bool ContainsValue(TValue value) {
if (Arena is null) {
throw new InvalidOperationException("Cannot ContainsValue on ArenaDict<TKey, TValue>: dictionary has not been properly initialized with arena reference");
}
var self = info.Value;
if (self == null) {
throw new InvalidOperationException("Cannot ContainsValue on ArenaDict<TKey, TValue>: dictionary memory has previously been freed");
}
var items = self->ItemsBuffer.Value;
if (items == IntPtr.Zero) {
throw new InvalidOperationException("Cannot ContainsValue on ArenaDict<TKey, TValue>: dictionary's backing array has previously been freed");
}
var entryEnumerator = new FastInternalEnumerator(this);
while (entryEnumerator.GetNextEntry(out var entry)) {
if (EqualityComparer<TValue>.Default.Equals(value, *entry.Value)) return true;
}
return false;
}
bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> item) {
if (Arena is null) {
throw new InvalidOperationException("Cannot Contains key value pair on ArenaDict<TKey, TValue>: dictionary has not been properly initialized with arena reference");
}
var self = info.Value;
if (self == null) {
throw new InvalidOperationException("Cannot Contains key value pair on ArenaDict<TKey, TValue>: dictionary memory has previously been freed");
}
var items = self->ItemsBuffer.Value;
if (items == IntPtr.Zero) {
throw new InvalidOperationException("Cannot Contains key value pair on ArenaDict<TKey, TValue>: dictionary's backing array has previously been freed");
}
var key = item.Key;
var valRef = Get(self, items, &key, false);
if (valRef == null) {
return false;
}
return EqualityComparer<TValue>.Default.Equals(*valRef, item.Value);
}
private TValue* Get(UnmanagedDict* self, IntPtr items, TKey* key, bool throwIfNotFound) {
var hashCode = GetHashCode(key);
if (!TryGetEntry(self, items, key, hashCode, out var entry, out _) || entry.HashCode == noneHashCode) {
// no key found
if (throwIfNotFound) {
throw new KeyNotFoundException();
}
return null;
}
return entry.Value;
}
private void Set(UnmanagedDict* self, ref IntPtr items, TKey* key, in TValue* value, bool allowDuplicates) {
var hashCode = GetHashCode(key);
if (!TryGetEntry(self, items, key, hashCode, out var entry, out _)) {
// if TryGetEntry fails then `entry` is the last entry it checked
// inside the bucket and never the head entry inside the backing
// array, so we need to add a node after it
// no key found, add to bucket
var head = GetHead(self, items); // get head from freelist or bump allocator
// remove head by advancing head to the next item
self->Head = head.Next;
// point popped head to nothing, point entry to popped head
head.Next = nullOffset;
entry.Next = head.Offset;
entry = head;
}
// overwrite entry with correct values
entry.HashCode = hashCode;
*entry.Key = *key;
*entry.Value = *value;
// increment count and rebalance at 75% full
self->Version++;
self->Count++;
if (self->Count >= RebalanceCount(self->BackingArrayLength)) {
AddCapacity(self, ref items);
}
}
private Entry GetIndex(UnmanagedDict* self, IntPtr items, int index) {
return GetOffset(self, items, index * self->EntrySize);
}
private Entry GetOffset(UnmanagedDict* self, IntPtr items, int offset) {
return new Entry(items + offset, self);
}
/// <summary>
/// Gets but does not pop the head off the overflow area's freelist. This may
/// instead allocate a new entry using the bump allocator if the freelist is
/// empty
/// </summary>
/// <returns>Entry which point to the head entry</returns>
private Entry GetHead(UnmanagedDict* self, IntPtr items) {
var head = self->Head;
if (head != nullOffset) {
return GetOffset(self, items, head);
}
// no entry in freelist, allocate via bump allocator
head = self->Bump;
self->Bump += self->EntrySize;
// make sure the newly allocated entry is zeroed, because
// we only zero the backing array on clear, not the additional
// memory areas
var headEntry = GetOffset(self, items, head);
// don't actually need to clear, just set Next to 0
//headEntry.Clear();
headEntry.Next = nullOffset;
Debug.Assert(head < self->ItemsBuffer.Size);
Debug.Assert(headEntry.Next == nullOffset);
return headEntry;
}
public bool Remove(TKey key) {
if (Arena is null) {
throw new InvalidOperationException("Cannot Remove item from ArenaDict<TKey, TValue>: dictionary has not been properly initialized with arena reference");
}
var self = info.Value;
if (self == null) {
throw new InvalidOperationException("Cannot Remove item from ArenaDict<TKey, TValue>: dictionary memory has previously been freed");
}
var items = self->ItemsBuffer.Value;
if (items == IntPtr.Zero) {
throw new InvalidOperationException("Cannot Remove item from ArenaDict<TKey, TValue>: dictionary's backing array has previously been freed");
}
var hashCode = GetHashCode(&key);
if (!TryGetEntry(self, items, &key, hashCode, out var entry, out var _prev)) {
return false;
}
if (_prev.HasValue) {
// entry is a linked list node, so we just unlink it
UnlinkEntry(self, entry, _prev.Value);
}
else {
// entry is in main backing array
if (entry.Next != nullOffset) {
// entry links to another value, copy the next value into the
// backing array and then unlink it
var next = GetOffset(self, items, entry.Next);
// set hashcode, key, and value but leave `next` property as
// is so we can subsequently call UnlinkEntry
entry.HashCode = next.HashCode;
*entry.Key = *next.Key;
*entry.Value = *next.Value;
UnlinkEntry(self, next, entry);
}
else {
// entry links to no values, clear
entry.Clear();
}
}
self->Version++;
self->Count--;
return true;
}
private void UnlinkEntry(UnmanagedDict* self, Entry entry, Entry prev) {
// unlink node
prev.Next = entry.Next;
// insert new head node into freelist
var prevHead = self->Head;
self->Head = entry.Offset;
entry.Next = prevHead;
}
bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item) {
if (Arena is null) {
throw new InvalidOperationException("Cannot Remove key value pair from ArenaDict<TKey, TValue>: dictionary has not been properly initialized with arena reference");
}
var self = info.Value;
if (self == null) {
throw new InvalidOperationException("Cannot Remove key value pair from ArenaDict<TKey, TValue>: dictionary memory has previously been freed");
}
var items = self->ItemsBuffer.Value;
if (items == IntPtr.Zero) {
throw new InvalidOperationException("Cannot Remove key value pair from ArenaDict<TKey, TValue>: dictionary's backing array has previously been freed");
}
var key = item.Key;
var valRef = Get(self, items, &key, false);
if (valRef != null && EqualityComparer<TValue>.Default.Equals(*valRef, item.Value)) {
Remove(key);
return true;
}
return false;
}
void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int index) {
if (Arena is null) {
throw new InvalidOperationException("Cannot CopyTo key value pairs on ArenaDict<TKey, TValue>: dictionary has not been properly initialized with arena reference");
}
var self = info.Value;
if (self == null) {
throw new InvalidOperationException("Cannot CopyTo key value pairs on ArenaDict<TKey, TValue>: dictionary memory has previously been freed");
}
var items = self->ItemsBuffer.Value;
if (items == IntPtr.Zero) {
throw new InvalidOperationException("Cannot CopyTo key value pairs on ArenaDict<TKey, TValue>: dictionary's backing array has previously been freed");
}
if (array == null) {
throw new ArgumentNullException(nameof(array));
}
if (array.Rank != 1) {
throw new ArgumentException("Only single dimensional arrays are supported for the requested action.", nameof(array));
}
if (array.GetLowerBound(0) != 0) {
throw new ArgumentException("The lower bound of target array must be zero.", nameof(array));
}
if ((uint)index > (uint)array.Length) {
throw new ArgumentOutOfRangeException(nameof(index), "Non-negative number required.");
}
if (array.Length - index < Count) {
throw new ArgumentException("Destination array is not long enough to copy all the items in the collection. Check array index and length.", nameof(array));
}
var entryEnumerator = new FastInternalEnumerator(this);
while (entryEnumerator.GetNextEntry(out var entry)) {
array[index++] = new KeyValuePair<TKey, TValue>(*entry.Key, *entry.Value);
}
}
public Enumerator GetEnumerator() {
if (Arena is null) {
throw new InvalidOperationException("Cannot GetEnumerator for ArenaDict<TKey, TValue>: dictionary has not been properly initialized with arena reference");
}
var self = info.Value;
if (self == null) {
throw new InvalidOperationException("Cannot GetEnumerator for ArenaDict<TKey, TValue>: dictionary memory has previously been freed");
}
var items = self->ItemsBuffer.Value;
if (items == IntPtr.Zero) {
throw new InvalidOperationException("Cannot GetEnumerator for ArenaDict<TKey, TValue>: dictionary's backing array has previously been freed");
}
return new Enumerator(this);
}
IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator() {
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator() {
return GetEnumerator();
}
public UnmanagedRef<UnmanagedDict> GetUnderlyingReference() {
return info;
}
public static explicit operator ArenaDict<TKey, TValue>(UnmanagedRef<UnmanagedDict> dictData) {
return new ArenaDict<TKey, TValue>(dictData);
}
public TValue this[TKey key] {
get {
if (Arena is null) {
throw new InvalidOperationException("Cannot get item at index in ArenaDict<TKey, TValue>: dictionary has not been properly initialized with arena reference");
}
var self = info.Value;
if (self == null) {
throw new InvalidOperationException("Cannot get item at index in ArenaDict<TKey, TValue>: dictionary memory has previously been freed");
}
var items = self->ItemsBuffer.Value;
if (items == IntPtr.Zero) {
throw new InvalidOperationException("Cannot get item at index in ArenaDict<TKey, TValue>: dictionary's backing array has previously been freed");
}
return *Get(self, items, &key, true);
}
set {
if (Arena is null) {
throw new InvalidOperationException("Cannot set item at index in ArenaDict<TKey, TValue>: dictionary has not been properly initialized with arena reference");
}
var self = info.Value;
if (self == null) {
throw new InvalidOperationException("Cannot set item at index in ArenaDict<TKey, TValue>: dictionary memory has previously been freed");
}
var items = self->ItemsBuffer.Value;
if (items == IntPtr.Zero) {
throw new InvalidOperationException("Cannot set item at index in ArenaDict<TKey, TValue>: dictionary's backing array has previously been freed");
}
Set(self, ref items, &key, &value, true);
}
}
public int Count {
get {
var self = info.Value;
if (self == null) {
return 0;
}
return self->Count;
}
}
public KeyCollection Keys {
get {
if (Arena is null) {
throw new InvalidOperationException("Cannot get Keys for ArenaDict<TKey, TValue>: dictionary has not been properly initialized with arena reference");
}
var self = info.Value;
if (self == null) {
throw new InvalidOperationException("Cannot get Keys for ArenaDict<TKey, TValue>: dictionary memory has previously been freed");
}
var items = self->ItemsBuffer.Value;
if (items == IntPtr.Zero) {
throw new InvalidOperationException("Cannot get Keys for ArenaDict<TKey, TValue>: dictionary's backing array has previously been freed");
}
return new KeyCollection(this);
}
}
public ValueCollection Values {
get {
if (Arena is null) {
throw new InvalidOperationException("Cannot get Values for ArenaDict<TKey, TValue>: dictionary has not been properly initialized with arena reference");
}
var self = info.Value;
if (self == null) {
throw new InvalidOperationException("Cannot get Values for ArenaDict<TKey, TValue>: dictionary memory has previously been freed");
}
var items = self->ItemsBuffer.Value;
if (items == IntPtr.Zero) {
throw new InvalidOperationException("Cannot get Values for ArenaDict<TKey, TValue>: dictionary's backing array has previously been freed");
}
return new ValueCollection(this);
}
}
public bool IsAllocated { get { return info.HasValue; } }
public Arena Arena { get { return info.Arena; } }
bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly { get { return false; } }
ICollection<TKey> IDictionary<TKey, TValue>.Keys { get { return Keys; } }
ICollection<TValue> IDictionary<TKey, TValue>.Values { get { return Values; } }
/// <summary>
/// Wrapper struct around a memory area representing an UnmanagedDictEntry, key, and value
/// </summary>
private unsafe readonly struct Entry {
public readonly IntPtr Pointer;
public readonly UnmanagedDict* Dict;
public Entry(IntPtr pointer, UnmanagedDict* dict) {
Pointer = pointer;
Dict = dict;
}
public void Clear() {
*(UnmanagedDictEntry*)Pointer = default;
*Key = default;
*Value = default;
}
public override string ToString() {
return $"Entry({*Key}={*Value}, HashCode={HashCode}, Next={Next}, Offset={Offset})";
}
/// <summary>
/// Offset of this entry from the start of the memory storage area for the dictionary's items
/// </summary>
public int Offset { get { return (int)((ulong)Pointer - (ulong)Dict->ItemsBuffer.Value); } }
public TKey* Key { get { return (TKey*)(Pointer + Dict->KeyOffset); } }
public TValue* Value { get { return (TValue*)(Pointer + Dict->ValueOffset); } }
public int HashCode { get { return ((UnmanagedDictEntry*)Pointer)->HashCode; } set { ((UnmanagedDictEntry*)Pointer)->HashCode = value; } }
public int Next { get { return ((UnmanagedDictEntry*)Pointer)->Next; } set { ((UnmanagedDictEntry*)Pointer)->Next = value; } }
}
[Serializable]
public struct Enumerator : IEnumerator<KeyValuePair<TKey, TValue>>, System.Collections.IEnumerator {
private ArenaDict<TKey, TValue> dict;
private int index;
private int offset;
private int headOffset;
private int version;
private int count;
private KeyValuePair<TKey, TValue> current;
internal Enumerator(ArenaDict<TKey, TValue> dict) {
this.dict = dict;
var dictPtr = dict.info.Value;
index = 0;
offset = 0;
headOffset = 0;
version = dictPtr->Version;
count = dictPtr->BackingArrayLength;
current = default;
}
public void Dispose() {
}
public bool MoveNext() {
var dictPtr = dict.info.Value;
if (dictPtr == null || version != dictPtr->Version) {
throw new InvalidOperationException("Collection was modified; enumeration operation may not execute.");
}
var itemsPtr = dictPtr->ItemsBuffer.Value;
if (itemsPtr == IntPtr.Zero) {
throw new InvalidOperationException("Collection was modified; enumeration operation may not execute.");
}
while ((uint)index < (uint)count) {
// get current entry
var entry = dict.GetOffset(dictPtr, itemsPtr, offset);
// move to next entry associated with the current index
offset = entry.Next;
if (offset == nullOffset) {
// if the position of the next entry is zero then there are no further
// entries at this index, increment the index and set the new offset to
// the head of the list (the entry in the backing array)
headOffset += dictPtr->EntrySize;
offset = headOffset;
index++;
}
// only entries with a hashcode which isn't zero are valid entries
if (entry.HashCode != noneHashCode) {
current = new KeyValuePair<TKey, TValue>(*entry.Key, *entry.Value);
return true;
}
}
index = count + 1;
current = default;
return false;
}
public KeyValuePair<TKey, TValue> Current {
get {
return current;
}
}
object IEnumerator.Current {
get {
if (index == 0 || index == count + 1) {
throw new InvalidOperationException("Enumeration has either not started or has already finished.");
}
return Current;
}
}
void IEnumerator.Reset() {
var dictPtr = dict.info.Value;
if (dictPtr == null || version != dictPtr->Version || !dictPtr->ItemsBuffer.HasValue) {
throw new InvalidOperationException("Collection was modified; enumeration operation may not execute.");
}
index = 0;
offset = 0;
headOffset = 0;
current = default;
}
}
/// <summary>
/// Used in place of `foreach (var kvp in this)` internally since it's more efficient
/// </summary>
private struct FastInternalEnumerator {
private ArenaDict<TKey, TValue> dict;
private int index;
private int offset;
private int headOffset;
private int count;
private UnmanagedDict* dictPtr;
private IntPtr itemsPtr;
internal FastInternalEnumerator(ArenaDict<TKey, TValue> dict) {
this.dict = dict;
dictPtr = dict.info.Value;
index = 0;
offset = 0;
headOffset = 0;
count = dictPtr->BackingArrayLength;
itemsPtr = dictPtr->ItemsBuffer.Value;
}
public bool GetNextEntry(out Entry result) {
while ((uint)index < (uint)count) {
// get current entry
var entry = dict.GetOffset(dictPtr, itemsPtr, offset);
// move to next entry associated with the current index
offset = entry.Next;
if (offset == nullOffset) {
// if the position of the next entry is zero then there are no further
// entries at this index, increment the index and set the new offset to
// the head of the list (the entry in the backing array)
headOffset += dictPtr->EntrySize;
offset = headOffset;
index++;
}
// only entries with a hashcode which isn't zero are valid entries
if (entry.HashCode != noneHashCode) {
result = entry;
return true;
}
}
index = count + 1;
result = default;
return false;
}
}
#region Key and value collections
public readonly struct KeyCollection : ICollection<TKey>, IEnumerable<TKey>, IReadOnlyCollection<TKey> {
private readonly ArenaDict<TKey, TValue> dict;
public KeyCollection(ArenaDict<TKey, TValue> dict) {
this.dict = dict;
}
public Enumerator GetEnumerator() {
if (dict.Arena is null) {
throw new InvalidOperationException("Cannot GetEnumerator for ArenaDict<TKey, TValue>.KeyCollection: dictionary has not been properly initialized with arena reference");
}
var self = dict.info.Value;
if (self == null) {
throw new InvalidOperationException("Cannot GetEnumerator for ArenaDict<TKey, TValue>.KeyCollection: dictionary memory has previously been freed");
}
var items = self->ItemsBuffer.Value;
if (items == IntPtr.Zero) {
throw new InvalidOperationException("Cannot GetEnumerator for ArenaDict<TKey, TValue>.KeyCollection: dictionary's backing array has previously been freed");
}
return new Enumerator(dict);
}
public void CopyTo(TKey[] array, int index) {
if (dict.Arena is null) {
throw new InvalidOperationException("Cannot CopyTo on ArenaDict<TKey, TValue>.KeyCollection: dictionary has not been properly initialized with arena reference");
}
var self = dict.info.Value;
if (self == null) {
throw new InvalidOperationException("Cannot CopyTo on ArenaDict<TKey, TValue>.KeyCollection: dictionary memory has previously been freed");
}
var items = self->ItemsBuffer.Value;
if (items == IntPtr.Zero) {
throw new InvalidOperationException("Cannot CopyTo on ArenaDict<TKey, TValue>.KeyCollection: dictionary's backing array has previously been freed");
}
if (array == null) {
throw new ArgumentNullException(nameof(array));
}
if (array.Rank != 1) {
throw new ArgumentException("Only single dimensional arrays are supported for the requested action.", nameof(array));
}
if (array.GetLowerBound(0) != 0) {
throw new ArgumentException("The lower bound of target array must be zero.", nameof(array));
}
if ((uint)index > (uint)array.Length) {
throw new ArgumentOutOfRangeException(nameof(index), "Non-negative number required.");
}
if (array.Length - index < Count) {
throw new ArgumentException("Destination array is not long enough to copy all the items in the collection. Check array index and length.", nameof(array));
}
var entryEnumerator = new FastInternalEnumerator(dict);
while (entryEnumerator.GetNextEntry(out var entry)) {
array[index++] = *entry.Key;
}
}
public int Count => dict.Count;
bool ICollection<TKey>.IsReadOnly => true;
void ICollection<TKey>.Add(TKey item) =>
throw new NotSupportedException("Mutating a value collection derived from a dictionary is not allowed.");
bool ICollection<TKey>.Remove(TKey item) =>
throw new NotSupportedException("Mutating a value collection derived from a dictionary is not allowed.");
void ICollection<TKey>.Clear() =>
throw new NotSupportedException("Mutating a value collection derived from a dictionary is not allowed.");
bool ICollection<TKey>.Contains(TKey item) => dict.ContainsKey(item);
IEnumerator<TKey> IEnumerable<TKey>.GetEnumerator() => GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
public struct Enumerator : IEnumerator<TKey>, System.Collections.IEnumerator {
private ArenaDict<TKey, TValue> dict;
private int index;
private int offset;
private int headOffset;
private int version;
private int count;
private TKey currentKey;
internal Enumerator(ArenaDict<TKey, TValue> dict) {
this.dict = dict;
var dictPtr = dict.info.Value;
index = 0;
offset = 0;
headOffset = 0;
version = dictPtr->Version;
count = dictPtr->BackingArrayLength;
currentKey = default;
}
public void Dispose() {
}
public bool MoveNext() {
var dictPtr = dict.info.Value;
if (dictPtr == null || version != dictPtr->Version) {
throw new InvalidOperationException("Collection was modified; enumeration operation may not execute.");
}
var itemsPtr = dictPtr->ItemsBuffer.Value;
if (itemsPtr == IntPtr.Zero) {
throw new InvalidOperationException("Collection was modified; enumeration operation may not execute.");
}
while ((uint)index < (uint)count) {
// get current entry
var entry = dict.GetOffset(dictPtr, itemsPtr, offset);
// move to next entry associated with the current index
offset = entry.Next;
if (offset == nullOffset) {
// if the position of the next entry is zero then there are no further
// entries at this index, increment the index and set the new offset to
// the head of the list (the entry in the backing array)
headOffset += dictPtr->EntrySize;
offset = headOffset;
index++;
}