`enum_variant_type` -- proc macro derive to generate structs from enums and convert between them

Hiya, have just published enum_variant_type, a proc macro derive to generate structs from enum variants.

This is a poor-man's implementation while https://github.com/rust-lang/rfcs/pull/2593 isn't available.

Links:

Examples:

use enum_variant_type::EnumVariantType;

#[derive(Debug, EnumVariantType, PartialEq)]
pub enum MyEnum {
    /// Unit variant.
    #[evt_attrs(derive(Clone, Copy, Debug, PartialEq))]
    Unit,
    /// Tuple variant.
    #[evt_attrs(derive(Debug, PartialEq))]
    Tuple(u32, u64),
    /// Struct variant.
    #[evt_attrs(derive(Debug))]
    Struct {
        field_0: u32,
        field_1: u64,
    },
}

// Now you can do the following:
use std::convert::TryFrom;
let unit: Unit = Unit::try_from(MyEnum::Unit).unwrap();
let tuple: Tuple = Tuple::try_from(MyEnum::Tuple(12, 34)).unwrap();
let named: Struct = Struct::try_from(MyEnum::Struct { field_0: 12, field_1: 34 }).unwrap();

let enum_unit = MyEnum::from(unit);
let enum_tuple = MyEnum::from(tuple);
let enum_struct = MyEnum::from(named);

// If the enum variant doesn't match the variant type, then the original variant is returned in
// the `Result`'s `Err` variant.
assert_eq!(Err(MyEnum::Unit), Tuple::try_from(MyEnum::Unit));

Notes:

Enums with type parameters and lifetimes are rudimentarily handled, so may not work for all use cases. Please feel free to contribute :bowing_man:.

6 Likes