DictionarySlim.cs 9.5 KB

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