Skip to content

Commit 37e0eb9

Browse files
committed
feat(hal): add nicer addr->NonNull conversion (#509)
This is just a bit more convenient.
1 parent 312b382 commit 37e0eb9

File tree

2 files changed

+26
-2
lines changed

2 files changed

+26
-2
lines changed

hal-core/src/addr.rs

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -152,6 +152,18 @@ pub trait Address:
152152
);
153153
ptr::with_exposed_provenance_mut(self.as_usize())
154154
}
155+
156+
/// Converts this address into a `Option<NonNull<T>>` from a
157+
/// `VAddr`, returning `None` if the address is null.
158+
///
159+
/// # Panics
160+
///
161+
/// - If `self` is not aligned for a `T`-typed value.
162+
#[inline]
163+
#[track_caller]
164+
fn as_non_null<T>(self) -> Option<ptr::NonNull<T>> {
165+
ptr::NonNull::new(self.as_mut_ptr::<T>())
166+
}
155167
}
156168

157169
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
@@ -369,6 +381,18 @@ macro_rules! impl_addrs {
369381
pub fn as_mut_ptr<T>(self) -> *mut T {
370382
Address::as_mut_ptr(self)
371383
}
384+
385+
/// Converts this address into a `Option<NonNull<T>>` from a
386+
/// `VAddr`, returning `None` if the address is null.
387+
///
388+
/// # Panics
389+
///
390+
/// - If `self` is not aligned for a `T`-typed value.
391+
#[inline]
392+
#[track_caller]
393+
pub fn as_non_null<T>(self) -> Option<ptr::NonNull<T>> {
394+
ptr::NonNull::new(self.as_mut_ptr::<T>())
395+
}
372396
}
373397
)+
374398
}

hal-x86_64/src/mm.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -303,7 +303,7 @@ impl<R: level::Recursive> PageTable<R> {
303303
tracing::trace!(next.addr = ?vaddr, "found next table virtual address");
304304
// XXX(eliza): this _probably_ could be be a `new_unchecked`...if, after
305305
// all this, the next table address is null...we're probably pretty fucked!
306-
Some(unsafe { &*NonNull::new(vaddr.as_mut_ptr())?.as_ptr() })
306+
Some(unsafe { vaddr.as_non_null()?.as_ref() })
307307
}
308308

309309
#[inline]
@@ -336,7 +336,7 @@ impl<R: level::Recursive> PageTable<R> {
336336
tracing::trace!(next.addr = ?vaddr, "found next table virtual address");
337337
// XXX(eliza): this _probably_ could be be a `new_unchecked`...if, after
338338
// all this, the next table address is null...we're probably pretty fucked!
339-
Some(unsafe { &mut *NonNull::new(vaddr.as_ptr())?.as_ptr() })
339+
Some(unsafe { vaddr.as_non_null()?.as_mut() })
340340
}
341341

342342
fn create_next_table<S: Size>(

0 commit comments

Comments
 (0)