about summary refs log tree commit diff
path: root/src/libcore/ptr/const_ptr.rs
diff options
context:
space:
mode:
authorMatthias Schiffer <mschiffer@universe-factory.net>2020-04-13 20:58:23 +0200
committerMatthias Schiffer <mschiffer@universe-factory.net>2020-04-14 18:49:29 +0200
commit2a29f8f89deb34356e767e3c0fb9fdd6d4fdbc27 (patch)
tree60c5525398496d355baf0b88480b2ae9070f6e60 /src/libcore/ptr/const_ptr.rs
parent43612e21a61bf6cd4bf741ffce64d7dd3b8ee19f (diff)
downloadrust-2a29f8f89deb34356e767e3c0fb9fdd6d4fdbc27.tar.gz
rust-2a29f8f89deb34356e767e3c0fb9fdd6d4fdbc27.zip
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.
Diffstat (limited to 'src/libcore/ptr/const_ptr.rs')
-rw-r--r--src/libcore/ptr/const_ptr.rs26
1 files changed, 25 insertions, 1 deletions
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<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")]