StringDictionarySlim.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  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. public bool TryAdd(Key key, TValue value)
  153. {
  154. Entry[] entries = _entries;
  155. int bucketIndex = key.HashCode & (_buckets.Length - 1);
  156. for (int i = _buckets[bucketIndex] - 1;
  157. (uint)i < (uint)entries.Length; i = entries[i].next)
  158. {
  159. if (key.Name == entries[i].key.Name)
  160. {
  161. return false;
  162. }
  163. }
  164. AddKey(key, bucketIndex) = value;
  165. return true;
  166. }
  167. /// <summary>
  168. /// Adds a new item and expects key to not to exist.
  169. /// </summary>
  170. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  171. public void AddDangerous(in Key key, TValue value)
  172. {
  173. AddKey(key, key.HashCode & (_buckets.Length - 1)) = value;
  174. }
  175. public ref TValue this[Key key]
  176. {
  177. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  178. get => ref GetOrAddValueRef(key);
  179. }
  180. [MethodImpl(MethodImplOptions.NoInlining)]
  181. private ref TValue AddKey(Key key, int bucketIndex)
  182. {
  183. Entry[] entries = _entries;
  184. int entryIndex;
  185. if (_freeList != -1)
  186. {
  187. entryIndex = _freeList;
  188. _freeList = -3 - entries[_freeList].next;
  189. }
  190. else
  191. {
  192. if (_count == entries.Length || entries.Length == 1)
  193. {
  194. entries = Resize();
  195. bucketIndex = key.HashCode & (_buckets.Length - 1);
  196. // entry indexes were not changed by Resize
  197. }
  198. entryIndex = _count;
  199. }
  200. entries[entryIndex].key = key;
  201. entries[entryIndex].next = _buckets[bucketIndex] - 1;
  202. _buckets[bucketIndex] = entryIndex + 1;
  203. _count++;
  204. return ref entries[entryIndex].value;
  205. }
  206. private Entry[] Resize()
  207. {
  208. Debug.Assert(_entries.Length == _count || _entries.Length == 1); // We only copy _count, so if it's longer we will miss some
  209. int count = _count;
  210. int newSize = _entries.Length * 2;
  211. if ((uint)newSize > (uint)int.MaxValue) // uint cast handles overflow
  212. throw new InvalidOperationException("Capacity Overflow");
  213. var entries = new Entry[newSize];
  214. Array.Copy(_entries, 0, entries, 0, count);
  215. var newBuckets = new int[entries.Length];
  216. while (count-- > 0)
  217. {
  218. int bucketIndex = entries[count].key.HashCode & (newBuckets.Length - 1);
  219. entries[count].next = newBuckets[bucketIndex] - 1;
  220. newBuckets[bucketIndex] = count + 1;
  221. }
  222. _buckets = newBuckets;
  223. _entries = entries;
  224. return entries;
  225. }
  226. /// <summary>
  227. /// Gets an enumerator over the dictionary
  228. /// </summary>
  229. public Enumerator GetEnumerator() => new Enumerator(this); // avoid boxing
  230. /// <summary>
  231. /// Gets an enumerator over the dictionary
  232. /// </summary>
  233. IEnumerator<KeyValuePair<Key, TValue>> IEnumerable<KeyValuePair<Key, TValue>>.GetEnumerator() =>
  234. new Enumerator(this);
  235. /// <summary>
  236. /// Gets an enumerator over the dictionary
  237. /// </summary>
  238. IEnumerator IEnumerable.GetEnumerator() => new Enumerator(this);
  239. public struct Enumerator : IEnumerator<KeyValuePair<Key, TValue>>
  240. {
  241. private readonly StringDictionarySlim<TValue> _dictionary;
  242. private int _index;
  243. private int _count;
  244. private KeyValuePair<Key, TValue> _current;
  245. internal Enumerator(StringDictionarySlim<TValue> dictionary)
  246. {
  247. _dictionary = dictionary;
  248. _index = 0;
  249. _count = _dictionary._count;
  250. _current = default;
  251. }
  252. public bool MoveNext()
  253. {
  254. if (_count == 0)
  255. {
  256. _current = default;
  257. return false;
  258. }
  259. _count--;
  260. while (_dictionary._entries[_index].next < -1)
  261. _index++;
  262. _current = new KeyValuePair<Key, TValue>(
  263. _dictionary._entries[_index].key,
  264. _dictionary._entries[_index++].value);
  265. return true;
  266. }
  267. public KeyValuePair<Key, TValue> Current => _current;
  268. object IEnumerator.Current => _current;
  269. void IEnumerator.Reset()
  270. {
  271. _index = 0;
  272. _count = _dictionary._count;
  273. _current = default;
  274. }
  275. public void Dispose() { }
  276. }
  277. internal static class HashHelpers
  278. {
  279. internal static readonly int[] SizeOneIntArray = new int[1];
  280. internal static int PowerOf2(int v)
  281. {
  282. if ((v & (v - 1)) == 0) return v;
  283. int i = 2;
  284. while (i < v) i <<= 1;
  285. return i;
  286. }
  287. }
  288. internal sealed class DictionarySlimDebugView<V>
  289. {
  290. private readonly StringDictionarySlim<V> _dictionary;
  291. public DictionarySlimDebugView(StringDictionarySlim<V> dictionary)
  292. {
  293. _dictionary = dictionary ?? throw new ArgumentNullException(nameof(dictionary));
  294. }
  295. [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
  296. public KeyValuePair<Key, V>[] Items => _dictionary.ToArray();
  297. }
  298. }
  299. }