#[derive(EnumRepr)]
{
// Attributes available to this derive:
#[enum_repr]
}
Expand description
Automatically implements [std::convert::From] for repr from enum.
And implements [std::convert::TryFrom] for enum from repr.
or implements [std::convert::From] for enum from repr.
§Where to use:
- Managing Type
- Easy to understand constants
§Note:
- require
#[repr(u8)]or#[repr(u16)]or … - default is require explicit
- #[enum_repr(default)] is special attribute on variant
§Enum Attribute:
- serde: automatically implements [
serde::Serialize] and [serde::Deserialize] - implicit: make it less explicit
§Variant Attribute:
- default: Sets the fallback value if none of the others apply.
this attribute is required to be used only once or not at all
if this attribute is not used, it will be impl [
std::convert::TryFrom] used, it will be impl [std::convert::From]
§Examples
§Normal
use more_convert::EnumRepr;
#[derive(EnumRepr, Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum Test {
Zero = 0,
Three = 3,
Four = 4,
}
assert_eq!(0u8, Test::Zero.into());
assert_eq!(3u8, Test::Three.into());
assert_eq!(4u8, Test::Four.into());
assert_eq!(0u8.try_into(), Ok(Test::Zero));
assert_eq!(3u8.try_into(), Ok(Test::Three));
assert_eq!(4u8.try_into(), Ok(Test::Four));
assert_eq!(TryInto::<Test>::try_into(1u8).unwrap_err(), String::from("invalid Test: 1"));§serde
use more_convert::EnumRepr;
#[derive(EnumRepr, Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
#[enum_repr(serde)]
pub enum Test {
Zero = 0,
Three = 3,
Four = 4,
}
assert_eq!(serde_json::to_string(&Test::Zero).unwrap(), "0");
assert_eq!(serde_json::to_string(&Test::Three).unwrap(), "3");
assert_eq!(serde_json::to_string(&Test::Four).unwrap(), "4");
assert_eq!(serde_json::from_str::<Test>("0").unwrap(), Test::Zero);
assert_eq!(serde_json::from_str::<Test>("3").unwrap(), Test::Three);
assert_eq!(serde_json::from_str::<Test>("4").unwrap(), Test::Four);
assert_eq!(serde_json::from_str::<Test>("1").unwrap_err().to_string(), String::from("invalid Test: 1"));§implicit
use more_convert::EnumRepr;
#[derive(EnumRepr, Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
#[enum_repr(implicit)]
pub enum Test {
Zero,
Three = 3,
Four,
}
assert_eq!(0u8, Test::Zero.into());
assert_eq!(3u8, Test::Three.into());
assert_eq!(4u8, Test::Four.into());
assert_eq!(0u8.try_into(), Ok(Test::Zero));
assert_eq!(3u8.try_into(), Ok(Test::Three));
assert_eq!(4u8.try_into(), Ok(Test::Four));
assert_eq!(TryInto::<Test>::try_into(1u8).unwrap_err(), String::from("invalid Test: 1"));§default
use more_convert::EnumRepr;
#[derive(EnumRepr, Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum Test {
Zero = 0,
One = 1,
#[enum_repr(default)]
Two = 2,
}
assert_eq!(0u8, Test::Zero.into());
assert_eq!(1u8, Test::One.into());
assert_eq!(2u8, Test::Two.into());
// Invalid values return the default variant
assert_eq!(Test::Two, 255u8.into());