@@ -6,6 +6,7 @@ use crate::marker::Unsize;
6
6
use crate :: mem;
7
7
use crate :: ops:: { CoerceUnsized , DispatchFromDyn } ;
8
8
use crate :: ptr:: Unique ;
9
+ use crate :: slice:: SliceIndex ;
9
10
10
11
/// `*mut T` but non-zero and covariant.
11
12
///
@@ -192,7 +193,6 @@ impl<T> NonNull<[T]> {
192
193
///
193
194
/// ```rust
194
195
/// #![feature(slice_ptr_len, nonnull_slice_from_raw_parts)]
195
- ///
196
196
/// use std::ptr::NonNull;
197
197
///
198
198
/// let slice: NonNull<[i8]> = NonNull::slice_from_raw_parts(NonNull::dangling(), 3);
@@ -210,20 +210,51 @@ impl<T> NonNull<[T]> {
210
210
/// # Examples
211
211
///
212
212
/// ```rust
213
- /// #![feature(slice_ptr_ptr, nonnull_slice_from_raw_parts)]
214
- ///
213
+ /// #![feature(slice_ptr_get, nonnull_slice_from_raw_parts)]
215
214
/// use std::ptr::NonNull;
216
215
///
217
216
/// let slice: NonNull<[i8]> = NonNull::slice_from_raw_parts(NonNull::dangling(), 3);
218
217
/// assert_eq!(slice.as_non_null_ptr(), NonNull::new(1 as *mut i8).unwrap());
219
218
/// ```
220
219
#[ 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" ) ]
223
222
pub const fn as_non_null_ptr ( self ) -> NonNull < T > {
224
223
// SAFETY: We know `self` is non-null.
225
224
unsafe { NonNull :: new_unchecked ( self . as_ptr ( ) . as_mut_ptr ( ) ) }
226
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 = "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
+ }
227
258
}
228
259
229
260
#[ stable( feature = "nonnull" , since = "1.25.0" ) ]
0 commit comments