Macro fake_enum::fake_enum[][src]

macro_rules! fake_enum {
    {#[repr($t:ty)] $(#[$meta:meta])* $vis:vis enum $name:ident {
        $($item:ident = $expr:literal),*$(,)?
    }} => { ... };
    {#[repr($t:ty)] $(#[$meta:meta])* $vis:vis enum struct $name:ident {
        $($item:ident = $expr:literal),*$(,)?
    }} => { ... };
}

Constructs a "Fake Enum", that acts like a rust enum with unit variants, but can accept invalid (undefined) variants without undefined behaviour. The enum derives Copy, Clone, Eq, and PartialEq. Additionally, it implements Debug, where all valid variants are printed as defined, and invalid variants are formatted as name(value). Any other derives can be added following the repr. Two forms of this macro is provided. enum name declares an enum named "name". All the variants are declared with the same visibility as the type in the enclosing module. enum struct name declares an scoped enum named "name". The variants are declared pub within "name".

In Both cases, it is valid to transmute the declared type to and from the repr type (note that no from implementation is provided)

use fake_enum::fake_enum;
fake_enum!{
   #[repr(u8)] pub enum Foo{
       Bar = 0,
       Baz = 1,
   }  
};
let x = Bar;
assert_eq!(format!("{:?}",x),"Bar");
assert_eq!(unsafe{std::mem::transmute::<_,Foo>(1u8)},Baz)