pub struct NonZero<T: ZeroablePrimitive>(/* private fields */);Expand description
A value that is known not to equal zero.
This enables some memory layout optimization.
For example, Option<NonZero<u32>> is the same size as u32:
§Layout
NonZero<T> is guaranteed to have the same layout and bit validity as T
with the exception that the all-zero bit pattern is invalid.
Option<NonZero<T>> is guaranteed to be compatible with T, including in
FFI.
Thanks to the null pointer optimization, NonZero<T> and
Option<NonZero<T>> are guaranteed to have the same size and alignment:
use std::num::NonZero;
assert_eq!(size_of::<NonZero<u32>>(), size_of::<Option<NonZero<u32>>>());
assert_eq!(align_of::<NonZero<u32>>(), align_of::<Option<NonZero<u32>>>());§Note on generic usage
NonZero<T> can only be used with some standard library primitive types
(such as u8, i32, and etc.). The type parameter T must implement the
internal trait [ZeroablePrimitive], which is currently permanently unstable
and cannot be implemented by users. Therefore, you cannot use NonZero<T>
with your own types, nor can you implement traits for all NonZero<T>,
only for concrete types.
Implementations§
Source§impl<T> NonZero<T>where
T: ZeroablePrimitive,
impl<T> NonZero<T>where
T: ZeroablePrimitive,
1.28.0 (const: 1.47.0) · Sourcepub const fn new(n: T) -> Option<Self>
pub const fn new(n: T) -> Option<Self>
Creates a non-zero if the given value is not zero.
1.28.0 (const: 1.28.0) · Sourcepub const unsafe fn new_unchecked(n: T) -> Self
pub const unsafe fn new_unchecked(n: T) -> Self
Creates a non-zero without checking whether the value is non-zero. This results in undefined behavior if the value is zero.
§Safety
The value must not be zero.