#memory-layout #control #explicit #options #variant #pattern #niches

controlled-option

Custom Option type with explicit control over niches and memory layout

5 releases (3 breaking)

0.4.1 Aug 24, 2021
0.4.0 Aug 24, 2021
0.3.0 Aug 24, 2021
0.2.0 Aug 24, 2021
0.1.0 Aug 23, 2021

#13 in #explicit

Download history 185/week @ 2024-07-25 196/week @ 2024-08-01 237/week @ 2024-08-08 206/week @ 2024-08-15 165/week @ 2024-08-22 200/week @ 2024-08-29 131/week @ 2024-09-05 892/week @ 2024-09-12 660/week @ 2024-09-19 204/week @ 2024-09-26 153/week @ 2024-10-03 230/week @ 2024-10-10 224/week @ 2024-10-17 243/week @ 2024-10-24 274/week @ 2024-10-31 92/week @ 2024-11-07

854 downloads per month
Used in 9 crates (2 directly)

MIT/Apache

19KB
457 lines

controlled-option

This crate provides a custom implementation of the standard Option, where you have explicit control over how the None variant is laid out in memory.


lib.rs:

This crate provides a replacement for the standard Option type where you have full control over how the None and Some variants are represented in memory.

Normally, you don't have to think about this. The standard Option is a perfectly normal enum, and the compiler takes care of determining the most efficient in-memory representation. In particular, the compiler knows that certain types have niches — in-memory bit patterns that do not represent valid values of the type. If a type has a niche, then the compiler can use that bit pattern to represent the None variant. This works automatically for most of the types you might care about: in particular, for references and the various NonZero types in std::num.

However, sometimes a type has multiple possible niches, and you need control over which one the compiler chooses to use. Or, you might have defined a type such that the compiler cannot see that it has a niche available to use. In this case, you can use the Niche and ControlledOption types from this crate to take full control over how the None and Some variants are laid out in memory.

Dependencies

~1.5MB
~38K SLoC