MappingTree.cs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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 = GetNode(new RangeNode<T>(start, start + 1UL, default));
  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>>
  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. }
  61. }