OrderedDictionary.cs 22 KB

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