Add to_raw_parts methods to *const, *mut, and NonNull

These are not named `into_` because they do not consume their receiver
since raw pointers are `Copy`.
This commit is contained in:
Simon Sapin 2021-01-18 16:56:53 +01:00
parent 937d580a25
commit c0e3a1b096
4 changed files with 35 additions and 1 deletions

View File

@ -48,6 +48,17 @@ impl<T: ?Sized> *const T {
self as _
}
/// Decompose a (possibly wide) pointer into is address and metadata components.
///
/// The pointer can be later reconstructed with [`from_raw_parts`].
#[cfg(not(bootstrap))]
#[unstable(feature = "ptr_metadata", issue = /* FIXME */ "none")]
#[rustc_const_unstable(feature = "ptr_metadata", issue = /* FIXME */ "none")]
#[inline]
pub const fn to_raw_parts(self) -> (*const (), <T as super::Pointee>::Metadata) {
(self.cast(), super::metadata(self))
}
/// Returns `None` if the pointer is null, or else returns a shared reference to
/// the value wrapped in `Some`. If the value may be uninitialized, [`as_uninit_ref`]
/// must be used instead.

View File

@ -28,8 +28,9 @@ pub trait Pointee {
pub trait Thin = Pointee<Metadata = ()>;
/// Extract the metadata component of a pointer.
#[rustc_const_unstable(feature = "ptr_metadata", issue = /* FIXME */ "none")]
#[inline]
pub fn metadata<T: ?Sized>(ptr: *const T) -> <T as Pointee>::Metadata {
pub const fn metadata<T: ?Sized>(ptr: *const T) -> <T as Pointee>::Metadata {
// SAFETY: Accessing the value from the `PtrRepr` union is safe since *const T
// and PtrComponents<T> have the same memory layouts. Only std can make this
// guarantee.

View File

@ -47,6 +47,17 @@ impl<T: ?Sized> *mut T {
self as _
}
/// Decompose a (possibly wide) pointer into is address and metadata components.
///
/// The pointer can be later reconstructed with [`from_raw_parts_mut`].
#[cfg(not(bootstrap))]
#[unstable(feature = "ptr_metadata", issue = /* FIXME */ "none")]
#[rustc_const_unstable(feature = "ptr_metadata", issue = /* FIXME */ "none")]
#[inline]
pub const fn to_raw_parts(self) -> (*mut (), <T as super::Pointee>::Metadata) {
(self.cast(), super::metadata(self))
}
/// Returns `None` if the pointer is null, or else returns a shared reference to
/// the value wrapped in `Some`. If the value may be uninitialized, [`as_uninit_ref`]
/// must be used instead.

View File

@ -193,6 +193,17 @@ impl<T: ?Sized> NonNull<T> {
}
}
/// Decompose a (possibly wide) pointer into is address and metadata components.
///
/// The pointer can be later reconstructed with [`NonNull::from_raw_parts`].
#[cfg(not(bootstrap))]
#[unstable(feature = "ptr_metadata", issue = /* FIXME */ "none")]
#[rustc_const_unstable(feature = "ptr_metadata", issue = /* FIXME */ "none")]
#[inline]
pub const fn to_raw_parts(self) -> (NonNull<()>, <T as super::Pointee>::Metadata) {
(self.cast(), super::metadata(self.as_ptr()))
}
/// Acquires the underlying `*mut` pointer.
#[stable(feature = "nonnull", since = "1.25.0")]
#[rustc_const_stable(feature = "const_nonnull_as_ptr", since = "1.32.0")]