]> git.lizzy.rs Git - rust.git/blob - library/core/src/ptr/non_null.rs
Rollup merge of #105973 - oli-obk:simplify_callee_checks, r=jackh726
[rust.git] / library / core / src / ptr / non_null.rs
1 use crate::cmp::Ordering;
2 use crate::convert::From;
3 use crate::fmt;
4 use crate::hash;
5 use crate::intrinsics::assert_unsafe_precondition;
6 use crate::marker::Unsize;
7 use crate::mem::{self, MaybeUninit};
8 use crate::num::NonZeroUsize;
9 use crate::ops::{CoerceUnsized, DispatchFromDyn};
10 use crate::ptr::Unique;
11 use crate::slice::{self, SliceIndex};
12
13 /// `*mut T` but non-zero and [covariant].
14 ///
15 /// This is often the correct thing to use when building data structures using
16 /// raw pointers, but is ultimately more dangerous to use because of its additional
17 /// properties. If you're not sure if you should use `NonNull<T>`, just use `*mut T`!
18 ///
19 /// Unlike `*mut T`, the pointer must always be non-null, even if the pointer
20 /// is never dereferenced. This is so that enums may use this forbidden value
21 /// as a discriminant -- `Option<NonNull<T>>` has the same size as `*mut T`.
22 /// However the pointer may still dangle if it isn't dereferenced.
23 ///
24 /// Unlike `*mut T`, `NonNull<T>` was chosen to be covariant over `T`. This makes it
25 /// possible to use `NonNull<T>` when building covariant types, but introduces the
26 /// risk of unsoundness if used in a type that shouldn't actually be covariant.
27 /// (The opposite choice was made for `*mut T` even though technically the unsoundness
28 /// could only be caused by calling unsafe functions.)
29 ///
30 /// Covariance is correct for most safe abstractions, such as `Box`, `Rc`, `Arc`, `Vec`,
31 /// and `LinkedList`. This is the case because they provide a public API that follows the
32 /// normal shared XOR mutable rules of Rust.
33 ///
34 /// If your type cannot safely be covariant, you must ensure it contains some
35 /// additional field to provide invariance. Often this field will be a [`PhantomData`]
36 /// type like `PhantomData<Cell<T>>` or `PhantomData<&'a mut T>`.
37 ///
38 /// Notice that `NonNull<T>` has a `From` instance for `&T`. However, this does
39 /// not change the fact that mutating through a (pointer derived from a) shared
40 /// reference is undefined behavior unless the mutation happens inside an
41 /// [`UnsafeCell<T>`]. The same goes for creating a mutable reference from a shared
42 /// reference. When using this `From` instance without an `UnsafeCell<T>`,
43 /// it is your responsibility to ensure that `as_mut` is never called, and `as_ptr`
44 /// is never used for mutation.
45 ///
46 /// [covariant]: https://doc.rust-lang.org/reference/subtyping.html
47 /// [`PhantomData`]: crate::marker::PhantomData
48 /// [`UnsafeCell<T>`]: crate::cell::UnsafeCell
49 #[stable(feature = "nonnull", since = "1.25.0")]
50 #[repr(transparent)]
51 #[rustc_layout_scalar_valid_range_start(1)]
52 #[rustc_nonnull_optimization_guaranteed]
53 pub struct NonNull<T: ?Sized> {
54     pointer: *const T,
55 }
56
57 /// `NonNull` pointers are not `Send` because the data they reference may be aliased.
58 // N.B., this impl is unnecessary, but should provide better error messages.
59 #[stable(feature = "nonnull", since = "1.25.0")]
60 impl<T: ?Sized> !Send for NonNull<T> {}
61
62 /// `NonNull` pointers are not `Sync` because the data they reference may be aliased.
63 // N.B., this impl is unnecessary, but should provide better error messages.
64 #[stable(feature = "nonnull", since = "1.25.0")]
65 impl<T: ?Sized> !Sync for NonNull<T> {}
66
67 impl<T: Sized> NonNull<T> {
68     /// Creates a new `NonNull` that is dangling, but well-aligned.
69     ///
70     /// This is useful for initializing types which lazily allocate, like
71     /// `Vec::new` does.
72     ///
73     /// Note that the pointer value may potentially represent a valid pointer to
74     /// a `T`, which means this must not be used as a "not yet initialized"
75     /// sentinel value. Types that lazily allocate must track initialization by
76     /// some other means.
77     ///
78     /// # Examples
79     ///
80     /// ```
81     /// use std::ptr::NonNull;
82     ///
83     /// let ptr = NonNull::<u32>::dangling();
84     /// // Important: don't try to access the value of `ptr` without
85     /// // initializing it first! The pointer is not null but isn't valid either!
86     /// ```
87     #[stable(feature = "nonnull", since = "1.25.0")]
88     #[rustc_const_stable(feature = "const_nonnull_dangling", since = "1.36.0")]
89     #[must_use]
90     #[inline]
91     pub const fn dangling() -> Self {
92         // SAFETY: mem::align_of() returns a non-zero usize which is then casted
93         // to a *mut T. Therefore, `ptr` is not null and the conditions for
94         // calling new_unchecked() are respected.
95         unsafe {
96             let ptr = crate::ptr::invalid_mut::<T>(mem::align_of::<T>());
97             NonNull::new_unchecked(ptr)
98         }
99     }
100
101     /// Returns a shared references to the value. In contrast to [`as_ref`], this does not require
102     /// that the value has to be initialized.
103     ///
104     /// For the mutable counterpart see [`as_uninit_mut`].
105     ///
106     /// [`as_ref`]: NonNull::as_ref
107     /// [`as_uninit_mut`]: NonNull::as_uninit_mut
108     ///
109     /// # Safety
110     ///
111     /// When calling this method, you have to ensure that all of the following is true:
112     ///
113     /// * The pointer must be properly aligned.
114     ///
115     /// * It must be "dereferenceable" in the sense defined in [the module documentation].
116     ///
117     /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
118     ///   arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
119     ///   In particular, while this reference exists, the memory the pointer points to must
120     ///   not get mutated (except inside `UnsafeCell`).
121     ///
122     /// This applies even if the result of this method is unused!
123     ///
124     /// [the module documentation]: crate::ptr#safety
125     #[inline]
126     #[must_use]
127     #[unstable(feature = "ptr_as_uninit", issue = "75402")]
128     #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")]
129     pub const unsafe fn as_uninit_ref<'a>(self) -> &'a MaybeUninit<T> {
130         // SAFETY: the caller must guarantee that `self` meets all the
131         // requirements for a reference.
132         unsafe { &*self.cast().as_ptr() }
133     }
134
135     /// Returns a unique references to the value. In contrast to [`as_mut`], this does not require
136     /// that the value has to be initialized.
137     ///
138     /// For the shared counterpart see [`as_uninit_ref`].
139     ///
140     /// [`as_mut`]: NonNull::as_mut
141     /// [`as_uninit_ref`]: NonNull::as_uninit_ref
142     ///
143     /// # Safety
144     ///
145     /// When calling this method, you have to ensure that all of the following is true:
146     ///
147     /// * The pointer must be properly aligned.
148     ///
149     /// * It must be "dereferenceable" in the sense defined in [the module documentation].
150     ///
151     /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
152     ///   arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
153     ///   In particular, while this reference exists, the memory the pointer points to must
154     ///   not get accessed (read or written) through any other pointer.
155     ///
156     /// This applies even if the result of this method is unused!
157     ///
158     /// [the module documentation]: crate::ptr#safety
159     #[inline]
160     #[must_use]
161     #[unstable(feature = "ptr_as_uninit", issue = "75402")]
162     #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")]
163     pub const unsafe fn as_uninit_mut<'a>(self) -> &'a mut MaybeUninit<T> {
164         // SAFETY: the caller must guarantee that `self` meets all the
165         // requirements for a reference.
166         unsafe { &mut *self.cast().as_ptr() }
167     }
168 }
169
170 impl<T: ?Sized> NonNull<T> {
171     /// Creates a new `NonNull`.
172     ///
173     /// # Safety
174     ///
175     /// `ptr` must be non-null.
176     ///
177     /// # Examples
178     ///
179     /// ```
180     /// use std::ptr::NonNull;
181     ///
182     /// let mut x = 0u32;
183     /// let ptr = unsafe { NonNull::new_unchecked(&mut x as *mut _) };
184     /// ```
185     ///
186     /// *Incorrect* usage of this function:
187     ///
188     /// ```rust,no_run
189     /// use std::ptr::NonNull;
190     ///
191     /// // NEVER DO THAT!!! This is undefined behavior. ⚠️
192     /// let ptr = unsafe { NonNull::<u32>::new_unchecked(std::ptr::null_mut()) };
193     /// ```
194     #[stable(feature = "nonnull", since = "1.25.0")]
195     #[rustc_const_stable(feature = "const_nonnull_new_unchecked", since = "1.25.0")]
196     #[inline]
197     pub const unsafe fn new_unchecked(ptr: *mut T) -> Self {
198         // SAFETY: the caller must guarantee that `ptr` is non-null.
199         unsafe {
200             assert_unsafe_precondition!("NonNull::new_unchecked requires that the pointer is non-null", [T: ?Sized](ptr: *mut T) => !ptr.is_null());
201             NonNull { pointer: ptr as _ }
202         }
203     }
204
205     /// Creates a new `NonNull` if `ptr` is non-null.
206     ///
207     /// # Examples
208     ///
209     /// ```
210     /// use std::ptr::NonNull;
211     ///
212     /// let mut x = 0u32;
213     /// let ptr = NonNull::<u32>::new(&mut x as *mut _).expect("ptr is null!");
214     ///
215     /// if let Some(ptr) = NonNull::<u32>::new(std::ptr::null_mut()) {
216     ///     unreachable!();
217     /// }
218     /// ```
219     #[stable(feature = "nonnull", since = "1.25.0")]
220     #[rustc_const_unstable(feature = "const_nonnull_new", issue = "93235")]
221     #[inline]
222     pub const fn new(ptr: *mut T) -> Option<Self> {
223         if !ptr.is_null() {
224             // SAFETY: The pointer is already checked and is not null
225             Some(unsafe { Self::new_unchecked(ptr) })
226         } else {
227             None
228         }
229     }
230
231     /// Performs the same functionality as [`std::ptr::from_raw_parts`], except that a
232     /// `NonNull` pointer is returned, as opposed to a raw `*const` pointer.
233     ///
234     /// See the documentation of [`std::ptr::from_raw_parts`] for more details.
235     ///
236     /// [`std::ptr::from_raw_parts`]: crate::ptr::from_raw_parts
237     #[unstable(feature = "ptr_metadata", issue = "81513")]
238     #[rustc_const_unstable(feature = "ptr_metadata", issue = "81513")]
239     #[inline]
240     pub const fn from_raw_parts(
241         data_address: NonNull<()>,
242         metadata: <T as super::Pointee>::Metadata,
243     ) -> NonNull<T> {
244         // SAFETY: The result of `ptr::from::raw_parts_mut` is non-null because `data_address` is.
245         unsafe {
246             NonNull::new_unchecked(super::from_raw_parts_mut(data_address.as_ptr(), metadata))
247         }
248     }
249
250     /// Decompose a (possibly wide) pointer into its address and metadata components.
251     ///
252     /// The pointer can be later reconstructed with [`NonNull::from_raw_parts`].
253     #[unstable(feature = "ptr_metadata", issue = "81513")]
254     #[rustc_const_unstable(feature = "ptr_metadata", issue = "81513")]
255     #[must_use = "this returns the result of the operation, \
256                   without modifying the original"]
257     #[inline]
258     pub const fn to_raw_parts(self) -> (NonNull<()>, <T as super::Pointee>::Metadata) {
259         (self.cast(), super::metadata(self.as_ptr()))
260     }
261
262     /// Gets the "address" portion of the pointer.
263     ///
264     /// For more details see the equivalent method on a raw pointer, [`pointer::addr`].
265     ///
266     /// This API and its claimed semantics are part of the Strict Provenance experiment,
267     /// see the [`ptr` module documentation][crate::ptr].
268     #[must_use]
269     #[inline]
270     #[unstable(feature = "strict_provenance", issue = "95228")]
271     pub fn addr(self) -> NonZeroUsize
272     where
273         T: Sized,
274     {
275         // SAFETY: The pointer is guaranteed by the type to be non-null,
276         // meaning that the address will be non-zero.
277         unsafe { NonZeroUsize::new_unchecked(self.pointer.addr()) }
278     }
279
280     /// Creates a new pointer with the given address.
281     ///
282     /// For more details see the equivalent method on a raw pointer, [`pointer::with_addr`].
283     ///
284     /// This API and its claimed semantics are part of the Strict Provenance experiment,
285     /// see the [`ptr` module documentation][crate::ptr].
286     #[must_use]
287     #[inline]
288     #[unstable(feature = "strict_provenance", issue = "95228")]
289     pub fn with_addr(self, addr: NonZeroUsize) -> Self
290     where
291         T: Sized,
292     {
293         // SAFETY: The result of `ptr::from::with_addr` is non-null because `addr` is guaranteed to be non-zero.
294         unsafe { NonNull::new_unchecked(self.pointer.with_addr(addr.get()) as *mut _) }
295     }
296
297     /// Creates a new pointer by mapping `self`'s address to a new one.
298     ///
299     /// For more details see the equivalent method on a raw pointer, [`pointer::map_addr`].
300     ///
301     /// This API and its claimed semantics are part of the Strict Provenance experiment,
302     /// see the [`ptr` module documentation][crate::ptr].
303     #[must_use]
304     #[inline]
305     #[unstable(feature = "strict_provenance", issue = "95228")]
306     pub fn map_addr(self, f: impl FnOnce(NonZeroUsize) -> NonZeroUsize) -> Self
307     where
308         T: Sized,
309     {
310         self.with_addr(f(self.addr()))
311     }
312
313     /// Acquires the underlying `*mut` pointer.
314     ///
315     /// # Examples
316     ///
317     /// ```
318     /// use std::ptr::NonNull;
319     ///
320     /// let mut x = 0u32;
321     /// let ptr = NonNull::new(&mut x).expect("ptr is null!");
322     ///
323     /// let x_value = unsafe { *ptr.as_ptr() };
324     /// assert_eq!(x_value, 0);
325     ///
326     /// unsafe { *ptr.as_ptr() += 2; }
327     /// let x_value = unsafe { *ptr.as_ptr() };
328     /// assert_eq!(x_value, 2);
329     /// ```
330     #[stable(feature = "nonnull", since = "1.25.0")]
331     #[rustc_const_stable(feature = "const_nonnull_as_ptr", since = "1.32.0")]
332     #[must_use]
333     #[inline(always)]
334     pub const fn as_ptr(self) -> *mut T {
335         self.pointer as *mut T
336     }
337
338     /// Returns a shared reference to the value. If the value may be uninitialized, [`as_uninit_ref`]
339     /// must be used instead.
340     ///
341     /// For the mutable counterpart see [`as_mut`].
342     ///
343     /// [`as_uninit_ref`]: NonNull::as_uninit_ref
344     /// [`as_mut`]: NonNull::as_mut
345     ///
346     /// # Safety
347     ///
348     /// When calling this method, you have to ensure that all of the following is true:
349     ///
350     /// * The pointer must be properly aligned.
351     ///
352     /// * It must be "dereferenceable" in the sense defined in [the module documentation].
353     ///
354     /// * The pointer must point to an initialized instance of `T`.
355     ///
356     /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
357     ///   arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
358     ///   In particular, while this reference exists, the memory the pointer points to must
359     ///   not get mutated (except inside `UnsafeCell`).
360     ///
361     /// This applies even if the result of this method is unused!
362     /// (The part about being initialized is not yet fully decided, but until
363     /// it is, the only safe approach is to ensure that they are indeed initialized.)
364     ///
365     /// # Examples
366     ///
367     /// ```
368     /// use std::ptr::NonNull;
369     ///
370     /// let mut x = 0u32;
371     /// let ptr = NonNull::new(&mut x as *mut _).expect("ptr is null!");
372     ///
373     /// let ref_x = unsafe { ptr.as_ref() };
374     /// println!("{ref_x}");
375     /// ```
376     ///
377     /// [the module documentation]: crate::ptr#safety
378     #[stable(feature = "nonnull", since = "1.25.0")]
379     #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")]
380     #[must_use]
381     #[inline(always)]
382     pub const unsafe fn as_ref<'a>(&self) -> &'a T {
383         // SAFETY: the caller must guarantee that `self` meets all the
384         // requirements for a reference.
385         unsafe { &*self.as_ptr() }
386     }
387
388     /// Returns a unique reference to the value. If the value may be uninitialized, [`as_uninit_mut`]
389     /// must be used instead.
390     ///
391     /// For the shared counterpart see [`as_ref`].
392     ///
393     /// [`as_uninit_mut`]: NonNull::as_uninit_mut
394     /// [`as_ref`]: NonNull::as_ref
395     ///
396     /// # Safety
397     ///
398     /// When calling this method, you have to ensure that all of the following is true:
399     ///
400     /// * The pointer must be properly aligned.
401     ///
402     /// * It must be "dereferenceable" in the sense defined in [the module documentation].
403     ///
404     /// * The pointer must point to an initialized instance of `T`.
405     ///
406     /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
407     ///   arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
408     ///   In particular, while this reference exists, the memory the pointer points to must
409     ///   not get accessed (read or written) through any other pointer.
410     ///
411     /// This applies even if the result of this method is unused!
412     /// (The part about being initialized is not yet fully decided, but until
413     /// it is, the only safe approach is to ensure that they are indeed initialized.)
414     /// # Examples
415     ///
416     /// ```
417     /// use std::ptr::NonNull;
418     ///
419     /// let mut x = 0u32;
420     /// let mut ptr = NonNull::new(&mut x).expect("null pointer");
421     ///
422     /// let x_ref = unsafe { ptr.as_mut() };
423     /// assert_eq!(*x_ref, 0);
424     /// *x_ref += 2;
425     /// assert_eq!(*x_ref, 2);
426     /// ```
427     ///
428     /// [the module documentation]: crate::ptr#safety
429     #[stable(feature = "nonnull", since = "1.25.0")]
430     #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")]
431     #[must_use]
432     #[inline(always)]
433     pub const unsafe fn as_mut<'a>(&mut self) -> &'a mut T {
434         // SAFETY: the caller must guarantee that `self` meets all the
435         // requirements for a mutable reference.
436         unsafe { &mut *self.as_ptr() }
437     }
438
439     /// Casts to a pointer of another type.
440     ///
441     /// # Examples
442     ///
443     /// ```
444     /// use std::ptr::NonNull;
445     ///
446     /// let mut x = 0u32;
447     /// let ptr = NonNull::new(&mut x as *mut _).expect("null pointer");
448     ///
449     /// let casted_ptr = ptr.cast::<i8>();
450     /// let raw_ptr: *mut i8 = casted_ptr.as_ptr();
451     /// ```
452     #[stable(feature = "nonnull_cast", since = "1.27.0")]
453     #[rustc_const_stable(feature = "const_nonnull_cast", since = "1.36.0")]
454     #[must_use = "this returns the result of the operation, \
455                   without modifying the original"]
456     #[inline]
457     pub const fn cast<U>(self) -> NonNull<U> {
458         // SAFETY: `self` is a `NonNull` pointer which is necessarily non-null
459         unsafe { NonNull::new_unchecked(self.as_ptr() as *mut U) }
460     }
461 }
462
463 impl<T> NonNull<[T]> {
464     /// Creates a non-null raw slice from a thin pointer and a length.
465     ///
466     /// The `len` argument is the number of **elements**, not the number of bytes.
467     ///
468     /// This function is safe, but dereferencing the return value is unsafe.
469     /// See the documentation of [`slice::from_raw_parts`] for slice safety requirements.
470     ///
471     /// # Examples
472     ///
473     /// ```rust
474     /// #![feature(nonnull_slice_from_raw_parts)]
475     ///
476     /// use std::ptr::NonNull;
477     ///
478     /// // create a slice pointer when starting out with a pointer to the first element
479     /// let mut x = [5, 6, 7];
480     /// let nonnull_pointer = NonNull::new(x.as_mut_ptr()).unwrap();
481     /// let slice = NonNull::slice_from_raw_parts(nonnull_pointer, 3);
482     /// assert_eq!(unsafe { slice.as_ref()[2] }, 7);
483     /// ```
484     ///
485     /// (Note that this example artificially demonstrates a use of this method,
486     /// but `let slice = NonNull::from(&x[..]);` would be a better way to write code like this.)
487     #[unstable(feature = "nonnull_slice_from_raw_parts", issue = "71941")]
488     #[rustc_const_unstable(feature = "const_nonnull_slice_from_raw_parts", issue = "71941")]
489     #[must_use]
490     #[inline]
491     pub const fn slice_from_raw_parts(data: NonNull<T>, len: usize) -> Self {
492         // SAFETY: `data` is a `NonNull` pointer which is necessarily non-null
493         unsafe { Self::new_unchecked(super::slice_from_raw_parts_mut(data.as_ptr(), len)) }
494     }
495
496     /// Returns the length of a non-null raw slice.
497     ///
498     /// The returned value is the number of **elements**, not the number of bytes.
499     ///
500     /// This function is safe, even when the non-null raw slice cannot be dereferenced to a slice
501     /// because the pointer does not have a valid address.
502     ///
503     /// # Examples
504     ///
505     /// ```rust
506     /// #![feature(nonnull_slice_from_raw_parts)]
507     /// use std::ptr::NonNull;
508     ///
509     /// let slice: NonNull<[i8]> = NonNull::slice_from_raw_parts(NonNull::dangling(), 3);
510     /// assert_eq!(slice.len(), 3);
511     /// ```
512     #[stable(feature = "slice_ptr_len_nonnull", since = "1.63.0")]
513     #[rustc_const_stable(feature = "const_slice_ptr_len_nonnull", since = "1.63.0")]
514     #[rustc_allow_const_fn_unstable(const_slice_ptr_len)]
515     #[must_use]
516     #[inline]
517     pub const fn len(self) -> usize {
518         self.as_ptr().len()
519     }
520
521     /// Returns a non-null pointer to the slice's buffer.
522     ///
523     /// # Examples
524     ///
525     /// ```rust
526     /// #![feature(slice_ptr_get, nonnull_slice_from_raw_parts)]
527     /// use std::ptr::NonNull;
528     ///
529     /// let slice: NonNull<[i8]> = NonNull::slice_from_raw_parts(NonNull::dangling(), 3);
530     /// assert_eq!(slice.as_non_null_ptr(), NonNull::<i8>::dangling());
531     /// ```
532     #[inline]
533     #[must_use]
534     #[unstable(feature = "slice_ptr_get", issue = "74265")]
535     #[rustc_const_unstable(feature = "slice_ptr_get", issue = "74265")]
536     pub const fn as_non_null_ptr(self) -> NonNull<T> {
537         // SAFETY: We know `self` is non-null.
538         unsafe { NonNull::new_unchecked(self.as_ptr().as_mut_ptr()) }
539     }
540
541     /// Returns a raw pointer to the slice's buffer.
542     ///
543     /// # Examples
544     ///
545     /// ```rust
546     /// #![feature(slice_ptr_get, nonnull_slice_from_raw_parts)]
547     /// use std::ptr::NonNull;
548     ///
549     /// let slice: NonNull<[i8]> = NonNull::slice_from_raw_parts(NonNull::dangling(), 3);
550     /// assert_eq!(slice.as_mut_ptr(), NonNull::<i8>::dangling().as_ptr());
551     /// ```
552     #[inline]
553     #[must_use]
554     #[unstable(feature = "slice_ptr_get", issue = "74265")]
555     #[rustc_const_unstable(feature = "slice_ptr_get", issue = "74265")]
556     pub const fn as_mut_ptr(self) -> *mut T {
557         self.as_non_null_ptr().as_ptr()
558     }
559
560     /// Returns a shared reference to a slice of possibly uninitialized values. In contrast to
561     /// [`as_ref`], this does not require that the value has to be initialized.
562     ///
563     /// For the mutable counterpart see [`as_uninit_slice_mut`].
564     ///
565     /// [`as_ref`]: NonNull::as_ref
566     /// [`as_uninit_slice_mut`]: NonNull::as_uninit_slice_mut
567     ///
568     /// # Safety
569     ///
570     /// When calling this method, you have to ensure that all of the following is true:
571     ///
572     /// * The pointer must be [valid] for reads for `ptr.len() * mem::size_of::<T>()` many bytes,
573     ///   and it must be properly aligned. This means in particular:
574     ///
575     ///     * The entire memory range of this slice must be contained within a single allocated object!
576     ///       Slices can never span across multiple allocated objects.
577     ///
578     ///     * The pointer must be aligned even for zero-length slices. One
579     ///       reason for this is that enum layout optimizations may rely on references
580     ///       (including slices of any length) being aligned and non-null to distinguish
581     ///       them from other data. You can obtain a pointer that is usable as `data`
582     ///       for zero-length slices using [`NonNull::dangling()`].
583     ///
584     /// * The total size `ptr.len() * mem::size_of::<T>()` of the slice must be no larger than `isize::MAX`.
585     ///   See the safety documentation of [`pointer::offset`].
586     ///
587     /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
588     ///   arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
589     ///   In particular, while this reference exists, the memory the pointer points to must
590     ///   not get mutated (except inside `UnsafeCell`).
591     ///
592     /// This applies even if the result of this method is unused!
593     ///
594     /// See also [`slice::from_raw_parts`].
595     ///
596     /// [valid]: crate::ptr#safety
597     #[inline]
598     #[must_use]
599     #[unstable(feature = "ptr_as_uninit", issue = "75402")]
600     #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")]
601     pub const unsafe fn as_uninit_slice<'a>(self) -> &'a [MaybeUninit<T>] {
602         // SAFETY: the caller must uphold the safety contract for `as_uninit_slice`.
603         unsafe { slice::from_raw_parts(self.cast().as_ptr(), self.len()) }
604     }
605
606     /// Returns a unique reference to a slice of possibly uninitialized values. In contrast to
607     /// [`as_mut`], this does not require that the value has to be initialized.
608     ///
609     /// For the shared counterpart see [`as_uninit_slice`].
610     ///
611     /// [`as_mut`]: NonNull::as_mut
612     /// [`as_uninit_slice`]: NonNull::as_uninit_slice
613     ///
614     /// # Safety
615     ///
616     /// When calling this method, you have to ensure that all of the following is true:
617     ///
618     /// * The pointer must be [valid] for reads and writes for `ptr.len() * mem::size_of::<T>()`
619     ///   many bytes, and it must be properly aligned. This means in particular:
620     ///
621     ///     * The entire memory range of this slice must be contained within a single allocated object!
622     ///       Slices can never span across multiple allocated objects.
623     ///
624     ///     * The pointer must be aligned even for zero-length slices. One
625     ///       reason for this is that enum layout optimizations may rely on references
626     ///       (including slices of any length) being aligned and non-null to distinguish
627     ///       them from other data. You can obtain a pointer that is usable as `data`
628     ///       for zero-length slices using [`NonNull::dangling()`].
629     ///
630     /// * The total size `ptr.len() * mem::size_of::<T>()` of the slice must be no larger than `isize::MAX`.
631     ///   See the safety documentation of [`pointer::offset`].
632     ///
633     /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
634     ///   arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
635     ///   In particular, while this reference exists, the memory the pointer points to must
636     ///   not get accessed (read or written) through any other pointer.
637     ///
638     /// This applies even if the result of this method is unused!
639     ///
640     /// See also [`slice::from_raw_parts_mut`].
641     ///
642     /// [valid]: crate::ptr#safety
643     ///
644     /// # Examples
645     ///
646     /// ```rust
647     /// #![feature(allocator_api, ptr_as_uninit)]
648     ///
649     /// use std::alloc::{Allocator, Layout, Global};
650     /// use std::mem::MaybeUninit;
651     /// use std::ptr::NonNull;
652     ///
653     /// let memory: NonNull<[u8]> = Global.allocate(Layout::new::<[u8; 32]>())?;
654     /// // This is safe as `memory` is valid for reads and writes for `memory.len()` many bytes.
655     /// // Note that calling `memory.as_mut()` is not allowed here as the content may be uninitialized.
656     /// # #[allow(unused_variables)]
657     /// let slice: &mut [MaybeUninit<u8>] = unsafe { memory.as_uninit_slice_mut() };
658     /// # Ok::<_, std::alloc::AllocError>(())
659     /// ```
660     #[inline]
661     #[must_use]
662     #[unstable(feature = "ptr_as_uninit", issue = "75402")]
663     #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")]
664     pub const unsafe fn as_uninit_slice_mut<'a>(self) -> &'a mut [MaybeUninit<T>] {
665         // SAFETY: the caller must uphold the safety contract for `as_uninit_slice_mut`.
666         unsafe { slice::from_raw_parts_mut(self.cast().as_ptr(), self.len()) }
667     }
668
669     /// Returns a raw pointer to an element or subslice, without doing bounds
670     /// checking.
671     ///
672     /// Calling this method with an out-of-bounds index or when `self` is not dereferenceable
673     /// is *[undefined behavior]* even if the resulting pointer is not used.
674     ///
675     /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
676     ///
677     /// # Examples
678     ///
679     /// ```
680     /// #![feature(slice_ptr_get, nonnull_slice_from_raw_parts)]
681     /// use std::ptr::NonNull;
682     ///
683     /// let x = &mut [1, 2, 4];
684     /// let x = NonNull::slice_from_raw_parts(NonNull::new(x.as_mut_ptr()).unwrap(), x.len());
685     ///
686     /// unsafe {
687     ///     assert_eq!(x.get_unchecked_mut(1).as_ptr(), x.as_non_null_ptr().as_ptr().add(1));
688     /// }
689     /// ```
690     #[unstable(feature = "slice_ptr_get", issue = "74265")]
691     #[rustc_const_unstable(feature = "const_slice_index", issue = "none")]
692     #[inline]
693     pub const unsafe fn get_unchecked_mut<I>(self, index: I) -> NonNull<I::Output>
694     where
695         I: ~const SliceIndex<[T]>,
696     {
697         // SAFETY: the caller ensures that `self` is dereferenceable and `index` in-bounds.
698         // As a consequence, the resulting pointer cannot be null.
699         unsafe { NonNull::new_unchecked(self.as_ptr().get_unchecked_mut(index)) }
700     }
701 }
702
703 #[stable(feature = "nonnull", since = "1.25.0")]
704 #[rustc_const_unstable(feature = "const_clone", issue = "91805")]
705 impl<T: ?Sized> const Clone for NonNull<T> {
706     #[inline(always)]
707     fn clone(&self) -> Self {
708         *self
709     }
710 }
711
712 #[stable(feature = "nonnull", since = "1.25.0")]
713 impl<T: ?Sized> Copy for NonNull<T> {}
714
715 #[unstable(feature = "coerce_unsized", issue = "18598")]
716 impl<T: ?Sized, U: ?Sized> CoerceUnsized<NonNull<U>> for NonNull<T> where T: Unsize<U> {}
717
718 #[unstable(feature = "dispatch_from_dyn", issue = "none")]
719 impl<T: ?Sized, U: ?Sized> DispatchFromDyn<NonNull<U>> for NonNull<T> where T: Unsize<U> {}
720
721 #[stable(feature = "nonnull", since = "1.25.0")]
722 impl<T: ?Sized> fmt::Debug for NonNull<T> {
723     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
724         fmt::Pointer::fmt(&self.as_ptr(), f)
725     }
726 }
727
728 #[stable(feature = "nonnull", since = "1.25.0")]
729 impl<T: ?Sized> fmt::Pointer for NonNull<T> {
730     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
731         fmt::Pointer::fmt(&self.as_ptr(), f)
732     }
733 }
734
735 #[stable(feature = "nonnull", since = "1.25.0")]
736 impl<T: ?Sized> Eq for NonNull<T> {}
737
738 #[stable(feature = "nonnull", since = "1.25.0")]
739 impl<T: ?Sized> PartialEq for NonNull<T> {
740     #[inline]
741     fn eq(&self, other: &Self) -> bool {
742         self.as_ptr() == other.as_ptr()
743     }
744 }
745
746 #[stable(feature = "nonnull", since = "1.25.0")]
747 impl<T: ?Sized> Ord for NonNull<T> {
748     #[inline]
749     fn cmp(&self, other: &Self) -> Ordering {
750         self.as_ptr().cmp(&other.as_ptr())
751     }
752 }
753
754 #[stable(feature = "nonnull", since = "1.25.0")]
755 impl<T: ?Sized> PartialOrd for NonNull<T> {
756     #[inline]
757     fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
758         self.as_ptr().partial_cmp(&other.as_ptr())
759     }
760 }
761
762 #[stable(feature = "nonnull", since = "1.25.0")]
763 impl<T: ?Sized> hash::Hash for NonNull<T> {
764     #[inline]
765     fn hash<H: hash::Hasher>(&self, state: &mut H) {
766         self.as_ptr().hash(state)
767     }
768 }
769
770 #[unstable(feature = "ptr_internals", issue = "none")]
771 #[rustc_const_unstable(feature = "const_convert", issue = "88674")]
772 impl<T: ?Sized> const From<Unique<T>> for NonNull<T> {
773     #[inline]
774     fn from(unique: Unique<T>) -> Self {
775         // SAFETY: A Unique pointer cannot be null, so the conditions for
776         // new_unchecked() are respected.
777         unsafe { NonNull::new_unchecked(unique.as_ptr()) }
778     }
779 }
780
781 #[stable(feature = "nonnull", since = "1.25.0")]
782 #[rustc_const_unstable(feature = "const_convert", issue = "88674")]
783 impl<T: ?Sized> const From<&mut T> for NonNull<T> {
784     /// Converts a `&mut T` to a `NonNull<T>`.
785     ///
786     /// This conversion is safe and infallible since references cannot be null.
787     #[inline]
788     fn from(reference: &mut T) -> Self {
789         // SAFETY: A mutable reference cannot be null.
790         unsafe { NonNull { pointer: reference as *mut T } }
791     }
792 }
793
794 #[stable(feature = "nonnull", since = "1.25.0")]
795 #[rustc_const_unstable(feature = "const_convert", issue = "88674")]
796 impl<T: ?Sized> const From<&T> for NonNull<T> {
797     /// Converts a `&T` to a `NonNull<T>`.
798     ///
799     /// This conversion is safe and infallible since references cannot be null.
800     #[inline]
801     fn from(reference: &T) -> Self {
802         // SAFETY: A reference cannot be null, so the conditions for
803         // new_unchecked() are respected.
804         unsafe { NonNull { pointer: reference as *const T } }
805     }
806 }