DictionarySlim.cs 10 KB

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