Skip to main content

core/ptr/
non_null.rs

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