Skip to content

Commit

Permalink
Add and use Unique::as_non_null_ptr
Browse files Browse the repository at this point in the history
  • Loading branch information
saethlin committed Feb 9, 2024
1 parent 611c3cb commit dbf817b
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 4 deletions.
6 changes: 2 additions & 4 deletions library/core/src/ptr/non_null.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1591,8 +1591,7 @@ impl<T> NonNull<[T]> {
#[unstable(feature = "slice_ptr_get", issue = "74265")]
#[rustc_const_unstable(feature = "slice_ptr_get", issue = "74265")]
pub const fn as_non_null_ptr(self) -> NonNull<T> {
// SAFETY: We know `self` is non-null.
unsafe { NonNull::new_unchecked(self.as_ptr().as_mut_ptr()) }
self.cast()
}

/// Returns a raw pointer to the slice's buffer.
Expand Down Expand Up @@ -1828,8 +1827,7 @@ impl<T: ?Sized> hash::Hash for NonNull<T> {
impl<T: ?Sized> From<Unique<T>> for NonNull<T> {
#[inline]
fn from(unique: Unique<T>) -> Self {
// SAFETY: A Unique pointer cannot be null.
unsafe { NonNull { pointer: unique.as_ptr() } }
unique.as_non_null_ptr()
}
}

Expand Down
7 changes: 7 additions & 0 deletions library/core/src/ptr/unique.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,13 @@ impl<T: ?Sized> Unique<T> {
self.pointer.as_ptr()
}

/// Acquires the underlying `*mut` pointer.
#[must_use = "`self` will be dropped if the result is not used"]
#[inline]
pub const fn as_non_null_ptr(self) -> NonNull<T> {
self.pointer
}

/// Dereferences the content.
///
/// The resulting lifetime is bound to self so this behaves "as if"
Expand Down

0 comments on commit dbf817b

Please sign in to comment.