1 use crate::cmp::Ordering;
2 use crate::convert::From;
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};
12 /// `*mut T` but non-zero and [covariant].
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`!
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.
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.)
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.
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>`.
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.
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")]
50 #[rustc_layout_scalar_valid_range_start(1)]
51 #[rustc_nonnull_optimization_guaranteed]
52 pub struct NonNull<T: ?Sized> {
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> {}
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> {}
66 impl<T: Sized> NonNull<T> {
67 /// Creates a new `NonNull` that is dangling, but well-aligned.
69 /// This is useful for initializing types which lazily allocate, like
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
80 /// use std::ptr::NonNull;
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!
86 #[stable(feature = "nonnull", since = "1.25.0")]
87 #[rustc_const_stable(feature = "const_nonnull_dangling", since = "1.36.0")]
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.
95 let ptr = crate::ptr::invalid_mut::<T>(mem::align_of::<T>());
96 NonNull::new_unchecked(ptr)
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.
103 /// For the mutable counterpart see [`as_uninit_mut`].
105 /// [`as_ref`]: NonNull::as_ref
106 /// [`as_uninit_mut`]: NonNull::as_uninit_mut
110 /// When calling this method, you have to ensure that all of the following is true:
112 /// * The pointer must be properly aligned.
114 /// * It must be "dereferenceable" in the sense defined in [the module documentation].
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`).
121 /// This applies even if the result of this method is unused!
123 /// [the module documentation]: crate::ptr#safety
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() }
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.
137 /// For the shared counterpart see [`as_uninit_ref`].
139 /// [`as_mut`]: NonNull::as_mut
140 /// [`as_uninit_ref`]: NonNull::as_uninit_ref
144 /// When calling this method, you have to ensure that all of the following is true:
146 /// * The pointer must be properly aligned.
148 /// * It must be "dereferenceable" in the sense defined in [the module documentation].
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.
155 /// This applies even if the result of this method is unused!
157 /// [the module documentation]: crate::ptr#safety
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() }
169 impl<T: ?Sized> NonNull<T> {
170 /// Creates a new `NonNull`.
174 /// `ptr` must be non-null.
179 /// use std::ptr::NonNull;
181 /// let mut x = 0u32;
182 /// let ptr = unsafe { NonNull::new_unchecked(&mut x as *mut _) };
185 /// *Incorrect* usage of this function:
188 /// use std::ptr::NonNull;
190 /// // NEVER DO THAT!!! This is undefined behavior. ⚠️
191 /// let ptr = unsafe { NonNull::<u32>::new_unchecked(std::ptr::null_mut()) };
193 #[stable(feature = "nonnull", since = "1.25.0")]
194 #[rustc_const_stable(feature = "const_nonnull_new_unchecked", since = "1.25.0")]
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 _ } }
201 /// Creates a new `NonNull` if `ptr` is non-null.
206 /// use std::ptr::NonNull;
208 /// let mut x = 0u32;
209 /// let ptr = NonNull::<u32>::new(&mut x as *mut _).expect("ptr is null!");
211 /// if let Some(ptr) = NonNull::<u32>::new(std::ptr::null_mut()) {
215 #[stable(feature = "nonnull", since = "1.25.0")]
216 #[rustc_const_unstable(feature = "const_nonnull_new", issue = "93235")]
218 pub const fn new(ptr: *mut T) -> Option<Self> {
220 // SAFETY: The pointer is already checked and is not null
221 Some(unsafe { Self::new_unchecked(ptr) })
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.
230 /// See the documentation of [`std::ptr::from_raw_parts`] for more details.
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")]
236 pub const fn from_raw_parts(
237 data_address: NonNull<()>,
238 metadata: <T as super::Pointee>::Metadata,
240 // SAFETY: The result of `ptr::from::raw_parts_mut` is non-null because `data_address` is.
242 NonNull::new_unchecked(super::from_raw_parts_mut(data_address.as_ptr(), metadata))
246 /// Decompose a (possibly wide) pointer into its address and metadata components.
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"]
254 pub const fn to_raw_parts(self) -> (NonNull<()>, <T as super::Pointee>::Metadata) {
255 (self.cast(), super::metadata(self.as_ptr()))
258 /// Gets the "address" portion of the pointer.
260 /// For more details see the equivalent method on a raw pointer, [`pointer::addr`].
262 /// This API and its claimed semantics are part of the Strict Provenance experiment,
263 /// see the [`ptr` module documentation][crate::ptr].
266 #[unstable(feature = "strict_provenance", issue = "95228")]
267 pub fn addr(self) -> NonZeroUsize
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()) }
276 /// Creates a new pointer with the given address.
278 /// For more details see the equivalent method on a raw pointer, [`pointer::with_addr`].
280 /// This API and its claimed semantics are part of the Strict Provenance experiment,
281 /// see the [`ptr` module documentation][crate::ptr].
284 #[unstable(feature = "strict_provenance", issue = "95228")]
285 pub fn with_addr(self, addr: NonZeroUsize) -> Self
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 _) }
293 /// Creates a new pointer by mapping `self`'s address to a new one.
295 /// For more details see the equivalent method on a raw pointer, [`pointer::map_addr`].
297 /// This API and its claimed semantics are part of the Strict Provenance experiment,
298 /// see the [`ptr` module documentation][crate::ptr].
301 #[unstable(feature = "strict_provenance", issue = "95228")]
302 pub fn map_addr(self, f: impl FnOnce(NonZeroUsize) -> NonZeroUsize) -> Self
306 self.with_addr(f(self.addr()))
309 /// Acquires the underlying `*mut` pointer.
314 /// use std::ptr::NonNull;
316 /// let mut x = 0u32;
317 /// let ptr = NonNull::new(&mut x).expect("ptr is null!");
319 /// let x_value = unsafe { *ptr.as_ptr() };
320 /// assert_eq!(x_value, 0);
322 /// unsafe { *ptr.as_ptr() += 2; }
323 /// let x_value = unsafe { *ptr.as_ptr() };
324 /// assert_eq!(x_value, 2);
326 #[stable(feature = "nonnull", since = "1.25.0")]
327 #[rustc_const_stable(feature = "const_nonnull_as_ptr", since = "1.32.0")]
330 pub const fn as_ptr(self) -> *mut T {
331 self.pointer as *mut T
334 /// Returns a shared reference to the value. If the value may be uninitialized, [`as_uninit_ref`]
335 /// must be used instead.
337 /// For the mutable counterpart see [`as_mut`].
339 /// [`as_uninit_ref`]: NonNull::as_uninit_ref
340 /// [`as_mut`]: NonNull::as_mut
344 /// When calling this method, you have to ensure that all of the following is true:
346 /// * The pointer must be properly aligned.
348 /// * It must be "dereferenceable" in the sense defined in [the module documentation].
350 /// * The pointer must point to an initialized instance of `T`.
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`).
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.)
364 /// use std::ptr::NonNull;
366 /// let mut x = 0u32;
367 /// let ptr = NonNull::new(&mut x as *mut _).expect("ptr is null!");
369 /// let ref_x = unsafe { ptr.as_ref() };
370 /// println!("{ref_x}");
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")]
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() }
384 /// Returns a unique reference to the value. If the value may be uninitialized, [`as_uninit_mut`]
385 /// must be used instead.
387 /// For the shared counterpart see [`as_ref`].
389 /// [`as_uninit_mut`]: NonNull::as_uninit_mut
390 /// [`as_ref`]: NonNull::as_ref
394 /// When calling this method, you have to ensure that all of the following is true:
396 /// * The pointer must be properly aligned.
398 /// * It must be "dereferenceable" in the sense defined in [the module documentation].
400 /// * The pointer must point to an initialized instance of `T`.
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.
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.)
413 /// use std::ptr::NonNull;
415 /// let mut x = 0u32;
416 /// let mut ptr = NonNull::new(&mut x).expect("null pointer");
418 /// let x_ref = unsafe { ptr.as_mut() };
419 /// assert_eq!(*x_ref, 0);
421 /// assert_eq!(*x_ref, 2);
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")]
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() }
435 /// Casts to a pointer of another type.
440 /// use std::ptr::NonNull;
442 /// let mut x = 0u32;
443 /// let ptr = NonNull::new(&mut x as *mut _).expect("null pointer");
445 /// let casted_ptr = ptr.cast::<i8>();
446 /// let raw_ptr: *mut i8 = casted_ptr.as_ptr();
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"]
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) }
459 impl<T> NonNull<[T]> {
460 /// Creates a non-null raw slice from a thin pointer and a length.
462 /// The `len` argument is the number of **elements**, not the number of bytes.
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.
470 /// #![feature(nonnull_slice_from_raw_parts)]
472 /// use std::ptr::NonNull;
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);
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")]
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)) }
492 /// Returns the length of a non-null raw slice.
494 /// The returned value is the number of **elements**, not the number of bytes.
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.
502 /// #![feature(nonnull_slice_from_raw_parts)]
503 /// use std::ptr::NonNull;
505 /// let slice: NonNull<[i8]> = NonNull::slice_from_raw_parts(NonNull::dangling(), 3);
506 /// assert_eq!(slice.len(), 3);
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)]
513 pub const fn len(self) -> usize {
517 /// Returns a non-null pointer to the slice's buffer.
522 /// #![feature(slice_ptr_get, nonnull_slice_from_raw_parts)]
523 /// use std::ptr::NonNull;
525 /// let slice: NonNull<[i8]> = NonNull::slice_from_raw_parts(NonNull::dangling(), 3);
526 /// assert_eq!(slice.as_non_null_ptr(), NonNull::<i8>::dangling());
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()) }
537 /// Returns a raw pointer to the slice's buffer.
542 /// #![feature(slice_ptr_get, nonnull_slice_from_raw_parts)]
543 /// use std::ptr::NonNull;
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());
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()
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.
559 /// For the mutable counterpart see [`as_uninit_slice_mut`].
561 /// [`as_ref`]: NonNull::as_ref
562 /// [`as_uninit_slice_mut`]: NonNull::as_uninit_slice_mut
566 /// When calling this method, you have to ensure that all of the following is true:
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:
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.
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()`].
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`].
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`).
588 /// This applies even if the result of this method is unused!
590 /// See also [`slice::from_raw_parts`].
592 /// [valid]: crate::ptr#safety
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()) }
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.
605 /// For the shared counterpart see [`as_uninit_slice`].
607 /// [`as_mut`]: NonNull::as_mut
608 /// [`as_uninit_slice`]: NonNull::as_uninit_slice
612 /// When calling this method, you have to ensure that all of the following is true:
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:
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.
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()`].
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`].
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.
634 /// This applies even if the result of this method is unused!
636 /// See also [`slice::from_raw_parts_mut`].
638 /// [valid]: crate::ptr#safety
643 /// #![feature(allocator_api, ptr_as_uninit)]
645 /// use std::alloc::{Allocator, Layout, Global};
646 /// use std::mem::MaybeUninit;
647 /// use std::ptr::NonNull;
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>(())
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()) }
665 /// Returns a raw pointer to an element or subslice, without doing bounds
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.
671 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
676 /// #![feature(slice_ptr_get, nonnull_slice_from_raw_parts)]
677 /// use std::ptr::NonNull;
679 /// let x = &mut [1, 2, 4];
680 /// let x = NonNull::slice_from_raw_parts(NonNull::new(x.as_mut_ptr()).unwrap(), x.len());
683 /// assert_eq!(x.get_unchecked_mut(1).as_ptr(), x.as_non_null_ptr().as_ptr().add(1));
686 #[unstable(feature = "slice_ptr_get", issue = "74265")]
687 #[rustc_const_unstable(feature = "const_slice_index", issue = "none")]
689 pub const unsafe fn get_unchecked_mut<I>(self, index: I) -> NonNull<I::Output>
691 I: ~const SliceIndex<[T]>,
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)) }
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> {
703 fn clone(&self) -> Self {
708 #[stable(feature = "nonnull", since = "1.25.0")]
709 impl<T: ?Sized> Copy for NonNull<T> {}
711 #[unstable(feature = "coerce_unsized", issue = "27732")]
712 impl<T: ?Sized, U: ?Sized> CoerceUnsized<NonNull<U>> for NonNull<T> where T: Unsize<U> {}
714 #[unstable(feature = "dispatch_from_dyn", issue = "none")]
715 impl<T: ?Sized, U: ?Sized> DispatchFromDyn<NonNull<U>> for NonNull<T> where T: Unsize<U> {}
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)
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)
731 #[stable(feature = "nonnull", since = "1.25.0")]
732 impl<T: ?Sized> Eq for NonNull<T> {}
734 #[stable(feature = "nonnull", since = "1.25.0")]
735 impl<T: ?Sized> PartialEq for NonNull<T> {
737 fn eq(&self, other: &Self) -> bool {
738 self.as_ptr() == other.as_ptr()
742 #[stable(feature = "nonnull", since = "1.25.0")]
743 impl<T: ?Sized> Ord for NonNull<T> {
745 fn cmp(&self, other: &Self) -> Ordering {
746 self.as_ptr().cmp(&other.as_ptr())
750 #[stable(feature = "nonnull", since = "1.25.0")]
751 impl<T: ?Sized> PartialOrd for NonNull<T> {
753 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
754 self.as_ptr().partial_cmp(&other.as_ptr())
758 #[stable(feature = "nonnull", since = "1.25.0")]
759 impl<T: ?Sized> hash::Hash for NonNull<T> {
761 fn hash<H: hash::Hasher>(&self, state: &mut H) {
762 self.as_ptr().hash(state)
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> {
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()) }
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>`.
782 /// This conversion is safe and infallible since references cannot be null.
784 fn from(reference: &mut T) -> Self {
785 // SAFETY: A mutable reference cannot be null.
786 unsafe { NonNull { pointer: reference as *mut T } }
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>`.
795 /// This conversion is safe and infallible since references cannot be null.
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 } }