TreeDictionary.cs 19 KB

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