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