OrderedDictionary.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  1. #pragma warning disable CA1863 // Cache a 'CompositeFormat' for repeated use in this formatting operation
  2. #nullable disable
  3. // based on https://github.com/jehugaleahsa/truncon.collections.OrderedDictionary
  4. // https://github.com/jehugaleahsa/truncon.collections.OrderedDictionary/blob/master/UNLICENSE.txt
  5. using System.Collections;
  6. using System.ComponentModel;
  7. using System.Diagnostics;
  8. using System.Globalization;
  9. namespace Jint.Runtime;
  10. /// <summary>
  11. /// Represents a dictionary that tracks the order that items were added.
  12. /// </summary>
  13. /// <typeparam name="TKey">The type of the dictionary keys.</typeparam>
  14. /// <typeparam name="TValue">The type of the dictionary values.</typeparam>
  15. /// <remarks>
  16. /// This dictionary makes it possible to get the index of a key and a key based on an index.
  17. /// It can be costly to find the index of a key because it must be searched for linearly.
  18. /// It can be costly to insert a key/value pair because other key's indexes must be adjusted.
  19. /// It can be costly to remove a key/value pair because other keys' indexes must be adjusted.
  20. /// </remarks>
  21. [DebuggerDisplay("Count = {Count}")]
  22. internal sealed class OrderedDictionary<TKey, TValue>
  23. : IDictionary<TKey, TValue>, IList<KeyValuePair<TKey, TValue>> where TKey : class where TValue : class
  24. {
  25. private readonly Dictionary<TKey, TValue> dictionary;
  26. private readonly List<TKey> keys;
  27. private const string ArrayTooSmall = "The given array was too small to hold the items.";
  28. private const string EditReadOnlyList = "An attempt was made to edit a read-only list.";
  29. private const string IndexOutOfRange = "The index is negative or outside the bounds of the collection.";
  30. private const string TooSmall = "The given value cannot be less than {0}.";
  31. /// <summary>
  32. /// Initializes a new instance of an OrderedDictionary.
  33. /// </summary>
  34. public OrderedDictionary()
  35. {
  36. dictionary = new Dictionary<TKey, TValue>();
  37. keys = new List<TKey>();
  38. }
  39. /// <summary>
  40. /// Initializes a new instance of an OrderedDictionary.
  41. /// </summary>
  42. /// <param name="capacity">The initial capacity of the dictionary.</param>
  43. /// <exception cref="System.ArgumentOutOfRangeException">The capacity is less than zero.</exception>
  44. public OrderedDictionary(int capacity)
  45. {
  46. dictionary = new Dictionary<TKey, TValue>(capacity);
  47. keys = new List<TKey>(capacity);
  48. }
  49. /// <summary>
  50. /// Initializes a new instance of an OrderedDictionary.
  51. /// </summary>
  52. /// <param name="comparer">The equality comparer to use to compare keys.</param>
  53. public OrderedDictionary(IEqualityComparer<TKey> comparer)
  54. {
  55. dictionary = new Dictionary<TKey, TValue>(comparer);
  56. keys = new List<TKey>();
  57. }
  58. /// <summary>
  59. /// Initializes a new instance of an OrderedDictionary.
  60. /// </summary>
  61. /// <param name="capacity">The initial capacity of the dictionary.</param>
  62. /// <param name="comparer">The equality comparer to use to compare keys.</param>
  63. public OrderedDictionary(int capacity, IEqualityComparer<TKey> comparer)
  64. {
  65. dictionary = new Dictionary<TKey, TValue>(capacity, comparer);
  66. keys = new List<TKey>(capacity);
  67. }
  68. /// <summary>
  69. /// Adds the given key/value pair to the dictionary.
  70. /// </summary>
  71. /// <param name="key">The key to add to the dictionary.</param>
  72. /// <param name="value">The value to associated with the key.</param>
  73. /// <exception cref="System.ArgumentException">The given key already exists in the dictionary.</exception>
  74. /// <exception cref="System.ArgumentNullException">The key is null.</exception>
  75. public void Add(TKey key, TValue value)
  76. {
  77. dictionary.Add(key, value);
  78. keys.Add(key);
  79. }
  80. /// <summary>
  81. /// Inserts the given key/value pair at the specified index.
  82. /// </summary>
  83. /// <param name="index">The index to insert the key/value pair.</param>
  84. /// <param name="key">The key to insert.</param>
  85. /// <param name="value">The value to insert.</param>
  86. /// <exception cref="System.ArgumentException">The given key already exists in the dictionary.</exception>
  87. /// <exception cref="System.ArgumentNullException">The key is null.</exception>
  88. /// <exception cref="System.ArgumentOutOfRangeException">The index is negative -or- larger than the size of the dictionary.</exception>
  89. public void Insert(int index, TKey key, TValue value)
  90. {
  91. if (index < 0 || index > dictionary.Count)
  92. {
  93. Throw.ArgumentOutOfRangeException(nameof(index), IndexOutOfRange);
  94. }
  95. dictionary.Add(key, value);
  96. keys.Insert(index, key);
  97. }
  98. /// <summary>
  99. /// Determines whether the given key exists in the dictionary.
  100. /// </summary>
  101. /// <param name="key">The key to look for.</param>
  102. /// <returns>True if the key exists in the dictionary; otherwise, false.</returns>
  103. /// <exception cref="System.ArgumentNullException">The key is null.</exception>
  104. public bool ContainsKey(TKey key)
  105. {
  106. return dictionary.ContainsKey(key);
  107. }
  108. /// <summary>
  109. /// Gets the key at the given index.
  110. /// </summary>
  111. /// <param name="index">The index of the key to get.</param>
  112. /// <returns>The key at the given index.</returns>
  113. /// <exception cref="System.ArgumentOutOfRangeException">The index is negative -or- larger than the number of keys.</exception>
  114. public TKey GetKey(int index)
  115. {
  116. return keys[index];
  117. }
  118. /// <summary>
  119. /// Gets the index of the given key.
  120. /// </summary>
  121. /// <param name="key">The key to get the index of.</param>
  122. /// <returns>The index of the key in the dictionary -or- -1 if the key is not found.</returns>
  123. /// <remarks>The operation runs in O(n).</remarks>
  124. public int IndexOf(TKey key)
  125. {
  126. if (!dictionary.ContainsKey(key))
  127. {
  128. return -1;
  129. }
  130. var keysCount = keys.Count;
  131. for (int i = 0; i < keysCount; ++i)
  132. {
  133. if (dictionary.Comparer.Equals(keys[i], key))
  134. {
  135. return i;
  136. }
  137. }
  138. return -1;
  139. }
  140. /// <summary>
  141. /// Gets the keys in the dictionary in the order they were added.
  142. /// </summary>
  143. public KeyCollection Keys => new KeyCollection(this);
  144. /// <summary>
  145. /// Removes the key/value pair with the given key from the dictionary.
  146. /// </summary>
  147. /// <param name="key">The key of the pair to remove.</param>
  148. /// <returns>True if the key was found and the pair removed; otherwise, false.</returns>
  149. /// <exception cref="System.ArgumentNullException">The key is null.</exception>
  150. /// <remarks>This operation runs in O(n).</remarks>
  151. public bool Remove(TKey key)
  152. {
  153. if (dictionary.Remove(key))
  154. {
  155. var keysCount = keys.Count;
  156. for (int i = 0; i < keysCount; ++i)
  157. {
  158. if (dictionary.Comparer.Equals(keys[i], key))
  159. {
  160. keys.RemoveAt(i);
  161. break;
  162. }
  163. }
  164. return true;
  165. }
  166. return false;
  167. }
  168. /// <summary>
  169. /// Removes the key/value pair at the given index.
  170. /// </summary>
  171. /// <param name="index">The index of the key/value pair to remove.</param>
  172. /// <exception cref="System.ArgumentOutOfRangeException">The index is negative -or- larger than the size of the dictionary.</exception>
  173. /// <remarks>This operation runs in O(n).</remarks>
  174. public void RemoveAt(int index)
  175. {
  176. TKey key = keys[index];
  177. dictionary.Remove(key);
  178. keys.RemoveAt(index);
  179. }
  180. /// <summary>
  181. /// Tries to get the value associated with the given key. If the key is not found,
  182. /// default(TValue) value is stored in the value.
  183. /// </summary>
  184. /// <param name="key">The key to get the value for.</param>
  185. /// <param name="value">The value used to hold the results.</param>
  186. /// <returns>True if the key was found; otherwise, false.</returns>
  187. /// <exception cref="System.ArgumentNullException">The key is null.</exception>
  188. public bool TryGetValue(TKey key, out TValue value)
  189. {
  190. return dictionary.TryGetValue(key, out value);
  191. }
  192. /// <summary>
  193. /// Gets the values in the dictionary.
  194. /// </summary>
  195. public ValueCollection Values => new ValueCollection(this);
  196. /// <summary>
  197. /// Gets or sets the value at the given index.
  198. /// </summary>
  199. /// <param name="index">The index of the value to get.</param>
  200. /// <returns>The value at the given index.</returns>
  201. /// <exception cref="System.ArgumentOutOfRangeException">The index is negative -or- beyond the length of the dictionary.</exception>
  202. public TValue this[int index]
  203. {
  204. get => dictionary[keys[index]];
  205. set => dictionary[keys[index]] = value;
  206. }
  207. /// <summary>
  208. /// Gets or sets the value associated with the given key.
  209. /// </summary>
  210. /// <param name="key">The key to get the associated value by or to associate with the value.</param>
  211. /// <returns>The value associated with the given key.</returns>
  212. /// <exception cref="System.ArgumentNullException">The key is null.</exception>
  213. /// <exception cref="System.Collections.Generic.KeyNotFoundException">The key is not in the dictionary.</exception>
  214. public TValue this[TKey key]
  215. {
  216. get => dictionary[key];
  217. set
  218. {
  219. if (!dictionary.ContainsKey(key))
  220. {
  221. keys.Add(key);
  222. }
  223. dictionary[key] = value;
  224. }
  225. }
  226. /// <summary>
  227. /// Removes all key/value pairs from the dictionary.
  228. /// </summary>
  229. public void Clear()
  230. {
  231. dictionary.Clear();
  232. keys.Clear();
  233. }
  234. /// <summary>
  235. /// Gets the number of key/value pairs in the dictionary.
  236. /// </summary>
  237. public int Count => dictionary.Count;
  238. /// <summary>
  239. /// Gets the key/value pairs in the dictionary in the order they were added.
  240. /// </summary>
  241. /// <returns>An enumerator over the key/value pairs in the dictionary.</returns>
  242. public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
  243. {
  244. foreach (TKey key in keys)
  245. {
  246. yield return new KeyValuePair<TKey, TValue>(key, dictionary[key]);
  247. }
  248. }
  249. int IList<KeyValuePair<TKey, TValue>>.IndexOf(KeyValuePair<TKey, TValue> item)
  250. {
  251. if (!dictionary.TryGetValue(item.Key, out var value))
  252. {
  253. return -1;
  254. }
  255. if (!Equals(item.Value, value))
  256. {
  257. return -1;
  258. }
  259. var keysCount = keys.Count;
  260. for (int i = 0; i < keysCount; ++i)
  261. {
  262. if (dictionary.Comparer.Equals(keys[i], item.Key))
  263. {
  264. return i;
  265. }
  266. }
  267. return -1;
  268. }
  269. void IList<KeyValuePair<TKey, TValue>>.Insert(int index, KeyValuePair<TKey, TValue> item)
  270. {
  271. if (index < 0 || index > dictionary.Count)
  272. {
  273. Throw.ArgumentOutOfRangeException(nameof(index), IndexOutOfRange);
  274. }
  275. dictionary.Add(item.Key, item.Value);
  276. keys.Insert(index, item.Key);
  277. }
  278. KeyValuePair<TKey, TValue> IList<KeyValuePair<TKey, TValue>>.this[int index]
  279. {
  280. get
  281. {
  282. TKey key = keys[index];
  283. TValue value = dictionary[key];
  284. return new KeyValuePair<TKey, TValue>(key, value);
  285. }
  286. set
  287. {
  288. TKey key = keys[index];
  289. if (dictionary.Comparer.Equals(key, value.Key))
  290. {
  291. dictionary[value.Key] = value.Value;
  292. }
  293. else
  294. {
  295. dictionary.Add(value.Key, value.Value);
  296. dictionary.Remove(key);
  297. keys[index] = value.Key;
  298. }
  299. }
  300. }
  301. ICollection<TKey> IDictionary<TKey, TValue>.Keys => Keys;
  302. ICollection<TValue> IDictionary<TKey, TValue>.Values => Values;
  303. void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> item)
  304. {
  305. dictionary.Add(item.Key, item.Value);
  306. keys.Add(item.Key);
  307. }
  308. bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> item)
  309. {
  310. if (!dictionary.TryGetValue(item.Key, out var value))
  311. {
  312. return false;
  313. }
  314. return Equals(value, item.Value);
  315. }
  316. void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
  317. {
  318. if (array == null)
  319. {
  320. Throw.ArgumentNullException(nameof(array));
  321. return;
  322. }
  323. if (arrayIndex < 0)
  324. {
  325. Throw.ArgumentOutOfRangeException(nameof(arrayIndex), string.Format(CultureInfo.CurrentCulture, TooSmall, 0));
  326. }
  327. if (dictionary.Count > array.Length - arrayIndex)
  328. {
  329. Throw.ArgumentException(ArrayTooSmall, nameof(array));
  330. }
  331. foreach (TKey key in keys)
  332. {
  333. TValue value = dictionary[key];
  334. array[arrayIndex] = new KeyValuePair<TKey, TValue>(key, value);
  335. ++arrayIndex;
  336. }
  337. }
  338. bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly => false;
  339. bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item)
  340. {
  341. if (!dictionary.TryGetValue(item.Key, out var value))
  342. {
  343. return false;
  344. }
  345. if (!Equals(item.Value, value))
  346. {
  347. return false;
  348. }
  349. // O(n)
  350. dictionary.Remove(item.Key);
  351. var keysCount = keys.Count;
  352. for (int i = 0; i < keysCount; ++i)
  353. {
  354. if (dictionary.Comparer.Equals(keys[i], item.Key))
  355. {
  356. keys.RemoveAt(i);
  357. }
  358. }
  359. return true;
  360. }
  361. IEnumerator IEnumerable.GetEnumerator()
  362. {
  363. return GetEnumerator();
  364. }
  365. /// <summary>
  366. /// Wraps the keys in an OrderDictionary.
  367. /// </summary>
  368. public sealed class KeyCollection : ICollection<TKey>
  369. {
  370. private readonly OrderedDictionary<TKey, TValue> parent;
  371. /// <summary>
  372. /// Initializes a new instance of a KeyCollection.
  373. /// </summary>
  374. /// <param name="dictionary">The OrderedDictionary whose keys to wrap.</param>
  375. /// <exception cref="System.ArgumentNullException">The dictionary is null.</exception>
  376. public KeyCollection(OrderedDictionary<TKey, TValue> dictionary)
  377. {
  378. parent = dictionary;
  379. }
  380. /// <summary>
  381. /// Copies the keys from the OrderedDictionary to the given array, starting at the given index.
  382. /// </summary>
  383. /// <param name="array">The array to copy the keys to.</param>
  384. /// <param name="arrayIndex">The index into the array to start copying the keys.</param>
  385. /// <exception cref="System.ArgumentNullException">The array is null.</exception>
  386. /// <exception cref="System.ArgumentOutOfRangeException">The arrayIndex is negative.</exception>
  387. /// <exception cref="System.ArgumentException">The array, starting at the given index, is not large enough to contain all the keys.</exception>
  388. public void CopyTo(TKey[] array, int arrayIndex)
  389. {
  390. parent.keys.CopyTo(array, arrayIndex);
  391. }
  392. /// <summary>
  393. /// Gets the number of keys in the OrderedDictionary.
  394. /// </summary>
  395. public int Count
  396. {
  397. get { return parent.dictionary.Count; }
  398. }
  399. /// <summary>
  400. /// Gets an enumerator over the keys in the OrderedDictionary.
  401. /// </summary>
  402. /// <returns>The enumerator.</returns>
  403. public IEnumerator<TKey> GetEnumerator()
  404. {
  405. return parent.keys.GetEnumerator();
  406. }
  407. [EditorBrowsable(EditorBrowsableState.Never)]
  408. bool ICollection<TKey>.Contains(TKey item)
  409. {
  410. return parent.dictionary.ContainsKey(item);
  411. }
  412. [EditorBrowsable(EditorBrowsableState.Never)]
  413. void ICollection<TKey>.Add(TKey item)
  414. {
  415. Throw.NotSupportedException(EditReadOnlyList);
  416. }
  417. [EditorBrowsable(EditorBrowsableState.Never)]
  418. void ICollection<TKey>.Clear()
  419. {
  420. Throw.NotSupportedException(EditReadOnlyList);
  421. }
  422. [EditorBrowsable(EditorBrowsableState.Never)]
  423. bool ICollection<TKey>.IsReadOnly
  424. {
  425. get { return true; }
  426. }
  427. [EditorBrowsable(EditorBrowsableState.Never)]
  428. bool ICollection<TKey>.Remove(TKey item)
  429. {
  430. Throw.NotSupportedException(EditReadOnlyList);
  431. return false;
  432. }
  433. IEnumerator IEnumerable.GetEnumerator()
  434. {
  435. return GetEnumerator();
  436. }
  437. }
  438. /// <summary>
  439. /// Wraps the keys in an OrderDictionary.
  440. /// </summary>
  441. public sealed class ValueCollection : ICollection<TValue>
  442. {
  443. private readonly OrderedDictionary<TKey, TValue> parent;
  444. /// <summary>
  445. /// Initializes a new instance of a ValueCollection.
  446. /// </summary>
  447. /// <param name="dictionary">The OrderedDictionary whose keys to wrap.</param>
  448. /// <exception cref="System.ArgumentNullException">The dictionary is null.</exception>
  449. public ValueCollection(OrderedDictionary<TKey, TValue> dictionary)
  450. {
  451. parent = dictionary;
  452. }
  453. /// <summary>
  454. /// Copies the values from the OrderedDictionary to the given array, starting at the given index.
  455. /// </summary>
  456. /// <param name="array">The array to copy the values to.</param>
  457. /// <param name="arrayIndex">The index into the array to start copying the values.</param>
  458. /// <exception cref="System.ArgumentNullException">The array is null.</exception>
  459. /// <exception cref="System.ArgumentOutOfRangeException">The arrayIndex is negative.</exception>
  460. /// <exception cref="System.ArgumentException">The array, starting at the given index, is not large enough to contain all the values.</exception>
  461. public void CopyTo(TValue[] array, int arrayIndex)
  462. {
  463. if (arrayIndex < 0)
  464. {
  465. Throw.ArgumentOutOfRangeException(nameof(arrayIndex), string.Format(CultureInfo.InvariantCulture, TooSmall, 0));
  466. }
  467. if (parent.dictionary.Count > array.Length - arrayIndex)
  468. {
  469. Throw.ArgumentException(ArrayTooSmall, nameof(array));
  470. }
  471. foreach (TKey key in parent.keys)
  472. {
  473. TValue value = parent.dictionary[key];
  474. array[arrayIndex] = value;
  475. ++arrayIndex;
  476. }
  477. }
  478. /// <summary>
  479. /// Gets the number of values in the OrderedDictionary.
  480. /// </summary>
  481. public int Count => parent.dictionary.Count;
  482. /// <summary>
  483. /// Gets an enumerator over the values in the OrderedDictionary.
  484. /// </summary>
  485. /// <returns>The enumerator.</returns>
  486. public IEnumerator<TValue> GetEnumerator()
  487. {
  488. foreach (TKey key in parent.keys)
  489. {
  490. TValue value = parent.dictionary[key];
  491. yield return value;
  492. }
  493. }
  494. [EditorBrowsable(EditorBrowsableState.Never)]
  495. bool ICollection<TValue>.Contains(TValue item)
  496. {
  497. return parent.dictionary.ContainsValue(item);
  498. }
  499. [EditorBrowsable(EditorBrowsableState.Never)]
  500. void ICollection<TValue>.Add(TValue item)
  501. {
  502. Throw.NotSupportedException(EditReadOnlyList);
  503. }
  504. [EditorBrowsable(EditorBrowsableState.Never)]
  505. void ICollection<TValue>.Clear()
  506. {
  507. Throw.NotSupportedException(EditReadOnlyList);
  508. }
  509. [EditorBrowsable(EditorBrowsableState.Never)]
  510. bool ICollection<TValue>.IsReadOnly => true;
  511. [EditorBrowsable(EditorBrowsableState.Never)]
  512. bool ICollection<TValue>.Remove(TValue item)
  513. {
  514. Throw.NotSupportedException(EditReadOnlyList);
  515. return false;
  516. }
  517. IEnumerator IEnumerable.GetEnumerator()
  518. {
  519. return GetEnumerator();
  520. }
  521. }
  522. }