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