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            {
    #[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!(
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    #[rustc_never_returns_null_ptr]
408    #[must_use]
409    #[inline(always)]
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 = "CURRENT_RUSTC_VERSION")]
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 = "Adds a signed offset to a pointer.\n\n`count` is in units of T; e.g., a `count` of 3 represents a pointer\noffset of `3 * size_of::<T>()` bytes.\n\n# Safety\n\nIf any of the following conditions are violated, the result is Undefined Behavior:\n\n* The offset in bytes, `count * size_of::<T>()`, computed on mathematical integers (without\n\"wrapping around\"), must fit in an `isize`.\n\n* Let `result` be `self.addr() + count * size_of::<T>()`, computed on mathematical integers.\nThis must fit in a `usize`.\n\n* If the computed offset is non-zero, then `self` must be [derived from][crate::ptr#provenance] a pointer to some\n[allocation], and the entire memory range between `self` and `result`\n(i.e., `min(self.addr(), result)..max(self.addr(), result)`)\nmust be in bounds of that allocation.\n\nAllocations can never be larger than `isize::MAX` bytes and they can only contain addresses\nrepresentable by `usize`, so technically the last condition implies the first two. This implies, for\ninstance, that `vec.as_ptr().offset(vec.len() as isize)` (for `vec: Vec<T>`) is always safe.\n\n[allocation]: crate::ptr#allocation\n"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. See that method for documentation
579    /// and safety requirements.
580    ///
581    /// For non-`Sized` pointees this operation changes only the data pointer,
582    /// leaving the metadata untouched.
583    #[must_use]
584    #[inline(always)]
585    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
586    #[stable(feature = "non_null_convenience", since = "1.80.0")]
587    #[rustc_const_stable(feature = "non_null_convenience", since = "1.80.0")]
588    pub const unsafe fn byte_offset(self, count: isize) -> Self {
589        // SAFETY: the caller must uphold the safety contract for `offset` and `byte_offset` has
590        // the same safety contract.
591        // Additionally safety contract of `offset` guarantees that the resulting pointer is
592        // pointing to an allocation, there can't be an allocation at null, thus it's safe to
593        // construct `NonNull`.
594        unsafe { transmute(self.as_ptr().byte_offset(count)) }
595    }
596
597    #[doc = "Adds an unsigned offset to a pointer.\n\nThis can only move the pointer forward (or not move it). If you need to move forward or\nbackward depending on the value, then you might want [`offset`](#method.offset) instead\nwhich takes a signed offset.\n\n`count` is in units of T; e.g., a `count` of 3 represents a pointer\noffset of `3 * size_of::<T>()` bytes.\n\n# Safety\n\nIf any of the following conditions are violated, the result is Undefined Behavior:\n\n* The offset in bytes, `count * size_of::<T>()`, computed on mathematical integers (without\n\"wrapping around\"), must fit in an `isize`.\n\n* Let `result` be `self.addr() + count * size_of::<T>()`, computed on mathematical integers.\nThis must fit in a `usize`.\n\n* If the computed offset is non-zero, then `self` must be [derived from][crate::ptr#provenance] a pointer to some\n[allocation], and the entire memory range between `self` and `result`\n(i.e., `self.addr()..result`) must be in bounds of that allocation.\n\nAllocations can never be larger than `isize::MAX` bytes and they can only contain addresses\nrepresentable by `usize`, so technically the last condition implies the first two. This implies, for\ninstance, that `vec.as_ptr().add(vec.len())` (for `vec: Vec<T>`) is always safe.\n\n[allocation]: crate::ptr#allocation\n"include_str!("./docs/add.md")]
598    ///
599    /// # Examples
600    ///
601    /// ```
602    /// use std::ptr::NonNull;
603    ///
604    /// let s: &str = "123";
605    /// let ptr: NonNull<u8> = NonNull::new(s.as_ptr().cast_mut()).unwrap();
606    ///
607    /// unsafe {
608    ///     println!("{}", ptr.add(1).read() as char);
609    ///     println!("{}", ptr.add(2).read() as char);
610    /// }
611    /// ```
612    #[inline(always)]
613    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
614    #[must_use = "returns a new pointer rather than modifying its argument"]
615    #[stable(feature = "non_null_convenience", since = "1.80.0")]
616    #[rustc_const_stable(feature = "non_null_convenience", since = "1.80.0")]
617    pub const unsafe fn add(self, count: usize) -> Self
618    where
619        T: Sized,
620    {
621        // SAFETY: the caller must uphold the safety contract for `offset`.
622        // Additionally safety contract of `offset` guarantees that the resulting pointer is
623        // pointing to an allocation, there can't be an allocation at null, thus it's safe to
624        // construct `NonNull`.
625        unsafe { transmute(intrinsics::offset(self.as_ptr(), count)) }
626    }
627
628    /// Calculates the offset from a pointer in bytes (convenience for `.byte_offset(count as isize)`).
629    ///
630    /// `count` is in units of bytes.
631    ///
632    /// This is purely a convenience for casting to a `u8` pointer and
633    /// using [`add`][NonNull::add] on it. See that method for documentation
634    /// and safety requirements.
635    ///
636    /// For non-`Sized` pointees this operation changes only the data pointer,
637    /// leaving the metadata untouched.
638    #[must_use]
639    #[inline(always)]
640    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
641    #[stable(feature = "non_null_convenience", since = "1.80.0")]
642    #[rustc_const_stable(feature = "non_null_convenience", since = "1.80.0")]
643    pub const unsafe fn byte_add(self, count: usize) -> Self {
644        // SAFETY: the caller must uphold the safety contract for `add` and `byte_add` has the same
645        // safety contract.
646        // Additionally safety contract of `add` guarantees that the resulting pointer is pointing
647        // to an allocation, there can't be an allocation at null, thus it's safe to construct
648        // `NonNull`.
649        unsafe { transmute(self.as_ptr().byte_add(count)) }
650    }
651
652    #[doc = "Subtracts an unsigned offset from a pointer.\n\nThis can only move the pointer backward (or not move it). If you need to move forward or\nbackward depending on the value, then you might want [`offset`](#method.offset) instead\nwhich takes a signed offset.\n\n`count` is in units of T; e.g., a `count` of 3 represents a pointer\noffset of `3 * size_of::<T>()` bytes.\n\n# Safety\n\nIf any of the following conditions are violated, the result is Undefined Behavior:\n\n* The offset in bytes, `count * size_of::<T>()`, computed on mathematical integers (without\n  \"wrapping around\"), must fit in an `isize`.\n\n* Let `result` be `self.addr() - count * size_of::<T>()`, computed on mathematical integers.\nThis must fit in a `usize`.\n\n* If the computed offset is non-zero, then `self` must be [derived from][crate::ptr#provenance] a pointer to some\n[allocation], and the entire memory range between `self` and `result`\n(i.e., `result..self.addr()`) must be in bounds of that allocation.\n\nAllocations can never be larger than `isize::MAX` bytes and they can only contain addresses\nrepresentable by `usize`, so technically the last condition implies the first two.\n\n[allocation]: crate::ptr#allocation\n"include_str!("./docs/sub.md")]
653    ///
654    /// # Examples
655    ///
656    /// ```
657    /// use std::ptr::NonNull;
658    ///
659    /// let s: &str = "123";
660    ///
661    /// unsafe {
662    ///     let end: NonNull<u8> = NonNull::new(s.as_ptr().cast_mut()).unwrap().add(3);
663    ///     println!("{}", end.sub(1).read() as char);
664    ///     println!("{}", end.sub(2).read() as char);
665    /// }
666    /// ```
667    #[inline(always)]
668    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
669    #[must_use = "returns a new pointer rather than modifying its argument"]
670    #[stable(feature = "non_null_convenience", since = "1.80.0")]
671    #[rustc_const_stable(feature = "non_null_convenience", since = "1.80.0")]
672    pub const unsafe fn sub(self, count: usize) -> Self
673    where
674        T: Sized,
675    {
676        if T::IS_ZST {
677            // Pointer arithmetic does nothing when the pointee is a ZST.
678            self
679        } else {
680            // SAFETY: the caller must uphold the safety contract for `offset`.
681            // Because the pointee is *not* a ZST, that means that `count` is
682            // at most `isize::MAX`, and thus the negation cannot overflow.
683            unsafe { self.offset((count as isize).unchecked_neg()) }
684        }
685    }
686
687    /// Calculates the offset from a pointer in bytes (convenience for
688    /// `.byte_offset((count as isize).wrapping_neg())`).
689    ///
690    /// `count` is in units of bytes.
691    ///
692    /// This is purely a convenience for casting to a `u8` pointer and
693    /// using [`sub`][NonNull::sub] on it. See that method for documentation
694    /// and safety requirements.
695    ///
696    /// For non-`Sized` pointees this operation changes only the data pointer,
697    /// leaving the metadata untouched.
698    #[must_use]
699    #[inline(always)]
700    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
701    #[stable(feature = "non_null_convenience", since = "1.80.0")]
702    #[rustc_const_stable(feature = "non_null_convenience", since = "1.80.0")]
703    pub const unsafe fn byte_sub(self, count: usize) -> Self {
704        // SAFETY: the caller must uphold the safety contract for `sub` and `byte_sub` has the same
705        // safety contract.
706        // Additionally safety contract of `sub` guarantees that the resulting pointer is pointing
707        // to an allocation, there can't be an allocation at null, thus it's safe to construct
708        // `NonNull`.
709        unsafe { transmute(self.as_ptr().byte_sub(count)) }
710    }
711
712    /// Calculates the distance between two pointers within the same allocation. The returned value is in
713    /// units of T: the distance in bytes divided by `size_of::<T>()`.
714    ///
715    /// This is equivalent to `(self as isize - origin as isize) / (size_of::<T>() as isize)`,
716    /// except that it has a lot more opportunities for UB, in exchange for the compiler
717    /// better understanding what you are doing.
718    ///
719    /// The primary motivation of this method is for computing the `len` of an array/slice
720    /// of `T` that you are currently representing as a "start" and "end" pointer
721    /// (and "end" is "one past the end" of the array).
722    /// In that case, `end.offset_from(start)` gets you the length of the array.
723    ///
724    /// All of the following safety requirements are trivially satisfied for this usecase.
725    ///
726    /// [`offset`]: #method.offset
727    ///
728    /// # Safety
729    ///
730    /// If any of the following conditions are violated, the result is Undefined Behavior:
731    ///
732    /// * `self` and `origin` must either
733    ///
734    ///   * point to the same address, or
735    ///   * both be *derived from* a pointer to the same [allocation], and the memory range between
736    ///     the two pointers must be in bounds of that object. (See below for an example.)
737    ///
738    /// * The distance between the pointers, in bytes, must be an exact multiple
739    ///   of the size of `T`.
740    ///
741    /// As a consequence, the absolute distance between the pointers, in bytes, computed on
742    /// mathematical integers (without "wrapping around"), cannot overflow an `isize`. This is
743    /// implied by the in-bounds requirement, and the fact that no allocation can be larger
744    /// than `isize::MAX` bytes.
745    ///
746    /// The requirement for pointers to be derived from the same allocation is primarily
747    /// needed for `const`-compatibility: the distance between pointers into *different* allocated
748    /// objects is not known at compile-time. However, the requirement also exists at
749    /// runtime and may be exploited by optimizations. If you wish to compute the difference between
750    /// pointers that are not guaranteed to be from the same allocation, use
751    /// `(self.addr() as isize - origin.addr() as isize) / size_of::<T>()`.
752    ///
753    /// [`add`]: #method.add
754    /// [allocation]: crate::ptr#allocation
755    ///
756    /// # Panics
757    ///
758    /// This function panics if `T` is a Zero-Sized Type ("ZST").
759    ///
760    /// # Examples
761    ///
762    /// Basic usage:
763    ///
764    /// ```
765    /// use std::ptr::NonNull;
766    ///
767    /// let a = [0; 5];
768    /// let ptr1: NonNull<u32> = NonNull::from(&a[1]);
769    /// let ptr2: NonNull<u32> = NonNull::from(&a[3]);
770    /// unsafe {
771    ///     assert_eq!(ptr2.offset_from(ptr1), 2);
772    ///     assert_eq!(ptr1.offset_from(ptr2), -2);
773    ///     assert_eq!(ptr1.offset(2), ptr2);
774    ///     assert_eq!(ptr2.offset(-2), ptr1);
775    /// }
776    /// ```
777    ///
778    /// *Incorrect* usage:
779    ///
780    /// ```rust,no_run
781    /// use std::ptr::NonNull;
782    ///
783    /// let ptr1 = NonNull::new(Box::into_raw(Box::new(0u8))).unwrap();
784    /// let ptr2 = NonNull::new(Box::into_raw(Box::new(1u8))).unwrap();
785    /// let diff = (ptr2.addr().get() as isize).wrapping_sub(ptr1.addr().get() as isize);
786    /// // Make ptr2_other an "alias" of ptr2.add(1), but derived from ptr1.
787    /// let diff_plus_1 = diff.wrapping_add(1);
788    /// let ptr2_other = NonNull::new(ptr1.as_ptr().wrapping_byte_offset(diff_plus_1)).unwrap();
789    /// assert_eq!(ptr2.addr(), ptr2_other.addr());
790    /// // Since ptr2_other and ptr2 are derived from pointers to different objects,
791    /// // computing their offset is undefined behavior, even though
792    /// // they point to addresses that are in-bounds of the same object!
793    ///
794    /// let one = unsafe { ptr2_other.offset_from(ptr2) }; // Undefined Behavior! ⚠️
795    /// ```
796    #[inline]
797    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
798    #[stable(feature = "non_null_convenience", since = "1.80.0")]
799    #[rustc_const_stable(feature = "non_null_convenience", since = "1.80.0")]
800    pub const unsafe fn offset_from(self, origin: NonNull<T>) -> isize
801    where
802        T: Sized,
803    {
804        // SAFETY: the caller must uphold the safety contract for `offset_from`.
805        unsafe { self.as_ptr().offset_from(origin.as_ptr()) }
806    }
807
808    /// Calculates the distance between two pointers within the same allocation. The returned value is in
809    /// units of **bytes**.
810    ///
811    /// This is purely a convenience for casting to a `u8` pointer and
812    /// using [`offset_from`][NonNull::offset_from] on it. See that method for
813    /// documentation and safety requirements.
814    ///
815    /// For non-`Sized` pointees this operation considers only the data pointers,
816    /// ignoring the metadata.
817    #[inline(always)]
818    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
819    #[stable(feature = "non_null_convenience", since = "1.80.0")]
820    #[rustc_const_stable(feature = "non_null_convenience", since = "1.80.0")]
821    pub const unsafe fn byte_offset_from<U: ?Sized>(self, origin: NonNull<U>) -> isize {
822        // SAFETY: the caller must uphold the safety contract for `byte_offset_from`.
823        unsafe { self.as_ptr().byte_offset_from(origin.as_ptr()) }
824    }
825
826    // N.B. `wrapping_offset``, `wrapping_add`, etc are not implemented because they can wrap to null
827
828    /// Calculates the distance between two pointers within the same allocation, *where it's known that
829    /// `self` is equal to or greater than `origin`*. The returned value is in
830    /// units of T: the distance in bytes is divided by `size_of::<T>()`.
831    ///
832    /// This computes the same value that [`offset_from`](#method.offset_from)
833    /// would compute, but with the added precondition that the offset is
834    /// guaranteed to be non-negative.  This method is equivalent to
835    /// `usize::try_from(self.offset_from(origin)).unwrap_unchecked()`,
836    /// but it provides slightly more information to the optimizer, which can
837    /// sometimes allow it to optimize slightly better with some backends.
838    ///
839    /// This method can be though of as recovering the `count` that was passed
840    /// to [`add`](#method.add) (or, with the parameters in the other order,
841    /// to [`sub`](#method.sub)).  The following are all equivalent, assuming
842    /// that their safety preconditions are met:
843    /// ```rust
844    /// # unsafe fn blah(ptr: std::ptr::NonNull<u32>, origin: std::ptr::NonNull<u32>, count: usize) -> bool { unsafe {
845    /// ptr.offset_from_unsigned(origin) == count
846    /// # &&
847    /// origin.add(count) == ptr
848    /// # &&
849    /// ptr.sub(count) == origin
850    /// # } }
851    /// ```
852    ///
853    /// # Safety
854    ///
855    /// - The distance between the pointers must be non-negative (`self >= origin`)
856    ///
857    /// - *All* the safety conditions of [`offset_from`](#method.offset_from)
858    ///   apply to this method as well; see it for the full details.
859    ///
860    /// Importantly, despite the return type of this method being able to represent
861    /// a larger offset, it's still *not permitted* to pass pointers which differ
862    /// by more than `isize::MAX` *bytes*.  As such, the result of this method will
863    /// always be less than or equal to `isize::MAX as usize`.
864    ///
865    /// # Panics
866    ///
867    /// This function panics if `T` is a Zero-Sized Type ("ZST").
868    ///
869    /// # Examples
870    ///
871    /// ```
872    /// use std::ptr::NonNull;
873    ///
874    /// let a = [0; 5];
875    /// let ptr1: NonNull<u32> = NonNull::from(&a[1]);
876    /// let ptr2: NonNull<u32> = NonNull::from(&a[3]);
877    /// unsafe {
878    ///     assert_eq!(ptr2.offset_from_unsigned(ptr1), 2);
879    ///     assert_eq!(ptr1.add(2), ptr2);
880    ///     assert_eq!(ptr2.sub(2), ptr1);
881    ///     assert_eq!(ptr2.offset_from_unsigned(ptr2), 0);
882    /// }
883    ///
884    /// // This would be incorrect, as the pointers are not correctly ordered:
885    /// // ptr1.offset_from_unsigned(ptr2)
886    /// ```
887    #[inline]
888    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
889    #[stable(feature = "ptr_sub_ptr", since = "1.87.0")]
890    #[rustc_const_stable(feature = "const_ptr_sub_ptr", since = "1.87.0")]
891    pub const unsafe fn offset_from_unsigned(self, subtracted: NonNull<T>) -> usize
892    where
893        T: Sized,
894    {
895        // SAFETY: the caller must uphold the safety contract for `offset_from_unsigned`.
896        unsafe { self.as_ptr().offset_from_unsigned(subtracted.as_ptr()) }
897    }
898
899    /// Calculates the distance between two pointers within the same allocation, *where it's known that
900    /// `self` is equal to or greater than `origin`*. The returned value is in
901    /// units of **bytes**.
902    ///
903    /// This is purely a convenience for casting to a `u8` pointer and
904    /// using [`offset_from_unsigned`][NonNull::offset_from_unsigned] on it.
905    /// See that method for documentation and safety requirements.
906    ///
907    /// For non-`Sized` pointees this operation considers only the data pointers,
908    /// ignoring the metadata.
909    #[inline(always)]
910    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
911    #[stable(feature = "ptr_sub_ptr", since = "1.87.0")]
912    #[rustc_const_stable(feature = "const_ptr_sub_ptr", since = "1.87.0")]
913    pub const unsafe fn byte_offset_from_unsigned<U: ?Sized>(self, origin: NonNull<U>) -> usize {
914        // SAFETY: the caller must uphold the safety contract for `byte_offset_from_unsigned`.
915        unsafe { self.as_ptr().byte_offset_from_unsigned(origin.as_ptr()) }
916    }
917
918    /// Reads the value from `self` without moving it. This leaves the
919    /// memory in `self` unchanged.
920    ///
921    /// See [`ptr::read`] for safety concerns and examples.
922    ///
923    /// [`ptr::read`]: crate::ptr::read()
924    #[inline]
925    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
926    #[stable(feature = "non_null_convenience", since = "1.80.0")]
927    #[rustc_const_stable(feature = "non_null_convenience", since = "1.80.0")]
928    pub const unsafe fn read(self) -> T
929    where
930        T: Sized,
931    {
932        // SAFETY: the caller must uphold the safety contract for `read`.
933        unsafe { ptr::read(self.as_ptr()) }
934    }
935
936    /// Performs a volatile read of the value from `self` without moving it. This
937    /// leaves the memory in `self` unchanged.
938    ///
939    /// Volatile operations are intended to act on I/O memory, and are guaranteed
940    /// to not be elided or reordered by the compiler across other volatile
941    /// operations.
942    ///
943    /// See [`ptr::read_volatile`] for safety concerns and examples.
944    ///
945    /// [`ptr::read_volatile`]: crate::ptr::read_volatile()
946    #[inline]
947    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
948    #[stable(feature = "non_null_convenience", since = "1.80.0")]
949    #[rustc_const_unstable(feature = "const_volatile", issue = "159094")]
950    pub const unsafe fn read_volatile(self) -> T
951    where
952        T: Sized,
953    {
954        // SAFETY: the caller must uphold the safety contract for `read_volatile`.
955        unsafe { ptr::read_volatile(self.as_ptr()) }
956    }
957
958    /// Reads the value from `self` without moving it. This leaves the
959    /// memory in `self` unchanged.
960    ///
961    /// Unlike `read`, the pointer may be unaligned.
962    ///
963    /// See [`ptr::read_unaligned`] for safety concerns and examples.
964    ///
965    /// [`ptr::read_unaligned`]: crate::ptr::read_unaligned()
966    #[inline]
967    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
968    #[stable(feature = "non_null_convenience", since = "1.80.0")]
969    #[rustc_const_stable(feature = "non_null_convenience", since = "1.80.0")]
970    pub const unsafe fn read_unaligned(self) -> T
971    where
972        T: Sized,
973    {
974        // SAFETY: the caller must uphold the safety contract for `read_unaligned`.
975        unsafe { ptr::read_unaligned(self.as_ptr()) }
976    }
977
978    /// Copies `count * size_of::<T>()` bytes from `self` to `dest`. The source
979    /// and destination may overlap.
980    ///
981    /// NOTE: this has the *same* argument order as [`ptr::copy`].
982    ///
983    /// See [`ptr::copy`] for safety concerns and examples.
984    ///
985    /// [`ptr::copy`]: crate::ptr::copy()
986    #[inline(always)]
987    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
988    #[stable(feature = "non_null_convenience", since = "1.80.0")]
989    #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.83.0")]
990    pub const unsafe fn copy_to(self, dest: NonNull<T>, count: usize)
991    where
992        T: Sized,
993    {
994        // SAFETY: the caller must uphold the safety contract for `copy`.
995        unsafe { ptr::copy(self.as_ptr(), dest.as_ptr(), count) }
996    }
997
998    /// Copies `count * size_of::<T>()` bytes from `self` to `dest`. The source
999    /// and destination may *not* overlap.
1000    ///
1001    /// NOTE: this has the *same* argument order as [`ptr::copy_nonoverlapping`].
1002    ///
1003    /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples.
1004    ///
1005    /// [`ptr::copy_nonoverlapping`]: crate::ptr::copy_nonoverlapping()
1006    #[inline(always)]
1007    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1008    #[stable(feature = "non_null_convenience", since = "1.80.0")]
1009    #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.83.0")]
1010    pub const unsafe fn copy_to_nonoverlapping(self, dest: NonNull<T>, count: usize)
1011    where
1012        T: Sized,
1013    {
1014        // SAFETY: the caller must uphold the safety contract for `copy_nonoverlapping`.
1015        unsafe { ptr::copy_nonoverlapping(self.as_ptr(), dest.as_ptr(), count) }
1016    }
1017
1018    /// Copies `count * size_of::<T>()` bytes from `src` to `self`. The source
1019    /// and destination may overlap.
1020    ///
1021    /// NOTE: this has the *opposite* argument order of [`ptr::copy`].
1022    ///
1023    /// See [`ptr::copy`] for safety concerns and examples.
1024    ///
1025    /// [`ptr::copy`]: crate::ptr::copy()
1026    #[inline(always)]
1027    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1028    #[stable(feature = "non_null_convenience", since = "1.80.0")]
1029    #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.83.0")]
1030    pub const unsafe fn copy_from(self, src: NonNull<T>, count: usize)
1031    where
1032        T: Sized,
1033    {
1034        // SAFETY: the caller must uphold the safety contract for `copy`.
1035        unsafe { ptr::copy(src.as_ptr(), self.as_ptr(), count) }
1036    }
1037
1038    /// Copies `count * size_of::<T>()` bytes from `src` to `self`. The source
1039    /// and destination may *not* overlap.
1040    ///
1041    /// NOTE: this has the *opposite* argument order of [`ptr::copy_nonoverlapping`].
1042    ///
1043    /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples.
1044    ///
1045    /// [`ptr::copy_nonoverlapping`]: crate::ptr::copy_nonoverlapping()
1046    #[inline(always)]
1047    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1048    #[stable(feature = "non_null_convenience", since = "1.80.0")]
1049    #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.83.0")]
1050    pub const unsafe fn copy_from_nonoverlapping(self, src: NonNull<T>, count: usize)
1051    where
1052        T: Sized,
1053    {
1054        // SAFETY: the caller must uphold the safety contract for `copy_nonoverlapping`.
1055        unsafe { ptr::copy_nonoverlapping(src.as_ptr(), self.as_ptr(), count) }
1056    }
1057
1058    /// Executes the destructor (if any) of the pointed-to value.
1059    ///
1060    /// See [`ptr::drop_in_place`] for safety concerns and examples.
1061    ///
1062    /// [`ptr::drop_in_place`]: crate::ptr::drop_in_place()
1063    #[inline(always)]
1064    #[stable(feature = "non_null_convenience", since = "1.80.0")]
1065    #[rustc_const_unstable(feature = "const_drop_in_place", issue = "109342")]
1066    pub const unsafe fn drop_in_place(mut self)
1067    where
1068        T: [const] Destruct,
1069    {
1070        // SAFETY: the caller must uphold the safety contract for `drop_in_place`.
1071        unsafe { ptr::drop_glue(self.as_mut()) }
1072    }
1073
1074    /// Overwrites a memory location with the given value without reading or
1075    /// dropping the old value.
1076    ///
1077    /// See [`ptr::write`] for safety concerns and examples.
1078    ///
1079    /// [`ptr::write`]: crate::ptr::write()
1080    #[inline(always)]
1081    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1082    #[stable(feature = "non_null_convenience", since = "1.80.0")]
1083    #[rustc_const_stable(feature = "const_ptr_write", since = "1.83.0")]
1084    pub const unsafe fn write(self, val: T)
1085    where
1086        T: Sized,
1087    {
1088        // SAFETY: the caller must uphold the safety contract for `write`.
1089        unsafe { ptr::write(self.as_ptr(), val) }
1090    }
1091
1092    /// Invokes memset on the specified pointer, setting `count * size_of::<T>()`
1093    /// bytes of memory starting at `self` to `val`.
1094    ///
1095    /// See [`ptr::write_bytes`] for safety concerns and examples.
1096    ///
1097    /// [`ptr::write_bytes`]: crate::ptr::write_bytes()
1098    #[inline(always)]
1099    #[doc(alias = "memset")]
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_ptr_write", since = "1.83.0")]
1103    pub const unsafe fn write_bytes(self, val: u8, count: usize)
1104    where
1105        T: Sized,
1106    {
1107        // SAFETY: the caller must uphold the safety contract for `write_bytes`.
1108        unsafe { ptr::write_bytes(self.as_ptr(), val, count) }
1109    }
1110
1111    /// Performs a volatile write of a memory location with the given value without
1112    /// reading or dropping the old value.
1113    ///
1114    /// Volatile operations are intended to act on I/O memory, and are guaranteed
1115    /// to not be elided or reordered by the compiler across other volatile
1116    /// operations.
1117    ///
1118    /// See [`ptr::write_volatile`] for safety concerns and examples.
1119    ///
1120    /// [`ptr::write_volatile`]: crate::ptr::write_volatile()
1121    #[inline(always)]
1122    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1123    #[stable(feature = "non_null_convenience", since = "1.80.0")]
1124    #[rustc_const_unstable(feature = "const_volatile", issue = "159094")]
1125    pub const unsafe fn write_volatile(self, val: T)
1126    where
1127        T: Sized,
1128    {
1129        // SAFETY: the caller must uphold the safety contract for `write_volatile`.
1130        unsafe { ptr::write_volatile(self.as_ptr(), val) }
1131    }
1132
1133    /// Overwrites a memory location with the given value without reading or
1134    /// dropping the old value.
1135    ///
1136    /// Unlike `write`, the pointer may be unaligned.
1137    ///
1138    /// See [`ptr::write_unaligned`] for safety concerns and examples.
1139    ///
1140    /// [`ptr::write_unaligned`]: crate::ptr::write_unaligned()
1141    #[inline(always)]
1142    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1143    #[stable(feature = "non_null_convenience", since = "1.80.0")]
1144    #[rustc_const_stable(feature = "const_ptr_write", since = "1.83.0")]
1145    pub const unsafe fn write_unaligned(self, val: T)
1146    where
1147        T: Sized,
1148    {
1149        // SAFETY: the caller must uphold the safety contract for `write_unaligned`.
1150        unsafe { ptr::write_unaligned(self.as_ptr(), val) }
1151    }
1152
1153    /// Replaces the value at `self` with `src`, returning the old
1154    /// value, without dropping either.
1155    ///
1156    /// See [`ptr::replace`] for safety concerns and examples.
1157    ///
1158    /// [`ptr::replace`]: crate::ptr::replace()
1159    #[inline(always)]
1160    #[stable(feature = "non_null_convenience", since = "1.80.0")]
1161    #[rustc_const_stable(feature = "const_inherent_ptr_replace", since = "1.88.0")]
1162    pub const unsafe fn replace(self, src: T) -> T
1163    where
1164        T: Sized,
1165    {
1166        // SAFETY: the caller must uphold the safety contract for `replace`.
1167        unsafe { ptr::replace(self.as_ptr(), src) }
1168    }
1169
1170    /// Swaps the values at two mutable locations of the same type, without
1171    /// deinitializing either. They may overlap, unlike `mem::swap` which is
1172    /// otherwise equivalent.
1173    ///
1174    /// See [`ptr::swap`] for safety concerns and examples.
1175    ///
1176    /// [`ptr::swap`]: crate::ptr::swap()
1177    #[inline(always)]
1178    #[stable(feature = "non_null_convenience", since = "1.80.0")]
1179    #[rustc_const_stable(feature = "const_swap", since = "1.85.0")]
1180    pub const unsafe fn swap(self, with: NonNull<T>)
1181    where
1182        T: Sized,
1183    {
1184        // SAFETY: the caller must uphold the safety contract for `swap`.
1185        unsafe { ptr::swap(self.as_ptr(), with.as_ptr()) }
1186    }
1187
1188    /// Computes the offset that needs to be applied to the pointer in order to make it aligned to
1189    /// `align`.
1190    ///
1191    /// If it is not possible to align the pointer, the implementation returns
1192    /// `usize::MAX`.
1193    ///
1194    /// The offset is expressed in number of `T` elements, and not bytes.
1195    ///
1196    /// There are no guarantees whatsoever that offsetting the pointer will not overflow or go
1197    /// beyond the allocation that the pointer points into. It is up to the caller to ensure that
1198    /// the returned offset is correct in all terms other than alignment.
1199    ///
1200    /// When this is called during compile-time evaluation (which is unstable), the implementation
1201    /// may return `usize::MAX` in cases where that can never happen at runtime. This is because the
1202    /// actual alignment of pointers is not known yet during compile-time, so an offset with
1203    /// guaranteed alignment can sometimes not be computed. For example, a buffer declared as `[u8;
1204    /// N]` might be allocated at an odd or an even address, but at compile-time this is not yet
1205    /// known, so the execution has to be correct for either choice. It is therefore impossible to
1206    /// find an offset that is guaranteed to be 2-aligned. (This behavior is subject to change, as usual
1207    /// for unstable APIs.)
1208    ///
1209    /// # Panics
1210    ///
1211    /// The function panics if `align` is not a power-of-two.
1212    ///
1213    /// # Examples
1214    ///
1215    /// Accessing adjacent `u8` as `u16`
1216    ///
1217    /// ```
1218    /// use std::ptr::NonNull;
1219    ///
1220    /// # unsafe {
1221    /// let x = [5_u8, 6, 7, 8, 9];
1222    /// let ptr = NonNull::new(x.as_ptr() as *mut u8).unwrap();
1223    /// let offset = ptr.align_offset(align_of::<u16>());
1224    ///
1225    /// if offset < x.len() - 1 {
1226    ///     let u16_ptr = ptr.add(offset).cast::<u16>();
1227    ///     assert!(u16_ptr.read() == u16::from_ne_bytes([5, 6]) || u16_ptr.read() == u16::from_ne_bytes([6, 7]));
1228    /// } else {
1229    ///     // while the pointer can be aligned via `offset`, it would point
1230    ///     // outside the allocation
1231    /// }
1232    /// # }
1233    /// ```
1234    #[inline]
1235    #[must_use]
1236    #[stable(feature = "non_null_convenience", since = "1.80.0")]
1237    pub fn align_offset(self, align: usize) -> usize
1238    where
1239        T: Sized,
1240    {
1241        if !align.is_power_of_two() {
1242            {
    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");
1243        }
1244
1245        {
1246            // SAFETY: `align` has been checked to be a power of 2 above.
1247            unsafe { ptr::align_offset(self.as_ptr(), align) }
1248        }
1249    }
1250
1251    /// Returns whether the pointer is properly aligned for `T`.
1252    ///
1253    /// # Examples
1254    ///
1255    /// ```
1256    /// use std::ptr::NonNull;
1257    ///
1258    /// // On some platforms, the alignment of i32 is less than 4.
1259    /// #[repr(align(4))]
1260    /// struct AlignedI32(i32);
1261    ///
1262    /// let data = AlignedI32(42);
1263    /// let ptr = NonNull::<AlignedI32>::from(&data);
1264    ///
1265    /// assert!(ptr.is_aligned());
1266    /// assert!(!NonNull::new(ptr.as_ptr().wrapping_byte_add(1)).unwrap().is_aligned());
1267    /// ```
1268    #[inline]
1269    #[must_use]
1270    #[stable(feature = "pointer_is_aligned", since = "1.79.0")]
1271    pub fn is_aligned(self) -> bool
1272    where
1273        T: Sized,
1274    {
1275        self.as_ptr().is_aligned()
1276    }
1277
1278    /// Returns whether the pointer is aligned to `align`.
1279    ///
1280    /// For non-`Sized` pointees this operation considers only the data pointer,
1281    /// ignoring the metadata.
1282    ///
1283    /// # Panics
1284    ///
1285    /// The function panics if `align` is not a power-of-two (this includes 0).
1286    ///
1287    /// # Examples
1288    ///
1289    /// ```
1290    /// #![feature(pointer_is_aligned_to)]
1291    ///
1292    /// // On some platforms, the alignment of i32 is less than 4.
1293    /// #[repr(align(4))]
1294    /// struct AlignedI32(i32);
1295    ///
1296    /// let data = AlignedI32(42);
1297    /// let ptr = &data as *const AlignedI32;
1298    ///
1299    /// assert!(ptr.is_aligned_to(1));
1300    /// assert!(ptr.is_aligned_to(2));
1301    /// assert!(ptr.is_aligned_to(4));
1302    ///
1303    /// assert!(ptr.wrapping_byte_add(2).is_aligned_to(2));
1304    /// assert!(!ptr.wrapping_byte_add(2).is_aligned_to(4));
1305    ///
1306    /// assert_ne!(ptr.is_aligned_to(8), ptr.wrapping_add(1).is_aligned_to(8));
1307    /// ```
1308    #[inline]
1309    #[must_use]
1310    #[unstable(feature = "pointer_is_aligned_to", issue = "96284")]
1311    pub fn is_aligned_to(self, align: usize) -> bool {
1312        self.as_ptr().is_aligned_to(align)
1313    }
1314}
1315
1316impl<T> NonNull<T> {
1317    /// Casts from a type to its maybe-uninitialized version.
1318    #[must_use]
1319    #[inline(always)]
1320    #[unstable(feature = "cast_maybe_uninit", issue = "145036")]
1321    pub const fn cast_uninit(self) -> NonNull<MaybeUninit<T>> {
1322        self.cast()
1323    }
1324
1325    /// Creates a non-null raw slice from a thin pointer and a length.
1326    ///
1327    /// The `len` argument is the number of **elements**, not the number of bytes.
1328    ///
1329    /// This function is safe, but dereferencing the return value is unsafe.
1330    /// See the documentation of [`slice::from_raw_parts`] for slice safety requirements.
1331    ///
1332    /// # Examples
1333    ///
1334    /// ```rust
1335    /// #![feature(ptr_cast_slice)]
1336    /// use std::ptr::NonNull;
1337    ///
1338    /// // create a slice pointer when starting out with a pointer to the first element
1339    /// let mut x = [5, 6, 7];
1340    /// let nonnull_pointer = NonNull::new(x.as_mut_ptr()).unwrap();
1341    /// let slice = nonnull_pointer.cast_slice(3);
1342    /// assert_eq!(unsafe { slice.as_ref()[2] }, 7);
1343    /// ```
1344    ///
1345    /// (Note that this example artificially demonstrates a use of this method,
1346    /// but `let slice = NonNull::from(&x[..]);` would be a better way to write code like this.)
1347    #[inline]
1348    #[must_use]
1349    #[unstable(feature = "ptr_cast_slice", issue = "149103")]
1350    pub const fn cast_slice(self, len: usize) -> NonNull<[T]> {
1351        NonNull::slice_from_raw_parts(self, len)
1352    }
1353}
1354impl<T> NonNull<MaybeUninit<T>> {
1355    /// Casts from a maybe-uninitialized type to its initialized version.
1356    ///
1357    /// This is always safe, since UB can only occur if the pointer is read
1358    /// before being initialized.
1359    #[must_use]
1360    #[inline(always)]
1361    #[unstable(feature = "cast_maybe_uninit", issue = "145036")]
1362    pub const fn cast_init(self) -> NonNull<T> {
1363        self.cast()
1364    }
1365}
1366
1367impl<T> NonNull<[T]> {
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    /// This function is safe, but dereferencing the return value is unsafe.
1373    /// See the documentation of [`slice::from_raw_parts`] for slice safety requirements.
1374    ///
1375    /// # Examples
1376    ///
1377    /// ```rust
1378    /// use std::ptr::NonNull;
1379    ///
1380    /// // create a slice pointer when starting out with a pointer to the first element
1381    /// let mut x = [5, 6, 7];
1382    /// let nonnull_pointer = NonNull::new(x.as_mut_ptr()).unwrap();
1383    /// let slice = NonNull::slice_from_raw_parts(nonnull_pointer, 3);
1384    /// assert_eq!(unsafe { slice.as_ref()[2] }, 7);
1385    /// ```
1386    ///
1387    /// (Note that this example artificially demonstrates a use of this method,
1388    /// but `let slice = NonNull::from(&x[..]);` would be a better way to write code like this.)
1389    #[stable(feature = "nonnull_slice_from_raw_parts", since = "1.70.0")]
1390    #[rustc_const_stable(feature = "const_slice_from_raw_parts_mut", since = "1.83.0")]
1391    #[must_use]
1392    #[inline]
1393    pub const fn slice_from_raw_parts(data: NonNull<T>, len: usize) -> Self {
1394        // SAFETY: `data` is a `NonNull` pointer which is necessarily non-null
1395        unsafe { Self::new_unchecked(data.as_ptr().cast_slice(len)) }
1396    }
1397
1398    /// Returns the length of a non-null raw slice.
1399    ///
1400    /// The returned value is the number of **elements**, not the number of bytes.
1401    ///
1402    /// This function is safe, even when the non-null raw slice cannot be dereferenced to a slice
1403    /// because the pointer does not have a valid address.
1404    ///
1405    /// # Examples
1406    ///
1407    /// ```rust
1408    /// use std::ptr::NonNull;
1409    ///
1410    /// let slice: NonNull<[i8]> = NonNull::slice_from_raw_parts(NonNull::dangling(), 3);
1411    /// assert_eq!(slice.len(), 3);
1412    /// ```
1413    #[stable(feature = "slice_ptr_len_nonnull", since = "1.63.0")]
1414    #[rustc_const_stable(feature = "const_slice_ptr_len_nonnull", since = "1.63.0")]
1415    #[must_use]
1416    #[inline]
1417    pub const fn len(self) -> usize {
1418        self.as_ptr().len()
1419    }
1420
1421    /// Returns `true` if the non-null raw slice has a length of 0.
1422    ///
1423    /// # Examples
1424    ///
1425    /// ```rust
1426    /// use std::ptr::NonNull;
1427    ///
1428    /// let slice: NonNull<[i8]> = NonNull::slice_from_raw_parts(NonNull::dangling(), 3);
1429    /// assert!(!slice.is_empty());
1430    /// ```
1431    #[stable(feature = "slice_ptr_is_empty_nonnull", since = "1.79.0")]
1432    #[rustc_const_stable(feature = "const_slice_ptr_is_empty_nonnull", since = "1.79.0")]
1433    #[must_use]
1434    #[inline]
1435    pub const fn is_empty(self) -> bool {
1436        self.len() == 0
1437    }
1438
1439    /// Returns a non-null pointer to the slice's buffer.
1440    ///
1441    /// # Examples
1442    ///
1443    /// ```rust
1444    /// #![feature(slice_ptr_get)]
1445    /// use std::ptr::NonNull;
1446    ///
1447    /// let slice: NonNull<[i8]> = NonNull::slice_from_raw_parts(NonNull::dangling(), 3);
1448    /// assert_eq!(slice.as_non_null_ptr(), NonNull::<i8>::dangling());
1449    /// ```
1450    #[inline]
1451    #[must_use]
1452    #[unstable(feature = "slice_ptr_get", issue = "74265")]
1453    pub const fn as_non_null_ptr(self) -> NonNull<T> {
1454        self.cast()
1455    }
1456
1457    /// Returns a raw pointer to the slice's buffer.
1458    ///
1459    /// # Examples
1460    ///
1461    /// ```rust
1462    /// #![feature(slice_ptr_get)]
1463    /// use std::ptr::NonNull;
1464    ///
1465    /// let slice: NonNull<[i8]> = NonNull::slice_from_raw_parts(NonNull::dangling(), 3);
1466    /// assert_eq!(slice.as_mut_ptr(), NonNull::<i8>::dangling().as_ptr());
1467    /// ```
1468    #[inline]
1469    #[must_use]
1470    #[unstable(feature = "slice_ptr_get", issue = "74265")]
1471    #[rustc_never_returns_null_ptr]
1472    pub const fn as_mut_ptr(self) -> *mut T {
1473        self.as_non_null_ptr().as_ptr()
1474    }
1475
1476    /// Returns a shared reference to a slice of possibly uninitialized values. In contrast to
1477    /// [`as_ref`], this does not require that the value has to be initialized.
1478    ///
1479    /// For the mutable counterpart see [`as_uninit_slice_mut`].
1480    ///
1481    /// [`as_ref`]: NonNull::as_ref
1482    /// [`as_uninit_slice_mut`]: NonNull::as_uninit_slice_mut
1483    ///
1484    /// # Safety
1485    ///
1486    /// When calling this method, you have to ensure that all of the following is true:
1487    ///
1488    /// * The pointer must be [valid] for reads for `ptr.len() * size_of::<T>()` many bytes,
1489    ///   and it must be properly aligned. This means in particular:
1490    ///
1491    ///     * The entire memory range of this slice must be contained within a single allocation!
1492    ///       Slices can never span across multiple allocations.
1493    ///
1494    ///     * The pointer must be aligned even for zero-length slices. One
1495    ///       reason for this is that enum layout optimizations may rely on references
1496    ///       (including slices of any length) being aligned and non-null to distinguish
1497    ///       them from other data. You can obtain a pointer that is usable as `data`
1498    ///       for zero-length slices using [`NonNull::dangling()`].
1499    ///
1500    /// * The total size `ptr.len() * size_of::<T>()` of the slice must be no larger than `isize::MAX`.
1501    ///   See the safety documentation of [`pointer::offset`].
1502    ///
1503    /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
1504    ///   arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
1505    ///   In particular, while this reference exists, the memory the pointer points to must
1506    ///   not get mutated (except inside `UnsafeCell`).
1507    ///
1508    /// This applies even if the result of this method is unused!
1509    ///
1510    /// See also [`slice::from_raw_parts`].
1511    ///
1512    /// [valid]: crate::ptr#safety
1513    #[inline]
1514    #[must_use]
1515    #[unstable(feature = "ptr_as_uninit", issue = "75402")]
1516    pub const unsafe fn as_uninit_slice<'a>(self) -> &'a [MaybeUninit<T>] {
1517        // SAFETY: the caller must uphold the safety contract for `as_uninit_slice`.
1518        unsafe { slice::from_raw_parts(self.cast().as_ptr(), self.len()) }
1519    }
1520
1521    /// Returns a unique reference to a slice of possibly uninitialized values. In contrast to
1522    /// [`as_mut`], this does not require that the value has to be initialized.
1523    ///
1524    /// For the shared counterpart see [`as_uninit_slice`].
1525    ///
1526    /// [`as_mut`]: NonNull::as_mut
1527    /// [`as_uninit_slice`]: NonNull::as_uninit_slice
1528    ///
1529    /// # Safety
1530    ///
1531    /// When calling this method, you have to ensure that all of the following is true:
1532    ///
1533    /// * The pointer must be [valid] for reads and writes for `ptr.len() * size_of::<T>()`
1534    ///   many bytes, and it must be properly aligned. This means in particular:
1535    ///
1536    ///     * The entire memory range of this slice must be contained within a single allocation!
1537    ///       Slices can never span across multiple allocations.
1538    ///
1539    ///     * The pointer must be aligned even for zero-length slices. One
1540    ///       reason for this is that enum layout optimizations may rely on references
1541    ///       (including slices of any length) being aligned and non-null to distinguish
1542    ///       them from other data. You can obtain a pointer that is usable as `data`
1543    ///       for zero-length slices using [`NonNull::dangling()`].
1544    ///
1545    /// * The total size `ptr.len() * size_of::<T>()` of the slice must be no larger than `isize::MAX`.
1546    ///   See the safety documentation of [`pointer::offset`].
1547    ///
1548    /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
1549    ///   arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
1550    ///   In particular, while this reference exists, the memory the pointer points to must
1551    ///   not get accessed (read or written) through any other pointer.
1552    ///
1553    /// This applies even if the result of this method is unused!
1554    ///
1555    /// See also [`slice::from_raw_parts_mut`].
1556    ///
1557    /// [valid]: crate::ptr#safety
1558    ///
1559    /// # Examples
1560    ///
1561    /// ```rust
1562    /// #![feature(ptr_as_uninit)]
1563    ///
1564    /// use std::alloc::{Allocator, Layout, Global};
1565    /// use std::mem::MaybeUninit;
1566    /// use std::ptr::NonNull;
1567    ///
1568    /// let memory: NonNull<[u8]> = Global.allocate(Layout::new::<[u8; 32]>())?;
1569    /// // This is safe as `memory` is valid for reads and writes for `memory.len()` many bytes.
1570    /// // Note that calling `memory.as_mut()` is not allowed here as the content may be uninitialized.
1571    /// # #[allow(unused_variables)]
1572    /// let slice: &mut [MaybeUninit<u8>] = unsafe { memory.as_uninit_slice_mut() };
1573    /// # // Prevent leaks for Miri.
1574    /// # unsafe { Global.deallocate(memory.cast(), Layout::new::<[u8; 32]>()); }
1575    /// # Ok::<_, std::alloc::AllocError>(())
1576    /// ```
1577    #[inline]
1578    #[must_use]
1579    #[unstable(feature = "ptr_as_uninit", issue = "75402")]
1580    pub const unsafe fn as_uninit_slice_mut<'a>(self) -> &'a mut [MaybeUninit<T>] {
1581        // SAFETY: the caller must uphold the safety contract for `as_uninit_slice_mut`.
1582        unsafe { slice::from_raw_parts_mut(self.cast().as_ptr(), self.len()) }
1583    }
1584
1585    /// Returns a raw pointer to an element or subslice, without doing bounds
1586    /// checking.
1587    ///
1588    /// Calling this method with an [out-of-bounds index] or when `self` is not dereferenceable
1589    /// is *[undefined behavior]* even if the resulting pointer is not used.
1590    ///
1591    /// [out-of-bounds index]: #method.add
1592    /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1593    ///
1594    /// # Examples
1595    ///
1596    /// ```
1597    /// #![feature(slice_ptr_get)]
1598    /// use std::ptr::NonNull;
1599    ///
1600    /// let x = &mut [1, 2, 4];
1601    /// let x = NonNull::slice_from_raw_parts(NonNull::new(x.as_mut_ptr()).unwrap(), x.len());
1602    ///
1603    /// unsafe {
1604    ///     assert_eq!(x.get_unchecked_mut(1).as_ptr(), x.as_non_null_ptr().as_ptr().add(1));
1605    /// }
1606    /// ```
1607    #[unstable(feature = "slice_ptr_get", issue = "74265")]
1608    #[rustc_const_unstable(feature = "const_index", issue = "143775")]
1609    #[inline]
1610    pub const unsafe fn get_unchecked_mut<I>(self, index: I) -> NonNull<I::Output>
1611    where
1612        I: [const] SliceIndex<[T]>,
1613    {
1614        // SAFETY: the caller ensures that `self` is dereferenceable and `index` in-bounds.
1615        // As a consequence, the resulting pointer cannot be null.
1616        unsafe { NonNull::new_unchecked(self.as_ptr().get_unchecked_mut(index)) }
1617    }
1618}
1619
1620#[stable(feature = "nonnull", since = "1.25.0")]
1621impl<T: PointeeSized> Clone for NonNull<T> {
1622    #[inline(always)]
1623    fn clone(&self) -> Self {
1624        *self
1625    }
1626}
1627
1628#[stable(feature = "nonnull", since = "1.25.0")]
1629impl<T: PointeeSized> Copy for NonNull<T> {}
1630
1631#[doc(hidden)]
1632#[unstable(feature = "trivial_clone", issue = "none")]
1633unsafe impl<T: PointeeSized> TrivialClone for NonNull<T> {}
1634
1635#[unstable(feature = "coerce_unsized", issue = "18598")]
1636impl<T: PointeeSized, U: PointeeSized> CoerceUnsized<NonNull<U>> for NonNull<T> where T: Unsize<U> {}
1637
1638#[unstable(feature = "dispatch_from_dyn", issue = "none")]
1639impl<T: PointeeSized, U: PointeeSized> DispatchFromDyn<NonNull<U>> for NonNull<T> where T: Unsize<U> {}
1640
1641#[stable(feature = "nonnull", since = "1.25.0")]
1642impl<T: PointeeSized> fmt::Debug for NonNull<T> {
1643    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1644        fmt::Pointer::fmt(&self.as_ptr(), f)
1645    }
1646}
1647
1648#[stable(feature = "nonnull", since = "1.25.0")]
1649impl<T: PointeeSized> fmt::Pointer for NonNull<T> {
1650    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1651        fmt::Pointer::fmt(&self.as_ptr(), f)
1652    }
1653}
1654
1655#[stable(feature = "nonnull", since = "1.25.0")]
1656impl<T: PointeeSized> Eq for NonNull<T> {}
1657
1658#[stable(feature = "nonnull", since = "1.25.0")]
1659impl<T: PointeeSized> PartialEq for NonNull<T> {
1660    #[inline]
1661    #[allow(ambiguous_wide_pointer_comparisons)]
1662    fn eq(&self, other: &Self) -> bool {
1663        self.as_ptr() == other.as_ptr()
1664    }
1665}
1666
1667#[stable(feature = "nonnull", since = "1.25.0")]
1668impl<T: PointeeSized> Ord for NonNull<T> {
1669    #[inline]
1670    #[allow(ambiguous_wide_pointer_comparisons)]
1671    fn cmp(&self, other: &Self) -> Ordering {
1672        self.as_ptr().cmp(&other.as_ptr())
1673    }
1674}
1675
1676#[stable(feature = "nonnull", since = "1.25.0")]
1677impl<T: PointeeSized> PartialOrd for NonNull<T> {
1678    #[inline]
1679    #[allow(ambiguous_wide_pointer_comparisons)]
1680    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1681        self.as_ptr().partial_cmp(&other.as_ptr())
1682    }
1683}
1684
1685#[stable(feature = "nonnull", since = "1.25.0")]
1686impl<T: PointeeSized> hash::Hash for NonNull<T> {
1687    #[inline]
1688    fn hash<H: hash::Hasher>(&self, state: &mut H) {
1689        self.as_ptr().hash(state)
1690    }
1691}
1692
1693#[stable(feature = "nonnull", since = "1.25.0")]
1694#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
1695const impl<T: PointeeSized> From<&mut T> for NonNull<T> {
1696    /// Converts a `&mut T` to a `NonNull<T>`.
1697    ///
1698    /// This conversion is safe and infallible since references cannot be null.
1699    #[inline]
1700    fn from(r: &mut T) -> Self {
1701        NonNull::from_mut(r)
1702    }
1703}
1704
1705#[stable(feature = "nonnull", since = "1.25.0")]
1706#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
1707const impl<T: PointeeSized> From<&T> for NonNull<T> {
1708    /// Converts a `&T` to a `NonNull<T>`.
1709    ///
1710    /// This conversion is safe and infallible since references cannot be null.
1711    #[inline]
1712    fn from(r: &T) -> Self {
1713        NonNull::from_ref(r)
1714    }
1715}