1 use crate::cmp::Ordering;
2 use crate::convert::From;
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};
11 /// `*mut T` but non-zero and covariant.
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`!
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.
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.)
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.
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>`.
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.
44 /// [`PhantomData`]: crate::marker::PhantomData
45 /// [`UnsafeCell<T>`]: crate::cell::UnsafeCell
46 #[stable(feature = "nonnull", since = "1.25.0")]
48 #[rustc_layout_scalar_valid_range_start(1)]
49 #[rustc_nonnull_optimization_guaranteed]
50 pub struct NonNull<T: ?Sized> {
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> {}
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> {}
64 impl<T: Sized> NonNull<T> {
65 /// Creates a new `NonNull` that is dangling, but well-aligned.
67 /// This is useful for initializing types which lazily allocate, like
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
74 #[stable(feature = "nonnull", since = "1.25.0")]
75 #[rustc_const_stable(feature = "const_nonnull_dangling", since = "1.32.0")]
77 pub const fn dangling() -> Self {
78 // SAFETY: mem::align_of() returns a non-zero usize which is then casted
79 // to a *mut T. Therefore, `ptr` is not null and the conditions for
80 // calling new_unchecked() are respected.
82 let ptr = mem::align_of::<T>() as *mut T;
83 NonNull::new_unchecked(ptr)
87 /// Returns a shared references to the value. In contrast to [`as_ref`], this does not require
88 /// that the value has to be initialized.
90 /// For the mutable counterpart see [`as_uninit_mut`].
92 /// [`as_ref`]: NonNull::as_ref
93 /// [`as_uninit_mut`]: NonNull::as_uninit_mut
97 /// When calling this method, you have to ensure that all of the following is true:
99 /// * The pointer must be properly aligned.
101 /// * It must be "dereferencable" in the sense defined in [the module documentation].
103 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
104 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
105 /// In particular, for the duration of this lifetime, the memory the pointer points to must
106 /// not get mutated (except inside `UnsafeCell`).
108 /// This applies even if the result of this method is unused!
110 /// [the module documentation]: crate::ptr#safety
112 #[unstable(feature = "ptr_as_uninit", issue = "75402")]
113 pub unsafe fn as_uninit_ref(&self) -> &MaybeUninit<T> {
114 // SAFETY: the caller must guarantee that `self` meets all the
115 // requirements for a reference.
116 unsafe { &*self.cast().as_ptr() }
119 /// Returns a unique references to the value. In contrast to [`as_mut`], this does not require
120 /// that the value has to be initialized.
122 /// For the shared counterpart see [`as_uninit_ref`].
124 /// [`as_mut`]: NonNull::as_mut
125 /// [`as_uninit_ref`]: NonNull::as_uninit_ref
129 /// When calling this method, you have to ensure that all of the following is true:
131 /// * The pointer must be properly aligned.
133 /// * It must be "dereferencable" in the sense defined in [the module documentation].
135 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
136 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
137 /// In particular, for the duration of this lifetime, the memory the pointer points to must
138 /// not get accessed (read or written) through any other pointer.
140 /// This applies even if the result of this method is unused!
142 /// [the module documentation]: crate::ptr#safety
144 #[unstable(feature = "ptr_as_uninit", issue = "75402")]
145 pub unsafe fn as_uninit_mut(&mut self) -> &mut MaybeUninit<T> {
146 // SAFETY: the caller must guarantee that `self` meets all the
147 // requirements for a reference.
148 unsafe { &mut *self.cast().as_ptr() }
152 impl<T: ?Sized> NonNull<T> {
153 /// Creates a new `NonNull`.
157 /// `ptr` must be non-null.
158 #[stable(feature = "nonnull", since = "1.25.0")]
159 #[rustc_const_stable(feature = "const_nonnull_new_unchecked", since = "1.32.0")]
161 pub const unsafe fn new_unchecked(ptr: *mut T) -> Self {
162 // SAFETY: the caller must guarantee that `ptr` is non-null.
163 unsafe { NonNull { pointer: ptr as _ } }
166 /// Creates a new `NonNull` if `ptr` is non-null.
167 #[stable(feature = "nonnull", since = "1.25.0")]
169 pub fn new(ptr: *mut T) -> Option<Self> {
171 // SAFETY: The pointer is already checked and is not null
172 Some(unsafe { Self::new_unchecked(ptr) })
178 /// Acquires the underlying `*mut` pointer.
179 #[stable(feature = "nonnull", since = "1.25.0")]
180 #[rustc_const_stable(feature = "const_nonnull_as_ptr", since = "1.32.0")]
182 pub const fn as_ptr(self) -> *mut T {
183 self.pointer as *mut T
186 /// Returns a shared reference to the value. If the value may be uninitialized, [`as_uninit_ref`]
187 /// must be used instead.
189 /// For the mutable counterpart see [`as_mut`].
191 /// [`as_uninit_ref`]: NonNull::as_uninit_ref
192 /// [`as_mut`]: NonNull::as_mut
196 /// When calling this method, you have to ensure that all of the following is true:
198 /// * The pointer must be properly aligned.
200 /// * It must be "dereferencable" in the sense defined in [the module documentation].
202 /// * The pointer must point to an initialized instance of `T`.
204 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
205 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
206 /// In particular, for the duration of this lifetime, the memory the pointer points to must
207 /// not get mutated (except inside `UnsafeCell`).
209 /// This applies even if the result of this method is unused!
210 /// (The part about being initialized is not yet fully decided, but until
211 /// it is, the only safe approach is to ensure that they are indeed initialized.)
213 /// [the module documentation]: crate::ptr#safety
214 #[stable(feature = "nonnull", since = "1.25.0")]
216 pub unsafe fn as_ref(&self) -> &T {
217 // SAFETY: the caller must guarantee that `self` meets all the
218 // requirements for a reference.
219 unsafe { &*self.as_ptr() }
222 /// Returns a unique reference to the value. If the value may be uninitialized, [`as_uninit_mut`]
223 /// must be used instead.
225 /// For the shared counterpart see [`as_ref`].
227 /// [`as_uninit_mut`]: NonNull::as_uninit_mut
228 /// [`as_ref`]: NonNull::as_ref
232 /// When calling this method, you have to ensure that all of the following is true:
234 /// * The pointer must be properly aligned.
236 /// * It must be "dereferencable" in the sense defined in [the module documentation].
238 /// * The pointer must point to an initialized instance of `T`.
240 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
241 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
242 /// In particular, for the duration of this lifetime, the memory the pointer points to must
243 /// not get accessed (read or written) through any other pointer.
245 /// This applies even if the result of this method is unused!
246 /// (The part about being initialized is not yet fully decided, but until
247 /// it is, the only safe approach is to ensure that they are indeed initialized.)
249 /// [the module documentation]: crate::ptr#safety
250 #[stable(feature = "nonnull", since = "1.25.0")]
252 pub unsafe fn as_mut(&mut self) -> &mut T {
253 // SAFETY: the caller must guarantee that `self` meets all the
254 // requirements for a mutable reference.
255 unsafe { &mut *self.as_ptr() }
258 /// Casts to a pointer of another type.
259 #[stable(feature = "nonnull_cast", since = "1.27.0")]
260 #[rustc_const_stable(feature = "const_nonnull_cast", since = "1.32.0")]
262 pub const fn cast<U>(self) -> NonNull<U> {
263 // SAFETY: `self` is a `NonNull` pointer which is necessarily non-null
264 unsafe { NonNull::new_unchecked(self.as_ptr() as *mut U) }
268 impl<T> NonNull<[T]> {
269 /// Creates a non-null raw slice from a thin pointer and a length.
271 /// The `len` argument is the number of **elements**, not the number of bytes.
273 /// This function is safe, but dereferencing the return value is unsafe.
274 /// See the documentation of [`slice::from_raw_parts`] for slice safety requirements.
279 /// #![feature(nonnull_slice_from_raw_parts)]
281 /// use std::ptr::NonNull;
283 /// // create a slice pointer when starting out with a pointer to the first element
284 /// let mut x = [5, 6, 7];
285 /// let nonnull_pointer = NonNull::new(x.as_mut_ptr()).unwrap();
286 /// let slice = NonNull::slice_from_raw_parts(nonnull_pointer, 3);
287 /// assert_eq!(unsafe { slice.as_ref()[2] }, 7);
290 /// (Note that this example artificially demonstrates a use of this method,
291 /// but `let slice = NonNull::from(&x[..]);` would be a better way to write code like this.)
292 #[unstable(feature = "nonnull_slice_from_raw_parts", issue = "71941")]
293 #[rustc_const_unstable(feature = "const_nonnull_slice_from_raw_parts", issue = "71941")]
295 pub const fn slice_from_raw_parts(data: NonNull<T>, len: usize) -> Self {
296 // SAFETY: `data` is a `NonNull` pointer which is necessarily non-null
297 unsafe { Self::new_unchecked(super::slice_from_raw_parts_mut(data.as_ptr(), len)) }
300 /// Returns the length of a non-null raw slice.
302 /// The returned value is the number of **elements**, not the number of bytes.
304 /// This function is safe, even when the non-null raw slice cannot be dereferenced to a slice
305 /// because the pointer does not have a valid address.
310 /// #![feature(slice_ptr_len, nonnull_slice_from_raw_parts)]
311 /// use std::ptr::NonNull;
313 /// let slice: NonNull<[i8]> = NonNull::slice_from_raw_parts(NonNull::dangling(), 3);
314 /// assert_eq!(slice.len(), 3);
316 #[unstable(feature = "slice_ptr_len", issue = "71146")]
317 #[rustc_const_unstable(feature = "const_slice_ptr_len", issue = "71146")]
319 pub const fn len(self) -> usize {
323 /// Returns a non-null pointer to the slice's buffer.
328 /// #![feature(slice_ptr_get, nonnull_slice_from_raw_parts)]
329 /// use std::ptr::NonNull;
331 /// let slice: NonNull<[i8]> = NonNull::slice_from_raw_parts(NonNull::dangling(), 3);
332 /// assert_eq!(slice.as_non_null_ptr(), NonNull::new(1 as *mut i8).unwrap());
335 #[unstable(feature = "slice_ptr_get", issue = "74265")]
336 #[rustc_const_unstable(feature = "slice_ptr_get", issue = "74265")]
337 pub const fn as_non_null_ptr(self) -> NonNull<T> {
338 // SAFETY: We know `self` is non-null.
339 unsafe { NonNull::new_unchecked(self.as_ptr().as_mut_ptr()) }
342 /// Returns a raw pointer to the slice's buffer.
347 /// #![feature(slice_ptr_get, nonnull_slice_from_raw_parts)]
348 /// use std::ptr::NonNull;
350 /// let slice: NonNull<[i8]> = NonNull::slice_from_raw_parts(NonNull::dangling(), 3);
351 /// assert_eq!(slice.as_mut_ptr(), 1 as *mut i8);
354 #[unstable(feature = "slice_ptr_get", issue = "74265")]
355 #[rustc_const_unstable(feature = "slice_ptr_get", issue = "74265")]
356 pub const fn as_mut_ptr(self) -> *mut T {
357 self.as_non_null_ptr().as_ptr()
360 /// Returns a shared reference to a slice of possibly uninitialized values. In contrast to
361 /// [`as_ref`], this does not require that the value has to be initialized.
363 /// For the mutable counterpart see [`as_uninit_slice_mut`].
365 /// [`as_ref`]: NonNull::as_ref
366 /// [`as_uninit_slice_mut`]: NonNull::as_uninit_slice_mut
370 /// When calling this method, you have to ensure that all of the following is true:
372 /// * The pointer must be [valid] for reads for `ptr.len() * mem::size_of::<T>()` many bytes,
373 /// and it must be properly aligned. This means in particular:
375 /// * The entire memory range of this slice must be contained within a single allocated object!
376 /// Slices can never span across multiple allocated objects.
378 /// * The pointer must be aligned even for zero-length slices. One
379 /// reason for this is that enum layout optimizations may rely on references
380 /// (including slices of any length) being aligned and non-null to distinguish
381 /// them from other data. You can obtain a pointer that is usable as `data`
382 /// for zero-length slices using [`NonNull::dangling()`].
384 /// * The total size `ptr.len() * mem::size_of::<T>()` of the slice must be no larger than `isize::MAX`.
385 /// See the safety documentation of [`pointer::offset`].
387 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
388 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
389 /// In particular, for the duration of this lifetime, the memory the pointer points to must
390 /// not get mutated (except inside `UnsafeCell`).
392 /// This applies even if the result of this method is unused!
394 /// See also [`slice::from_raw_parts`].
396 /// [valid]: crate::ptr#safety
397 /// [`pointer::offset`]: ../../std/primitive.pointer.html#method.offset
399 #[unstable(feature = "ptr_as_uninit", issue = "75402")]
400 pub unsafe fn as_uninit_slice(&self) -> &[MaybeUninit<T>] {
401 // SAFETY: the caller must uphold the safety contract for `as_uninit_slice`.
402 unsafe { slice::from_raw_parts(self.cast().as_ptr(), self.len()) }
405 /// Returns a unique reference to a slice of possibly uninitialized values. In contrast to
406 /// [`as_mut`], this does not require that the value has to be initialized.
408 /// For the shared counterpart see [`as_uninit_slice`].
410 /// [`as_mut`]: NonNull::as_mut
411 /// [`as_uninit_slice`]: NonNull::as_uninit_slice
415 /// When calling this method, you have to ensure that all of the following is true:
417 /// * The pointer must be [valid] for reads and writes for `ptr.len() * mem::size_of::<T>()`
418 /// many bytes, and it must be properly aligned. This means in particular:
420 /// * The entire memory range of this slice must be contained within a single allocated object!
421 /// Slices can never span across multiple allocated objects.
423 /// * The pointer must be aligned even for zero-length slices. One
424 /// reason for this is that enum layout optimizations may rely on references
425 /// (including slices of any length) being aligned and non-null to distinguish
426 /// them from other data. You can obtain a pointer that is usable as `data`
427 /// for zero-length slices using [`NonNull::dangling()`].
429 /// * The total size `ptr.len() * mem::size_of::<T>()` of the slice must be no larger than `isize::MAX`.
430 /// See the safety documentation of [`pointer::offset`].
432 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
433 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
434 /// In particular, for the duration of this lifetime, the memory the pointer points to must
435 /// not get accessed (read or written) through any other pointer.
437 /// This applies even if the result of this method is unused!
439 /// See also [`slice::from_raw_parts_mut`].
441 /// [valid]: crate::ptr#safety
442 /// [`pointer::offset`]: ../../std/primitive.pointer.html#method.offset
447 /// #![feature(allocator_api, ptr_as_uninit)]
449 /// use std::alloc::{Allocator, Layout, Global};
450 /// use std::mem::MaybeUninit;
451 /// use std::ptr::NonNull;
453 /// let memory: NonNull<[u8]> = Global.allocate(Layout::new::<[u8; 32]>())?;
454 /// // This is safe as `memory` is valid for reads and writes for `memory.len()` many bytes.
455 /// // Note that calling `memory.as_mut()` is not allowed here as the content may be uninitialized.
456 /// # #[allow(unused_variables)]
457 /// let slice: &mut [MaybeUninit<u8>] = unsafe { memory.as_uninit_slice_mut() };
458 /// # Ok::<_, std::alloc::AllocError>(())
461 #[unstable(feature = "ptr_as_uninit", issue = "75402")]
462 pub unsafe fn as_uninit_slice_mut(&self) -> &mut [MaybeUninit<T>] {
463 // SAFETY: the caller must uphold the safety contract for `as_uninit_slice_mut`.
464 unsafe { slice::from_raw_parts_mut(self.cast().as_ptr(), self.len()) }
467 /// Returns a raw pointer to an element or subslice, without doing bounds
470 /// Calling this method with an out-of-bounds index or when `self` is not dereferencable
471 /// is *[undefined behavior]* even if the resulting pointer is not used.
473 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
478 /// #![feature(slice_ptr_get, nonnull_slice_from_raw_parts)]
479 /// use std::ptr::NonNull;
481 /// let x = &mut [1, 2, 4];
482 /// let x = NonNull::slice_from_raw_parts(NonNull::new(x.as_mut_ptr()).unwrap(), x.len());
485 /// assert_eq!(x.get_unchecked_mut(1).as_ptr(), x.as_non_null_ptr().as_ptr().add(1));
488 #[unstable(feature = "slice_ptr_get", issue = "74265")]
490 pub unsafe fn get_unchecked_mut<I>(self, index: I) -> NonNull<I::Output>
494 // SAFETY: the caller ensures that `self` is dereferencable and `index` in-bounds.
495 // As a consequence, the resulting pointer cannot be NULL.
496 unsafe { NonNull::new_unchecked(self.as_ptr().get_unchecked_mut(index)) }
500 #[stable(feature = "nonnull", since = "1.25.0")]
501 impl<T: ?Sized> Clone for NonNull<T> {
503 fn clone(&self) -> Self {
508 #[stable(feature = "nonnull", since = "1.25.0")]
509 impl<T: ?Sized> Copy for NonNull<T> {}
511 #[unstable(feature = "coerce_unsized", issue = "27732")]
512 impl<T: ?Sized, U: ?Sized> CoerceUnsized<NonNull<U>> for NonNull<T> where T: Unsize<U> {}
514 #[unstable(feature = "dispatch_from_dyn", issue = "none")]
515 impl<T: ?Sized, U: ?Sized> DispatchFromDyn<NonNull<U>> for NonNull<T> where T: Unsize<U> {}
517 #[stable(feature = "nonnull", since = "1.25.0")]
518 impl<T: ?Sized> fmt::Debug for NonNull<T> {
519 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
520 fmt::Pointer::fmt(&self.as_ptr(), f)
524 #[stable(feature = "nonnull", since = "1.25.0")]
525 impl<T: ?Sized> fmt::Pointer for NonNull<T> {
526 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
527 fmt::Pointer::fmt(&self.as_ptr(), f)
531 #[stable(feature = "nonnull", since = "1.25.0")]
532 impl<T: ?Sized> Eq for NonNull<T> {}
534 #[stable(feature = "nonnull", since = "1.25.0")]
535 impl<T: ?Sized> PartialEq for NonNull<T> {
537 fn eq(&self, other: &Self) -> bool {
538 self.as_ptr() == other.as_ptr()
542 #[stable(feature = "nonnull", since = "1.25.0")]
543 impl<T: ?Sized> Ord for NonNull<T> {
545 fn cmp(&self, other: &Self) -> Ordering {
546 self.as_ptr().cmp(&other.as_ptr())
550 #[stable(feature = "nonnull", since = "1.25.0")]
551 impl<T: ?Sized> PartialOrd for NonNull<T> {
553 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
554 self.as_ptr().partial_cmp(&other.as_ptr())
558 #[stable(feature = "nonnull", since = "1.25.0")]
559 impl<T: ?Sized> hash::Hash for NonNull<T> {
561 fn hash<H: hash::Hasher>(&self, state: &mut H) {
562 self.as_ptr().hash(state)
566 #[unstable(feature = "ptr_internals", issue = "none")]
567 impl<T: ?Sized> From<Unique<T>> for NonNull<T> {
569 fn from(unique: Unique<T>) -> Self {
570 // SAFETY: A Unique pointer cannot be null, so the conditions for
571 // new_unchecked() are respected.
572 unsafe { NonNull::new_unchecked(unique.as_ptr()) }
576 #[stable(feature = "nonnull", since = "1.25.0")]
577 impl<T: ?Sized> From<&mut T> for NonNull<T> {
579 fn from(reference: &mut T) -> Self {
580 // SAFETY: A mutable reference cannot be null.
581 unsafe { NonNull { pointer: reference as *mut T } }
585 #[stable(feature = "nonnull", since = "1.25.0")]
586 impl<T: ?Sized> From<&T> for NonNull<T> {
588 fn from(reference: &T) -> Self {
589 // SAFETY: A reference cannot be null, so the conditions for
590 // new_unchecked() are respected.
591 unsafe { NonNull { pointer: reference as *const T } }