Skip to content

Commit 2a29f8f

Browse files
committed
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.
1 parent 43612e2 commit 2a29f8f

File tree

2 files changed

+50
-2
lines changed

2 files changed

+50
-2
lines changed

src/libcore/ptr/const_ptr.rs

+25-1
Original file line numberDiff line numberDiff line change
@@ -708,7 +708,31 @@ impl<T: ?Sized> *const T {
708708

709709
#[cfg(not(bootstrap))]
710710
#[lang = "const_slice_ptr"]
711-
impl<T> *const [T] {}
711+
impl<T> *const [T] {
712+
/// Returns the length of a raw slice.
713+
///
714+
/// The returned value is the number of **elements**, not the number of bytes.
715+
///
716+
/// This function is safe, even when the raw slice cannot be cast to a slice
717+
/// reference because the pointer is null or unaligned.
718+
///
719+
/// # Examples
720+
///
721+
/// ```rust
722+
/// #![feature(slice_ptr_len)]
723+
///
724+
/// use std::ptr;
725+
///
726+
/// let slice: *const [i8] = ptr::slice_from_raw_parts(ptr::null(), 3);
727+
/// assert_eq!(slice.len(), 3);
728+
/// ```
729+
#[inline]
730+
#[unstable(feature = "slice_ptr_len", issue = "none")]
731+
#[rustc_const_unstable(feature = "const_slice_ptr_len", issue = "none")]
732+
pub const fn len(self) -> usize {
733+
unsafe { Repr { rust: self }.raw }.len
734+
}
735+
}
712736

713737
// Equality for pointers
714738
#[stable(feature = "rust1", since = "1.0.0")]

src/libcore/ptr/mut_ptr.rs

+25-1
Original file line numberDiff line numberDiff line change
@@ -896,7 +896,31 @@ impl<T: ?Sized> *mut T {
896896

897897
#[cfg(not(bootstrap))]
898898
#[lang = "mut_slice_ptr"]
899-
impl<T> *mut [T] {}
899+
impl<T> *mut [T] {
900+
/// Returns the length of a raw slice.
901+
///
902+
/// The returned value is the number of **elements**, not the number of bytes.
903+
///
904+
/// This function is safe, even when the raw slice cannot be cast to a slice
905+
/// reference because the pointer is null or unaligned.
906+
///
907+
/// # Examples
908+
///
909+
/// ```rust
910+
/// #![feature(slice_ptr_len)]
911+
///
912+
/// use std::ptr;
913+
///
914+
/// let slice: *mut [i8] = ptr::slice_from_raw_parts_mut(ptr::null_mut(), 3);
915+
/// assert_eq!(slice.len(), 3);
916+
/// ```
917+
#[inline]
918+
#[unstable(feature = "slice_ptr_len", issue = "none")]
919+
#[rustc_const_unstable(feature = "const_slice_ptr_len", issue = "none")]
920+
pub const fn len(self) -> usize {
921+
unsafe { Repr { rust_mut: self }.raw }.len
922+
}
923+
}
900924

901925
// Equality for pointers
902926
#[stable(feature = "rust1", since = "1.0.0")]

0 commit comments

Comments
 (0)