Struct NonNull
struct NonNull<T: PointeeSized> { ... }
*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.
Representation
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!;
Implementations
impl<T> NonNull<MaybeUninit<T>>
const fn cast_init(self: 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: Self) -> NonNull<MaybeUninit<T>>Casts from a type to its maybe-uninitialized version.
const fn cast_slice(self: 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: 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: 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: 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: Self) -> *mut TReturns a raw pointer to the slice's buffer.
Examples
use NonNull; let slice: = slice_from_raw_parts; assert_eq!;unsafe const fn as_uninit_slice<'a>(self: 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.-
unsafe const fn as_uninit_slice_mut<'a>(self: 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::-
unsafe const fn get_unchecked_mut<I>(self: Self, index: I) -> NonNull<<I as >::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>
unsafe const fn new_unchecked(ptr: *mut T) -> SelfCreates a new
NonNull.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.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<impl super::Thin: super::Thin>(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: 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: 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: 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: 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<impl FnOnce(NonZero<usize>) -> NonZero<usize>: FnOnce(NonZero<usize>) -> NonZero<usize>>(self: 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: 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!;unsafe const fn as_ref<'a>(self: &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!;unsafe const fn as_mut<'a>(self: &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: 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: 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!;unsafe const fn offset(self: Self, count: isize) -> Self where T: SizedAdds an 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 computed offset,
count * size_of::<T>()bytes, must not overflowisize. -
If the computed offset is non-zero, then
selfmust be derived from a pointer to some allocation, and the entire memory range betweenselfand the result must be in bounds of that allocation. In particular, this range must not "wrap around" the edge of the address space.
Allocations can never be larger than
isize::MAXbytes, so if the computed offset stays in bounds of the allocation, it is guaranteed to satisfy the first requirement. This implies, for instance, thatvec.as_ptr().add(vec.len())(forvec: Vec<T>) is always safe.Examples
use NonNull; let mut s = ; let ptr: = new.unwrap; unsafe-
unsafe const fn byte_offset(self: 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.unsafe const fn add(self: Self, count: usize) -> Self where T: SizedAdds an offset to a pointer (convenience for
.offset(count as isize)).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 computed offset,
count * size_of::<T>()bytes, must not overflowisize. -
If the computed offset is non-zero, then
selfmust be derived from a pointer to some allocation, and the entire memory range betweenselfand the result must be in bounds of that allocation. In particular, this range must not "wrap around" the edge of the address space.
Allocations can never be larger than
isize::MAXbytes, so if the computed offset stays in bounds of the allocation, it is guaranteed to satisfy the first requirement. 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-
unsafe const fn byte_add(self: 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.unsafe const fn sub(self: Self, count: usize) -> Self where T: SizedSubtracts an offset from a pointer (convenience for
.offset((count as isize).wrapping_neg())).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 computed offset,
count * size_of::<T>()bytes, must not overflowisize. -
If the computed offset is non-zero, then
selfmust be derived from a pointer to some allocation, and the entire memory range betweenselfand the result must be in bounds of that allocation. In particular, this range must not "wrap around" the edge of the address space.
Allocations can never be larger than
isize::MAXbytes, so if the computed offset stays in bounds of the allocation, it is guaranteed to satisfy the first requirement. This implies, for instance, thatvec.as_ptr().add(vec.len())(forvec: Vec<T>) is always safe.Examples
use NonNull; let s: &str = "123"; unsafe-
unsafe const fn byte_sub(self: 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.unsafe const fn offset_from(self: Self, origin: NonNull<T>) -> isize where T: SizedCalculates 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 as isize - origin 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! ⚠️-
unsafe const fn byte_offset_from<U: ?Sized>(self: 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.unsafe const fn offset_from_unsigned(self: Self, subtracted: NonNull<T>) -> usize where T: SizedCalculates 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)-
unsafe const fn byte_offset_from_unsigned<U: ?Sized>(self: 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.unsafe const fn read(self: Self) -> T where T: SizedReads the value from
selfwithout moving it. This leaves the memory inselfunchanged.See
ptr::readfor safety concerns and examples.unsafe fn read_volatile(self: Self) -> T where T: SizedPerforms 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.unsafe const fn read_unaligned(self: Self) -> T where T: SizedReads 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.unsafe const fn copy_to(self: Self, dest: NonNull<T>, count: usize) where T: SizedCopies
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.unsafe const fn copy_to_nonoverlapping(self: Self, dest: NonNull<T>, count: usize) where T: SizedCopies
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.unsafe const fn copy_from(self: Self, src: NonNull<T>, count: usize) where T: SizedCopies
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.unsafe const fn copy_from_nonoverlapping(self: Self, src: NonNull<T>, count: usize) where T: SizedCopies
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.unsafe const fn drop_in_place(self: Self) where T:Executes the destructor (if any) of the pointed-to value.
See
ptr::drop_in_placefor safety concerns and examples.unsafe const fn write(self: Self, val: T) where T: SizedOverwrites a memory location with the given value without reading or dropping the old value.
See
ptr::writefor safety concerns and examples.unsafe const fn write_bytes(self: Self, val: u8, count: usize) where T: SizedInvokes 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: Self, val: T) where T: SizedPerforms 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.unsafe const fn write_unaligned(self: Self, val: T) where T: SizedOverwrites 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.unsafe const fn replace(self: Self, src: T) -> T where T: SizedReplaces the value at
selfwithsrc, returning the old value, without dropping either.See
ptr::replacefor safety concerns and examples.unsafe const fn swap(self: Self, with: NonNull<T>) where T: SizedSwaps 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: Self, align: usize) -> usize where T: SizedComputes 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: Self) -> bool where T: SizedReturns 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: 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!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.
unsafe const fn as_uninit_ref<'a>(self: 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.unsafe const fn as_uninit_mut<'a>(self: 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<N: usize>(self: Self) -> NonNull<[T; N]>Casts from a pointer-to-
Tto a pointer-to-[T; N].
impl<T> Any for NonNull<T>
fn type_id(self: &Self) -> TypeId
impl<T> Borrow for NonNull<T>
fn borrow(self: &Self) -> &T
impl<T> BorrowMut for NonNull<T>
fn borrow_mut(self: &mut Self) -> &mut T
impl<T> CloneToUninit for NonNull<T>
unsafe fn clone_to_uninit(self: &Self, dest: *mut u8)
impl<T> Freeze for NonNull<T>
impl<T> From for NonNull<T>
fn from(t: T) -> TReturns the argument unchanged.
impl<T> RefUnwindSafe for NonNull<T>
impl<T> Unpin for NonNull<T>
impl<T> UnsafeUnpin for NonNull<T>
impl<T, U> Into for NonNull<T>
fn into(self: Self) -> UCalls
U::from(self).That is, this conversion is whatever the implementation of
[From]<T> for Uchooses to do.
impl<T, U> TryFrom for NonNull<T>
fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
impl<T, U> TryInto for NonNull<T>
fn try_into(self: Self) -> Result<U, <U as TryFrom<T>>::Error>
impl<T, U: PointeeSized> CoerceUnsized for NonNull<T>
impl<T, U: PointeeSized> DispatchFromDyn for NonNull<T>
impl<T: PointeeSized> Clone for NonNull<T>
fn clone(self: &Self) -> Self
impl<T: PointeeSized> Copy for NonNull<T>
impl<T: PointeeSized> Debug for NonNull<T>
fn fmt(self: &Self, f: &mut Formatter<'_>) -> Result
impl<T: PointeeSized> Eq for NonNull<T>
impl<T: PointeeSized> From 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 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> Hash for NonNull<T>
fn hash<H: hash::Hasher>(self: &Self, state: &mut H)
impl<T: PointeeSized> Ord for NonNull<T>
fn cmp(self: &Self, other: &Self) -> Ordering
impl<T: PointeeSized> PartialEq for NonNull<T>
fn eq(self: &Self, other: &Self) -> bool
impl<T: PointeeSized> PartialOrd for NonNull<T>
fn partial_cmp(self: &Self, other: &Self) -> Option<Ordering>
impl<T: PointeeSized> PinCoerceUnsized for NonNull<T>
impl<T: PointeeSized> Pointer for NonNull<T>
fn fmt(self: &Self, f: &mut Formatter<'_>) -> Result