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