pub struct NonNullConst<T: PointeeSized>(/* private fields */);Expand description
*const 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 NonNullConst<T>, just use *const T!
Unlike *const 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<NonNullConst<T>> has the same size as *const T.
However the pointer may still dangle if it isn’t dereferenced.
Unlike *const T, NonNullConst<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.
§Representation
Thanks to the null pointer optimization,
NonNullConst<T> and Option<NonNullConst<T>>
are guaranteed to have the same size and alignment:
use non_null_const::NonNullConst;
assert_eq!(size_of::<NonNullConst<i16>>(), size_of::<Option<NonNullConst<i16>>>());
assert_eq!(align_of::<NonNullConst<i16>>(), align_of::<Option<NonNullConst<i16>>>());
assert_eq!(size_of::<NonNullConst<str>>(), size_of::<Option<NonNullConst<str>>>());
assert_eq!(align_of::<NonNullConst<str>>(), align_of::<Option<NonNullConst<str>>>());Implementations§
Source§impl<T: Sized> NonNullConst<T>
impl<T: Sized> NonNullConst<T>
Sourcepub const fn without_provenance(addr: NonZero<usize>) -> Self
pub const fn without_provenance(addr: NonZero<usize>) -> Self
Creates a pointer with the given address and no provenance.
For more details, see the equivalent method on a raw pointer, ptr::without_provenance.
This is a Strict Provenance API.
Sourcepub const fn dangling() -> Self
pub const fn dangling() -> Self
Creates a new NonNullConst that is dangling, but well-aligned.
This is useful for initializing types which lazily allocate, like
Vec::new does.
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 non_null_const::NonNullConst;
let ptr = NonNullConst::<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!Sourcepub fn with_exposed_provenance(addr: NonZero<usize>) -> Self
pub fn with_exposed_provenance(addr: NonZero<usize>) -> Self
Converts an address back to a immutable pointer, picking up some previously ‘exposed’ provenance.
For more details, see the equivalent method on a raw pointer, ptr::with_exposed_provenance.
This is an Exposed Provenance API.
Sourcepub const unsafe fn as_uninit_ref<'a>(self) -> &'a MaybeUninit<T>
Available on crate feature ptr_as_uninit only.
pub const unsafe fn as_uninit_ref<'a>(self) -> &'a MaybeUninit<T>
ptr_as_uninit only.Returns a shared references to the value. In contrast to as_ref, this does not require
that the value has to be initialized.
§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.
Sourcepub const fn cast_array<const N: usize>(self) -> NonNullConst<[T; N]>
Available on crate feature ptr_cast_array only.
pub const fn cast_array<const N: usize>(self) -> NonNullConst<[T; N]>
ptr_cast_array only.Casts from a pointer-to-T to a pointer-to-[T; N].
Source§impl<T: PointeeSized> NonNullConst<T>
impl<T: PointeeSized> NonNullConst<T>
Sourcepub const unsafe fn new_unchecked(ptr: *const T) -> Self
pub const unsafe fn new_unchecked(ptr: *const T) -> Self
Creates a new NonNullConst.
§Safety
ptr must be non-null.
§Examples
use non_null_const::NonNullConst;
let x = 0u32;
let ptr = unsafe { NonNullConst::new_unchecked(&x as *const _) };Incorrect usage of this function:
use non_null_const::NonNullConst;
// NEVER DO THAT!!! This is undefined behavior. ⚠️
let ptr = unsafe { NonNullConst::<u32>::new_unchecked(std::ptr::null()) };Sourcepub const fn new(ptr: *const T) -> Option<Self>
pub const fn new(ptr: *const T) -> Option<Self>
Creates a new NonNullConst if ptr is 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_null for more information.
§Examples
use non_null_const::NonNullConst;
let x = 0u32;
let ptr = NonNullConst::<u32>::new(&x as *const _).expect("ptr is null!");
if let Some(ptr) = NonNullConst::<u32>::new(std::ptr::null()) {
unreachable!();
}Sourcepub const fn from_mut(r: &mut T) -> Self
pub const fn from_mut(r: &mut T) -> Self
Converts a mutable reference to a NonNullConst pointer.
Sourcepub const fn from_raw_parts(
data_pointer: NonNullConst<impl Thin>,
metadata: <T as Pointee>::Metadata,
) -> NonNullConst<T>
Available on crate feature ptr_metadata only.
pub const fn from_raw_parts( data_pointer: NonNullConst<impl Thin>, metadata: <T as Pointee>::Metadata, ) -> NonNullConst<T>
ptr_metadata only.Performs the same functionality as std::ptr::from_raw_parts, except that a
NonNullConst pointer is returned, as opposed to a raw *const pointer.
See the documentation of std::ptr::from_raw_parts for more details.
Sourcepub const fn to_raw_parts(self) -> (NonNullConst<()>, <T as Pointee>::Metadata)
Available on crate feature ptr_metadata only.
pub const fn to_raw_parts(self) -> (NonNullConst<()>, <T as Pointee>::Metadata)
ptr_metadata only.Decompose a (possibly wide) pointer into its data pointer and metadata components.
The pointer can be later reconstructed with NonNullConst::from_raw_parts.
Sourcepub fn addr(self) -> NonZero<usize>
pub fn addr(self) -> NonZero<usize>
Gets the “address” portion of the pointer.
For more details, see the equivalent method on a raw pointer, pointer::addr.
This is a Strict Provenance API.
Sourcepub fn expose_provenance(self) -> NonZero<usize>
pub fn expose_provenance(self) -> NonZero<usize>
Exposes the “provenance” part of the pointer for future use in
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 API.
Sourcepub fn with_addr(self, addr: NonZero<usize>) -> Self
pub fn with_addr(self, addr: NonZero<usize>) -> Self
Creates a new pointer with the given address and the provenance of
self.
For more details, see the equivalent method on a raw pointer, pointer::with_addr.
This is a Strict Provenance API.
Sourcepub fn map_addr(self, f: impl FnOnce(NonZero<usize>) -> NonZero<usize>) -> Self
pub fn map_addr(self, f: impl FnOnce(NonZero<usize>) -> NonZero<usize>) -> Self
Creates a new pointer by mapping self’s address to a new one, preserving the
provenance of self.
For more details, see the equivalent method on a raw pointer, pointer::map_addr.
This is a Strict Provenance API.
Sourcepub const fn as_ptr(self) -> *const T
pub const fn as_ptr(self) -> *const T
Acquires the underlying *const pointer.
§Examples
use non_null_const::NonNullConst;
let x = 0u32;
let ptr = NonNullConst::new(&x).expect("ptr is null!");
let x_value = unsafe { *ptr.as_ptr() };
assert_eq!(x_value, 0);Sourcepub const unsafe fn as_ref<'a>(&self) -> &'a T
pub const unsafe fn as_ref<'a>(&self) -> &'a T
Returns a shared reference to the value. If the value may be uninitialized, as_uninit_ref
must be used instead.
§Safety
When calling this method, you have to ensure that the pointer is convertible to a reference.
§Examples
use non_null_const::NonNullConst;
let x = 0u32;
let ptr = NonNullConst::new(&x as *const _).expect("ptr is null!");
let ref_x = unsafe { ptr.as_ref() };
println!("{ref_x}");Sourcepub const fn cast<U>(self) -> NonNullConst<U>
pub const fn cast<U>(self) -> NonNullConst<U>
Casts to a pointer of another type.
§Examples
use non_null_const::NonNullConst;
let x = 0u32;
let ptr = NonNullConst::new(&x as *const _).expect("null pointer");
let casted_ptr = ptr.cast::<i8>();
let raw_ptr: *const i8 = casted_ptr.as_ptr();Sourcepub fn try_cast_aligned<U>(self) -> Option<NonNullConst<U>>
Available on crate feature pointer_try_cast_aligned only.
pub fn try_cast_aligned<U>(self) -> Option<NonNullConst<U>>
pointer_try_cast_aligned only.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, None is returned.
§Examples
#![feature(pointer_try_cast_aligned)]
use non_null_const::NonNullConst;
let x = 0u64;
let aligned = NonNullConst::from_ref(&x);
let unaligned = unsafe { aligned.byte_add(1) };
assert!(aligned.try_cast_aligned::<u32>().is_some());
assert!(unaligned.try_cast_aligned::<u32>().is_none());Sourcepub const unsafe fn offset(self, count: isize) -> Selfwhere
T: Sized,
pub const unsafe fn offset(self, count: isize) -> Selfwhere
T: Sized,
Adds an offset to a pointer.
count is in units of T; e.g., a count of 3 represents a pointer
offset of 3 * 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::MAX bytes, so if the computed offset
stays in bounds of the allocation, it is guaranteed to satisfy the first requirement.
This implies, for instance, that vec.as_ptr().add(vec.len()) (for vec: Vec<T>) is always
safe.
§Examples
use non_null_const::NonNullConst;
let s = [1, 2, 3];
let ptr: NonNullConst<u32> = NonNullConst::new(s.as_ptr()).unwrap();
unsafe {
println!("{}", ptr.offset(1).read());
println!("{}", ptr.offset(2).read());
}Sourcepub const unsafe fn byte_offset(self, count: isize) -> Self
pub const unsafe fn byte_offset(self, count: isize) -> Self
Calculates the offset from a pointer in bytes.
count is in units of bytes.
This is purely a convenience for casting to a u8 pointer and
using offset on it. See that method for documentation
and safety requirements.
For non-Sized pointees this operation changes only the data pointer,
leaving the metadata untouched.
Sourcepub const unsafe fn add(self, count: usize) -> Selfwhere
T: Sized,
pub const unsafe fn add(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., a count of 3 represents a pointer
offset of 3 * 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::MAX bytes, so if the computed offset
stays in bounds of the allocation, it is guaranteed to satisfy the first requirement.
This implies, for instance, that vec.as_ptr().add(vec.len()) (for vec: Vec<T>) is always
safe.
§Examples
use non_null_const::NonNullConst;
let s: &str = "123";
let ptr: NonNullConst<u8> = NonNullConst::new(s.as_ptr().cast()).unwrap();
unsafe {
println!("{}", ptr.add(1).read() as char);
println!("{}", ptr.add(2).read() as char);
}Sourcepub const unsafe fn byte_add(self, count: usize) -> Self
pub const unsafe fn byte_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 a u8 pointer and
using add on it. See that method for documentation
and safety requirements.
For non-Sized pointees this operation changes only the data pointer,
leaving the metadata untouched.
Sourcepub const unsafe fn sub(self, count: usize) -> Selfwhere
T: Sized,
pub const unsafe fn sub(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., a count of 3 represents a pointer
offset of 3 * 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::MAX bytes, so if the computed offset
stays in bounds of the allocation, it is guaranteed to satisfy the first requirement.
This implies, for instance, that vec.as_ptr().add(vec.len()) (for vec: Vec<T>) is always
safe.
§Examples
use non_null_const::NonNullConst;
let s: &str = "123";
unsafe {
let end: NonNullConst<u8> = NonNullConst::new(s.as_ptr().cast()).unwrap().add(3);
println!("{}", end.sub(1).read() as char);
println!("{}", end.sub(2).read() as char);
}Sourcepub const unsafe fn byte_sub(self, count: usize) -> Self
pub const unsafe fn byte_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 a u8 pointer and
using sub on it. See that method for documentation
and safety requirements.
For non-Sized pointees this operation changes only the data pointer,
leaving the metadata untouched.
Sourcepub const unsafe fn offset_from(self, origin: NonNullConst<T>) -> isizewhere
T: Sized,
pub const unsafe fn offset_from(self, origin: NonNullConst<T>) -> isizewhere
T: Sized,
Calculates the distance between two pointers within the same allocation. The returned value is in
units of T: the distance in bytes divided by size_of::<T>().
This is equivalent to (self as isize - origin as isize) / (size_of::<T>() as isize),
except that it has a lot more opportunities for UB, in exchange for the compiler
better understanding what you are doing.
The primary motivation of this method is for computing the len of an array/slice
of T 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 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
than isize::MAX bytes.
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 T is a Zero-Sized Type (“ZST”).
§Examples
Basic usage:
use non_null_const::NonNullConst;
let a = [0; 5];
let ptr1: NonNullConst<u32> = NonNullConst::from(&a[1]);
let ptr2: NonNullConst<u32> = NonNullConst::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:
use non_null_const::NonNullConst;
let ptr1 = NonNullConst::new(Box::into_raw(Box::new(0u8))).unwrap();
let ptr2 = NonNullConst::new(Box::into_raw(Box::new(1u8))).unwrap();
let diff = (ptr2.addr().get() as isize).wrapping_sub(ptr1.addr().get() as isize);
// Make ptr2_other an "alias" of ptr2.add(1), but derived from ptr1.
let diff_plus_1 = diff.wrapping_add(1);
let ptr2_other = NonNullConst::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!
let one = unsafe { ptr2_other.offset_from(ptr2) }; // Undefined Behavior! ⚠️Sourcepub const unsafe fn byte_offset_from<U: ?Sized>(
self,
origin: NonNullConst<U>,
) -> isize
pub const unsafe fn byte_offset_from<U: ?Sized>( self, origin: NonNullConst<U>, ) -> isize
Calculates 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 u8 pointer and
using offset_from on it. See that method for
documentation and safety requirements.
For non-Sized pointees this operation considers only the data pointers,
ignoring the metadata.
Sourcepub const unsafe fn offset_from_unsigned(
self,
subtracted: NonNullConst<T>,
) -> usizewhere
T: Sized,
pub const unsafe fn offset_from_unsigned(
self,
subtracted: NonNullConst<T>,
) -> usizewhere
T: Sized,
Calculates the distance between two pointers within the same allocation, where it’s known that
self is equal to or greater than origin. The returned value is in
units of T: the distance in bytes is divided by size_of::<T>().
This computes the same value that offset_from
would compute, but with the added precondition that the offset is
guaranteed to be non-negative. This method is equivalent to
usize::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 count that was passed
to add (or, with the parameters in the other order,
to sub). The following are all equivalent, assuming
that their safety preconditions are met:
ptr.offset_from_unsigned(origin) == count
origin.add(count) == ptr
ptr.sub(count) == origin§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 represent
a larger offset, it’s still not permitted to pass pointers which differ
by more than isize::MAX bytes. As such, the result of this method will
always be less than or equal to isize::MAX as usize.
§Panics
This function panics if T is a Zero-Sized Type (“ZST”).
§Examples
use non_null_const::NonNullConst;
let a = [0; 5];
let ptr1: NonNullConst<u32> = NonNullConst::from(&a[1]);
let ptr2: NonNullConst<u32> = NonNullConst::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)Sourcepub const unsafe fn byte_offset_from_unsigned<U: ?Sized>(
self,
origin: NonNullConst<U>,
) -> usize
pub const unsafe fn byte_offset_from_unsigned<U: ?Sized>( self, origin: NonNullConst<U>, ) -> usize
Calculates the distance between two pointers within the same allocation, where it’s known that
self is equal to or greater than origin. The returned value is in
units of bytes.
This is purely a convenience for casting to a u8 pointer and
using offset_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.
Sourcepub const unsafe fn read(self) -> Twhere
T: Sized,
pub const unsafe fn read(self) -> Twhere
T: Sized,
Reads the value from self without moving it. This leaves the
memory in self unchanged.
See ptr::read for safety concerns and examples.
Sourcepub unsafe fn read_volatile(self) -> Twhere
T: Sized,
pub unsafe fn read_volatile(self) -> Twhere
T: Sized,
Performs a volatile read of the value from self without moving it. This
leaves the memory in self unchanged.
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_volatile for safety concerns and examples.
Sourcepub const unsafe fn read_unaligned(self) -> Twhere
T: Sized,
pub const unsafe fn read_unaligned(self) -> Twhere
T: Sized,
Reads the value from self without moving it. This leaves the
memory in self unchanged.
Unlike read, the pointer may be unaligned.
See ptr::read_unaligned for safety concerns and examples.
Sourcepub const unsafe fn copy_to(self, dest: NonNullConst<T>, count: usize)where
T: Sized,
pub const unsafe fn copy_to(self, dest: NonNullConst<T>, count: usize)where
T: Sized,
Sourcepub const unsafe fn copy_to_nonoverlapping(
self,
dest: NonNullConst<T>,
count: usize,
)where
T: Sized,
pub const unsafe fn copy_to_nonoverlapping(
self,
dest: NonNullConst<T>,
count: usize,
)where
T: Sized,
Copies count * size_of::<T>() bytes from self to dest. The source
and destination may not overlap.
NOTE: this has the same argument order as ptr::copy_nonoverlapping.
See ptr::copy_nonoverlapping for safety concerns and examples.
Sourcepub fn align_offset(self, align: usize) -> usizewhere
T: Sized,
pub fn align_offset(self, align: usize) -> usizewhere
T: Sized,
Computes the offset that needs to be applied to the pointer in order to make it aligned to
align.
If it is not possible to align the pointer, the implementation returns
usize::MAX.
The offset is expressed in number of T elements, 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::MAX in 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 align is not a power-of-two.
§Examples
Accessing adjacent u8 as u16
use non_null_const::NonNullConst;
let x = [5_u8, 6, 7, 8, 9];
let ptr = NonNullConst::new(x.as_ptr() as *const u8).unwrap();
let offset = ptr.align_offset(align_of::<u16>());
if offset < x.len() - 1 {
let u16_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
}Sourcepub fn is_aligned(self) -> boolwhere
T: Sized,
pub fn is_aligned(self) -> boolwhere
T: Sized,
Returns whether the pointer is properly aligned for T.
§Examples
use non_null_const::NonNullConst;
// On some platforms, the alignment of i32 is less than 4.
#[repr(align(4))]
struct AlignedI32(i32);
let data = AlignedI32(42);
let ptr = NonNullConst::<AlignedI32>::from(&data);
assert!(ptr.is_aligned());
assert!(!NonNullConst::new(ptr.as_ptr().wrapping_byte_add(1)).unwrap().is_aligned());Sourcepub fn is_aligned_to(self, align: usize) -> bool
Available on crate feature pointer_is_aligned_to only.
pub fn is_aligned_to(self, align: usize) -> bool
pointer_is_aligned_to only.Returns whether the pointer is aligned to align.
For non-Sized pointees this operation considers only the data pointer,
ignoring the metadata.
§Panics
The function panics if align 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))]
struct AlignedI32(i32);
let data = AlignedI32(42);
let ptr = &data as *const AlignedI32;
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> NonNullConst<T>
impl<T> NonNullConst<T>
Sourcepub const fn cast_uninit(self) -> NonNullConst<MaybeUninit<T>>
Available on crate feature cast_maybe_uninit only.
pub const fn cast_uninit(self) -> NonNullConst<MaybeUninit<T>>
cast_maybe_uninit only.Casts from a type to its maybe-uninitialized version.
Source§impl<T> NonNullConst<MaybeUninit<T>>
impl<T> NonNullConst<MaybeUninit<T>>
Sourcepub const fn cast_init(self) -> NonNullConst<T>
Available on crate feature cast_maybe_uninit only.
pub const fn cast_init(self) -> NonNullConst<T>
cast_maybe_uninit only.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.
Source§impl<T> NonNullConst<[T]>
impl<T> NonNullConst<[T]>
Sourcepub const fn slice_from_raw_parts(data: NonNullConst<T>, len: usize) -> Self
pub const fn slice_from_raw_parts(data: NonNullConst<T>, len: usize) -> Self
Creates a non-null raw slice from a thin pointer and a length.
The len argument 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_parts for slice safety requirements.
§Examples
use non_null_const::NonNullConst;
// create a slice pointer when starting out with a pointer to the first element
let x = [5, 6, 7];
let nonnullconst_pointer = NonNullConst::new(x.as_ptr()).unwrap();
let slice = NonNullConst::slice_from_raw_parts(nonnullconst_pointer, 3);
assert_eq!(unsafe { slice.as_ref()[2] }, 7);(Note that this example artificially demonstrates a use of this method,
but let slice = NonNullConst::from(&x[..]); would be a better way to write code like this.)
Sourcepub const fn len(self) -> usize
pub const fn len(self) -> usize
Returns 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 non_null_const::NonNullConst;
let slice: NonNullConst<[i8]> = NonNullConst::slice_from_raw_parts(NonNullConst::dangling(), 3);
assert_eq!(slice.len(), 3);Sourcepub const fn is_empty(self) -> bool
pub const fn is_empty(self) -> bool
Returns true if the non-null raw slice has a length of 0.
§Examples
use non_null_const::NonNullConst;
let slice: NonNullConst<[i8]> = NonNullConst::slice_from_raw_parts(NonNullConst::dangling(), 3);
assert!(!slice.is_empty());Sourcepub const fn as_non_null_ptr(self) -> NonNullConst<T>
Available on crate feature slice_ptr_get only.
pub const fn as_non_null_ptr(self) -> NonNullConst<T>
slice_ptr_get only.Returns a non-null pointer to the slice’s buffer.
§Examples
#![feature(slice_ptr_get)]
use non_null_const::NonNullConst;
let slice: NonNullConst<[i8]> = NonNullConst::slice_from_raw_parts(NonNullConst::dangling(), 3);
assert_eq!(slice.as_non_null_ptr(), NonNullConst::<i8>::dangling());Sourcepub const unsafe fn as_uninit_slice<'a>(self) -> &'a [MaybeUninit<T>]
Available on crate feature ptr_as_uninit only.
pub const unsafe fn as_uninit_slice<'a>(self) -> &'a [MaybeUninit<T>]
ptr_as_uninit only.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.
§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 usingNonNullConst::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.
This applies even if the result of this method is unused!
See also slice::from_raw_parts.
Sourcepub const unsafe fn get_unchecked<I>(self, index: I) -> NonNullConst<I::Output>where
I: SliceIndex<[T]>,
Available on crate feature const_index only.
pub const unsafe fn get_unchecked<I>(self, index: I) -> NonNullConst<I::Output>where
I: SliceIndex<[T]>,
const_index only.Returns a raw pointer to an element or subslice, without doing bounds checking.
Calling this method with an out-of-bounds index or when self is not dereferenceable
is undefined behavior even if the resulting pointer is not used.
§Examples
#![feature(slice_ptr_get)]
use non_null_const::NonNullConst;
let x = &[1, 2, 4];
let x = NonNullConst::slice_from_raw_parts(NonNullConst::new(x.as_ptr()).unwrap(), x.len());
unsafe {
assert_eq!(x.get_unchecked(1).as_ptr(), x.as_non_null_ptr().as_ptr().add(1));
}Trait Implementations§
Source§impl<T: PointeeSized> Clone for NonNullConst<T>
impl<T: PointeeSized> Clone for NonNullConst<T>
Source§impl<T: PointeeSized> Debug for NonNullConst<T>
impl<T: PointeeSized> Debug for NonNullConst<T>
Source§impl<T: PointeeSized> From<&T> for NonNullConst<T>
impl<T: PointeeSized> From<&T> for NonNullConst<T>
Source§impl<T: PointeeSized> From<&mut T> for NonNullConst<T>
impl<T: PointeeSized> From<&mut T> for NonNullConst<T>
Source§impl<T: PointeeSized> From<NonNull<T>> for NonNullConst<T>
impl<T: PointeeSized> From<NonNull<T>> for NonNullConst<T>
Source§fn from(ptr: NonNullMut<T>) -> Self
fn from(ptr: NonNullMut<T>) -> Self
Source§impl<T: PointeeSized> From<NonNullConst<T>> for NonNullMut<T>
impl<T: PointeeSized> From<NonNullConst<T>> for NonNullMut<T>
Source§fn from(ptr: NonNullConst<T>) -> Self
fn from(ptr: NonNullConst<T>) -> Self
Source§impl<T: PointeeSized> Hash for NonNullConst<T>
impl<T: PointeeSized> Hash for NonNullConst<T>
Source§impl<T: PointeeSized> Ord for NonNullConst<T>
impl<T: PointeeSized> Ord for NonNullConst<T>
Source§impl<T: PointeeSized> PartialEq for NonNullConst<T>
impl<T: PointeeSized> PartialEq for NonNullConst<T>
Source§impl<T: PointeeSized> PartialOrd for NonNullConst<T>
impl<T: PointeeSized> PartialOrd for NonNullConst<T>
Source§impl<T: PointeeSized> Pointer for NonNullConst<T>
impl<T: PointeeSized> Pointer for NonNullConst<T>
impl<T, U: PointeeSized> CoerceUnsized<NonNullConst<U>> for NonNullConst<T>where
T: Unsize<U> + PointeeSized,
coerce_unsized only.impl<T: PointeeSized> Copy for NonNullConst<T>
impl<T, U: PointeeSized> DispatchFromDyn<NonNullConst<U>> for NonNullConst<T>where
T: Unsize<U> + PointeeSized,
dispatch_from_dyn only.impl<T: PointeeSized> Eq for NonNullConst<T>
impl<T: PointeeSized> PinCoerceUnsized for NonNullConst<T>
impl<T: PointeeSized> !Send for NonNullConst<T>
NonNullConst pointers are not Send because the data they reference may be aliased.
impl<T: PointeeSized> !Sync for NonNullConst<T>
NonNullConst pointers are not Sync because the data they reference may be aliased.