StringDictionarySlim.cs 11 KB

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