Macro impl_enum_try_from

Source
macro_rules! impl_enum_try_from {
    ($(#[$meta:meta])* $vis:vis enum $name:ident {
        $($(#[$vmeta:meta])* $vname:ident $(= $val:expr)?,)*
    }, $type:ty, $err_ty:ty, $err:expr) => { ... };
}
Expand description

Macro which implements the TryFrom trait for the given enum and type.

The first argument is the enum to implement the trait for.

The second argument is the type to implement the trait for. Usually i32 or u32 would be the best choice. However, if you are providing any concrete primitive type in repr (i.e. #[repr(u8)]), then you should use the same type.

The third argument is the type of the error which should be returned if the value provided to try_from is not a valid variant of the enum.

The fourth argument is the concrete error value which should be returned if the value provided to try_from is not a valid variant of the enum.

ยงExamples

impl_enum_try_from!(
    #[repr(u16)]
    #[derive(PartialEq, Eq, Debug)]
    enum MyEnum {
       Foo = 0,
       Bar = 1,
       Baz = 2,
    },
    u16,
    (),
    ()
);

assert_eq!(MyEnum::try_from(0), Ok(MyEnum::Foo));
assert_eq!(MyEnum::try_from(1), Ok(MyEnum::Bar));
assert_eq!(MyEnum::try_from(2), Ok(MyEnum::Baz));
assert_eq!(MyEnum::try_from(3), Err(()));
use thiserror::Error;

#[derive(Error, Debug, PartialEq, Eq)]
pub enum MyError {
   #[error("invalid value")]
   InvalidValue,
}

impl_enum_try_from!(
    #[repr(u16)]
    #[derive(PartialEq, Eq, Debug)]
    enum MyEnum {
        Foo = 0,
        Bar = 1,
        Baz = 2,
    },
    u16,
    MyError,
    MyError::InvalidValue
);