From 2a29f8f89deb34356e767e3c0fb9fdd6d4fdbc27 Mon Sep 17 00:00:00 2001 From: Matthias Schiffer Date: Mon, 13 Apr 2020 20:58:23 +0200 Subject: ptr: introduce len() method on raw slices It is already possible to extract the pointer part of a raw slice by a simple cast, but retrieving the length is not possible without relying on the representation of the raw slice when it is not valid to convert the raw slice into a slice reference (i.e. the pointer is null or unaligned). Introduce a len() method on raw slices to add this missing feature. --- src/libcore/ptr/const_ptr.rs | 26 +++++++++++++++++++++++++- src/libcore/ptr/mut_ptr.rs | 26 +++++++++++++++++++++++++- 2 files changed, 50 insertions(+), 2 deletions(-) (limited to 'src/libcore/ptr') diff --git a/src/libcore/ptr/const_ptr.rs b/src/libcore/ptr/const_ptr.rs index 00bd985114a..33c9e0b5315 100644 --- a/src/libcore/ptr/const_ptr.rs +++ b/src/libcore/ptr/const_ptr.rs @@ -708,7 +708,31 @@ impl *const T { #[cfg(not(bootstrap))] #[lang = "const_slice_ptr"] -impl *const [T] {} +impl *const [T] { + /// Returns the length of a raw slice. + /// + /// The returned value is the number of **elements**, not the number of bytes. + /// + /// This function is safe, even when the raw slice cannot be cast to a slice + /// reference because the pointer is null or unaligned. + /// + /// # Examples + /// + /// ```rust + /// #![feature(slice_ptr_len)] + /// + /// use std::ptr; + /// + /// let slice: *const [i8] = ptr::slice_from_raw_parts(ptr::null(), 3); + /// assert_eq!(slice.len(), 3); + /// ``` + #[inline] + #[unstable(feature = "slice_ptr_len", issue = "none")] + #[rustc_const_unstable(feature = "const_slice_ptr_len", issue = "none")] + pub const fn len(self) -> usize { + unsafe { Repr { rust: self }.raw }.len + } +} // Equality for pointers #[stable(feature = "rust1", since = "1.0.0")] diff --git a/src/libcore/ptr/mut_ptr.rs b/src/libcore/ptr/mut_ptr.rs index 00084456839..89475973675 100644 --- a/src/libcore/ptr/mut_ptr.rs +++ b/src/libcore/ptr/mut_ptr.rs @@ -896,7 +896,31 @@ impl *mut T { #[cfg(not(bootstrap))] #[lang = "mut_slice_ptr"] -impl *mut [T] {} +impl *mut [T] { + /// Returns the length of a raw slice. + /// + /// The returned value is the number of **elements**, not the number of bytes. + /// + /// This function is safe, even when the raw slice cannot be cast to a slice + /// reference because the pointer is null or unaligned. + /// + /// # Examples + /// + /// ```rust + /// #![feature(slice_ptr_len)] + /// + /// use std::ptr; + /// + /// let slice: *mut [i8] = ptr::slice_from_raw_parts_mut(ptr::null_mut(), 3); + /// assert_eq!(slice.len(), 3); + /// ``` + #[inline] + #[unstable(feature = "slice_ptr_len", issue = "none")] + #[rustc_const_unstable(feature = "const_slice_ptr_len", issue = "none")] + pub const fn len(self) -> usize { + unsafe { Repr { rust_mut: self }.raw }.len + } +} // Equality for pointers #[stable(feature = "rust1", since = "1.0.0")] -- cgit 1.4.1-3-g733a5