MappingTree.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. using Ryujinx.Common.Collections;
  2. using System;
  3. namespace Ryujinx.Memory.WindowsShared
  4. {
  5. /// <summary>
  6. /// A intrusive Red-Black Tree that also supports getting nodes overlapping a given range.
  7. /// </summary>
  8. /// <typeparam name="T">Type of the value stored on the node</typeparam>
  9. class MappingTree<T> : IntrusiveRedBlackTree<RangeNode<T>>
  10. {
  11. private const int ArrayGrowthSize = 16;
  12. public int GetNodes(ulong start, ulong end, ref RangeNode<T>[] overlaps, int overlapCount = 0)
  13. {
  14. RangeNode<T> node = this.GetNodeByKey(start);
  15. for (; node != null; node = node.Successor)
  16. {
  17. if (overlaps.Length <= overlapCount)
  18. {
  19. Array.Resize(ref overlaps, overlapCount + ArrayGrowthSize);
  20. }
  21. overlaps[overlapCount++] = node;
  22. if (node.End >= end)
  23. {
  24. break;
  25. }
  26. }
  27. return overlapCount;
  28. }
  29. }
  30. class RangeNode<T> : IntrusiveRedBlackTreeNode<RangeNode<T>>, IComparable<RangeNode<T>>, IComparable<ulong>
  31. {
  32. public ulong Start { get; }
  33. public ulong End { get; private set; }
  34. public T Value { get; }
  35. public RangeNode(ulong start, ulong end, T value)
  36. {
  37. Start = start;
  38. End = end;
  39. Value = value;
  40. }
  41. public void Extend(ulong sizeDelta)
  42. {
  43. End += sizeDelta;
  44. }
  45. public int CompareTo(RangeNode<T> other)
  46. {
  47. if (Start < other.Start)
  48. {
  49. return -1;
  50. }
  51. else if (Start <= other.End - 1UL)
  52. {
  53. return 0;
  54. }
  55. else
  56. {
  57. return 1;
  58. }
  59. }
  60. public int CompareTo(ulong address)
  61. {
  62. if (address < Start)
  63. {
  64. return 1;
  65. }
  66. else if (address <= End - 1UL)
  67. {
  68. return 0;
  69. }
  70. else
  71. {
  72. return -1;
  73. }
  74. }
  75. }
  76. }