From c478b5473d6623622d318d058477f5f09e2eeb52 Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Fri, 3 Jul 2020 11:58:05 +0200 Subject: [PATCH] add as_ptr method to raw slices --- src/libcore/ptr/const_ptr.rs | 21 +++++++++++++++++++++ src/libcore/ptr/mut_ptr.rs | 21 +++++++++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/src/libcore/ptr/const_ptr.rs b/src/libcore/ptr/const_ptr.rs index d1d7a7152382..f926befb4b32 100644 --- a/src/libcore/ptr/const_ptr.rs +++ b/src/libcore/ptr/const_ptr.rs @@ -826,6 +826,27 @@ impl *const [T] { // Only `std` can make this guarantee. unsafe { Repr { rust: self }.raw }.len } + + /// Returns a raw pointer to the slice's buffer. + /// + /// This is equivalent to casting `self` to `*const T`, but more type-safe. + /// + /// # Examples + /// + /// ```rust + /// #![feature(slice_ptr_ptr)] + /// + /// use std::ptr; + /// + /// let slice: *const [i8] = ptr::slice_from_raw_parts(ptr::null(), 3); + /// assert_eq!(slice.as_ptr(), 0 as *const i8); + /// ``` + #[inline] + #[unstable(feature = "slice_ptr_ptr", issue = "none")] + #[rustc_const_unstable(feature = "const_slice_ptr_ptr", issue = "none")] + pub const fn as_ptr(self) -> *const T { + self as *const T + } } // Equality for pointers diff --git a/src/libcore/ptr/mut_ptr.rs b/src/libcore/ptr/mut_ptr.rs index 7d4b6339b511..7fc4805c9211 100644 --- a/src/libcore/ptr/mut_ptr.rs +++ b/src/libcore/ptr/mut_ptr.rs @@ -1028,6 +1028,27 @@ impl *mut [T] { // Only `std` can make this guarantee. unsafe { Repr { rust_mut: self }.raw }.len } + + /// Returns a raw pointer to the slice's buffer. + /// + /// This is equivalent to casting `self` to `*mut T`, but more type-safe. + /// + /// # Examples + /// + /// ```rust + /// #![feature(slice_ptr_ptr)] + /// + /// use std::ptr; + /// + /// let slice: *mut [i8] = ptr::slice_from_raw_parts_mut(ptr::null_mut(), 3); + /// assert_eq!(slice.as_ptr(), 0 as *mut i8); + /// ``` + #[inline] + #[unstable(feature = "slice_ptr_ptr", issue = "none")] + #[rustc_const_unstable(feature = "const_slice_ptr_ptr", issue = "none")] + pub const fn as_ptr(self) -> *mut T { + self as *mut T + } } // Equality for pointers