StringDictionarySlim.cs 12 KB

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