from-repr-enum-derive

Crates.iofrom-repr-enum-derive
lib.rsfrom-repr-enum-derive
version0.1.2
sourcesrc
created_at2018-03-16 05:17:56.48029
updated_at2018-03-18 00:04:33.189505
descriptionDerive From for an enum with a repr
homepage
repositoryhttps://github.com/tejom/From-repr-enum-derive
max_upload_size
id55902
size5,784
Matthew Tejo (tejom)

documentation

https://github.com/tejom/From-repr-enum-derive

README

from-repr-enum-derive

A crate to derive from for an Enum with a repr defined

Currently a #[repr()] is needed for the derive to work

Example:


#[macro_use]
extern crate from_repr_enum_derive;


#[repr(u8)]
#[derive(FromReprEnum,Debug,PartialEq)]
enum Foo {
    X = 1,
    Y = 2,
    Unknown = 255,
}

fn main() {
    let z = Foo::from(1);
    assert_eq!(Foo::X, z);
}

The match block that is created needs a default enum variant. The crate has a default of Unknown

Custom default variant

You can define your own with another attribute #[ReprEnumDefault = ""]

#[repr(u8)]
#[derive(FromReprEnum, Debug, PartialEq)]
#[ReprEnumDefault = "NotFound"]
enum Bar {
    X = 1,
    Y = 2,
    NotFound = 255,
}

fn main() {
    let x = Bar::from(1);
    assert_eq!(Bar::X, x);

    let u = Bar::from(99);
    assert_eq!(Bar::NotFound, u);
}

Notes

The match block generated tries to use the Enum name with a wildcard. If the variants aren't found by the compiler you might need to add use path::to::Enum::*

Commit count: 17

cargo fmt