core/ptr/
non_null.rs

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