#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

#865 in Text processing

Download history 132/week @ 2023-12-04 57/week @ 2023-12-11 118/week @ 2023-12-18 6/week @ 2023-12-25 42/week @ 2024-01-01 67/week @ 2024-01-08 130/week @ 2024-01-15 92/week @ 2024-01-22 161/week @ 2024-01-29 155/week @ 2024-02-05 88/week @ 2024-02-12 106/week @ 2024-02-19 113/week @ 2024-02-26 218/week @ 2024-03-04 150/week @ 2024-03-11 92/week @ 2024-03-18

576 downloads per month
Used in 7 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
~33K SLoC