Movatterモバイル変換


[0]ホーム

URL:


NonNull

core::ptr

StructNonNull 

1.25.0 ·Source
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>

1.89.0 (const: 1.89.0) ·Source

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) ·Source

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
usestd::ptr::NonNull;letptr = NonNull::<u32>::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!
1.89.0 ·Source

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.

Source

pub const unsafe fnas_uninit_ref<'a>(self) -> &'aMaybeUninit<T>

🔬This is a nightly-only experimental API. (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.

Source

pub const unsafe fnas_uninit_mut<'a>(self) -> &'a mutMaybeUninit<T>

🔬This is a nightly-only experimental API. (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

pub const fncast_array<const N:usize>(self) ->NonNull<[T; N]>

🔬This is a nightly-only experimental API. (ptr_cast_array #144514)

Casts from a pointer-to-T to a pointer-to-[T; N].

Source§

impl<T:PointeeSized>NonNull<T>

1.25.0 (const: 1.25.0) ·Source

pub const unsafe fnnew_unchecked(ptr:*mut T) -> Self

Creates a newNonNull.

§Safety

ptr must be non-null.

§Examples
usestd::ptr::NonNull;letmutx =0u32;letptr =unsafe{ NonNull::new_unchecked(&mutxas*mut_) };

Incorrect usage of this function:

usestd::ptr::NonNull;// NEVER DO THAT!!! This is undefined behavior. ⚠️letptr =unsafe{ NonNull::<u32>::new_unchecked(std::ptr::null_mut()) };
1.25.0 (const: 1.85.0) ·Source

pub const fnnew(ptr:*mut T) ->Option<Self>

Creates a newNonNull ifptr is non-null.

§Panics during const evaluation

This method will panic during const evaluation if the pointer cannot bedetermined to be null or not. Seeis_null for more information.

§Examples
usestd::ptr::NonNull;letmutx =0u32;letptr = NonNull::<u32>::new(&mutxas*mut_).expect("ptr is null!");if letSome(ptr) = NonNull::<u32>::new(std::ptr::null_mut()) {unreachable!();}
1.89.0 (const: 1.89.0) ·Source

pub const fnfrom_ref(r:&T) -> Self

Converts a reference to aNonNull pointer.

1.89.0 (const: 1.89.0) ·Source

pub const fnfrom_mut(r:&mut T) -> Self

Converts a mutable reference to aNonNull pointer.

Source

pub const fnfrom_raw_parts( data_pointer:NonNull<implThin>, metadata: <T asPointee>::Metadata,) ->NonNull<T>

🔬This is a nightly-only experimental API. (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.

Source

pub const fnto_raw_parts(self) -> (NonNull<()>, <T asPointee>::Metadata)

🔬This is a nightly-only experimental API. (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 ·Source

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 ·Source

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 ·Source

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 ·Source

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) ·Source

pub const fnas_ptr(self) ->*mut T

Acquires the underlying*mut pointer.

§Examples
usestd::ptr::NonNull;letmutx =0u32;letptr = NonNull::new(&mutx).expect("ptr is null!");letx_value =unsafe{*ptr.as_ptr() };assert_eq!(x_value,0);unsafe{*ptr.as_ptr() +=2; }letx_value =unsafe{*ptr.as_ptr() };assert_eq!(x_value,2);
1.25.0 (const: 1.73.0) ·Source

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
usestd::ptr::NonNull;letmutx =0u32;letptr = NonNull::new(&mutxas*mut_).expect("ptr is null!");letref_x =unsafe{ ptr.as_ref() };println!("{ref_x}");
1.25.0 (const: 1.83.0) ·Source

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
usestd::ptr::NonNull;letmutx =0u32;letmutptr = NonNull::new(&mutx).expect("null pointer");letx_ref =unsafe{ ptr.as_mut() };assert_eq!(*x_ref,0);*x_ref +=2;assert_eq!(*x_ref,2);
1.27.0 (const: 1.36.0) ·Source

pub const fncast<U>(self) ->NonNull<U>

Casts to a pointer of another type.

§Examples
usestd::ptr::NonNull;letmutx =0u32;letptr = NonNull::new(&mutxas*mut_).expect("null pointer");letcasted_ptr = ptr.cast::<i8>();letraw_ptr:*muti8 = casted_ptr.as_ptr();
Source

pub fntry_cast_aligned<U>(self) ->Option<NonNull<U>>

🔬This is a nightly-only experimental API. (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
#![feature(pointer_try_cast_aligned)]usestd::ptr::NonNull;letmutx =0u64;letaligned = NonNull::from_mut(&mutx);letunaligned =unsafe{ aligned.byte_add(1) };assert!(aligned.try_cast_aligned::<u32>().is_some());assert!(unaligned.try_cast_aligned::<u32>().is_none());
1.80.0 (const: 1.80.0) ·Source

pub const unsafe fnoffset(self, count:isize) -> Self
where 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, thenself must be derived from a pointer to someallocation, and the entire memory range betweenself and 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
usestd::ptr::NonNull;letmuts = [1,2,3];letptr: NonNull<u32> = NonNull::new(s.as_mut_ptr()).unwrap();unsafe{println!("{}", ptr.offset(1).read());println!("{}", ptr.offset(2).read());}
1.80.0 (const: 1.80.0) ·Source

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) ·Source

pub const unsafe fnadd(self, count:usize) -> Self
where 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, thenself must be derived from a pointer to someallocation, and the entire memory range betweenself and 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
usestd::ptr::NonNull;lets:&str ="123";letptr: NonNull<u8> = NonNull::new(s.as_ptr().cast_mut()).unwrap();unsafe{println!("{}", ptr.add(1).read()aschar);println!("{}", ptr.add(2).read()aschar);}
1.80.0 (const: 1.80.0) ·Source

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) ·Source

pub const unsafe fnsub(self, count:usize) -> Self
where 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, thenself must be derived from a pointer to someallocation, and the entire memory range betweenself and 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
usestd::ptr::NonNull;lets:&str ="123";unsafe{letend: NonNull<u8> = NonNull::new(s.as_ptr().cast_mut()).unwrap().add(3);println!("{}", end.sub(1).read()aschar);println!("{}", end.sub(2).read()aschar);}
1.80.0 (const: 1.80.0) ·Source

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) ·Source

pub const unsafe fnoffset_from(self, origin:NonNull<T>) ->isize
where 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:

  • self andorigin must 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 ofT.

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) ·Source

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) ·Source

pub const unsafe fnoffset_from_unsigned(self, subtracted:NonNull<T>) ->usize
where 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:

ptr.offset_from_unsigned(origin) == countorigin.add(count) == ptrptr.sub(count) == origin
§Safety
  • The distance between the pointers must be non-negative (self >= origin)

  • All the safety conditions ofoffset_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) ·Source

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) ·Source

pub const unsafe fnread(self) -> T
where T:Sized,

Reads the value fromself without moving it. This leaves thememory inself unchanged.

Seeptr::read for safety concerns and examples.

1.80.0 ·Source

pub unsafe fnread_volatile(self) -> T
where 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) ·Source

pub const unsafe fnread_unaligned(self) -> T
where 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) ·Source

pub const unsafe fncopy_to(self, dest:NonNull<T>, count:usize)
where T:Sized,

Copiescount * size_of::<T>() bytes fromself todest. The sourceand destination may overlap.

NOTE: this has thesame argument order asptr::copy.

Seeptr::copy for safety concerns and examples.

1.80.0 (const: 1.83.0) ·Source

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) ·Source

pub const unsafe fncopy_from(self, src:NonNull<T>, count:usize)
where T:Sized,

Copiescount * size_of::<T>() bytes fromsrc toself. The sourceand destination may overlap.

NOTE: this has theopposite argument order ofptr::copy.

Seeptr::copy for safety concerns and examples.

1.80.0 (const: 1.83.0) ·Source

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 ·Source

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) ·Source

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) ·Source

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 ·Source

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) ·Source

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) ·Source

pub const unsafe fnreplace(self, src: T) -> T
where 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) ·Source

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 ·Source

pub fnalign_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 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 ·Source

pub fnis_aligned(self) ->bool
where T:Sized,

Returns whether the pointer is properly aligned forT.

§Examples
usestd::ptr::NonNull;// On some platforms, the alignment of i32 is less than 4.#[repr(align(4))]structAlignedI32(i32);letdata = AlignedI32(42);letptr = NonNull::<AlignedI32>::from(&data);assert!(ptr.is_aligned());assert!(!NonNull::new(ptr.as_ptr().wrapping_byte_add(1)).unwrap().is_aligned());
Source

pub fnis_aligned_to(self, align:usize) ->bool

🔬This is a nightly-only experimental API. (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>

Source

pub const fncast_uninit(self) ->NonNull<MaybeUninit<T>>

🔬This is a nightly-only experimental API. (cast_maybe_uninit #145036)

Casts from a type to its maybe-uninitialized version.

Source§

impl<T>NonNull<MaybeUninit<T>>

Source

pub const fncast_init(self) ->NonNull<T>

🔬This is a nightly-only experimental API. (cast_maybe_uninit #145036)

Casts from a maybe-uninitialized type to its initialized version.

This is always safe, since UB can only occur if the pointer is readbefore being initialized.

Source§

impl<T>NonNull<[T]>

1.70.0 (const: 1.83.0) ·Source

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) ·Source

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
usestd::ptr::NonNull;letslice: NonNull<[i8]> = NonNull::slice_from_raw_parts(NonNull::dangling(),3);assert_eq!(slice.len(),3);
1.79.0 (const: 1.79.0) ·Source

pub const fnis_empty(self) ->bool

Returnstrue if the non-null raw slice has a length of 0.

§Examples
usestd::ptr::NonNull;letslice: NonNull<[i8]> = NonNull::slice_from_raw_parts(NonNull::dangling(),3);assert!(!slice.is_empty());
Source

pub const fnas_non_null_ptr(self) ->NonNull<T>

🔬This is a nightly-only experimental API. (slice_ptr_get #74265)

Returns a non-null pointer to the slice’s buffer.

§Examples
#![feature(slice_ptr_get)]usestd::ptr::NonNull;letslice: NonNull<[i8]> = NonNull::slice_from_raw_parts(NonNull::dangling(),3);assert_eq!(slice.as_non_null_ptr(), NonNull::<i8>::dangling());
Source

pub const fnas_mut_ptr(self) ->*mut T

🔬This is a nightly-only experimental API. (slice_ptr_get #74265)

Returns a raw pointer to the slice’s buffer.

§Examples
#![feature(slice_ptr_get)]usestd::ptr::NonNull;letslice: NonNull<[i8]> = NonNull::slice_from_raw_parts(NonNull::dangling(),3);assert_eq!(slice.as_mut_ptr(), NonNull::<i8>::dangling().as_ptr());
Source

pub const unsafe fnas_uninit_slice<'a>(self) -> &'a [MaybeUninit<T>]

🔬This is a nightly-only experimental API. (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 forptr.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 asdatafor zero-length slices usingNonNull::dangling().

  • The total sizeptr.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'a isarbitrarily 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.

Source

pub const unsafe fnas_uninit_slice_mut<'a>(self) -> &'a mut [MaybeUninit<T>]

🔬This is a nightly-only experimental API. (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 forptr.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 asdatafor zero-length slices usingNonNull::dangling().

  • The total sizeptr.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'a isarbitrarily 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() };
Source

pub 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)

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
#![feature(slice_ptr_get)]usestd::ptr::NonNull;letx =&mut[1,2,4];letx = NonNull::slice_from_raw_parts(NonNull::new(x.as_mut_ptr()).unwrap(), x.len());unsafe{assert_eq!(x.get_unchecked_mut(1).as_ptr(), x.as_non_null_ptr().as_ptr().add(1));}

Trait Implementations§

1.25.0 ·Source§

impl<T:PointeeSized>Clone forNonNull<T>

Source§

fnclone(&self) -> Self

Returns a duplicate of the value.Read more
1.0.0 ·Source§

fnclone_from(&mut self, source: &Self)
where Self:,

Performs copy-assignment fromsource.Read more
1.25.0 ·Source§

impl<T:PointeeSized>Debug forNonNull<T>

Source§

fnfmt(&self, f: &mutFormatter<'_>) ->Result

Formats the value using the given formatter.Read more
1.25.0 (const:unstable) ·Source§

impl<T:PointeeSized>From<&T> forNonNull<T>

Source§

fnfrom(r:&T) -> Self

Converts a&T to aNonNull<T>.

This conversion is safe and infallible since references cannot be null.

1.25.0 (const:unstable) ·Source§

impl<T:PointeeSized>From<&mut T> forNonNull<T>

Source§

fnfrom(r:&mut T) -> Self

Converts a&mut T to aNonNull<T>.

This conversion is safe and infallible since references cannot be null.

1.25.0 ·Source§

impl<T:PointeeSized>Hash forNonNull<T>

Source§

fnhash<H:Hasher>(&self, state:&mut H)

Feeds this value into the givenHasher.Read more
1.3.0 ·Source§

fnhash_slice<H:Hasher>(data: &[Self], state:&mut H)
where Self:Sized,

Feeds a slice of this type into the givenHasher.Read more
1.25.0 ·Source§

impl<T:PointeeSized>Ord forNonNull<T>

Source§

fncmp(&self, other: &Self) ->Ordering

This method returns anOrdering betweenself andother.Read more
1.21.0 ·Source§

fnmax(self, other: Self) -> Self
where Self:Sized,

Compares and returns the maximum of two values.Read more
1.21.0 ·Source§

fnmin(self, other: Self) -> Self
where Self:Sized,

Compares and returns the minimum of two values.Read more
1.50.0 ·Source§

fnclamp(self, min: Self, max: Self) -> Self
where Self:Sized,

Restrict a value to a certain interval.Read more
1.25.0 ·Source§

impl<T:PointeeSized>PartialEq forNonNull<T>

Source§

fneq(&self, other: &Self) ->bool

Tests forself andother values to be equal, and is used by==.
1.0.0 ·Source§

fnne(&self, other:&Rhs) ->bool

Tests for!=. The default implementation is almost always sufficient,and should not be overridden without very good reason.
1.25.0 ·Source§

impl<T:PointeeSized>PartialOrd forNonNull<T>

Source§

fnpartial_cmp(&self, other: &Self) ->Option<Ordering>

This method returns an ordering betweenself andother values if one exists.Read more
1.0.0 ·Source§

fnlt(&self, other:&Rhs) ->bool

Tests less than (forself andother) and is used by the< operator.Read more
1.0.0 ·Source§

fnle(&self, other:&Rhs) ->bool

Tests less than or equal to (forself andother) and is used by the<= operator.Read more
1.0.0 ·Source§

fngt(&self, other:&Rhs) ->bool

Tests greater than (forself andother) and is used by the>operator.Read more
1.0.0 ·Source§

fnge(&self, other:&Rhs) ->bool

Tests greater than or equal to (forself andother) and is used bythe>= operator.Read more
1.25.0 ·Source§

impl<T:PointeeSized>Pointer forNonNull<T>

Source§

fnfmt(&self, f: &mutFormatter<'_>) ->Result

Formats the value using the given formatter.Read more
Source§

impl<T, U:PointeeSized>CoerceUnsized<NonNull<U>> forNonNull<T>
where T:Unsize<U> +PointeeSized,

1.25.0 ·Source§

impl<T:PointeeSized>Copy forNonNull<T>

Source§

impl<T, U:PointeeSized>DispatchFromDyn<NonNull<U>> forNonNull<T>
where T:Unsize<U> +PointeeSized,

1.25.0 ·Source§

impl<T:PointeeSized>Eq forNonNull<T>

1.33.0 ·Source§

impl<T:PointeeSized>PinCoerceUnsized forNonNull<T>

1.25.0 ·Source§

impl<T:PointeeSized> !Send forNonNull<T>

NonNull pointers are notSend because the data they reference may be aliased.

1.25.0 ·Source§

impl<T:PointeeSized> !Sync forNonNull<T>

NonNull pointers are notSync because the data they reference may be aliased.

1.25.0 ·Source§

impl<T:RefUnwindSafe + ?Sized>UnwindSafe forNonNull<T>

Auto Trait Implementations§

§

impl<T>Freeze forNonNull<T>
where T: ?Sized,

§

impl<T>RefUnwindSafe forNonNull<T>
where T:RefUnwindSafe + ?Sized,

§

impl<T>Unpin forNonNull<T>
where T: ?Sized,

Blanket Implementations§

Source§

impl<T>Any for T
where T: 'static + ?Sized,

Source§

fntype_id(&self) ->TypeId

Gets theTypeId ofself.Read more
Source§

impl<T>Borrow<T> for T
where T: ?Sized,

Source§

fnborrow(&self) ->&T

Immutably borrows from an owned value.Read more
Source§

impl<T>BorrowMut<T> for T
where T: ?Sized,

Source§

fnborrow_mut(&mut self) ->&mut T

Mutably borrows from an owned value.Read more
Source§

impl<T>CloneToUninit for T
where T:Clone,

Source§

unsafe fnclone_to_uninit(&self, dest:*mutu8)

🔬This is a nightly-only experimental API. (clone_to_uninit #126799)
Performs copy-assignment fromself todest.Read more
Source§

impl<T>From<T> for T

Source§

fnfrom(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U>Into<U> for T
where U:From<T>,

Source§

fninto(self) -> U

CallsU::from(self).

That is, this conversion is whatever the implementation ofFrom<T> for U chooses to do.

Source§

impl<T, U>TryFrom<U> for T
where U:Into<T>,

Source§

typeError =Infallible

The type returned in the event of a conversion error.
Source§

fntry_from(value: U) ->Result<T, <T asTryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U>TryInto<U> for T
where U:TryFrom<T>,

Source§

typeError = <U asTryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fntry_into(self) ->Result<U, <U asTryFrom<T>>::Error>

Performs the conversion.

[8]ページ先頭

©2009-2025 Movatter.jp