TreeDictionary.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Diagnostics.CodeAnalysis;
  5. namespace Ryujinx.Common.Collections
  6. {
  7. /// <summary>
  8. /// Dictionary that provides the ability for O(logN) Lookups for keys that exist in the Dictionary, and O(logN) lookups for keys immediately greater than or less than a specified key.
  9. /// </summary>
  10. /// <typeparam name="K">Key</typeparam>
  11. /// <typeparam name="V">Value</typeparam>
  12. public class TreeDictionary<K, V> : IntrusiveRedBlackTreeImpl<Node<K, V>>, IDictionary<K, V> where K : IComparable<K>
  13. {
  14. #region Public Methods
  15. /// <summary>
  16. /// Returns the value of the node whose key is <paramref name="key"/>, or the default value if no such node exists.
  17. /// </summary>
  18. /// <param name="key">Key of the node value to get</param>
  19. /// <returns>Value associated w/ <paramref name="key"/></returns>
  20. /// <exception cref="ArgumentNullException"><paramref name="key"/> is null</exception>
  21. public V Get(K key)
  22. {
  23. if (key == null)
  24. {
  25. throw new ArgumentNullException(nameof(key));
  26. }
  27. Node<K, V> node = GetNode(key);
  28. if (node == null)
  29. {
  30. return default;
  31. }
  32. return node.Value;
  33. }
  34. /// <summary>
  35. /// Adds a new node into the tree whose key is <paramref name="key"/> key and value is <paramref name="value"/>.
  36. /// <br></br>
  37. /// <b>Note:</b> Adding the same key multiple times will cause the value for that key to be overwritten.
  38. /// </summary>
  39. /// <param name="key">Key of the node to add</param>
  40. /// <param name="value">Value of the node to add</param>
  41. /// <exception cref="ArgumentNullException"><paramref name="key"/> or <paramref name="value"/> are null</exception>
  42. public void Add(K key, V value)
  43. {
  44. if (key == null)
  45. {
  46. throw new ArgumentNullException(nameof(key));
  47. }
  48. if (value == null)
  49. {
  50. throw new ArgumentNullException(nameof(value));
  51. }
  52. Insert(key, value);
  53. }
  54. /// <summary>
  55. /// Removes the node whose key is <paramref name="key"/> from the tree.
  56. /// </summary>
  57. /// <param name="key">Key of the node to remove</param>
  58. /// <exception cref="ArgumentNullException"><paramref name="key"/> is null</exception>
  59. public void Remove(K key)
  60. {
  61. if (key == null)
  62. {
  63. throw new ArgumentNullException(nameof(key));
  64. }
  65. if (Delete(key) != null)
  66. {
  67. Count--;
  68. }
  69. }
  70. /// <summary>
  71. /// Returns the value whose key is equal to or immediately less than <paramref name="key"/>.
  72. /// </summary>
  73. /// <param name="key">Key for which to find the floor value of</param>
  74. /// <returns>Key of node immediately less than <paramref name="key"/></returns>
  75. /// <exception cref="ArgumentNullException"><paramref name="key"/> is null</exception>
  76. public K Floor(K key)
  77. {
  78. Node<K, V> node = FloorNode(key);
  79. if (node != null)
  80. {
  81. return node.Key;
  82. }
  83. return default;
  84. }
  85. /// <summary>
  86. /// Returns the node whose key is equal to or immediately greater than <paramref name="key"/>.
  87. /// </summary>
  88. /// <param name="key">Key for which to find the ceiling node of</param>
  89. /// <returns>Key of node immediately greater than <paramref name="key"/></returns>
  90. /// <exception cref="ArgumentNullException"><paramref name="key"/> is null</exception>
  91. public K Ceiling(K key)
  92. {
  93. Node<K, V> node = CeilingNode(key);
  94. if (node != null)
  95. {
  96. return node.Key;
  97. }
  98. return default;
  99. }
  100. /// <summary>
  101. /// Finds the value whose key is immediately greater than <paramref name="key"/>.
  102. /// </summary>
  103. /// <param name="key">Key to find the successor of</param>
  104. /// <returns>Value</returns>
  105. public K SuccessorOf(K key)
  106. {
  107. Node<K, V> node = GetNode(key);
  108. if (node != null)
  109. {
  110. Node<K, V> successor = SuccessorOf(node);
  111. return successor != null ? successor.Key : default;
  112. }
  113. return default;
  114. }
  115. /// <summary>
  116. /// Finds the value whose key is immediately less than <paramref name="key"/>.
  117. /// </summary>
  118. /// <param name="key">Key to find the predecessor of</param>
  119. /// <returns>Value</returns>
  120. public K PredecessorOf(K key)
  121. {
  122. Node<K, V> node = GetNode(key);
  123. if (node != null)
  124. {
  125. Node<K, V> predecessor = PredecessorOf(node);
  126. return predecessor != null ? predecessor.Key : default;
  127. }
  128. return default;
  129. }
  130. /// <summary>
  131. /// Adds all the nodes in the dictionary as key/value pairs into <paramref name="list"/>.
  132. /// <br></br>
  133. /// The key/value pairs will be added in Level Order.
  134. /// </summary>
  135. /// <param name="list">List to add the tree pairs into</param>
  136. public List<KeyValuePair<K, V>> AsLevelOrderList()
  137. {
  138. List<KeyValuePair<K, V>> list = new List<KeyValuePair<K, V>>();
  139. Queue<Node<K, V>> nodes = new Queue<Node<K, V>>();
  140. if (this.Root != null)
  141. {
  142. nodes.Enqueue(this.Root);
  143. }
  144. while (nodes.TryDequeue(out Node<K, V> node))
  145. {
  146. list.Add(new KeyValuePair<K, V>(node.Key, node.Value));
  147. if (node.Left != null)
  148. {
  149. nodes.Enqueue(node.Left);
  150. }
  151. if (node.Right != null)
  152. {
  153. nodes.Enqueue(node.Right);
  154. }
  155. }
  156. return list;
  157. }
  158. /// <summary>
  159. /// Adds all the nodes in the dictionary into <paramref name="list"/>.
  160. /// </summary>
  161. /// <returns>A list of all KeyValuePairs sorted by Key Order</returns>
  162. public List<KeyValuePair<K, V>> AsList()
  163. {
  164. List<KeyValuePair<K, V>> list = new List<KeyValuePair<K, V>>();
  165. AddToList(Root, list);
  166. return list;
  167. }
  168. #endregion
  169. #region Private Methods (BST)
  170. /// <summary>
  171. /// Adds all nodes that are children of or contained within <paramref name="node"/> into <paramref name="list"/>, in Key Order.
  172. /// </summary>
  173. /// <param name="node">The node to search for nodes within</param>
  174. /// <param name="list">The list to add node to</param>
  175. private void AddToList(Node<K, V> node, List<KeyValuePair<K, V>> list)
  176. {
  177. if (node == null)
  178. {
  179. return;
  180. }
  181. AddToList(node.Left, list);
  182. list.Add(new KeyValuePair<K, V>(node.Key, node.Value));
  183. AddToList(node.Right, list);
  184. }
  185. /// <summary>
  186. /// Retrieve the node reference whose key is <paramref name="key"/>, or null if no such node exists.
  187. /// </summary>
  188. /// <param name="key">Key of the node to get</param>
  189. /// <returns>Node reference in the tree</returns>
  190. /// <exception cref="ArgumentNullException"><paramref name="key"/> is null</exception>
  191. private Node<K, V> GetNode(K key)
  192. {
  193. if (key == null)
  194. {
  195. throw new ArgumentNullException(nameof(key));
  196. }
  197. Node<K, V> node = Root;
  198. while (node != null)
  199. {
  200. int cmp = key.CompareTo(node.Key);
  201. if (cmp < 0)
  202. {
  203. node = node.Left;
  204. }
  205. else if (cmp > 0)
  206. {
  207. node = node.Right;
  208. }
  209. else
  210. {
  211. return node;
  212. }
  213. }
  214. return null;
  215. }
  216. /// <summary>
  217. /// Inserts a new node into the tree whose key is <paramref name="key"/> and value is <paramref name="value"/>.
  218. /// <br></br>
  219. /// Adding the same key multiple times will overwrite the previous value.
  220. /// </summary>
  221. /// <param name="key">Key of the node to insert</param>
  222. /// <param name="value">Value of the node to insert</param>
  223. private void Insert(K key, V value)
  224. {
  225. Node<K, V> newNode = BSTInsert(key, value);
  226. RestoreBalanceAfterInsertion(newNode);
  227. }
  228. /// <summary>
  229. /// Insertion Mechanism for a Binary Search Tree (BST).
  230. /// <br></br>
  231. /// Iterates the tree starting from the root and inserts a new node where all children in the left subtree are less than <paramref name="key"/>, and all children in the right subtree are greater than <paramref name="key"/>.
  232. /// <br></br>
  233. /// <b>Note: </b> If a node whose key is <paramref name="key"/> already exists, it's value will be overwritten.
  234. /// </summary>
  235. /// <param name="key">Key of the node to insert</param>
  236. /// <param name="value">Value of the node to insert</param>
  237. /// <returns>The inserted Node</returns>
  238. private Node<K, V> BSTInsert(K key, V value)
  239. {
  240. Node<K, V> parent = null;
  241. Node<K, V> node = Root;
  242. while (node != null)
  243. {
  244. parent = node;
  245. int cmp = key.CompareTo(node.Key);
  246. if (cmp < 0)
  247. {
  248. node = node.Left;
  249. }
  250. else if (cmp > 0)
  251. {
  252. node = node.Right;
  253. }
  254. else
  255. {
  256. node.Value = value;
  257. return node;
  258. }
  259. }
  260. Node<K, V> newNode = new Node<K, V>(key, value, parent);
  261. if (newNode.Parent == null)
  262. {
  263. Root = newNode;
  264. }
  265. else if (key.CompareTo(parent.Key) < 0)
  266. {
  267. parent.Left = newNode;
  268. }
  269. else
  270. {
  271. parent.Right = newNode;
  272. }
  273. Count++;
  274. return newNode;
  275. }
  276. /// <summary>
  277. /// Removes <paramref name="key"/> from the dictionary, if it exists.
  278. /// </summary>
  279. /// <param name="key">Key of the node to delete</param>
  280. /// <returns>The deleted Node</returns>
  281. private Node<K, V> Delete(K key)
  282. {
  283. // O(1) Retrieval
  284. Node<K, V> nodeToDelete = GetNode(key);
  285. if (nodeToDelete == null) return null;
  286. Node<K, V> replacementNode;
  287. if (LeftOf(nodeToDelete) == null || RightOf(nodeToDelete) == null)
  288. {
  289. replacementNode = nodeToDelete;
  290. }
  291. else
  292. {
  293. replacementNode = PredecessorOf(nodeToDelete);
  294. }
  295. Node<K, V> tmp = LeftOf(replacementNode) ?? RightOf(replacementNode);
  296. if (tmp != null)
  297. {
  298. tmp.Parent = ParentOf(replacementNode);
  299. }
  300. if (ParentOf(replacementNode) == null)
  301. {
  302. Root = tmp;
  303. }
  304. else if (replacementNode == LeftOf(ParentOf(replacementNode)))
  305. {
  306. ParentOf(replacementNode).Left = tmp;
  307. }
  308. else
  309. {
  310. ParentOf(replacementNode).Right = tmp;
  311. }
  312. if (replacementNode != nodeToDelete)
  313. {
  314. nodeToDelete.Key = replacementNode.Key;
  315. nodeToDelete.Value = replacementNode.Value;
  316. }
  317. if (tmp != null && ColorOf(replacementNode) == Black)
  318. {
  319. RestoreBalanceAfterRemoval(tmp);
  320. }
  321. return replacementNode;
  322. }
  323. /// <summary>
  324. /// Returns the node whose key immediately less than or equal to <paramref name="key"/>.
  325. /// </summary>
  326. /// <param name="key">Key for which to find the floor node of</param>
  327. /// <returns>Node whose key is immediately less than or equal to <paramref name="key"/>, or null if no such node is found.</returns>
  328. /// <exception cref="ArgumentNullException"><paramref name="key"/> is null</exception>
  329. private Node<K, V> FloorNode(K key)
  330. {
  331. if (key == null)
  332. {
  333. throw new ArgumentNullException(nameof(key));
  334. }
  335. Node<K, V> tmp = Root;
  336. while (tmp != null)
  337. {
  338. int cmp = key.CompareTo(tmp.Key);
  339. if (cmp > 0)
  340. {
  341. if (tmp.Right != null)
  342. {
  343. tmp = tmp.Right;
  344. }
  345. else
  346. {
  347. return tmp;
  348. }
  349. }
  350. else if (cmp < 0)
  351. {
  352. if (tmp.Left != null)
  353. {
  354. tmp = tmp.Left;
  355. }
  356. else
  357. {
  358. Node<K, V> parent = tmp.Parent;
  359. Node<K, V> ptr = tmp;
  360. while (parent != null && ptr == parent.Left)
  361. {
  362. ptr = parent;
  363. parent = parent.Parent;
  364. }
  365. return parent;
  366. }
  367. }
  368. else
  369. {
  370. return tmp;
  371. }
  372. }
  373. return null;
  374. }
  375. /// <summary>
  376. /// Returns the node whose key is immediately greater than or equal to than <paramref name="key"/>.
  377. /// </summary>
  378. /// <param name="key">Key for which to find the ceiling node of</param>
  379. /// <returns>Node whose key is immediately greater than or equal to <paramref name="key"/>, or null if no such node is found.</returns>
  380. /// <exception cref="ArgumentNullException"><paramref name="key"/> is null</exception>
  381. private Node<K, V> CeilingNode(K key)
  382. {
  383. if (key == null)
  384. {
  385. throw new ArgumentNullException(nameof(key));
  386. }
  387. Node<K, V> tmp = Root;
  388. while (tmp != null)
  389. {
  390. int cmp = key.CompareTo(tmp.Key);
  391. if (cmp < 0)
  392. {
  393. if (tmp.Left != null)
  394. {
  395. tmp = tmp.Left;
  396. }
  397. else
  398. {
  399. return tmp;
  400. }
  401. }
  402. else if (cmp > 0)
  403. {
  404. if (tmp.Right != null)
  405. {
  406. tmp = tmp.Right;
  407. }
  408. else
  409. {
  410. Node<K, V> parent = tmp.Parent;
  411. Node<K, V> ptr = tmp;
  412. while (parent != null && ptr == parent.Right)
  413. {
  414. ptr = parent;
  415. parent = parent.Parent;
  416. }
  417. return parent;
  418. }
  419. }
  420. else
  421. {
  422. return tmp;
  423. }
  424. }
  425. return null;
  426. }
  427. #endregion
  428. #region Interface Implementations
  429. // Method descriptions are not provided as they are already included as part of the interface.
  430. public bool ContainsKey(K key)
  431. {
  432. if (key == null)
  433. {
  434. throw new ArgumentNullException(nameof(key));
  435. }
  436. return GetNode(key) != null;
  437. }
  438. bool IDictionary<K, V>.Remove(K key)
  439. {
  440. int count = Count;
  441. Remove(key);
  442. return count > Count;
  443. }
  444. public bool TryGetValue(K key, [MaybeNullWhen(false)] out V value)
  445. {
  446. if (null == key)
  447. {
  448. throw new ArgumentNullException(nameof(key));
  449. }
  450. Node<K, V> node = GetNode(key);
  451. value = node != null ? node.Value : default;
  452. return node != null;
  453. }
  454. public void Add(KeyValuePair<K, V> item)
  455. {
  456. if (item.Key == null)
  457. {
  458. throw new ArgumentNullException(nameof(item.Key));
  459. }
  460. Add(item.Key, item.Value);
  461. }
  462. public bool Contains(KeyValuePair<K, V> item)
  463. {
  464. if (item.Key == null)
  465. {
  466. return false;
  467. }
  468. Node<K, V> node = GetNode(item.Key);
  469. if (node != null)
  470. {
  471. return node.Key.Equals(item.Key) && node.Value.Equals(item.Value);
  472. }
  473. return false;
  474. }
  475. public void CopyTo(KeyValuePair<K, V>[] array, int arrayIndex)
  476. {
  477. if (arrayIndex < 0 || array.Length - arrayIndex < this.Count)
  478. {
  479. throw new ArgumentOutOfRangeException(nameof(arrayIndex));
  480. }
  481. SortedList<K, V> list = GetKeyValues();
  482. int offset = 0;
  483. for (int i = arrayIndex; i < array.Length && offset < list.Count; i++)
  484. {
  485. array[i] = new KeyValuePair<K, V>(list.Keys[i], list.Values[i]);
  486. offset++;
  487. }
  488. }
  489. public bool Remove(KeyValuePair<K, V> item)
  490. {
  491. Node<K, V> node = GetNode(item.Key);
  492. if (node == null)
  493. {
  494. return false;
  495. }
  496. if (node.Value.Equals(item.Value))
  497. {
  498. int count = Count;
  499. Remove(item.Key);
  500. return count > Count;
  501. }
  502. return false;
  503. }
  504. public IEnumerator<KeyValuePair<K, V>> GetEnumerator()
  505. {
  506. return GetKeyValues().GetEnumerator();
  507. }
  508. IEnumerator IEnumerable.GetEnumerator()
  509. {
  510. return GetKeyValues().GetEnumerator();
  511. }
  512. public ICollection<K> Keys => GetKeyValues().Keys;
  513. public ICollection<V> Values => GetKeyValues().Values;
  514. public bool IsReadOnly => false;
  515. public V this[K key]
  516. {
  517. get => Get(key);
  518. set => Add(key, value);
  519. }
  520. #endregion
  521. #region Private Interface Helper Methods
  522. /// <summary>
  523. /// Returns a sorted list of all the node keys / values in the tree.
  524. /// </summary>
  525. /// <returns>List of node keys</returns>
  526. private SortedList<K, V> GetKeyValues()
  527. {
  528. SortedList<K, V> set = new SortedList<K, V>();
  529. Queue<Node<K, V>> queue = new Queue<Node<K, V>>();
  530. if (Root != null)
  531. {
  532. queue.Enqueue(Root);
  533. }
  534. while (queue.TryDequeue(out Node<K, V> node))
  535. {
  536. set.Add(node.Key, node.Value);
  537. if (null != node.Left)
  538. {
  539. queue.Enqueue(node.Left);
  540. }
  541. if (null != node.Right)
  542. {
  543. queue.Enqueue(node.Right);
  544. }
  545. }
  546. return set;
  547. }
  548. #endregion
  549. }
  550. /// <summary>
  551. /// Represents a node in the TreeDictionary which contains a key and value of generic type K and V, respectively.
  552. /// </summary>
  553. /// <typeparam name="K">Key of the node</typeparam>
  554. /// <typeparam name="V">Value of the node</typeparam>
  555. public class Node<K, V> : IntrusiveRedBlackTreeNode<Node<K, V>> where K : IComparable<K>
  556. {
  557. internal K Key;
  558. internal V Value;
  559. internal Node(K key, V value, Node<K, V> parent)
  560. {
  561. Key = key;
  562. Value = value;
  563. Parent = parent;
  564. }
  565. }
  566. }