Struct NonNull
#[repr(transparent)]
pub struct NonNull<T: PointeeSized> { pub(in ::ptr::non_null) pointer: *const T is !null }
*mut T but non-zero and covariant.
This is often the correct thing to use when building data structures using
raw pointers, but is ultimately more dangerous to use because of its additional
properties. If you're not sure if you should use NonNull<T>, just use *mut T!
Unlike *mut T, the pointer must always be non-null, even if the pointer
is never dereferenced. This is so that enums may use this forbidden value
as a discriminant -- Option<NonNull<T>> has the same size as *mut T.
However the pointer may still dangle if it isn't dereferenced.
Unlike *mut T, NonNull<T> is covariant over T. This is usually the correct
choice for most data structures and safe abstractions, such as Box, Rc, Arc, Vec,
and LinkedList.
In rare cases, if your type exposes a way to mutate the value of T through a NonNull<T>,
and you need to prevent unsoundness from variance (for example, if T could be a reference
with a shorter lifetime), you should add a field to make your type invariant, such as
PhantomData<Cell<T>> or PhantomData<&'a mut T>.
Example of a type that must be invariant:
use Cell;
use PhantomData;
Notice that NonNull<T> has a From instance for &T. However, this does
not change the fact that mutating through a (pointer derived from a) shared
reference is undefined behavior unless the mutation happens inside an
UnsafeCell<T>. The same goes for creating a mutable reference from a shared
reference. When using this From instance without an UnsafeCell<T>,
it is your responsibility to ensure that as_mut is never called, and as_ptr
is never used for mutation.
Layout
NonNull<T> is guaranteed to have the same layout and bit validity as *mut T
with the exception that a null pointer is invalid.
Option<NonNull<T>> is guaranteed to be ABI-compatible with *mut T, including in
FFI.
Thanks to the null pointer optimization,
NonNull<T> and Option<NonNull<T>>
are guaranteed to have the same size and alignment:
use NonNull;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
Fields
pointer: *const T is !null
Implementations
impl<T> NonNull<MaybeUninit<T>>
const fn cast_init(self) -> NonNull<T>Casts from a maybe-uninitialized type to its initialized version.
This is always safe, since UB can only occur if the pointer is read before being initialized.
impl<T> NonNull<T>
const fn cast_uninit(self) -> NonNull<MaybeUninit<T>>Casts from a type to its maybe-uninitialized version.
const fn cast_slice(self, len: usize) -> NonNull<[T]>Creates a non-null raw slice from a thin pointer and a length.
The
lenargument is the number of elements, not the number of bytes.This function is safe, but dereferencing the return value is unsafe. See the documentation of
slice::from_raw_partsfor slice safety requirements.Examples
use NonNull; // create a slice pointer when starting out with a pointer to the first element let mut x = ; let nonnull_pointer = new.unwrap; let slice = nonnull_pointer.cast_slice; assert_eq!;(Note that this example artificially demonstrates a use of this method, but
let slice = NonNull::from(&x[..]);would be a better way to write code like this.)
impl<T> NonNull<[T]>
const fn slice_from_raw_parts(data: NonNull<T>, len: usize) -> SelfCreates a non-null raw slice from a thin pointer and a length.
The
lenargument is the number of elements, not the number of bytes.This function is safe, but dereferencing the return value is unsafe. See the documentation of
slice::from_raw_partsfor slice safety requirements.Examples
use NonNull; // create a slice pointer when starting out with a pointer to the first element let mut x = ; let nonnull_pointer = new.unwrap; let slice = slice_from_raw_parts; assert_eq!;(Note that this example artificially demonstrates a use of this method, but
let slice = NonNull::from(&x[..]);would be a better way to write code like this.)const fn len(self) -> usizeReturns the length of a non-null raw slice.
The returned value is the number of elements, not the number of bytes.
This function is safe, even when the non-null raw slice cannot be dereferenced to a slice because the pointer does not have a valid address.
Examples
use NonNull; let slice: = slice_from_raw_parts; assert_eq!;const fn is_empty(self) -> boolReturns
trueif the non-null raw slice has a length of 0.Examples
use NonNull; let slice: = slice_from_raw_parts; assert!;const fn as_non_null_ptr(self) -> NonNull<T>Returns a non-null pointer to the slice's buffer.
Examples
use NonNull; let slice: = slice_from_raw_parts; assert_eq!;const fn as_mut_ptr(self) -> *mut TReturns a raw pointer to the slice's buffer.
Examples
use NonNull; let slice: = slice_from_raw_parts; assert_eq!;const unsafe fn as_uninit_slice<'a>(self) -> &'a [MaybeUninit<T>]Returns a shared reference to a slice of possibly uninitialized values. In contrast to
as_ref, this does not require that the value has to be initialized.For the mutable counterpart see
as_uninit_slice_mut.Safety
When calling this method, you have to ensure that all of the following is true:
-
The pointer must be valid for reads for
ptr.len() * size_of::<T>()many bytes, and it must be properly aligned. This means in particular:-
The entire memory range of this slice must be contained within a single allocation! Slices can never span across multiple allocations.
-
The pointer must be aligned even for zero-length slices. One reason for this is that enum layout optimizations may rely on references (including slices of any length) being aligned and non-null to distinguish them from other data. You can obtain a pointer that is usable as
datafor zero-length slices using [NonNull::dangling()].
-
-
The total size
ptr.len() * size_of::<T>()of the slice must be no larger thanisize::MAX. See the safety documentation ofpointer::offset. -
You must enforce Rust's aliasing rules, since the returned lifetime
'ais arbitrarily chosen and does not necessarily reflect the actual lifetime of the data. In particular, while this reference exists, the memory the pointer points to must not get mutated (except insideUnsafeCell).
This applies even if the result of this method is unused!
See also
slice::from_raw_parts.-
const unsafe fn as_uninit_slice_mut<'a>(self) -> &'a mut [MaybeUninit<T>]Returns a unique reference to a slice of possibly uninitialized values. In contrast to
as_mut, this does not require that the value has to be initialized.For the shared counterpart see
as_uninit_slice.Safety
When calling this method, you have to ensure that all of the following is true:
-
The pointer must be valid for reads and writes for
ptr.len() * size_of::<T>()many bytes, and it must be properly aligned. This means in particular:-
The entire memory range of this slice must be contained within a single allocation! Slices can never span across multiple allocations.
-
The pointer must be aligned even for zero-length slices. One reason for this is that enum layout optimizations may rely on references (including slices of any length) being aligned and non-null to distinguish them from other data. You can obtain a pointer that is usable as
datafor zero-length slices using [NonNull::dangling()].
-
-
The total size
ptr.len() * size_of::<T>()of the slice must be no larger thanisize::MAX. See the safety documentation ofpointer::offset. -
You must enforce Rust's aliasing rules, since the returned lifetime
'ais arbitrarily chosen and does not necessarily reflect the actual lifetime of the data. In particular, while this reference exists, the memory the pointer points to must not get accessed (read or written) through any other pointer.
This applies even if the result of this method is unused!
See also
slice::from_raw_parts_mut.Examples
use ; use MaybeUninit; use NonNull; let memory: = Global.allocate?; // This is safe as `memory` is valid for reads and writes for `memory.len()` many bytes. // Note that calling `memory.as_mut()` is not allowed here as the content may be uninitialized. # let slice: &mut = unsafe ; # // Prevent leaks for Miri. # unsafe # Ok::-
const unsafe fn get_unchecked_mut<I>(self, index: I) -> NonNull<I::Output> where I: ~const SliceIndex<[T]>,Returns a raw pointer to an element or subslice, without doing bounds checking.
Calling this method with an out-of-bounds index or when
selfis not dereferenceable is undefined behavior even if the resulting pointer is not used.Examples
use NonNull; let x = &mut ; let x = slice_from_raw_parts; unsafe
impl<T: PointeeSized> NonNull<T>
const unsafe fn new_unchecked(ptr: *mut T) -> SelfCreates a new
NonNull.Note that if you have an
&mut, you can use the safefrom_mutinstead.Safety
ptrmust be non-null.Examples
use NonNull; let mut x = 0u32; let ptr = unsafe ;Incorrect usage of this function:
use NonNull; // NEVER DO THAT!!! This is undefined behavior. ⚠️ let ptr = unsafe ;const fn new(ptr: *mut T) -> Option<Self>Creates a new
NonNullifptris non-null.Note that if you have an
&mut, you can usefrom_mutinstead to avoid theOption.Panics during const evaluation
This method will panic during const evaluation if the pointer cannot be determined to be null or not. See
is_nullfor more information.Examples
use NonNull; let mut x = 0u32; let ptr = new.expect; if let Some = newconst fn from_ref(r: &T) -> SelfConverts a reference to a
NonNullpointer.const fn from_mut(r: &mut T) -> SelfConverts a mutable reference to a
NonNullpointer.const fn from_raw_parts(data_pointer: NonNull<impl Thin>, metadata: <T as Pointee>::Metadata) -> NonNull<T>Performs the same functionality as
std::ptr::from_raw_parts, except that aNonNullpointer is returned, as opposed to a raw*constpointer.See the documentation of
std::ptr::from_raw_partsfor more details.const fn to_raw_parts(self) -> (NonNull<()>, <T as Pointee>::Metadata)Decompose a (possibly wide) pointer into its data pointer and metadata components.
The pointer can be later reconstructed with
NonNull::from_raw_parts.fn addr(self) -> NonZero<usize>Gets the "address" portion of the pointer.
For more details, see the equivalent method on a raw pointer,
pointer::addr.This is a [Strict Provenance][crate::ptr#strict-provenance] API.
fn expose_provenance(self) -> NonZero<usize>Exposes the ["provenance"][crate::ptr#provenance] part of the pointer for future use in [
with_exposed_provenance][NonNull::with_exposed_provenance] and returns the "address" portion.For more details, see the equivalent method on a raw pointer,
pointer::expose_provenance.This is an [Exposed Provenance][crate::ptr#exposed-provenance] API.
fn with_addr(self, addr: NonZero<usize>) -> SelfCreates a new pointer with the given address and the [provenance][crate::ptr#provenance] of
self.For more details, see the equivalent method on a raw pointer,
pointer::with_addr.This is a [Strict Provenance][crate::ptr#strict-provenance] API.
fn map_addr(self, f: impl FnOnce(NonZero<usize>) -> NonZero<usize>) -> SelfCreates a new pointer by mapping
self's address to a new one, preserving the [provenance][crate::ptr#provenance] ofself.For more details, see the equivalent method on a raw pointer,
pointer::map_addr.This is a [Strict Provenance][crate::ptr#strict-provenance] API.
const fn as_ptr(self) -> *mut TAcquires the underlying
*mutpointer.Examples
use NonNull; let mut x = 0u32; let ptr = new.expect; let x_value = unsafe ; assert_eq!; unsafe let x_value = unsafe ; assert_eq!;const unsafe fn as_ref<'a>(&self) -> &'a TReturns a shared reference to the value. If the value may be uninitialized,
as_uninit_refmust be used instead.For the mutable counterpart see
as_mut.Safety
When calling this method, you have to ensure that the pointer is convertible to a reference.
Examples
use NonNull; let mut x = 0u32; let ptr = new.expect; let ref_x = unsafe ; println!;const unsafe fn as_mut<'a>(&mut self) -> &'a mut TReturns a unique reference to the value. If the value may be uninitialized,
as_uninit_mutmust be used instead.For the shared counterpart see
as_ref.Safety
When calling this method, you have to ensure that the pointer is convertible to a reference.
Examples
use NonNull; let mut x = 0u32; let mut ptr = new.expect; let x_ref = unsafe ; assert_eq!; *x_ref += 2; assert_eq!;const fn cast<U>(self) -> NonNull<U>Casts to a pointer of another type.
Examples
use NonNull; let mut x = 0u32; let ptr = new.expect; let casted_ptr = ptr.; let raw_ptr: *mut i8 = casted_ptr.as_ptr;fn try_cast_aligned<U>(self) -> Option<NonNull<U>>Try to cast to a pointer of another type by checking alignment.
If the pointer is properly aligned to the target type, it will be cast to the target type. Otherwise,
Noneis returned.Examples
use NonNull; let mut x = 0u64; let aligned = from_mut; let unaligned = unsafe ; assert!; assert!;const unsafe fn offset(self, count: isize) -> Self where T: Sized,Adds a signed offset to a pointer.
countis in units of T; e.g., acountof 3 represents a pointer offset of3 * size_of::<T>()bytes.Safety
If any of the following conditions are violated, the result is Undefined Behavior:
-
The offset in bytes,
count * size_of::<T>(), computed on mathematical integers (without "wrapping around"), must fit in anisize. -
Let
resultbeself.addr() + count * size_of::<T>(), computed on mathematical integers. This must fit in ausize. -
If the computed offset is non-zero, then
selfmust be [derived from][crate::ptr#provenance] a pointer to some allocation, and the entire memory range betweenselfandresult(i.e.,min(self.addr(), result)..max(self.addr(), result)) must be in bounds of that allocation.
Allocations can never be larger than
isize::MAXbytes and they can only contain addresses representable byusize, so technically the last condition implies the first two. This implies, for instance, thatvec.as_ptr().offset(vec.len() as isize)(forvec: Vec<T>) is always safe.Examples
use NonNull; let mut s = ; let ptr: = new.unwrap; unsafe-
const unsafe fn byte_offset(self, count: isize) -> SelfCalculates the offset from a pointer in bytes.
countis in units of bytes.This is purely a convenience for casting to a
u8pointer and using [offset][pointer::offset] on it. See that method for documentation and safety requirements.For non-
Sizedpointees this operation changes only the data pointer, leaving the metadata untouched.const unsafe fn add(self, count: usize) -> Self where T: Sized,Adds an unsigned offset to a pointer.
This can only move the pointer forward (or not move it). If you need to move forward or backward depending on the value, then you might want
offsetinstead which takes a signed offset.countis in units of T; e.g., acountof 3 represents a pointer offset of3 * size_of::<T>()bytes.Safety
If any of the following conditions are violated, the result is Undefined Behavior:
-
The offset in bytes,
count * size_of::<T>(), computed on mathematical integers (without "wrapping around"), must fit in anisize. -
Let
resultbeself.addr() + count * size_of::<T>(), computed on mathematical integers. This must fit in ausize. -
If the computed offset is non-zero, then
selfmust be [derived from][crate::ptr#provenance] a pointer to some allocation, and the entire memory range betweenselfandresult(i.e.,self.addr()..result) must be in bounds of that allocation.
Allocations can never be larger than
isize::MAXbytes and they can only contain addresses representable byusize, so technically the last condition implies the first two. This implies, for instance, thatvec.as_ptr().add(vec.len())(forvec: Vec<T>) is always safe.Examples
use NonNull; let s: &str = "123"; let ptr: = new.unwrap; unsafe-
const unsafe fn byte_add(self, count: usize) -> SelfCalculates the offset from a pointer in bytes (convenience for
.byte_offset(count as isize)).countis in units of bytes.This is purely a convenience for casting to a
u8pointer and using [add][NonNull::add] on it. See that method for documentation and safety requirements.For non-
Sizedpointees this operation changes only the data pointer, leaving the metadata untouched.const unsafe fn sub(self, count: usize) -> Self where T: Sized,Subtracts an unsigned offset from a pointer.
This can only move the pointer backward (or not move it). If you need to move forward or backward depending on the value, then you might want
offsetinstead which takes a signed offset.countis in units of T; e.g., acountof 3 represents a pointer offset of3 * size_of::<T>()bytes.Safety
If any of the following conditions are violated, the result is Undefined Behavior:
-
The offset in bytes,
count * size_of::<T>(), computed on mathematical integers (without "wrapping around"), must fit in anisize. -
Let
resultbeself.addr() - count * size_of::<T>(), computed on mathematical integers. This must fit in ausize. -
If the computed offset is non-zero, then
selfmust be [derived from][crate::ptr#provenance] a pointer to some allocation, and the entire memory range betweenselfandresult(i.e.,result..self.addr()) must be in bounds of that allocation.
Allocations can never be larger than
isize::MAXbytes and they can only contain addresses representable byusize, so technically the last condition implies the first two.Examples
use NonNull; let s: &str = "123"; unsafe-
const unsafe fn byte_sub(self, count: usize) -> SelfCalculates the offset from a pointer in bytes (convenience for
.byte_offset((count as isize).wrapping_neg())).countis in units of bytes.This is purely a convenience for casting to a
u8pointer and using [sub][NonNull::sub] on it. See that method for documentation and safety requirements.For non-
Sizedpointees this operation changes only the data pointer, leaving the metadata untouched.const unsafe fn offset_from(self, origin: NonNull<T>) -> isize where T: Sized,Calculates the distance between two pointers within the same allocation. The returned value is in units of T: the distance in bytes divided by
size_of::<T>().This is equivalent to
(self as isize - origin as isize) / (size_of::<T>() as isize), except that it has a lot more opportunities for UB, in exchange for the compiler better understanding what you are doing.The primary motivation of this method is for computing the
lenof an array/slice ofTthat you are currently representing as a "start" and "end" pointer (and "end" is "one past the end" of the array). In that case,end.offset_from(start)gets you the length of the array.All of the following safety requirements are trivially satisfied for this usecase.
Safety
If any of the following conditions are violated, the result is Undefined Behavior:
-
selfandoriginmust either- point to the same address, or
- both be derived from a pointer to the same allocation, and the memory range between the two pointers must be in bounds of that object. (See below for an example.)
-
The distance between the pointers, in bytes, must be an exact multiple of the size of
T.
As a consequence, the absolute distance between the pointers, in bytes, computed on mathematical integers (without "wrapping around"), cannot overflow an
isize. This is implied by the in-bounds requirement, and the fact that no allocation can be larger thanisize::MAXbytes.The requirement for pointers to be derived from the same allocation is primarily needed for
const-compatibility: the distance between pointers into different allocated objects is not known at compile-time. However, the requirement also exists at runtime and may be exploited by optimizations. If you wish to compute the difference between pointers that are not guaranteed to be from the same allocation, use(self.addr() as isize - origin.addr() as isize) / size_of::<T>().Panics
This function panics if
Tis a Zero-Sized Type ("ZST").Examples
Basic usage:
use NonNull; let a = ; let ptr1: = from; let ptr2: = from; unsafeIncorrect usage:
use NonNull; let ptr1 = new.unwrap; let ptr2 = new.unwrap; let diff = .wrapping_sub; // Make ptr2_other an "alias" of ptr2.add(1), but derived from ptr1. let diff_plus_1 = diff.wrapping_add; let ptr2_other = new.unwrap; assert_eq!; // Since ptr2_other and ptr2 are derived from pointers to different objects, // computing their offset is undefined behavior, even though // they point to addresses that are in-bounds of the same object! let one = unsafe ; // Undefined Behavior! ⚠️-
const unsafe fn byte_offset_from<U: ?Sized>(self, origin: NonNull<U>) -> isizeCalculates the distance between two pointers within the same allocation. The returned value is in units of bytes.
This is purely a convenience for casting to a
u8pointer and using [offset_from][NonNull::offset_from] on it. See that method for documentation and safety requirements.For non-
Sizedpointees this operation considers only the data pointers, ignoring the metadata.const unsafe fn offset_from_unsigned(self, subtracted: NonNull<T>) -> usize where T: Sized,Calculates the distance between two pointers within the same allocation, where it's known that
selfis equal to or greater thanorigin. The returned value is in units of T: the distance in bytes is divided bysize_of::<T>().This computes the same value that
offset_fromwould compute, but with the added precondition that the offset is guaranteed to be non-negative. This method is equivalent tousize::try_from(self.offset_from(origin)).unwrap_unchecked(), but it provides slightly more information to the optimizer, which can sometimes allow it to optimize slightly better with some backends.This method can be though of as recovering the
countthat was passed toadd(or, with the parameters in the other order, tosub). The following are all equivalent, assuming that their safety preconditions are met:# unsafeSafety
-
The distance between the pointers must be non-negative (
self >= origin) -
All the safety conditions of
offset_fromapply to this method as well; see it for the full details.
Importantly, despite the return type of this method being able to represent a larger offset, it's still not permitted to pass pointers which differ by more than
isize::MAXbytes. As such, the result of this method will always be less than or equal toisize::MAX as usize.Panics
This function panics if
Tis a Zero-Sized Type ("ZST").Examples
use NonNull; let a = ; let ptr1: = from; let ptr2: = from; unsafe // This would be incorrect, as the pointers are not correctly ordered: // ptr1.offset_from_unsigned(ptr2)-
const unsafe fn byte_offset_from_unsigned<U: ?Sized>(self, origin: NonNull<U>) -> usizeCalculates the distance between two pointers within the same allocation, where it's known that
selfis equal to or greater thanorigin. The returned value is in units of bytes.This is purely a convenience for casting to a
u8pointer and using [offset_from_unsigned][NonNull::offset_from_unsigned] on it. See that method for documentation and safety requirements.For non-
Sizedpointees this operation considers only the data pointers, ignoring the metadata.const unsafe fn read(self) -> T where T: Sized,Reads the value from
selfwithout moving it. This leaves the memory inselfunchanged.See
ptr::readfor safety concerns and examples.unsafe fn read_volatile(self) -> T where T: Sized,Performs a volatile read of the value from
selfwithout moving it. This leaves the memory inselfunchanged.Volatile operations are intended to act on I/O memory, and are guaranteed to not be elided or reordered by the compiler across other volatile operations.
See
ptr::read_volatilefor safety concerns and examples.const unsafe fn read_unaligned(self) -> T where T: Sized,Reads the value from
selfwithout moving it. This leaves the memory inselfunchanged.Unlike
read, the pointer may be unaligned.See
ptr::read_unalignedfor safety concerns and examples.const unsafe fn copy_to(self, dest: NonNull<T>, count: usize) where T: Sized,Copies
count * size_of::<T>()bytes fromselftodest. The source and destination may overlap.NOTE: this has the same argument order as
ptr::copy.See
ptr::copyfor safety concerns and examples.const unsafe fn copy_to_nonoverlapping(self, dest: NonNull<T>, count: usize) where T: Sized,Copies
count * size_of::<T>()bytes fromselftodest. The source and destination may not overlap.NOTE: this has the same argument order as
ptr::copy_nonoverlapping.See
ptr::copy_nonoverlappingfor safety concerns and examples.const unsafe fn copy_from(self, src: NonNull<T>, count: usize) where T: Sized,Copies
count * size_of::<T>()bytes fromsrctoself. The source and destination may overlap.NOTE: this has the opposite argument order of
ptr::copy.See
ptr::copyfor safety concerns and examples.const unsafe fn copy_from_nonoverlapping(self, src: NonNull<T>, count: usize) where T: Sized,Copies
count * size_of::<T>()bytes fromsrctoself. The source and destination may not overlap.NOTE: this has the opposite argument order of
ptr::copy_nonoverlapping.See
ptr::copy_nonoverlappingfor safety concerns and examples.const unsafe fn drop_in_place(self) where T: ,Executes the destructor (if any) of the pointed-to value.
See
ptr::drop_in_placefor safety concerns and examples.const unsafe fn write(self, val: T) where T: Sized,Overwrites a memory location with the given value without reading or dropping the old value.
See
ptr::writefor safety concerns and examples.const unsafe fn write_bytes(self, val: u8, count: usize) where T: Sized,Invokes memset on the specified pointer, setting
count * size_of::<T>()bytes of memory starting atselftoval.See
ptr::write_bytesfor safety concerns and examples.unsafe fn write_volatile(self, val: T) where T: Sized,Performs a volatile write of a memory location with the given value without reading or dropping the old value.
Volatile operations are intended to act on I/O memory, and are guaranteed to not be elided or reordered by the compiler across other volatile operations.
See
ptr::write_volatilefor safety concerns and examples.const unsafe fn write_unaligned(self, val: T) where T: Sized,Overwrites a memory location with the given value without reading or dropping the old value.
Unlike
write, the pointer may be unaligned.See
ptr::write_unalignedfor safety concerns and examples.const unsafe fn replace(self, src: T) -> T where T: Sized,Replaces the value at
selfwithsrc, returning the old value, without dropping either.See
ptr::replacefor safety concerns and examples.const unsafe fn swap(self, with: NonNull<T>) where T: Sized,Swaps the values at two mutable locations of the same type, without deinitializing either. They may overlap, unlike
mem::swapwhich is otherwise equivalent.See
ptr::swapfor safety concerns and examples.fn align_offset(self, align: usize) -> usize where T: Sized,Computes the offset that needs to be applied to the pointer in order to make it aligned to
align.If it is not possible to align the pointer, the implementation returns
usize::MAX.The offset is expressed in number of
Telements, and not bytes.There are no guarantees whatsoever that offsetting the pointer will not overflow or go beyond the allocation that the pointer points into. It is up to the caller to ensure that the returned offset is correct in all terms other than alignment.
When this is called during compile-time evaluation (which is unstable), the implementation may return
usize::MAXin cases where that can never happen at runtime. This is because the actual alignment of pointers is not known yet during compile-time, so an offset with guaranteed alignment can sometimes not be computed. For example, a buffer declared as[u8; N]might be allocated at an odd or an even address, but at compile-time this is not yet known, so the execution has to be correct for either choice. It is therefore impossible to find an offset that is guaranteed to be 2-aligned. (This behavior is subject to change, as usual for unstable APIs.)Panics
The function panics if
alignis not a power-of-two.Examples
Accessing adjacent
u8asu16use NonNull; # unsafefn is_aligned(self) -> bool where T: Sized,Returns whether the pointer is properly aligned for
T.Examples
use NonNull; // On some platforms, the alignment of i32 is less than 4. ; let data = AlignedI32; let ptr = from; assert!; assert!;fn is_aligned_to(self, align: usize) -> boolReturns whether the pointer is aligned to
align.For non-
Sizedpointees this operation considers only the data pointer, ignoring the metadata.Panics
The function panics if
alignis not a power-of-two (this includes 0).Examples
// On some platforms, the alignment of i32 is less than 4. ; let data = AlignedI32; let ptr = &data as *const AlignedI32; assert!; assert!; assert!; assert!; assert!; assert_ne!;
impl<T: Sized> NonNull<T>
const fn without_provenance(addr: NonZero<usize>) -> SelfCreates a pointer with the given address and no [provenance][crate::ptr#provenance].
For more details, see the equivalent method on a raw pointer,
ptr::without_provenance_mut.This is a [Strict Provenance][crate::ptr#strict-provenance] API.
const fn dangling() -> SelfCreates a new
NonNullthat is dangling, but well-aligned.This is useful for initializing types which lazily allocate, like
Vec::newdoes.Note that the address of the returned pointer may potentially be that of a valid pointer, which means this must not be used as a "not yet initialized" sentinel value. Types that lazily allocate must track initialization by some other means.
Examples
use NonNull; let ptr = dangling; // Important: don't try to access the value of `ptr` without // initializing it first! The pointer is not null but isn't valid either!const fn with_exposed_provenance(addr: NonZero<usize>) -> SelfConverts an address back to a mutable pointer, picking up some previously 'exposed' [provenance][crate::ptr#provenance].
For more details, see the equivalent method on a raw pointer,
ptr::with_exposed_provenance_mut.This is an [Exposed Provenance][crate::ptr#exposed-provenance] API.
const unsafe fn as_uninit_ref<'a>(self) -> &'a MaybeUninit<T>Returns a shared references to the value. In contrast to
as_ref, this does not require that the value has to be initialized.For the mutable counterpart see
as_uninit_mut.Safety
When calling this method, you have to ensure that the pointer is convertible to a reference. Note that because the created reference is to
MaybeUninit<T>, the source pointer can point to uninitialized memory.const unsafe fn as_uninit_mut<'a>(self) -> &'a mut MaybeUninit<T>Returns a unique references to the value. In contrast to
as_mut, this does not require that the value has to be initialized.For the shared counterpart see
as_uninit_ref.Safety
When calling this method, you have to ensure that the pointer is convertible to a reference. Note that because the created reference is to
MaybeUninit<T>, the source pointer can point to uninitialized memory.const fn cast_array<const N: usize>(self) -> NonNull<[T; N]>Casts from a pointer-to-
Tto a pointer-to-[T; N].
Trait Implementations
impl<T, U: PointeeSized> CoerceUnsized<NonNull<U>> for NonNull<T>
where
T: Unsize<U> + PointeeSized,
impl<T, U: PointeeSized> DispatchFromDyn<NonNull<U>> for NonNull<T>
where
T: Unsize<U> + PointeeSized,
impl<T: PointeeSized> !Send for NonNull<T>
impl<T: PointeeSized> !Sync for NonNull<T>
impl<T: PointeeSized> Clone for NonNull<T>
fn clone(&self) -> Self
impl<T: PointeeSized> Copy for NonNull<T>
impl<T: PointeeSized> Debug for NonNull<T>
fn fmt(&self, f: &mut Formatter<'_>) -> Result
impl<T: PointeeSized> Eq for NonNull<T>
impl<T: PointeeSized> From<&T> for NonNull<T>
fn from(r: &T) -> SelfConverts a
&Tto aNonNull<T>.This conversion is safe and infallible since references cannot be null.
impl<T: PointeeSized> From<&mut T> for NonNull<T>
fn from(r: &mut T) -> SelfConverts a
&mut Tto aNonNull<T>.This conversion is safe and infallible since references cannot be null.
impl<T: PointeeSized> From<Unique<T>> for NonNull<T>
fn from(unique: Unique<T>) -> Self
impl<T: PointeeSized> Hash for NonNull<T>
fn hash<H: Hasher>(&self, state: &mut H)
impl<T: PointeeSized> Ord for NonNull<T>
fn cmp(&self, other: &Self) -> Ordering
impl<T: PointeeSized> PartialEq for NonNull<T>
fn eq(&self, other: &Self) -> bool
impl<T: PointeeSized> PartialOrd for NonNull<T>
fn partial_cmp(&self, other: &Self) -> Option<Ordering>
impl<T: PointeeSized> Pointer for NonNull<T>
fn fmt(&self, f: &mut Formatter<'_>) -> Result
impl<T: PointeeSized> TrivialClone for NonNull<T>
impl<T: RefUnwindSafe + PointeeSized> UnwindSafe for NonNull<T>
Auto Trait Implementations
impl<T> Freeze for NonNull<T>
where
*const T is !null: Freeze,
T: ?Sized,
impl<T> RefUnwindSafe for NonNull<T>
where
*const T is !null: RefUnwindSafe,
T: ?Sized,
impl<T> Unpin for NonNull<T>
where
*const T is !null: Unpin,
T: ?Sized,
impl<T> UnsafeUnpin for NonNull<T>
where
*const T is !null: UnsafeUnpin,
T: ?Sized,
Blanket Implementations
impl<T> Any for NonNull<T>
where
T: 'static + ?Sized,
fn type_id(&self) -> TypeId
impl<T> Borrow<T> for NonNull<T>
where
T: ?Sized,
fn borrow(&self) -> &T
impl<T> BorrowMut<T> for NonNull<T>
where
T: ?Sized,
fn borrow_mut(&mut self) -> &mut T
impl<T> CloneToUninit for NonNull<T>
where
T: Clone,
unsafe fn clone_to_uninit(&self, dest: *mut u8)
impl<T> From<T> for NonNull<T>
fn from(t: T) -> TReturns the argument unchanged.
impl<T> Printable for NonNull<T>
where
T: Copy + Debug,
impl<T> SizeHint for NonNull<T>
where
T: ?Sized,
fn lower_bound(&self) -> usizefn upper_bound(&self) -> Option<usize>
impl<T> SizedTypeProperties for NonNull<T>
impl<T, U> Into<U> for NonNull<T>
where
U: From<T>,
fn into(self) -> UCalls
U::from(self).That is, this conversion is whatever the implementation of
[From]<T> for Uchooses to do.
impl<T, U> TryFrom<U> for NonNull<T>
where
U: Into<T>,
type Error = Infallible;fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
impl<T, U> TryInto<U> for NonNull<T>
where
U: TryFrom<T>,
type Error = <U as TryFrom<T>>::Error;fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>