]> git.lizzy.rs Git - rust.git/blob - library/core/src/ptr/non_null.rs
Rollup merge of #106811 - khuey:dwp_extension, r=davidtwco
[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         // SAFETY: The pointer is guaranteed by the type to be non-null,
273         // meaning that the address will be non-zero.
274         unsafe { NonZeroUsize::new_unchecked(self.pointer.addr()) }
275     }
276
277     /// Creates a new pointer with the given address.
278     ///
279     /// For more details see the equivalent method on a raw pointer, [`pointer::with_addr`].
280     ///
281     /// This API and its claimed semantics are part of the Strict Provenance experiment,
282     /// see the [`ptr` module documentation][crate::ptr].
283     #[must_use]
284     #[inline]
285     #[unstable(feature = "strict_provenance", issue = "95228")]
286     pub fn with_addr(self, addr: NonZeroUsize) -> Self {
287         // SAFETY: The result of `ptr::from::with_addr` is non-null because `addr` is guaranteed to be non-zero.
288         unsafe { NonNull::new_unchecked(self.pointer.with_addr(addr.get()) as *mut _) }
289     }
290
291     /// Creates a new pointer by mapping `self`'s address to a new one.
292     ///
293     /// For more details see the equivalent method on a raw pointer, [`pointer::map_addr`].
294     ///
295     /// This API and its claimed semantics are part of the Strict Provenance experiment,
296     /// see the [`ptr` module documentation][crate::ptr].
297     #[must_use]
298     #[inline]
299     #[unstable(feature = "strict_provenance", issue = "95228")]
300     pub fn map_addr(self, f: impl FnOnce(NonZeroUsize) -> NonZeroUsize) -> Self {
301         self.with_addr(f(self.addr()))
302     }
303
304     /// Acquires the underlying `*mut` pointer.
305     ///
306     /// # Examples
307     ///
308     /// ```
309     /// use std::ptr::NonNull;
310     ///
311     /// let mut x = 0u32;
312     /// let ptr = NonNull::new(&mut x).expect("ptr is null!");
313     ///
314     /// let x_value = unsafe { *ptr.as_ptr() };
315     /// assert_eq!(x_value, 0);
316     ///
317     /// unsafe { *ptr.as_ptr() += 2; }
318     /// let x_value = unsafe { *ptr.as_ptr() };
319     /// assert_eq!(x_value, 2);
320     /// ```
321     #[stable(feature = "nonnull", since = "1.25.0")]
322     #[rustc_const_stable(feature = "const_nonnull_as_ptr", since = "1.32.0")]
323     #[must_use]
324     #[inline(always)]
325     pub const fn as_ptr(self) -> *mut T {
326         self.pointer as *mut T
327     }
328
329     /// Returns a shared reference to the value. If the value may be uninitialized, [`as_uninit_ref`]
330     /// must be used instead.
331     ///
332     /// For the mutable counterpart see [`as_mut`].
333     ///
334     /// [`as_uninit_ref`]: NonNull::as_uninit_ref
335     /// [`as_mut`]: NonNull::as_mut
336     ///
337     /// # Safety
338     ///
339     /// When calling this method, you have to ensure that all of the following is true:
340     ///
341     /// * The pointer must be properly aligned.
342     ///
343     /// * It must be "dereferenceable" in the sense defined in [the module documentation].
344     ///
345     /// * The pointer must point to an initialized instance of `T`.
346     ///
347     /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
348     ///   arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
349     ///   In particular, while this reference exists, the memory the pointer points to must
350     ///   not get mutated (except inside `UnsafeCell`).
351     ///
352     /// This applies even if the result of this method is unused!
353     /// (The part about being initialized is not yet fully decided, but until
354     /// it is, the only safe approach is to ensure that they are indeed initialized.)
355     ///
356     /// # Examples
357     ///
358     /// ```
359     /// use std::ptr::NonNull;
360     ///
361     /// let mut x = 0u32;
362     /// let ptr = NonNull::new(&mut x as *mut _).expect("ptr is null!");
363     ///
364     /// let ref_x = unsafe { ptr.as_ref() };
365     /// println!("{ref_x}");
366     /// ```
367     ///
368     /// [the module documentation]: crate::ptr#safety
369     #[stable(feature = "nonnull", since = "1.25.0")]
370     #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")]
371     #[must_use]
372     #[inline(always)]
373     pub const unsafe fn as_ref<'a>(&self) -> &'a T {
374         // SAFETY: the caller must guarantee that `self` meets all the
375         // requirements for a reference.
376         unsafe { &*self.as_ptr() }
377     }
378
379     /// Returns a unique reference to the value. If the value may be uninitialized, [`as_uninit_mut`]
380     /// must be used instead.
381     ///
382     /// For the shared counterpart see [`as_ref`].
383     ///
384     /// [`as_uninit_mut`]: NonNull::as_uninit_mut
385     /// [`as_ref`]: NonNull::as_ref
386     ///
387     /// # Safety
388     ///
389     /// When calling this method, you have to ensure that all of the following is true:
390     ///
391     /// * The pointer must be properly aligned.
392     ///
393     /// * It must be "dereferenceable" in the sense defined in [the module documentation].
394     ///
395     /// * The pointer must point to an initialized instance of `T`.
396     ///
397     /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
398     ///   arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
399     ///   In particular, while this reference exists, the memory the pointer points to must
400     ///   not get accessed (read or written) through any other pointer.
401     ///
402     /// This applies even if the result of this method is unused!
403     /// (The part about being initialized is not yet fully decided, but until
404     /// it is, the only safe approach is to ensure that they are indeed initialized.)
405     /// # Examples
406     ///
407     /// ```
408     /// use std::ptr::NonNull;
409     ///
410     /// let mut x = 0u32;
411     /// let mut ptr = NonNull::new(&mut x).expect("null pointer");
412     ///
413     /// let x_ref = unsafe { ptr.as_mut() };
414     /// assert_eq!(*x_ref, 0);
415     /// *x_ref += 2;
416     /// assert_eq!(*x_ref, 2);
417     /// ```
418     ///
419     /// [the module documentation]: crate::ptr#safety
420     #[stable(feature = "nonnull", since = "1.25.0")]
421     #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")]
422     #[must_use]
423     #[inline(always)]
424     pub const unsafe fn as_mut<'a>(&mut self) -> &'a mut T {
425         // SAFETY: the caller must guarantee that `self` meets all the
426         // requirements for a mutable reference.
427         unsafe { &mut *self.as_ptr() }
428     }
429
430     /// Casts to a pointer of another type.
431     ///
432     /// # Examples
433     ///
434     /// ```
435     /// use std::ptr::NonNull;
436     ///
437     /// let mut x = 0u32;
438     /// let ptr = NonNull::new(&mut x as *mut _).expect("null pointer");
439     ///
440     /// let casted_ptr = ptr.cast::<i8>();
441     /// let raw_ptr: *mut i8 = casted_ptr.as_ptr();
442     /// ```
443     #[stable(feature = "nonnull_cast", since = "1.27.0")]
444     #[rustc_const_stable(feature = "const_nonnull_cast", since = "1.36.0")]
445     #[must_use = "this returns the result of the operation, \
446                   without modifying the original"]
447     #[inline]
448     pub const fn cast<U>(self) -> NonNull<U> {
449         // SAFETY: `self` is a `NonNull` pointer which is necessarily non-null
450         unsafe { NonNull::new_unchecked(self.as_ptr() as *mut U) }
451     }
452 }
453
454 impl<T> NonNull<[T]> {
455     /// Creates a non-null raw slice from a thin pointer and a length.
456     ///
457     /// The `len` argument is the number of **elements**, not the number of bytes.
458     ///
459     /// This function is safe, but dereferencing the return value is unsafe.
460     /// See the documentation of [`slice::from_raw_parts`] for slice safety requirements.
461     ///
462     /// # Examples
463     ///
464     /// ```rust
465     /// #![feature(nonnull_slice_from_raw_parts)]
466     ///
467     /// use std::ptr::NonNull;
468     ///
469     /// // create a slice pointer when starting out with a pointer to the first element
470     /// let mut x = [5, 6, 7];
471     /// let nonnull_pointer = NonNull::new(x.as_mut_ptr()).unwrap();
472     /// let slice = NonNull::slice_from_raw_parts(nonnull_pointer, 3);
473     /// assert_eq!(unsafe { slice.as_ref()[2] }, 7);
474     /// ```
475     ///
476     /// (Note that this example artificially demonstrates a use of this method,
477     /// but `let slice = NonNull::from(&x[..]);` would be a better way to write code like this.)
478     #[unstable(feature = "nonnull_slice_from_raw_parts", issue = "71941")]
479     #[rustc_const_unstable(feature = "const_nonnull_slice_from_raw_parts", issue = "71941")]
480     #[must_use]
481     #[inline]
482     pub const fn slice_from_raw_parts(data: NonNull<T>, len: usize) -> Self {
483         // SAFETY: `data` is a `NonNull` pointer which is necessarily non-null
484         unsafe { Self::new_unchecked(super::slice_from_raw_parts_mut(data.as_ptr(), len)) }
485     }
486
487     /// Returns the length of a non-null raw slice.
488     ///
489     /// The returned value is the number of **elements**, not the number of bytes.
490     ///
491     /// This function is safe, even when the non-null raw slice cannot be dereferenced to a slice
492     /// because the pointer does not have a valid address.
493     ///
494     /// # Examples
495     ///
496     /// ```rust
497     /// #![feature(nonnull_slice_from_raw_parts)]
498     /// use std::ptr::NonNull;
499     ///
500     /// let slice: NonNull<[i8]> = NonNull::slice_from_raw_parts(NonNull::dangling(), 3);
501     /// assert_eq!(slice.len(), 3);
502     /// ```
503     #[stable(feature = "slice_ptr_len_nonnull", since = "1.63.0")]
504     #[rustc_const_stable(feature = "const_slice_ptr_len_nonnull", since = "1.63.0")]
505     #[rustc_allow_const_fn_unstable(const_slice_ptr_len)]
506     #[must_use]
507     #[inline]
508     pub const fn len(self) -> usize {
509         self.as_ptr().len()
510     }
511
512     /// Returns a non-null pointer to the slice's buffer.
513     ///
514     /// # Examples
515     ///
516     /// ```rust
517     /// #![feature(slice_ptr_get, nonnull_slice_from_raw_parts)]
518     /// use std::ptr::NonNull;
519     ///
520     /// let slice: NonNull<[i8]> = NonNull::slice_from_raw_parts(NonNull::dangling(), 3);
521     /// assert_eq!(slice.as_non_null_ptr(), NonNull::<i8>::dangling());
522     /// ```
523     #[inline]
524     #[must_use]
525     #[unstable(feature = "slice_ptr_get", issue = "74265")]
526     #[rustc_const_unstable(feature = "slice_ptr_get", issue = "74265")]
527     pub const fn as_non_null_ptr(self) -> NonNull<T> {
528         // SAFETY: We know `self` is non-null.
529         unsafe { NonNull::new_unchecked(self.as_ptr().as_mut_ptr()) }
530     }
531
532     /// Returns a raw pointer to the slice's buffer.
533     ///
534     /// # Examples
535     ///
536     /// ```rust
537     /// #![feature(slice_ptr_get, nonnull_slice_from_raw_parts)]
538     /// use std::ptr::NonNull;
539     ///
540     /// let slice: NonNull<[i8]> = NonNull::slice_from_raw_parts(NonNull::dangling(), 3);
541     /// assert_eq!(slice.as_mut_ptr(), NonNull::<i8>::dangling().as_ptr());
542     /// ```
543     #[inline]
544     #[must_use]
545     #[unstable(feature = "slice_ptr_get", issue = "74265")]
546     #[rustc_const_unstable(feature = "slice_ptr_get", issue = "74265")]
547     pub const fn as_mut_ptr(self) -> *mut T {
548         self.as_non_null_ptr().as_ptr()
549     }
550
551     /// Returns a shared reference to a slice of possibly uninitialized values. In contrast to
552     /// [`as_ref`], this does not require that the value has to be initialized.
553     ///
554     /// For the mutable counterpart see [`as_uninit_slice_mut`].
555     ///
556     /// [`as_ref`]: NonNull::as_ref
557     /// [`as_uninit_slice_mut`]: NonNull::as_uninit_slice_mut
558     ///
559     /// # Safety
560     ///
561     /// When calling this method, you have to ensure that all of the following is true:
562     ///
563     /// * The pointer must be [valid] for reads for `ptr.len() * mem::size_of::<T>()` many bytes,
564     ///   and it must be properly aligned. This means in particular:
565     ///
566     ///     * The entire memory range of this slice must be contained within a single allocated object!
567     ///       Slices can never span across multiple allocated objects.
568     ///
569     ///     * The pointer must be aligned even for zero-length slices. One
570     ///       reason for this is that enum layout optimizations may rely on references
571     ///       (including slices of any length) being aligned and non-null to distinguish
572     ///       them from other data. You can obtain a pointer that is usable as `data`
573     ///       for zero-length slices using [`NonNull::dangling()`].
574     ///
575     /// * The total size `ptr.len() * mem::size_of::<T>()` of the slice must be no larger than `isize::MAX`.
576     ///   See the safety documentation of [`pointer::offset`].
577     ///
578     /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
579     ///   arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
580     ///   In particular, while this reference exists, the memory the pointer points to must
581     ///   not get mutated (except inside `UnsafeCell`).
582     ///
583     /// This applies even if the result of this method is unused!
584     ///
585     /// See also [`slice::from_raw_parts`].
586     ///
587     /// [valid]: crate::ptr#safety
588     #[inline]
589     #[must_use]
590     #[unstable(feature = "ptr_as_uninit", issue = "75402")]
591     #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")]
592     pub const unsafe fn as_uninit_slice<'a>(self) -> &'a [MaybeUninit<T>] {
593         // SAFETY: the caller must uphold the safety contract for `as_uninit_slice`.
594         unsafe { slice::from_raw_parts(self.cast().as_ptr(), self.len()) }
595     }
596
597     /// Returns a unique reference to a slice of possibly uninitialized values. In contrast to
598     /// [`as_mut`], this does not require that the value has to be initialized.
599     ///
600     /// For the shared counterpart see [`as_uninit_slice`].
601     ///
602     /// [`as_mut`]: NonNull::as_mut
603     /// [`as_uninit_slice`]: NonNull::as_uninit_slice
604     ///
605     /// # Safety
606     ///
607     /// When calling this method, you have to ensure that all of the following is true:
608     ///
609     /// * The pointer must be [valid] for reads and writes for `ptr.len() * mem::size_of::<T>()`
610     ///   many bytes, and it must be properly aligned. This means in particular:
611     ///
612     ///     * The entire memory range of this slice must be contained within a single allocated object!
613     ///       Slices can never span across multiple allocated objects.
614     ///
615     ///     * The pointer must be aligned even for zero-length slices. One
616     ///       reason for this is that enum layout optimizations may rely on references
617     ///       (including slices of any length) being aligned and non-null to distinguish
618     ///       them from other data. You can obtain a pointer that is usable as `data`
619     ///       for zero-length slices using [`NonNull::dangling()`].
620     ///
621     /// * The total size `ptr.len() * mem::size_of::<T>()` of the slice must be no larger than `isize::MAX`.
622     ///   See the safety documentation of [`pointer::offset`].
623     ///
624     /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
625     ///   arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
626     ///   In particular, while this reference exists, the memory the pointer points to must
627     ///   not get accessed (read or written) through any other pointer.
628     ///
629     /// This applies even if the result of this method is unused!
630     ///
631     /// See also [`slice::from_raw_parts_mut`].
632     ///
633     /// [valid]: crate::ptr#safety
634     ///
635     /// # Examples
636     ///
637     /// ```rust
638     /// #![feature(allocator_api, ptr_as_uninit)]
639     ///
640     /// use std::alloc::{Allocator, Layout, Global};
641     /// use std::mem::MaybeUninit;
642     /// use std::ptr::NonNull;
643     ///
644     /// let memory: NonNull<[u8]> = Global.allocate(Layout::new::<[u8; 32]>())?;
645     /// // This is safe as `memory` is valid for reads and writes for `memory.len()` many bytes.
646     /// // Note that calling `memory.as_mut()` is not allowed here as the content may be uninitialized.
647     /// # #[allow(unused_variables)]
648     /// let slice: &mut [MaybeUninit<u8>] = unsafe { memory.as_uninit_slice_mut() };
649     /// # Ok::<_, std::alloc::AllocError>(())
650     /// ```
651     #[inline]
652     #[must_use]
653     #[unstable(feature = "ptr_as_uninit", issue = "75402")]
654     #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")]
655     pub const unsafe fn as_uninit_slice_mut<'a>(self) -> &'a mut [MaybeUninit<T>] {
656         // SAFETY: the caller must uphold the safety contract for `as_uninit_slice_mut`.
657         unsafe { slice::from_raw_parts_mut(self.cast().as_ptr(), self.len()) }
658     }
659
660     /// Returns a raw pointer to an element or subslice, without doing bounds
661     /// checking.
662     ///
663     /// Calling this method with an out-of-bounds index or when `self` is not dereferenceable
664     /// is *[undefined behavior]* even if the resulting pointer is not used.
665     ///
666     /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
667     ///
668     /// # Examples
669     ///
670     /// ```
671     /// #![feature(slice_ptr_get, nonnull_slice_from_raw_parts)]
672     /// use std::ptr::NonNull;
673     ///
674     /// let x = &mut [1, 2, 4];
675     /// let x = NonNull::slice_from_raw_parts(NonNull::new(x.as_mut_ptr()).unwrap(), x.len());
676     ///
677     /// unsafe {
678     ///     assert_eq!(x.get_unchecked_mut(1).as_ptr(), x.as_non_null_ptr().as_ptr().add(1));
679     /// }
680     /// ```
681     #[unstable(feature = "slice_ptr_get", issue = "74265")]
682     #[rustc_const_unstable(feature = "const_slice_index", issue = "none")]
683     #[inline]
684     pub const unsafe fn get_unchecked_mut<I>(self, index: I) -> NonNull<I::Output>
685     where
686         I: ~const SliceIndex<[T]>,
687     {
688         // SAFETY: the caller ensures that `self` is dereferenceable and `index` in-bounds.
689         // As a consequence, the resulting pointer cannot be null.
690         unsafe { NonNull::new_unchecked(self.as_ptr().get_unchecked_mut(index)) }
691     }
692 }
693
694 #[stable(feature = "nonnull", since = "1.25.0")]
695 #[rustc_const_unstable(feature = "const_clone", issue = "91805")]
696 impl<T: ?Sized> const Clone for NonNull<T> {
697     #[inline(always)]
698     fn clone(&self) -> Self {
699         *self
700     }
701 }
702
703 #[stable(feature = "nonnull", since = "1.25.0")]
704 impl<T: ?Sized> Copy for NonNull<T> {}
705
706 #[unstable(feature = "coerce_unsized", issue = "18598")]
707 impl<T: ?Sized, U: ?Sized> CoerceUnsized<NonNull<U>> for NonNull<T> where T: Unsize<U> {}
708
709 #[unstable(feature = "dispatch_from_dyn", issue = "none")]
710 impl<T: ?Sized, U: ?Sized> DispatchFromDyn<NonNull<U>> for NonNull<T> where T: Unsize<U> {}
711
712 #[stable(feature = "nonnull", since = "1.25.0")]
713 impl<T: ?Sized> fmt::Debug for NonNull<T> {
714     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
715         fmt::Pointer::fmt(&self.as_ptr(), f)
716     }
717 }
718
719 #[stable(feature = "nonnull", since = "1.25.0")]
720 impl<T: ?Sized> fmt::Pointer for NonNull<T> {
721     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
722         fmt::Pointer::fmt(&self.as_ptr(), f)
723     }
724 }
725
726 #[stable(feature = "nonnull", since = "1.25.0")]
727 impl<T: ?Sized> Eq for NonNull<T> {}
728
729 #[stable(feature = "nonnull", since = "1.25.0")]
730 impl<T: ?Sized> PartialEq for NonNull<T> {
731     #[inline]
732     fn eq(&self, other: &Self) -> bool {
733         self.as_ptr() == other.as_ptr()
734     }
735 }
736
737 #[stable(feature = "nonnull", since = "1.25.0")]
738 impl<T: ?Sized> Ord for NonNull<T> {
739     #[inline]
740     fn cmp(&self, other: &Self) -> Ordering {
741         self.as_ptr().cmp(&other.as_ptr())
742     }
743 }
744
745 #[stable(feature = "nonnull", since = "1.25.0")]
746 impl<T: ?Sized> PartialOrd for NonNull<T> {
747     #[inline]
748     fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
749         self.as_ptr().partial_cmp(&other.as_ptr())
750     }
751 }
752
753 #[stable(feature = "nonnull", since = "1.25.0")]
754 impl<T: ?Sized> hash::Hash for NonNull<T> {
755     #[inline]
756     fn hash<H: hash::Hasher>(&self, state: &mut H) {
757         self.as_ptr().hash(state)
758     }
759 }
760
761 #[unstable(feature = "ptr_internals", issue = "none")]
762 #[rustc_const_unstable(feature = "const_convert", issue = "88674")]
763 impl<T: ?Sized> const From<Unique<T>> for NonNull<T> {
764     #[inline]
765     fn from(unique: Unique<T>) -> Self {
766         // SAFETY: A Unique pointer cannot be null, so the conditions for
767         // new_unchecked() are respected.
768         unsafe { NonNull::new_unchecked(unique.as_ptr()) }
769     }
770 }
771
772 #[stable(feature = "nonnull", since = "1.25.0")]
773 #[rustc_const_unstable(feature = "const_convert", issue = "88674")]
774 impl<T: ?Sized> const From<&mut T> for NonNull<T> {
775     /// Converts a `&mut T` to a `NonNull<T>`.
776     ///
777     /// This conversion is safe and infallible since references cannot be null.
778     #[inline]
779     fn from(reference: &mut T) -> Self {
780         // SAFETY: A mutable reference cannot be null.
781         unsafe { NonNull { pointer: reference as *mut T } }
782     }
783 }
784
785 #[stable(feature = "nonnull", since = "1.25.0")]
786 #[rustc_const_unstable(feature = "const_convert", issue = "88674")]
787 impl<T: ?Sized> const From<&T> for NonNull<T> {
788     /// Converts a `&T` to a `NonNull<T>`.
789     ///
790     /// This conversion is safe and infallible since references cannot be null.
791     #[inline]
792     fn from(reference: &T) -> Self {
793         // SAFETY: A reference cannot be null, so the conditions for
794         // new_unchecked() are respected.
795         unsafe { NonNull { pointer: reference as *const T } }
796     }
797 }