Option of Enum w/o extra size

The text at std::option - Rust says:

Rust guarantees to optimize the following types T such that Option<T> has the same size as T :

Missing from this is the possibility of having an enum E { ... } such that Option<E> would have the same size as E. In the vast majority of cases, some values of the discriminant field of an enum are not utilized and could be co-opted by Option to indicate the lack of a value.

Has such an optimization ever been considered?

Such an optimization is not only considered but also already applied. However it is not guaranteed in a way that unsafe code (like mem::transmute) can rely on it or you can be 100% certain (as opposed to only 99.99% certain) that it will always stay optimized this way in the future.

enum Foo { First, Second, Third }

enum Bar { SomeBar(u8), NoneBar, OtherNoneBar }

use std::mem::size_of;
fn main() {
    dbg!(size_of::<Foo>());
    dbg!(size_of::<Option<Foo>>());
    dbg!(size_of::<Bar>());
    dbg!(size_of::<Option<Bar>>());
    
    eprintln!("and even:");
    dbg!(size_of::<Foo>());
    dbg!(size_of::<Option<Option<Option<Option<Foo>>>>>());
    
    dbg!(size_of::<Bar>());
    dbg!(size_of::<Option<Option<Option<Option<Bar>>>>>());
}

(playground)

     Running `target/debug/playground`
[src/main.rs:7] size_of::<Foo>() = 1
[src/main.rs:8] size_of::<Option<Foo>>() = 1
[src/main.rs:9] size_of::<Bar>() = 2
[src/main.rs:10] size_of::<Option<Bar>>() = 2
and even:
[src/main.rs:13] size_of::<Foo>() = 1
[src/main.rs:14] size_of::<Option<Option<Option<Option<Foo>>>>>() = 1
[src/main.rs:16] size_of::<Bar>() = 2
[src/main.rs:17] size_of::<Option<Option<Option<Option<Bar>>>>>() = 2
6 Likes