1 use crate::cmp::Ordering;
2 use crate::convert::From;
5 use crate::intrinsics::assert_unsafe_precondition;
6 use crate::marker::Unsize;
7 use crate::mem::{self, MaybeUninit};
8 use crate::num::NonZeroUsize;
9 use crate::ops::{CoerceUnsized, DispatchFromDyn};
10 use crate::ptr::Unique;
11 use crate::slice::{self, SliceIndex};
13 /// `*mut T` but non-zero and [covariant].
15 /// This is often the correct thing to use when building data structures using
16 /// raw pointers, but is ultimately more dangerous to use because of its additional
17 /// properties. If you're not sure if you should use `NonNull<T>`, just use `*mut T`!
19 /// Unlike `*mut T`, the pointer must always be non-null, even if the pointer
20 /// is never dereferenced. This is so that enums may use this forbidden value
21 /// as a discriminant -- `Option<NonNull<T>>` has the same size as `*mut T`.
22 /// However the pointer may still dangle if it isn't dereferenced.
24 /// Unlike `*mut T`, `NonNull<T>` was chosen to be covariant over `T`. This makes it
25 /// possible to use `NonNull<T>` when building covariant types, but introduces the
26 /// risk of unsoundness if used in a type that shouldn't actually be covariant.
27 /// (The opposite choice was made for `*mut T` even though technically the unsoundness
28 /// could only be caused by calling unsafe functions.)
30 /// Covariance is correct for most safe abstractions, such as `Box`, `Rc`, `Arc`, `Vec`,
31 /// and `LinkedList`. This is the case because they provide a public API that follows the
32 /// normal shared XOR mutable rules of Rust.
34 /// If your type cannot safely be covariant, you must ensure it contains some
35 /// additional field to provide invariance. Often this field will be a [`PhantomData`]
36 /// type like `PhantomData<Cell<T>>` or `PhantomData<&'a mut T>`.
38 /// Notice that `NonNull<T>` has a `From` instance for `&T`. However, this does
39 /// not change the fact that mutating through a (pointer derived from a) shared
40 /// reference is undefined behavior unless the mutation happens inside an
41 /// [`UnsafeCell<T>`]. The same goes for creating a mutable reference from a shared
42 /// reference. When using this `From` instance without an `UnsafeCell<T>`,
43 /// it is your responsibility to ensure that `as_mut` is never called, and `as_ptr`
44 /// is never used for mutation.
46 /// [covariant]: https://doc.rust-lang.org/reference/subtyping.html
47 /// [`PhantomData`]: crate::marker::PhantomData
48 /// [`UnsafeCell<T>`]: crate::cell::UnsafeCell
49 #[stable(feature = "nonnull", since = "1.25.0")]
51 #[rustc_layout_scalar_valid_range_start(1)]
52 #[rustc_nonnull_optimization_guaranteed]
53 pub struct NonNull<T: ?Sized> {
57 /// `NonNull` pointers are not `Send` because the data they reference may be aliased.
58 // N.B., this impl is unnecessary, but should provide better error messages.
59 #[stable(feature = "nonnull", since = "1.25.0")]
60 impl<T: ?Sized> !Send for NonNull<T> {}
62 /// `NonNull` pointers are not `Sync` because the data they reference may be aliased.
63 // N.B., this impl is unnecessary, but should provide better error messages.
64 #[stable(feature = "nonnull", since = "1.25.0")]
65 impl<T: ?Sized> !Sync for NonNull<T> {}
67 impl<T: Sized> NonNull<T> {
68 /// Creates a new `NonNull` that is dangling, but well-aligned.
70 /// This is useful for initializing types which lazily allocate, like
73 /// Note that the pointer value may potentially represent a valid pointer to
74 /// a `T`, which means this must not be used as a "not yet initialized"
75 /// sentinel value. Types that lazily allocate must track initialization by
81 /// use std::ptr::NonNull;
83 /// let ptr = NonNull::<u32>::dangling();
84 /// // Important: don't try to access the value of `ptr` without
85 /// // initializing it first! The pointer is not null but isn't valid either!
87 #[stable(feature = "nonnull", since = "1.25.0")]
88 #[rustc_const_stable(feature = "const_nonnull_dangling", since = "1.36.0")]
91 pub const fn dangling() -> Self {
92 // SAFETY: mem::align_of() returns a non-zero usize which is then casted
93 // to a *mut T. Therefore, `ptr` is not null and the conditions for
94 // calling new_unchecked() are respected.
96 let ptr = crate::ptr::invalid_mut::<T>(mem::align_of::<T>());
97 NonNull::new_unchecked(ptr)
101 /// Returns a shared references to the value. In contrast to [`as_ref`], this does not require
102 /// that the value has to be initialized.
104 /// For the mutable counterpart see [`as_uninit_mut`].
106 /// [`as_ref`]: NonNull::as_ref
107 /// [`as_uninit_mut`]: NonNull::as_uninit_mut
111 /// When calling this method, you have to ensure that all of the following is true:
113 /// * The pointer must be properly aligned.
115 /// * It must be "dereferenceable" in the sense defined in [the module documentation].
117 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
118 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
119 /// In particular, while this reference exists, the memory the pointer points to must
120 /// not get mutated (except inside `UnsafeCell`).
122 /// This applies even if the result of this method is unused!
124 /// [the module documentation]: crate::ptr#safety
127 #[unstable(feature = "ptr_as_uninit", issue = "75402")]
128 #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")]
129 pub const unsafe fn as_uninit_ref<'a>(self) -> &'a MaybeUninit<T> {
130 // SAFETY: the caller must guarantee that `self` meets all the
131 // requirements for a reference.
132 unsafe { &*self.cast().as_ptr() }
135 /// Returns a unique references to the value. In contrast to [`as_mut`], this does not require
136 /// that the value has to be initialized.
138 /// For the shared counterpart see [`as_uninit_ref`].
140 /// [`as_mut`]: NonNull::as_mut
141 /// [`as_uninit_ref`]: NonNull::as_uninit_ref
145 /// When calling this method, you have to ensure that all of the following is true:
147 /// * The pointer must be properly aligned.
149 /// * It must be "dereferenceable" in the sense defined in [the module documentation].
151 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
152 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
153 /// In particular, while this reference exists, the memory the pointer points to must
154 /// not get accessed (read or written) through any other pointer.
156 /// This applies even if the result of this method is unused!
158 /// [the module documentation]: crate::ptr#safety
161 #[unstable(feature = "ptr_as_uninit", issue = "75402")]
162 #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")]
163 pub const unsafe fn as_uninit_mut<'a>(self) -> &'a mut MaybeUninit<T> {
164 // SAFETY: the caller must guarantee that `self` meets all the
165 // requirements for a reference.
166 unsafe { &mut *self.cast().as_ptr() }
170 impl<T: ?Sized> NonNull<T> {
171 /// Creates a new `NonNull`.
175 /// `ptr` must be non-null.
180 /// use std::ptr::NonNull;
182 /// let mut x = 0u32;
183 /// let ptr = unsafe { NonNull::new_unchecked(&mut x as *mut _) };
186 /// *Incorrect* usage of this function:
189 /// use std::ptr::NonNull;
191 /// // NEVER DO THAT!!! This is undefined behavior. ⚠️
192 /// let ptr = unsafe { NonNull::<u32>::new_unchecked(std::ptr::null_mut()) };
194 #[stable(feature = "nonnull", since = "1.25.0")]
195 #[rustc_const_stable(feature = "const_nonnull_new_unchecked", since = "1.25.0")]
197 pub const unsafe fn new_unchecked(ptr: *mut T) -> Self {
198 // SAFETY: the caller must guarantee that `ptr` is non-null.
200 assert_unsafe_precondition!([T: ?Sized](ptr: *mut T) => !ptr.is_null());
201 NonNull { pointer: ptr as _ }
205 /// Creates a new `NonNull` if `ptr` is non-null.
210 /// use std::ptr::NonNull;
212 /// let mut x = 0u32;
213 /// let ptr = NonNull::<u32>::new(&mut x as *mut _).expect("ptr is null!");
215 /// if let Some(ptr) = NonNull::<u32>::new(std::ptr::null_mut()) {
219 #[stable(feature = "nonnull", since = "1.25.0")]
220 #[rustc_const_unstable(feature = "const_nonnull_new", issue = "93235")]
222 pub const fn new(ptr: *mut T) -> Option<Self> {
224 // SAFETY: The pointer is already checked and is not null
225 Some(unsafe { Self::new_unchecked(ptr) })
231 /// Performs the same functionality as [`std::ptr::from_raw_parts`], except that a
232 /// `NonNull` pointer is returned, as opposed to a raw `*const` pointer.
234 /// See the documentation of [`std::ptr::from_raw_parts`] for more details.
236 /// [`std::ptr::from_raw_parts`]: crate::ptr::from_raw_parts
237 #[unstable(feature = "ptr_metadata", issue = "81513")]
238 #[rustc_const_unstable(feature = "ptr_metadata", issue = "81513")]
240 pub const fn from_raw_parts(
241 data_address: NonNull<()>,
242 metadata: <T as super::Pointee>::Metadata,
244 // SAFETY: The result of `ptr::from::raw_parts_mut` is non-null because `data_address` is.
246 NonNull::new_unchecked(super::from_raw_parts_mut(data_address.as_ptr(), metadata))
250 /// Decompose a (possibly wide) pointer into its address and metadata components.
252 /// The pointer can be later reconstructed with [`NonNull::from_raw_parts`].
253 #[unstable(feature = "ptr_metadata", issue = "81513")]
254 #[rustc_const_unstable(feature = "ptr_metadata", issue = "81513")]
255 #[must_use = "this returns the result of the operation, \
256 without modifying the original"]
258 pub const fn to_raw_parts(self) -> (NonNull<()>, <T as super::Pointee>::Metadata) {
259 (self.cast(), super::metadata(self.as_ptr()))
262 /// Gets the "address" portion of the pointer.
264 /// For more details see the equivalent method on a raw pointer, [`pointer::addr`].
266 /// This API and its claimed semantics are part of the Strict Provenance experiment,
267 /// see the [`ptr` module documentation][crate::ptr].
270 #[unstable(feature = "strict_provenance", issue = "95228")]
271 pub fn addr(self) -> NonZeroUsize
275 // SAFETY: The pointer is guaranteed by the type to be non-null,
276 // meaning that the address will be non-zero.
277 unsafe { NonZeroUsize::new_unchecked(self.pointer.addr()) }
280 /// Creates a new pointer with the given address.
282 /// For more details see the equivalent method on a raw pointer, [`pointer::with_addr`].
284 /// This API and its claimed semantics are part of the Strict Provenance experiment,
285 /// see the [`ptr` module documentation][crate::ptr].
288 #[unstable(feature = "strict_provenance", issue = "95228")]
289 pub fn with_addr(self, addr: NonZeroUsize) -> Self
293 // SAFETY: The result of `ptr::from::with_addr` is non-null because `addr` is guaranteed to be non-zero.
294 unsafe { NonNull::new_unchecked(self.pointer.with_addr(addr.get()) as *mut _) }
297 /// Creates a new pointer by mapping `self`'s address to a new one.
299 /// For more details see the equivalent method on a raw pointer, [`pointer::map_addr`].
301 /// This API and its claimed semantics are part of the Strict Provenance experiment,
302 /// see the [`ptr` module documentation][crate::ptr].
305 #[unstable(feature = "strict_provenance", issue = "95228")]
306 pub fn map_addr(self, f: impl FnOnce(NonZeroUsize) -> NonZeroUsize) -> Self
310 self.with_addr(f(self.addr()))
313 /// Acquires the underlying `*mut` pointer.
318 /// use std::ptr::NonNull;
320 /// let mut x = 0u32;
321 /// let ptr = NonNull::new(&mut x).expect("ptr is null!");
323 /// let x_value = unsafe { *ptr.as_ptr() };
324 /// assert_eq!(x_value, 0);
326 /// unsafe { *ptr.as_ptr() += 2; }
327 /// let x_value = unsafe { *ptr.as_ptr() };
328 /// assert_eq!(x_value, 2);
330 #[stable(feature = "nonnull", since = "1.25.0")]
331 #[rustc_const_stable(feature = "const_nonnull_as_ptr", since = "1.32.0")]
334 pub const fn as_ptr(self) -> *mut T {
335 self.pointer as *mut T
338 /// Returns a shared reference to the value. If the value may be uninitialized, [`as_uninit_ref`]
339 /// must be used instead.
341 /// For the mutable counterpart see [`as_mut`].
343 /// [`as_uninit_ref`]: NonNull::as_uninit_ref
344 /// [`as_mut`]: NonNull::as_mut
348 /// When calling this method, you have to ensure that all of the following is true:
350 /// * The pointer must be properly aligned.
352 /// * It must be "dereferenceable" in the sense defined in [the module documentation].
354 /// * The pointer must point to an initialized instance of `T`.
356 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
357 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
358 /// In particular, while this reference exists, the memory the pointer points to must
359 /// not get mutated (except inside `UnsafeCell`).
361 /// This applies even if the result of this method is unused!
362 /// (The part about being initialized is not yet fully decided, but until
363 /// it is, the only safe approach is to ensure that they are indeed initialized.)
368 /// use std::ptr::NonNull;
370 /// let mut x = 0u32;
371 /// let ptr = NonNull::new(&mut x as *mut _).expect("ptr is null!");
373 /// let ref_x = unsafe { ptr.as_ref() };
374 /// println!("{ref_x}");
377 /// [the module documentation]: crate::ptr#safety
378 #[stable(feature = "nonnull", since = "1.25.0")]
379 #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")]
382 pub const unsafe fn as_ref<'a>(&self) -> &'a T {
383 // SAFETY: the caller must guarantee that `self` meets all the
384 // requirements for a reference.
385 unsafe { &*self.as_ptr() }
388 /// Returns a unique reference to the value. If the value may be uninitialized, [`as_uninit_mut`]
389 /// must be used instead.
391 /// For the shared counterpart see [`as_ref`].
393 /// [`as_uninit_mut`]: NonNull::as_uninit_mut
394 /// [`as_ref`]: NonNull::as_ref
398 /// When calling this method, you have to ensure that all of the following is true:
400 /// * The pointer must be properly aligned.
402 /// * It must be "dereferenceable" in the sense defined in [the module documentation].
404 /// * The pointer must point to an initialized instance of `T`.
406 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
407 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
408 /// In particular, while this reference exists, the memory the pointer points to must
409 /// not get accessed (read or written) through any other pointer.
411 /// This applies even if the result of this method is unused!
412 /// (The part about being initialized is not yet fully decided, but until
413 /// it is, the only safe approach is to ensure that they are indeed initialized.)
417 /// use std::ptr::NonNull;
419 /// let mut x = 0u32;
420 /// let mut ptr = NonNull::new(&mut x).expect("null pointer");
422 /// let x_ref = unsafe { ptr.as_mut() };
423 /// assert_eq!(*x_ref, 0);
425 /// assert_eq!(*x_ref, 2);
428 /// [the module documentation]: crate::ptr#safety
429 #[stable(feature = "nonnull", since = "1.25.0")]
430 #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")]
433 pub const unsafe fn as_mut<'a>(&mut self) -> &'a mut T {
434 // SAFETY: the caller must guarantee that `self` meets all the
435 // requirements for a mutable reference.
436 unsafe { &mut *self.as_ptr() }
439 /// Casts to a pointer of another type.
444 /// use std::ptr::NonNull;
446 /// let mut x = 0u32;
447 /// let ptr = NonNull::new(&mut x as *mut _).expect("null pointer");
449 /// let casted_ptr = ptr.cast::<i8>();
450 /// let raw_ptr: *mut i8 = casted_ptr.as_ptr();
452 #[stable(feature = "nonnull_cast", since = "1.27.0")]
453 #[rustc_const_stable(feature = "const_nonnull_cast", since = "1.36.0")]
454 #[must_use = "this returns the result of the operation, \
455 without modifying the original"]
457 pub const fn cast<U>(self) -> NonNull<U> {
458 // SAFETY: `self` is a `NonNull` pointer which is necessarily non-null
459 unsafe { NonNull::new_unchecked(self.as_ptr() as *mut U) }
463 impl<T> NonNull<[T]> {
464 /// Creates a non-null raw slice from a thin pointer and a length.
466 /// The `len` argument is the number of **elements**, not the number of bytes.
468 /// This function is safe, but dereferencing the return value is unsafe.
469 /// See the documentation of [`slice::from_raw_parts`] for slice safety requirements.
474 /// #![feature(nonnull_slice_from_raw_parts)]
476 /// use std::ptr::NonNull;
478 /// // create a slice pointer when starting out with a pointer to the first element
479 /// let mut x = [5, 6, 7];
480 /// let nonnull_pointer = NonNull::new(x.as_mut_ptr()).unwrap();
481 /// let slice = NonNull::slice_from_raw_parts(nonnull_pointer, 3);
482 /// assert_eq!(unsafe { slice.as_ref()[2] }, 7);
485 /// (Note that this example artificially demonstrates a use of this method,
486 /// but `let slice = NonNull::from(&x[..]);` would be a better way to write code like this.)
487 #[unstable(feature = "nonnull_slice_from_raw_parts", issue = "71941")]
488 #[rustc_const_unstable(feature = "const_nonnull_slice_from_raw_parts", issue = "71941")]
491 pub const fn slice_from_raw_parts(data: NonNull<T>, len: usize) -> Self {
492 // SAFETY: `data` is a `NonNull` pointer which is necessarily non-null
493 unsafe { Self::new_unchecked(super::slice_from_raw_parts_mut(data.as_ptr(), len)) }
496 /// Returns the length of a non-null raw slice.
498 /// The returned value is the number of **elements**, not the number of bytes.
500 /// This function is safe, even when the non-null raw slice cannot be dereferenced to a slice
501 /// because the pointer does not have a valid address.
506 /// #![feature(nonnull_slice_from_raw_parts)]
507 /// use std::ptr::NonNull;
509 /// let slice: NonNull<[i8]> = NonNull::slice_from_raw_parts(NonNull::dangling(), 3);
510 /// assert_eq!(slice.len(), 3);
512 #[stable(feature = "slice_ptr_len_nonnull", since = "1.63.0")]
513 #[rustc_const_stable(feature = "const_slice_ptr_len_nonnull", since = "1.63.0")]
514 #[rustc_allow_const_fn_unstable(const_slice_ptr_len)]
517 pub const fn len(self) -> usize {
521 /// Returns a non-null pointer to the slice's buffer.
526 /// #![feature(slice_ptr_get, nonnull_slice_from_raw_parts)]
527 /// use std::ptr::NonNull;
529 /// let slice: NonNull<[i8]> = NonNull::slice_from_raw_parts(NonNull::dangling(), 3);
530 /// assert_eq!(slice.as_non_null_ptr(), NonNull::<i8>::dangling());
534 #[unstable(feature = "slice_ptr_get", issue = "74265")]
535 #[rustc_const_unstable(feature = "slice_ptr_get", issue = "74265")]
536 pub const fn as_non_null_ptr(self) -> NonNull<T> {
537 // SAFETY: We know `self` is non-null.
538 unsafe { NonNull::new_unchecked(self.as_ptr().as_mut_ptr()) }
541 /// Returns a raw pointer to the slice's buffer.
546 /// #![feature(slice_ptr_get, nonnull_slice_from_raw_parts)]
547 /// use std::ptr::NonNull;
549 /// let slice: NonNull<[i8]> = NonNull::slice_from_raw_parts(NonNull::dangling(), 3);
550 /// assert_eq!(slice.as_mut_ptr(), NonNull::<i8>::dangling().as_ptr());
554 #[unstable(feature = "slice_ptr_get", issue = "74265")]
555 #[rustc_const_unstable(feature = "slice_ptr_get", issue = "74265")]
556 pub const fn as_mut_ptr(self) -> *mut T {
557 self.as_non_null_ptr().as_ptr()
560 /// Returns a shared reference to a slice of possibly uninitialized values. In contrast to
561 /// [`as_ref`], this does not require that the value has to be initialized.
563 /// For the mutable counterpart see [`as_uninit_slice_mut`].
565 /// [`as_ref`]: NonNull::as_ref
566 /// [`as_uninit_slice_mut`]: NonNull::as_uninit_slice_mut
570 /// When calling this method, you have to ensure that all of the following is true:
572 /// * The pointer must be [valid] for reads for `ptr.len() * mem::size_of::<T>()` many bytes,
573 /// and it must be properly aligned. This means in particular:
575 /// * The entire memory range of this slice must be contained within a single allocated object!
576 /// Slices can never span across multiple allocated objects.
578 /// * The pointer must be aligned even for zero-length slices. One
579 /// reason for this is that enum layout optimizations may rely on references
580 /// (including slices of any length) being aligned and non-null to distinguish
581 /// them from other data. You can obtain a pointer that is usable as `data`
582 /// for zero-length slices using [`NonNull::dangling()`].
584 /// * The total size `ptr.len() * mem::size_of::<T>()` of the slice must be no larger than `isize::MAX`.
585 /// See the safety documentation of [`pointer::offset`].
587 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
588 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
589 /// In particular, while this reference exists, the memory the pointer points to must
590 /// not get mutated (except inside `UnsafeCell`).
592 /// This applies even if the result of this method is unused!
594 /// See also [`slice::from_raw_parts`].
596 /// [valid]: crate::ptr#safety
599 #[unstable(feature = "ptr_as_uninit", issue = "75402")]
600 #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")]
601 pub const unsafe fn as_uninit_slice<'a>(self) -> &'a [MaybeUninit<T>] {
602 // SAFETY: the caller must uphold the safety contract for `as_uninit_slice`.
603 unsafe { slice::from_raw_parts(self.cast().as_ptr(), self.len()) }
606 /// Returns a unique reference to a slice of possibly uninitialized values. In contrast to
607 /// [`as_mut`], this does not require that the value has to be initialized.
609 /// For the shared counterpart see [`as_uninit_slice`].
611 /// [`as_mut`]: NonNull::as_mut
612 /// [`as_uninit_slice`]: NonNull::as_uninit_slice
616 /// When calling this method, you have to ensure that all of the following is true:
618 /// * The pointer must be [valid] for reads and writes for `ptr.len() * mem::size_of::<T>()`
619 /// many bytes, and it must be properly aligned. This means in particular:
621 /// * The entire memory range of this slice must be contained within a single allocated object!
622 /// Slices can never span across multiple allocated objects.
624 /// * The pointer must be aligned even for zero-length slices. One
625 /// reason for this is that enum layout optimizations may rely on references
626 /// (including slices of any length) being aligned and non-null to distinguish
627 /// them from other data. You can obtain a pointer that is usable as `data`
628 /// for zero-length slices using [`NonNull::dangling()`].
630 /// * The total size `ptr.len() * mem::size_of::<T>()` of the slice must be no larger than `isize::MAX`.
631 /// See the safety documentation of [`pointer::offset`].
633 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
634 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
635 /// In particular, while this reference exists, the memory the pointer points to must
636 /// not get accessed (read or written) through any other pointer.
638 /// This applies even if the result of this method is unused!
640 /// See also [`slice::from_raw_parts_mut`].
642 /// [valid]: crate::ptr#safety
647 /// #![feature(allocator_api, ptr_as_uninit)]
649 /// use std::alloc::{Allocator, Layout, Global};
650 /// use std::mem::MaybeUninit;
651 /// use std::ptr::NonNull;
653 /// let memory: NonNull<[u8]> = Global.allocate(Layout::new::<[u8; 32]>())?;
654 /// // This is safe as `memory` is valid for reads and writes for `memory.len()` many bytes.
655 /// // Note that calling `memory.as_mut()` is not allowed here as the content may be uninitialized.
656 /// # #[allow(unused_variables)]
657 /// let slice: &mut [MaybeUninit<u8>] = unsafe { memory.as_uninit_slice_mut() };
658 /// # Ok::<_, std::alloc::AllocError>(())
662 #[unstable(feature = "ptr_as_uninit", issue = "75402")]
663 #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")]
664 pub const unsafe fn as_uninit_slice_mut<'a>(self) -> &'a mut [MaybeUninit<T>] {
665 // SAFETY: the caller must uphold the safety contract for `as_uninit_slice_mut`.
666 unsafe { slice::from_raw_parts_mut(self.cast().as_ptr(), self.len()) }
669 /// Returns a raw pointer to an element or subslice, without doing bounds
672 /// Calling this method with an out-of-bounds index or when `self` is not dereferenceable
673 /// is *[undefined behavior]* even if the resulting pointer is not used.
675 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
680 /// #![feature(slice_ptr_get, nonnull_slice_from_raw_parts)]
681 /// use std::ptr::NonNull;
683 /// let x = &mut [1, 2, 4];
684 /// let x = NonNull::slice_from_raw_parts(NonNull::new(x.as_mut_ptr()).unwrap(), x.len());
687 /// assert_eq!(x.get_unchecked_mut(1).as_ptr(), x.as_non_null_ptr().as_ptr().add(1));
690 #[unstable(feature = "slice_ptr_get", issue = "74265")]
691 #[rustc_const_unstable(feature = "const_slice_index", issue = "none")]
693 pub const unsafe fn get_unchecked_mut<I>(self, index: I) -> NonNull<I::Output>
695 I: ~const SliceIndex<[T]>,
697 // SAFETY: the caller ensures that `self` is dereferenceable and `index` in-bounds.
698 // As a consequence, the resulting pointer cannot be null.
699 unsafe { NonNull::new_unchecked(self.as_ptr().get_unchecked_mut(index)) }
703 #[stable(feature = "nonnull", since = "1.25.0")]
704 #[rustc_const_unstable(feature = "const_clone", issue = "91805")]
705 impl<T: ?Sized> const Clone for NonNull<T> {
707 fn clone(&self) -> Self {
712 #[stable(feature = "nonnull", since = "1.25.0")]
713 impl<T: ?Sized> Copy for NonNull<T> {}
715 #[unstable(feature = "coerce_unsized", issue = "27732")]
716 impl<T: ?Sized, U: ?Sized> CoerceUnsized<NonNull<U>> for NonNull<T> where T: Unsize<U> {}
718 #[unstable(feature = "dispatch_from_dyn", issue = "none")]
719 impl<T: ?Sized, U: ?Sized> DispatchFromDyn<NonNull<U>> for NonNull<T> where T: Unsize<U> {}
721 #[stable(feature = "nonnull", since = "1.25.0")]
722 impl<T: ?Sized> fmt::Debug for NonNull<T> {
723 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
724 fmt::Pointer::fmt(&self.as_ptr(), f)
728 #[stable(feature = "nonnull", since = "1.25.0")]
729 impl<T: ?Sized> fmt::Pointer for NonNull<T> {
730 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
731 fmt::Pointer::fmt(&self.as_ptr(), f)
735 #[stable(feature = "nonnull", since = "1.25.0")]
736 impl<T: ?Sized> Eq for NonNull<T> {}
738 #[stable(feature = "nonnull", since = "1.25.0")]
739 impl<T: ?Sized> PartialEq for NonNull<T> {
741 fn eq(&self, other: &Self) -> bool {
742 self.as_ptr() == other.as_ptr()
746 #[stable(feature = "nonnull", since = "1.25.0")]
747 impl<T: ?Sized> Ord for NonNull<T> {
749 fn cmp(&self, other: &Self) -> Ordering {
750 self.as_ptr().cmp(&other.as_ptr())
754 #[stable(feature = "nonnull", since = "1.25.0")]
755 impl<T: ?Sized> PartialOrd for NonNull<T> {
757 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
758 self.as_ptr().partial_cmp(&other.as_ptr())
762 #[stable(feature = "nonnull", since = "1.25.0")]
763 impl<T: ?Sized> hash::Hash for NonNull<T> {
765 fn hash<H: hash::Hasher>(&self, state: &mut H) {
766 self.as_ptr().hash(state)
770 #[unstable(feature = "ptr_internals", issue = "none")]
771 #[rustc_const_unstable(feature = "const_convert", issue = "88674")]
772 impl<T: ?Sized> const From<Unique<T>> for NonNull<T> {
774 fn from(unique: Unique<T>) -> Self {
775 // SAFETY: A Unique pointer cannot be null, so the conditions for
776 // new_unchecked() are respected.
777 unsafe { NonNull::new_unchecked(unique.as_ptr()) }
781 #[stable(feature = "nonnull", since = "1.25.0")]
782 #[rustc_const_unstable(feature = "const_convert", issue = "88674")]
783 impl<T: ?Sized> const From<&mut T> for NonNull<T> {
784 /// Converts a `&mut T` to a `NonNull<T>`.
786 /// This conversion is safe and infallible since references cannot be null.
788 fn from(reference: &mut T) -> Self {
789 // SAFETY: A mutable reference cannot be null.
790 unsafe { NonNull { pointer: reference as *mut T } }
794 #[stable(feature = "nonnull", since = "1.25.0")]
795 #[rustc_const_unstable(feature = "const_convert", issue = "88674")]
796 impl<T: ?Sized> const From<&T> for NonNull<T> {
797 /// Converts a `&T` to a `NonNull<T>`.
799 /// This conversion is safe and infallible since references cannot be null.
801 fn from(reference: &T) -> Self {
802 // SAFETY: A reference cannot be null, so the conditions for
803 // new_unchecked() are respected.
804 unsafe { NonNull { pointer: reference as *const T } }