2
0

StringDictionarySlim.cs 11 KB

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