Use ptr::metadata in <[T]>::len implementation

This avoids duplication of ptr::metadata code.
This commit is contained in:
Konrad Borowski 2022-08-21 15:05:58 +00:00
parent 4b695f7c4e
commit 155b4c28c1
3 changed files with 9 additions and 17 deletions

View File

@ -135,16 +135,16 @@ pub const fn from_raw_parts_mut<T: ?Sized>(
} }
#[repr(C)] #[repr(C)]
pub(crate) union PtrRepr<T: ?Sized> { union PtrRepr<T: ?Sized> {
pub(crate) const_ptr: *const T, const_ptr: *const T,
pub(crate) mut_ptr: *mut T, mut_ptr: *mut T,
pub(crate) components: PtrComponents<T>, components: PtrComponents<T>,
} }
#[repr(C)] #[repr(C)]
pub(crate) struct PtrComponents<T: ?Sized> { struct PtrComponents<T: ?Sized> {
pub(crate) data_address: *const (), data_address: *const (),
pub(crate) metadata: <T as Pointee>::Metadata, metadata: <T as Pointee>::Metadata,
} }
// Manual impl needed to avoid `T: Copy` bound. // Manual impl needed to avoid `T: Copy` bound.

View File

@ -390,7 +390,6 @@ pub use crate::intrinsics::copy;
pub use crate::intrinsics::write_bytes; pub use crate::intrinsics::write_bytes;
mod metadata; mod metadata;
pub(crate) use metadata::PtrRepr;
#[unstable(feature = "ptr_metadata", issue = "81513")] #[unstable(feature = "ptr_metadata", issue = "81513")]
pub use metadata::{from_raw_parts, from_raw_parts_mut, metadata, DynMetadata, Pointee, Thin}; pub use metadata::{from_raw_parts, from_raw_parts_mut, metadata, DynMetadata, Pointee, Thin};

View File

@ -123,18 +123,11 @@ impl<T> [T] {
#[lang = "slice_len_fn"] #[lang = "slice_len_fn"]
#[stable(feature = "rust1", since = "1.0.0")] #[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_slice_len", since = "1.39.0")] #[rustc_const_stable(feature = "const_slice_len", since = "1.39.0")]
#[rustc_allow_const_fn_unstable(ptr_metadata)]
#[inline] #[inline]
#[must_use] #[must_use]
// SAFETY: const sound because we transmute out the length field as a usize (which it must be)
pub const fn len(&self) -> usize { pub const fn len(&self) -> usize {
// FIXME: Replace with `crate::ptr::metadata(self)` when that is const-stable. ptr::metadata(self)
// As of this writing this causes a "Const-stable functions can only call other
// const-stable functions" error.
// 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.
unsafe { crate::ptr::PtrRepr { const_ptr: self }.components.metadata }
} }
/// Returns `true` if the slice has a length of 0. /// Returns `true` if the slice has a length of 0.