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
78 /// use std::ptr::NonNull;
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!
84 #[stable(feature = "nonnull", since = "1.25.0")]
85 #[rustc_const_stable(feature = "const_nonnull_dangling", since = "1.36.0")]
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.
93 let ptr = mem::align_of::<T>() as *mut T;
94 NonNull::new_unchecked(ptr)
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.
101 /// For the mutable counterpart see [`as_uninit_mut`].
103 /// [`as_ref`]: NonNull::as_ref
104 /// [`as_uninit_mut`]: NonNull::as_uninit_mut
108 /// When calling this method, you have to ensure that all of the following is true:
110 /// * The pointer must be properly aligned.
112 /// * It must be "dereferenceable" in the sense defined in [the module documentation].
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`).
119 /// This applies even if the result of this method is unused!
121 /// [the module documentation]: crate::ptr#safety
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() }
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.
135 /// For the shared counterpart see [`as_uninit_ref`].
137 /// [`as_mut`]: NonNull::as_mut
138 /// [`as_uninit_ref`]: NonNull::as_uninit_ref
142 /// When calling this method, you have to ensure that all of the following is true:
144 /// * The pointer must be properly aligned.
146 /// * It must be "dereferenceable" in the sense defined in [the module documentation].
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.
153 /// This applies even if the result of this method is unused!
155 /// [the module documentation]: crate::ptr#safety
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() }
167 impl<T: ?Sized> NonNull<T> {
168 /// Creates a new `NonNull`.
172 /// `ptr` must be non-null.
177 /// use std::ptr::NonNull;
179 /// let mut x = 0u32;
180 /// let ptr = unsafe { NonNull::new_unchecked(&mut x as *mut _) };
183 /// *Incorrect* usage of this function:
186 /// use std::ptr::NonNull;
188 /// // NEVER DO THAT!!! This is undefined behavior. ⚠️
189 /// let ptr = unsafe { NonNull::<u32>::new_unchecked(std::ptr::null_mut()) };
191 #[stable(feature = "nonnull", since = "1.25.0")]
192 #[rustc_const_stable(feature = "const_nonnull_new_unchecked", since = "1.25.0")]
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 _ } }
199 /// Creates a new `NonNull` if `ptr` is non-null.
204 /// use std::ptr::NonNull;
206 /// let mut x = 0u32;
207 /// let ptr = NonNull::<u32>::new(&mut x as *mut _).expect("ptr is null!");
209 /// if let Some(ptr) = NonNull::<u32>::new(std::ptr::null_mut()) {
213 #[stable(feature = "nonnull", since = "1.25.0")]
214 #[rustc_const_unstable(feature = "const_nonnull_new", issue = "93235")]
216 pub const fn new(ptr: *mut T) -> Option<Self> {
218 // SAFETY: The pointer is already checked and is not null
219 Some(unsafe { Self::new_unchecked(ptr) })
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.
228 /// See the documentation of [`std::ptr::from_raw_parts`] for more details.
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")]
234 pub const fn from_raw_parts(
235 data_address: NonNull<()>,
236 metadata: <T as super::Pointee>::Metadata,
238 // SAFETY: The result of `ptr::from::raw_parts_mut` is non-null because `data_address` is.
240 NonNull::new_unchecked(super::from_raw_parts_mut(data_address.as_ptr(), metadata))
244 /// Decompose a (possibly wide) pointer into its address and metadata components.
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"]
252 pub const fn to_raw_parts(self) -> (NonNull<()>, <T as super::Pointee>::Metadata) {
253 (self.cast(), super::metadata(self.as_ptr()))
256 /// Acquires the underlying `*mut` pointer.
261 /// use std::ptr::NonNull;
263 /// let mut x = 0u32;
264 /// let ptr = NonNull::new(&mut x).expect("ptr is null!");
266 /// let x_value = unsafe { *ptr.as_ptr() };
267 /// assert_eq!(x_value, 0);
269 /// unsafe { *ptr.as_ptr() += 2; }
270 /// let x_value = unsafe { *ptr.as_ptr() };
271 /// assert_eq!(x_value, 2);
273 #[stable(feature = "nonnull", since = "1.25.0")]
274 #[rustc_const_stable(feature = "const_nonnull_as_ptr", since = "1.32.0")]
277 pub const fn as_ptr(self) -> *mut T {
278 self.pointer as *mut T
281 /// Returns a shared reference to the value. If the value may be uninitialized, [`as_uninit_ref`]
282 /// must be used instead.
284 /// For the mutable counterpart see [`as_mut`].
286 /// [`as_uninit_ref`]: NonNull::as_uninit_ref
287 /// [`as_mut`]: NonNull::as_mut
291 /// When calling this method, you have to ensure that all of the following is true:
293 /// * The pointer must be properly aligned.
295 /// * It must be "dereferenceable" in the sense defined in [the module documentation].
297 /// * The pointer must point to an initialized instance of `T`.
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`).
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.)
311 /// use std::ptr::NonNull;
313 /// let mut x = 0u32;
314 /// let ptr = NonNull::new(&mut x as *mut _).expect("ptr is null!");
316 /// let ref_x = unsafe { ptr.as_ref() };
317 /// println!("{}", ref_x);
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")]
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() }
331 /// Returns a unique reference to the value. If the value may be uninitialized, [`as_uninit_mut`]
332 /// must be used instead.
334 /// For the shared counterpart see [`as_ref`].
336 /// [`as_uninit_mut`]: NonNull::as_uninit_mut
337 /// [`as_ref`]: NonNull::as_ref
341 /// When calling this method, you have to ensure that all of the following is true:
343 /// * The pointer must be properly aligned.
345 /// * It must be "dereferenceable" in the sense defined in [the module documentation].
347 /// * The pointer must point to an initialized instance of `T`.
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.
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.)
360 /// use std::ptr::NonNull;
362 /// let mut x = 0u32;
363 /// let mut ptr = NonNull::new(&mut x).expect("null pointer");
365 /// let x_ref = unsafe { ptr.as_mut() };
366 /// assert_eq!(*x_ref, 0);
368 /// assert_eq!(*x_ref, 2);
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")]
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() }
382 /// Casts to a pointer of another type.
387 /// use std::ptr::NonNull;
389 /// let mut x = 0u32;
390 /// let ptr = NonNull::new(&mut x as *mut _).expect("null pointer");
392 /// let casted_ptr = ptr.cast::<i8>();
393 /// let raw_ptr: *mut i8 = casted_ptr.as_ptr();
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"]
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) }
406 impl<T> NonNull<[T]> {
407 /// Creates a non-null raw slice from a thin pointer and a length.
409 /// The `len` argument is the number of **elements**, not the number of bytes.
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.
417 /// #![feature(nonnull_slice_from_raw_parts)]
419 /// use std::ptr::NonNull;
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);
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")]
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)) }
439 /// Returns the length of a non-null raw slice.
441 /// The returned value is the number of **elements**, not the number of bytes.
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.
449 /// #![feature(slice_ptr_len, nonnull_slice_from_raw_parts)]
450 /// use std::ptr::NonNull;
452 /// let slice: NonNull<[i8]> = NonNull::slice_from_raw_parts(NonNull::dangling(), 3);
453 /// assert_eq!(slice.len(), 3);
455 #[unstable(feature = "slice_ptr_len", issue = "71146")]
456 #[rustc_const_unstable(feature = "const_slice_ptr_len", issue = "71146")]
459 pub const fn len(self) -> usize {
463 /// Returns a non-null pointer to the slice's buffer.
468 /// #![feature(slice_ptr_get, nonnull_slice_from_raw_parts)]
469 /// use std::ptr::NonNull;
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());
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()) }
483 /// Returns a raw pointer to the slice's buffer.
488 /// #![feature(slice_ptr_get, nonnull_slice_from_raw_parts)]
489 /// use std::ptr::NonNull;
491 /// let slice: NonNull<[i8]> = NonNull::slice_from_raw_parts(NonNull::dangling(), 3);
492 /// assert_eq!(slice.as_mut_ptr(), 1 as *mut i8);
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()
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.
505 /// For the mutable counterpart see [`as_uninit_slice_mut`].
507 /// [`as_ref`]: NonNull::as_ref
508 /// [`as_uninit_slice_mut`]: NonNull::as_uninit_slice_mut
512 /// When calling this method, you have to ensure that all of the following is true:
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:
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.
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()`].
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`].
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`).
534 /// This applies even if the result of this method is unused!
536 /// See also [`slice::from_raw_parts`].
538 /// [valid]: crate::ptr#safety
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()) }
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.
551 /// For the shared counterpart see [`as_uninit_slice`].
553 /// [`as_mut`]: NonNull::as_mut
554 /// [`as_uninit_slice`]: NonNull::as_uninit_slice
558 /// When calling this method, you have to ensure that all of the following is true:
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:
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.
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()`].
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`].
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.
580 /// This applies even if the result of this method is unused!
582 /// See also [`slice::from_raw_parts_mut`].
584 /// [valid]: crate::ptr#safety
589 /// #![feature(allocator_api, ptr_as_uninit)]
591 /// use std::alloc::{Allocator, Layout, Global};
592 /// use std::mem::MaybeUninit;
593 /// use std::ptr::NonNull;
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>(())
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()) }
611 /// Returns a raw pointer to an element or subslice, without doing bounds
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.
617 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
622 /// #![feature(slice_ptr_get, nonnull_slice_from_raw_parts)]
623 /// use std::ptr::NonNull;
625 /// let x = &mut [1, 2, 4];
626 /// let x = NonNull::slice_from_raw_parts(NonNull::new(x.as_mut_ptr()).unwrap(), x.len());
629 /// assert_eq!(x.get_unchecked_mut(1).as_ptr(), x.as_non_null_ptr().as_ptr().add(1));
632 #[unstable(feature = "slice_ptr_get", issue = "74265")]
634 pub unsafe fn get_unchecked_mut<I>(self, index: I) -> NonNull<I::Output>
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)) }
644 #[stable(feature = "nonnull", since = "1.25.0")]
645 impl<T: ?Sized> Clone for NonNull<T> {
647 fn clone(&self) -> Self {
652 #[stable(feature = "nonnull", since = "1.25.0")]
653 impl<T: ?Sized> Copy for NonNull<T> {}
655 #[unstable(feature = "coerce_unsized", issue = "27732")]
656 impl<T: ?Sized, U: ?Sized> CoerceUnsized<NonNull<U>> for NonNull<T> where T: Unsize<U> {}
658 #[unstable(feature = "dispatch_from_dyn", issue = "none")]
659 impl<T: ?Sized, U: ?Sized> DispatchFromDyn<NonNull<U>> for NonNull<T> where T: Unsize<U> {}
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)
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)
675 #[stable(feature = "nonnull", since = "1.25.0")]
676 impl<T: ?Sized> Eq for NonNull<T> {}
678 #[stable(feature = "nonnull", since = "1.25.0")]
679 impl<T: ?Sized> PartialEq for NonNull<T> {
681 fn eq(&self, other: &Self) -> bool {
682 self.as_ptr() == other.as_ptr()
686 #[stable(feature = "nonnull", since = "1.25.0")]
687 impl<T: ?Sized> Ord for NonNull<T> {
689 fn cmp(&self, other: &Self) -> Ordering {
690 self.as_ptr().cmp(&other.as_ptr())
694 #[stable(feature = "nonnull", since = "1.25.0")]
695 impl<T: ?Sized> PartialOrd for NonNull<T> {
697 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
698 self.as_ptr().partial_cmp(&other.as_ptr())
702 #[stable(feature = "nonnull", since = "1.25.0")]
703 impl<T: ?Sized> hash::Hash for NonNull<T> {
705 fn hash<H: hash::Hasher>(&self, state: &mut H) {
706 self.as_ptr().hash(state)
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> {
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()) }
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> {
725 fn from(reference: &mut T) -> Self {
726 // SAFETY: A mutable reference cannot be null.
727 unsafe { NonNull { pointer: reference as *mut T } }
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> {
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 } }