core/ptr/
non_null.rs

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