StringDictionarySlim.cs 11 KB

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