Skip to content

attribute to reserve None value on Option<enum> #59788

Open
@npmccallum

Description

@npmccallum

For example:

#[repr(u8)]
#[reserved(0)]
enum Foo {
    Bar = 17,
    Baz = 32,
}

fn main() {
    assert_eq!(std::mem::size_of::<Option<Foo>>(), std::mem::size_of::<Foo>());

    let foo: Option<Foo> = None;
    let byte: u8 = std::mem::transmute(foo);
    println!("{}", byte); // Prints 0
}

This would be incredibly useful in FFI situations. Often there is an enum of values for which a particular value (usually zero) is reserved to represent "none" or "invalid" or "empty". This would make translation into idiomatic Rust both easy and safe.

Rust already optimizes Option<enum> this way. However, it always selects the highest used discriminant + 1 to represent None (this is likely undefined behavior). Having control over this value simply makes the behavior defined. It would also mean that the compiler could warn if there was any attempt to use the reserved value in an actual enumeration item.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-FFIArea: Foreign function interface (FFI)A-enumArea: Enums (discriminated unions, or more generally ADTs (algebraic data types))C-feature-requestCategory: A feature request, i.e: not implemented / a PR.T-langRelevant to the language teamneeds-rfcThis change is large or controversial enough that it should have an RFC accepted before doing it.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions