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