aboutsummaryrefslogtreecommitdiff
path: root/src/Ryujinx.Memory/WindowsShared/MappingTree.cs
blob: 97758c2b19020748be854d0bed1b83fc8e253fdb (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
using Ryujinx.Common.Collections;
using System;

namespace Ryujinx.Memory.WindowsShared
{
    /// <summary>
    /// A intrusive Red-Black Tree that also supports getting nodes overlapping a given range.
    /// </summary>
    /// <typeparam name="T">Type of the value stored on the node</typeparam>
    class MappingTree<T> : IntrusiveRedBlackTree<RangeNode<T>>
    {
        private const int ArrayGrowthSize = 16;

        public int GetNodes(ulong start, ulong end, ref RangeNode<T>[] overlaps, int overlapCount = 0)
        {
            RangeNode<T> node = this.GetNodeByKey(start);

            for (; node != null; node = node.Successor)
            {
                if (overlaps.Length <= overlapCount)
                {
                    Array.Resize(ref overlaps, overlapCount + ArrayGrowthSize);
                }

                overlaps[overlapCount++] = node;

                if (node.End >= end)
                {
                    break;
                }
            }

            return overlapCount;
        }
    }

    class RangeNode<T> : IntrusiveRedBlackTreeNode<RangeNode<T>>, IComparable<RangeNode<T>>, IComparable<ulong>
    {
        public ulong Start { get; }
        public ulong End { get; private set; }
        public T Value { get; }

        public RangeNode(ulong start, ulong end, T value)
        {
            Start = start;
            End = end;
            Value = value;
        }

        public void Extend(ulong sizeDelta)
        {
            End += sizeDelta;
        }

        public int CompareTo(RangeNode<T> other)
        {
            if (Start < other.Start)
            {
                return -1;
            }
            else if (Start <= other.End - 1UL)
            {
                return 0;
            }
            else
            {
                return 1;
            }
        }

        public int CompareTo(ulong address)
        {
            if (address < Start)
            {
                return 1;
            }
            else if (address <= End - 1UL)
            {
                return 0;
            }
            else
            {
                return -1;
            }
        }
    }
}