#enums #integer-value #open #integer #newtype #generate

no-std bin+lib open-enum

An attribute for generating "open" fieldless enums, those that accept any integer value, by using a newtype struct and associated constants

8 releases (4 breaking)

0.5.2 Jun 17, 2024
0.5.1 May 29, 2024
0.5.0 Feb 15, 2024
0.4.1 Nov 18, 2023
0.1.0 Sep 2, 2022

#232 in Rust patterns

Download history 1220/week @ 2024-07-16 1102/week @ 2024-07-23 1362/week @ 2024-07-30 1641/week @ 2024-08-06 1975/week @ 2024-08-13 2173/week @ 2024-08-20 3124/week @ 2024-08-27 2688/week @ 2024-09-03 2257/week @ 2024-09-10 2573/week @ 2024-09-17 3257/week @ 2024-09-24 2779/week @ 2024-10-01 4967/week @ 2024-10-08 4538/week @ 2024-10-15 3414/week @ 2024-10-22 3814/week @ 2024-10-29

17,249 downloads per month
Used in 3 crates

Apache-2.0

21KB
106 lines

open-enum

Rust enums are closed, meaning that the integer value distinguishing an enum, its discriminant, must be one of the variants listed. If the integer value isn't one of those discriminants, it is considered immediate undefined behavior. This is true for enums with and without fields. This can make working with enums troublesome in high performance code that can't afford premature runtime checks. It can also introduce Undefined Behavior at unexpected times if the author is unfamiliar with the rules of writing unsafe Rust.

In constrast, C++ scoped enumerations are open, meaning that the enum is a strongly-typed integer that could hold any value, though with a scoped set of well-known values. open-enum lets you have this in Rust. It turns this enum declaration:

#[open_enum]
enum Color {
    Red,
    Green,
    Blue,
    Orange,
    Black,
}

into a tuple struct with associated constants:

#[derive(PartialEq, Eq)]  // In order to work in `match`.
struct Color(pub u8);  // Automatic integer type, can be specified.

impl Color {
    pub const Red: Self = Color(0);
    pub const Green: Self = Color(1);
    pub const Blue: Self = Color(2);
    pub const Orange: Self = Color(3);
    pub const Black: Self = Color(4);
}

Contributing

See CONTRIBUTING.md for details.

License

Apache 2.0; see LICENSE for details.

Disclaimer

This project is not an official Google project. It is not supported by Google and Google specifically disclaims all warranties as to its quality, merchantability, or fitness for a particular purpose.

Dependencies

~220–670KB
~16K SLoC