StringDictionarySlim.cs 11 KB

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