Skip to main content

core/ptr/
non_null.rs

1use crate::clone::TrivialClone;
2use crate::cmp::Ordering;
3use crate::marker::{Destruct, PointeeSized, Unsize};
4use crate::mem::{MaybeUninit, SizedTypeProperties, transmute};
5use crate::num::NonZero;
6use crate::ops::{CoerceUnsized, DispatchFromDyn};
7use crate::slice::{self, SliceIndex};
8use crate::ub_checks::assert_unsafe_precondition;
9use crate::{fmt, hash, intrinsics, mem, ptr};
10
11/// `*mut T` but non-zero and [covariant].
12///
13/// This is often the correct thing to use when building data structures using
14/// raw pointers, but is ultimately more dangerous to use because of its additional
15/// properties. If you're not sure if you should use `NonNull<T>`, just use `*mut T`!
16///
17/// Unlike `*mut T`, the pointer must always be non-null, even if the pointer
18/// is never dereferenced. This is so that enums may use this forbidden value
19/// as a discriminant -- `Option<NonNull<T>>` has the same size as `*mut T`.
20/// However the pointer may still dangle if it isn't dereferenced.
21///
22/// Unlike `*mut T`, `NonNull<T>` is covariant over `T`. This is usually the correct
23/// choice for most data structures and safe abstractions, such as `Box`, `Rc`, `Arc`, `Vec`,
24/// and `LinkedList`.
25///
26/// In rare cases, if your type exposes a way to mutate the value of `T` through a `NonNull<T>`,
27/// and you need to prevent unsoundness from variance (for example, if `T` could be a reference
28/// with a shorter lifetime), you should add a field to make your type invariant, such as
29/// `PhantomData<Cell<T>>` or `PhantomData<&'a mut T>`.
30///
31/// Example of a type that must be invariant:
32/// ```rust
33/// use std::cell::Cell;
34/// use std::marker::PhantomData;
35/// struct Invariant<T> {
36///     ptr: std::ptr::NonNull<T>,
37///     _invariant: PhantomData<Cell<T>>,
38/// }
39/// ```
40///
41/// Notice that `NonNull<T>` has a `From` instance for `&T`. However, this does
42/// not change the fact that mutating through a (pointer derived from a) shared
43/// reference is undefined behavior unless the mutation happens inside an
44/// [`UnsafeCell<T>`]. The same goes for creating a mutable reference from a shared
45/// reference. When using this `From` instance without an `UnsafeCell<T>`,
46/// it is your responsibility to ensure that `as_mut` is never called, and `as_ptr`
47/// is never used for mutation.
48///
49/// # Layout
50///
51/// `NonNull<T>` is guaranteed to have the same layout and bit validity as `*mut T`
52/// with the exception that a null pointer is invalid.
53/// `Option<NonNull<T>>` is guaranteed to be ABI-compatible with `*mut T`, including in
54/// FFI.
55///
56/// Thanks to the [null pointer optimization],
57/// `NonNull<T>` and `Option<NonNull<T>>`
58/// are guaranteed to have the same size and alignment:
59///
60/// ```
61/// use std::ptr::NonNull;
62///
63/// assert_eq!(size_of::<NonNull<i16>>(), size_of::<Option<NonNull<i16>>>());
64/// assert_eq!(align_of::<NonNull<i16>>(), align_of::<Option<NonNull<i16>>>());
65///
66/// assert_eq!(size_of::<NonNull<str>>(), size_of::<Option<NonNull<str>>>());
67/// assert_eq!(align_of::<NonNull<str>>(), align_of::<Option<NonNull<str>>>());
68/// ```
69///
70/// [covariant]: https://doc.rust-lang.org/reference/subtyping.html
71/// [`PhantomData`]: crate::marker::PhantomData
72/// [`UnsafeCell<T>`]: crate::cell::UnsafeCell
73/// [null pointer optimization]: crate::option#representation
74#[stable(feature = "nonnull", since = "1.25.0")]
75#[repr(transparent)]
76#[rustc_nonnull_optimization_guaranteed]
77#[lang = "non_null"]
78pub struct NonNull<#[rustc_assert_variance(covariant)] T: PointeeSized> {
79    pointer: crate::pattern_type!(*const T is !null),
80}
81
82/// `NonNull` pointers are not `Send` because the data they reference may be aliased.
83// N.B., this impl is unnecessary, but should provide better error messages.
84#[stable(feature = "nonnull", since = "1.25.0")]
85impl<T: PointeeSized> !Send for NonNull<T> {}
86
87/// `NonNull` pointers are not `Sync` because the data they reference may be aliased.
88// N.B., this impl is unnecessary, but should provide better error messages.
89#[stable(feature = "nonnull", since = "1.25.0")]
90impl<T: PointeeSized> !Sync for NonNull<T> {}
91
92impl<T: Sized> NonNull<T> {
93    /// Creates a pointer with the given address and no [provenance][crate::ptr#provenance].
94    ///
95    /// For more details, see the equivalent method on a raw pointer, [`ptr::without_provenance_mut`].
96    ///
97    /// This is a [Strict Provenance][crate::ptr#strict-provenance] API.
98    #[stable(feature = "nonnull_provenance", since = "1.89.0")]
99    #[rustc_const_stable(feature = "nonnull_provenance", since = "1.89.0")]
100    #[must_use]
101    #[inline]
102    pub const fn without_provenance(addr: NonZero<usize>) -> Self {
103        // SAFETY: we know `addr` is non-zero and all nonzero integers are valid raw pointers.
104        unsafe { transmute(addr) }
105    }
106
107    /// Creates a new `NonNull` that is dangling, but well-aligned.
108    ///
109    /// This is useful for initializing types which lazily allocate, like
110    /// `Vec::new` does.
111    ///
112    /// Note that the address of the returned pointer may potentially
113    /// be that of a valid pointer, which means this must not be used
114    /// as a "not yet initialized" sentinel value.
115    /// Types that lazily allocate must track initialization by some other means.
116    ///
117    /// # Examples
118    ///
119    /// ```
120    /// use std::ptr::NonNull;
121    ///
122    /// let ptr = NonNull::<u32>::dangling();
123    /// // Important: don't try to access the value of `ptr` without
124    /// // initializing it first! The pointer is not null but isn't valid either!
125    /// ```
126    #[stable(feature = "nonnull", since = "1.25.0")]
127    #[rustc_const_stable(feature = "const_nonnull_dangling", since = "1.36.0")]
128    #[must_use]
129    #[inline]
130    pub const fn dangling() -> Self {
131        let align = crate::mem::Alignment::of::<T>();
132        NonNull::without_provenance(align.as_nonzero_usize())
133    }
134
135    /// Converts an address back to a mutable pointer, picking up some previously 'exposed'
136    /// [provenance][crate::ptr#provenance].
137    ///
138    /// For more details, see the equivalent method on a raw pointer, [`ptr::with_exposed_provenance_mut`].
139    ///
140    /// This is an [Exposed Provenance][crate::ptr#exposed-provenance] API.
141    #[stable(feature = "nonnull_provenance", since = "1.89.0")]
142    #[rustc_const_unstable(feature = "const_nonnull_with_exposed_provenance", issue = "154215")]
143    #[inline]
144    pub const fn with_exposed_provenance(addr: NonZero<usize>) -> Self {
145        // SAFETY: we know `addr` is non-zero.
146        unsafe {
147            let ptr = crate::ptr::with_exposed_provenance_mut(addr.get());
148            NonNull::new_unchecked(ptr)
149        }
150    }
151
152    /// Returns a shared references to the value. In contrast to [`as_ref`], this does not require
153    /// that the value has to be initialized.
154    ///
155    /// For the mutable counterpart see [`as_uninit_mut`].
156    ///
157    /// [`as_ref`]: NonNull::as_ref
158    /// [`as_uninit_mut`]: NonNull::as_uninit_mut
159    ///
160    /// # Safety
161    ///
162    /// When calling this method, you have to ensure that
163    /// the pointer is [convertible to a reference](crate::ptr#pointer-to-reference-conversion).
164    /// Note that because the created reference is to `MaybeUninit<T>`, the
165    /// source pointer can point to uninitialized memory.
166    #[inline]
167    #[must_use]
168    #[unstable(feature = "ptr_as_uninit", issue = "75402")]
169    pub const unsafe fn as_uninit_ref<'a>(self) -> &'a MaybeUninit<T> {
170        // SAFETY: the caller must guarantee that `self` meets all the
171        // requirements for a reference.
172        unsafe { &*self.cast().as_ptr() }
173    }
174
175    /// Returns a unique references to the value. In contrast to [`as_mut`], this does not require
176    /// that the value has to be initialized.
177    ///
178    /// For the shared counterpart see [`as_uninit_ref`].
179    ///
180    /// [`as_mut`]: NonNull::as_mut
181    /// [`as_uninit_ref`]: NonNull::as_uninit_ref
182    ///
183    /// # Safety
184    ///
185    /// When calling this method, you have to ensure that
186    /// the pointer is [convertible to a reference](crate::ptr#pointer-to-reference-conversion).
187    /// Note that because the created reference is to `MaybeUninit<T>`, the
188    /// source pointer can point to uninitialized memory.
189    #[inline]
190    #[must_use]
191    #[unstable(feature = "ptr_as_uninit", issue = "75402")]
192    pub const unsafe fn as_uninit_mut<'a>(self) -> &'a mut MaybeUninit<T> {
193        // SAFETY: the caller must guarantee that `self` meets all the
194        // requirements for a reference.
195        unsafe { &mut *self.cast().as_ptr() }
196    }
197
198    /// Casts from a pointer-to-`T` to a pointer-to-`[T; N]`.
199    #[inline]
200    #[unstable(feature = "ptr_cast_array", issue = "144514")]
201    pub const fn cast_array<const N: usize>(self) -> NonNull<[T; N]> {
202        self.cast()
203    }
204}
205
206impl<T: PointeeSized> NonNull<T> {
207    /// Creates a new `NonNull`.
208    ///
209    /// Note that if you have an `&mut`, you can use the safe [`from_mut`] instead.
210    ///
211    /// [`from_mut`]: NonNull::from_mut
212    ///
213    /// # Safety
214    ///
215    /// `ptr` must be non-null.
216    ///
217    /// # Examples
218    ///
219    /// ```
220    /// use std::ptr::NonNull;
221    ///
222    /// let mut x = 0u32;
223    /// let ptr = unsafe { NonNull::new_unchecked(&mut x as *mut _) };
224    /// ```
225    ///
226    /// *Incorrect* usage of this function:
227    ///
228    /// ```rust,no_run
229    /// use std::ptr::NonNull;
230    ///
231    /// // NEVER DO THAT!!! This is undefined behavior. ⚠️
232    /// let ptr = unsafe { NonNull::<u32>::new_unchecked(std::ptr::null_mut()) };
233    /// ```
234    #[stable(feature = "nonnull", since = "1.25.0")]
235    #[rustc_const_stable(feature = "const_nonnull_new_unchecked", since = "1.25.0")]
236    #[inline]
237    #[track_caller]
238    pub const unsafe fn new_unchecked(ptr: *mut T) -> Self {
239        // SAFETY: the caller must guarantee that `ptr` is non-null.
240        unsafe {
241            assert_unsafe_precondition!(
242                check_language_ub,
243                "NonNull::new_unchecked requires that the pointer is non-null",
244                (ptr: *mut () = ptr as *mut ()) => !ptr.is_null()
245            );
246            transmute(ptr)
247        }
248    }
249
250    /// Creates a new `NonNull` if `ptr` is non-null.
251    ///
252    /// Note that if you have an `&mut`, you can use [`from_mut`] instead to avoid the `Option`.
253    ///
254    /// [`from_mut`]: NonNull::from_mut
255    ///
256    /// # Panics during const evaluation
257    ///
258    /// This method will panic during const evaluation if the pointer cannot be
259    /// determined to be null or not. See [`is_null`] for more information.
260    ///
261    /// [`is_null`]: ../primitive.pointer.html#method.is_null-1
262    ///
263    /// # Examples
264    ///
265    /// ```
266    /// use std::ptr::NonNull;
267    ///
268    /// let mut x = 0u32;
269    /// let ptr = NonNull::<u32>::new(&mut x as *mut _).expect("pointer should not be null");
270    ///
271    /// if let Some(ptr) = NonNull::<u32>::new(std::ptr::null_mut()) {
272    ///     unreachable!();
273    /// }
274    /// ```
275    #[stable(feature = "nonnull", since = "1.25.0")]
276    #[rustc_const_stable(feature = "const_nonnull_new", since = "1.85.0")]
277    #[inline]
278    pub const fn new(ptr: *mut T) -> Option<Self> {
279        if !ptr.is_null() {
280            // SAFETY: The pointer is already checked and is not null
281            Some(unsafe { Self::new_unchecked(ptr) })
282        } else {
283            None
284        }
285    }
286
287    /// Converts a reference to a `NonNull` pointer.
288    #[stable(feature = "non_null_from_ref", since = "1.89.0")]
289    #[rustc_const_stable(feature = "non_null_from_ref", since = "1.89.0")]
290    #[inline]
291    pub const fn from_ref(r: &T) -> Self {
292        // SAFETY: A reference cannot be null.
293        unsafe { transmute(r as *const T) }
294    }
295
296    /// Converts a mutable reference to a `NonNull` pointer.
297    #[stable(feature = "non_null_from_ref", since = "1.89.0")]
298    #[rustc_const_stable(feature = "non_null_from_ref", since = "1.89.0")]
299    #[inline]
300    pub const fn from_mut(r: &mut T) -> Self {
301        // SAFETY: A mutable reference cannot be null.
302        unsafe { transmute(r as *mut T) }
303    }
304
305    /// Performs the same functionality as [`std::ptr::from_raw_parts`], except that a
306    /// `NonNull` pointer is returned, as opposed to a raw `*const` pointer.
307    ///
308    /// See the documentation of [`std::ptr::from_raw_parts`] for more details.
309    ///
310    /// [`std::ptr::from_raw_parts`]: crate::ptr::from_raw_parts
311    #[unstable(feature = "ptr_metadata", issue = "81513")]
312    #[inline]
313    pub const fn from_raw_parts(
314        data_pointer: NonNull<impl super::Thin>,
315        metadata: <T as super::Pointee>::Metadata,
316    ) -> NonNull<T> {
317        // SAFETY: The result of `ptr::from::raw_parts_mut` is non-null because `data_pointer` is.
318        unsafe {
319            NonNull::new_unchecked(super::from_raw_parts_mut(data_pointer.as_ptr(), metadata))
320        }
321    }
322
323    /// Decompose a (possibly wide) pointer into its data pointer and metadata components.
324    ///
325    /// The pointer can be later reconstructed with [`NonNull::from_raw_parts`].
326    #[unstable(feature = "ptr_metadata", issue = "81513")]
327    #[must_use = "this returns the result of the operation, \
328                  without modifying the original"]
329    #[inline]
330    pub const fn to_raw_parts(self) -> (NonNull<()>, <T as super::Pointee>::Metadata) {
331        (self.cast(), super::metadata(self.as_ptr()))
332    }
333
334    /// Gets the "address" portion of the pointer.
335    ///
336    /// For more details, see the equivalent method on a raw pointer, [`pointer::addr`].
337    ///
338    /// This is a [Strict Provenance][crate::ptr#strict-provenance] API.
339    #[must_use]
340    #[inline]
341    #[stable(feature = "strict_provenance", since = "1.84.0")]
342    pub fn addr(self) -> NonZero<usize> {
343        // SAFETY: The pointer is guaranteed by the type to be non-null,
344        // meaning that the address will be non-zero.
345        unsafe { NonZero::new_unchecked(self.as_ptr().addr()) }
346    }
347
348    /// Exposes the ["provenance"][crate::ptr#provenance] part of the pointer for future use in
349    /// [`with_exposed_provenance`][NonNull::with_exposed_provenance] and returns the "address" portion.
350    ///
351    /// For more details, see the equivalent method on a raw pointer, [`pointer::expose_provenance`].
352    ///
353    /// This is an [Exposed Provenance][crate::ptr#exposed-provenance] API.
354    #[stable(feature = "nonnull_provenance", since = "1.89.0")]
355    pub fn expose_provenance(self) -> NonZero<usize> {
356        // SAFETY: The pointer is guaranteed by the type to be non-null,
357        // meaning that the address will be non-zero.
358        unsafe { NonZero::new_unchecked(self.as_ptr().expose_provenance()) }
359    }
360
361    /// Creates a new pointer with the given address and the [provenance][crate::ptr#provenance] of
362    /// `self`.
363    ///
364    /// For more details, see the equivalent method on a raw pointer, [`pointer::with_addr`].
365    ///
366    /// This is a [Strict Provenance][crate::ptr#strict-provenance] API.
367    #[must_use]
368    #[inline]
369    #[stable(feature = "strict_provenance", since = "1.84.0")]
370    pub fn with_addr(self, addr: NonZero<usize>) -> Self {
371        // SAFETY: The result of `ptr::from::with_addr` is non-null because `addr` is guaranteed to be non-zero.
372        unsafe { NonNull::new_unchecked(self.as_ptr().with_addr(addr.get()) as *mut _) }
373    }
374
375    /// Creates a new pointer by mapping `self`'s address to a new one, preserving the
376    /// [provenance][crate::ptr#provenance] of `self`.
377    ///
378    /// For more details, see the equivalent method on a raw pointer, [`pointer::map_addr`].
379    ///
380    /// This is a [Strict Provenance][crate::ptr#strict-provenance] API.
381    #[must_use]
382    #[inline]
383    #[stable(feature = "strict_provenance", since = "1.84.0")]
384    pub fn map_addr(self, f: impl FnOnce(NonZero<usize>) -> NonZero<usize>) -> Self {
385        self.with_addr(f(self.addr()))
386    }
387
388    /// Acquires the underlying `*mut` pointer.
389    ///
390    /// # Examples
391    ///
392    /// ```
393    /// use std::ptr::NonNull;
394    ///
395    /// let mut x = 0u32;
396    /// let ptr = NonNull::from_mut(&mut x);
397    ///
398    /// let x_value = unsafe { *ptr.as_ptr() };
399    /// assert_eq!(x_value, 0);
400    ///
401    /// unsafe { *ptr.as_ptr() += 2; }
402    /// let x_value = unsafe { *ptr.as_ptr() };
403    /// assert_eq!(x_value, 2);
404    /// ```
405    #[stable(feature = "nonnull", since = "1.25.0")]
406    #[rustc_const_stable(feature = "const_nonnull_as_ptr", since = "1.32.0")]
407    #[must_use]
408    #[inline(always)]
409    #[lint::never_returns_null_ptr]
410    pub const fn as_ptr(self) -> *mut T {
411        // This is a transmute for the same reasons as `NonZero::get`.
412
413        // SAFETY: `NonNull` is `transparent` over a `*const T`, and `*const T`
414        // and `*mut T` have the same layout, so transitively we can transmute
415        // our `NonNull` to a `*mut T` directly.
416        unsafe { mem::transmute::<Self, *mut T>(self) }
417    }
418
419    /// Returns a shared reference to the value. If the value may be uninitialized, [`as_uninit_ref`]
420    /// must be used instead.
421    ///
422    /// For the mutable counterpart see [`as_mut`].
423    ///
424    /// [`as_uninit_ref`]: NonNull::as_uninit_ref
425    /// [`as_mut`]: NonNull::as_mut
426    ///
427    /// # Safety
428    ///
429    /// When calling this method, you have to ensure that
430    /// the pointer is [convertible to a reference](crate::ptr#pointer-to-reference-conversion).
431    ///
432    /// # Examples
433    ///
434    /// ```
435    /// use std::ptr::NonNull;
436    ///
437    /// let mut x = 0u32;
438    /// let ptr = NonNull::from_mut(&mut x);
439    ///
440    /// let ref_x = unsafe { ptr.as_ref() };
441    /// println!("{ref_x}");
442    /// ```
443    ///
444    /// [the module documentation]: crate::ptr#safety
445    #[stable(feature = "nonnull", since = "1.25.0")]
446    #[rustc_const_stable(feature = "const_nonnull_as_ref", since = "1.73.0")]
447    #[must_use]
448    #[inline(always)]
449    pub const unsafe fn as_ref<'a>(&self) -> &'a T {
450        // SAFETY: the caller must guarantee that `self` meets all the
451        // requirements for a reference.
452        // `cast_const` avoids a mutable raw pointer deref.
453        unsafe { &*self.as_ptr().cast_const() }
454    }
455
456    /// Returns a unique reference to the value. If the value may be uninitialized, [`as_uninit_mut`]
457    /// must be used instead.
458    ///
459    /// For the shared counterpart see [`as_ref`].
460    ///
461    /// [`as_uninit_mut`]: NonNull::as_uninit_mut
462    /// [`as_ref`]: NonNull::as_ref
463    ///
464    /// # Safety
465    ///
466    /// When calling this method, you have to ensure that
467    /// the pointer is [convertible to a reference](crate::ptr#pointer-to-reference-conversion).
468    /// # Examples
469    ///
470    /// ```
471    /// use std::ptr::NonNull;
472    ///
473    /// let mut x = 0u32;
474    /// let mut ptr = NonNull::from_mut(&mut x);
475    ///
476    /// let x_ref = unsafe { ptr.as_mut() };
477    /// assert_eq!(*x_ref, 0);
478    /// *x_ref += 2;
479    /// assert_eq!(*x_ref, 2);
480    /// ```
481    ///
482    /// [the module documentation]: crate::ptr#safety
483    #[stable(feature = "nonnull", since = "1.25.0")]
484    #[rustc_const_stable(feature = "const_ptr_as_ref", since = "1.83.0")]
485    #[must_use]
486    #[inline(always)]
487    pub const unsafe fn as_mut<'a>(&mut self) -> &'a mut T {
488        // SAFETY: the caller must guarantee that `self` meets all the
489        // requirements for a mutable reference.
490        unsafe { &mut *self.as_ptr() }
491    }
492
493    /// Casts to a pointer of another type.
494    ///
495    /// # Examples
496    ///
497    /// ```
498    /// use std::ptr::NonNull;
499    ///
500    /// let mut x = 0u32;
501    /// let ptr = NonNull::from_mut(&mut x);
502    ///
503    /// let casted_ptr = ptr.cast::<i8>();
504    /// let raw_ptr: *mut i8 = casted_ptr.as_ptr();
505    /// ```
506    #[stable(feature = "nonnull_cast", since = "1.27.0")]
507    #[rustc_const_stable(feature = "const_nonnull_cast", since = "1.36.0")]
508    #[must_use = "this returns the result of the operation, \
509                  without modifying the original"]
510    #[inline]
511    pub const fn cast<U>(self) -> NonNull<U> {
512        // SAFETY: `self` is a `NonNull` pointer which is necessarily non-null
513        unsafe { transmute(self.as_ptr() as *mut U) }
514    }
515
516    /// Try to cast to a pointer of another type by checking alignment.
517    ///
518    /// If the pointer is properly aligned to the target type, it will be
519    /// cast to the target type. Otherwise, `None` is returned.
520    ///
521    /// # Examples
522    ///
523    /// ```rust
524    /// use std::ptr::NonNull;
525    ///
526    /// let mut x = 0u64;
527    ///
528    /// let aligned = NonNull::from_mut(&mut x);
529    /// let unaligned = unsafe { aligned.byte_add(1) };
530    ///
531    /// assert!(aligned.try_cast_aligned::<u32>().is_some());
532    /// assert!(unaligned.try_cast_aligned::<u32>().is_none());
533    /// ```
534    #[stable(feature = "pointer_try_cast_aligned", since = "1.101.0")]
535    #[must_use = "this returns the result of the operation, \
536                  without modifying the original"]
537    #[inline]
538    pub fn try_cast_aligned<U>(self) -> Option<NonNull<U>> {
539        if self.is_aligned_to(align_of::<U>()) { Some(self.cast()) } else { None }
540    }
541
542    #[doc = include_str!("./docs/offset.md")]
543    ///
544    /// # Examples
545    ///
546    /// ```
547    /// use std::ptr::NonNull;
548    ///
549    /// let mut s = [1, 2, 3];
550    /// let ptr: NonNull<u32> = NonNull::new(s.as_mut_ptr()).unwrap();
551    ///
552    /// unsafe {
553    ///     println!("{}", ptr.offset(1).read());
554    ///     println!("{}", ptr.offset(2).read());
555    /// }
556    /// ```
557    #[inline(always)]
558    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
559    #[must_use = "returns a new pointer rather than modifying its argument"]
560    #[stable(feature = "non_null_convenience", since = "1.80.0")]
561    #[rustc_const_stable(feature = "non_null_convenience", since = "1.80.0")]
562    pub const unsafe fn offset(self, count: isize) -> Self
563    where
564        T: Sized,
565    {
566        // SAFETY: the caller must uphold the safety contract for `offset`.
567        // Additionally safety contract of `offset` guarantees that the resulting pointer is
568        // pointing to an allocation, there can't be an allocation at null, thus it's safe to
569        // construct `NonNull`.
570        unsafe { transmute(intrinsics::offset(self.as_ptr(), count)) }
571    }
572
573    /// Calculates the offset from a pointer in bytes.
574    ///
575    /// `count` is in units of **bytes**.
576    ///
577    /// This is purely a convenience for casting to a `u8` pointer and
578    /// using [offset][pointer::offset] on it.
579    ///
580    /// For non-`Sized` pointees this operation changes only the data pointer,
581    /// leaving the metadata untouched.
582    ///
583    /// # Safety
584    ///
585    /// See [offset][pointer::offset] for documentation and safety requirements.
586    #[must_use]
587    #[inline(always)]
588    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
589    #[stable(feature = "non_null_convenience", since = "1.80.0")]
590    #[rustc_const_stable(feature = "non_null_convenience", since = "1.80.0")]
591    pub const unsafe fn byte_offset(self, count: isize) -> Self {
592        // SAFETY: the caller must uphold the safety contract for `offset` and `byte_offset` has
593        // the same safety contract.
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        unsafe { transmute(self.as_ptr().byte_offset(count)) }
598    }
599
600    #[doc = include_str!("./docs/add.md")]
601    ///
602    /// # Examples
603    ///
604    /// ```
605    /// use std::ptr::NonNull;
606    ///
607    /// let s: &str = "123";
608    /// let ptr: NonNull<u8> = NonNull::new(s.as_ptr().cast_mut()).unwrap();
609    ///
610    /// unsafe {
611    ///     println!("{}", ptr.add(1).read() as char);
612    ///     println!("{}", ptr.add(2).read() as char);
613    /// }
614    /// ```
615    #[inline(always)]
616    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
617    #[must_use = "returns a new pointer rather than modifying its argument"]
618    #[stable(feature = "non_null_convenience", since = "1.80.0")]
619    #[rustc_const_stable(feature = "non_null_convenience", since = "1.80.0")]
620    pub const unsafe fn add(self, count: usize) -> Self
621    where
622        T: Sized,
623    {
624        // SAFETY: the caller must uphold the safety contract for `offset`.
625        // Additionally safety contract of `offset` guarantees that the resulting pointer is
626        // pointing to an allocation, there can't be an allocation at null, thus it's safe to
627        // construct `NonNull`.
628        unsafe { transmute(intrinsics::offset(self.as_ptr(), count)) }
629    }
630
631    /// Calculates the offset from a pointer in bytes (convenience for `.byte_offset(count as isize)`).
632    ///
633    /// `count` is in units of bytes.
634    ///
635    /// This is purely a convenience for casting to a `u8` pointer and
636    /// using [`add`][NonNull::add] on it.
637    ///
638    /// For non-`Sized` pointees this operation changes only the data pointer,
639    /// leaving the metadata untouched.
640    ///
641    /// # Safety
642    ///
643    /// See [`add`][NonNull::add] for documentation and safety requirements.
644    #[must_use]
645    #[inline(always)]
646    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
647    #[stable(feature = "non_null_convenience", since = "1.80.0")]
648    #[rustc_const_stable(feature = "non_null_convenience", since = "1.80.0")]
649    pub const unsafe fn byte_add(self, count: usize) -> Self {
650        // SAFETY: the caller must uphold the safety contract for `add` and `byte_add` has the same
651        // safety contract.
652        // Additionally safety contract of `add` guarantees that the resulting pointer is pointing
653        // to an allocation, there can't be an allocation at null, thus it's safe to construct
654        // `NonNull`.
655        unsafe { transmute(self.as_ptr().byte_add(count)) }
656    }
657
658    #[doc = include_str!("./docs/sub.md")]
659    ///
660    /// # Examples
661    ///
662    /// ```
663    /// use std::ptr::NonNull;
664    ///
665    /// let s: &str = "123";
666    ///
667    /// unsafe {
668    ///     let end: NonNull<u8> = NonNull::new(s.as_ptr().cast_mut()).unwrap().add(3);
669    ///     println!("{}", end.sub(1).read() as char);
670    ///     println!("{}", end.sub(2).read() as char);
671    /// }
672    /// ```
673    #[inline(always)]
674    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
675    #[must_use = "returns a new pointer rather than modifying its argument"]
676    #[stable(feature = "non_null_convenience", since = "1.80.0")]
677    #[rustc_const_stable(feature = "non_null_convenience", since = "1.80.0")]
678    pub const unsafe fn sub(self, count: usize) -> Self
679    where
680        T: Sized,
681    {
682        if T::IS_ZST {
683            // Pointer arithmetic does nothing when the pointee is a ZST.
684            self
685        } else {
686            // SAFETY: the caller must uphold the safety contract for `offset`.
687            // Because the pointee is *not* a ZST, that means that `count` is
688            // at most `isize::MAX`, and thus the negation cannot overflow.
689            unsafe { self.offset((count as isize).unchecked_neg()) }
690        }
691    }
692
693    /// Calculates the offset from a pointer in bytes (convenience for
694    /// `.byte_offset((count as isize).wrapping_neg())`).
695    ///
696    /// `count` is in units of bytes.
697    ///
698    /// This is purely a convenience for casting to a `u8` pointer and
699    /// using [`sub`][NonNull::sub] on it.
700    ///
701    /// For non-`Sized` pointees this operation changes only the data pointer,
702    /// leaving the metadata untouched.
703    ///
704    /// # Safety
705    ///
706    /// See [`sub`][NonNull::sub] for documentation and safety requirements.
707    #[must_use]
708    #[inline(always)]
709    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
710    #[stable(feature = "non_null_convenience", since = "1.80.0")]
711    #[rustc_const_stable(feature = "non_null_convenience", since = "1.80.0")]
712    pub const unsafe fn byte_sub(self, count: usize) -> Self {
713        // SAFETY: the caller must uphold the safety contract for `sub` and `byte_sub` has the same
714        // safety contract.
715        // Additionally safety contract of `sub` guarantees that the resulting pointer is pointing
716        // to an allocation, there can't be an allocation at null, thus it's safe to construct
717        // `NonNull`.
718        unsafe { transmute(self.as_ptr().byte_sub(count)) }
719    }
720
721    /// Calculates the distance between two pointers within the same allocation. The returned value is in
722    /// units of T: the distance in bytes divided by `size_of::<T>()`.
723    ///
724    /// This is equivalent to `(self as isize - origin as isize) / (size_of::<T>() as isize)`,
725    /// except that it has a lot more opportunities for UB, in exchange for the compiler
726    /// better understanding what you are doing.
727    ///
728    /// The primary motivation of this method is for computing the `len` of an array/slice
729    /// of `T` that you are currently representing as a "start" and "end" pointer
730    /// (and "end" is "one past the end" of the array).
731    /// In that case, `end.offset_from(start)` gets you the length of the array.
732    ///
733    /// All of the following safety requirements are trivially satisfied for this usecase.
734    ///
735    /// [`offset`]: #method.offset
736    ///
737    /// # Safety
738    ///
739    /// If any of the following conditions are violated, the result is Undefined Behavior:
740    ///
741    /// * `self` and `origin` must either
742    ///
743    ///   * point to the same address, or
744    ///   * both be *derived from* a pointer to the same [allocation], and the memory range between
745    ///     the two pointers must be in bounds of that object. (See below for an example.)
746    ///
747    /// * The distance between the pointers, in bytes, must be an exact multiple
748    ///   of the size of `T`.
749    ///
750    /// As a consequence, the absolute distance between the pointers, in bytes, computed on
751    /// mathematical integers (without "wrapping around"), cannot overflow an `isize`. This is
752    /// implied by the in-bounds requirement, and the fact that no allocation can be larger
753    /// than `isize::MAX` bytes.
754    ///
755    /// The requirement for pointers to be derived from the same allocation is primarily
756    /// needed for `const`-compatibility: the distance between pointers into *different* allocated
757    /// objects is not known at compile-time. However, the requirement also exists at
758    /// runtime and may be exploited by optimizations. If you wish to compute the difference between
759    /// pointers that are not guaranteed to be from the same allocation, use
760    /// `(self.addr() as isize - origin.addr() as isize) / size_of::<T>()`.
761    ///
762    /// [`add`]: #method.add
763    /// [allocation]: crate::ptr#allocation
764    ///
765    /// # Panics
766    ///
767    /// This function panics if `T` is a Zero-Sized Type ("ZST").
768    ///
769    /// # Examples
770    ///
771    /// Basic usage:
772    ///
773    /// ```
774    /// use std::ptr::NonNull;
775    ///
776    /// let a = [0; 5];
777    /// let ptr1: NonNull<u32> = NonNull::from(&a[1]);
778    /// let ptr2: NonNull<u32> = NonNull::from(&a[3]);
779    /// unsafe {
780    ///     assert_eq!(ptr2.offset_from(ptr1), 2);
781    ///     assert_eq!(ptr1.offset_from(ptr2), -2);
782    ///     assert_eq!(ptr1.offset(2), ptr2);
783    ///     assert_eq!(ptr2.offset(-2), ptr1);
784    /// }
785    /// ```
786    ///
787    /// *Incorrect* usage:
788    ///
789    /// ```rust,no_run
790    /// use std::ptr::NonNull;
791    ///
792    /// let ptr1 = NonNull::new(Box::into_raw(Box::new(0u8))).unwrap();
793    /// let ptr2 = NonNull::new(Box::into_raw(Box::new(1u8))).unwrap();
794    /// let diff = (ptr2.addr().get() as isize).wrapping_sub(ptr1.addr().get() as isize);
795    /// // Make ptr2_other an "alias" of ptr2.add(1), but derived from ptr1.
796    /// let diff_plus_1 = diff.wrapping_add(1);
797    /// let ptr2_other = NonNull::new(ptr1.as_ptr().wrapping_byte_offset(diff_plus_1)).unwrap();
798    /// assert_eq!(ptr2.addr(), ptr2_other.addr());
799    /// // Since ptr2_other and ptr2 are derived from pointers to different objects,
800    /// // computing their offset is undefined behavior, even though
801    /// // they point to addresses that are in-bounds of the same object!
802    ///
803    /// let one = unsafe { ptr2_other.offset_from(ptr2) }; // Undefined Behavior! ⚠️
804    /// ```
805    #[inline]
806    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
807    #[stable(feature = "non_null_convenience", since = "1.80.0")]
808    #[rustc_const_stable(feature = "non_null_convenience", since = "1.80.0")]
809    pub const unsafe fn offset_from(self, origin: NonNull<T>) -> isize
810    where
811        T: Sized,
812    {
813        // SAFETY: the caller must uphold the safety contract for `offset_from`.
814        unsafe { self.as_ptr().offset_from(origin.as_ptr()) }
815    }
816
817    /// Calculates the distance between two pointers within the same allocation. The returned value is in
818    /// units of **bytes**.
819    ///
820    /// This is purely a convenience for casting to a `u8` pointer and
821    /// using [`offset_from`][NonNull::offset_from] on it.
822    ///
823    /// For non-`Sized` pointees this operation considers only the data pointers,
824    /// ignoring the metadata.
825    ///
826    /// # Safety
827    ///
828    /// See [`offset_from`][NonNull::offset_from] for documentation and safety requirements.
829    #[inline(always)]
830    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
831    #[stable(feature = "non_null_convenience", since = "1.80.0")]
832    #[rustc_const_stable(feature = "non_null_convenience", since = "1.80.0")]
833    pub const unsafe fn byte_offset_from<U: ?Sized>(self, origin: NonNull<U>) -> isize {
834        // SAFETY: the caller must uphold the safety contract for `byte_offset_from`.
835        unsafe { self.as_ptr().byte_offset_from(origin.as_ptr()) }
836    }
837
838    // N.B. `wrapping_offset``, `wrapping_add`, etc are not implemented because they can wrap to null
839
840    /// Calculates the distance between two pointers within the same allocation, *where it's known that
841    /// `self` is equal to or greater than `origin`*. The returned value is in
842    /// units of T: the distance in bytes is divided by `size_of::<T>()`.
843    ///
844    /// This computes the same value that [`offset_from`](#method.offset_from)
845    /// would compute, but with the added precondition that the offset is
846    /// guaranteed to be non-negative.  This method is equivalent to
847    /// `usize::try_from(self.offset_from(origin)).unwrap_unchecked()`,
848    /// but it provides slightly more information to the optimizer, which can
849    /// sometimes allow it to optimize slightly better with some backends.
850    ///
851    /// This method can be though of as recovering the `count` that was passed
852    /// to [`add`](#method.add) (or, with the parameters in the other order,
853    /// to [`sub`](#method.sub)).  The following are all equivalent, assuming
854    /// that their safety preconditions are met:
855    /// ```rust
856    /// # unsafe fn blah(ptr: std::ptr::NonNull<u32>, origin: std::ptr::NonNull<u32>, count: usize) -> bool { unsafe {
857    /// ptr.offset_from_unsigned(origin) == count
858    /// # &&
859    /// origin.add(count) == ptr
860    /// # &&
861    /// ptr.sub(count) == origin
862    /// # } }
863    /// ```
864    ///
865    /// # Safety
866    ///
867    /// - The distance between the pointers must be non-negative (`self >= origin`)
868    ///
869    /// - *All* the safety conditions of [`offset_from`](#method.offset_from)
870    ///   apply to this method as well; see it for the full details.
871    ///
872    /// Importantly, despite the return type of this method being able to represent
873    /// a larger offset, it's still *not permitted* to pass pointers which differ
874    /// by more than `isize::MAX` *bytes*.  As such, the result of this method will
875    /// always be less than or equal to `isize::MAX as usize`.
876    ///
877    /// # Panics
878    ///
879    /// This function panics if `T` is a Zero-Sized Type ("ZST").
880    ///
881    /// # Examples
882    ///
883    /// ```
884    /// use std::ptr::NonNull;
885    ///
886    /// let a = [0; 5];
887    /// let ptr1: NonNull<u32> = NonNull::from(&a[1]);
888    /// let ptr2: NonNull<u32> = NonNull::from(&a[3]);
889    /// unsafe {
890    ///     assert_eq!(ptr2.offset_from_unsigned(ptr1), 2);
891    ///     assert_eq!(ptr1.add(2), ptr2);
892    ///     assert_eq!(ptr2.sub(2), ptr1);
893    ///     assert_eq!(ptr2.offset_from_unsigned(ptr2), 0);
894    /// }
895    ///
896    /// // This would be incorrect, as the pointers are not correctly ordered:
897    /// // ptr1.offset_from_unsigned(ptr2)
898    /// ```
899    #[inline]
900    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
901    #[stable(feature = "ptr_sub_ptr", since = "1.87.0")]
902    #[rustc_const_stable(feature = "const_ptr_sub_ptr", since = "1.87.0")]
903    pub const unsafe fn offset_from_unsigned(self, subtracted: NonNull<T>) -> usize
904    where
905        T: Sized,
906    {
907        // SAFETY: the caller must uphold the safety contract for `offset_from_unsigned`.
908        unsafe { self.as_ptr().offset_from_unsigned(subtracted.as_ptr()) }
909    }
910
911    /// Calculates the distance between two pointers within the same allocation, *where it's known that
912    /// `self` is equal to or greater than `origin`*. The returned value is in
913    /// units of **bytes**.
914    ///
915    /// This is purely a convenience for casting to a `u8` pointer and
916    /// using [`offset_from_unsigned`][NonNull::offset_from_unsigned] on it.
917    ///
918    /// For non-`Sized` pointees this operation considers only the data pointers,
919    /// ignoring the metadata.
920    ///
921    /// # Safety
922    ///
923    /// See [`offset_from_unsigned`][NonNull::offset_from_unsigned] for documentation and safety requirements.
924    #[inline(always)]
925    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
926    #[stable(feature = "ptr_sub_ptr", since = "1.87.0")]
927    #[rustc_const_stable(feature = "const_ptr_sub_ptr", since = "1.87.0")]
928    pub const unsafe fn byte_offset_from_unsigned<U: ?Sized>(self, origin: NonNull<U>) -> usize {
929        // SAFETY: the caller must uphold the safety contract for `byte_offset_from_unsigned`.
930        unsafe { self.as_ptr().byte_offset_from_unsigned(origin.as_ptr()) }
931    }
932
933    /// Reads the value from `self` without moving it. This leaves the
934    /// memory in `self` unchanged.
935    ///
936    /// # Safety
937    ///
938    /// See [`ptr::read`] for safety concerns and examples.
939    ///
940    /// [`ptr::read`]: crate::ptr::read()
941    #[inline]
942    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
943    #[stable(feature = "non_null_convenience", since = "1.80.0")]
944    #[rustc_const_stable(feature = "non_null_convenience", since = "1.80.0")]
945    pub const unsafe fn read(self) -> T
946    where
947        T: Sized,
948    {
949        // SAFETY: the caller must uphold the safety contract for `read`.
950        unsafe { ptr::read(self.as_ptr()) }
951    }
952
953    /// Performs a volatile read of the value from `self` without moving it. This
954    /// leaves the memory in `self` unchanged.
955    ///
956    /// Volatile operations are intended to act on I/O memory, and are guaranteed
957    /// to not be elided or reordered by the compiler across other volatile
958    /// operations.
959    ///
960    /// # Safety
961    ///
962    /// See [`ptr::read_volatile`] for safety concerns and examples.
963    ///
964    /// [`ptr::read_volatile`]: crate::ptr::read_volatile()
965    #[inline]
966    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
967    #[stable(feature = "non_null_convenience", since = "1.80.0")]
968    #[rustc_const_unstable(feature = "const_volatile", issue = "159094")]
969    pub const unsafe fn read_volatile(self) -> T
970    where
971        T: Sized,
972    {
973        // SAFETY: the caller must uphold the safety contract for `read_volatile`.
974        unsafe { ptr::read_volatile(self.as_ptr()) }
975    }
976
977    /// Reads the value from `self` without moving it. This leaves the
978    /// memory in `self` unchanged.
979    ///
980    /// Unlike `read`, the pointer may be unaligned.
981    ///
982    /// # Safety
983    ///
984    /// See [`ptr::read_unaligned`] for safety concerns and examples.
985    ///
986    /// [`ptr::read_unaligned`]: crate::ptr::read_unaligned()
987    #[inline]
988    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
989    #[stable(feature = "non_null_convenience", since = "1.80.0")]
990    #[rustc_const_stable(feature = "non_null_convenience", since = "1.80.0")]
991    pub const unsafe fn read_unaligned(self) -> T
992    where
993        T: Sized,
994    {
995        // SAFETY: the caller must uphold the safety contract for `read_unaligned`.
996        unsafe { ptr::read_unaligned(self.as_ptr()) }
997    }
998
999    /// Copies `count * size_of::<T>()` bytes from `self` to `dest`. The source
1000    /// and destination may overlap.
1001    ///
1002    /// NOTE: this has the *same* argument order as [`ptr::copy`].
1003    ///
1004    /// # Safety
1005    ///
1006    /// See [`ptr::copy`] for safety concerns and examples.
1007    ///
1008    /// [`ptr::copy`]: crate::ptr::copy()
1009    #[inline(always)]
1010    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1011    #[stable(feature = "non_null_convenience", since = "1.80.0")]
1012    #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.83.0")]
1013    pub const unsafe fn copy_to(self, dest: NonNull<T>, count: usize)
1014    where
1015        T: Sized,
1016    {
1017        // SAFETY: the caller must uphold the safety contract for `copy`.
1018        unsafe { ptr::copy(self.as_ptr(), dest.as_ptr(), count) }
1019    }
1020
1021    /// Copies `count * size_of::<T>()` bytes from `self` to `dest`. The source
1022    /// and destination may *not* overlap.
1023    ///
1024    /// NOTE: this has the *same* argument order as [`ptr::copy_nonoverlapping`].
1025    ///
1026    /// # Safety
1027    ///
1028    /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples.
1029    ///
1030    /// [`ptr::copy_nonoverlapping`]: crate::ptr::copy_nonoverlapping()
1031    #[inline(always)]
1032    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1033    #[stable(feature = "non_null_convenience", since = "1.80.0")]
1034    #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.83.0")]
1035    pub const unsafe fn copy_to_nonoverlapping(self, dest: NonNull<T>, count: usize)
1036    where
1037        T: Sized,
1038    {
1039        // SAFETY: the caller must uphold the safety contract for `copy_nonoverlapping`.
1040        unsafe { ptr::copy_nonoverlapping(self.as_ptr(), dest.as_ptr(), count) }
1041    }
1042
1043    /// Copies `count * size_of::<T>()` bytes from `src` to `self`. The source
1044    /// and destination may overlap.
1045    ///
1046    /// NOTE: this has the *opposite* argument order of [`ptr::copy`].
1047    ///
1048    /// # Safety
1049    ///
1050    /// See [`ptr::copy`] for safety concerns and examples.
1051    ///
1052    /// [`ptr::copy`]: crate::ptr::copy()
1053    #[inline(always)]
1054    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1055    #[stable(feature = "non_null_convenience", since = "1.80.0")]
1056    #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.83.0")]
1057    pub const unsafe fn copy_from(self, src: NonNull<T>, count: usize)
1058    where
1059        T: Sized,
1060    {
1061        // SAFETY: the caller must uphold the safety contract for `copy`.
1062        unsafe { ptr::copy(src.as_ptr(), self.as_ptr(), count) }
1063    }
1064
1065    /// Copies `count * size_of::<T>()` bytes from `src` to `self`. The source
1066    /// and destination may *not* overlap.
1067    ///
1068    /// NOTE: this has the *opposite* argument order of [`ptr::copy_nonoverlapping`].
1069    ///
1070    /// # Safety
1071    ///
1072    /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples.
1073    ///
1074    /// [`ptr::copy_nonoverlapping`]: crate::ptr::copy_nonoverlapping()
1075    #[inline(always)]
1076    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1077    #[stable(feature = "non_null_convenience", since = "1.80.0")]
1078    #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.83.0")]
1079    pub const unsafe fn copy_from_nonoverlapping(self, src: NonNull<T>, count: usize)
1080    where
1081        T: Sized,
1082    {
1083        // SAFETY: the caller must uphold the safety contract for `copy_nonoverlapping`.
1084        unsafe { ptr::copy_nonoverlapping(src.as_ptr(), self.as_ptr(), count) }
1085    }
1086
1087    /// Executes the destructor (if any) of the pointed-to value.
1088    ///
1089    /// # Safety
1090    ///
1091    /// See [`ptr::drop_in_place`] for safety concerns and examples.
1092    ///
1093    /// [`ptr::drop_in_place`]: crate::ptr::drop_in_place()
1094    #[inline(always)]
1095    #[stable(feature = "non_null_convenience", since = "1.80.0")]
1096    #[rustc_const_unstable(feature = "const_drop_in_place", issue = "109342")]
1097    pub const unsafe fn drop_in_place(mut self)
1098    where
1099        T: [const] Destruct,
1100    {
1101        // SAFETY: the caller must uphold the safety contract for `drop_in_place`.
1102        unsafe { ptr::drop_glue(self.as_mut()) }
1103    }
1104
1105    /// Overwrites a memory location with the given value without reading or
1106    /// dropping the old value.
1107    ///
1108    /// # Safety
1109    ///
1110    /// See [`ptr::write`] for safety concerns and examples.
1111    ///
1112    /// [`ptr::write`]: crate::ptr::write()
1113    #[inline(always)]
1114    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1115    #[stable(feature = "non_null_convenience", since = "1.80.0")]
1116    #[rustc_const_stable(feature = "const_ptr_write", since = "1.83.0")]
1117    pub const unsafe fn write(self, val: T)
1118    where
1119        T: Sized,
1120    {
1121        // SAFETY: the caller must uphold the safety contract for `write`.
1122        unsafe { ptr::write(self.as_ptr(), val) }
1123    }
1124
1125    /// Invokes memset on the specified pointer, setting `count * size_of::<T>()`
1126    /// bytes of memory starting at `self` to `val`.
1127    ///
1128    /// # Safety
1129    ///
1130    /// See [`ptr::write_bytes`] for safety concerns and examples.
1131    ///
1132    /// [`ptr::write_bytes`]: crate::ptr::write_bytes()
1133    #[inline(always)]
1134    #[doc(alias = "memset")]
1135    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1136    #[stable(feature = "non_null_convenience", since = "1.80.0")]
1137    #[rustc_const_stable(feature = "const_ptr_write", since = "1.83.0")]
1138    pub const unsafe fn write_bytes(self, val: u8, count: usize)
1139    where
1140        T: Sized,
1141    {
1142        // SAFETY: the caller must uphold the safety contract for `write_bytes`.
1143        unsafe { ptr::write_bytes(self.as_ptr(), val, count) }
1144    }
1145
1146    /// Performs a volatile write of a memory location with the given value without
1147    /// reading or dropping the old value.
1148    ///
1149    /// Volatile operations are intended to act on I/O memory, and are guaranteed
1150    /// to not be elided or reordered by the compiler across other volatile
1151    /// operations.
1152    ///
1153    /// # Safety
1154    ///
1155    /// See [`ptr::write_volatile`] for safety concerns and examples.
1156    ///
1157    /// [`ptr::write_volatile`]: crate::ptr::write_volatile()
1158    #[inline(always)]
1159    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1160    #[stable(feature = "non_null_convenience", since = "1.80.0")]
1161    #[rustc_const_unstable(feature = "const_volatile", issue = "159094")]
1162    pub const unsafe fn write_volatile(self, val: T)
1163    where
1164        T: Sized,
1165    {
1166        // SAFETY: the caller must uphold the safety contract for `write_volatile`.
1167        unsafe { ptr::write_volatile(self.as_ptr(), val) }
1168    }
1169
1170    /// Overwrites a memory location with the given value without reading or
1171    /// dropping the old value.
1172    ///
1173    /// Unlike `write`, the pointer may be unaligned.
1174    ///
1175    /// # Safety
1176    ///
1177    /// See [`ptr::write_unaligned`] for safety concerns and examples.
1178    ///
1179    /// [`ptr::write_unaligned`]: crate::ptr::write_unaligned()
1180    #[inline(always)]
1181    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1182    #[stable(feature = "non_null_convenience", since = "1.80.0")]
1183    #[rustc_const_stable(feature = "const_ptr_write", since = "1.83.0")]
1184    pub const unsafe fn write_unaligned(self, val: T)
1185    where
1186        T: Sized,
1187    {
1188        // SAFETY: the caller must uphold the safety contract for `write_unaligned`.
1189        unsafe { ptr::write_unaligned(self.as_ptr(), val) }
1190    }
1191
1192    /// Replaces the value at `self` with `src`, returning the old
1193    /// value, without dropping either.
1194    ///
1195    /// # Safety
1196    ///
1197    /// See [`ptr::replace`] for safety concerns and examples.
1198    ///
1199    /// [`ptr::replace`]: crate::ptr::replace()
1200    #[inline(always)]
1201    #[stable(feature = "non_null_convenience", since = "1.80.0")]
1202    #[rustc_const_stable(feature = "const_inherent_ptr_replace", since = "1.88.0")]
1203    pub const unsafe fn replace(self, src: T) -> T
1204    where
1205        T: Sized,
1206    {
1207        // SAFETY: the caller must uphold the safety contract for `replace`.
1208        unsafe { ptr::replace(self.as_ptr(), src) }
1209    }
1210
1211    /// Swaps the values at two mutable locations of the same type, without
1212    /// deinitializing either. They may overlap, unlike `mem::swap` which is
1213    /// otherwise equivalent.
1214    ///
1215    /// # Safety
1216    ///
1217    /// See [`ptr::swap`] for safety concerns and examples.
1218    ///
1219    /// [`ptr::swap`]: crate::ptr::swap()
1220    #[inline(always)]
1221    #[stable(feature = "non_null_convenience", since = "1.80.0")]
1222    #[rustc_const_stable(feature = "const_swap", since = "1.85.0")]
1223    pub const unsafe fn swap(self, with: NonNull<T>)
1224    where
1225        T: Sized,
1226    {
1227        // SAFETY: the caller must uphold the safety contract for `swap`.
1228        unsafe { ptr::swap(self.as_ptr(), with.as_ptr()) }
1229    }
1230
1231    /// Computes the offset that needs to be applied to the pointer in order to make it aligned to
1232    /// `align`.
1233    ///
1234    /// If it is not possible to align the pointer, the implementation returns
1235    /// `usize::MAX`.
1236    ///
1237    /// The offset is expressed in number of `T` elements, and not bytes.
1238    ///
1239    /// There are no guarantees whatsoever that offsetting the pointer will not overflow or go
1240    /// beyond the allocation that the pointer points into. It is up to the caller to ensure that
1241    /// the returned offset is correct in all terms other than alignment.
1242    ///
1243    /// When this is called during compile-time evaluation (which is unstable), the implementation
1244    /// may return `usize::MAX` in cases where that can never happen at runtime. This is because the
1245    /// actual alignment of pointers is not known yet during compile-time, so an offset with
1246    /// guaranteed alignment can sometimes not be computed. For example, a buffer declared as `[u8;
1247    /// N]` might be allocated at an odd or an even address, but at compile-time this is not yet
1248    /// known, so the execution has to be correct for either choice. It is therefore impossible to
1249    /// find an offset that is guaranteed to be 2-aligned. (This behavior is subject to change, as usual
1250    /// for unstable APIs.)
1251    ///
1252    /// # Panics
1253    ///
1254    /// The function panics if `align` is not a power-of-two.
1255    ///
1256    /// # Examples
1257    ///
1258    /// Accessing adjacent `u8` as `u16`
1259    ///
1260    /// ```
1261    /// use std::ptr::NonNull;
1262    ///
1263    /// # unsafe {
1264    /// let x = [5_u8, 6, 7, 8, 9];
1265    /// let ptr = NonNull::new(x.as_ptr() as *mut u8).unwrap();
1266    /// let offset = ptr.align_offset(align_of::<u16>());
1267    ///
1268    /// if offset < x.len() - 1 {
1269    ///     let u16_ptr = ptr.add(offset).cast::<u16>();
1270    ///     assert!(u16_ptr.read() == u16::from_ne_bytes([5, 6]) || u16_ptr.read() == u16::from_ne_bytes([6, 7]));
1271    /// } else {
1272    ///     // while the pointer can be aligned via `offset`, it would point
1273    ///     // outside the allocation
1274    /// }
1275    /// # }
1276    /// ```
1277    #[inline]
1278    #[must_use]
1279    #[stable(feature = "non_null_convenience", since = "1.80.0")]
1280    pub fn align_offset(self, align: usize) -> usize
1281    where
1282        T: Sized,
1283    {
1284        if !align.is_power_of_two() {
1285            panic!("align_offset: align is not a power-of-two");
1286        }
1287
1288        {
1289            // SAFETY: `align` has been checked to be a power of 2 above.
1290            unsafe { ptr::align_offset(self.as_ptr(), align) }
1291        }
1292    }
1293
1294    /// Returns whether the pointer is properly aligned for `T`.
1295    ///
1296    /// # Examples
1297    ///
1298    /// ```
1299    /// use std::ptr::NonNull;
1300    ///
1301    /// // On some platforms, the alignment of i32 is less than 4.
1302    /// #[repr(align(4))]
1303    /// struct AlignedI32(i32);
1304    ///
1305    /// let data = AlignedI32(42);
1306    /// let ptr = NonNull::<AlignedI32>::from(&data);
1307    ///
1308    /// assert!(ptr.is_aligned());
1309    /// assert!(!NonNull::new(ptr.as_ptr().wrapping_byte_add(1)).unwrap().is_aligned());
1310    /// ```
1311    #[inline]
1312    #[must_use]
1313    #[stable(feature = "pointer_is_aligned", since = "1.79.0")]
1314    pub fn is_aligned(self) -> bool
1315    where
1316        T: Sized,
1317    {
1318        self.as_ptr().is_aligned()
1319    }
1320
1321    /// Returns whether the pointer is aligned to `align`.
1322    ///
1323    /// For non-`Sized` pointees this operation considers only the data pointer,
1324    /// ignoring the metadata.
1325    ///
1326    /// # Panics
1327    ///
1328    /// The function panics if `align` is not a power-of-two (this includes 0).
1329    ///
1330    /// # Examples
1331    ///
1332    /// ```
1333    /// #![feature(pointer_is_aligned_to)]
1334    ///
1335    /// // On some platforms, the alignment of i32 is less than 4.
1336    /// #[repr(align(4))]
1337    /// struct AlignedI32(i32);
1338    ///
1339    /// let data = AlignedI32(42);
1340    /// let ptr = &data as *const AlignedI32;
1341    ///
1342    /// assert!(ptr.is_aligned_to(1));
1343    /// assert!(ptr.is_aligned_to(2));
1344    /// assert!(ptr.is_aligned_to(4));
1345    ///
1346    /// assert!(ptr.wrapping_byte_add(2).is_aligned_to(2));
1347    /// assert!(!ptr.wrapping_byte_add(2).is_aligned_to(4));
1348    ///
1349    /// assert_ne!(ptr.is_aligned_to(8), ptr.wrapping_add(1).is_aligned_to(8));
1350    /// ```
1351    #[inline]
1352    #[must_use]
1353    #[unstable(feature = "pointer_is_aligned_to", issue = "96284")]
1354    pub fn is_aligned_to(self, align: usize) -> bool {
1355        self.as_ptr().is_aligned_to(align)
1356    }
1357}
1358
1359impl<T> NonNull<T> {
1360    /// Casts from a type to its maybe-uninitialized version.
1361    #[must_use]
1362    #[inline(always)]
1363    #[unstable(feature = "cast_maybe_uninit", issue = "145036")]
1364    pub const fn cast_uninit(self) -> NonNull<MaybeUninit<T>> {
1365        self.cast()
1366    }
1367
1368    /// Creates a non-null raw slice from a thin pointer and a length.
1369    ///
1370    /// The `len` argument is the number of **elements**, not the number of bytes.
1371    ///
1372    /// See [`ptr::slice_from_raw_parts`] for more information.
1373    ///
1374    /// [`ptr::slice_from_raw_parts`]: crate::ptr::slice_from_raw_parts
1375    ///
1376    /// # Examples
1377    ///
1378    /// ```rust
1379    /// use std::ptr::NonNull;
1380    ///
1381    /// // create a slice pointer when starting out with a pointer to the first element
1382    /// let mut x = [5, 6, 7];
1383    /// let nonnull_pointer = NonNull::new(x.as_mut_ptr()).unwrap();
1384    /// let slice = nonnull_pointer.cast_slice(3);
1385    /// assert_eq!(unsafe { slice.as_ref()[2] }, 7);
1386    /// ```
1387    ///
1388    /// (Note that this example artificially demonstrates a use of this method,
1389    /// but `let slice = NonNull::from(&x[..]);` would be a better way to write code like this.)
1390    #[inline]
1391    #[must_use]
1392    #[stable(feature = "ptr_cast_slice", since = "1.101.0")]
1393    #[rustc_const_stable(feature = "ptr_cast_slice", since = "1.101.0")]
1394    pub const fn cast_slice(self, len: usize) -> NonNull<[T]> {
1395        NonNull::slice_from_raw_parts(self, len)
1396    }
1397}
1398impl<T> NonNull<MaybeUninit<T>> {
1399    /// Casts from a maybe-uninitialized type to its initialized version.
1400    ///
1401    /// This is always safe, since UB can only occur if the pointer is read
1402    /// before being initialized.
1403    #[must_use]
1404    #[inline(always)]
1405    #[unstable(feature = "cast_maybe_uninit", issue = "145036")]
1406    pub const fn cast_init(self) -> NonNull<T> {
1407        self.cast()
1408    }
1409}
1410
1411impl<T> NonNull<[T]> {
1412    /// Creates a non-null raw slice from a thin pointer and a length.
1413    ///
1414    /// The `len` argument is the number of **elements**, not the number of bytes.
1415    ///
1416    /// This function is safe, but dereferencing the return value is unsafe.
1417    /// See the documentation of [`slice::from_raw_parts`] for slice safety requirements.
1418    ///
1419    /// # Examples
1420    ///
1421    /// ```rust
1422    /// use std::ptr::NonNull;
1423    ///
1424    /// // create a slice pointer when starting out with a pointer to the first element
1425    /// let mut x = [5, 6, 7];
1426    /// let nonnull_pointer = NonNull::new(x.as_mut_ptr()).unwrap();
1427    /// let slice = NonNull::slice_from_raw_parts(nonnull_pointer, 3);
1428    /// assert_eq!(unsafe { slice.as_ref()[2] }, 7);
1429    /// ```
1430    ///
1431    /// (Note that this example artificially demonstrates a use of this method,
1432    /// but `let slice = NonNull::from(&x[..]);` would be a better way to write code like this.)
1433    #[stable(feature = "nonnull_slice_from_raw_parts", since = "1.70.0")]
1434    #[rustc_const_stable(feature = "const_slice_from_raw_parts_mut", since = "1.83.0")]
1435    #[must_use]
1436    #[inline]
1437    pub const fn slice_from_raw_parts(data: NonNull<T>, len: usize) -> Self {
1438        // SAFETY: `data` is a `NonNull` pointer which is necessarily non-null
1439        unsafe { Self::new_unchecked(data.as_ptr().cast_slice(len)) }
1440    }
1441
1442    /// Returns the length of a non-null raw slice.
1443    ///
1444    /// The returned value is the number of **elements**, not the number of bytes.
1445    ///
1446    /// This function is safe, even when the non-null raw slice cannot be dereferenced to a slice
1447    /// because the pointer does not have a valid address.
1448    ///
1449    /// # Examples
1450    ///
1451    /// ```rust
1452    /// use std::ptr::NonNull;
1453    ///
1454    /// let slice: NonNull<[i8]> = NonNull::slice_from_raw_parts(NonNull::dangling(), 3);
1455    /// assert_eq!(slice.len(), 3);
1456    /// ```
1457    #[stable(feature = "slice_ptr_len_nonnull", since = "1.63.0")]
1458    #[rustc_const_stable(feature = "const_slice_ptr_len_nonnull", since = "1.63.0")]
1459    #[must_use]
1460    #[inline]
1461    pub const fn len(self) -> usize {
1462        self.as_ptr().len()
1463    }
1464
1465    /// Returns `true` if the non-null raw slice has a length of 0.
1466    ///
1467    /// # Examples
1468    ///
1469    /// ```rust
1470    /// use std::ptr::NonNull;
1471    ///
1472    /// let slice: NonNull<[i8]> = NonNull::slice_from_raw_parts(NonNull::dangling(), 3);
1473    /// assert!(!slice.is_empty());
1474    /// ```
1475    #[stable(feature = "slice_ptr_is_empty_nonnull", since = "1.79.0")]
1476    #[rustc_const_stable(feature = "const_slice_ptr_is_empty_nonnull", since = "1.79.0")]
1477    #[must_use]
1478    #[inline]
1479    pub const fn is_empty(self) -> bool {
1480        self.len() == 0
1481    }
1482
1483    /// Returns a non-null pointer to the slice's buffer.
1484    ///
1485    /// # Examples
1486    ///
1487    /// ```rust
1488    /// #![feature(slice_ptr_get)]
1489    /// use std::ptr::NonNull;
1490    ///
1491    /// let slice: NonNull<[i8]> = NonNull::slice_from_raw_parts(NonNull::dangling(), 3);
1492    /// assert_eq!(slice.as_non_null_ptr(), NonNull::<i8>::dangling());
1493    /// ```
1494    #[inline]
1495    #[must_use]
1496    #[unstable(feature = "slice_ptr_get", issue = "74265")]
1497    pub const fn as_non_null_ptr(self) -> NonNull<T> {
1498        self.cast()
1499    }
1500
1501    /// Returns a raw pointer to the slice's buffer.
1502    ///
1503    /// # Examples
1504    ///
1505    /// ```rust
1506    /// #![feature(slice_ptr_get)]
1507    /// use std::ptr::NonNull;
1508    ///
1509    /// let slice: NonNull<[i8]> = NonNull::slice_from_raw_parts(NonNull::dangling(), 3);
1510    /// assert_eq!(slice.as_mut_ptr(), NonNull::<i8>::dangling().as_ptr());
1511    /// ```
1512    #[inline]
1513    #[must_use]
1514    #[unstable(feature = "slice_ptr_get", issue = "74265")]
1515    #[lint::never_returns_null_ptr]
1516    pub const fn as_mut_ptr(self) -> *mut T {
1517        self.as_non_null_ptr().as_ptr()
1518    }
1519
1520    /// Returns a shared reference to a slice of possibly uninitialized values. In contrast to
1521    /// [`as_ref`], this does not require that the value has to be initialized.
1522    ///
1523    /// For the mutable counterpart see [`as_uninit_slice_mut`].
1524    ///
1525    /// [`as_ref`]: NonNull::as_ref
1526    /// [`as_uninit_slice_mut`]: NonNull::as_uninit_slice_mut
1527    ///
1528    /// # Safety
1529    ///
1530    /// When calling this method, you have to ensure that all of the following is true:
1531    ///
1532    /// * The pointer must be [valid] for reads for `ptr.len() * size_of::<T>()` many bytes,
1533    ///   and it must be properly aligned. This means in particular:
1534    ///
1535    ///     * The entire memory range of this slice must be contained within a single allocation!
1536    ///       Slices can never span across multiple allocations.
1537    ///
1538    ///     * The pointer must be aligned even for zero-length slices. One
1539    ///       reason for this is that enum layout optimizations may rely on references
1540    ///       (including slices of any length) being aligned and non-null to distinguish
1541    ///       them from other data. You can obtain a pointer that is usable as `data`
1542    ///       for zero-length slices using [`NonNull::dangling()`].
1543    ///
1544    /// * The total size `ptr.len() * size_of::<T>()` of the slice must be no larger than `isize::MAX`.
1545    ///   See the safety documentation of [`pointer::offset`].
1546    ///
1547    /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
1548    ///   arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
1549    ///   In particular, while this reference exists, the memory the pointer points to must
1550    ///   not get mutated (except inside `UnsafeCell`).
1551    ///
1552    /// This applies even if the result of this method is unused!
1553    ///
1554    /// See also [`slice::from_raw_parts`].
1555    ///
1556    /// [valid]: crate::ptr#safety
1557    #[inline]
1558    #[must_use]
1559    #[unstable(feature = "ptr_as_uninit", issue = "75402")]
1560    pub const unsafe fn as_uninit_slice<'a>(self) -> &'a [MaybeUninit<T>] {
1561        // SAFETY: the caller must uphold the safety contract for `as_uninit_slice`.
1562        unsafe { slice::from_raw_parts(self.cast().as_ptr(), self.len()) }
1563    }
1564
1565    /// Returns a unique reference to a slice of possibly uninitialized values. In contrast to
1566    /// [`as_mut`], this does not require that the value has to be initialized.
1567    ///
1568    /// For the shared counterpart see [`as_uninit_slice`].
1569    ///
1570    /// [`as_mut`]: NonNull::as_mut
1571    /// [`as_uninit_slice`]: NonNull::as_uninit_slice
1572    ///
1573    /// # Safety
1574    ///
1575    /// When calling this method, you have to ensure that all of the following is true:
1576    ///
1577    /// * The pointer must be [valid] for reads and writes for `ptr.len() * size_of::<T>()`
1578    ///   many bytes, and it must be properly aligned. This means in particular:
1579    ///
1580    ///     * The entire memory range of this slice must be contained within a single allocation!
1581    ///       Slices can never span across multiple allocations.
1582    ///
1583    ///     * The pointer must be aligned even for zero-length slices. One
1584    ///       reason for this is that enum layout optimizations may rely on references
1585    ///       (including slices of any length) being aligned and non-null to distinguish
1586    ///       them from other data. You can obtain a pointer that is usable as `data`
1587    ///       for zero-length slices using [`NonNull::dangling()`].
1588    ///
1589    /// * The total size `ptr.len() * size_of::<T>()` of the slice must be no larger than `isize::MAX`.
1590    ///   See the safety documentation of [`pointer::offset`].
1591    ///
1592    /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
1593    ///   arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
1594    ///   In particular, while this reference exists, the memory the pointer points to must
1595    ///   not get accessed (read or written) through any other pointer.
1596    ///
1597    /// This applies even if the result of this method is unused!
1598    ///
1599    /// See also [`slice::from_raw_parts_mut`].
1600    ///
1601    /// [valid]: crate::ptr#safety
1602    ///
1603    /// # Examples
1604    ///
1605    /// ```rust
1606    /// #![feature(ptr_as_uninit)]
1607    ///
1608    /// use std::alloc::{Allocator, Layout, Global};
1609    /// use std::mem::MaybeUninit;
1610    /// use std::ptr::NonNull;
1611    ///
1612    /// let memory: NonNull<[u8]> = Global.allocate(Layout::new::<[u8; 32]>())?;
1613    /// // This is safe as `memory` is valid for reads and writes for `memory.len()` many bytes.
1614    /// // Note that calling `memory.as_mut()` is not allowed here as the content may be uninitialized.
1615    /// # #[allow(unused_variables)]
1616    /// let slice: &mut [MaybeUninit<u8>] = unsafe { memory.as_uninit_slice_mut() };
1617    /// # // Prevent leaks for Miri.
1618    /// # unsafe { Global.deallocate(memory.cast(), Layout::new::<[u8; 32]>()); }
1619    /// # Ok::<_, std::alloc::AllocError>(())
1620    /// ```
1621    #[inline]
1622    #[must_use]
1623    #[unstable(feature = "ptr_as_uninit", issue = "75402")]
1624    pub const unsafe fn as_uninit_slice_mut<'a>(self) -> &'a mut [MaybeUninit<T>] {
1625        // SAFETY: the caller must uphold the safety contract for `as_uninit_slice_mut`.
1626        unsafe { slice::from_raw_parts_mut(self.cast().as_ptr(), self.len()) }
1627    }
1628
1629    /// Returns a raw pointer to an element or subslice, without doing bounds
1630    /// checking.
1631    ///
1632    /// # Safety
1633    ///
1634    /// Calling this method with an [out-of-bounds index] or when `self` is not dereferenceable
1635    /// is *[undefined behavior]* even if the resulting pointer is not used.
1636    ///
1637    /// [out-of-bounds index]: #method.add
1638    /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1639    ///
1640    /// # Examples
1641    ///
1642    /// ```
1643    /// #![feature(slice_ptr_get)]
1644    /// use std::ptr::NonNull;
1645    ///
1646    /// let x = &mut [1, 2, 4];
1647    /// let x = NonNull::slice_from_raw_parts(NonNull::new(x.as_mut_ptr()).unwrap(), x.len());
1648    ///
1649    /// unsafe {
1650    ///     assert_eq!(x.get_unchecked_mut(1).as_ptr(), x.as_non_null_ptr().as_ptr().add(1));
1651    /// }
1652    /// ```
1653    #[unstable(feature = "slice_ptr_get", issue = "74265")]
1654    #[rustc_const_unstable(feature = "const_index", issue = "143775")]
1655    #[inline]
1656    pub const unsafe fn get_unchecked_mut<I>(self, index: I) -> NonNull<I::Output>
1657    where
1658        I: [const] SliceIndex<[T]>,
1659    {
1660        // SAFETY: the caller ensures that `self` is dereferenceable and `index` in-bounds.
1661        // As a consequence, the resulting pointer cannot be null.
1662        unsafe { NonNull::new_unchecked(self.as_ptr().get_unchecked_mut(index)) }
1663    }
1664}
1665
1666#[stable(feature = "nonnull", since = "1.25.0")]
1667impl<T: PointeeSized> Clone for NonNull<T> {
1668    #[inline(always)]
1669    fn clone(&self) -> Self {
1670        *self
1671    }
1672}
1673
1674#[stable(feature = "nonnull", since = "1.25.0")]
1675impl<T: PointeeSized> Copy for NonNull<T> {}
1676
1677#[doc(hidden)]
1678#[unstable(feature = "trivial_clone", issue = "none")]
1679unsafe impl<T: PointeeSized> TrivialClone for NonNull<T> {}
1680
1681#[unstable(feature = "coerce_unsized", issue = "18598")]
1682impl<T: PointeeSized, U: PointeeSized> CoerceUnsized<NonNull<U>> for NonNull<T> where T: Unsize<U> {}
1683
1684#[unstable(feature = "dispatch_from_dyn", issue = "none")]
1685impl<T: PointeeSized, U: PointeeSized> DispatchFromDyn<NonNull<U>> for NonNull<T> where T: Unsize<U> {}
1686
1687#[stable(feature = "nonnull", since = "1.25.0")]
1688impl<T: PointeeSized> fmt::Debug for NonNull<T> {
1689    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1690        fmt::Pointer::fmt(&self.as_ptr(), f)
1691    }
1692}
1693
1694#[stable(feature = "nonnull", since = "1.25.0")]
1695impl<T: PointeeSized> fmt::Pointer for NonNull<T> {
1696    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1697        fmt::Pointer::fmt(&self.as_ptr(), f)
1698    }
1699}
1700
1701#[stable(feature = "nonnull", since = "1.25.0")]
1702impl<T: PointeeSized> Eq for NonNull<T> {}
1703
1704#[stable(feature = "nonnull", since = "1.25.0")]
1705impl<T: PointeeSized> PartialEq for NonNull<T> {
1706    #[inline]
1707    #[allow(ambiguous_wide_pointer_comparisons)]
1708    fn eq(&self, other: &Self) -> bool {
1709        self.as_ptr() == other.as_ptr()
1710    }
1711}
1712
1713#[stable(feature = "nonnull", since = "1.25.0")]
1714impl<T: PointeeSized> Ord for NonNull<T> {
1715    #[inline]
1716    #[allow(ambiguous_wide_pointer_comparisons)]
1717    fn cmp(&self, other: &Self) -> Ordering {
1718        self.as_ptr().cmp(&other.as_ptr())
1719    }
1720}
1721
1722#[stable(feature = "nonnull", since = "1.25.0")]
1723impl<T: PointeeSized> PartialOrd for NonNull<T> {
1724    #[inline]
1725    #[allow(ambiguous_wide_pointer_comparisons)]
1726    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1727        self.as_ptr().partial_cmp(&other.as_ptr())
1728    }
1729}
1730
1731#[stable(feature = "nonnull", since = "1.25.0")]
1732impl<T: PointeeSized> hash::Hash for NonNull<T> {
1733    #[inline]
1734    fn hash<H: hash::Hasher>(&self, state: &mut H) {
1735        self.as_ptr().hash(state)
1736    }
1737}
1738
1739#[stable(feature = "nonnull", since = "1.25.0")]
1740#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
1741const impl<T: PointeeSized> From<&mut T> for NonNull<T> {
1742    /// Converts a `&mut T` to a `NonNull<T>`.
1743    ///
1744    /// This conversion is safe and infallible since references cannot be null.
1745    #[inline]
1746    fn from(r: &mut T) -> Self {
1747        NonNull::from_mut(r)
1748    }
1749}
1750
1751#[stable(feature = "nonnull", since = "1.25.0")]
1752#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
1753const impl<T: PointeeSized> From<&T> for NonNull<T> {
1754    /// Converts a `&T` to a `NonNull<T>`.
1755    ///
1756    /// This conversion is safe and infallible since references cannot be null.
1757    #[inline]
1758    fn from(r: &T) -> Self {
1759        NonNull::from_ref(r)
1760    }
1761}