aboutsummaryrefslogtreecommitdiff
path: root/src/Ryujinx.Common/Collections
diff options
context:
space:
mode:
authorTSR Berry <20988865+TSRBerry@users.noreply.github.com>2023-04-08 01:22:00 +0200
committerMary <thog@protonmail.com>2023-04-27 23:51:14 +0200
commitcee712105850ac3385cd0091a923438167433f9f (patch)
tree4a5274b21d8b7f938c0d0ce18736d3f2993b11b1 /src/Ryujinx.Common/Collections
parentcd124bda587ef09668a971fa1cac1c3f0cfc9f21 (diff)
Move solution and projects to src
Diffstat (limited to 'src/Ryujinx.Common/Collections')
-rw-r--r--src/Ryujinx.Common/Collections/IntervalTree.cs499
-rw-r--r--src/Ryujinx.Common/Collections/IntrusiveRedBlackTree.cs285
-rw-r--r--src/Ryujinx.Common/Collections/IntrusiveRedBlackTreeImpl.cs354
-rw-r--r--src/Ryujinx.Common/Collections/IntrusiveRedBlackTreeNode.cs16
-rw-r--r--src/Ryujinx.Common/Collections/TreeDictionary.cs617
5 files changed, 1771 insertions, 0 deletions
diff --git a/src/Ryujinx.Common/Collections/IntervalTree.cs b/src/Ryujinx.Common/Collections/IntervalTree.cs
new file mode 100644
index 00000000..b5188cc7
--- /dev/null
+++ b/src/Ryujinx.Common/Collections/IntervalTree.cs
@@ -0,0 +1,499 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+
+namespace Ryujinx.Common.Collections
+{
+ /// <summary>
+ /// An Augmented Interval Tree based off of the "TreeDictionary"'s Red-Black Tree. Allows fast overlap checking of ranges.
+ /// </summary>
+ /// <typeparam name="K">Key</typeparam>
+ /// <typeparam name="V">Value</typeparam>
+ public class IntervalTree<K, V> : IntrusiveRedBlackTreeImpl<IntervalTreeNode<K, V>> where K : IComparable<K>
+ {
+ private const int ArrayGrowthSize = 32;
+
+ #region Public Methods
+
+ /// <summary>
+ /// Gets the values of the interval whose key is <paramref name="key"/>.
+ /// </summary>
+ /// <param name="key">Key of the node value to get</param>
+ /// <param name="overlaps">Overlaps array to place results in</param>
+ /// <returns>Number of values found</returns>
+ /// <exception cref="ArgumentNullException"><paramref name="key"/> is null</exception>
+ public int Get(K key, ref V[] overlaps)
+ {
+ ArgumentNullException.ThrowIfNull(key);
+
+ IntervalTreeNode<K, V> node = GetNode(key);
+
+ if (node == null)
+ {
+ return 0;
+ }
+
+ if (node.Values.Count > overlaps.Length)
+ {
+ Array.Resize(ref overlaps, node.Values.Count);
+ }
+
+ int overlapsCount = 0;
+ foreach (RangeNode<K, V> value in node.Values)
+ {
+ overlaps[overlapsCount++] = value.Value;
+ }
+
+ return overlapsCount;
+ }
+
+ /// <summary>
+ /// Returns the values of the intervals whose start and end keys overlap the given range.
+ /// </summary>
+ /// <param name="start">Start of the range</param>
+ /// <param name="end">End of the range</param>
+ /// <param name="overlaps">Overlaps array to place results in</param>
+ /// <param name="overlapCount">Index to start writing results into the array. Defaults to 0</param>
+ /// <returns>Number of values found</returns>
+ /// <exception cref="ArgumentNullException"><paramref name="start"/> or <paramref name="end"/> is null</exception>
+ public int Get(K start, K end, ref V[] overlaps, int overlapCount = 0)
+ {
+ ArgumentNullException.ThrowIfNull(start);
+ ArgumentNullException.ThrowIfNull(end);
+
+ GetValues(Root, start, end, ref overlaps, ref overlapCount);
+
+ return overlapCount;
+ }
+
+ /// <summary>
+ /// Adds a new interval into the tree whose start is <paramref name="start"/>, end is <paramref name="end"/> and value is <paramref name="value"/>.
+ /// </summary>
+ /// <param name="start">Start of the range to add</param>
+ /// <param name="end">End of the range to insert</param>
+ /// <param name="value">Value to add</param>
+ /// <exception cref="ArgumentNullException"><paramref name="start"/>, <paramref name="end"/> or <paramref name="value"/> are null</exception>
+ public void Add(K start, K end, V value)
+ {
+ ArgumentNullException.ThrowIfNull(start);
+ ArgumentNullException.ThrowIfNull(end);
+ ArgumentNullException.ThrowIfNull(value);
+
+ Insert(start, end, value);
+ }
+
+ /// <summary>
+ /// Removes the given <paramref name="value"/> from the tree, searching for it with <paramref name="key"/>.
+ /// </summary>
+ /// <param name="key">Key of the node to remove</param>
+ /// <param name="value">Value to remove</param>
+ /// <exception cref="ArgumentNullException"><paramref name="key"/> is null</exception>
+ /// <returns>Number of deleted values</returns>
+ public int Remove(K key, V value)
+ {
+ ArgumentNullException.ThrowIfNull(key);
+
+ int removed = Delete(key, value);
+
+ Count -= removed;
+
+ return removed;
+ }
+
+ /// <summary>
+ /// Adds all the nodes in the dictionary into <paramref name="list"/>.
+ /// </summary>
+ /// <returns>A list of all RangeNodes sorted by Key Order</returns>
+ public List<RangeNode<K, V>> AsList()
+ {
+ List<RangeNode<K, V>> list = new List<RangeNode<K, V>>();
+
+ AddToList(Root, list);
+
+ return list;
+ }
+
+ #endregion
+
+ #region Private Methods (BST)
+
+ /// <summary>
+ /// Adds all RangeNodes that are children of or contained within <paramref name="node"/> into <paramref name="list"/>, in Key Order.
+ /// </summary>
+ /// <param name="node">The node to search for RangeNodes within</param>
+ /// <param name="list">The list to add RangeNodes to</param>
+ private void AddToList(IntervalTreeNode<K, V> node, List<RangeNode<K, V>> list)
+ {
+ if (node == null)
+ {
+ return;
+ }
+
+ AddToList(node.Left, list);
+
+ list.AddRange(node.Values);
+
+ AddToList(node.Right, list);
+ }
+
+ /// <summary>
+ /// Retrieve the node reference whose key is <paramref name="key"/>, or null if no such node exists.
+ /// </summary>
+ /// <param name="key">Key of the node to get</param>
+ /// <returns>Node reference in the tree</returns>
+ /// <exception cref="ArgumentNullException"><paramref name="key"/> is null</exception>
+ private IntervalTreeNode<K, V> GetNode(K key)
+ {
+ ArgumentNullException.ThrowIfNull(key);
+
+ IntervalTreeNode<K, V> node = Root;
+ while (node != null)
+ {
+ int cmp = key.CompareTo(node.Start);
+ if (cmp < 0)
+ {
+ node = node.Left;
+ }
+ else if (cmp > 0)
+ {
+ node = node.Right;
+ }
+ else
+ {
+ return node;
+ }
+ }
+ return null;
+ }
+
+ /// <summary>
+ /// Retrieve all values that overlap the given start and end keys.
+ /// </summary>
+ /// <param name="start">Start of the range</param>
+ /// <param name="end">End of the range</param>
+ /// <param name="overlaps">Overlaps array to place results in</param>
+ /// <param name="overlapCount">Overlaps count to update</param>
+ private void GetValues(IntervalTreeNode<K, V> node, K start, K end, ref V[] overlaps, ref int overlapCount)
+ {
+ if (node == null || start.CompareTo(node.Max) >= 0)
+ {
+ return;
+ }
+
+ GetValues(node.Left, start, end, ref overlaps, ref overlapCount);
+
+ bool endsOnRight = end.CompareTo(node.Start) > 0;
+ if (endsOnRight)
+ {
+ if (start.CompareTo(node.End) < 0)
+ {
+ // Contains this node. Add overlaps to list.
+ foreach (RangeNode<K,V> overlap in node.Values)
+ {
+ if (start.CompareTo(overlap.End) < 0)
+ {
+ if (overlaps.Length >= overlapCount)
+ {
+ Array.Resize(ref overlaps, overlapCount + ArrayGrowthSize);
+ }
+
+ overlaps[overlapCount++] = overlap.Value;
+ }
+ }
+ }
+
+ GetValues(node.Right, start, end, ref overlaps, ref overlapCount);
+ }
+ }
+
+ /// <summary>
+ /// Inserts a new node into the tree with a given <paramref name="start"/>, <paramref name="end"/> and <paramref name="value"/>.
+ /// </summary>
+ /// <param name="start">Start of the range to insert</param>
+ /// <param name="end">End of the range to insert</param>
+ /// <param name="value">Value to insert</param>
+ private void Insert(K start, K end, V value)
+ {
+ IntervalTreeNode<K, V> newNode = BSTInsert(start, end, value);
+ RestoreBalanceAfterInsertion(newNode);
+ }
+
+ /// <summary>
+ /// Propagate an increase in max value starting at the given node, heading up the tree.
+ /// This should only be called if the max increases - not for rebalancing or removals.
+ /// </summary>
+ /// <param name="node">The node to start propagating from</param>
+ private void PropagateIncrease(IntervalTreeNode<K, V> node)
+ {
+ K max = node.Max;
+ IntervalTreeNode<K, V> ptr = node;
+
+ while ((ptr = ptr.Parent) != null)
+ {
+ if (max.CompareTo(ptr.Max) > 0)
+ {
+ ptr.Max = max;
+ }
+ else
+ {
+ break;
+ }
+ }
+ }
+
+ /// <summary>
+ /// Propagate recalculating max value starting at the given node, heading up the tree.
+ /// This fully recalculates the max value from all children when there is potential for it to decrease.
+ /// </summary>
+ /// <param name="node">The node to start propagating from</param>
+ private void PropagateFull(IntervalTreeNode<K, V> node)
+ {
+ IntervalTreeNode<K, V> ptr = node;
+
+ do
+ {
+ K max = ptr.End;
+
+ if (ptr.Left != null && ptr.Left.Max.CompareTo(max) > 0)
+ {
+ max = ptr.Left.Max;
+ }
+
+ if (ptr.Right != null && ptr.Right.Max.CompareTo(max) > 0)
+ {
+ max = ptr.Right.Max;
+ }
+
+ ptr.Max = max;
+ } while ((ptr = ptr.Parent) != null);
+ }
+
+ /// <summary>
+ /// Insertion Mechanism for the interval tree. Similar to a BST insert, with the start of the range as the key.
+ /// 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"/>.
+ /// Each node can contain multiple values, and has an end address which is the maximum of all those values.
+ /// Post insertion, the "max" value of the node and all parents are updated.
+ /// </summary>
+ /// <param name="start">Start of the range to insert</param>
+ /// <param name="end">End of the range to insert</param>
+ /// <param name="value">Value to insert</param>
+ /// <returns>The inserted Node</returns>
+ private IntervalTreeNode<K, V> BSTInsert(K start, K end, V value)
+ {
+ IntervalTreeNode<K, V> parent = null;
+ IntervalTreeNode<K, V> node = Root;
+
+ while (node != null)
+ {
+ parent = node;
+ int cmp = start.CompareTo(node.Start);
+ if (cmp < 0)
+ {
+ node = node.Left;
+ }
+ else if (cmp > 0)
+ {
+ node = node.Right;
+ }
+ else
+ {
+ node.Values.Add(new RangeNode<K, V>(start, end, value));
+
+ if (end.CompareTo(node.End) > 0)
+ {
+ node.End = end;
+ if (end.CompareTo(node.Max) > 0)
+ {
+ node.Max = end;
+ PropagateIncrease(node);
+ }
+ }
+
+ Count++;
+ return node;
+ }
+ }
+ IntervalTreeNode<K, V> newNode = new IntervalTreeNode<K, V>(start, end, value, parent);
+ if (newNode.Parent == null)
+ {
+ Root = newNode;
+ }
+ else if (start.CompareTo(parent.Start) < 0)
+ {
+ parent.Left = newNode;
+ }
+ else
+ {
+ parent.Right = newNode;
+ }
+
+ PropagateIncrease(newNode);
+ Count++;
+ return newNode;
+ }
+
+ /// <summary>
+ /// Removes instances of <paramref name="value"> from the dictionary after searching for it with <paramref name="key">.
+ /// </summary>
+ /// <param name="key">Key to search for</param>
+ /// <param name="value">Value to delete</param>
+ /// <returns>Number of deleted values</returns>
+ private int Delete(K key, V value)
+ {
+ IntervalTreeNode<K, V> nodeToDelete = GetNode(key);
+
+ if (nodeToDelete == null)
+ {
+ return 0;
+ }
+
+ int removed = nodeToDelete.Values.RemoveAll(node => node.Value.Equals(value));
+
+ if (nodeToDelete.Values.Count > 0)
+ {
+ if (removed > 0)
+ {
+ nodeToDelete.End = nodeToDelete.Values.Max(node => node.End);
+
+ // Recalculate max from children and new end.
+ PropagateFull(nodeToDelete);
+ }
+
+ return removed;
+ }
+
+ IntervalTreeNode<K, V> replacementNode;
+
+ if (LeftOf(nodeToDelete) == null || RightOf(nodeToDelete) == null)
+ {
+ replacementNode = nodeToDelete;
+ }
+ else
+ {
+ replacementNode = PredecessorOf(nodeToDelete);
+ }
+
+ IntervalTreeNode<K, V> tmp = LeftOf(replacementNode) ?? RightOf(replacementNode);
+
+ if (tmp != null)
+ {
+ tmp.Parent = ParentOf(replacementNode);
+ }
+
+ if (ParentOf(replacementNode) == null)
+ {
+ Root = tmp;
+ }
+ else if (replacementNode == LeftOf(ParentOf(replacementNode)))
+ {
+ ParentOf(replacementNode).Left = tmp;
+ }
+ else
+ {
+ ParentOf(replacementNode).Right = tmp;
+ }
+
+ if (replacementNode != nodeToDelete)
+ {
+ nodeToDelete.Start = replacementNode.Start;
+ nodeToDelete.Values = replacementNode.Values;
+ nodeToDelete.End = replacementNode.End;
+ nodeToDelete.Max = replacementNode.Max;
+ }
+
+ PropagateFull(replacementNode);
+
+ if (tmp != null && ColorOf(replacementNode) == Black)
+ {
+ RestoreBalanceAfterRemoval(tmp);
+ }
+
+ return removed;
+ }
+
+ #endregion
+
+ protected override void RotateLeft(IntervalTreeNode<K, V> node)
+ {
+ if (node != null)
+ {
+ base.RotateLeft(node);
+
+ PropagateFull(node);
+ }
+ }
+
+ protected override void RotateRight(IntervalTreeNode<K, V> node)
+ {
+ if (node != null)
+ {
+ base.RotateRight(node);
+
+ PropagateFull(node);
+ }
+ }
+
+ public bool ContainsKey(K key)
+ {
+ ArgumentNullException.ThrowIfNull(key);
+
+ return GetNode(key) != null;
+ }
+ }
+
+ /// <summary>
+ /// Represents a value and its start and end keys.
+ /// </summary>
+ /// <typeparam name="K"></typeparam>
+ /// <typeparam name="V"></typeparam>
+ public readonly struct RangeNode<K, V>
+ {
+ public readonly K Start;
+ public readonly K End;
+ public readonly V Value;
+
+ public RangeNode(K start, K end, V value)
+ {
+ Start = start;
+ End = end;
+ Value = value;
+ }
+ }
+
+ /// <summary>
+ /// Represents a node in the IntervalTree which contains start and end keys of type K, and a value of generic type V.
+ /// </summary>
+ /// <typeparam name="K">Key type of the node</typeparam>
+ /// <typeparam name="V">Value type of the node</typeparam>
+ public class IntervalTreeNode<K, V> : IntrusiveRedBlackTreeNode<IntervalTreeNode<K, V>>
+ {
+ /// <summary>
+ /// The start of the range.
+ /// </summary>
+ internal K Start;
+
+ /// <summary>
+ /// The end of the range - maximum of all in the Values list.
+ /// </summary>
+ internal K End;
+
+ /// <summary>
+ /// The maximum end value of this node and all its children.
+ /// </summary>
+ internal K Max;
+
+ /// <summary>
+ /// Values contained on the node that shares a common Start value.
+ /// </summary>
+ internal List<RangeNode<K, V>> Values;
+
+ internal IntervalTreeNode(K start, K end, V value, IntervalTreeNode<K, V> parent)
+ {
+ Start = start;
+ End = end;
+ Max = end;
+ Values = new List<RangeNode<K, V>> { new RangeNode<K, V>(start, end, value) };
+ Parent = parent;
+ }
+ }
+}
diff --git a/src/Ryujinx.Common/Collections/IntrusiveRedBlackTree.cs b/src/Ryujinx.Common/Collections/IntrusiveRedBlackTree.cs
new file mode 100644
index 00000000..0063d91e
--- /dev/null
+++ b/src/Ryujinx.Common/Collections/IntrusiveRedBlackTree.cs
@@ -0,0 +1,285 @@
+using System;
+
+namespace Ryujinx.Common.Collections
+{
+ /// <summary>
+ /// Tree that provides the ability for O(logN) lookups for keys that exist in the tree, and O(logN) lookups for keys immediately greater than or less than a specified key.
+ /// </summary>
+ /// <typeparam name="T">Derived node type</typeparam>
+ public class IntrusiveRedBlackTree<T> : IntrusiveRedBlackTreeImpl<T> where T : IntrusiveRedBlackTreeNode<T>, IComparable<T>
+ {
+ #region Public Methods
+
+ /// <summary>
+ /// Adds a new node into the tree.
+ /// </summary>
+ /// <param name="node">Node to be added</param>
+ /// <exception cref="ArgumentNullException"><paramref name="node"/> is null</exception>
+ public void Add(T node)
+ {
+ ArgumentNullException.ThrowIfNull(node);
+
+ Insert(node);
+ }
+
+ /// <summary>
+ /// Removes a node from the tree.
+ /// </summary>
+ /// <param name="node">Note to be removed</param>
+ /// <exception cref="ArgumentNullException"><paramref name="node"/> is null</exception>
+ public void Remove(T node)
+ {
+ ArgumentNullException.ThrowIfNull(node);
+
+ if (Delete(node) != null)
+ {
+ Count--;
+ }
+ }
+
+ /// <summary>
+ /// Retrieve the node that is considered equal to the specified node by the comparator.
+ /// </summary>
+ /// <param name="searchNode">Node to compare with</param>
+ /// <returns>Node that is equal to <paramref name="searchNode"/></returns>
+ /// <exception cref="ArgumentNullException"><paramref name="searchNode"/> is null</exception>
+ public T GetNode(T searchNode)
+ {
+ ArgumentNullException.ThrowIfNull(searchNode);
+
+ T node = Root;
+ while (node != null)
+ {
+ int cmp = searchNode.CompareTo(node);
+ if (cmp < 0)
+ {
+ node = node.Left;
+ }
+ else if (cmp > 0)
+ {
+ node = node.Right;
+ }
+ else
+ {
+ return node;
+ }
+ }
+ return null;
+ }
+
+ #endregion
+
+ #region Private Methods (BST)
+
+ /// <summary>
+ /// Inserts a new node into the tree.
+ /// </summary>
+ /// <param name="node">Node to be inserted</param>
+ private void Insert(T node)
+ {
+ T newNode = BSTInsert(node);
+ RestoreBalanceAfterInsertion(newNode);
+ }
+
+ /// <summary>
+ /// Insertion Mechanism for a Binary Search Tree (BST).
+ /// <br></br>
+ /// Iterates the tree starting from the root and inserts a new node
+ /// where all children in the left subtree are less than <paramref name="newNode"/>,
+ /// and all children in the right subtree are greater than <paramref name="newNode"/>.
+ /// </summary>
+ /// <param name="newNode">Node to be inserted</param>
+ /// <returns>The inserted Node</returns>
+ private T BSTInsert(T newNode)
+ {
+ T parent = null;
+ T node = Root;
+
+ while (node != null)
+ {
+ parent = node;
+ int cmp = newNode.CompareTo(node);
+ if (cmp < 0)
+ {
+ node = node.Left;
+ }
+ else if (cmp > 0)
+ {
+ node = node.Right;
+ }
+ else
+ {
+ return node;
+ }
+ }
+ newNode.Parent = parent;
+ if (parent == null)
+ {
+ Root = newNode;
+ }
+ else if (newNode.CompareTo(parent) < 0)
+ {
+ parent.Left = newNode;
+ }
+ else
+ {
+ parent.Right = newNode;
+ }
+ Count++;
+ return newNode;
+ }
+
+ /// <summary>
+ /// Removes <paramref name="nodeToDelete"/> from the tree, if it exists.
+ /// </summary>
+ /// <param name="nodeToDelete">Node to be removed</param>
+ /// <returns>The deleted Node</returns>
+ private T Delete(T nodeToDelete)
+ {
+ if (nodeToDelete == null)
+ {
+ return null;
+ }
+
+ T old = nodeToDelete;
+ T child;
+ T parent;
+ bool color;
+
+ if (LeftOf(nodeToDelete) == null)
+ {
+ child = RightOf(nodeToDelete);
+ }
+ else if (RightOf(nodeToDelete) == null)
+ {
+ child = LeftOf(nodeToDelete);
+ }
+ else
+ {
+ T element = Minimum(RightOf(nodeToDelete));
+
+ child = RightOf(element);
+ parent = ParentOf(element);
+ color = ColorOf(element);
+
+ if (child != null)
+ {
+ child.Parent = parent;
+ }
+
+ if (parent == null)
+ {
+ Root = child;
+ }
+ else if (element == LeftOf(parent))
+ {
+ parent.Left = child;
+ }
+ else
+ {
+ parent.Right = child;
+ }
+
+ if (ParentOf(element) == old)
+ {
+ parent = element;
+ }
+
+ element.Color = old.Color;
+ element.Left = old.Left;
+ element.Right = old.Right;
+ element.Parent = old.Parent;
+
+ if (ParentOf(old) == null)
+ {
+ Root = element;
+ }
+ else if (old == LeftOf(ParentOf(old)))
+ {
+ ParentOf(old).Left = element;
+ }
+ else
+ {
+ ParentOf(old).Right = element;
+ }
+
+ LeftOf(old).Parent = element;
+
+ if (RightOf(old) != null)
+ {
+ RightOf(old).Parent = element;
+ }
+
+ if (child != null && color == Black)
+ {
+ RestoreBalanceAfterRemoval(child);
+ }
+
+ return old;
+ }
+
+ parent = ParentOf(nodeToDelete);
+ color = ColorOf(nodeToDelete);
+
+ if (child != null)
+ {
+ child.Parent = parent;
+ }
+
+ if (parent == null)
+ {
+ Root = child;
+ }
+ else if (nodeToDelete == LeftOf(parent))
+ {
+ parent.Left = child;
+ }
+ else
+ {
+ parent.Right = child;
+ }
+
+ if (child != null && color == Black)
+ {
+ RestoreBalanceAfterRemoval(child);
+ }
+
+ return old;
+ }
+
+ #endregion
+ }
+
+ public static class IntrusiveRedBlackTreeExtensions
+ {
+ /// <summary>
+ /// Retrieve the node that is considered equal to the key by the comparator.
+ /// </summary>
+ /// <param name="tree">Tree to search at</param>
+ /// <param name="key">Key of the node to be found</param>
+ /// <returns>Node that is equal to <paramref name="key"/></returns>
+ public static N GetNodeByKey<N, K>(this IntrusiveRedBlackTree<N> tree, K key)
+ where N : IntrusiveRedBlackTreeNode<N>, IComparable<N>, IComparable<K>
+ where K : struct
+ {
+ N node = tree.RootNode;
+ while (node != null)
+ {
+ int cmp = node.CompareTo(key);
+ if (cmp < 0)
+ {
+ node = node.Right;
+ }
+ else if (cmp > 0)
+ {
+ node = node.Left;
+ }
+ else
+ {
+ return node;
+ }
+ }
+ return null;
+ }
+ }
+}
diff --git a/src/Ryujinx.Common/Collections/IntrusiveRedBlackTreeImpl.cs b/src/Ryujinx.Common/Collections/IntrusiveRedBlackTreeImpl.cs
new file mode 100644
index 00000000..bcb2e2a2
--- /dev/null
+++ b/src/Ryujinx.Common/Collections/IntrusiveRedBlackTreeImpl.cs
@@ -0,0 +1,354 @@
+using System;
+
+namespace Ryujinx.Common.Collections
+{
+ /// <summary>
+ /// Tree that provides the ability for O(logN) lookups for keys that exist in the tree, and O(logN) lookups for keys immediately greater than or less than a specified key.
+ /// </summary>
+ /// <typeparam name="T">Derived node type</typeparam>
+ public class IntrusiveRedBlackTreeImpl<T> where T : IntrusiveRedBlackTreeNode<T>
+ {
+ protected const bool Black = true;
+ protected const bool Red = false;
+ protected T Root = null;
+
+ internal T RootNode => Root;
+
+ /// <summary>
+ /// Number of nodes on the tree.
+ /// </summary>
+ public int Count { get; protected set; }
+
+ /// <summary>
+ /// Removes all nodes on the tree.
+ /// </summary>
+ public void Clear()
+ {
+ Root = null;
+ Count = 0;
+ }
+
+ /// <summary>
+ /// Finds the node whose key is immediately greater than <paramref name="node"/>.
+ /// </summary>
+ /// <param name="node">Node to find the successor of</param>
+ /// <returns>Successor of <paramref name="node"/></returns>
+ internal static T SuccessorOf(T node)
+ {
+ if (node.Right != null)
+ {
+ return Minimum(node.Right);
+ }
+ T parent = node.Parent;
+ while (parent != null && node == parent.Right)
+ {
+ node = parent;
+ parent = parent.Parent;
+ }
+ return parent;
+ }
+
+ /// <summary>
+ /// Finds the node whose key is immediately less than <paramref name="node"/>.
+ /// </summary>
+ /// <param name="node">Node to find the predecessor of</param>
+ /// <returns>Predecessor of <paramref name="node"/></returns>
+ internal static T PredecessorOf(T node)
+ {
+ if (node.Left != null)
+ {
+ return Maximum(node.Left);
+ }
+ T parent = node.Parent;
+ while (parent != null && node == parent.Left)
+ {
+ node = parent;
+ parent = parent.Parent;
+ }
+ return parent;
+ }
+
+ /// <summary>
+ /// Returns the node with the largest key where <paramref name="node"/> is considered the root node.
+ /// </summary>
+ /// <param name="node">Root node</param>
+ /// <returns>Node with the maximum key in the tree of <paramref name="node"/></returns>
+ protected static T Maximum(T node)
+ {
+ T tmp = node;
+ while (tmp.Right != null)
+ {
+ tmp = tmp.Right;
+ }
+
+ return tmp;
+ }
+
+ /// <summary>
+ /// Returns the node with the smallest key where <paramref name="node"/> is considered the root node.
+ /// </summary>
+ /// <param name="node">Root node</param>
+ /// <returns>Node with the minimum key in the tree of <paramref name="node"/></returns>
+ /// <exception cref="ArgumentNullException"><paramref name="node"/> is null</exception>
+ protected static T Minimum(T node)
+ {
+ ArgumentNullException.ThrowIfNull(node);
+
+ T tmp = node;
+ while (tmp.Left != null)
+ {
+ tmp = tmp.Left;
+ }
+
+ return tmp;
+ }
+
+ protected void RestoreBalanceAfterRemoval(T balanceNode)
+ {
+ T ptr = balanceNode;
+
+ while (ptr != Root && ColorOf(ptr) == Black)
+ {
+ if (ptr == LeftOf(ParentOf(ptr)))
+ {
+ T sibling = RightOf(ParentOf(ptr));
+
+ if (ColorOf(sibling) == Red)
+ {
+ SetColor(sibling, Black);
+ SetColor(ParentOf(ptr), Red);
+ RotateLeft(ParentOf(ptr));
+ sibling = RightOf(ParentOf(ptr));
+ }
+ if (ColorOf(LeftOf(sibling)) == Black && ColorOf(RightOf(sibling)) == Black)
+ {
+ SetColor(sibling, Red);
+ ptr = ParentOf(ptr);
+ }
+ else
+ {
+ if (ColorOf(RightOf(sibling)) == Black)
+ {
+ SetColor(LeftOf(sibling), Black);
+ SetColor(sibling, Red);
+ RotateRight(sibling);
+ sibling = RightOf(ParentOf(ptr));
+ }
+ SetColor(sibling, ColorOf(ParentOf(ptr)));
+ SetColor(ParentOf(ptr), Black);
+ SetColor(RightOf(sibling), Black);
+ RotateLeft(ParentOf(ptr));
+ ptr = Root;
+ }
+ }
+ else
+ {
+ T sibling = LeftOf(ParentOf(ptr));
+
+ if (ColorOf(sibling) == Red)
+ {
+ SetColor(sibling, Black);
+ SetColor(ParentOf(ptr), Red);
+ RotateRight(ParentOf(ptr));
+ sibling = LeftOf(ParentOf(ptr));
+ }
+ if (ColorOf(RightOf(sibling)) == Black && ColorOf(LeftOf(sibling)) == Black)
+ {
+ SetColor(sibling, Red);
+ ptr = ParentOf(ptr);
+ }
+ else
+ {
+ if (ColorOf(LeftOf(sibling)) == Black)
+ {
+ SetColor(RightOf(sibling), Black);
+ SetColor(sibling, Red);
+ RotateLeft(sibling);
+ sibling = LeftOf(ParentOf(ptr));
+ }
+ SetColor(sibling, ColorOf(ParentOf(ptr)));
+ SetColor(ParentOf(ptr), Black);
+ SetColor(LeftOf(sibling), Black);
+ RotateRight(ParentOf(ptr));
+ ptr = Root;
+ }
+ }
+ }
+ SetColor(ptr, Black);
+ }
+
+ protected void RestoreBalanceAfterInsertion(T balanceNode)
+ {
+ SetColor(balanceNode, Red);
+ while (balanceNode != null && balanceNode != Root && ColorOf(ParentOf(balanceNode)) == Red)
+ {
+ if (ParentOf(balanceNode) == LeftOf(ParentOf(ParentOf(balanceNode))))
+ {
+ T sibling = RightOf(ParentOf(ParentOf(balanceNode)));
+
+ if (ColorOf(sibling) == Red)
+ {
+ SetColor(ParentOf(balanceNode), Black);
+ SetColor(sibling, Black);
+ SetColor(ParentOf(ParentOf(balanceNode)), Red);
+ balanceNode = ParentOf(ParentOf(balanceNode));
+ }
+ else
+ {
+ if (balanceNode == RightOf(ParentOf(balanceNode)))
+ {
+ balanceNode = ParentOf(balanceNode);
+ RotateLeft(balanceNode);
+ }
+ SetColor(ParentOf(balanceNode), Black);
+ SetColor(ParentOf(ParentOf(balanceNode)), Red);
+ RotateRight(ParentOf(ParentOf(balanceNode)));
+ }
+ }
+ else
+ {
+ T sibling = LeftOf(ParentOf(ParentOf(balanceNode)));
+
+ if (ColorOf(sibling) == Red)
+ {
+ SetColor(ParentOf(balanceNode), Black);
+ SetColor(sibling, Black);
+ SetColor(ParentOf(ParentOf(balanceNode)), Red);
+ balanceNode = ParentOf(ParentOf(balanceNode));
+ }
+ else
+ {
+ if (balanceNode == LeftOf(ParentOf(balanceNode)))
+ {
+ balanceNode = ParentOf(balanceNode);
+ RotateRight(balanceNode);
+ }
+ SetColor(ParentOf(balanceNode), Black);
+ SetColor(ParentOf(ParentOf(balanceNode)), Red);
+ RotateLeft(ParentOf(ParentOf(balanceNode)));
+ }
+ }
+ }
+ SetColor(Root, Black);
+ }
+
+ protected virtual void RotateLeft(T node)
+ {
+ if (node != null)
+ {
+ T right = RightOf(node);
+ node.Right = LeftOf(right);
+ if (node.Right != null)
+ {
+ node.Right.Parent = node;
+ }
+ T nodeParent = ParentOf(node);
+ right.Parent = nodeParent;
+ if (nodeParent == null)
+ {
+ Root = right;
+ }
+ else if (node == LeftOf(nodeParent))
+ {
+ nodeParent.Left = right;
+ }
+ else
+ {
+ nodeParent.Right = right;
+ }
+ right.Left = node;
+ node.Parent = right;
+ }
+ }
+
+ protected virtual void RotateRight(T node)
+ {
+ if (node != null)
+ {
+ T left = LeftOf(node);
+ node.Left = RightOf(left);
+ if (node.Left != null)
+ {
+ node.Left.Parent = node;
+ }
+ T nodeParent = ParentOf(node);
+ left.Parent = nodeParent;
+ if (nodeParent == null)
+ {
+ Root = left;
+ }
+ else if (node == RightOf(nodeParent))
+ {
+ nodeParent.Right = left;
+ }
+ else
+ {
+ nodeParent.Left = left;
+ }
+ left.Right = node;
+ node.Parent = left;
+ }
+ }
+
+ #region Safety-Methods
+
+ // These methods save memory by allowing us to forego sentinel nil nodes, as well as serve as protection against NullReferenceExceptions.
+
+ /// <summary>
+ /// Returns the color of <paramref name="node"/>, or Black if it is null.
+ /// </summary>
+ /// <param name="node">Node</param>
+ /// <returns>The boolean color of <paramref name="node"/>, or black if null</returns>
+ protected static bool ColorOf(T node)
+ {
+ return node == null || node.Color;
+ }
+
+ /// <summary>
+ /// Sets the color of <paramref name="node"/> node to <paramref name="color"/>.
+ /// <br></br>
+ /// This method does nothing if <paramref name="node"/> is null.
+ /// </summary>
+ /// <param name="node">Node to set the color of</param>
+ /// <param name="color">Color (Boolean)</param>
+ protected static void SetColor(T node, bool color)
+ {
+ if (node != null)
+ {
+ node.Color = color;
+ }
+ }
+
+ /// <summary>
+ /// This method returns the left node of <paramref name="node"/>, or null if <paramref name="node"/> is null.
+ /// </summary>
+ /// <param name="node">Node to retrieve the left child from</param>
+ /// <returns>Left child of <paramref name="node"/></returns>
+ protected static T LeftOf(T node)
+ {
+ return node?.Left;
+ }
+
+ /// <summary>
+ /// This method returns the right node of <paramref name="node"/>, or null if <paramref name="node"/> is null.
+ /// </summary>
+ /// <param name="node">Node to retrieve the right child from</param>
+ /// <returns>Right child of <paramref name="node"/></returns>
+ protected static T RightOf(T node)
+ {
+ return node?.Right;
+ }
+
+ /// <summary>
+ /// Returns the parent node of <paramref name="node"/>, or null if <paramref name="node"/> is null.
+ /// </summary>
+ /// <param name="node">Node to retrieve the parent from</param>
+ /// <returns>Parent of <paramref name="node"/></returns>
+ protected static T ParentOf(T node)
+ {
+ return node?.Parent;
+ }
+
+ #endregion
+ }
+}
diff --git a/src/Ryujinx.Common/Collections/IntrusiveRedBlackTreeNode.cs b/src/Ryujinx.Common/Collections/IntrusiveRedBlackTreeNode.cs
new file mode 100644
index 00000000..7143240d
--- /dev/null
+++ b/src/Ryujinx.Common/Collections/IntrusiveRedBlackTreeNode.cs
@@ -0,0 +1,16 @@
+namespace Ryujinx.Common.Collections
+{
+ /// <summary>
+ /// Represents a node in the Red-Black Tree.
+ /// </summary>
+ public class IntrusiveRedBlackTreeNode<T> where T : IntrusiveRedBlackTreeNode<T>
+ {
+ internal bool Color = true;
+ internal T Left;
+ internal T Right;
+ internal T Parent;
+
+ public T Predecessor => IntrusiveRedBlackTreeImpl<T>.PredecessorOf((T)this);
+ public T Successor => IntrusiveRedBlackTreeImpl<T>.SuccessorOf((T)this);
+ }
+} \ No newline at end of file
diff --git a/src/Ryujinx.Common/Collections/TreeDictionary.cs b/src/Ryujinx.Common/Collections/TreeDictionary.cs
new file mode 100644
index 00000000..d118a30c
--- /dev/null
+++ b/src/Ryujinx.Common/Collections/TreeDictionary.cs
@@ -0,0 +1,617 @@
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+
+namespace Ryujinx.Common.Collections
+{
+ /// <summary>
+ /// 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.
+ /// </summary>
+ /// <typeparam name="K">Key</typeparam>
+ /// <typeparam name="V">Value</typeparam>
+ public class TreeDictionary<K, V> : IntrusiveRedBlackTreeImpl<Node<K, V>>, IDictionary<K, V> where K : IComparable<K>
+ {
+ #region Public Methods
+
+ /// <summary>
+ /// Returns the value of the node whose key is <paramref name="key"/>, or the default value if no such node exists.
+ /// </summary>
+ /// <param name="key">Key of the node value to get</param>
+ /// <returns>Value associated w/ <paramref name="key"/></returns>
+ /// <exception cref="ArgumentNullException"><paramref name="key"/> is null</exception>
+ public V Get(K key)
+ {
+ ArgumentNullException.ThrowIfNull(key);
+
+ Node<K, V> node = GetNode(key);
+
+ if (node == null)
+ {
+ return default;
+ }
+
+ return node.Value;
+ }
+
+ /// <summary>
+ /// Adds a new node into the tree whose key is <paramref name="key"/> key and value is <paramref name="value"/>.
+ /// <br></br>
+ /// <b>Note:</b> Adding the same key multiple times will cause the value for that key to be overwritten.
+ /// </summary>
+ /// <param name="key">Key of the node to add</param>
+ /// <param name="value">Value of the node to add</param>
+ /// <exception cref="ArgumentNullException"><paramref name="key"/> or <paramref name="value"/> are null</exception>
+ public void Add(K key, V value)
+ {
+ ArgumentNullException.ThrowIfNull(key);
+ ArgumentNullException.ThrowIfNull(value);
+
+ Insert(key, value);
+ }
+
+ /// <summary>
+ /// Removes the node whose key is <paramref name="key"/> from the tree.
+ /// </summary>
+ /// <param name="key">Key of the node to remove</param>
+ /// <exception cref="ArgumentNullException"><paramref name="key"/> is null</exception>
+ public void Remove(K key)
+ {
+ ArgumentNullException.ThrowIfNull(key);
+
+ if (Delete(key) != null)
+ {
+ Count--;
+ }
+ }
+
+ /// <summary>
+ /// Returns the value whose key is equal to or immediately less than <paramref name="key"/>.
+ /// </summary>
+ /// <param name="key">Key for which to find the floor value of</param>
+ /// <returns>Key of node immediately less than <paramref name="key"/></returns>
+ /// <exception cref="ArgumentNullException"><paramref name="key"/> is null</exception>
+ public K Floor(K key)
+ {
+ Node<K, V> node = FloorNode(key);
+ if (node != null)
+ {
+ return node.Key;
+ }
+ return default;
+ }
+
+ /// <summary>
+ /// Returns the node whose key is equal to or immediately greater than <paramref name="key"/>.
+ /// </summary>
+ /// <param name="key">Key for which to find the ceiling node of</param>
+ /// <returns>Key of node immediately greater than <paramref name="key"/></returns>
+ /// <exception cref="ArgumentNullException"><paramref name="key"/> is null</exception>
+ public K Ceiling(K key)
+ {
+ Node<K, V> node = CeilingNode(key);
+ if (node != null)
+ {
+ return node.Key;
+ }
+ return default;
+ }
+
+ /// <summary>
+ /// Finds the value whose key is immediately greater than <paramref name="key"/>.
+ /// </summary>
+ /// <param name="key">Key to find the successor of</param>
+ /// <returns>Value</returns>
+ public K SuccessorOf(K key)
+ {
+ Node<K, V> node = GetNode(key);
+ if (node != null)
+ {
+ Node<K, V> successor = SuccessorOf(node);
+
+ return successor != null ? successor.Key : default;
+ }
+ return default;
+ }
+
+ /// <summary>
+ /// Finds the value whose key is immediately less than <paramref name="key"/>.
+ /// </summary>
+ /// <param name="key">Key to find the predecessor of</param>
+ /// <returns>Value</returns>
+ public K PredecessorOf(K key)
+ {
+ Node<K, V> node = GetNode(key);
+ if (node != null)
+ {
+ Node<K, V> predecessor = PredecessorOf(node);
+
+ return predecessor != null ? predecessor.Key : default;
+ }
+ return default;
+ }
+
+ /// <summary>
+ /// Adds all the nodes in the dictionary as key/value pairs into <paramref name="list"/>.
+ /// <br></br>
+ /// The key/value pairs will be added in Level Order.
+ /// </summary>
+ /// <param name="list">List to add the tree pairs into</param>
+ public List<KeyValuePair<K, V>> AsLevelOrderList()
+ {
+ List<KeyValuePair<K, V>> list = new List<KeyValuePair<K, V>>();
+
+ Queue<Node<K, V>> nodes = new Queue<Node<K, V>>();
+
+ if (this.Root != null)
+ {
+ nodes.Enqueue(this.Root);
+ }
+ while (nodes.TryDequeue(out Node<K, V> node))
+ {
+ list.Add(new KeyValuePair<K, V>(node.Key, node.Value));
+ if (node.Left != null)
+ {
+ nodes.Enqueue(node.Left);
+ }
+ if (node.Right != null)
+ {
+ nodes.Enqueue(node.Right);
+ }
+ }
+ return list;
+ }
+
+ /// <summary>
+ /// Adds all the nodes in the dictionary into <paramref name="list"/>.
+ /// </summary>
+ /// <returns>A list of all KeyValuePairs sorted by Key Order</returns>
+ public List<KeyValuePair<K, V>> AsList()
+ {
+ List<KeyValuePair<K, V>> list = new List<KeyValuePair<K, V>>();
+
+ AddToList(Root, list);
+
+ return list;
+ }
+
+ #endregion
+
+ #region Private Methods (BST)
+
+ /// <summary>
+ /// Adds all nodes that are children of or contained within <paramref name="node"/> into <paramref name="list"/>, in Key Order.
+ /// </summary>
+ /// <param name="node">The node to search for nodes within</param>
+ /// <param name="list">The list to add node to</param>
+ private void AddToList(Node<K, V> node, List<KeyValuePair<K, V>> list)
+ {
+ if (node == null)
+ {
+ return;
+ }
+
+ AddToList(node.Left, list);
+
+ list.Add(new KeyValuePair<K, V>(node.Key, node.Value));
+
+ AddToList(node.Right, list);
+ }
+
+ /// <summary>
+ /// Retrieve the node reference whose key is <paramref name="key"/>, or null if no such node exists.
+ /// </summary>
+ /// <param name="key">Key of the node to get</param>
+ /// <returns>Node reference in the tree</returns>
+ /// <exception cref="ArgumentNullException"><paramref name="key"/> is null</exception>
+ private Node<K, V> GetNode(K key)
+ {
+ ArgumentNullException.ThrowIfNull(key);
+
+ Node<K, V> node = Root;
+ while (node != null)
+ {
+ int cmp = key.CompareTo(node.Key);
+ if (cmp < 0)
+ {
+ node = node.Left;
+ }
+ else if (cmp > 0)
+ {
+ node = node.Right;
+ }
+ else
+ {
+ return node;
+ }
+ }
+ return null;
+ }
+
+ /// <summary>
+ /// Inserts a new node into the tree whose key is <paramref name="key"/> and value is <paramref name="value"/>.
+ /// <br></br>
+ /// Adding the same key multiple times will overwrite the previous value.
+ /// </summary>
+ /// <param name="key">Key of the node to insert</param>
+ /// <param name="value">Value of the node to insert</param>
+ private void Insert(K key, V value)
+ {
+ Node<K, V> newNode = BSTInsert(key, value);
+ RestoreBalanceAfterInsertion(newNode);
+ }
+
+ /// <summary>
+ /// Insertion Mechanism for a Binary Search Tree (BST).
+ /// <br></br>
+ /// 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"/>.
+ /// <br></br>
+ /// <b>Note: </b> If a node whose key is <paramref name="key"/> already exists, it's value will be overwritten.
+ /// </summary>
+ /// <param name="key">Key of the node to insert</param>
+ /// <param name="value">Value of the node to insert</param>
+ /// <returns>The inserted Node</returns>
+ private Node<K, V> BSTInsert(K key, V value)
+ {
+ Node<K, V> parent = null;
+ Node<K, V> node = Root;
+
+ while (node != null)
+ {
+ parent = node;
+ int cmp = key.CompareTo(node.Key);
+ if (cmp < 0)
+ {
+ node = node.Left;
+ }
+ else if (cmp > 0)
+ {
+ node = node.Right;
+ }
+ else
+ {
+ node.Value = value;
+ return node;
+ }
+ }
+ Node<K, V> newNode = new Node<K, V>(key, value, parent);
+ if (newNode.Parent == null)
+ {
+ Root = newNode;
+ }
+ else if (key.CompareTo(parent.Key) < 0)
+ {
+ parent.Left = newNode;
+ }
+ else
+ {
+ parent.Right = newNode;
+ }
+ Count++;
+ return newNode;
+ }
+
+ /// <summary>
+ /// Removes <paramref name="key"/> from the dictionary, if it exists.
+ /// </summary>
+ /// <param name="key">Key of the node to delete</param>
+ /// <returns>The deleted Node</returns>
+ private Node<K, V> Delete(K key)
+ {
+ // O(1) Retrieval
+ Node<K, V> nodeToDelete = GetNode(key);
+
+ if (nodeToDelete == null) return null;
+
+ Node<K, V> replacementNode;
+
+ if (LeftOf(nodeToDelete) == null || RightOf(nodeToDelete) == null)
+ {
+ replacementNode = nodeToDelete;
+ }
+ else
+ {
+ replacementNode = PredecessorOf(nodeToDelete);
+ }
+
+ Node<K, V> tmp = LeftOf(replacementNode) ?? RightOf(replacementNode);
+
+ if (tmp != null)
+ {
+ tmp.Parent = ParentOf(replacementNode);
+ }
+
+ if (ParentOf(replacementNode) == null)
+ {
+ Root = tmp;
+ }
+ else if (replacementNode == LeftOf(ParentOf(replacementNode)))
+ {
+ ParentOf(replacementNode).Left = tmp;
+ }
+ else
+ {
+ ParentOf(replacementNode).Right = tmp;
+ }
+
+ if (replacementNode != nodeToDelete)
+ {
+ nodeToDelete.Key = replacementNode.Key;
+ nodeToDelete.Value = replacementNode.Value;
+ }
+
+ if (tmp != null && ColorOf(replacementNode) == Black)
+ {
+ RestoreBalanceAfterRemoval(tmp);
+ }
+
+ return replacementNode;
+ }
+
+ /// <summary>
+ /// Returns the node whose key immediately less than or equal to <paramref name="key"/>.
+ /// </summary>
+ /// <param name="key">Key for which to find the floor node of</param>
+ /// <returns>Node whose key is immediately less than or equal to <paramref name="key"/>, or null if no such node is found.</returns>
+ /// <exception cref="ArgumentNullException"><paramref name="key"/> is null</exception>
+ private Node<K, V> FloorNode(K key)
+ {
+ ArgumentNullException.ThrowIfNull(key);
+
+ Node<K, V> tmp = Root;
+
+ while (tmp != null)
+ {
+ int cmp = key.CompareTo(tmp.Key);
+ if (cmp > 0)
+ {
+ if (tmp.Right != null)
+ {
+ tmp = tmp.Right;
+ }
+ else
+ {
+ return tmp;
+ }
+ }
+ else if (cmp < 0)
+ {
+ if (tmp.Left != null)
+ {
+ tmp = tmp.Left;
+ }
+ else
+ {
+ Node<K, V> parent = tmp.Parent;
+ Node<K, V> ptr = tmp;
+ while (parent != null && ptr == parent.Left)
+ {
+ ptr = parent;
+ parent = parent.Parent;
+ }
+ return parent;
+ }
+ }
+ else
+ {
+ return tmp;
+ }
+ }
+ return null;
+ }
+
+ /// <summary>
+ /// Returns the node whose key is immediately greater than or equal to than <paramref name="key"/>.
+ /// </summary>
+ /// <param name="key">Key for which to find the ceiling node of</param>
+ /// <returns>Node whose key is immediately greater than or equal to <paramref name="key"/>, or null if no such node is found.</returns>
+ /// <exception cref="ArgumentNullException"><paramref name="key"/> is null</exception>
+ private Node<K, V> CeilingNode(K key)
+ {
+ ArgumentNullException.ThrowIfNull(key);
+
+ Node<K, V> tmp = Root;
+
+ while (tmp != null)
+ {
+ int cmp = key.CompareTo(tmp.Key);
+ if (cmp < 0)
+ {
+ if (tmp.Left != null)
+ {
+ tmp = tmp.Left;
+ }
+ else
+ {
+ return tmp;
+ }
+ }
+ else if (cmp > 0)
+ {
+ if (tmp.Right != null)
+ {
+ tmp = tmp.Right;
+ }
+ else
+ {
+ Node<K, V> parent = tmp.Parent;
+ Node<K, V> ptr = tmp;
+ while (parent != null && ptr == parent.Right)
+ {
+ ptr = parent;
+ parent = parent.Parent;
+ }
+ return parent;
+ }
+ }
+ else
+ {
+ return tmp;
+ }
+ }
+ return null;
+ }
+
+ #endregion
+
+ #region Interface Implementations
+
+ // Method descriptions are not provided as they are already included as part of the interface.
+ public bool ContainsKey(K key)
+ {
+ ArgumentNullException.ThrowIfNull(key);
+
+ return GetNode(key) != null;
+ }
+
+ bool IDictionary<K, V>.Remove(K key)
+ {
+ int count = Count;
+ Remove(key);
+ return count > Count;
+ }
+
+ public bool TryGetValue(K key, [MaybeNullWhen(false)] out V value)
+ {
+ ArgumentNullException.ThrowIfNull(key);
+
+ Node<K, V> node = GetNode(key);
+ value = node != null ? node.Value : default;
+ return node != null;
+ }
+
+ public void Add(KeyValuePair<K, V> item)
+ {
+ ArgumentNullException.ThrowIfNull(item.Key);
+
+ Add(item.Key, item.Value);
+ }
+
+ public bool Contains(KeyValuePair<K, V> item)
+ {
+ if (item.Key == null)
+ {
+ return false;
+ }
+
+ Node<K, V> node = GetNode(item.Key);
+ if (node != null)
+ {
+ return node.Key.Equals(item.Key) && node.Value.Equals(item.Value);
+ }
+ return false;
+ }
+
+ public void CopyTo(KeyValuePair<K, V>[] array, int arrayIndex)
+ {
+ if (arrayIndex < 0 || array.Length - arrayIndex < this.Count)
+ {
+ throw new ArgumentOutOfRangeException(nameof(arrayIndex));
+ }
+
+ SortedList<K, V> list = GetKeyValues();
+
+ int offset = 0;
+
+ for (int i = arrayIndex; i < array.Length && offset < list.Count; i++)
+ {
+ array[i] = new KeyValuePair<K, V>(list.Keys[i], list.Values[i]);
+ offset++;
+ }
+ }
+
+ public bool Remove(KeyValuePair<K, V> item)
+ {
+ Node<K, V> node = GetNode(item.Key);
+
+ if (node == null)
+ {
+ return false;
+ }
+
+ if (node.Value.Equals(item.Value))
+ {
+ int count = Count;
+ Remove(item.Key);
+ return count > Count;
+ }
+
+ return false;
+ }
+
+ public IEnumerator<KeyValuePair<K, V>> GetEnumerator()
+ {
+ return GetKeyValues().GetEnumerator();
+ }
+
+ IEnumerator IEnumerable.GetEnumerator()
+ {
+ return GetKeyValues().GetEnumerator();
+ }
+
+ public ICollection<K> Keys => GetKeyValues().Keys;
+
+ public ICollection<V> Values => GetKeyValues().Values;
+
+ public bool IsReadOnly => false;
+
+ public V this[K key]
+ {
+ get => Get(key);
+ set => Add(key, value);
+ }
+
+ #endregion
+
+ #region Private Interface Helper Methods
+
+ /// <summary>
+ /// Returns a sorted list of all the node keys / values in the tree.
+ /// </summary>
+ /// <returns>List of node keys</returns>
+ private SortedList<K, V> GetKeyValues()
+ {
+ SortedList<K, V> set = new SortedList<K, V>();
+ Queue<Node<K, V>> queue = new Queue<Node<K, V>>();
+ if (Root != null)
+ {
+ queue.Enqueue(Root);
+ }
+
+ while (queue.TryDequeue(out Node<K, V> node))
+ {
+ set.Add(node.Key, node.Value);
+ if (null != node.Left)
+ {
+ queue.Enqueue(node.Left);
+ }
+ if (null != node.Right)
+ {
+ queue.Enqueue(node.Right);
+ }
+ }
+
+ return set;
+ }
+
+ #endregion
+ }
+
+ /// <summary>
+ /// Represents a node in the TreeDictionary which contains a key and value of generic type K and V, respectively.
+ /// </summary>
+ /// <typeparam name="K">Key of the node</typeparam>
+ /// <typeparam name="V">Value of the node</typeparam>
+ public class Node<K, V> : IntrusiveRedBlackTreeNode<Node<K, V>> where K : IComparable<K>
+ {
+ internal K Key;
+ internal V Value;
+
+ internal Node(K key, V value, Node<K, V> parent)
+ {
+ Key = key;
+ Value = value;
+ Parent = parent;
+ }
+ }
+}