MemoryRange.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. using System;
  2. namespace Ryujinx.Memory.Range
  3. {
  4. /// <summary>
  5. /// Range of memory composed of an address and size.
  6. /// </summary>
  7. public struct MemoryRange : IEquatable<MemoryRange>
  8. {
  9. /// <summary>
  10. /// An empty memory range, with a null address and zero size.
  11. /// </summary>
  12. public static MemoryRange Empty => new MemoryRange(0UL, 0);
  13. /// <summary>
  14. /// Start address of the range.
  15. /// </summary>
  16. public ulong Address { get; }
  17. /// <summary>
  18. /// Size of the range in bytes.
  19. /// </summary>
  20. public ulong Size { get; }
  21. /// <summary>
  22. /// Address where the range ends (exclusive).
  23. /// </summary>
  24. public ulong EndAddress => Address + Size;
  25. /// <summary>
  26. /// Creates a new memory range with the specified address and size.
  27. /// </summary>
  28. /// <param name="address">Start address</param>
  29. /// <param name="size">Size in bytes</param>
  30. public MemoryRange(ulong address, ulong size)
  31. {
  32. Address = address;
  33. Size = size;
  34. }
  35. /// <summary>
  36. /// Checks if the range overlaps with another.
  37. /// </summary>
  38. /// <param name="other">The other range to check for overlap</param>
  39. /// <returns>True if the ranges overlap, false otherwise</returns>
  40. public bool OverlapsWith(MemoryRange other)
  41. {
  42. ulong thisAddress = Address;
  43. ulong thisEndAddress = EndAddress;
  44. ulong otherAddress = other.Address;
  45. ulong otherEndAddress = other.EndAddress;
  46. // If any of the ranges if invalid (address + size overflows),
  47. // then they are never considered to overlap.
  48. if (thisEndAddress < thisAddress || otherEndAddress < otherAddress)
  49. {
  50. return false;
  51. }
  52. return thisAddress < otherEndAddress && otherAddress < thisEndAddress;
  53. }
  54. public override bool Equals(object obj)
  55. {
  56. return obj is MemoryRange other && Equals(other);
  57. }
  58. public bool Equals(MemoryRange other)
  59. {
  60. return Address == other.Address && Size == other.Size;
  61. }
  62. public override int GetHashCode()
  63. {
  64. return HashCode.Combine(Address, Size);
  65. }
  66. }
  67. }