pub struct NonNull<T:PointeeSized> {/* private fields */ }Expand description
*mut T but non-zero andcovariant.
This is often the correct thing to use when building data structures usingraw pointers, but is ultimately more dangerous to use because of its additionalproperties. If you’re not sure if you should useNonNull<T>, just use*mut T!
Unlike*mut T, the pointer must always be non-null, even if the pointeris never dereferenced. This is so that enums may use this forbidden valueas 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 overT. This is usually the correctchoice for most data structures and safe abstractions, such asBox,Rc,Arc,Vec,andLinkedList.
In rare cases, if your type exposes a way to mutate the value ofT through aNonNull<T>,and you need to prevent unsoundness from variance (for example, ifT could be a referencewith a shorter lifetime), you should add a field to make your type invariant, such asPhantomData<Cell<T>> orPhantomData<&'a mut T>.
Example of a type that must be invariant:
usestd::cell::Cell;usestd::marker::PhantomData;structInvariant<T> { ptr: std::ptr::NonNull<T>, _invariant: PhantomData<Cell<T>>,}Notice thatNonNull<T> has aFrom instance for&T. However, this doesnot change the fact that mutating through a (pointer derived from a) sharedreference is undefined behavior unless the mutation happens inside anUnsafeCell<T>. The same goes for creating a mutable reference from a sharedreference. When using thisFrom instance without anUnsafeCell<T>,it is your responsibility to ensure thatas_mut is never called, andas_ptris never used for mutation.
§Representation
Thanks to thenull pointer optimization,NonNull<T> andOption<NonNull<T>>are guaranteed to have the same size and alignment:
usestd::ptr::NonNull;assert_eq!(size_of::<NonNull<i16>>(), size_of::<Option<NonNull<i16>>>());assert_eq!(align_of::<NonNull<i16>>(), align_of::<Option<NonNull<i16>>>());assert_eq!(size_of::<NonNull<str>>(), size_of::<Option<NonNull<str>>>());assert_eq!(align_of::<NonNull<str>>(), align_of::<Option<NonNull<str>>>());Implementations§
Source§impl<T:Sized>NonNull<T>
impl<T:Sized>NonNull<T>
1.89.0 (const: 1.89.0) ·Sourcepub const fnwithout_provenance(addr:NonZero<usize>) -> Self
pub const fnwithout_provenance(addr:NonZero<usize>) -> Self
Creates a pointer with the given address and noprovenance.
For more details, see the equivalent method on a raw pointer,ptr::without_provenance_mut.
This is aStrict Provenance API.
1.25.0 (const: 1.36.0) ·Sourcepub const fndangling() -> Self
pub const fndangling() -> Self
Creates a newNonNull that is dangling, but well-aligned.
This is useful for initializing types which lazily allocate, likeVec::new does.
Note that the address of the returned pointer may potentiallybe that of a valid pointer, which means this must not be usedas a “not yet initialized” sentinel value.Types that lazily allocate must track initialization by some other means.
§Examples
1.89.0 ·Sourcepub fnwith_exposed_provenance(addr:NonZero<usize>) -> Self
pub fnwith_exposed_provenance(addr:NonZero<usize>) -> Self
Converts an address back to a mutable pointer, picking up some previously ‘exposed’provenance.
For more details, see the equivalent method on a raw pointer,ptr::with_exposed_provenance_mut.
This is anExposed Provenance API.
Sourcepub const unsafe fnas_uninit_ref<'a>(self) -> &'aMaybeUninit<T>
🔬This is a nightly-only experimental API. (ptr_as_uninit #75402)
pub const unsafe fnas_uninit_ref<'a>(self) -> &'aMaybeUninit<T>
ptr_as_uninit #75402)Returns a shared references to the value. In contrast toas_ref, this does not requirethat the value has to be initialized.
For the mutable counterpart seeas_uninit_mut.
§Safety
When calling this method, you have to ensure thatthe pointer isconvertible to a reference.Note that because the created reference is toMaybeUninit<T>, thesource pointer can point to uninitialized memory.
Sourcepub const unsafe fnas_uninit_mut<'a>(self) -> &'a mutMaybeUninit<T>
🔬This is a nightly-only experimental API. (ptr_as_uninit #75402)
pub const unsafe fnas_uninit_mut<'a>(self) -> &'a mutMaybeUninit<T>
ptr_as_uninit #75402)Returns a unique references to the value. In contrast toas_mut, this does not requirethat the value has to be initialized.
For the shared counterpart seeas_uninit_ref.
§Safety
When calling this method, you have to ensure thatthe pointer isconvertible to a reference.Note that because the created reference is toMaybeUninit<T>, thesource pointer can point to uninitialized memory.
Source§impl<T:PointeeSized>NonNull<T>
impl<T:PointeeSized>NonNull<T>
1.25.0 (const: 1.25.0) ·Sourcepub const unsafe fnnew_unchecked(ptr:*mut T) -> Self
pub const unsafe fnnew_unchecked(ptr:*mut T) -> Self
1.25.0 (const: 1.85.0) ·Sourcepub const fnnew(ptr:*mut T) ->Option<Self>
pub const fnnew(ptr:*mut T) ->Option<Self>
1.89.0 (const: 1.89.0) ·Sourcepub const fnfrom_ref(r:&T) -> Self
pub const fnfrom_ref(r:&T) -> Self
Converts a reference to aNonNull pointer.
1.89.0 (const: 1.89.0) ·Sourcepub const fnfrom_mut(r:&mut T) -> Self
pub const fnfrom_mut(r:&mut T) -> Self
Converts a mutable reference to aNonNull pointer.
Sourcepub const fnfrom_raw_parts( data_pointer:NonNull<implThin>, metadata: <T asPointee>::Metadata,) ->NonNull<T>
🔬This is a nightly-only experimental API. (ptr_metadata #81513)
pub const fnfrom_raw_parts( data_pointer:NonNull<implThin>, metadata: <T asPointee>::Metadata,) ->NonNull<T>
ptr_metadata #81513)Performs the same functionality asstd::ptr::from_raw_parts, except that aNonNull pointer is returned, as opposed to a raw*const pointer.
See the documentation ofstd::ptr::from_raw_parts for more details.
Sourcepub const fnto_raw_parts(self) -> (NonNull<()>, <T asPointee>::Metadata)
🔬This is a nightly-only experimental API. (ptr_metadata #81513)
pub const fnto_raw_parts(self) -> (NonNull<()>, <T asPointee>::Metadata)
ptr_metadata #81513)Decompose a (possibly wide) pointer into its data pointer and metadata components.
The pointer can be later reconstructed withNonNull::from_raw_parts.
1.84.0 ·Sourcepub fnaddr(self) ->NonZero<usize>
pub fnaddr(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 aStrict Provenance API.
1.89.0 ·Sourcepub fnexpose_provenance(self) ->NonZero<usize>
pub fnexpose_provenance(self) ->NonZero<usize>
Exposes the“provenance” part of the pointer for future use inwith_exposed_provenance and returns the “address” portion.
For more details, see the equivalent method on a raw pointer,pointer::expose_provenance.
This is anExposed Provenance API.
1.84.0 ·Sourcepub fnwith_addr(self, addr:NonZero<usize>) -> Self
pub fnwith_addr(self, addr:NonZero<usize>) -> Self
Creates a new pointer with the given address and theprovenance ofself.
For more details, see the equivalent method on a raw pointer,pointer::with_addr.
This is aStrict Provenance API.
1.84.0 ·Sourcepub fnmap_addr(self, f: implFnOnce(NonZero<usize>) ->NonZero<usize>) -> Self
pub fnmap_addr(self, f: implFnOnce(NonZero<usize>) ->NonZero<usize>) -> Self
Creates a new pointer by mappingself’s address to a new one, preserving theprovenance ofself.
For more details, see the equivalent method on a raw pointer,pointer::map_addr.
This is aStrict Provenance API.
1.25.0 (const: 1.32.0) ·Sourcepub const fnas_ptr(self) ->*mut T
pub const fnas_ptr(self) ->*mut T
Acquires the underlying*mut pointer.
§Examples
1.25.0 (const: 1.73.0) ·Sourcepub const unsafe fnas_ref<'a>(&self) ->&'a T
pub const unsafe fnas_ref<'a>(&self) ->&'a T
Returns a shared reference to the value. If the value may be uninitialized,as_uninit_refmust be used instead.
For the mutable counterpart seeas_mut.
§Safety
When calling this method, you have to ensure thatthe pointer isconvertible to a reference.
§Examples
1.25.0 (const: 1.83.0) ·Sourcepub const unsafe fnas_mut<'a>(&mut self) ->&'a mut T
pub const unsafe fnas_mut<'a>(&mut self) ->&'a mut T
Returns a unique reference to the value. If the value may be uninitialized,as_uninit_mutmust be used instead.
For the shared counterpart seeas_ref.
§Safety
When calling this method, you have to ensure thatthe pointer isconvertible to a reference.
§Examples
1.27.0 (const: 1.36.0) ·Sourcepub const fncast<U>(self) ->NonNull<U>
pub const fncast<U>(self) ->NonNull<U>
Casts to a pointer of another type.
§Examples
Sourcepub fntry_cast_aligned<U>(self) ->Option<NonNull<U>>
🔬This is a nightly-only experimental API. (pointer_try_cast_aligned #141221)
pub fntry_cast_aligned<U>(self) ->Option<NonNull<U>>
pointer_try_cast_aligned #141221)Try to cast to a pointer of another type by checking alignment.
If the pointer is properly aligned to the target type, it will becast to the target type. Otherwise,None is returned.
§Examples
1.80.0 (const: 1.80.0) ·Sourcepub const unsafe fnoffset(self, count:isize) -> Selfwhere T:Sized,
pub const unsafe fnoffset(self, count:isize) -> Selfwhere T:Sized,
Adds an offset to a pointer.
count is in units of T; e.g., acount of 3 represents a pointeroffset 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 someallocation, and the entire memory range betweenselfand the result must be inbounds of that allocation. In particular, this range must not “wrap around” the edgeof the address space.
Allocations can never be larger thanisize::MAX bytes, so if the computed offsetstays 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 alwayssafe.
§Examples
1.80.0 (const: 1.80.0) ·Sourcepub const unsafe fnbyte_offset(self, count:isize) -> Self
pub const unsafe fnbyte_offset(self, count:isize) -> Self
Calculates the offset from a pointer in bytes.
count is in units ofbytes.
This is purely a convenience for casting to au8 pointer andusingoffset on it. See that method for documentationand safety requirements.
For non-Sized pointees this operation changes only the data pointer,leaving the metadata untouched.
1.80.0 (const: 1.80.0) ·Sourcepub const unsafe fnadd(self, count:usize) -> Selfwhere T:Sized,
pub const unsafe fnadd(self, count:usize) -> Selfwhere T:Sized,
Adds an offset to a pointer (convenience for.offset(count as isize)).
count is in units of T; e.g., acount of 3 represents a pointeroffset 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 someallocation, and the entire memory range betweenselfand the result must be inbounds of that allocation. In particular, this range must not “wrap around” the edgeof the address space.
Allocations can never be larger thanisize::MAX bytes, so if the computed offsetstays 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 alwayssafe.
§Examples
1.80.0 (const: 1.80.0) ·Sourcepub const unsafe fnbyte_add(self, count:usize) -> Self
pub const unsafe fnbyte_add(self, count:usize) -> Self
Calculates the offset from a pointer in bytes (convenience for.byte_offset(count as isize)).
count is in units of bytes.
This is purely a convenience for casting to au8 pointer andusingadd on it. See that method for documentationand safety requirements.
For non-Sized pointees this operation changes only the data pointer,leaving the metadata untouched.
1.80.0 (const: 1.80.0) ·Sourcepub const unsafe fnsub(self, count:usize) -> Selfwhere T:Sized,
pub const unsafe fnsub(self, count:usize) -> Selfwhere T:Sized,
Subtracts an offset from a pointer (convenience for.offset((count as isize).wrapping_neg())).
count is in units of T; e.g., acount of 3 represents a pointeroffset 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 someallocation, and the entire memory range betweenselfand the result must be inbounds of that allocation. In particular, this range must not “wrap around” the edgeof the address space.
Allocations can never be larger thanisize::MAX bytes, so if the computed offsetstays 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 alwayssafe.
§Examples
1.80.0 (const: 1.80.0) ·Sourcepub const unsafe fnbyte_sub(self, count:usize) -> Self
pub const unsafe fnbyte_sub(self, count:usize) -> Self
Calculates the offset from a pointer in bytes (convenience for.byte_offset((count as isize).wrapping_neg())).
count is in units of bytes.
This is purely a convenience for casting to au8 pointer andusingsub on it. See that method for documentationand safety requirements.
For non-Sized pointees this operation changes only the data pointer,leaving the metadata untouched.
1.80.0 (const: 1.80.0) ·Sourcepub const unsafe fnoffset_from(self, origin:NonNull<T>) ->isizewhere T:Sized,
pub const unsafe fnoffset_from(self, origin:NonNull<T>) ->isizewhere T:Sized,
Calculates the distance between two pointers within the same allocation. The returned value is inunits of T: the distance in bytes divided bysize_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 compilerbetter understanding what you are doing.
The primary motivation of this method is for computing thelen of an array/sliceofT that 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 bederived from a pointer to the sameallocation, and the memory range betweenthe 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 multipleof the size of
T.
As a consequence, the absolute distance between the pointers, in bytes, computed onmathematical integers (without “wrapping around”), cannot overflow anisize. This isimplied by the in-bounds requirement, and the fact that no allocation can be largerthanisize::MAX bytes.
The requirement for pointers to be derived from the same allocation is primarilyneeded forconst-compatibility: the distance between pointers intodifferent allocatedobjects is not known at compile-time. However, the requirement also exists atruntime and may be exploited by optimizations. If you wish to compute the difference betweenpointers that are not guaranteed to be from the same allocation, use(self as isize - origin as isize) / size_of::<T>().
§Panics
This function panics ifT is a Zero-Sized Type (“ZST”).
§Examples
Basic usage:
usestd::ptr::NonNull;leta = [0;5];letptr1: NonNull<u32> = NonNull::from(&a[1]);letptr2: NonNull<u32> = NonNull::from(&a[3]);unsafe{assert_eq!(ptr2.offset_from(ptr1),2);assert_eq!(ptr1.offset_from(ptr2), -2);assert_eq!(ptr1.offset(2), ptr2);assert_eq!(ptr2.offset(-2), ptr1);}Incorrect usage:
usestd::ptr::NonNull;letptr1 = NonNull::new(Box::into_raw(Box::new(0u8))).unwrap();letptr2 = NonNull::new(Box::into_raw(Box::new(1u8))).unwrap();letdiff = (ptr2.addr().get()asisize).wrapping_sub(ptr1.addr().get()asisize);// Make ptr2_other an "alias" of ptr2.add(1), but derived from ptr1.letdiff_plus_1 = diff.wrapping_add(1);letptr2_other = NonNull::new(ptr1.as_ptr().wrapping_byte_offset(diff_plus_1)).unwrap();assert_eq!(ptr2.addr(), ptr2_other.addr());// 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!letone =unsafe{ ptr2_other.offset_from(ptr2) };// Undefined Behavior! ⚠️1.80.0 (const: 1.80.0) ·Sourcepub const unsafe fnbyte_offset_from<U: ?Sized>( self, origin:NonNull<U>,) ->isize
pub const unsafe fnbyte_offset_from<U: ?Sized>( self, origin:NonNull<U>,) ->isize
Calculates the distance between two pointers within the same allocation. The returned value is inunits ofbytes.
This is purely a convenience for casting to au8 pointer andusingoffset_from on it. See that method fordocumentation and safety requirements.
For non-Sized pointees this operation considers only the data pointers,ignoring the metadata.
1.87.0 (const: 1.87.0) ·Sourcepub const unsafe fnoffset_from_unsigned(self, subtracted:NonNull<T>) ->usizewhere T:Sized,
pub const unsafe fnoffset_from_unsigned(self, subtracted:NonNull<T>) ->usizewhere T:Sized,
Calculates the distance between two pointers within the same allocation,where it’s known thatself is equal to or greater thanorigin. The returned value is inunits of T: the distance in bytes is divided bysize_of::<T>().
This computes the same value thatoffset_fromwould compute, but with the added precondition that the offset isguaranteed 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 cansometimes allow it to optimize slightly better with some backends.
This method can be though of as recovering thecount that was passedtoadd (or, with the parameters in the other order,tosub). The following are all equivalent, assumingthat their safety preconditions are met:
§Safety
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 representa larger offset, it’s stillnot permitted to pass pointers which differby more thanisize::MAXbytes. As such, the result of this method willalways be less than or equal toisize::MAX as usize.
§Panics
This function panics ifT is a Zero-Sized Type (“ZST”).
§Examples
usestd::ptr::NonNull;leta = [0;5];letptr1: NonNull<u32> = NonNull::from(&a[1]);letptr2: NonNull<u32> = NonNull::from(&a[3]);unsafe{assert_eq!(ptr2.offset_from_unsigned(ptr1),2);assert_eq!(ptr1.add(2), ptr2);assert_eq!(ptr2.sub(2), ptr1);assert_eq!(ptr2.offset_from_unsigned(ptr2),0);}// This would be incorrect, as the pointers are not correctly ordered:// ptr1.offset_from_unsigned(ptr2)1.87.0 (const: 1.87.0) ·Sourcepub const unsafe fnbyte_offset_from_unsigned<U: ?Sized>( self, origin:NonNull<U>,) ->usize
pub const unsafe fnbyte_offset_from_unsigned<U: ?Sized>( self, origin:NonNull<U>,) ->usize
Calculates the distance between two pointers within the same allocation,where it’s known thatself is equal to or greater thanorigin. The returned value is inunits ofbytes.
This is purely a convenience for casting to au8 pointer andusingoffset_from_unsigned on it.See that method for documentation and safety requirements.
For non-Sized pointees this operation considers only the data pointers,ignoring the metadata.
1.80.0 (const: 1.80.0) ·Sourcepub const unsafe fnread(self) -> Twhere T:Sized,
pub const unsafe fnread(self) -> Twhere T:Sized,
Reads the value fromself without moving it. This leaves thememory inself unchanged.
Seeptr::read for safety concerns and examples.
1.80.0 ·Sourcepub unsafe fnread_volatile(self) -> Twhere T:Sized,
pub unsafe fnread_volatile(self) -> Twhere T:Sized,
Performs a volatile read of the value fromself without moving it. Thisleaves the memory inself unchanged.
Volatile operations are intended to act on I/O memory, and are guaranteedto not be elided or reordered by the compiler across other volatileoperations.
Seeptr::read_volatile for safety concerns and examples.
1.80.0 (const: 1.80.0) ·Sourcepub const unsafe fnread_unaligned(self) -> Twhere T:Sized,
pub const unsafe fnread_unaligned(self) -> Twhere T:Sized,
Reads the value fromself without moving it. This leaves thememory inself unchanged.
Unlikeread, the pointer may be unaligned.
Seeptr::read_unaligned for safety concerns and examples.
1.80.0 (const: 1.83.0) ·Sourcepub const unsafe fncopy_to(self, dest:NonNull<T>, count:usize)where T:Sized,
pub const unsafe fncopy_to(self, dest:NonNull<T>, count:usize)where T:Sized,
1.80.0 (const: 1.83.0) ·Sourcepub const unsafe fncopy_to_nonoverlapping(self, dest:NonNull<T>, count:usize)where T:Sized,
pub const unsafe fncopy_to_nonoverlapping(self, dest:NonNull<T>, count:usize)where T:Sized,
Copiescount * size_of::<T>() bytes fromself todest. The sourceand destination maynot overlap.
NOTE: this has thesame argument order asptr::copy_nonoverlapping.
Seeptr::copy_nonoverlapping for safety concerns and examples.
1.80.0 (const: 1.83.0) ·Sourcepub const unsafe fncopy_from(self, src:NonNull<T>, count:usize)where T:Sized,
pub const unsafe fncopy_from(self, src:NonNull<T>, count:usize)where T:Sized,
1.80.0 (const: 1.83.0) ·Sourcepub const unsafe fncopy_from_nonoverlapping( self, src:NonNull<T>, count:usize,)where T:Sized,
pub const unsafe fncopy_from_nonoverlapping( self, src:NonNull<T>, count:usize,)where T:Sized,
Copiescount * size_of::<T>() bytes fromsrc toself. The sourceand destination maynot overlap.
NOTE: this has theopposite argument order ofptr::copy_nonoverlapping.
Seeptr::copy_nonoverlapping for safety concerns and examples.
1.80.0 ·Sourcepub unsafe fndrop_in_place(self)
pub unsafe fndrop_in_place(self)
Executes the destructor (if any) of the pointed-to value.
Seeptr::drop_in_place for safety concerns and examples.
1.80.0 (const: 1.83.0) ·Sourcepub const unsafe fnwrite(self, val: T)where T:Sized,
pub const unsafe fnwrite(self, val: T)where T:Sized,
Overwrites a memory location with the given value without reading ordropping the old value.
Seeptr::write for safety concerns and examples.
1.80.0 (const: 1.83.0) ·Sourcepub const unsafe fnwrite_bytes(self, val:u8, count:usize)where T:Sized,
pub const unsafe fnwrite_bytes(self, val:u8, count:usize)where T:Sized,
Invokes memset on the specified pointer, settingcount * size_of::<T>()bytes of memory starting atself toval.
Seeptr::write_bytes for safety concerns and examples.
1.80.0 ·Sourcepub unsafe fnwrite_volatile(self, val: T)where T:Sized,
pub unsafe fnwrite_volatile(self, val: T)where T:Sized,
Performs a volatile write of a memory location with the given value withoutreading or dropping the old value.
Volatile operations are intended to act on I/O memory, and are guaranteedto not be elided or reordered by the compiler across other volatileoperations.
Seeptr::write_volatile for safety concerns and examples.
1.80.0 (const: 1.83.0) ·Sourcepub const unsafe fnwrite_unaligned(self, val: T)where T:Sized,
pub const unsafe fnwrite_unaligned(self, val: T)where T:Sized,
Overwrites a memory location with the given value without reading ordropping the old value.
Unlikewrite, the pointer may be unaligned.
Seeptr::write_unaligned for safety concerns and examples.
1.80.0 (const: 1.88.0) ·Sourcepub const unsafe fnreplace(self, src: T) -> Twhere T:Sized,
pub const unsafe fnreplace(self, src: T) -> Twhere T:Sized,
Replaces the value atself withsrc, returning the oldvalue, without dropping either.
Seeptr::replace for safety concerns and examples.
1.80.0 (const: 1.85.0) ·Sourcepub const unsafe fnswap(self, with:NonNull<T>)where T:Sized,
pub const unsafe fnswap(self, with:NonNull<T>)where T:Sized,
Swaps the values at two mutable locations of the same type, withoutdeinitializing either. They may overlap, unlikemem::swap which isotherwise equivalent.
Seeptr::swap for safety concerns and examples.
1.80.0 ·Sourcepub fnalign_offset(self, align:usize) ->usizewhere T:Sized,
pub fnalign_offset(self, align:usize) ->usizewhere T:Sized,
Computes the offset that needs to be applied to the pointer in order to make it aligned toalign.
If it is not possible to align the pointer, the implementation returnsusize::MAX.
The offset is expressed in number ofT elements, and not bytes.
There are no guarantees whatsoever that offsetting the pointer will not overflow or gobeyond the allocation that the pointer points into. It is up to the caller to ensure thatthe returned offset is correct in all terms other than alignment.
When this is called during compile-time evaluation (which is unstable), the implementationmay returnusize::MAX in cases where that can never happen at runtime. This is because theactual alignment of pointers is not known yet during compile-time, so an offset withguaranteed 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 yetknown, so the execution has to be correct for either choice. It is therefore impossible tofind an offset that is guaranteed to be 2-aligned. (This behavior is subject to change, as usualfor unstable APIs.)
§Panics
The function panics ifalign is not a power-of-two.
§Examples
Accessing adjacentu8 asu16
usestd::ptr::NonNull;letx = [5_u8,6,7,8,9];letptr = NonNull::new(x.as_ptr()as*mutu8).unwrap();letoffset = ptr.align_offset(align_of::<u16>());ifoffset < x.len() -1{letu16_ptr = ptr.add(offset).cast::<u16>();assert!(u16_ptr.read() == u16::from_ne_bytes([5,6]) || u16_ptr.read() == u16::from_ne_bytes([6,7]));}else{// while the pointer can be aligned via `offset`, it would point // outside the allocation}1.79.0 ·Sourcepub fnis_aligned(self) ->boolwhere T:Sized,
pub fnis_aligned(self) ->boolwhere T:Sized,
Returns whether the pointer is properly aligned forT.
§Examples
Sourcepub fnis_aligned_to(self, align:usize) ->bool
🔬This is a nightly-only experimental API. (pointer_is_aligned_to #96284)
pub fnis_aligned_to(self, align:usize) ->bool
pointer_is_aligned_to #96284)Returns whether the pointer is aligned toalign.
For non-Sized pointees this operation considers only the data pointer,ignoring the metadata.
§Panics
The function panics ifalign is not a power-of-two (this includes 0).
§Examples
#![feature(pointer_is_aligned_to)]// On some platforms, the alignment of i32 is less than 4.#[repr(align(4))]structAlignedI32(i32);letdata = AlignedI32(42);letptr =&dataas*constAlignedI32;assert!(ptr.is_aligned_to(1));assert!(ptr.is_aligned_to(2));assert!(ptr.is_aligned_to(4));assert!(ptr.wrapping_byte_add(2).is_aligned_to(2));assert!(!ptr.wrapping_byte_add(2).is_aligned_to(4));assert_ne!(ptr.is_aligned_to(8), ptr.wrapping_add(1).is_aligned_to(8));Source§impl<T>NonNull<T>
impl<T>NonNull<T>
Sourcepub const fncast_uninit(self) ->NonNull<MaybeUninit<T>>
🔬This is a nightly-only experimental API. (cast_maybe_uninit #145036)
pub const fncast_uninit(self) ->NonNull<MaybeUninit<T>>
cast_maybe_uninit #145036)Casts from a type to its maybe-uninitialized version.
Source§impl<T>NonNull<MaybeUninit<T>>
impl<T>NonNull<MaybeUninit<T>>
Source§impl<T>NonNull<[T]>
impl<T>NonNull<[T]>
1.70.0 (const: 1.83.0) ·Sourcepub const fnslice_from_raw_parts(data:NonNull<T>, len:usize) -> Self
pub const fnslice_from_raw_parts(data:NonNull<T>, len:usize) -> Self
Creates a non-null raw slice from a thin pointer and a length.
Thelen argument is the number ofelements, not the number of bytes.
This function is safe, but dereferencing the return value is unsafe.See the documentation ofslice::from_raw_parts for slice safety requirements.
§Examples
usestd::ptr::NonNull;// create a slice pointer when starting out with a pointer to the first elementletmutx = [5,6,7];letnonnull_pointer = NonNull::new(x.as_mut_ptr()).unwrap();letslice = NonNull::slice_from_raw_parts(nonnull_pointer,3);assert_eq!(unsafe{ slice.as_ref()[2] },7);(Note that this example artificially demonstrates a use of this method,butlet slice = NonNull::from(&x[..]); would be a better way to write code like this.)
1.63.0 (const: 1.63.0) ·Sourcepub const fnlen(self) ->usize
pub const fnlen(self) ->usize
Returns the length of a non-null raw slice.
The returned value is the number ofelements, not the number of bytes.
This function is safe, even when the non-null raw slice cannot be dereferenced to a slicebecause the pointer does not have a valid address.
§Examples
1.79.0 (const: 1.79.0) ·Sourcepub const fnis_empty(self) ->bool
pub const fnis_empty(self) ->bool
Returnstrue if the non-null raw slice has a length of 0.
§Examples
Sourcepub const fnas_non_null_ptr(self) ->NonNull<T>
🔬This is a nightly-only experimental API. (slice_ptr_get #74265)
pub const fnas_non_null_ptr(self) ->NonNull<T>
slice_ptr_get #74265)Returns a non-null pointer to the slice’s buffer.
§Examples
Sourcepub const fnas_mut_ptr(self) ->*mut T
🔬This is a nightly-only experimental API. (slice_ptr_get #74265)
pub const fnas_mut_ptr(self) ->*mut T
slice_ptr_get #74265)Returns a raw pointer to the slice’s buffer.
§Examples
Sourcepub const unsafe fnas_uninit_slice<'a>(self) -> &'a [MaybeUninit<T>]
🔬This is a nightly-only experimental API. (ptr_as_uninit #75402)
pub const unsafe fnas_uninit_slice<'a>(self) -> &'a [MaybeUninit<T>]
ptr_as_uninit #75402)Returns a shared reference to a slice of possibly uninitialized values. In contrast toas_ref, this does not require that the value has to be initialized.
For the mutable counterpart seeas_uninit_slice_mut.
§Safety
When calling this method, you have to ensure that all of the following is true:
The pointer must bevalid 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. Onereason for this is that enum layout optimizations may rely on references(including slices of any length) being aligned and non-null to distinguishthem from other data. You can obtain a pointer that is usable as
datafor zero-length slices usingNonNull::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
'aisarbitrarily chosen and does not necessarily reflect the actual lifetime of the data.In particular, while this reference exists, the memory the pointer points to mustnot get mutated (except insideUnsafeCell).
This applies even if the result of this method is unused!
See alsoslice::from_raw_parts.
Sourcepub const unsafe fnas_uninit_slice_mut<'a>(self) -> &'a mut [MaybeUninit<T>]
🔬This is a nightly-only experimental API. (ptr_as_uninit #75402)
pub const unsafe fnas_uninit_slice_mut<'a>(self) -> &'a mut [MaybeUninit<T>]
ptr_as_uninit #75402)Returns a unique reference to a slice of possibly uninitialized values. In contrast toas_mut, this does not require that the value has to be initialized.
For the shared counterpart seeas_uninit_slice.
§Safety
When calling this method, you have to ensure that all of the following is true:
The pointer must bevalid 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. Onereason for this is that enum layout optimizations may rely on references(including slices of any length) being aligned and non-null to distinguishthem from other data. You can obtain a pointer that is usable as
datafor zero-length slices usingNonNull::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
'aisarbitrarily chosen and does not necessarily reflect the actual lifetime of the data.In particular, while this reference exists, the memory the pointer points to mustnot get accessed (read or written) through any other pointer.
This applies even if the result of this method is unused!
See alsoslice::from_raw_parts_mut.
§Examples
#![feature(allocator_api, ptr_as_uninit)]usestd::alloc::{Allocator, Layout, Global};usestd::mem::MaybeUninit;usestd::ptr::NonNull;letmemory: NonNull<[u8]> = Global.allocate(Layout::new::<[u8;32]>())?;// 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.letslice:&mut[MaybeUninit<u8>] =unsafe{ memory.as_uninit_slice_mut() };Sourcepub const unsafe fnget_unchecked_mut<I>(self, index: I) ->NonNull<I::Output>where I:SliceIndex<[T]>,
🔬This is a nightly-only experimental API. (slice_ptr_get #74265)
pub const unsafe fnget_unchecked_mut<I>(self, index: I) ->NonNull<I::Output>where I:SliceIndex<[T]>,
slice_ptr_get #74265)Returns a raw pointer to an element or subslice, without doing boundschecking.
Calling this method with an out-of-bounds index or whenself is not dereferenceableisundefined behavior even if the resulting pointer is not used.
§Examples
Trait Implementations§
1.25.0 ·Source§impl<T:PointeeSized>Clone forNonNull<T>
impl<T:PointeeSized>Clone forNonNull<T>
1.25.0 ·Source§impl<T:PointeeSized>Debug forNonNull<T>
impl<T:PointeeSized>Debug forNonNull<T>
1.25.0 ·Source§impl<T:PointeeSized>Hash forNonNull<T>
impl<T:PointeeSized>Hash forNonNull<T>
1.25.0 ·Source§impl<T:PointeeSized>Ord forNonNull<T>
impl<T:PointeeSized>Ord forNonNull<T>
1.25.0 ·Source§impl<T:PointeeSized>PartialEq forNonNull<T>
impl<T:PointeeSized>PartialEq forNonNull<T>
1.25.0 ·Source§impl<T:PointeeSized>PartialOrd forNonNull<T>
impl<T:PointeeSized>PartialOrd forNonNull<T>
1.25.0 ·Source§impl<T:PointeeSized>Pointer forNonNull<T>
impl<T:PointeeSized>Pointer forNonNull<T>
impl<T, U:PointeeSized>CoerceUnsized<NonNull<U>> forNonNull<T>where T:Unsize<U> +PointeeSized,
impl<T:PointeeSized>Copy forNonNull<T>
impl<T, U:PointeeSized>DispatchFromDyn<NonNull<U>> forNonNull<T>where T:Unsize<U> +PointeeSized,
impl<T:PointeeSized>Eq forNonNull<T>
impl<T:PointeeSized>PinCoerceUnsized forNonNull<T>
impl<T:PointeeSized> !Send forNonNull<T>
NonNull pointers are notSend because the data they reference may be aliased.
impl<T:PointeeSized> !Sync forNonNull<T>
NonNull pointers are notSync because the data they reference may be aliased.