From 37e0eb994d7c89205f2b817dbb6b4abee18372f2 Mon Sep 17 00:00:00 2001 From: Eliza Weisman Date: Sat, 11 Jan 2025 10:18:37 -0800 Subject: [PATCH] feat(hal): add nicer addr->`NonNull` conversion (#509) This is just a bit more convenient. --- hal-core/src/addr.rs | 24 ++++++++++++++++++++++++ hal-x86_64/src/mm.rs | 4 ++-- 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/hal-core/src/addr.rs b/hal-core/src/addr.rs index b06780a4..a70e0cbd 100644 --- a/hal-core/src/addr.rs +++ b/hal-core/src/addr.rs @@ -152,6 +152,18 @@ pub trait Address: ); ptr::with_exposed_provenance_mut(self.as_usize()) } + + /// Converts this address into a `Option>` from a + /// `VAddr`, returning `None` if the address is null. + /// + /// # Panics + /// + /// - If `self` is not aligned for a `T`-typed value. + #[inline] + #[track_caller] + fn as_non_null(self) -> Option> { + ptr::NonNull::new(self.as_mut_ptr::()) + } } #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd)] @@ -369,6 +381,18 @@ macro_rules! impl_addrs { pub fn as_mut_ptr(self) -> *mut T { Address::as_mut_ptr(self) } + + /// Converts this address into a `Option>` from a + /// `VAddr`, returning `None` if the address is null. + /// + /// # Panics + /// + /// - If `self` is not aligned for a `T`-typed value. + #[inline] + #[track_caller] + pub fn as_non_null(self) -> Option> { + ptr::NonNull::new(self.as_mut_ptr::()) + } } )+ } diff --git a/hal-x86_64/src/mm.rs b/hal-x86_64/src/mm.rs index d8500e37..aafdb201 100644 --- a/hal-x86_64/src/mm.rs +++ b/hal-x86_64/src/mm.rs @@ -303,7 +303,7 @@ impl PageTable { tracing::trace!(next.addr = ?vaddr, "found next table virtual address"); // XXX(eliza): this _probably_ could be be a `new_unchecked`...if, after // all this, the next table address is null...we're probably pretty fucked! - Some(unsafe { &*NonNull::new(vaddr.as_mut_ptr())?.as_ptr() }) + Some(unsafe { vaddr.as_non_null()?.as_ref() }) } #[inline] @@ -336,7 +336,7 @@ impl PageTable { tracing::trace!(next.addr = ?vaddr, "found next table virtual address"); // XXX(eliza): this _probably_ could be be a `new_unchecked`...if, after // all this, the next table address is null...we're probably pretty fucked! - Some(unsafe { &mut *NonNull::new(vaddr.as_ptr())?.as_ptr() }) + Some(unsafe { vaddr.as_non_null()?.as_mut() }) } fn create_next_table(