#[derive(FromStr)]
{
// Attributes available to this derive:
#[enumeration]
}
Expand description
Derives FromStr
for C-like enums.
The generated code will be more efficient than a simple match
statement for most enums. It is
guaranteed to run in O(m)
time (where m
is the length of the input string) rather than the
O(mn)
time (where n
is the number of variants) which would be required by the naive
approach.
§Examples
FromStr
can be derived for C-like enums by deriving enum_utils::FromStr
.
#[derive(Debug, PartialEq, enum_utils::FromStr)]
enum Test {
Alpha,
Beta,
}
assert_eq!("Alpha".parse(), Ok(Test::Alpha));
assert_eq!("Beta".parse(), Ok(Test::Beta));
§Attributes
The implementation can be customized by attributes of the form #[enumeration(...)]
. These
are based on the ones in serde
.
§#[enumeration(skip)]
This attribute causes a single variant of the enum to be ignored when deserializing. Variants which are skipped may have data fields.
#[derive(Debug, PartialEq, enum_utils::FromStr)]
enum Skip {
#[enumeration(skip)]
Alpha(usize),
Beta,
}
assert_eq!("Alpha".parse::<Skip>(), Err(()));
assert_eq!("Beta".parse(), Ok(Skip::Beta));
§#[enumeration(rename = "...")]
This attribute renames a single variant of an enum. This replaces the name of the variant and
overrides rename_all
.
Only one rename
attribute can appear for each enum variant.
#[derive(Debug, PartialEq, enum_utils::FromStr)]
enum Rename {
#[enumeration(rename = "α")]
Alpha,
Beta,
}
assert_eq!("Alpha".parse::<Rename>(), Err(()));
assert_eq!("α".parse(), Ok(Rename::Alpha));
assert_eq!("Beta".parse(), Ok(Rename::Beta));
§#[enumeration(alias = "...")]
This attribute is similar to rename
, but it does not replace the name of the variant.
Unlike rename
, there is no limit to the number of alias
attributes which can be applied.
This allows multiple strings to serialize to the same variant.
#[derive(Debug, PartialEq, enum_utils::FromStr)]
enum Alias {
#[enumeration(alias = "A", alias = "α")]
Alpha,
Beta,
}
assert_eq!("Alpha".parse(), Ok(Alias::Alpha));
assert_eq!("A".parse(), Ok(Alias::Alpha));
assert_eq!("α".parse(), Ok(Alias::Alpha));
assert_eq!("Beta".parse(), Ok(Alias::Beta));
§#[enumeration(rename_all = "...")]
This attribute can be applied to an entire enum, and causes all fields to be renamed according
to the given rename rule. All rename rules defined in serde
are supported.
#[enumeration(rename_all = "snake_case")]
#[derive(Debug, PartialEq, enum_utils::FromStr)]
enum RenameAll {
FooBar,
BarFoo,
}
assert_eq!("foo_bar".parse(), Ok(RenameAll::FooBar));
assert_eq!("bar_foo".parse(), Ok(RenameAll::BarFoo));
§#[enumeration(case_insensitive)]
This attribute can be applied to an entire enum, it causes all variants to be parsed case-insensitively.
#[enumeration(case_insensitive)]
#[derive(Debug, PartialEq, enum_utils::FromStr)]
enum NoCase {
Alpha,
Beta,
}
assert_eq!("ALPHA".parse(), Ok(NoCase::Alpha));
assert_eq!("beta".parse(), Ok(NoCase::Beta));