2024/02/12
That rust has built-in numeric types named like NonZero* that reserve the bit-pattern of 0 as a niche: see https://doc.rust-lang.org/core/num/index.html.
This is useful since that niche will absorb the cost of wrapping a NonZero int with Option:
use core::num::NonZeroU8;
use std::mem::size_of;
struct Struct<T>{ // has alignment 2, size 4
a: u16,
b: T,
}
fn main() {
println!(" NonZeroU8: {}", size_of::<NonZeroU8>());
println!(" Option<NonZeroU8>: {}", size_of::<Option<NonZeroU8>>());
println!(" Struct<NonZeroU8>: {}", size_of::<Struct<NonZeroU8>>());
println!("Option<Struct<NonZeroU8>: {}", size_of::<Option<Struct<NonZeroU8>>>());
}
# NonZeroU8: 1
# Option<NonZeroU8>: 1
# Struct<NonZeroU8>: 4
# Option<Struct<NonZeroU8>: 4