diff --git a/Ryujinx.Common/Collections/IntervalTree.cs b/Ryujinx.Common/Collections/IntervalTree.cs
new file mode 100644
index 0000000000..e1b81f4e08
--- /dev/null
+++ b/Ryujinx.Common/Collections/IntervalTree.cs
@@ -0,0 +1,815 @@
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+
+namespace Ryujinx.Common.Collections
+{
+ ///
+ /// An Augmented Interval Tree based off of the "TreeDictionary"'s Red-Black Tree. Allows fast overlap checking of ranges.
+ ///
+ /// Key
+ /// Value
+ public class IntervalTree where K : IComparable
+ {
+ private const int ArrayGrowthSize = 32;
+
+ private const bool Black = true;
+ private const bool Red = false;
+ private IntervalTreeNode _root = null;
+ private int _count = 0;
+
+ public int Count => _count;
+
+ public IntervalTree() { }
+
+ #region Public Methods
+
+ ///
+ /// Gets the values of the interval whose key is .
+ ///
+ /// Key of the node value to get
+ /// Overlaps array to place results in
+ /// Number of values found
+ /// is null
+ public int Get(K key, ref V[] overlaps)
+ {
+ if (key == null)
+ {
+ throw new ArgumentNullException(nameof(key));
+ }
+
+ IntervalTreeNode 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 value in node.Values)
+ {
+ overlaps[overlapsCount++] = value.Value;
+ }
+
+ return overlapsCount;
+ }
+
+ ///
+ /// Returns the values of the intervals whose start and end keys overlap the given range.
+ ///
+ /// Start of the range
+ /// End of the range
+ /// Overlaps array to place results in
+ /// Index to start writing results into the array. Defaults to 0
+ /// Number of values found
+ /// or is null
+ public int Get(K start, K end, ref V[] overlaps, int overlapCount = 0)
+ {
+ if (start == null)
+ {
+ throw new ArgumentNullException(nameof(start));
+ }
+
+ if (end == null)
+ {
+ throw new ArgumentNullException(nameof(end));
+ }
+
+ GetValues(_root, start, end, ref overlaps, ref overlapCount);
+
+ return overlapCount;
+ }
+
+ ///
+ /// Adds a new interval into the tree whose start is , end is and value is .
+ ///
+ /// Start of the range to add
+ /// End of the range to insert
+ /// Value to add
+ /// , or are null
+ public void Add(K start, K end, V value)
+ {
+ if (start == null)
+ {
+ throw new ArgumentNullException(nameof(start));
+ }
+
+ if (end == null)
+ {
+ throw new ArgumentNullException(nameof(end));
+ }
+
+ if (value == null)
+ {
+ throw new ArgumentNullException(nameof(value));
+ }
+
+ Insert(start, end, value);
+ }
+
+ ///
+ /// Removes the given from the tree, searching for it with .
+ ///
+ /// Key of the node to remove
+ /// Value to remove
+ /// is null
+ /// Number of deleted values
+ public int Remove(K key, V value)
+ {
+ if (key == null)
+ {
+ throw new ArgumentNullException(nameof(key));
+ }
+
+ int removed = Delete(key, value);
+
+ _count -= removed;
+
+ return removed;
+ }
+
+ ///
+ /// Adds all the nodes in the dictionary into .
+ ///
+ /// A list of all RangeNodes sorted by Key Order
+ public List> AsList()
+ {
+ List> list = new List>();
+
+ AddToList(_root, list);
+
+ return list;
+ }
+
+ #endregion
+
+ #region Private Methods (BST)
+
+ ///
+ /// Adds all RangeNodes that are children of or contained within into , in Key Order.
+ ///
+ /// The node to search for RangeNodes within
+ /// The list to add RangeNodes to
+ private void AddToList(IntervalTreeNode node, List> list)
+ {
+ if (node == null)
+ {
+ return;
+ }
+
+ AddToList(node.Left, list);
+
+ list.AddRange(node.Values);
+
+ AddToList(node.Right, list);
+ }
+
+ ///
+ /// Retrieve the node reference whose key is , or null if no such node exists.
+ ///
+ /// Key of the node to get
+ /// Node reference in the tree
+ /// is null
+ private IntervalTreeNode GetNode(K key)
+ {
+ if (key == null)
+ {
+ throw new ArgumentNullException(nameof(key));
+ }
+
+ IntervalTreeNode 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;
+ }
+
+ ///
+ /// Retrieve all values that overlap the given start and end keys.
+ ///
+ /// Start of the range
+ /// End of the range
+ /// Overlaps array to place results in
+ /// Overlaps count to update
+ private void GetValues(IntervalTreeNode 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 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);
+ }
+ }
+
+ ///
+ /// Inserts a new node into the tree with a given , and .
+ ///
+ /// Start of the range to insert
+ /// End of the range to insert
+ /// Value to insert
+ private void Insert(K start, K end, V value)
+ {
+ IntervalTreeNode newNode = BSTInsert(start, end, value);
+ RestoreBalanceAfterInsertion(newNode);
+ }
+
+ ///
+ /// 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.
+ ///
+ /// The node to start propagating from
+ private void PropagateIncrease(IntervalTreeNode node)
+ {
+ K max = node.Max;
+ IntervalTreeNode ptr = node;
+
+ while ((ptr = ptr.Parent) != null)
+ {
+ if (max.CompareTo(ptr.Max) > 0)
+ {
+ ptr.Max = max;
+ }
+ else
+ {
+ break;
+ }
+ }
+ }
+
+ ///
+ /// 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.
+ ///
+ /// The node to start propagating from
+ private void PropagateFull(IntervalTreeNode node)
+ {
+ IntervalTreeNode 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);
+ }
+
+ ///
+ /// 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 , and all children in the right subtree are greater than .
+ /// 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.
+ ///
+ /// Start of the range to insert
+ /// End of the range to insert
+ /// Value to insert
+ /// The inserted Node
+ private IntervalTreeNode BSTInsert(K start, K end, V value)
+ {
+ IntervalTreeNode parent = null;
+ IntervalTreeNode 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(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 newNode = new IntervalTreeNode(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;
+ }
+
+ ///
+ /// Removes instances of from the dictionary after searching for it with .
+ ///
+ /// Key to search for
+ /// Value to delete
+ /// Number of deleted values
+ private int Delete(K key, V value)
+ {
+ IntervalTreeNode 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 replacementNode;
+
+ if (LeftOf(nodeToDelete) == null || RightOf(nodeToDelete) == null)
+ {
+ replacementNode = nodeToDelete;
+ }
+ else
+ {
+ replacementNode = PredecessorOf(nodeToDelete);
+ }
+
+ IntervalTreeNode 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;
+ }
+
+ ///
+ /// Returns the node with the largest key where is considered the root node.
+ ///
+ /// Root Node
+ /// Node with the maximum key in the tree of
+ private static IntervalTreeNode Maximum(IntervalTreeNode node)
+ {
+ IntervalTreeNode tmp = node;
+ while (tmp.Right != null)
+ {
+ tmp = tmp.Right;
+ }
+
+ return tmp;
+ }
+
+ ///
+ /// Finds the node whose key is immediately less than .
+ ///
+ /// Node to find the predecessor of
+ /// Predecessor of
+ private static IntervalTreeNode PredecessorOf(IntervalTreeNode node)
+ {
+ if (node.Left != null)
+ {
+ return Maximum(node.Left);
+ }
+ IntervalTreeNode parent = node.Parent;
+ while (parent != null && node == parent.Left)
+ {
+ node = parent;
+ parent = parent.Parent;
+ }
+ return parent;
+ }
+ #endregion
+
+ #region Private Methods (RBL)
+ private void RestoreBalanceAfterRemoval(IntervalTreeNode balanceNode)
+ {
+ IntervalTreeNode ptr = balanceNode;
+
+ while (ptr != _root && ColorOf(ptr) == Black)
+ {
+ if (ptr == LeftOf(ParentOf(ptr)))
+ {
+ IntervalTreeNode 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
+ {
+ IntervalTreeNode 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);
+ }
+
+ private void RestoreBalanceAfterInsertion(IntervalTreeNode balanceNode)
+ {
+ SetColor(balanceNode, Red);
+ while (balanceNode != null && balanceNode != _root && ColorOf(ParentOf(balanceNode)) == Red)
+ {
+ if (ParentOf(balanceNode) == LeftOf(ParentOf(ParentOf(balanceNode))))
+ {
+ IntervalTreeNode 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
+ {
+ IntervalTreeNode 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);
+ }
+
+ private void RotateLeft(IntervalTreeNode node)
+ {
+ if (node != null)
+ {
+ IntervalTreeNode right = RightOf(node);
+ node.Right = LeftOf(right);
+ if (node.Right != null)
+ {
+ node.Right.Parent = node;
+ }
+ IntervalTreeNode 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;
+
+ PropagateFull(node);
+ }
+ }
+
+ private void RotateRight(IntervalTreeNode node)
+ {
+ if (node != null)
+ {
+ IntervalTreeNode left = LeftOf(node);
+ node.Left = RightOf(left);
+ if (node.Left != null)
+ {
+ node.Left.Parent = node;
+ }
+ IntervalTreeNode 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;
+
+ PropagateFull(node);
+ }
+ }
+ #endregion
+
+ #region Safety-Methods
+
+ // These methods save memory by allowing us to forego sentinel nil nodes, as well as serve as protection against NullReferenceExceptions.
+
+ ///
+ /// Returns the color of , or Black if it is null.
+ ///
+ /// Node
+ /// The boolean color of , or black if null
+ private static bool ColorOf(IntervalTreeNode node)
+ {
+ return node == null || node.Color;
+ }
+
+ ///
+ /// Sets the color of node to .
+ ///
+ /// This method does nothing if is null.
+ ///
+ /// Node to set the color of
+ /// Color (Boolean)
+ private static void SetColor(IntervalTreeNode node, bool color)
+ {
+ if (node != null)
+ {
+ node.Color = color;
+ }
+ }
+
+ ///
+ /// This method returns the left node of , or null if is null.
+ ///
+ /// Node to retrieve the left child from
+ /// Left child of
+ private static IntervalTreeNode LeftOf(IntervalTreeNode node)
+ {
+ return node?.Left;
+ }
+
+ ///
+ /// This method returns the right node of , or null if is null.
+ ///
+ /// Node to retrieve the right child from
+ /// Right child of
+ private static IntervalTreeNode RightOf(IntervalTreeNode node)
+ {
+ return node?.Right;
+ }
+
+ ///
+ /// Returns the parent node of , or null if is null.
+ ///
+ /// Node to retrieve the parent from
+ /// Parent of
+ private static IntervalTreeNode ParentOf(IntervalTreeNode node)
+ {
+ return node?.Parent;
+ }
+ #endregion
+
+ public bool ContainsKey(K key)
+ {
+ if (key == null)
+ {
+ throw new ArgumentNullException(nameof(key));
+ }
+ return GetNode(key) != null;
+ }
+
+ public void Clear()
+ {
+ _root = null;
+ _count = 0;
+ }
+ }
+
+ ///
+ /// Represents a value and its start and end keys.
+ ///
+ ///
+ ///
+ public readonly struct RangeNode
+ {
+ 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;
+ }
+ }
+
+ ///
+ /// Represents a node in the IntervalTree which contains start and end keys of type K, and a value of generic type V.
+ ///
+ /// Key type of the node
+ /// Value type of the node
+ internal class IntervalTreeNode
+ {
+ internal bool Color = true;
+ internal IntervalTreeNode Left = null;
+ internal IntervalTreeNode Right = null;
+ internal IntervalTreeNode Parent = null;
+
+ ///
+ /// The start of the range.
+ ///
+ internal K Start;
+
+ ///
+ /// The end of the range - maximum of all in the Values list.
+ ///
+ internal K End;
+
+ ///
+ /// The maximum end value of this node and all its children.
+ ///
+ internal K Max;
+
+ internal List> Values;
+
+ public IntervalTreeNode(K start, K end, V value, IntervalTreeNode parent)
+ {
+ this.Start = start;
+ this.End = end;
+ this.Max = end;
+ this.Values = new List> { new RangeNode(start, end, value) };
+ this.Parent = parent;
+ }
+ }
+}
diff --git a/Ryujinx.Common/Collections/TreeDictionary.cs b/Ryujinx.Common/Collections/TreeDictionary.cs
index a44f650c1b..ca9467df77 100644
--- a/Ryujinx.Common/Collections/TreeDictionary.cs
+++ b/Ryujinx.Common/Collections/TreeDictionary.cs
@@ -182,38 +182,40 @@ namespace Ryujinx.Common.Collections
///
/// Adds all the nodes in the dictionary into .
- ///
- /// The nodes will be added in Sorted by Key Order.
///
+ /// A list of all KeyValuePairs sorted by Key Order
public List> AsList()
{
List> list = new List>();
- Queue> nodes = new Queue>();
-
- if (this._root != null)
- {
- nodes.Enqueue(this._root);
- }
- while (nodes.Count > 0)
- {
- Node node = nodes.Dequeue();
- list.Add(new KeyValuePair(node.Key, node.Value));
- if (node.Left != null)
- {
- nodes.Enqueue(node.Left);
- }
- if (node.Right != null)
- {
- nodes.Enqueue(node.Right);
- }
- }
+ AddToList(_root, list);
return list;
}
+
#endregion
+
#region Private Methods (BST)
+ ///
+ /// Adds all nodes that are children of or contained within into , in Key Order.
+ ///
+ /// The node to search for nodes within
+ /// The list to add node to
+ private void AddToList(Node node, List> list)
+ {
+ if (node == null)
+ {
+ return;
+ }
+
+ AddToList(node.Left, list);
+
+ list.Add(new KeyValuePair(node.Key, node.Value));
+
+ AddToList(node.Right, list);
+ }
+
///
/// Retrieve the node reference whose key is , or null if no such node exists.
///
@@ -373,13 +375,8 @@ namespace Ryujinx.Common.Collections
///
/// Root Node
/// Node with the maximum key in the tree of
- /// is null
private static Node Maximum(Node node)
{
- if (node == null)
- {
- throw new ArgumentNullException(nameof(node));
- }
Node tmp = node;
while (tmp.Right != null)
{
@@ -519,7 +516,7 @@ namespace Ryujinx.Common.Collections
}
///
- /// Finds the node with the key immediately greater than .Key.
+ /// Finds the node with the key is immediately greater than .
///
/// Node to find the successor of
/// Successor of
@@ -539,7 +536,7 @@ namespace Ryujinx.Common.Collections
}
///
- /// Finds the node whose key immediately less than .Key.
+ /// Finds the node whose key is immediately less than .
///
/// Node to find the predecessor of
/// Predecessor of
@@ -557,7 +554,9 @@ namespace Ryujinx.Common.Collections
}
return parent;
}
+
#endregion
+
#region Private Methods (RBL)
private void RestoreBalanceAfterRemoval(Node balanceNode)
@@ -748,7 +747,7 @@ namespace Ryujinx.Common.Collections
#region Safety-Methods
- // These methods save memory by allowing us to forego sentinel nil nodes, as well as serve as protection against nullpointerexceptions.
+ // These methods save memory by allowing us to forego sentinel nil nodes, as well as serve as protection against NullReferenceExceptions.
///
/// Returns the color of , or Black if it is null.
diff --git a/Ryujinx.Memory/Range/MultiRangeList.cs b/Ryujinx.Memory/Range/MultiRangeList.cs
index 1d5439a022..38ca63b483 100644
--- a/Ryujinx.Memory/Range/MultiRangeList.cs
+++ b/Ryujinx.Memory/Range/MultiRangeList.cs
@@ -1,27 +1,21 @@
-using System;
+using Ryujinx.Common.Collections;
using System.Collections;
using System.Collections.Generic;
namespace Ryujinx.Memory.Range
{
- ///
- /// Sorted list of ranges that supports binary search.
- ///
- /// Type of the range.
public class MultiRangeList : IEnumerable where T : IMultiRangeItem
{
- private const int ArrayGrowthSize = 32;
+ private readonly IntervalTree _items;
- private readonly List _items;
-
- public int Count => _items.Count;
+ public int Count { get; private set; }
///
/// Creates a new range list.
///
public MultiRangeList()
{
- _items = new List();
+ _items = new IntervalTree();
}
///
@@ -30,14 +24,15 @@ namespace Ryujinx.Memory.Range
/// The item to be added
public void Add(T item)
{
- int index = BinarySearch(item.BaseAddress);
+ MultiRange range = item.Range;
- if (index < 0)
+ for (int i = 0; i < range.Count; i++)
{
- index = ~index;
+ var subrange = range.GetSubRange(i);
+ _items.Add(subrange.Address, subrange.EndAddress, item);
}
- _items.Insert(index, item);
+ Count++;
}
///
@@ -47,34 +42,23 @@ namespace Ryujinx.Memory.Range
/// True if the item was removed, or false if it was not found
public bool Remove(T item)
{
- int index = BinarySearch(item.BaseAddress);
+ MultiRange range = item.Range;
- if (index >= 0)
+ int removed = 0;
+
+ for (int i = 0; i < range.Count; i++)
{
- while (index > 0 && _items[index - 1].BaseAddress == item.BaseAddress)
- {
- index--;
- }
-
- while (index < _items.Count)
- {
- if (_items[index].Equals(item))
- {
- _items.RemoveAt(index);
-
- return true;
- }
-
- if (_items[index].BaseAddress > item.BaseAddress)
- {
- break;
- }
-
- index++;
- }
+ var subrange = range.GetSubRange(i);
+ removed += _items.Remove(subrange.Address, item);
}
- return false;
+ if (removed > 0)
+ {
+ // All deleted intervals are for the same item - the one we removed.
+ Count--;
+ }
+
+ return removed > 0;
}
///
@@ -97,22 +81,47 @@ namespace Ryujinx.Memory.Range
/// The number of overlapping items found
public int FindOverlaps(MultiRange range, ref T[] output)
{
- int outputIndex = 0;
+ int overlapCount = 0;
- foreach (T item in _items)
+ for (int i = 0; i < range.Count; i++)
{
- if (item.Range.OverlapsWith(range))
- {
- if (outputIndex == output.Length)
- {
- Array.Resize(ref output, outputIndex + ArrayGrowthSize);
- }
-
- output[outputIndex++] = item;
- }
+ var subrange = range.GetSubRange(i);
+ overlapCount = _items.Get(subrange.Address, subrange.EndAddress, ref output, overlapCount);
}
- return outputIndex;
+ // Remove any duplicates, caused by items having multiple sub range nodes in the tree.
+ if (overlapCount > 1)
+ {
+ int insertPtr = 0;
+ for (int i = 0; i < overlapCount; i++)
+ {
+ T item = output[i];
+ bool duplicate = false;
+
+ for (int j = insertPtr - 1; j >= 0; j--)
+ {
+ if (item.Equals(output[j]))
+ {
+ duplicate = true;
+ break;
+ }
+ }
+
+ if (!duplicate)
+ {
+ if (insertPtr != i)
+ {
+ output[insertPtr] = item;
+ }
+
+ insertPtr++;
+ }
+ }
+
+ overlapCount = insertPtr;
+ }
+
+ return overlapCount;
}
///
@@ -123,82 +132,50 @@ namespace Ryujinx.Memory.Range
/// The number of matches found
public int FindOverlaps(ulong baseAddress, ref T[] output)
{
- int index = BinarySearch(baseAddress);
+ int count = _items.Get(baseAddress, ref output);
- int outputIndex = 0;
-
- if (index >= 0)
+ // Only output items with matching base address
+ int insertPtr = 0;
+ for (int i = 0; i < count; i++)
{
- while (index > 0 && _items[index - 1].BaseAddress == baseAddress)
+ if (output[i].BaseAddress == baseAddress)
{
- index--;
- }
-
- while (index < _items.Count)
- {
- T overlap = _items[index++];
-
- if (overlap.BaseAddress != baseAddress)
+ if (i != insertPtr)
{
- break;
+ output[insertPtr] = output[i];
}
- if (outputIndex == output.Length)
- {
- Array.Resize(ref output, outputIndex + ArrayGrowthSize);
- }
-
- output[outputIndex++] = overlap;
+ insertPtr++;
}
}
- return outputIndex;
+ return insertPtr;
}
- ///
- /// Performs binary search on the internal list of items.
- ///
- /// Address to find
- /// List index of the item, or complement index of nearest item with lower value on the list
- private int BinarySearch(ulong address)
+ private List GetList()
{
- int left = 0;
- int right = _items.Count - 1;
+ var items = _items.AsList();
+ var result = new List();
- while (left <= right)
+ foreach (RangeNode item in items)
{
- int range = right - left;
-
- int middle = left + (range >> 1);
-
- T item = _items[middle];
-
- if (item.BaseAddress == address)
+ if (item.Start == item.Value.BaseAddress)
{
- return middle;
- }
-
- if (address < item.BaseAddress)
- {
- right = middle - 1;
- }
- else
- {
- left = middle + 1;
+ result.Add(item.Value);
}
}
- return ~left;
+ return result;
}
public IEnumerator GetEnumerator()
{
- return _items.GetEnumerator();
+ return GetList().GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
- return _items.GetEnumerator();
+ return GetList().GetEnumerator();
}
}
-}
\ No newline at end of file
+}