OrderedDictionary.cs 22 KB

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