Skip to main content

NonZeroUsize

Type Alias NonZeroUsize 

1.28.0 · Source
pub type NonZeroUsize = NonZero<usize>;
Expand description

A usize that is known not to equal zero.

This enables some memory layout optimization. For example, Option<NonZeroUsize> is the same size as usize:

assert_eq!(size_of::<Option<core::num::NonZeroUsize>>(), size_of::<usize>());

§Layout

NonZeroUsize is guaranteed to have the same layout and bit validity as usize with the exception that 0 is not a valid instance. Option<NonZeroUsize> is guaranteed to be compatible with usize, including in FFI.

Thanks to the null pointer optimization, NonZeroUsize and Option<NonZeroUsize> are guaranteed to have the same size and alignment:

use std::num::NonZeroUsize;

assert_eq!(size_of::<NonZeroUsize>(), size_of::<Option<NonZeroUsize>>());
assert_eq!(align_of::<NonZeroUsize>(), align_of::<Option<NonZeroUsize>>());

§Compile-time creation

Since both Option::unwrap() and Option::expect() are const, it is possible to define a new NonZeroUsize at compile time via:

use std::num::NonZeroUsize;

const TEN: NonZeroUsize = NonZeroUsize::new(10).expect("ten is non-zero");

Aliased Type§

#[repr(transparent)]
pub struct NonZeroUsize(/* private fields */);

Trait Implementations§

Source§

impl<'de> Deserialize<'de> for NonZeroUsize

Source§

fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Serialize for NonZeroUsize

Source§

fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,

Serialize this value into the given Serde serializer. Read more