DictionarySlim.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT license.
  3. // See the LICENSE file in the project root for more information.
  4. using System.Collections;
  5. using System.Diagnostics;
  6. using System.Runtime.CompilerServices;
  7. namespace Jint.Collections
  8. {
  9. /// <summary>
  10. /// DictionarySlim<string, TValue> is similar to Dictionary<TKey, TValue> but optimized in three ways:
  11. /// 1) It allows access to the value by ref replacing the common TryGetValue and Add pattern.
  12. /// 2) It does not store the hash code (assumes it is cheap to equate values).
  13. /// 3) It does not accept an equality comparer (assumes Object.GetHashCode() and Object.Equals() or overridden implementation are cheap and sufficient).
  14. /// </summary>
  15. [DebuggerDisplay("Count = {Count}")]
  16. internal class DictionarySlim<TKey, TValue> : IReadOnlyCollection<KeyValuePair<TKey, TValue>> where TKey : IEquatable<TKey>
  17. {
  18. // We want to initialize without allocating arrays. We also want to avoid null checks.
  19. // Array.Empty would give divide by zero in modulo operation. So we use static one element arrays.
  20. // The first add will cause a resize replacing these with real arrays of three elements.
  21. // Arrays are wrapped in a class to avoid being duplicated for each <TKey, TValue>
  22. private static readonly Entry[] InitialEntries = new Entry[1];
  23. private int _count;
  24. // 0-based index into _entries of head of free chain: -1 means empty
  25. private int _freeList = -1;
  26. // 1-based index into _entries; 0 means empty
  27. private int[] _buckets;
  28. private Entry[] _entries;
  29. [DebuggerDisplay("({key}, {value})->{next}")]
  30. private struct Entry
  31. {
  32. public TKey key;
  33. public TValue value;
  34. // 0-based index of next entry in chain: -1 means end of chain
  35. // also encodes whether this entry _itself_ is part of the free list by changing sign and subtracting 3,
  36. // so -2 means end of free list, -3 means index 0 but on free list, -4 means index 1 but on free list, etc.
  37. public int next;
  38. }
  39. public DictionarySlim()
  40. {
  41. _buckets = HashHelpers.SizeOneIntArray;
  42. _entries = InitialEntries;
  43. }
  44. public DictionarySlim(int capacity)
  45. {
  46. if (capacity < 2)
  47. capacity = 2; // 1 would indicate the dummy array
  48. capacity = HashHelpers.PowerOf2(capacity);
  49. _buckets = new int[capacity];
  50. _entries = new Entry[capacity];
  51. }
  52. public int Count => _count;
  53. /// <summary>
  54. /// Clears the dictionary. Note that this invalidates any active enumerators.
  55. /// </summary>
  56. public void Clear()
  57. {
  58. _count = 0;
  59. _freeList = -1;
  60. _buckets = HashHelpers.SizeOneIntArray;
  61. _entries = InitialEntries;
  62. }
  63. public bool ContainsKey(TKey key)
  64. {
  65. Entry[] entries = _entries;
  66. for (int i = _buckets[key.GetHashCode() & (_buckets.Length-1)] - 1;
  67. (uint)i < (uint)entries.Length; i = entries[i].next)
  68. {
  69. if (key.Equals(entries[i].key))
  70. return true;
  71. }
  72. return false;
  73. }
  74. public bool TryGetValue(TKey key, out TValue value)
  75. {
  76. Entry[] entries = _entries;
  77. for (int i = _buckets[key.GetHashCode() & (_buckets.Length - 1)] - 1;
  78. (uint)i < (uint)entries.Length; i = entries[i].next)
  79. {
  80. if (key.Equals(entries[i].key))
  81. {
  82. value = entries[i].value;
  83. return true;
  84. }
  85. }
  86. value = default;
  87. return false;
  88. }
  89. public bool Remove(TKey key)
  90. {
  91. Entry[] entries = _entries;
  92. int bucketIndex = key.GetHashCode() & (_buckets.Length - 1);
  93. int entryIndex = _buckets[bucketIndex] - 1;
  94. int lastIndex = -1;
  95. while (entryIndex != -1)
  96. {
  97. Entry candidate = entries[entryIndex];
  98. if (candidate.key.Equals(key))
  99. {
  100. if (lastIndex != -1)
  101. { // Fixup preceding element in chain to point to next (if any)
  102. entries[lastIndex].next = candidate.next;
  103. }
  104. else
  105. { // Fixup bucket to new head (if any)
  106. _buckets[bucketIndex] = candidate.next + 1;
  107. }
  108. entries[entryIndex] = default;
  109. entries[entryIndex].next = -3 - _freeList; // New head of free list
  110. _freeList = entryIndex;
  111. _count--;
  112. return true;
  113. }
  114. lastIndex = entryIndex;
  115. entryIndex = candidate.next;
  116. }
  117. return false;
  118. }
  119. // Not safe for concurrent _reads_ (at least, if either of them add)
  120. // For concurrent reads, prefer TryGetValue(key, out value)
  121. /// <summary>
  122. /// Gets the value for the specified key, or, if the key is not present,
  123. /// adds an entry and returns the value by ref. This makes it possible to
  124. /// add or update a value in a single look up operation.
  125. /// </summary>
  126. /// <param name="key">Key to look for</param>
  127. /// <returns>Reference to the new or existing value</returns>
  128. public ref TValue GetOrAddValueRef(TKey key)
  129. {
  130. Entry[] entries = _entries;
  131. int bucketIndex = key.GetHashCode() & (_buckets.Length - 1);
  132. for (int i = _buckets[bucketIndex] - 1;
  133. (uint)i < (uint)entries.Length; i = entries[i].next)
  134. {
  135. if (key.Equals(entries[i].key))
  136. return ref entries[i].value;
  137. }
  138. return ref AddKey(key, bucketIndex);
  139. }
  140. public ref TValue this[TKey key]
  141. {
  142. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  143. get => ref GetOrAddValueRef(key);
  144. }
  145. [MethodImpl(MethodImplOptions.NoInlining)]
  146. private ref TValue AddKey(TKey key, int bucketIndex)
  147. {
  148. Entry[] entries = _entries;
  149. int entryIndex;
  150. if (_freeList != -1)
  151. {
  152. entryIndex = _freeList;
  153. _freeList = -3 - entries[_freeList].next;
  154. }
  155. else
  156. {
  157. if (_count == entries.Length || entries.Length == 1)
  158. {
  159. entries = Resize();
  160. bucketIndex = key.GetHashCode() & (_buckets.Length - 1);
  161. // entry indexes were not changed by Resize
  162. }
  163. entryIndex = _count;
  164. }
  165. entries[entryIndex].key = key;
  166. entries[entryIndex].next = _buckets[bucketIndex] - 1;
  167. _buckets[bucketIndex] = entryIndex + 1;
  168. _count++;
  169. return ref entries[entryIndex].value;
  170. }
  171. private Entry[] Resize()
  172. {
  173. Debug.Assert(_entries.Length == _count || _entries.Length == 1); // We only copy _count, so if it's longer we will miss some
  174. int count = _count;
  175. int newSize = _entries.Length * 2;
  176. if ((uint)newSize > (uint)int.MaxValue) // uint cast handles overflow
  177. throw new InvalidOperationException("Capacity Overflow");
  178. var entries = new Entry[newSize];
  179. Array.Copy(_entries, 0, entries, 0, count);
  180. var newBuckets = new int[entries.Length];
  181. while (count-- > 0)
  182. {
  183. int bucketIndex = entries[count].key.GetHashCode() & (newBuckets.Length - 1);
  184. entries[count].next = newBuckets[bucketIndex] - 1;
  185. newBuckets[bucketIndex] = count + 1;
  186. }
  187. _buckets = newBuckets;
  188. _entries = entries;
  189. return entries;
  190. }
  191. /// <summary>
  192. /// Gets an enumerator over the dictionary
  193. /// </summary>
  194. public Enumerator GetEnumerator() => new Enumerator(this); // avoid boxing
  195. /// <summary>
  196. /// Gets an enumerator over the dictionary
  197. /// </summary>
  198. IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator() =>
  199. new Enumerator(this);
  200. /// <summary>
  201. /// Gets an enumerator over the dictionary
  202. /// </summary>
  203. IEnumerator IEnumerable.GetEnumerator() => new Enumerator(this);
  204. public struct Enumerator : IEnumerator<KeyValuePair<TKey, TValue>>
  205. {
  206. private readonly DictionarySlim<TKey, TValue> _dictionary;
  207. private int _index;
  208. private int _count;
  209. private KeyValuePair<TKey, TValue> _current;
  210. internal Enumerator(DictionarySlim<TKey, TValue> dictionary)
  211. {
  212. _dictionary = dictionary;
  213. _index = 0;
  214. _count = _dictionary._count;
  215. _current = default;
  216. }
  217. public bool MoveNext()
  218. {
  219. if (_count == 0)
  220. {
  221. _current = default;
  222. return false;
  223. }
  224. _count--;
  225. while (_dictionary._entries[_index].next < -1)
  226. _index++;
  227. _current = new KeyValuePair<TKey, TValue>(
  228. _dictionary._entries[_index].key,
  229. _dictionary._entries[_index++].value);
  230. return true;
  231. }
  232. public KeyValuePair<TKey, TValue> Current => _current;
  233. object IEnumerator.Current => _current;
  234. void IEnumerator.Reset()
  235. {
  236. _index = 0;
  237. _count = _dictionary._count;
  238. _current = default;
  239. }
  240. public void Dispose() { }
  241. }
  242. internal static class HashHelpers
  243. {
  244. internal static readonly int[] SizeOneIntArray = new int[1];
  245. internal static int PowerOf2(int v)
  246. {
  247. if ((v & (v - 1)) == 0) return v;
  248. int i = 2;
  249. while (i < v) i <<= 1;
  250. return i;
  251. }
  252. }
  253. }
  254. }