Explores how to create memory-efficient integer wrapper types in Rust using type niches. Starting with a DNA sequence position type (Pos) that only uses the u31 range, the post covers three approaches: a naive u32 wrapper (wastes 4 bytes in Option), the NonZero bias trick on stable Rust (stores value+1 to expose a niche, making Option<Pos> 4 bytes), and the experimental nightly pattern_type! macro that lets you declare a valid range directly (e.g., i32 is 0..=i32::MAX). The nightly approach is cleaner conceptually but requires unsafe transmute for now. The post also notes that the older rustc_layout_scalar_valid_range_start attributes are being replaced by pattern types.

5m read timeFrom deterministic.space
Post cover image
Table of contents
Simple position typeType nichesOn stable: the NonZero bias trickOn nightly: declaring the valid range directlyOn nightly: Pattern typesConclusion

Sort: