StringDictionarySlim.cs 12 KB

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