1
#[cfg(not(feature = "ferrocene_certified"))]
2
use crate::cmp::Ordering;
3
#[cfg(feature = "ferrocene_certified")]
4
use crate::marker::PointeeSized;
5
#[cfg(not(feature = "ferrocene_certified"))]
6
use crate::marker::{PointeeSized, Unsize};
7
#[cfg(not(feature = "ferrocene_certified"))]
8
use crate::mem::{MaybeUninit, SizedTypeProperties};
9
#[cfg(not(feature = "ferrocene_certified"))]
10
use crate::num::NonZero;
11
#[cfg(not(feature = "ferrocene_certified"))]
12
use crate::ops::{CoerceUnsized, DispatchFromDyn};
13
#[cfg(not(feature = "ferrocene_certified"))]
14
use crate::pin::PinCoerceUnsized;
15
#[cfg(not(feature = "ferrocene_certified"))]
16
use crate::ptr::Unique;
17
#[cfg(not(feature = "ferrocene_certified"))]
18
use crate::slice::{self, SliceIndex};
19
#[cfg(not(feature = "ferrocene_certified"))]
20
use crate::ub_checks::assert_unsafe_precondition;
21
#[cfg(not(feature = "ferrocene_certified"))]
22
use crate::{fmt, hash, intrinsics, mem, ptr};
23

            
24
/// `*mut T` but non-zero and [covariant].
25
///
26
/// This is often the correct thing to use when building data structures using
27
/// raw pointers, but is ultimately more dangerous to use because of its additional
28
/// properties. If you're not sure if you should use `NonNull<T>`, just use `*mut T`!
29
///
30
/// Unlike `*mut T`, the pointer must always be non-null, even if the pointer
31
/// is never dereferenced. This is so that enums may use this forbidden value
32
/// as a discriminant -- `Option<NonNull<T>>` has the same size as `*mut T`.
33
/// However the pointer may still dangle if it isn't dereferenced.
34
///
35
/// Unlike `*mut T`, `NonNull<T>` is covariant over `T`. This is usually the correct
36
/// choice for most data structures and safe abstractions, such as `Box`, `Rc`, `Arc`, `Vec`,
37
/// and `LinkedList`.
38
///
39
/// In rare cases, if your type exposes a way to mutate the value of `T` through a `NonNull<T>`,
40
/// and you need to prevent unsoundness from variance (for example, if `T` could be a reference
41
/// with a shorter lifetime), you should add a field to make your type invariant, such as
42
/// `PhantomData<Cell<T>>` or `PhantomData<&'a mut T>`.
43
///
44
/// Example of a type that must be invariant:
45
/// ```rust
46
/// use std::cell::Cell;
47
/// use std::marker::PhantomData;
48
/// struct Invariant<T> {
49
///     ptr: std::ptr::NonNull<T>,
50
///     _invariant: PhantomData<Cell<T>>,
51
/// }
52
/// ```
53
///
54
/// Notice that `NonNull<T>` has a `From` instance for `&T`. However, this does
55
/// not change the fact that mutating through a (pointer derived from a) shared
56
/// reference is undefined behavior unless the mutation happens inside an
57
/// [`UnsafeCell<T>`]. The same goes for creating a mutable reference from a shared
58
/// reference. When using this `From` instance without an `UnsafeCell<T>`,
59
/// it is your responsibility to ensure that `as_mut` is never called, and `as_ptr`
60
/// is never used for mutation.
61
///
62
/// # Representation
63
///
64
/// Thanks to the [null pointer optimization],
65
/// `NonNull<T>` and `Option<NonNull<T>>`
66
/// are guaranteed to have the same size and alignment:
67
///
68
/// ```
69
/// use std::ptr::NonNull;
70
///
71
/// assert_eq!(size_of::<NonNull<i16>>(), size_of::<Option<NonNull<i16>>>());
72
/// assert_eq!(align_of::<NonNull<i16>>(), align_of::<Option<NonNull<i16>>>());
73
///
74
/// assert_eq!(size_of::<NonNull<str>>(), size_of::<Option<NonNull<str>>>());
75
/// assert_eq!(align_of::<NonNull<str>>(), align_of::<Option<NonNull<str>>>());
76
/// ```
77
///
78
/// [covariant]: https://doc.rust-lang.org/reference/subtyping.html
79
/// [`PhantomData`]: crate::marker::PhantomData
80
/// [`UnsafeCell<T>`]: crate::cell::UnsafeCell
81
/// [null pointer optimization]: crate::option#representation
82
#[stable(feature = "nonnull", since = "1.25.0")]
83
#[repr(transparent)]
84
#[rustc_layout_scalar_valid_range_start(1)]
85
#[rustc_nonnull_optimization_guaranteed]
86
#[rustc_diagnostic_item = "NonNull"]
87
pub struct NonNull<T: PointeeSized> {
88
    // Remember to use `.as_ptr()` instead of `.pointer`, as field projecting to
89
    // this is banned by <https://github.com/rust-lang/compiler-team/issues/807>.
90
    pointer: *const T,
91
}
92

            
93
/// `NonNull` pointers are not `Send` because the data they reference may be aliased.
94
// N.B., this impl is unnecessary, but should provide better error messages.
95
#[stable(feature = "nonnull", since = "1.25.0")]
96
impl<T: PointeeSized> !Send for NonNull<T> {}
97

            
98
/// `NonNull` pointers are not `Sync` because the data they reference may be aliased.
99
// N.B., this impl is unnecessary, but should provide better error messages.
100
#[stable(feature = "nonnull", since = "1.25.0")]
101
impl<T: PointeeSized> !Sync for NonNull<T> {}
102

            
103
#[cfg(not(feature = "ferrocene_certified"))]
104
impl<T: Sized> NonNull<T> {
105
    /// Creates a pointer with the given address and no [provenance][crate::ptr#provenance].
106
    ///
107
    /// For more details, see the equivalent method on a raw pointer, [`ptr::without_provenance_mut`].
108
    ///
109
    /// This is a [Strict Provenance][crate::ptr#strict-provenance] API.
110
    #[stable(feature = "nonnull_provenance", since = "1.89.0")]
111
    #[rustc_const_stable(feature = "nonnull_provenance", since = "1.89.0")]
112
    #[must_use]
113
    #[inline]
114
19265
    pub const fn without_provenance(addr: NonZero<usize>) -> Self {
115
19265
        let pointer = crate::ptr::without_provenance(addr.get());
116
        // SAFETY: we know `addr` is non-zero.
117
19265
        unsafe { NonNull { pointer } }
118
19265
    }
119

            
120
    /// Creates a new `NonNull` that is dangling, but well-aligned.
121
    ///
122
    /// This is useful for initializing types which lazily allocate, like
123
    /// `Vec::new` does.
124
    ///
125
    /// Note that the address of the returned pointer may potentially
126
    /// be that of a valid pointer, which means this must not be used
127
    /// as a "not yet initialized" sentinel value.
128
    /// Types that lazily allocate must track initialization by some other means.
129
    ///
130
    /// # Examples
131
    ///
132
    /// ```
133
    /// use std::ptr::NonNull;
134
    ///
135
    /// let ptr = NonNull::<u32>::dangling();
136
    /// // Important: don't try to access the value of `ptr` without
137
    /// // initializing it first! The pointer is not null but isn't valid either!
138
    /// ```
139
    #[stable(feature = "nonnull", since = "1.25.0")]
140
    #[rustc_const_stable(feature = "const_nonnull_dangling", since = "1.36.0")]
141
    #[must_use]
142
    #[inline]
143
    pub const fn dangling() -> Self {
144
        let align = crate::ptr::Alignment::of::<T>();
145
        NonNull::without_provenance(align.as_nonzero())
146
    }
147

            
148
    /// Converts an address back to a mutable pointer, picking up some previously 'exposed'
149
    /// [provenance][crate::ptr#provenance].
150
    ///
151
    /// For more details, see the equivalent method on a raw pointer, [`ptr::with_exposed_provenance_mut`].
152
    ///
153
    /// This is an [Exposed Provenance][crate::ptr#exposed-provenance] API.
154
    #[stable(feature = "nonnull_provenance", since = "1.89.0")]
155
    #[inline]
156
    pub fn with_exposed_provenance(addr: NonZero<usize>) -> Self {
157
        // SAFETY: we know `addr` is non-zero.
158
        unsafe {
159
            let ptr = crate::ptr::with_exposed_provenance_mut(addr.get());
160
            NonNull::new_unchecked(ptr)
161
        }
162
    }
163

            
164
    /// Returns a shared references to the value. In contrast to [`as_ref`], this does not require
165
    /// that the value has to be initialized.
166
    ///
167
    /// For the mutable counterpart see [`as_uninit_mut`].
168
    ///
169
    /// [`as_ref`]: NonNull::as_ref
170
    /// [`as_uninit_mut`]: NonNull::as_uninit_mut
171
    ///
172
    /// # Safety
173
    ///
174
    /// When calling this method, you have to ensure that
175
    /// the pointer is [convertible to a reference](crate::ptr#pointer-to-reference-conversion).
176
    /// Note that because the created reference is to `MaybeUninit<T>`, the
177
    /// source pointer can point to uninitialized memory.
178
    #[inline]
179
    #[must_use]
180
    #[unstable(feature = "ptr_as_uninit", issue = "75402")]
181
    pub const unsafe fn as_uninit_ref<'a>(self) -> &'a MaybeUninit<T> {
182
        // SAFETY: the caller must guarantee that `self` meets all the
183
        // requirements for a reference.
184
        unsafe { &*self.cast().as_ptr() }
185
    }
186

            
187
    /// Returns a unique references to the value. In contrast to [`as_mut`], this does not require
188
    /// that the value has to be initialized.
189
    ///
190
    /// For the shared counterpart see [`as_uninit_ref`].
191
    ///
192
    /// [`as_mut`]: NonNull::as_mut
193
    /// [`as_uninit_ref`]: NonNull::as_uninit_ref
194
    ///
195
    /// # Safety
196
    ///
197
    /// When calling this method, you have to ensure that
198
    /// the pointer is [convertible to a reference](crate::ptr#pointer-to-reference-conversion).
199
    /// Note that because the created reference is to `MaybeUninit<T>`, the
200
    /// source pointer can point to uninitialized memory.
201
    #[inline]
202
    #[must_use]
203
    #[unstable(feature = "ptr_as_uninit", issue = "75402")]
204
    pub const unsafe fn as_uninit_mut<'a>(self) -> &'a mut MaybeUninit<T> {
205
        // SAFETY: the caller must guarantee that `self` meets all the
206
        // requirements for a reference.
207
        unsafe { &mut *self.cast().as_ptr() }
208
    }
209

            
210
    /// Casts from a pointer-to-`T` to a pointer-to-`[T; N]`.
211
    #[inline]
212
    #[unstable(feature = "ptr_cast_array", issue = "144514")]
213
    pub const fn cast_array<const N: usize>(self) -> NonNull<[T; N]> {
214
        self.cast()
215
    }
216
}
217

            
218
#[cfg(not(feature = "ferrocene_certified"))]
219
impl<T: PointeeSized> NonNull<T> {
220
    /// Creates a new `NonNull`.
221
    ///
222
    /// # Safety
223
    ///
224
    /// `ptr` must be non-null.
225
    ///
226
    /// # Examples
227
    ///
228
    /// ```
229
    /// use std::ptr::NonNull;
230
    ///
231
    /// let mut x = 0u32;
232
    /// let ptr = unsafe { NonNull::new_unchecked(&mut x as *mut _) };
233
    /// ```
234
    ///
235
    /// *Incorrect* usage of this function:
236
    ///
237
    /// ```rust,no_run
238
    /// use std::ptr::NonNull;
239
    ///
240
    /// // NEVER DO THAT!!! This is undefined behavior. ⚠️
241
    /// let ptr = unsafe { NonNull::<u32>::new_unchecked(std::ptr::null_mut()) };
242
    /// ```
243
    #[stable(feature = "nonnull", since = "1.25.0")]
244
    #[rustc_const_stable(feature = "const_nonnull_new_unchecked", since = "1.25.0")]
245
    #[inline]
246
    #[track_caller]
247
49698
    pub const unsafe fn new_unchecked(ptr: *mut T) -> Self {
248
        // SAFETY: the caller must guarantee that `ptr` is non-null.
249
        unsafe {
250
49698
            assert_unsafe_precondition!(
251
                check_language_ub,
252
                "NonNull::new_unchecked requires that the pointer is non-null",
253
49698
                (ptr: *mut () = ptr as *mut ()) => !ptr.is_null()
254
            );
255
49698
            NonNull { pointer: ptr as _ }
256
        }
257
49698
    }
258

            
259
    /// Creates a new `NonNull` if `ptr` is non-null.
260
    ///
261
    /// # Panics during const evaluation
262
    ///
263
    /// This method will panic during const evaluation if the pointer cannot be
264
    /// determined to be null or not. See [`is_null`] for more information.
265
    ///
266
    /// [`is_null`]: ../primitive.pointer.html#method.is_null-1
267
    ///
268
    /// # Examples
269
    ///
270
    /// ```
271
    /// use std::ptr::NonNull;
272
    ///
273
    /// let mut x = 0u32;
274
    /// let ptr = NonNull::<u32>::new(&mut x as *mut _).expect("ptr is null!");
275
    ///
276
    /// if let Some(ptr) = NonNull::<u32>::new(std::ptr::null_mut()) {
277
    ///     unreachable!();
278
    /// }
279
    /// ```
280
    #[stable(feature = "nonnull", since = "1.25.0")]
281
    #[rustc_const_stable(feature = "const_nonnull_new", since = "1.85.0")]
282
    #[inline]
283
18437
    pub const fn new(ptr: *mut T) -> Option<Self> {
284
18437
        if !ptr.is_null() {
285
            // SAFETY: The pointer is already checked and is not null
286
18437
            Some(unsafe { Self::new_unchecked(ptr) })
287
        } else {
288
            None
289
        }
290
18437
    }
291

            
292
    /// Converts a reference to a `NonNull` pointer.
293
    #[stable(feature = "non_null_from_ref", since = "1.89.0")]
294
    #[rustc_const_stable(feature = "non_null_from_ref", since = "1.89.0")]
295
    #[inline]
296
65263
    pub const fn from_ref(r: &T) -> Self {
297
        // SAFETY: A reference cannot be null.
298
65263
        unsafe { NonNull { pointer: r as *const T } }
299
65263
    }
300

            
301
    /// Converts a mutable reference to a `NonNull` pointer.
302
    #[stable(feature = "non_null_from_ref", since = "1.89.0")]
303
    #[rustc_const_stable(feature = "non_null_from_ref", since = "1.89.0")]
304
    #[inline]
305
9701
    pub const fn from_mut(r: &mut T) -> Self {
306
        // SAFETY: A mutable reference cannot be null.
307
9701
        unsafe { NonNull { pointer: r as *mut T } }
308
9701
    }
309

            
310
    /// Performs the same functionality as [`std::ptr::from_raw_parts`], except that a
311
    /// `NonNull` pointer is returned, as opposed to a raw `*const` pointer.
312
    ///
313
    /// See the documentation of [`std::ptr::from_raw_parts`] for more details.
314
    ///
315
    /// [`std::ptr::from_raw_parts`]: crate::ptr::from_raw_parts
316
    #[unstable(feature = "ptr_metadata", issue = "81513")]
317
    #[inline]
318
    pub const fn from_raw_parts(
319
        data_pointer: NonNull<impl super::Thin>,
320
        metadata: <T as super::Pointee>::Metadata,
321
    ) -> NonNull<T> {
322
        // SAFETY: The result of `ptr::from::raw_parts_mut` is non-null because `data_pointer` is.
323
        unsafe {
324
            NonNull::new_unchecked(super::from_raw_parts_mut(data_pointer.as_ptr(), metadata))
325
        }
326
    }
327

            
328
    /// Decompose a (possibly wide) pointer into its data pointer and metadata components.
329
    ///
330
    /// The pointer can be later reconstructed with [`NonNull::from_raw_parts`].
331
    #[unstable(feature = "ptr_metadata", issue = "81513")]
332
    #[must_use = "this returns the result of the operation, \
333
                  without modifying the original"]
334
    #[inline]
335
    pub const fn to_raw_parts(self) -> (NonNull<()>, <T as super::Pointee>::Metadata) {
336
        (self.cast(), super::metadata(self.as_ptr()))
337
    }
338

            
339
    /// Gets the "address" portion of the pointer.
340
    ///
341
    /// For more details, see the equivalent method on a raw pointer, [`pointer::addr`].
342
    ///
343
    /// This is a [Strict Provenance][crate::ptr#strict-provenance] API.
344
    #[must_use]
345
    #[inline]
346
    #[stable(feature = "strict_provenance", since = "1.84.0")]
347
    pub fn addr(self) -> NonZero<usize> {
348
        // SAFETY: The pointer is guaranteed by the type to be non-null,
349
        // meaning that the address will be non-zero.
350
        unsafe { NonZero::new_unchecked(self.as_ptr().addr()) }
351
    }
352

            
353
    /// Exposes the ["provenance"][crate::ptr#provenance] part of the pointer for future use in
354
    /// [`with_exposed_provenance`][NonNull::with_exposed_provenance] and returns the "address" portion.
355
    ///
356
    /// For more details, see the equivalent method on a raw pointer, [`pointer::expose_provenance`].
357
    ///
358
    /// This is an [Exposed Provenance][crate::ptr#exposed-provenance] API.
359
    #[stable(feature = "nonnull_provenance", since = "1.89.0")]
360
    pub fn expose_provenance(self) -> NonZero<usize> {
361
        // SAFETY: The pointer is guaranteed by the type to be non-null,
362
        // meaning that the address will be non-zero.
363
        unsafe { NonZero::new_unchecked(self.as_ptr().expose_provenance()) }
364
    }
365

            
366
    /// Creates a new pointer with the given address and the [provenance][crate::ptr#provenance] of
367
    /// `self`.
368
    ///
369
    /// For more details, see the equivalent method on a raw pointer, [`pointer::with_addr`].
370
    ///
371
    /// This is a [Strict Provenance][crate::ptr#strict-provenance] API.
372
    #[must_use]
373
    #[inline]
374
    #[stable(feature = "strict_provenance", since = "1.84.0")]
375
    pub fn with_addr(self, addr: NonZero<usize>) -> Self {
376
        // SAFETY: The result of `ptr::from::with_addr` is non-null because `addr` is guaranteed to be non-zero.
377
        unsafe { NonNull::new_unchecked(self.as_ptr().with_addr(addr.get()) as *mut _) }
378
    }
379

            
380
    /// Creates a new pointer by mapping `self`'s address to a new one, preserving the
381
    /// [provenance][crate::ptr#provenance] of `self`.
382
    ///
383
    /// For more details, see the equivalent method on a raw pointer, [`pointer::map_addr`].
384
    ///
385
    /// This is a [Strict Provenance][crate::ptr#strict-provenance] API.
386
    #[must_use]
387
    #[inline]
388
    #[stable(feature = "strict_provenance", since = "1.84.0")]
389
    pub fn map_addr(self, f: impl FnOnce(NonZero<usize>) -> NonZero<usize>) -> Self {
390
        self.with_addr(f(self.addr()))
391
    }
392

            
393
    /// Acquires the underlying `*mut` pointer.
394
    ///
395
    /// # Examples
396
    ///
397
    /// ```
398
    /// use std::ptr::NonNull;
399
    ///
400
    /// let mut x = 0u32;
401
    /// let ptr = NonNull::new(&mut x).expect("ptr is null!");
402
    ///
403
    /// let x_value = unsafe { *ptr.as_ptr() };
404
    /// assert_eq!(x_value, 0);
405
    ///
406
    /// unsafe { *ptr.as_ptr() += 2; }
407
    /// let x_value = unsafe { *ptr.as_ptr() };
408
    /// assert_eq!(x_value, 2);
409
    /// ```
410
    #[stable(feature = "nonnull", since = "1.25.0")]
411
    #[rustc_const_stable(feature = "const_nonnull_as_ptr", since = "1.32.0")]
412
    #[rustc_never_returns_null_ptr]
413
    #[must_use]
414
    #[inline(always)]
415
14073169
    pub const fn as_ptr(self) -> *mut T {
416
        // This is a transmute for the same reasons as `NonZero::get`.
417

            
418
        // SAFETY: `NonNull` is `transparent` over a `*const T`, and `*const T`
419
        // and `*mut T` have the same layout, so transitively we can transmute
420
        // our `NonNull` to a `*mut T` directly.
421
14073169
        unsafe { mem::transmute::<Self, *mut T>(self) }
422
14073169
    }
423

            
424
    /// Returns a shared reference to the value. If the value may be uninitialized, [`as_uninit_ref`]
425
    /// must be used instead.
426
    ///
427
    /// For the mutable counterpart see [`as_mut`].
428
    ///
429
    /// [`as_uninit_ref`]: NonNull::as_uninit_ref
430
    /// [`as_mut`]: NonNull::as_mut
431
    ///
432
    /// # Safety
433
    ///
434
    /// When calling this method, you have to ensure that
435
    /// the pointer is [convertible to a reference](crate::ptr#pointer-to-reference-conversion).
436
    ///
437
    /// # Examples
438
    ///
439
    /// ```
440
    /// use std::ptr::NonNull;
441
    ///
442
    /// let mut x = 0u32;
443
    /// let ptr = NonNull::new(&mut x as *mut _).expect("ptr is null!");
444
    ///
445
    /// let ref_x = unsafe { ptr.as_ref() };
446
    /// println!("{ref_x}");
447
    /// ```
448
    ///
449
    /// [the module documentation]: crate::ptr#safety
450
    #[stable(feature = "nonnull", since = "1.25.0")]
451
    #[rustc_const_stable(feature = "const_nonnull_as_ref", since = "1.73.0")]
452
    #[must_use]
453
    #[inline(always)]
454
2568427
    pub const unsafe fn as_ref<'a>(&self) -> &'a T {
455
        // SAFETY: the caller must guarantee that `self` meets all the
456
        // requirements for a reference.
457
        // `cast_const` avoids a mutable raw pointer deref.
458
2568427
        unsafe { &*self.as_ptr().cast_const() }
459
2568427
    }
460

            
461
    /// Returns a unique reference to the value. If the value may be uninitialized, [`as_uninit_mut`]
462
    /// must be used instead.
463
    ///
464
    /// For the shared counterpart see [`as_ref`].
465
    ///
466
    /// [`as_uninit_mut`]: NonNull::as_uninit_mut
467
    /// [`as_ref`]: NonNull::as_ref
468
    ///
469
    /// # Safety
470
    ///
471
    /// When calling this method, you have to ensure that
472
    /// the pointer is [convertible to a reference](crate::ptr#pointer-to-reference-conversion).
473
    /// # Examples
474
    ///
475
    /// ```
476
    /// use std::ptr::NonNull;
477
    ///
478
    /// let mut x = 0u32;
479
    /// let mut ptr = NonNull::new(&mut x).expect("null pointer");
480
    ///
481
    /// let x_ref = unsafe { ptr.as_mut() };
482
    /// assert_eq!(*x_ref, 0);
483
    /// *x_ref += 2;
484
    /// assert_eq!(*x_ref, 2);
485
    /// ```
486
    ///
487
    /// [the module documentation]: crate::ptr#safety
488
    #[stable(feature = "nonnull", since = "1.25.0")]
489
    #[rustc_const_stable(feature = "const_ptr_as_ref", since = "1.83.0")]
490
    #[must_use]
491
    #[inline(always)]
492
89394
    pub const unsafe fn as_mut<'a>(&mut self) -> &'a mut T {
493
        // SAFETY: the caller must guarantee that `self` meets all the
494
        // requirements for a mutable reference.
495
89394
        unsafe { &mut *self.as_ptr() }
496
89394
    }
497

            
498
    /// Casts to a pointer of another type.
499
    ///
500
    /// # Examples
501
    ///
502
    /// ```
503
    /// use std::ptr::NonNull;
504
    ///
505
    /// let mut x = 0u32;
506
    /// let ptr = NonNull::new(&mut x as *mut _).expect("null pointer");
507
    ///
508
    /// let casted_ptr = ptr.cast::<i8>();
509
    /// let raw_ptr: *mut i8 = casted_ptr.as_ptr();
510
    /// ```
511
    #[stable(feature = "nonnull_cast", since = "1.27.0")]
512
    #[rustc_const_stable(feature = "const_nonnull_cast", since = "1.36.0")]
513
    #[must_use = "this returns the result of the operation, \
514
                  without modifying the original"]
515
    #[inline]
516
218583
    pub const fn cast<U>(self) -> NonNull<U> {
517
        // SAFETY: `self` is a `NonNull` pointer which is necessarily non-null
518
218583
        unsafe { NonNull { pointer: self.as_ptr() as *mut U } }
519
218583
    }
520

            
521
    /// Try to cast to a pointer of another type by checking alignment.
522
    ///
523
    /// If the pointer is properly aligned to the target type, it will be
524
    /// cast to the target type. Otherwise, `None` is returned.
525
    ///
526
    /// # Examples
527
    ///
528
    /// ```rust
529
    /// #![feature(pointer_try_cast_aligned)]
530
    /// use std::ptr::NonNull;
531
    ///
532
    /// let mut x = 0u64;
533
    ///
534
    /// let aligned = NonNull::from_mut(&mut x);
535
    /// let unaligned = unsafe { aligned.byte_add(1) };
536
    ///
537
    /// assert!(aligned.try_cast_aligned::<u32>().is_some());
538
    /// assert!(unaligned.try_cast_aligned::<u32>().is_none());
539
    /// ```
540
    #[unstable(feature = "pointer_try_cast_aligned", issue = "141221")]
541
    #[must_use = "this returns the result of the operation, \
542
                  without modifying the original"]
543
    #[inline]
544
    pub fn try_cast_aligned<U>(self) -> Option<NonNull<U>> {
545
        if self.is_aligned_to(align_of::<U>()) { Some(self.cast()) } else { None }
546
    }
547

            
548
    /// Adds an offset to a pointer.
549
    ///
550
    /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
551
    /// offset of `3 * size_of::<T>()` bytes.
552
    ///
553
    /// # Safety
554
    ///
555
    /// If any of the following conditions are violated, the result is Undefined Behavior:
556
    ///
557
    /// * The computed offset, `count * size_of::<T>()` bytes, must not overflow `isize`.
558
    ///
559
    /// * If the computed offset is non-zero, then `self` must be derived from a pointer to some
560
    ///   [allocation], and the entire memory range between `self` and the result must be in
561
    ///   bounds of that allocation. In particular, this range must not "wrap around" the edge
562
    ///   of the address space.
563
    ///
564
    /// Allocations can never be larger than `isize::MAX` bytes, so if the computed offset
565
    /// stays in bounds of the allocation, it is guaranteed to satisfy the first requirement.
566
    /// This implies, for instance, that `vec.as_ptr().add(vec.len())` (for `vec: Vec<T>`) is always
567
    /// safe.
568
    ///
569
    /// [allocation]: crate::ptr#allocation
570
    ///
571
    /// # Examples
572
    ///
573
    /// ```
574
    /// use std::ptr::NonNull;
575
    ///
576
    /// let mut s = [1, 2, 3];
577
    /// let ptr: NonNull<u32> = NonNull::new(s.as_mut_ptr()).unwrap();
578
    ///
579
    /// unsafe {
580
    ///     println!("{}", ptr.offset(1).read());
581
    ///     println!("{}", ptr.offset(2).read());
582
    /// }
583
    /// ```
584
    #[inline(always)]
585
    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
586
    #[must_use = "returns a new pointer rather than modifying its argument"]
587
    #[stable(feature = "non_null_convenience", since = "1.80.0")]
588
    #[rustc_const_stable(feature = "non_null_convenience", since = "1.80.0")]
589
5700
    pub const unsafe fn offset(self, count: isize) -> Self
590
5700
    where
591
5700
        T: Sized,
592
    {
593
        // SAFETY: the caller must uphold the safety contract for `offset`.
594
        // Additionally safety contract of `offset` guarantees that the resulting pointer is
595
        // pointing to an allocation, there can't be an allocation at null, thus it's safe to
596
        // construct `NonNull`.
597
5700
        unsafe { NonNull { pointer: intrinsics::offset(self.as_ptr(), count) } }
598
5700
    }
599

            
600
    /// Calculates the offset from a pointer in bytes.
601
    ///
602
    /// `count` is in units of **bytes**.
603
    ///
604
    /// This is purely a convenience for casting to a `u8` pointer and
605
    /// using [offset][pointer::offset] on it. See that method for documentation
606
    /// and safety requirements.
607
    ///
608
    /// For non-`Sized` pointees this operation changes only the data pointer,
609
    /// leaving the metadata untouched.
610
    #[must_use]
611
    #[inline(always)]
612
    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
613
    #[stable(feature = "non_null_convenience", since = "1.80.0")]
614
    #[rustc_const_stable(feature = "non_null_convenience", since = "1.80.0")]
615
    pub const unsafe fn byte_offset(self, count: isize) -> Self {
616
        // SAFETY: the caller must uphold the safety contract for `offset` and `byte_offset` has
617
        // the same safety contract.
618
        // Additionally safety contract of `offset` guarantees that the resulting pointer is
619
        // pointing to an allocation, there can't be an allocation at null, thus it's safe to
620
        // construct `NonNull`.
621
        unsafe { NonNull { pointer: self.as_ptr().byte_offset(count) } }
622
    }
623

            
624
    /// Adds an offset to a pointer (convenience for `.offset(count as isize)`).
625
    ///
626
    /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
627
    /// offset of `3 * size_of::<T>()` bytes.
628
    ///
629
    /// # Safety
630
    ///
631
    /// If any of the following conditions are violated, the result is Undefined Behavior:
632
    ///
633
    /// * The computed offset, `count * size_of::<T>()` bytes, must not overflow `isize`.
634
    ///
635
    /// * If the computed offset is non-zero, then `self` must be derived from a pointer to some
636
    ///   [allocation], and the entire memory range between `self` and the result must be in
637
    ///   bounds of that allocation. In particular, this range must not "wrap around" the edge
638
    ///   of the address space.
639
    ///
640
    /// Allocations can never be larger than `isize::MAX` bytes, so if the computed offset
641
    /// stays in bounds of the allocation, it is guaranteed to satisfy the first requirement.
642
    /// This implies, for instance, that `vec.as_ptr().add(vec.len())` (for `vec: Vec<T>`) is always
643
    /// safe.
644
    ///
645
    /// [allocation]: crate::ptr#allocation
646
    ///
647
    /// # Examples
648
    ///
649
    /// ```
650
    /// use std::ptr::NonNull;
651
    ///
652
    /// let s: &str = "123";
653
    /// let ptr: NonNull<u8> = NonNull::new(s.as_ptr().cast_mut()).unwrap();
654
    ///
655
    /// unsafe {
656
    ///     println!("{}", ptr.add(1).read() as char);
657
    ///     println!("{}", ptr.add(2).read() as char);
658
    /// }
659
    /// ```
660
    #[inline(always)]
661
    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
662
    #[must_use = "returns a new pointer rather than modifying its argument"]
663
    #[stable(feature = "non_null_convenience", since = "1.80.0")]
664
    #[rustc_const_stable(feature = "non_null_convenience", since = "1.80.0")]
665
3955138
    pub const unsafe fn add(self, count: usize) -> Self
666
3955138
    where
667
3955138
        T: Sized,
668
    {
669
        // SAFETY: the caller must uphold the safety contract for `offset`.
670
        // Additionally safety contract of `offset` guarantees that the resulting pointer is
671
        // pointing to an allocation, there can't be an allocation at null, thus it's safe to
672
        // construct `NonNull`.
673
3955138
        unsafe { NonNull { pointer: intrinsics::offset(self.as_ptr(), count) } }
674
3955138
    }
675

            
676
    /// Calculates the offset from a pointer in bytes (convenience for `.byte_offset(count as isize)`).
677
    ///
678
    /// `count` is in units of bytes.
679
    ///
680
    /// This is purely a convenience for casting to a `u8` pointer and
681
    /// using [`add`][NonNull::add] on it. See that method for documentation
682
    /// and safety requirements.
683
    ///
684
    /// For non-`Sized` pointees this operation changes only the data pointer,
685
    /// leaving the metadata untouched.
686
    #[must_use]
687
    #[inline(always)]
688
    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
689
    #[stable(feature = "non_null_convenience", since = "1.80.0")]
690
    #[rustc_const_stable(feature = "non_null_convenience", since = "1.80.0")]
691
    pub const unsafe fn byte_add(self, count: usize) -> Self {
692
        // SAFETY: the caller must uphold the safety contract for `add` and `byte_add` has the same
693
        // safety contract.
694
        // Additionally safety contract of `add` guarantees that the resulting pointer is pointing
695
        // to an allocation, there can't be an allocation at null, thus it's safe to construct
696
        // `NonNull`.
697
        unsafe { NonNull { pointer: self.as_ptr().byte_add(count) } }
698
    }
699

            
700
    /// Subtracts an offset from a pointer (convenience for
701
    /// `.offset((count as isize).wrapping_neg())`).
702
    ///
703
    /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
704
    /// offset of `3 * size_of::<T>()` bytes.
705
    ///
706
    /// # Safety
707
    ///
708
    /// If any of the following conditions are violated, the result is Undefined Behavior:
709
    ///
710
    /// * The computed offset, `count * size_of::<T>()` bytes, must not overflow `isize`.
711
    ///
712
    /// * If the computed offset is non-zero, then `self` must be derived from a pointer to some
713
    ///   [allocation], and the entire memory range between `self` and the result must be in
714
    ///   bounds of that allocation. In particular, this range must not "wrap around" the edge
715
    ///   of the address space.
716
    ///
717
    /// Allocations can never be larger than `isize::MAX` bytes, so if the computed offset
718
    /// stays in bounds of the allocation, it is guaranteed to satisfy the first requirement.
719
    /// This implies, for instance, that `vec.as_ptr().add(vec.len())` (for `vec: Vec<T>`) is always
720
    /// safe.
721
    ///
722
    /// [allocation]: crate::ptr#allocation
723
    ///
724
    /// # Examples
725
    ///
726
    /// ```
727
    /// use std::ptr::NonNull;
728
    ///
729
    /// let s: &str = "123";
730
    ///
731
    /// unsafe {
732
    ///     let end: NonNull<u8> = NonNull::new(s.as_ptr().cast_mut()).unwrap().add(3);
733
    ///     println!("{}", end.sub(1).read() as char);
734
    ///     println!("{}", end.sub(2).read() as char);
735
    /// }
736
    /// ```
737
    #[inline(always)]
738
    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
739
    #[must_use = "returns a new pointer rather than modifying its argument"]
740
    #[stable(feature = "non_null_convenience", since = "1.80.0")]
741
    #[rustc_const_stable(feature = "non_null_convenience", since = "1.80.0")]
742
5700
    pub const unsafe fn sub(self, count: usize) -> Self
743
5700
    where
744
5700
        T: Sized,
745
    {
746
5700
        if T::IS_ZST {
747
            // Pointer arithmetic does nothing when the pointee is a ZST.
748
            self
749
        } else {
750
            // SAFETY: the caller must uphold the safety contract for `offset`.
751
            // Because the pointee is *not* a ZST, that means that `count` is
752
            // at most `isize::MAX`, and thus the negation cannot overflow.
753
5700
            unsafe { self.offset((count as isize).unchecked_neg()) }
754
        }
755
5700
    }
756

            
757
    /// Calculates the offset from a pointer in bytes (convenience for
758
    /// `.byte_offset((count as isize).wrapping_neg())`).
759
    ///
760
    /// `count` is in units of bytes.
761
    ///
762
    /// This is purely a convenience for casting to a `u8` pointer and
763
    /// using [`sub`][NonNull::sub] on it. See that method for documentation
764
    /// and safety requirements.
765
    ///
766
    /// For non-`Sized` pointees this operation changes only the data pointer,
767
    /// leaving the metadata untouched.
768
    #[must_use]
769
    #[inline(always)]
770
    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
771
    #[stable(feature = "non_null_convenience", since = "1.80.0")]
772
    #[rustc_const_stable(feature = "non_null_convenience", since = "1.80.0")]
773
    pub const unsafe fn byte_sub(self, count: usize) -> Self {
774
        // SAFETY: the caller must uphold the safety contract for `sub` and `byte_sub` has the same
775
        // safety contract.
776
        // Additionally safety contract of `sub` guarantees that the resulting pointer is pointing
777
        // to an allocation, there can't be an allocation at null, thus it's safe to construct
778
        // `NonNull`.
779
        unsafe { NonNull { pointer: self.as_ptr().byte_sub(count) } }
780
    }
781

            
782
    /// Calculates the distance between two pointers within the same allocation. The returned value is in
783
    /// units of T: the distance in bytes divided by `size_of::<T>()`.
784
    ///
785
    /// This is equivalent to `(self as isize - origin as isize) / (size_of::<T>() as isize)`,
786
    /// except that it has a lot more opportunities for UB, in exchange for the compiler
787
    /// better understanding what you are doing.
788
    ///
789
    /// The primary motivation of this method is for computing the `len` of an array/slice
790
    /// of `T` that you are currently representing as a "start" and "end" pointer
791
    /// (and "end" is "one past the end" of the array).
792
    /// In that case, `end.offset_from(start)` gets you the length of the array.
793
    ///
794
    /// All of the following safety requirements are trivially satisfied for this usecase.
795
    ///
796
    /// [`offset`]: #method.offset
797
    ///
798
    /// # Safety
799
    ///
800
    /// If any of the following conditions are violated, the result is Undefined Behavior:
801
    ///
802
    /// * `self` and `origin` must either
803
    ///
804
    ///   * point to the same address, or
805
    ///   * both be *derived from* a pointer to the same [allocation], and the memory range between
806
    ///     the two pointers must be in bounds of that object. (See below for an example.)
807
    ///
808
    /// * The distance between the pointers, in bytes, must be an exact multiple
809
    ///   of the size of `T`.
810
    ///
811
    /// As a consequence, the absolute distance between the pointers, in bytes, computed on
812
    /// mathematical integers (without "wrapping around"), cannot overflow an `isize`. This is
813
    /// implied by the in-bounds requirement, and the fact that no allocation can be larger
814
    /// than `isize::MAX` bytes.
815
    ///
816
    /// The requirement for pointers to be derived from the same allocation is primarily
817
    /// needed for `const`-compatibility: the distance between pointers into *different* allocated
818
    /// objects is not known at compile-time. However, the requirement also exists at
819
    /// runtime and may be exploited by optimizations. If you wish to compute the difference between
820
    /// pointers that are not guaranteed to be from the same allocation, use `(self as isize -
821
    /// origin as isize) / size_of::<T>()`.
822
    // FIXME: recommend `addr()` instead of `as usize` once that is stable.
823
    ///
824
    /// [`add`]: #method.add
825
    /// [allocation]: crate::ptr#allocation
826
    ///
827
    /// # Panics
828
    ///
829
    /// This function panics if `T` is a Zero-Sized Type ("ZST").
830
    ///
831
    /// # Examples
832
    ///
833
    /// Basic usage:
834
    ///
835
    /// ```
836
    /// use std::ptr::NonNull;
837
    ///
838
    /// let a = [0; 5];
839
    /// let ptr1: NonNull<u32> = NonNull::from(&a[1]);
840
    /// let ptr2: NonNull<u32> = NonNull::from(&a[3]);
841
    /// unsafe {
842
    ///     assert_eq!(ptr2.offset_from(ptr1), 2);
843
    ///     assert_eq!(ptr1.offset_from(ptr2), -2);
844
    ///     assert_eq!(ptr1.offset(2), ptr2);
845
    ///     assert_eq!(ptr2.offset(-2), ptr1);
846
    /// }
847
    /// ```
848
    ///
849
    /// *Incorrect* usage:
850
    ///
851
    /// ```rust,no_run
852
    /// use std::ptr::NonNull;
853
    ///
854
    /// let ptr1 = NonNull::new(Box::into_raw(Box::new(0u8))).unwrap();
855
    /// let ptr2 = NonNull::new(Box::into_raw(Box::new(1u8))).unwrap();
856
    /// let diff = (ptr2.addr().get() as isize).wrapping_sub(ptr1.addr().get() as isize);
857
    /// // Make ptr2_other an "alias" of ptr2.add(1), but derived from ptr1.
858
    /// let diff_plus_1 = diff.wrapping_add(1);
859
    /// let ptr2_other = NonNull::new(ptr1.as_ptr().wrapping_byte_offset(diff_plus_1)).unwrap();
860
    /// assert_eq!(ptr2.addr(), ptr2_other.addr());
861
    /// // Since ptr2_other and ptr2 are derived from pointers to different objects,
862
    /// // computing their offset is undefined behavior, even though
863
    /// // they point to addresses that are in-bounds of the same object!
864
    ///
865
    /// let one = unsafe { ptr2_other.offset_from(ptr2) }; // Undefined Behavior! ⚠️
866
    /// ```
867
    #[inline]
868
    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
869
    #[stable(feature = "non_null_convenience", since = "1.80.0")]
870
    #[rustc_const_stable(feature = "non_null_convenience", since = "1.80.0")]
871
    pub const unsafe fn offset_from(self, origin: NonNull<T>) -> isize
872
    where
873
        T: Sized,
874
    {
875
        // SAFETY: the caller must uphold the safety contract for `offset_from`.
876
        unsafe { self.as_ptr().offset_from(origin.as_ptr()) }
877
    }
878

            
879
    /// Calculates the distance between two pointers within the same allocation. The returned value is in
880
    /// units of **bytes**.
881
    ///
882
    /// This is purely a convenience for casting to a `u8` pointer and
883
    /// using [`offset_from`][NonNull::offset_from] on it. See that method for
884
    /// documentation and safety requirements.
885
    ///
886
    /// For non-`Sized` pointees this operation considers only the data pointers,
887
    /// ignoring the metadata.
888
    #[inline(always)]
889
    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
890
    #[stable(feature = "non_null_convenience", since = "1.80.0")]
891
    #[rustc_const_stable(feature = "non_null_convenience", since = "1.80.0")]
892
    pub const unsafe fn byte_offset_from<U: ?Sized>(self, origin: NonNull<U>) -> isize {
893
        // SAFETY: the caller must uphold the safety contract for `byte_offset_from`.
894
        unsafe { self.as_ptr().byte_offset_from(origin.as_ptr()) }
895
    }
896

            
897
    // N.B. `wrapping_offset``, `wrapping_add`, etc are not implemented because they can wrap to null
898

            
899
    /// Calculates the distance between two pointers within the same allocation, *where it's known that
900
    /// `self` is equal to or greater than `origin`*. The returned value is in
901
    /// units of T: the distance in bytes is divided by `size_of::<T>()`.
902
    ///
903
    /// This computes the same value that [`offset_from`](#method.offset_from)
904
    /// would compute, but with the added precondition that the offset is
905
    /// guaranteed to be non-negative.  This method is equivalent to
906
    /// `usize::try_from(self.offset_from(origin)).unwrap_unchecked()`,
907
    /// but it provides slightly more information to the optimizer, which can
908
    /// sometimes allow it to optimize slightly better with some backends.
909
    ///
910
    /// This method can be though of as recovering the `count` that was passed
911
    /// to [`add`](#method.add) (or, with the parameters in the other order,
912
    /// to [`sub`](#method.sub)).  The following are all equivalent, assuming
913
    /// that their safety preconditions are met:
914
    /// ```rust
915
    /// # unsafe fn blah(ptr: std::ptr::NonNull<u32>, origin: std::ptr::NonNull<u32>, count: usize) -> bool { unsafe {
916
    /// ptr.offset_from_unsigned(origin) == count
917
    /// # &&
918
    /// origin.add(count) == ptr
919
    /// # &&
920
    /// ptr.sub(count) == origin
921
    /// # } }
922
    /// ```
923
    ///
924
    /// # Safety
925
    ///
926
    /// - The distance between the pointers must be non-negative (`self >= origin`)
927
    ///
928
    /// - *All* the safety conditions of [`offset_from`](#method.offset_from)
929
    ///   apply to this method as well; see it for the full details.
930
    ///
931
    /// Importantly, despite the return type of this method being able to represent
932
    /// a larger offset, it's still *not permitted* to pass pointers which differ
933
    /// by more than `isize::MAX` *bytes*.  As such, the result of this method will
934
    /// always be less than or equal to `isize::MAX as usize`.
935
    ///
936
    /// # Panics
937
    ///
938
    /// This function panics if `T` is a Zero-Sized Type ("ZST").
939
    ///
940
    /// # Examples
941
    ///
942
    /// ```
943
    /// use std::ptr::NonNull;
944
    ///
945
    /// let a = [0; 5];
946
    /// let ptr1: NonNull<u32> = NonNull::from(&a[1]);
947
    /// let ptr2: NonNull<u32> = NonNull::from(&a[3]);
948
    /// unsafe {
949
    ///     assert_eq!(ptr2.offset_from_unsigned(ptr1), 2);
950
    ///     assert_eq!(ptr1.add(2), ptr2);
951
    ///     assert_eq!(ptr2.sub(2), ptr1);
952
    ///     assert_eq!(ptr2.offset_from_unsigned(ptr2), 0);
953
    /// }
954
    ///
955
    /// // This would be incorrect, as the pointers are not correctly ordered:
956
    /// // ptr1.offset_from_unsigned(ptr2)
957
    /// ```
958
    #[inline]
959
    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
960
    #[stable(feature = "ptr_sub_ptr", since = "1.87.0")]
961
    #[rustc_const_stable(feature = "const_ptr_sub_ptr", since = "1.87.0")]
962
20078
    pub const unsafe fn offset_from_unsigned(self, subtracted: NonNull<T>) -> usize
963
20078
    where
964
20078
        T: Sized,
965
    {
966
        // SAFETY: the caller must uphold the safety contract for `offset_from_unsigned`.
967
20078
        unsafe { self.as_ptr().offset_from_unsigned(subtracted.as_ptr()) }
968
20078
    }
969

            
970
    /// Calculates the distance between two pointers within the same allocation, *where it's known that
971
    /// `self` is equal to or greater than `origin`*. The returned value is in
972
    /// units of **bytes**.
973
    ///
974
    /// This is purely a convenience for casting to a `u8` pointer and
975
    /// using [`offset_from_unsigned`][NonNull::offset_from_unsigned] on it.
976
    /// See that method for documentation and safety requirements.
977
    ///
978
    /// For non-`Sized` pointees this operation considers only the data pointers,
979
    /// ignoring the metadata.
980
    #[inline(always)]
981
    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
982
    #[stable(feature = "ptr_sub_ptr", since = "1.87.0")]
983
    #[rustc_const_stable(feature = "const_ptr_sub_ptr", since = "1.87.0")]
984
    pub const unsafe fn byte_offset_from_unsigned<U: ?Sized>(self, origin: NonNull<U>) -> usize {
985
        // SAFETY: the caller must uphold the safety contract for `byte_offset_from_unsigned`.
986
        unsafe { self.as_ptr().byte_offset_from_unsigned(origin.as_ptr()) }
987
    }
988

            
989
    /// Reads the value from `self` without moving it. This leaves the
990
    /// memory in `self` unchanged.
991
    ///
992
    /// See [`ptr::read`] for safety concerns and examples.
993
    ///
994
    /// [`ptr::read`]: crate::ptr::read()
995
    #[inline]
996
    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
997
    #[stable(feature = "non_null_convenience", since = "1.80.0")]
998
    #[rustc_const_stable(feature = "non_null_convenience", since = "1.80.0")]
999
6390
    pub const unsafe fn read(self) -> T
6390
    where
6390
        T: Sized,
    {
        // SAFETY: the caller must uphold the safety contract for `read`.
6390
        unsafe { ptr::read(self.as_ptr()) }
6390
    }
    /// Performs a volatile read of the value from `self` without moving it. This
    /// leaves the memory in `self` unchanged.
    ///
    /// Volatile operations are intended to act on I/O memory, and are guaranteed
    /// to not be elided or reordered by the compiler across other volatile
    /// operations.
    ///
    /// See [`ptr::read_volatile`] for safety concerns and examples.
    ///
    /// [`ptr::read_volatile`]: crate::ptr::read_volatile()
    #[inline]
    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
    #[stable(feature = "non_null_convenience", since = "1.80.0")]
    pub unsafe fn read_volatile(self) -> T
    where
        T: Sized,
    {
        // SAFETY: the caller must uphold the safety contract for `read_volatile`.
        unsafe { ptr::read_volatile(self.as_ptr()) }
    }
    /// Reads the value from `self` without moving it. This leaves the
    /// memory in `self` unchanged.
    ///
    /// Unlike `read`, the pointer may be unaligned.
    ///
    /// See [`ptr::read_unaligned`] for safety concerns and examples.
    ///
    /// [`ptr::read_unaligned`]: crate::ptr::read_unaligned()
    #[inline]
    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
    #[stable(feature = "non_null_convenience", since = "1.80.0")]
    #[rustc_const_stable(feature = "non_null_convenience", since = "1.80.0")]
    pub const unsafe fn read_unaligned(self) -> T
    where
        T: Sized,
    {
        // SAFETY: the caller must uphold the safety contract for `read_unaligned`.
        unsafe { ptr::read_unaligned(self.as_ptr()) }
    }
    /// Copies `count * size_of::<T>()` bytes from `self` to `dest`. The source
    /// and destination may overlap.
    ///
    /// NOTE: this has the *same* argument order as [`ptr::copy`].
    ///
    /// See [`ptr::copy`] for safety concerns and examples.
    ///
    /// [`ptr::copy`]: crate::ptr::copy()
    #[inline(always)]
    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
    #[stable(feature = "non_null_convenience", since = "1.80.0")]
    #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.83.0")]
    pub const unsafe fn copy_to(self, dest: NonNull<T>, count: usize)
    where
        T: Sized,
    {
        // SAFETY: the caller must uphold the safety contract for `copy`.
        unsafe { ptr::copy(self.as_ptr(), dest.as_ptr(), count) }
    }
    /// Copies `count * size_of::<T>()` bytes from `self` to `dest`. The source
    /// and destination may *not* overlap.
    ///
    /// NOTE: this has the *same* argument order as [`ptr::copy_nonoverlapping`].
    ///
    /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples.
    ///
    /// [`ptr::copy_nonoverlapping`]: crate::ptr::copy_nonoverlapping()
    #[inline(always)]
    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
    #[stable(feature = "non_null_convenience", since = "1.80.0")]
    #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.83.0")]
    pub const unsafe fn copy_to_nonoverlapping(self, dest: NonNull<T>, count: usize)
    where
        T: Sized,
    {
        // SAFETY: the caller must uphold the safety contract for `copy_nonoverlapping`.
        unsafe { ptr::copy_nonoverlapping(self.as_ptr(), dest.as_ptr(), count) }
    }
    /// Copies `count * size_of::<T>()` bytes from `src` to `self`. The source
    /// and destination may overlap.
    ///
    /// NOTE: this has the *opposite* argument order of [`ptr::copy`].
    ///
    /// See [`ptr::copy`] for safety concerns and examples.
    ///
    /// [`ptr::copy`]: crate::ptr::copy()
    #[inline(always)]
    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
    #[stable(feature = "non_null_convenience", since = "1.80.0")]
    #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.83.0")]
    pub const unsafe fn copy_from(self, src: NonNull<T>, count: usize)
    where
        T: Sized,
    {
        // SAFETY: the caller must uphold the safety contract for `copy`.
        unsafe { ptr::copy(src.as_ptr(), self.as_ptr(), count) }
    }
    /// Copies `count * size_of::<T>()` bytes from `src` to `self`. The source
    /// and destination may *not* overlap.
    ///
    /// NOTE: this has the *opposite* argument order of [`ptr::copy_nonoverlapping`].
    ///
    /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples.
    ///
    /// [`ptr::copy_nonoverlapping`]: crate::ptr::copy_nonoverlapping()
    #[inline(always)]
    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
    #[stable(feature = "non_null_convenience", since = "1.80.0")]
    #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.83.0")]
    pub const unsafe fn copy_from_nonoverlapping(self, src: NonNull<T>, count: usize)
    where
        T: Sized,
    {
        // SAFETY: the caller must uphold the safety contract for `copy_nonoverlapping`.
        unsafe { ptr::copy_nonoverlapping(src.as_ptr(), self.as_ptr(), count) }
    }
    /// Executes the destructor (if any) of the pointed-to value.
    ///
    /// See [`ptr::drop_in_place`] for safety concerns and examples.
    ///
    /// [`ptr::drop_in_place`]: crate::ptr::drop_in_place()
    #[inline(always)]
    #[stable(feature = "non_null_convenience", since = "1.80.0")]
    pub unsafe fn drop_in_place(self) {
        // SAFETY: the caller must uphold the safety contract for `drop_in_place`.
        unsafe { ptr::drop_in_place(self.as_ptr()) }
    }
    /// Overwrites a memory location with the given value without reading or
    /// dropping the old value.
    ///
    /// See [`ptr::write`] for safety concerns and examples.
    ///
    /// [`ptr::write`]: crate::ptr::write()
    #[inline(always)]
    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
    #[stable(feature = "non_null_convenience", since = "1.80.0")]
    #[rustc_const_stable(feature = "const_ptr_write", since = "1.83.0")]
    pub const unsafe fn write(self, val: T)
    where
        T: Sized,
    {
        // SAFETY: the caller must uphold the safety contract for `write`.
        unsafe { ptr::write(self.as_ptr(), val) }
    }
    /// Invokes memset on the specified pointer, setting `count * size_of::<T>()`
    /// bytes of memory starting at `self` to `val`.
    ///
    /// See [`ptr::write_bytes`] for safety concerns and examples.
    ///
    /// [`ptr::write_bytes`]: crate::ptr::write_bytes()
    #[inline(always)]
    #[doc(alias = "memset")]
    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
    #[stable(feature = "non_null_convenience", since = "1.80.0")]
    #[rustc_const_stable(feature = "const_ptr_write", since = "1.83.0")]
    pub const unsafe fn write_bytes(self, val: u8, count: usize)
    where
        T: Sized,
    {
        // SAFETY: the caller must uphold the safety contract for `write_bytes`.
        unsafe { ptr::write_bytes(self.as_ptr(), val, count) }
    }
    /// Performs a volatile write of a memory location with the given value without
    /// reading or dropping the old value.
    ///
    /// Volatile operations are intended to act on I/O memory, and are guaranteed
    /// to not be elided or reordered by the compiler across other volatile
    /// operations.
    ///
    /// See [`ptr::write_volatile`] for safety concerns and examples.
    ///
    /// [`ptr::write_volatile`]: crate::ptr::write_volatile()
    #[inline(always)]
    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
    #[stable(feature = "non_null_convenience", since = "1.80.0")]
    pub unsafe fn write_volatile(self, val: T)
    where
        T: Sized,
    {
        // SAFETY: the caller must uphold the safety contract for `write_volatile`.
        unsafe { ptr::write_volatile(self.as_ptr(), val) }
    }
    /// Overwrites a memory location with the given value without reading or
    /// dropping the old value.
    ///
    /// Unlike `write`, the pointer may be unaligned.
    ///
    /// See [`ptr::write_unaligned`] for safety concerns and examples.
    ///
    /// [`ptr::write_unaligned`]: crate::ptr::write_unaligned()
    #[inline(always)]
    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
    #[stable(feature = "non_null_convenience", since = "1.80.0")]
    #[rustc_const_stable(feature = "const_ptr_write", since = "1.83.0")]
    pub const unsafe fn write_unaligned(self, val: T)
    where
        T: Sized,
    {
        // SAFETY: the caller must uphold the safety contract for `write_unaligned`.
        unsafe { ptr::write_unaligned(self.as_ptr(), val) }
    }
    /// Replaces the value at `self` with `src`, returning the old
    /// value, without dropping either.
    ///
    /// See [`ptr::replace`] for safety concerns and examples.
    ///
    /// [`ptr::replace`]: crate::ptr::replace()
    #[inline(always)]
    #[stable(feature = "non_null_convenience", since = "1.80.0")]
    #[rustc_const_stable(feature = "const_inherent_ptr_replace", since = "1.88.0")]
    pub const unsafe fn replace(self, src: T) -> T
    where
        T: Sized,
    {
        // SAFETY: the caller must uphold the safety contract for `replace`.
        unsafe { ptr::replace(self.as_ptr(), src) }
    }
    /// Swaps the values at two mutable locations of the same type, without
    /// deinitializing either. They may overlap, unlike `mem::swap` which is
    /// otherwise equivalent.
    ///
    /// See [`ptr::swap`] for safety concerns and examples.
    ///
    /// [`ptr::swap`]: crate::ptr::swap()
    #[inline(always)]
    #[stable(feature = "non_null_convenience", since = "1.80.0")]
    #[rustc_const_stable(feature = "const_swap", since = "1.85.0")]
    pub const unsafe fn swap(self, with: NonNull<T>)
    where
        T: Sized,
    {
        // SAFETY: the caller must uphold the safety contract for `swap`.
        unsafe { ptr::swap(self.as_ptr(), with.as_ptr()) }
    }
    /// Computes the offset that needs to be applied to the pointer in order to make it aligned to
    /// `align`.
    ///
    /// If it is not possible to align the pointer, the implementation returns
    /// `usize::MAX`.
    ///
    /// The offset is expressed in number of `T` elements, and not bytes.
    ///
    /// There are no guarantees whatsoever that offsetting the pointer will not overflow or go
    /// beyond the allocation that the pointer points into. It is up to the caller to ensure that
    /// the returned offset is correct in all terms other than alignment.
    ///
    /// When this is called during compile-time evaluation (which is unstable), the implementation
    /// may return `usize::MAX` in cases where that can never happen at runtime. This is because the
    /// actual alignment of pointers is not known yet during compile-time, so an offset with
    /// guaranteed alignment can sometimes not be computed. For example, a buffer declared as `[u8;
    /// N]` might be allocated at an odd or an even address, but at compile-time this is not yet
    /// known, so the execution has to be correct for either choice. It is therefore impossible to
    /// find an offset that is guaranteed to be 2-aligned. (This behavior is subject to change, as usual
    /// for unstable APIs.)
    ///
    /// # Panics
    ///
    /// The function panics if `align` is not a power-of-two.
    ///
    /// # Examples
    ///
    /// Accessing adjacent `u8` as `u16`
    ///
    /// ```
    /// use std::ptr::NonNull;
    ///
    /// # unsafe {
    /// let x = [5_u8, 6, 7, 8, 9];
    /// let ptr = NonNull::new(x.as_ptr() as *mut u8).unwrap();
    /// let offset = ptr.align_offset(align_of::<u16>());
    ///
    /// if offset < x.len() - 1 {
    ///     let u16_ptr = ptr.add(offset).cast::<u16>();
    ///     assert!(u16_ptr.read() == u16::from_ne_bytes([5, 6]) || u16_ptr.read() == u16::from_ne_bytes([6, 7]));
    /// } else {
    ///     // while the pointer can be aligned via `offset`, it would point
    ///     // outside the allocation
    /// }
    /// # }
    /// ```
    #[inline]
    #[must_use]
    #[stable(feature = "non_null_convenience", since = "1.80.0")]
    pub fn align_offset(self, align: usize) -> usize
    where
        T: Sized,
    {
        if !align.is_power_of_two() {
            panic!("align_offset: align is not a power-of-two");
        }
        {
            // SAFETY: `align` has been checked to be a power of 2 above.
            unsafe { ptr::align_offset(self.as_ptr(), align) }
        }
    }
    /// Returns whether the pointer is properly aligned for `T`.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::ptr::NonNull;
    ///
    /// // On some platforms, the alignment of i32 is less than 4.
    /// #[repr(align(4))]
    /// struct AlignedI32(i32);
    ///
    /// let data = AlignedI32(42);
    /// let ptr = NonNull::<AlignedI32>::from(&data);
    ///
    /// assert!(ptr.is_aligned());
    /// assert!(!NonNull::new(ptr.as_ptr().wrapping_byte_add(1)).unwrap().is_aligned());
    /// ```
    #[inline]
    #[must_use]
    #[stable(feature = "pointer_is_aligned", since = "1.79.0")]
    pub fn is_aligned(self) -> bool
    where
        T: Sized,
    {
        self.as_ptr().is_aligned()
    }
    /// Returns whether the pointer is aligned to `align`.
    ///
    /// For non-`Sized` pointees this operation considers only the data pointer,
    /// ignoring the metadata.
    ///
    /// # Panics
    ///
    /// The function panics if `align` is not a power-of-two (this includes 0).
    ///
    /// # Examples
    ///
    /// ```
    /// #![feature(pointer_is_aligned_to)]
    ///
    /// // On some platforms, the alignment of i32 is less than 4.
    /// #[repr(align(4))]
    /// struct AlignedI32(i32);
    ///
    /// let data = AlignedI32(42);
    /// let ptr = &data as *const AlignedI32;
    ///
    /// assert!(ptr.is_aligned_to(1));
    /// assert!(ptr.is_aligned_to(2));
    /// assert!(ptr.is_aligned_to(4));
    ///
    /// assert!(ptr.wrapping_byte_add(2).is_aligned_to(2));
    /// assert!(!ptr.wrapping_byte_add(2).is_aligned_to(4));
    ///
    /// assert_ne!(ptr.is_aligned_to(8), ptr.wrapping_add(1).is_aligned_to(8));
    /// ```
    #[inline]
    #[must_use]
    #[unstable(feature = "pointer_is_aligned_to", issue = "96284")]
    pub fn is_aligned_to(self, align: usize) -> bool {
        self.as_ptr().is_aligned_to(align)
    }
}
#[cfg(not(feature = "ferrocene_certified"))]
impl<T> NonNull<T> {
    /// Casts from a type to its maybe-uninitialized version.
    #[must_use]
    #[inline(always)]
    #[unstable(feature = "cast_maybe_uninit", issue = "145036")]
    pub const fn cast_uninit(self) -> NonNull<MaybeUninit<T>> {
        self.cast()
    }
}
#[cfg(not(feature = "ferrocene_certified"))]
impl<T> NonNull<MaybeUninit<T>> {
    /// Casts from a maybe-uninitialized type to its initialized version.
    ///
    /// This is always safe, since UB can only occur if the pointer is read
    /// before being initialized.
    #[must_use]
    #[inline(always)]
    #[unstable(feature = "cast_maybe_uninit", issue = "145036")]
    pub const fn cast_init(self) -> NonNull<T> {
        self.cast()
    }
}
#[cfg(not(feature = "ferrocene_certified"))]
impl<T> NonNull<[T]> {
    /// Creates a non-null raw slice from a thin pointer and a length.
    ///
    /// The `len` argument is the number of **elements**, not the number of bytes.
    ///
    /// This function is safe, but dereferencing the return value is unsafe.
    /// See the documentation of [`slice::from_raw_parts`] for slice safety requirements.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use std::ptr::NonNull;
    ///
    /// // create a slice pointer when starting out with a pointer to the first element
    /// let mut x = [5, 6, 7];
    /// let nonnull_pointer = NonNull::new(x.as_mut_ptr()).unwrap();
    /// let slice = NonNull::slice_from_raw_parts(nonnull_pointer, 3);
    /// assert_eq!(unsafe { slice.as_ref()[2] }, 7);
    /// ```
    ///
    /// (Note that this example artificially demonstrates a use of this method,
    /// but `let slice = NonNull::from(&x[..]);` would be a better way to write code like this.)
    #[stable(feature = "nonnull_slice_from_raw_parts", since = "1.70.0")]
    #[rustc_const_stable(feature = "const_slice_from_raw_parts_mut", since = "1.83.0")]
    #[must_use]
    #[inline]
18439
    pub const fn slice_from_raw_parts(data: NonNull<T>, len: usize) -> Self {
        // SAFETY: `data` is a `NonNull` pointer which is necessarily non-null
18439
        unsafe { Self::new_unchecked(super::slice_from_raw_parts_mut(data.as_ptr(), len)) }
18439
    }
    /// Returns the length of a non-null raw slice.
    ///
    /// The returned value is the number of **elements**, not the number of bytes.
    ///
    /// This function is safe, even when the non-null raw slice cannot be dereferenced to a slice
    /// because the pointer does not have a valid address.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use std::ptr::NonNull;
    ///
    /// let slice: NonNull<[i8]> = NonNull::slice_from_raw_parts(NonNull::dangling(), 3);
    /// assert_eq!(slice.len(), 3);
    /// ```
    #[stable(feature = "slice_ptr_len_nonnull", since = "1.63.0")]
    #[rustc_const_stable(feature = "const_slice_ptr_len_nonnull", since = "1.63.0")]
    #[must_use]
    #[inline]
    pub const fn len(self) -> usize {
        self.as_ptr().len()
    }
    /// Returns `true` if the non-null raw slice has a length of 0.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use std::ptr::NonNull;
    ///
    /// let slice: NonNull<[i8]> = NonNull::slice_from_raw_parts(NonNull::dangling(), 3);
    /// assert!(!slice.is_empty());
    /// ```
    #[stable(feature = "slice_ptr_is_empty_nonnull", since = "1.79.0")]
    #[rustc_const_stable(feature = "const_slice_ptr_is_empty_nonnull", since = "1.79.0")]
    #[must_use]
    #[inline]
    pub const fn is_empty(self) -> bool {
        self.len() == 0
    }
    /// Returns a non-null pointer to the slice's buffer.
    ///
    /// # Examples
    ///
    /// ```rust
    /// #![feature(slice_ptr_get)]
    /// use std::ptr::NonNull;
    ///
    /// let slice: NonNull<[i8]> = NonNull::slice_from_raw_parts(NonNull::dangling(), 3);
    /// assert_eq!(slice.as_non_null_ptr(), NonNull::<i8>::dangling());
    /// ```
    #[inline]
    #[must_use]
    #[unstable(feature = "slice_ptr_get", issue = "74265")]
13724
    pub const fn as_non_null_ptr(self) -> NonNull<T> {
13724
        self.cast()
13724
    }
    /// Returns a raw pointer to the slice's buffer.
    ///
    /// # Examples
    ///
    /// ```rust
    /// #![feature(slice_ptr_get)]
    /// use std::ptr::NonNull;
    ///
    /// let slice: NonNull<[i8]> = NonNull::slice_from_raw_parts(NonNull::dangling(), 3);
    /// assert_eq!(slice.as_mut_ptr(), NonNull::<i8>::dangling().as_ptr());
    /// ```
    #[inline]
    #[must_use]
    #[unstable(feature = "slice_ptr_get", issue = "74265")]
    #[rustc_never_returns_null_ptr]
13696
    pub const fn as_mut_ptr(self) -> *mut T {
13696
        self.as_non_null_ptr().as_ptr()
13696
    }
    /// Returns a shared reference to a slice of possibly uninitialized values. In contrast to
    /// [`as_ref`], this does not require that the value has to be initialized.
    ///
    /// For the mutable counterpart see [`as_uninit_slice_mut`].
    ///
    /// [`as_ref`]: NonNull::as_ref
    /// [`as_uninit_slice_mut`]: NonNull::as_uninit_slice_mut
    ///
    /// # Safety
    ///
    /// When calling this method, you have to ensure that all of the following is true:
    ///
    /// * The pointer must be [valid] for reads for `ptr.len() * size_of::<T>()` many bytes,
    ///   and it must be properly aligned. This means in particular:
    ///
    ///     * The entire memory range of this slice must be contained within a single allocation!
    ///       Slices can never span across multiple allocations.
    ///
    ///     * The pointer must be aligned even for zero-length slices. One
    ///       reason for this is that enum layout optimizations may rely on references
    ///       (including slices of any length) being aligned and non-null to distinguish
    ///       them from other data. You can obtain a pointer that is usable as `data`
    ///       for zero-length slices using [`NonNull::dangling()`].
    ///
    /// * The total size `ptr.len() * size_of::<T>()` of the slice must be no larger than `isize::MAX`.
    ///   See the safety documentation of [`pointer::offset`].
    ///
    /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
    ///   arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
    ///   In particular, while this reference exists, the memory the pointer points to must
    ///   not get mutated (except inside `UnsafeCell`).
    ///
    /// This applies even if the result of this method is unused!
    ///
    /// See also [`slice::from_raw_parts`].
    ///
    /// [valid]: crate::ptr#safety
    #[inline]
    #[must_use]
    #[unstable(feature = "ptr_as_uninit", issue = "75402")]
    pub const unsafe fn as_uninit_slice<'a>(self) -> &'a [MaybeUninit<T>] {
        // SAFETY: the caller must uphold the safety contract for `as_uninit_slice`.
        unsafe { slice::from_raw_parts(self.cast().as_ptr(), self.len()) }
    }
    /// Returns a unique reference to a slice of possibly uninitialized values. In contrast to
    /// [`as_mut`], this does not require that the value has to be initialized.
    ///
    /// For the shared counterpart see [`as_uninit_slice`].
    ///
    /// [`as_mut`]: NonNull::as_mut
    /// [`as_uninit_slice`]: NonNull::as_uninit_slice
    ///
    /// # Safety
    ///
    /// When calling this method, you have to ensure that all of the following is true:
    ///
    /// * The pointer must be [valid] for reads and writes for `ptr.len() * size_of::<T>()`
    ///   many bytes, and it must be properly aligned. This means in particular:
    ///
    ///     * The entire memory range of this slice must be contained within a single allocation!
    ///       Slices can never span across multiple allocations.
    ///
    ///     * The pointer must be aligned even for zero-length slices. One
    ///       reason for this is that enum layout optimizations may rely on references
    ///       (including slices of any length) being aligned and non-null to distinguish
    ///       them from other data. You can obtain a pointer that is usable as `data`
    ///       for zero-length slices using [`NonNull::dangling()`].
    ///
    /// * The total size `ptr.len() * size_of::<T>()` of the slice must be no larger than `isize::MAX`.
    ///   See the safety documentation of [`pointer::offset`].
    ///
    /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
    ///   arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
    ///   In particular, while this reference exists, the memory the pointer points to must
    ///   not get accessed (read or written) through any other pointer.
    ///
    /// This applies even if the result of this method is unused!
    ///
    /// See also [`slice::from_raw_parts_mut`].
    ///
    /// [valid]: crate::ptr#safety
    ///
    /// # Examples
    ///
    /// ```rust
    /// #![feature(allocator_api, ptr_as_uninit)]
    ///
    /// use std::alloc::{Allocator, Layout, Global};
    /// use std::mem::MaybeUninit;
    /// use std::ptr::NonNull;
    ///
    /// let memory: NonNull<[u8]> = Global.allocate(Layout::new::<[u8; 32]>())?;
    /// // This is safe as `memory` is valid for reads and writes for `memory.len()` many bytes.
    /// // Note that calling `memory.as_mut()` is not allowed here as the content may be uninitialized.
    /// # #[allow(unused_variables)]
    /// let slice: &mut [MaybeUninit<u8>] = unsafe { memory.as_uninit_slice_mut() };
    /// # // Prevent leaks for Miri.
    /// # unsafe { Global.deallocate(memory.cast(), Layout::new::<[u8; 32]>()); }
    /// # Ok::<_, std::alloc::AllocError>(())
    /// ```
    #[inline]
    #[must_use]
    #[unstable(feature = "ptr_as_uninit", issue = "75402")]
    pub const unsafe fn as_uninit_slice_mut<'a>(self) -> &'a mut [MaybeUninit<T>] {
        // SAFETY: the caller must uphold the safety contract for `as_uninit_slice_mut`.
        unsafe { slice::from_raw_parts_mut(self.cast().as_ptr(), self.len()) }
    }
    /// Returns a raw pointer to an element or subslice, without doing bounds
    /// checking.
    ///
    /// Calling this method with an out-of-bounds index or when `self` is not dereferenceable
    /// is *[undefined behavior]* even if the resulting pointer is not used.
    ///
    /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
    ///
    /// # Examples
    ///
    /// ```
    /// #![feature(slice_ptr_get)]
    /// use std::ptr::NonNull;
    ///
    /// let x = &mut [1, 2, 4];
    /// let x = NonNull::slice_from_raw_parts(NonNull::new(x.as_mut_ptr()).unwrap(), x.len());
    ///
    /// unsafe {
    ///     assert_eq!(x.get_unchecked_mut(1).as_ptr(), x.as_non_null_ptr().as_ptr().add(1));
    /// }
    /// ```
    #[unstable(feature = "slice_ptr_get", issue = "74265")]
    #[rustc_const_unstable(feature = "const_index", issue = "143775")]
    #[inline]
    pub const unsafe fn get_unchecked_mut<I>(self, index: I) -> NonNull<I::Output>
    where
        I: [const] SliceIndex<[T]>,
    {
        // SAFETY: the caller ensures that `self` is dereferenceable and `index` in-bounds.
        // As a consequence, the resulting pointer cannot be null.
        unsafe { NonNull::new_unchecked(self.as_ptr().get_unchecked_mut(index)) }
    }
}
#[stable(feature = "nonnull", since = "1.25.0")]
#[cfg(not(feature = "ferrocene_certified"))]
impl<T: PointeeSized> Clone for NonNull<T> {
    #[inline(always)]
    fn clone(&self) -> Self {
        *self
    }
}
#[stable(feature = "nonnull", since = "1.25.0")]
#[cfg(not(feature = "ferrocene_certified"))]
impl<T: PointeeSized> Copy for NonNull<T> {}
#[unstable(feature = "coerce_unsized", issue = "18598")]
#[cfg(not(feature = "ferrocene_certified"))]
impl<T: PointeeSized, U: PointeeSized> CoerceUnsized<NonNull<U>> for NonNull<T> where T: Unsize<U> {}
#[unstable(feature = "dispatch_from_dyn", issue = "none")]
#[cfg(not(feature = "ferrocene_certified"))]
impl<T: PointeeSized, U: PointeeSized> DispatchFromDyn<NonNull<U>> for NonNull<T> where T: Unsize<U> {}
#[stable(feature = "pin", since = "1.33.0")]
#[cfg(not(feature = "ferrocene_certified"))]
unsafe impl<T: PointeeSized> PinCoerceUnsized for NonNull<T> {}
#[stable(feature = "nonnull", since = "1.25.0")]
#[cfg(not(feature = "ferrocene_certified"))]
impl<T: PointeeSized> fmt::Debug for NonNull<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Pointer::fmt(&self.as_ptr(), f)
    }
}
#[stable(feature = "nonnull", since = "1.25.0")]
#[cfg(not(feature = "ferrocene_certified"))]
impl<T: PointeeSized> fmt::Pointer for NonNull<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Pointer::fmt(&self.as_ptr(), f)
    }
}
#[stable(feature = "nonnull", since = "1.25.0")]
#[cfg(not(feature = "ferrocene_certified"))]
impl<T: PointeeSized> Eq for NonNull<T> {}
#[stable(feature = "nonnull", since = "1.25.0")]
#[cfg(not(feature = "ferrocene_certified"))]
impl<T: PointeeSized> PartialEq for NonNull<T> {
    #[inline]
    #[allow(ambiguous_wide_pointer_comparisons)]
2618910
    fn eq(&self, other: &Self) -> bool {
2618910
        self.as_ptr() == other.as_ptr()
2618910
    }
}
#[stable(feature = "nonnull", since = "1.25.0")]
#[cfg(not(feature = "ferrocene_certified"))]
impl<T: PointeeSized> Ord for NonNull<T> {
    #[inline]
    #[allow(ambiguous_wide_pointer_comparisons)]
    fn cmp(&self, other: &Self) -> Ordering {
        self.as_ptr().cmp(&other.as_ptr())
    }
}
#[stable(feature = "nonnull", since = "1.25.0")]
#[cfg(not(feature = "ferrocene_certified"))]
impl<T: PointeeSized> PartialOrd for NonNull<T> {
    #[inline]
    #[allow(ambiguous_wide_pointer_comparisons)]
2
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
2
        self.as_ptr().partial_cmp(&other.as_ptr())
2
    }
}
#[stable(feature = "nonnull", since = "1.25.0")]
#[cfg(not(feature = "ferrocene_certified"))]
impl<T: PointeeSized> hash::Hash for NonNull<T> {
    #[inline]
    fn hash<H: hash::Hasher>(&self, state: &mut H) {
        self.as_ptr().hash(state)
    }
}
#[unstable(feature = "ptr_internals", issue = "none")]
#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
#[cfg(not(feature = "ferrocene_certified"))]
impl<T: PointeeSized> const From<Unique<T>> for NonNull<T> {
    #[inline]
7902
    fn from(unique: Unique<T>) -> Self {
7902
        unique.as_non_null_ptr()
7902
    }
}
#[stable(feature = "nonnull", since = "1.25.0")]
#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
#[cfg(not(feature = "ferrocene_certified"))]
impl<T: PointeeSized> const From<&mut T> for NonNull<T> {
    /// Converts a `&mut T` to a `NonNull<T>`.
    ///
    /// This conversion is safe and infallible since references cannot be null.
    #[inline]
9579
    fn from(r: &mut T) -> Self {
9579
        NonNull::from_mut(r)
9579
    }
}
#[stable(feature = "nonnull", since = "1.25.0")]
#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
#[cfg(not(feature = "ferrocene_certified"))]
impl<T: PointeeSized> const From<&T> for NonNull<T> {
    /// Converts a `&T` to a `NonNull<T>`.
    ///
    /// This conversion is safe and infallible since references cannot be null.
    #[inline]
1024
    fn from(r: &T) -> Self {
1024
        NonNull::from_ref(r)
1024
    }
}