IntervalTree.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. namespace Ryujinx.Common.Collections
  5. {
  6. /// <summary>
  7. /// An Augmented Interval Tree based off of the "TreeDictionary"'s Red-Black Tree. Allows fast overlap checking of ranges.
  8. /// </summary>
  9. /// <typeparam name="K">Key</typeparam>
  10. /// <typeparam name="V">Value</typeparam>
  11. public class IntervalTree<K, V> : IntrusiveRedBlackTreeImpl<IntervalTreeNode<K, V>> where K : IComparable<K>
  12. {
  13. private const int ArrayGrowthSize = 32;
  14. #region Public Methods
  15. /// <summary>
  16. /// Gets the values of the interval whose key is <paramref name="key"/>.
  17. /// </summary>
  18. /// <param name="key">Key of the node value to get</param>
  19. /// <param name="overlaps">Overlaps array to place results in</param>
  20. /// <returns>Number of values found</returns>
  21. /// <exception cref="ArgumentNullException"><paramref name="key"/> is null</exception>
  22. public int Get(K key, ref V[] overlaps)
  23. {
  24. ArgumentNullException.ThrowIfNull(key);
  25. IntervalTreeNode<K, V> node = GetNode(key);
  26. if (node == null)
  27. {
  28. return 0;
  29. }
  30. if (node.Values.Count > overlaps.Length)
  31. {
  32. Array.Resize(ref overlaps, node.Values.Count);
  33. }
  34. int overlapsCount = 0;
  35. foreach (RangeNode<K, V> value in node.Values)
  36. {
  37. overlaps[overlapsCount++] = value.Value;
  38. }
  39. return overlapsCount;
  40. }
  41. /// <summary>
  42. /// Returns the values of the intervals whose start and end keys overlap the given range.
  43. /// </summary>
  44. /// <param name="start">Start of the range</param>
  45. /// <param name="end">End of the range</param>
  46. /// <param name="overlaps">Overlaps array to place results in</param>
  47. /// <param name="overlapCount">Index to start writing results into the array. Defaults to 0</param>
  48. /// <returns>Number of values found</returns>
  49. /// <exception cref="ArgumentNullException"><paramref name="start"/> or <paramref name="end"/> is null</exception>
  50. public int Get(K start, K end, ref V[] overlaps, int overlapCount = 0)
  51. {
  52. ArgumentNullException.ThrowIfNull(start);
  53. ArgumentNullException.ThrowIfNull(end);
  54. GetValues(Root, start, end, ref overlaps, ref overlapCount);
  55. return overlapCount;
  56. }
  57. /// <summary>
  58. /// Adds a new interval into the tree whose start is <paramref name="start"/>, end is <paramref name="end"/> and value is <paramref name="value"/>.
  59. /// </summary>
  60. /// <param name="start">Start of the range to add</param>
  61. /// <param name="end">End of the range to insert</param>
  62. /// <param name="value">Value to add</param>
  63. /// <exception cref="ArgumentNullException"><paramref name="start"/>, <paramref name="end"/> or <paramref name="value"/> are null</exception>
  64. public void Add(K start, K end, V value)
  65. {
  66. ArgumentNullException.ThrowIfNull(start);
  67. ArgumentNullException.ThrowIfNull(end);
  68. ArgumentNullException.ThrowIfNull(value);
  69. Insert(start, end, value);
  70. }
  71. /// <summary>
  72. /// Removes the given <paramref name="value"/> from the tree, searching for it with <paramref name="key"/>.
  73. /// </summary>
  74. /// <param name="key">Key of the node to remove</param>
  75. /// <param name="value">Value to remove</param>
  76. /// <exception cref="ArgumentNullException"><paramref name="key"/> is null</exception>
  77. /// <returns>Number of deleted values</returns>
  78. public int Remove(K key, V value)
  79. {
  80. ArgumentNullException.ThrowIfNull(key);
  81. int removed = Delete(key, value);
  82. Count -= removed;
  83. return removed;
  84. }
  85. /// <summary>
  86. /// Adds all the nodes in the dictionary into <paramref name="list"/>.
  87. /// </summary>
  88. /// <returns>A list of all RangeNodes sorted by Key Order</returns>
  89. public List<RangeNode<K, V>> AsList()
  90. {
  91. List<RangeNode<K, V>> list = new List<RangeNode<K, V>>();
  92. AddToList(Root, list);
  93. return list;
  94. }
  95. #endregion
  96. #region Private Methods (BST)
  97. /// <summary>
  98. /// Adds all RangeNodes that are children of or contained within <paramref name="node"/> into <paramref name="list"/>, in Key Order.
  99. /// </summary>
  100. /// <param name="node">The node to search for RangeNodes within</param>
  101. /// <param name="list">The list to add RangeNodes to</param>
  102. private void AddToList(IntervalTreeNode<K, V> node, List<RangeNode<K, V>> list)
  103. {
  104. if (node == null)
  105. {
  106. return;
  107. }
  108. AddToList(node.Left, list);
  109. list.AddRange(node.Values);
  110. AddToList(node.Right, list);
  111. }
  112. /// <summary>
  113. /// Retrieve the node reference whose key is <paramref name="key"/>, or null if no such node exists.
  114. /// </summary>
  115. /// <param name="key">Key of the node to get</param>
  116. /// <returns>Node reference in the tree</returns>
  117. /// <exception cref="ArgumentNullException"><paramref name="key"/> is null</exception>
  118. private IntervalTreeNode<K, V> GetNode(K key)
  119. {
  120. ArgumentNullException.ThrowIfNull(key);
  121. IntervalTreeNode<K, V> node = Root;
  122. while (node != null)
  123. {
  124. int cmp = key.CompareTo(node.Start);
  125. if (cmp < 0)
  126. {
  127. node = node.Left;
  128. }
  129. else if (cmp > 0)
  130. {
  131. node = node.Right;
  132. }
  133. else
  134. {
  135. return node;
  136. }
  137. }
  138. return null;
  139. }
  140. /// <summary>
  141. /// Retrieve all values that overlap the given start and end keys.
  142. /// </summary>
  143. /// <param name="start">Start of the range</param>
  144. /// <param name="end">End of the range</param>
  145. /// <param name="overlaps">Overlaps array to place results in</param>
  146. /// <param name="overlapCount">Overlaps count to update</param>
  147. private void GetValues(IntervalTreeNode<K, V> node, K start, K end, ref V[] overlaps, ref int overlapCount)
  148. {
  149. if (node == null || start.CompareTo(node.Max) >= 0)
  150. {
  151. return;
  152. }
  153. GetValues(node.Left, start, end, ref overlaps, ref overlapCount);
  154. bool endsOnRight = end.CompareTo(node.Start) > 0;
  155. if (endsOnRight)
  156. {
  157. if (start.CompareTo(node.End) < 0)
  158. {
  159. // Contains this node. Add overlaps to list.
  160. foreach (RangeNode<K,V> overlap in node.Values)
  161. {
  162. if (start.CompareTo(overlap.End) < 0)
  163. {
  164. if (overlaps.Length >= overlapCount)
  165. {
  166. Array.Resize(ref overlaps, overlapCount + ArrayGrowthSize);
  167. }
  168. overlaps[overlapCount++] = overlap.Value;
  169. }
  170. }
  171. }
  172. GetValues(node.Right, start, end, ref overlaps, ref overlapCount);
  173. }
  174. }
  175. /// <summary>
  176. /// Inserts a new node into the tree with a given <paramref name="start"/>, <paramref name="end"/> and <paramref name="value"/>.
  177. /// </summary>
  178. /// <param name="start">Start of the range to insert</param>
  179. /// <param name="end">End of the range to insert</param>
  180. /// <param name="value">Value to insert</param>
  181. private void Insert(K start, K end, V value)
  182. {
  183. IntervalTreeNode<K, V> newNode = BSTInsert(start, end, value);
  184. RestoreBalanceAfterInsertion(newNode);
  185. }
  186. /// <summary>
  187. /// Propagate an increase in max value starting at the given node, heading up the tree.
  188. /// This should only be called if the max increases - not for rebalancing or removals.
  189. /// </summary>
  190. /// <param name="node">The node to start propagating from</param>
  191. private void PropagateIncrease(IntervalTreeNode<K, V> node)
  192. {
  193. K max = node.Max;
  194. IntervalTreeNode<K, V> ptr = node;
  195. while ((ptr = ptr.Parent) != null)
  196. {
  197. if (max.CompareTo(ptr.Max) > 0)
  198. {
  199. ptr.Max = max;
  200. }
  201. else
  202. {
  203. break;
  204. }
  205. }
  206. }
  207. /// <summary>
  208. /// Propagate recalculating max value starting at the given node, heading up the tree.
  209. /// This fully recalculates the max value from all children when there is potential for it to decrease.
  210. /// </summary>
  211. /// <param name="node">The node to start propagating from</param>
  212. private void PropagateFull(IntervalTreeNode<K, V> node)
  213. {
  214. IntervalTreeNode<K, V> ptr = node;
  215. do
  216. {
  217. K max = ptr.End;
  218. if (ptr.Left != null && ptr.Left.Max.CompareTo(max) > 0)
  219. {
  220. max = ptr.Left.Max;
  221. }
  222. if (ptr.Right != null && ptr.Right.Max.CompareTo(max) > 0)
  223. {
  224. max = ptr.Right.Max;
  225. }
  226. ptr.Max = max;
  227. } while ((ptr = ptr.Parent) != null);
  228. }
  229. /// <summary>
  230. /// Insertion Mechanism for the interval tree. Similar to a BST insert, with the start of the range as the key.
  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="start"/>, and all children in the right subtree are greater than <paramref name="start"/>.
  232. /// Each node can contain multiple values, and has an end address which is the maximum of all those values.
  233. /// Post insertion, the "max" value of the node and all parents are updated.
  234. /// </summary>
  235. /// <param name="start">Start of the range to insert</param>
  236. /// <param name="end">End of the range to insert</param>
  237. /// <param name="value">Value to insert</param>
  238. /// <returns>The inserted Node</returns>
  239. private IntervalTreeNode<K, V> BSTInsert(K start, K end, V value)
  240. {
  241. IntervalTreeNode<K, V> parent = null;
  242. IntervalTreeNode<K, V> node = Root;
  243. while (node != null)
  244. {
  245. parent = node;
  246. int cmp = start.CompareTo(node.Start);
  247. if (cmp < 0)
  248. {
  249. node = node.Left;
  250. }
  251. else if (cmp > 0)
  252. {
  253. node = node.Right;
  254. }
  255. else
  256. {
  257. node.Values.Add(new RangeNode<K, V>(start, end, value));
  258. if (end.CompareTo(node.End) > 0)
  259. {
  260. node.End = end;
  261. if (end.CompareTo(node.Max) > 0)
  262. {
  263. node.Max = end;
  264. PropagateIncrease(node);
  265. }
  266. }
  267. Count++;
  268. return node;
  269. }
  270. }
  271. IntervalTreeNode<K, V> newNode = new IntervalTreeNode<K, V>(start, end, value, parent);
  272. if (newNode.Parent == null)
  273. {
  274. Root = newNode;
  275. }
  276. else if (start.CompareTo(parent.Start) < 0)
  277. {
  278. parent.Left = newNode;
  279. }
  280. else
  281. {
  282. parent.Right = newNode;
  283. }
  284. PropagateIncrease(newNode);
  285. Count++;
  286. return newNode;
  287. }
  288. /// <summary>
  289. /// Removes instances of <paramref name="value"> from the dictionary after searching for it with <paramref name="key">.
  290. /// </summary>
  291. /// <param name="key">Key to search for</param>
  292. /// <param name="value">Value to delete</param>
  293. /// <returns>Number of deleted values</returns>
  294. private int Delete(K key, V value)
  295. {
  296. IntervalTreeNode<K, V> nodeToDelete = GetNode(key);
  297. if (nodeToDelete == null)
  298. {
  299. return 0;
  300. }
  301. int removed = nodeToDelete.Values.RemoveAll(node => node.Value.Equals(value));
  302. if (nodeToDelete.Values.Count > 0)
  303. {
  304. if (removed > 0)
  305. {
  306. nodeToDelete.End = nodeToDelete.Values.Max(node => node.End);
  307. // Recalculate max from children and new end.
  308. PropagateFull(nodeToDelete);
  309. }
  310. return removed;
  311. }
  312. IntervalTreeNode<K, V> replacementNode;
  313. if (LeftOf(nodeToDelete) == null || RightOf(nodeToDelete) == null)
  314. {
  315. replacementNode = nodeToDelete;
  316. }
  317. else
  318. {
  319. replacementNode = PredecessorOf(nodeToDelete);
  320. }
  321. IntervalTreeNode<K, V> tmp = LeftOf(replacementNode) ?? RightOf(replacementNode);
  322. if (tmp != null)
  323. {
  324. tmp.Parent = ParentOf(replacementNode);
  325. }
  326. if (ParentOf(replacementNode) == null)
  327. {
  328. Root = tmp;
  329. }
  330. else if (replacementNode == LeftOf(ParentOf(replacementNode)))
  331. {
  332. ParentOf(replacementNode).Left = tmp;
  333. }
  334. else
  335. {
  336. ParentOf(replacementNode).Right = tmp;
  337. }
  338. if (replacementNode != nodeToDelete)
  339. {
  340. nodeToDelete.Start = replacementNode.Start;
  341. nodeToDelete.Values = replacementNode.Values;
  342. nodeToDelete.End = replacementNode.End;
  343. nodeToDelete.Max = replacementNode.Max;
  344. }
  345. PropagateFull(replacementNode);
  346. if (tmp != null && ColorOf(replacementNode) == Black)
  347. {
  348. RestoreBalanceAfterRemoval(tmp);
  349. }
  350. return removed;
  351. }
  352. #endregion
  353. protected override void RotateLeft(IntervalTreeNode<K, V> node)
  354. {
  355. if (node != null)
  356. {
  357. base.RotateLeft(node);
  358. PropagateFull(node);
  359. }
  360. }
  361. protected override void RotateRight(IntervalTreeNode<K, V> node)
  362. {
  363. if (node != null)
  364. {
  365. base.RotateRight(node);
  366. PropagateFull(node);
  367. }
  368. }
  369. public bool ContainsKey(K key)
  370. {
  371. ArgumentNullException.ThrowIfNull(key);
  372. return GetNode(key) != null;
  373. }
  374. }
  375. /// <summary>
  376. /// Represents a value and its start and end keys.
  377. /// </summary>
  378. /// <typeparam name="K"></typeparam>
  379. /// <typeparam name="V"></typeparam>
  380. public readonly struct RangeNode<K, V>
  381. {
  382. public readonly K Start;
  383. public readonly K End;
  384. public readonly V Value;
  385. public RangeNode(K start, K end, V value)
  386. {
  387. Start = start;
  388. End = end;
  389. Value = value;
  390. }
  391. }
  392. /// <summary>
  393. /// Represents a node in the IntervalTree which contains start and end keys of type K, and a value of generic type V.
  394. /// </summary>
  395. /// <typeparam name="K">Key type of the node</typeparam>
  396. /// <typeparam name="V">Value type of the node</typeparam>
  397. public class IntervalTreeNode<K, V> : IntrusiveRedBlackTreeNode<IntervalTreeNode<K, V>>
  398. {
  399. /// <summary>
  400. /// The start of the range.
  401. /// </summary>
  402. internal K Start;
  403. /// <summary>
  404. /// The end of the range - maximum of all in the Values list.
  405. /// </summary>
  406. internal K End;
  407. /// <summary>
  408. /// The maximum end value of this node and all its children.
  409. /// </summary>
  410. internal K Max;
  411. /// <summary>
  412. /// Values contained on the node that shares a common Start value.
  413. /// </summary>
  414. internal List<RangeNode<K, V>> Values;
  415. internal IntervalTreeNode(K start, K end, V value, IntervalTreeNode<K, V> parent)
  416. {
  417. Start = start;
  418. End = end;
  419. Max = end;
  420. Values = new List<RangeNode<K, V>> { new RangeNode<K, V>(start, end, value) };
  421. Parent = parent;
  422. }
  423. }
  424. }