@@ -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);
@@ -210,20 +210,51 @@ impl<T> NonNull<[T]> {
210210 /// # Examples
211211 ///
212212 /// ```rust
213- /// #![feature(slice_ptr_ptr, nonnull_slice_from_raw_parts)]
214- ///
213+ /// #![feature(slice_ptr_get, nonnull_slice_from_raw_parts)]
215214 /// use std::ptr::NonNull;
216215 ///
217216 /// let slice: NonNull<[i8]> = NonNull::slice_from_raw_parts(NonNull::dangling(), 3);
218217 /// assert_eq!(slice.as_non_null_ptr(), NonNull::new(1 as *mut i8).unwrap());
219218 /// ```
220219 #[ inline]
221- #[ unstable( feature = "slice_ptr_ptr " , issue = "none" ) ]
222- #[ rustc_const_unstable( feature = "const_slice_ptr_ptr " , issue = "none" ) ]
220+ #[ unstable( feature = "slice_ptr_get " , issue = "none" ) ]
221+ #[ rustc_const_unstable( feature = "slice_ptr_get " , issue = "none" ) ]
223222 pub const fn as_non_null_ptr ( self ) -> NonNull < T > {
224223 // SAFETY: We know `self` is non-null.
225224 unsafe { NonNull :: new_unchecked ( self . as_ptr ( ) . as_mut_ptr ( ) ) }
226225 }
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 = "none" ) ]
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+ }
227258}
228259
229260#[ stable( feature = "nonnull" , since = "1.25.0" ) ]
0 commit comments