using System;
using WhiteMagic.Native;
namespace WhiteMagic.Memory;
///
/// An immutable snapshot of a memory region as reported by VirtualQueryEx.
///
public readonly record struct MemoryRegion
{
/// The base address of the region of pages.
public IntPtr BaseAddress { get; }
/// The size of the region, in bytes.
public nuint Size { get; }
/// The access protection of the pages in the region.
public MemoryProtectionType Protection { get; }
/// The state of the pages in the region.
public MemoryState State { get; }
/// The type of pages in the region.
public MemoryType Type { get; }
/// The base address of a range of pages allocated by VirtualAllocEx.
public IntPtr AllocationBase { get; }
/// The memory protection option when the region was initially allocated.
public MemoryProtectionType AllocationProtect { get; }
///
/// Initializes a new from explicit values.
///
public MemoryRegion(
IntPtr baseAddress,
nuint size,
MemoryProtectionType protection,
MemoryState state,
MemoryType type,
IntPtr allocationBase,
MemoryProtectionType allocationProtect)
{
BaseAddress = baseAddress;
Size = size;
Protection = protection;
State = state;
Type = type;
AllocationBase = allocationBase;
AllocationProtect = allocationProtect;
}
///
/// Initializes a new from a raw MEMORY_BASIC_INFORMATION.
///
internal MemoryRegion(MemoryBasicInformation info)
{
BaseAddress = info.BaseAddress;
Size = info.RegionSize;
AllocationBase = info.AllocationBase;
AllocationProtect = (MemoryProtectionType)info.AllocationProtect;
Protection = (MemoryProtectionType)info.Protect;
State = (MemoryState)info.State;
Type = (MemoryType)info.Type;
}
///
/// Returns if is inside the region,
/// defined as [BaseAddress, BaseAddress + Size).
///
public bool Contains(IntPtr address)
{
return (nuint)(address - BaseAddress) < Size;
}
}