StringDictionarySlim.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  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. public void SetOrUpdateValue<TState>(Key key, Func<TValue, TState, TValue> updater, TState state)
  126. {
  127. ref var currentValue = ref GetOrAddValueRef(key);
  128. currentValue = updater(currentValue, state);
  129. }
  130. // Not safe for concurrent _reads_ (at least, if either of them add)
  131. // For concurrent reads, prefer TryGetValue(key, out value)
  132. /// <summary>
  133. /// Gets the value for the specified key, or, if the key is not present,
  134. /// adds an entry and returns the value by ref. This makes it possible to
  135. /// add or update a value in a single look up operation.
  136. /// </summary>
  137. /// <param name="key">Key to look for</param>
  138. /// <returns>Reference to the new or existing value</returns>
  139. public ref TValue GetOrAddValueRef(Key key)
  140. {
  141. Entry[] entries = _entries;
  142. int bucketIndex = key.HashCode & (_buckets.Length - 1);
  143. for (int i = _buckets[bucketIndex] - 1;
  144. (uint)i < (uint)entries.Length; i = entries[i].next)
  145. {
  146. if (key.Name == entries[i].key.Name)
  147. return ref entries[i].value;
  148. }
  149. return ref AddKey(key, bucketIndex);
  150. }
  151. public ref TValue this[Key key]
  152. {
  153. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  154. get => ref GetOrAddValueRef(key);
  155. }
  156. [MethodImpl(MethodImplOptions.NoInlining)]
  157. private ref TValue AddKey(Key key, int bucketIndex)
  158. {
  159. Entry[] entries = _entries;
  160. int entryIndex;
  161. if (_freeList != -1)
  162. {
  163. entryIndex = _freeList;
  164. _freeList = -3 - entries[_freeList].next;
  165. }
  166. else
  167. {
  168. if (_count == entries.Length || entries.Length == 1)
  169. {
  170. entries = Resize();
  171. bucketIndex = key.HashCode & (_buckets.Length - 1);
  172. // entry indexes were not changed by Resize
  173. }
  174. entryIndex = _count;
  175. }
  176. entries[entryIndex].key = key;
  177. entries[entryIndex].next = _buckets[bucketIndex] - 1;
  178. _buckets[bucketIndex] = entryIndex + 1;
  179. _count++;
  180. return ref entries[entryIndex].value;
  181. }
  182. private Entry[] Resize()
  183. {
  184. Debug.Assert(_entries.Length == _count || _entries.Length == 1); // We only copy _count, so if it's longer we will miss some
  185. int count = _count;
  186. int newSize = _entries.Length * 2;
  187. if ((uint)newSize > (uint)int.MaxValue) // uint cast handles overflow
  188. throw new InvalidOperationException("Capacity Overflow");
  189. var entries = new Entry[newSize];
  190. Array.Copy(_entries, 0, entries, 0, count);
  191. var newBuckets = new int[entries.Length];
  192. while (count-- > 0)
  193. {
  194. int bucketIndex = entries[count].key.HashCode & (newBuckets.Length - 1);
  195. entries[count].next = newBuckets[bucketIndex] - 1;
  196. newBuckets[bucketIndex] = count + 1;
  197. }
  198. _buckets = newBuckets;
  199. _entries = entries;
  200. return entries;
  201. }
  202. /// <summary>
  203. /// Gets an enumerator over the dictionary
  204. /// </summary>
  205. public Enumerator GetEnumerator() => new Enumerator(this); // avoid boxing
  206. /// <summary>
  207. /// Gets an enumerator over the dictionary
  208. /// </summary>
  209. IEnumerator<KeyValuePair<Key, TValue>> IEnumerable<KeyValuePair<Key, TValue>>.GetEnumerator() =>
  210. new Enumerator(this);
  211. /// <summary>
  212. /// Gets an enumerator over the dictionary
  213. /// </summary>
  214. IEnumerator IEnumerable.GetEnumerator() => new Enumerator(this);
  215. public struct Enumerator : IEnumerator<KeyValuePair<Key, TValue>>
  216. {
  217. private readonly StringDictionarySlim<TValue> _dictionary;
  218. private int _index;
  219. private int _count;
  220. private KeyValuePair<Key, TValue> _current;
  221. internal Enumerator(StringDictionarySlim<TValue> dictionary)
  222. {
  223. _dictionary = dictionary;
  224. _index = 0;
  225. _count = _dictionary._count;
  226. _current = default;
  227. }
  228. public bool MoveNext()
  229. {
  230. if (_count == 0)
  231. {
  232. _current = default;
  233. return false;
  234. }
  235. _count--;
  236. while (_dictionary._entries[_index].next < -1)
  237. _index++;
  238. _current = new KeyValuePair<Key, TValue>(
  239. _dictionary._entries[_index].key,
  240. _dictionary._entries[_index++].value);
  241. return true;
  242. }
  243. public KeyValuePair<Key, TValue> Current => _current;
  244. object IEnumerator.Current => _current;
  245. void IEnumerator.Reset()
  246. {
  247. _index = 0;
  248. _count = _dictionary._count;
  249. _current = default;
  250. }
  251. public void Dispose() { }
  252. }
  253. internal static class HashHelpers
  254. {
  255. internal static readonly int[] SizeOneIntArray = new int[1];
  256. internal static int PowerOf2(int v)
  257. {
  258. if ((v & (v - 1)) == 0) return v;
  259. int i = 2;
  260. while (i < v) i <<= 1;
  261. return i;
  262. }
  263. }
  264. internal sealed class DictionarySlimDebugView<V>
  265. {
  266. private readonly StringDictionarySlim<V> _dictionary;
  267. public DictionarySlimDebugView(StringDictionarySlim<V> dictionary)
  268. {
  269. _dictionary = dictionary ?? throw new ArgumentNullException(nameof(dictionary));
  270. }
  271. [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
  272. public KeyValuePair<Key, V>[] Items => _dictionary.ToArray();
  273. }
  274. }
  275. }