From dbf817bae1f25f0fa2fbb1e40ab74afc892d9a60 Mon Sep 17 00:00:00 2001 From: Ben Kimock Date: Thu, 8 Feb 2024 11:11:13 -0500 Subject: [PATCH] Add and use Unique::as_non_null_ptr --- library/core/src/ptr/non_null.rs | 6 ++---- library/core/src/ptr/unique.rs | 7 +++++++ 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/library/core/src/ptr/non_null.rs b/library/core/src/ptr/non_null.rs index 575af96fc982f..320cd5eb3b2ae 100644 --- a/library/core/src/ptr/non_null.rs +++ b/library/core/src/ptr/non_null.rs @@ -1591,8 +1591,7 @@ impl 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 { - // 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. @@ -1828,8 +1827,7 @@ impl hash::Hash for NonNull { impl From> for NonNull { #[inline] fn from(unique: Unique) -> Self { - // SAFETY: A Unique pointer cannot be null. - unsafe { NonNull { pointer: unique.as_ptr() } } + unique.as_non_null_ptr() } } diff --git a/library/core/src/ptr/unique.rs b/library/core/src/ptr/unique.rs index 2d878836b1627..b74d691e45427 100644 --- a/library/core/src/ptr/unique.rs +++ b/library/core/src/ptr/unique.rs @@ -106,6 +106,13 @@ impl Unique { 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 { + self.pointer + } + /// Dereferences the content. /// /// The resulting lifetime is bound to self so this behaves "as if"