Terraria v1.4.4.9
Terraria source code documentation
Loading...
Searching...
No Matches
CacheDict.cs
Go to the documentation of this file.
3
5
6internal sealed class CacheDict<TKey, TValue>
7{
8 private sealed class Entry
9 {
10 internal readonly int _hash;
11
12 internal readonly TKey _key;
13
14 internal readonly TValue _value;
15
16 internal Entry(int hash, TKey key, TValue value)
17 {
18 _hash = hash;
19 _key = key;
20 _value = value;
21 }
22 }
23
24 private readonly int _mask;
25
26 private readonly Entry[] _entries;
27
28 internal TValue this[TKey key]
29 {
30 set
31 {
32 Add(key, value);
33 }
34 }
35
36 internal CacheDict(int size)
37 {
38 int num = AlignSize(size);
39 _mask = num - 1;
40 _entries = new Entry[num];
41 }
42
43 private static int AlignSize(int size)
44 {
45 size--;
46 size |= size >> 1;
47 size |= size >> 2;
48 size |= size >> 4;
49 size |= size >> 8;
50 size |= size >> 16;
51 size++;
52 return size;
53 }
54
55 internal bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value)
56 {
57 int hashCode = key.GetHashCode();
58 int num = hashCode & _mask;
59 Entry entry = Volatile.Read(ref _entries[num]);
60 if (entry != null && entry._hash == hashCode && entry._key.Equals(key))
61 {
62 value = entry._value;
63 return true;
64 }
65 value = default(TValue);
66 return false;
67 }
68
69 internal void Add(TKey key, TValue value)
70 {
71 int hashCode = key.GetHashCode();
72 int num = hashCode & _mask;
73 Entry entry = Volatile.Read(ref _entries[num]);
74 if (entry == null || entry._hash != hashCode || !entry._key.Equals(key))
75 {
76 Volatile.Write(ref _entries[num], new Entry(hashCode, key, value));
77 }
78 }
79}
Entry(int hash, TKey key, TValue value)
Definition CacheDict.cs:16
readonly Entry[] _entries
Definition CacheDict.cs:26
bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value)
Definition CacheDict.cs:55
static int AlignSize(int size)
Definition CacheDict.cs:43
void Add(TKey key, TValue value)
Definition CacheDict.cs:69
static bool Read(ref bool location)
Definition Volatile.cs:67
static void Write(ref bool location, bool value)
Definition Volatile.cs:74