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