From e829590d40b6312d994987dd0fdc13fec625c8b2 Mon Sep 17 00:00:00 2001 From: Matthew Leach Date: Wed, 26 Aug 2026 12:03:19 +0100 Subject: [PATCH] libkernel: add `cast_mem_kind` Add functions to addresses and regions which allow easy casting from one address space kind to another, while preserving bits. --- libkernel/src/memory/address.rs | 11 +++++++++++ libkernel/src/memory/region.rs | 15 +++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/libkernel/src/memory/address.rs b/libkernel/src/memory/address.rs index ccc488da..b2ed0575 100644 --- a/libkernel/src/memory/address.rs +++ b/libkernel/src/memory/address.rs @@ -118,6 +118,17 @@ impl Address { } } + /// Cast from one address space kind to the other, without modification of + /// the address bits. + /// + /// # Safety + /// + /// the caller must ensure that the same address is valid in the other + /// address space, e.g. through identity mappings. + pub const unsafe fn cast_mem_kind(self) -> Address { + Address::from_value(self.value()) + } + /// Return the underlying raw address value. pub const fn value(self) -> usize { self.inner diff --git a/libkernel/src/memory/region.rs b/libkernel/src/memory/region.rs index 9ef666ca..7bc95394 100644 --- a/libkernel/src/memory/region.rs +++ b/libkernel/src/memory/region.rs @@ -53,6 +53,21 @@ impl MemoryRegion { Self { address, size } } + /// Cast from one address space kind to the other, without modification of + /// the address bits. + /// + /// # Safety + /// + /// the caller must ensure that the same address is valid in the other + /// address space, e.g. through identity mappings. + pub const unsafe fn cast_mem_kind(self) -> MemoryRegion { + // SAFETY: The caller ensures the safety invariant is true. + MemoryRegion { + address: unsafe { self.address.cast_mem_kind() }, + size: self.size, + } + } + /// Create an empty region with a size of 0 and address 0. pub const fn empty() -> Self { Self {