@@ -6,6 +6,7 @@ use crate::marker::Unsize;
66use crate :: mem;
77use crate :: ops:: { CoerceUnsized , DispatchFromDyn } ;
88use crate :: ptr:: Unique ;
9+ use crate :: slice:: SliceIndex ;
910
1011/// `*mut T` but non-zero and covariant.
1112///
@@ -192,7 +193,6 @@ impl<T> NonNull<[T]> {
192193 ///
193194 /// ```rust
194195 /// #![feature(slice_ptr_len, nonnull_slice_from_raw_parts)]
195- ///
196196 /// use std::ptr::NonNull;
197197 ///
198198 /// let slice: NonNull<[i8]> = NonNull::slice_from_raw_parts(NonNull::dangling(), 3);
@@ -204,6 +204,57 @@ impl<T> NonNull<[T]> {
204204 pub const fn len ( self ) -> usize {
205205 self . as_ptr ( ) . len ( )
206206 }
207+
208+ /// Returns a non-null pointer to the slice's buffer.
209+ ///
210+ /// # Examples
211+ ///
212+ /// ```rust
213+ /// #![feature(slice_ptr_get, nonnull_slice_from_raw_parts)]
214+ /// use std::ptr::NonNull;
215+ ///
216+ /// let slice: NonNull<[i8]> = NonNull::slice_from_raw_parts(NonNull::dangling(), 3);
217+ /// assert_eq!(slice.as_non_null_ptr(), NonNull::new(1 as *mut i8).unwrap());
218+ /// ```
219+ #[ inline]
220+ #[ unstable( feature = "slice_ptr_get" , issue = "74265" ) ]
221+ #[ rustc_const_unstable( feature = "slice_ptr_get" , issue = "74265" ) ]
222+ pub const fn as_non_null_ptr ( self ) -> NonNull < T > {
223+ // SAFETY: We know `self` is non-null.
224+ unsafe { NonNull :: new_unchecked ( self . as_ptr ( ) . as_mut_ptr ( ) ) }
225+ }
226+
227+ /// Returns a raw pointer to an element or subslice, without doing bounds
228+ /// checking.
229+ ///
230+ /// Calling this method with an out-of-bounds index or when `self` is not dereferencable
231+ /// is *[undefined behavior]* even if the resulting pointer is not used.
232+ ///
233+ /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
234+ ///
235+ /// # Examples
236+ ///
237+ /// ```
238+ /// #![feature(slice_ptr_get, nonnull_slice_from_raw_parts)]
239+ /// use std::ptr::NonNull;
240+ ///
241+ /// let x = &mut [1, 2, 4];
242+ /// let x = NonNull::slice_from_raw_parts(NonNull::new(x.as_mut_ptr()).unwrap(), x.len());
243+ ///
244+ /// unsafe {
245+ /// assert_eq!(x.get_unchecked_mut(1).as_ptr(), x.as_non_null_ptr().as_ptr().add(1));
246+ /// }
247+ /// ```
248+ #[ unstable( feature = "slice_ptr_get" , issue = "74265" ) ]
249+ #[ inline]
250+ pub unsafe fn get_unchecked_mut < I > ( self , index : I ) -> NonNull < I :: Output >
251+ where
252+ I : SliceIndex < [ T ] > ,
253+ {
254+ // SAFETY: the caller ensures that `self` is dereferencable and `index` in-bounds.
255+ // As a consequence, the resulting pointer cannot be NULL.
256+ unsafe { NonNull :: new_unchecked ( self . as_ptr ( ) . get_unchecked_mut ( index) ) }
257+ }
207258}
208259
209260#[ stable( feature = "nonnull" , since = "1.25.0" ) ]
0 commit comments