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.
This commit is contained in:
Matthias Schiffer 2020-04-13 20:58:23 +02:00
parent 43612e21a6
commit 2a29f8f89d
No known key found for this signature in database
GPG Key ID: 16EF3F64CB201D9C
2 changed files with 50 additions and 2 deletions

View File

@ -708,7 +708,31 @@ impl<T: ?Sized> *const T {
#[cfg(not(bootstrap))]
#[lang = "const_slice_ptr"]
impl<T> *const [T] {}
impl<T> *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")]

View File

@ -896,7 +896,31 @@ impl<T: ?Sized> *mut T {
#[cfg(not(bootstrap))]
#[lang = "mut_slice_ptr"]
impl<T> *mut [T] {}
impl<T> *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")]