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 /// [`PhantomData`]: crate::marker::PhantomData
46 /// [`UnsafeCell<T>`]: crate::cell::UnsafeCell
47 #[stable(feature = "nonnull", since = "1.25.0")]
49 #[rustc_layout_scalar_valid_range_start(1)]
50 #[rustc_nonnull_optimization_guaranteed]
51 pub struct NonNull<T: ?Sized> {
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> {}
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> {}
65 impl<T: Sized> NonNull<T> {
66 /// Creates a new `NonNull` that is dangling, but well-aligned.
68 /// This is useful for initializing types which lazily allocate, like
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
79 /// use std::ptr::NonNull;
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!
85 #[stable(feature = "nonnull", since = "1.25.0")]
86 #[rustc_const_stable(feature = "const_nonnull_dangling", since = "1.36.0")]
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.
94 let ptr = crate::ptr::invalid_mut::<T>(mem::align_of::<T>());
95 NonNull::new_unchecked(ptr)
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.
102 /// For the mutable counterpart see [`as_uninit_mut`].
104 /// [`as_ref`]: NonNull::as_ref
105 /// [`as_uninit_mut`]: NonNull::as_uninit_mut
109 /// When calling this method, you have to ensure that all of the following is true:
111 /// * The pointer must be properly aligned.
113 /// * It must be "dereferenceable" in the sense defined in [the module documentation].
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`).
120 /// This applies even if the result of this method is unused!
122 /// [the module documentation]: crate::ptr#safety
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() }
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.
136 /// For the shared counterpart see [`as_uninit_ref`].
138 /// [`as_mut`]: NonNull::as_mut
139 /// [`as_uninit_ref`]: NonNull::as_uninit_ref
143 /// When calling this method, you have to ensure that all of the following is true:
145 /// * The pointer must be properly aligned.
147 /// * It must be "dereferenceable" in the sense defined in [the module documentation].
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.
154 /// This applies even if the result of this method is unused!
156 /// [the module documentation]: crate::ptr#safety
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() }
168 impl<T: ?Sized> NonNull<T> {
169 /// Creates a new `NonNull`.
173 /// `ptr` must be non-null.
178 /// use std::ptr::NonNull;
180 /// let mut x = 0u32;
181 /// let ptr = unsafe { NonNull::new_unchecked(&mut x as *mut _) };
184 /// *Incorrect* usage of this function:
187 /// use std::ptr::NonNull;
189 /// // NEVER DO THAT!!! This is undefined behavior. ⚠️
190 /// let ptr = unsafe { NonNull::<u32>::new_unchecked(std::ptr::null_mut()) };
192 #[stable(feature = "nonnull", since = "1.25.0")]
193 #[rustc_const_stable(feature = "const_nonnull_new_unchecked", since = "1.25.0")]
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 _ } }
200 /// Creates a new `NonNull` if `ptr` is non-null.
205 /// use std::ptr::NonNull;
207 /// let mut x = 0u32;
208 /// let ptr = NonNull::<u32>::new(&mut x as *mut _).expect("ptr is null!");
210 /// if let Some(ptr) = NonNull::<u32>::new(std::ptr::null_mut()) {
214 #[stable(feature = "nonnull", since = "1.25.0")]
215 #[rustc_const_unstable(feature = "const_nonnull_new", issue = "93235")]
217 pub const fn new(ptr: *mut T) -> Option<Self> {
219 // SAFETY: The pointer is already checked and is not null
220 Some(unsafe { Self::new_unchecked(ptr) })
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.
229 /// See the documentation of [`std::ptr::from_raw_parts`] for more details.
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")]
235 pub const fn from_raw_parts(
236 data_address: NonNull<()>,
237 metadata: <T as super::Pointee>::Metadata,
239 // SAFETY: The result of `ptr::from::raw_parts_mut` is non-null because `data_address` is.
241 NonNull::new_unchecked(super::from_raw_parts_mut(data_address.as_ptr(), metadata))
245 /// Decompose a (possibly wide) pointer into its address and metadata components.
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"]
253 pub const fn to_raw_parts(self) -> (NonNull<()>, <T as super::Pointee>::Metadata) {
254 (self.cast(), super::metadata(self.as_ptr()))
257 /// Gets the "address" portion of the pointer.
259 /// For more details see the equivalent method on a raw pointer, [`pointer::addr`].
261 /// This API and its claimed semantics are part of the Strict Provenance experiment,
262 /// see the [`ptr` module documentation][crate::ptr].
265 #[unstable(feature = "strict_provenance", issue = "95228")]
266 pub fn addr(self) -> NonZeroUsize
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()) }
275 /// Creates a new pointer with the given address.
277 /// For more details see the equivalent method on a raw pointer, [`pointer::with_addr`].
279 /// This API and its claimed semantics are part of the Strict Provenance experiment,
280 /// see the [`ptr` module documentation][crate::ptr].
283 #[unstable(feature = "strict_provenance", issue = "95228")]
284 pub fn with_addr(self, addr: NonZeroUsize) -> Self
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 _) }
292 /// Creates a new pointer by mapping `self`'s address to a new one.
294 /// For more details see the equivalent method on a raw pointer, [`pointer::map_addr`].
296 /// This API and its claimed semantics are part of the Strict Provenance experiment,
297 /// see the [`ptr` module documentation][crate::ptr].
300 #[unstable(feature = "strict_provenance", issue = "95228")]
301 pub fn map_addr(self, f: impl FnOnce(NonZeroUsize) -> NonZeroUsize) -> Self
305 self.with_addr(f(self.addr()))
308 /// Acquires the underlying `*mut` pointer.
313 /// use std::ptr::NonNull;
315 /// let mut x = 0u32;
316 /// let ptr = NonNull::new(&mut x).expect("ptr is null!");
318 /// let x_value = unsafe { *ptr.as_ptr() };
319 /// assert_eq!(x_value, 0);
321 /// unsafe { *ptr.as_ptr() += 2; }
322 /// let x_value = unsafe { *ptr.as_ptr() };
323 /// assert_eq!(x_value, 2);
325 #[stable(feature = "nonnull", since = "1.25.0")]
326 #[rustc_const_stable(feature = "const_nonnull_as_ptr", since = "1.32.0")]
329 pub const fn as_ptr(self) -> *mut T {
330 self.pointer as *mut T
333 /// Returns a shared reference to the value. If the value may be uninitialized, [`as_uninit_ref`]
334 /// must be used instead.
336 /// For the mutable counterpart see [`as_mut`].
338 /// [`as_uninit_ref`]: NonNull::as_uninit_ref
339 /// [`as_mut`]: NonNull::as_mut
343 /// When calling this method, you have to ensure that all of the following is true:
345 /// * The pointer must be properly aligned.
347 /// * It must be "dereferenceable" in the sense defined in [the module documentation].
349 /// * The pointer must point to an initialized instance of `T`.
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`).
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.)
363 /// use std::ptr::NonNull;
365 /// let mut x = 0u32;
366 /// let ptr = NonNull::new(&mut x as *mut _).expect("ptr is null!");
368 /// let ref_x = unsafe { ptr.as_ref() };
369 /// println!("{ref_x}");
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")]
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() }
383 /// Returns a unique reference to the value. If the value may be uninitialized, [`as_uninit_mut`]
384 /// must be used instead.
386 /// For the shared counterpart see [`as_ref`].
388 /// [`as_uninit_mut`]: NonNull::as_uninit_mut
389 /// [`as_ref`]: NonNull::as_ref
393 /// When calling this method, you have to ensure that all of the following is true:
395 /// * The pointer must be properly aligned.
397 /// * It must be "dereferenceable" in the sense defined in [the module documentation].
399 /// * The pointer must point to an initialized instance of `T`.
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.
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.)
412 /// use std::ptr::NonNull;
414 /// let mut x = 0u32;
415 /// let mut ptr = NonNull::new(&mut x).expect("null pointer");
417 /// let x_ref = unsafe { ptr.as_mut() };
418 /// assert_eq!(*x_ref, 0);
420 /// assert_eq!(*x_ref, 2);
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")]
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() }
434 /// Casts to a pointer of another type.
439 /// use std::ptr::NonNull;
441 /// let mut x = 0u32;
442 /// let ptr = NonNull::new(&mut x as *mut _).expect("null pointer");
444 /// let casted_ptr = ptr.cast::<i8>();
445 /// let raw_ptr: *mut i8 = casted_ptr.as_ptr();
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"]
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) }
458 impl<T> NonNull<[T]> {
459 /// Creates a non-null raw slice from a thin pointer and a length.
461 /// The `len` argument is the number of **elements**, not the number of bytes.
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.
469 /// #![feature(nonnull_slice_from_raw_parts)]
471 /// use std::ptr::NonNull;
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);
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")]
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)) }
491 /// Returns the length of a non-null raw slice.
493 /// The returned value is the number of **elements**, not the number of bytes.
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.
501 /// #![feature(slice_ptr_len, nonnull_slice_from_raw_parts)]
502 /// use std::ptr::NonNull;
504 /// let slice: NonNull<[i8]> = NonNull::slice_from_raw_parts(NonNull::dangling(), 3);
505 /// assert_eq!(slice.len(), 3);
507 #[unstable(feature = "slice_ptr_len", issue = "71146")]
508 #[rustc_const_unstable(feature = "const_slice_ptr_len", issue = "71146")]
511 pub const fn len(self) -> usize {
515 /// Returns a non-null pointer to the slice's buffer.
520 /// #![feature(slice_ptr_get, nonnull_slice_from_raw_parts)]
521 /// use std::ptr::NonNull;
523 /// let slice: NonNull<[i8]> = NonNull::slice_from_raw_parts(NonNull::dangling(), 3);
524 /// assert_eq!(slice.as_non_null_ptr(), NonNull::<i8>::dangling());
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()) }
535 /// Returns a raw pointer to the slice's buffer.
540 /// #![feature(slice_ptr_get, nonnull_slice_from_raw_parts)]
541 /// use std::ptr::NonNull;
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());
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()
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.
557 /// For the mutable counterpart see [`as_uninit_slice_mut`].
559 /// [`as_ref`]: NonNull::as_ref
560 /// [`as_uninit_slice_mut`]: NonNull::as_uninit_slice_mut
564 /// When calling this method, you have to ensure that all of the following is true:
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:
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.
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()`].
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`].
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`).
586 /// This applies even if the result of this method is unused!
588 /// See also [`slice::from_raw_parts`].
590 /// [valid]: crate::ptr#safety
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()) }
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.
603 /// For the shared counterpart see [`as_uninit_slice`].
605 /// [`as_mut`]: NonNull::as_mut
606 /// [`as_uninit_slice`]: NonNull::as_uninit_slice
610 /// When calling this method, you have to ensure that all of the following is true:
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:
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.
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()`].
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`].
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.
632 /// This applies even if the result of this method is unused!
634 /// See also [`slice::from_raw_parts_mut`].
636 /// [valid]: crate::ptr#safety
641 /// #![feature(allocator_api, ptr_as_uninit)]
643 /// use std::alloc::{Allocator, Layout, Global};
644 /// use std::mem::MaybeUninit;
645 /// use std::ptr::NonNull;
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>(())
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()) }
663 /// Returns a raw pointer to an element or subslice, without doing bounds
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.
669 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
674 /// #![feature(slice_ptr_get, nonnull_slice_from_raw_parts)]
675 /// use std::ptr::NonNull;
677 /// let x = &mut [1, 2, 4];
678 /// let x = NonNull::slice_from_raw_parts(NonNull::new(x.as_mut_ptr()).unwrap(), x.len());
681 /// assert_eq!(x.get_unchecked_mut(1).as_ptr(), x.as_non_null_ptr().as_ptr().add(1));
684 #[unstable(feature = "slice_ptr_get", issue = "74265")]
685 #[rustc_const_unstable(feature = "const_slice_index", issue = "none")]
687 pub const unsafe fn get_unchecked_mut<I>(self, index: I) -> NonNull<I::Output>
689 I: ~const SliceIndex<[T]>,
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)) }
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> {
701 fn clone(&self) -> Self {
706 #[stable(feature = "nonnull", since = "1.25.0")]
707 impl<T: ?Sized> Copy for NonNull<T> {}
709 #[unstable(feature = "coerce_unsized", issue = "27732")]
710 impl<T: ?Sized, U: ?Sized> CoerceUnsized<NonNull<U>> for NonNull<T> where T: Unsize<U> {}
712 #[unstable(feature = "dispatch_from_dyn", issue = "none")]
713 impl<T: ?Sized, U: ?Sized> DispatchFromDyn<NonNull<U>> for NonNull<T> where T: Unsize<U> {}
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)
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)
729 #[stable(feature = "nonnull", since = "1.25.0")]
730 impl<T: ?Sized> Eq for NonNull<T> {}
732 #[stable(feature = "nonnull", since = "1.25.0")]
733 impl<T: ?Sized> PartialEq for NonNull<T> {
735 fn eq(&self, other: &Self) -> bool {
736 self.as_ptr() == other.as_ptr()
740 #[stable(feature = "nonnull", since = "1.25.0")]
741 impl<T: ?Sized> Ord for NonNull<T> {
743 fn cmp(&self, other: &Self) -> Ordering {
744 self.as_ptr().cmp(&other.as_ptr())
748 #[stable(feature = "nonnull", since = "1.25.0")]
749 impl<T: ?Sized> PartialOrd for NonNull<T> {
751 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
752 self.as_ptr().partial_cmp(&other.as_ptr())
756 #[stable(feature = "nonnull", since = "1.25.0")]
757 impl<T: ?Sized> hash::Hash for NonNull<T> {
759 fn hash<H: hash::Hasher>(&self, state: &mut H) {
760 self.as_ptr().hash(state)
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> {
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()) }
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>`.
780 /// This conversion is safe and infallible since references cannot be null.
782 fn from(reference: &mut T) -> Self {
783 // SAFETY: A mutable reference cannot be null.
784 unsafe { NonNull { pointer: reference as *mut T } }
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>`.
793 /// This conversion is safe and infallible since references cannot be null.
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 } }