Skip to content

Commit

Permalink
ptr: introduce len() method on raw slices
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
neocturne committed Apr 14, 2020
1 parent 43612e2 commit 2a29f8f
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 2 deletions.
26 changes: 25 additions & 1 deletion src/libcore/ptr/const_ptr.rs
Expand Up @@ -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")]
Expand Down
26 changes: 25 additions & 1 deletion src/libcore/ptr/mut_ptr.rs
Expand Up @@ -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")]
Expand Down

0 comments on commit 2a29f8f

Please sign in to comment.