DictionarySlim.cs 10 KB

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