Skip to content

Commit

Permalink
feat(hal): add nicer addr->NonNull conversion (#509)
Browse files Browse the repository at this point in the history
This is just a bit more convenient.
  • Loading branch information
hawkw committed Jan 11, 2025
1 parent 312b382 commit 37e0eb9
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 2 deletions.
24 changes: 24 additions & 0 deletions hal-core/src/addr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,18 @@ pub trait Address:
);
ptr::with_exposed_provenance_mut(self.as_usize())
}

/// Converts this address into a `Option<NonNull<T>>` 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<T>(self) -> Option<ptr::NonNull<T>> {
ptr::NonNull::new(self.as_mut_ptr::<T>())
}
}

#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
Expand Down Expand Up @@ -369,6 +381,18 @@ macro_rules! impl_addrs {
pub fn as_mut_ptr<T>(self) -> *mut T {
Address::as_mut_ptr(self)
}

/// Converts this address into a `Option<NonNull<T>>` 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<T>(self) -> Option<ptr::NonNull<T>> {
ptr::NonNull::new(self.as_mut_ptr::<T>())
}
}
)+
}
Expand Down
4 changes: 2 additions & 2 deletions hal-x86_64/src/mm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -303,7 +303,7 @@ impl<R: level::Recursive> PageTable<R> {
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]
Expand Down Expand Up @@ -336,7 +336,7 @@ impl<R: level::Recursive> PageTable<R> {
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<S: Size>(
Expand Down

0 comments on commit 37e0eb9

Please sign in to comment.