In Rust, why is Option<Option<bool>> one byte while Option<Option<&u64>> takes 16, and how does NonZeroU32 give an AccountId the same saving?
answer
- patterns the payload can never hold
- each Option layer spends one
- a reference has only null
- NonZeroU32 frees zero
basics
~20 sNone goes in a niche, a bit pattern the payload never holds. bool has 254 spares, so nested Options fit one byte; a reference has only null, so a second layer needs a tag. NonZeroU32 frees 0, so Option<AccountId> stays 4 bytes.
solid answer
~40 sThe compiler can drop an enum's tag when a payload has invalid bit patterns, called niches, and store `None` in one of them. A `bool` may only be 0 or 1, so `Option<bool>` and `Option<Option<bool>>` are each 1 byte. A reference must be non-null and null is its only niche, so `Option<&u64>` is 8 bytes but `Option<Option<&u64>>` must add a tag and is 16. A plain `u32` has no invalid pattern, so `Option<u32>` is 8 bytes; `NonZeroU32` makes 0 invalid, so `struct AccountId(NonZeroU32)` gives a 4-byte `Option<AccountId>`, built with `NonZeroU32::new(raw).map(AccountId)`. The bool, nested and newtype sizes are what rustc 1.99.1 does, not a layout promise.
code
rust · 28 linesuse std::mem::size_of;
use std::num::NonZeroU32;
#[derive(Clone, Copy, Debug, PartialEq)]
struct AccountId(NonZeroU32); // 0 can never be a valid id
#[allow(dead_code)] // only its size is inspected
enum HttpStatus { Ok = 200, NotFound = 404 }
fn main() {
// bool uses 2 of its 256 bit patterns; each Option layer takes a spare one.
assert_eq!(size_of::<Option<bool>>(), 1);
assert_eq!(size_of::<Option<Option<bool>>>(), 1);
// A reference has exactly one spare pattern (null), so the second layer needs a tag.
assert_eq!(size_of::<Option<&u64>>(), 8);
assert_eq!(size_of::<Option<Option<&u64>>>(), 16);
// A plain u32 has no spare pattern; NonZeroU32 frees up 0.
assert_eq!(size_of::<Option<u32>>(), 8);
assert_eq!(size_of::<Option<AccountId>>(), 4);
// Unused discriminant values and invalid chars are niches too.
assert_eq!(size_of::<Option<HttpStatus>>(), size_of::<HttpStatus>());
assert_eq!(size_of::<Option<char>>(), 4);
let id = NonZeroU32::new(7).map(AccountId);
assert_eq!(id, Some(AccountId(NonZeroU32::new(7).unwrap())));
assert_eq!(NonZeroU32::new(0), None);
println!("all sizes as expected on this target");
}go deeper
Recall that Option<&T> and Option<Box<T>> are the size of the pointer, because None uses the null pattern.
Explain a niche as an impossible bit pattern, count how many each type has, and show why the second Option layer around a reference needs a tag.
Choose types such as NonZeroU32 so optional ids stay small in large collections, and treat the nested and newtype sizes as observed rustc behaviour.
Decide how far a memory budget for large collections may rest on observed niche sizes, which a compiler upgrade could change, and when a type is redesigned to free a niche.
## What a niche is An enum needs some way to record which variant a value holds. Usually that is a separate **tag**. But if one variant's payload has **bit patterns it can never legally hold**, the compiler can use one of those impossible patterns to mean "the other variant" and drop the tag entirely. Such a spare pattern is called a **niche**, and using it is the **niche optimisation**. The Reference's list of undefined behaviour is what makes patterns impossible: - a `bool` must be 0 or 1; - a `char` must not be a surrogate (`0xD800..=0xDFFF`) and must be at most `char::MAX`; - a reference or `Box` must be non-null; - an enum must hold one of its declared discriminants. Since no valid value can have those patterns, `Option` can claim one for `None`. ## Counting spare patterns Each layer of `Option` needs one spare pattern. Whether nested Options stay small depends on how many the innermost type has left: | Payload `T` (rustc 1.99.1, 64-bit) | Spare patterns used | `Option<T>` | `Option<Option<T>>` | |---|---|---|---| | `bool` (1 byte) | 254 values above 1 | 1 | 1 | | `&u64` (8 bytes) | null only | 8 | 16 | | `u32` | none: every pattern is a valid number | 8 | — | | `NonZeroU32` | zero only | 4 | 8 | | `char` | values above `char::MAX` | 4 | — | | unit-only `HttpStatus` (2 bytes) | unused discriminant values | 2 | — | So `Option<Option<bool>>` is one byte (even a third layer still fits), while `Option<Option<&u64>>` spends the single null niche on the inner `None` and must add a tag for the outer one; the alignment of 8 rounds that to 16 bytes. ## Giving your own type a niche An identifier that can never be zero is the common case: 1. Wrap the integer in a newtype over `std::num::NonZeroU32`: `struct AccountId(NonZeroU32);`. 2. Construct it at the boundary with `NonZeroU32::new(raw)`, which returns `Option<NonZeroU32>`, `None` for 0; `.map(AccountId)` turns that into `Option<AccountId>`. 3. Store `Option<AccountId>` wherever an id may be missing: on rustc 1.99.1 it is 4 bytes, the same as a bare `u32`, where `Option<u32>` is 8. 4. Avoid `NonZeroU32::new_unchecked`: it is an `unsafe fn`, and passing 0 is undefined behaviour. `NonZeroU32` is an alias for `NonZero<u32>`, documented as having the same layout and bit validity as `u32`, except that `0` is not a valid instance. ## Observed, not promised The sizes in the table are what rustc 1.99.1 produces. The default representation promises only a short documented list of `Option` layouts, so these numbers are a memory saving to enjoy, not a layout for transmutes or FFI to rely on; which layouts are guaranteed, and the attributes that make them so, is a topic of its own. ## Where it pays - **Collections of optional ids.** A `Vec<Option<AccountId>>` uses half the memory of a `Vec<Option<u32>>`. - **Optional owned children.** `Option<Box<Node>>` is one pointer, with null as `None`. - **Enums inside enums.** An enum's own tag usually has spare values, so `Option<PaymentEvent>` is the same size as `PaymentEvent` on rustc 1.99.1. - **No unsafe code.** The optimisation is automatic: you choose types that rule out impossible values, and the compiler finds the niche. ## Common misreadings - **`Option<u32>` cannot use 0 for `None`.** `Some(0)` is a valid value and needs its own pattern, so with no impossible pattern left the compiler adds a tag. - **Nesting costs at the layer that runs out.** `Option<Option<bool>>` costs nothing extra because `bool` has many spare patterns; `Option<Option<&u64>>` doubles to 16 bytes because a reference has one. - **Niches come from types, not from values.** A `u32` that your program happens never to set to zero gets no niche; only a type whose invalid pattern is part of its definition, such as `NonZeroU32`, gives the compiler one.
- Why is `Option<Option<NonZeroU32>>` 8 bytes rather than 4?`NonZeroU32` has exactly one invalid pattern, zero, and the inner Option spends it on its `None`. Nothing is left inside the 4 bytes for the outer `None`, so the compiler adds a tag and pads to the 4-byte alignment: 8 bytes.
- How do you build an `AccountId` from a `u32` read off the wire?`NonZeroU32::new(raw)` returns `Option<NonZeroU32>`, `None` for zero, so `NonZeroU32::new(raw).map(AccountId)` yields an `Option<AccountId>` and makes the zero case explicit at the boundary. `NonZeroU32::new_unchecked` is an `unsafe fn`, and calling it with zero is undefined behaviour.
- Does a third layer, `Option<Option<Option<bool>>>`, still fit in one byte?Yes, on rustc 1.99.1 it is 1 byte. A `bool` uses only 2 of the 256 patterns of its byte, and each `Option` layer claims one more of the 254 invalid values for its own `None`, so nesting stays tag-free until those spare values run out.
- Option<T> is always at least one byte bigger than T.
- Every Option around a reference is 8 bytes, however deeply nested.
- Option<u32> is 4 bytes because None is stored as zero.
- Option<Option<bool>> needs a second byte for the outer None.
- Niche optimisation needs an unsafe block or a repr attribute.