mscorlib(4.0.0.0) API with additions
CacheDict.cs
2 using System.Threading;
3 
5 {
6  internal class CacheDict<TKey, TValue>
7  {
8  internal 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  this.hash = hash;
19  this.key = key;
20  this.value = value;
21  }
22  }
23 
24  protected readonly int mask;
25 
26  protected readonly Entry[] entries;
27 
28  internal TValue this[TKey key]
29  {
30  get
31  {
32  if (TryGetValue(key, out TValue value))
33  {
34  return value;
35  }
36  throw new KeyNotFoundException();
37  }
38  set
39  {
40  Add(key, value);
41  }
42  }
43 
44  internal CacheDict(int size)
45  {
46  int num = AlignSize(size);
47  mask = num - 1;
48  entries = new Entry[num];
49  }
50 
51  private static int AlignSize(int size)
52  {
53  size--;
54  size |= size >> 1;
55  size |= size >> 2;
56  size |= size >> 4;
57  size |= size >> 8;
58  size |= size >> 16;
59  return size + 1;
60  }
61 
62  internal bool TryGetValue(TKey key, out TValue value)
63  {
64  int hashCode = key.GetHashCode();
65  int num = hashCode & mask;
66  Entry entry = Volatile.Read(ref entries[num]);
67  if (entry != null && entry.hash == hashCode && entry.key.Equals(key))
68  {
69  value = entry.value;
70  return true;
71  }
72  value = default(TValue);
73  return false;
74  }
75 
76  internal void Add(TKey key, TValue value)
77  {
78  int hashCode = key.GetHashCode();
79  int num = hashCode & mask;
80  Entry entry = Volatile.Read(ref entries[num]);
81  if (entry == null || entry.hash != hashCode || !entry.key.Equals(key))
82  {
83  Volatile.Write(ref entries[num], new Entry(hashCode, key, value));
84  }
85  }
86  }
87 }
static void Write(ref bool location, bool value)
Writes the specified value to the specified field. On systems that require it, inserts a memory barri...
Definition: Volatile.cs:186
Definition: __Canon.cs:3
The exception that is thrown when the key specified for accessing an element in a collection does not...
Contains methods for performing volatile memory operations.
Definition: Volatile.cs:8
The Add key (the addition key on the numeric keypad).
static bool Read(ref bool location)
Reads the value of the specified field. On systems that require it, inserts a memory barrier that pre...
Definition: Volatile.cs:15