strum icon indicating copy to clipboard operation
strum copied to clipboard

FromStr derive could support setting the error type

Open Ten0 opened this issue 5 years ago • 1 comments

When you derive on an enum, sometimes you want to implement some From<XXXNotFound> for some other error types, with maybe more explicit messages. It would be great if we could have an attribute that enables us to set the function that would be used to build the error from the original &str.

e.g.

#[derive(EnumString)]
#[strum(parse_err_ty = "SomeEnumNotFound", parse_err_fn = "some_enum_not_found_err")]
pub enum SomeEnum {
	A,
	B,
}

pub struct SomeEnumNotFound;
fn some_enum_not_found_err(_not_found: &str) -> SomeEnumNotFound { SomeEnumNotFound }

generating

impl FromStr for SomeEnum {
    type Err = SomeEnumNotFound;
    fn from_str(s: &str) -> Result<SomeEnum, Self::Err> {
        match s {
            "A" => A,
            "B" => B,
            other => some_enum_not_found_err(other),
        }
    }
}

If parse_err_fn is not specified but parse_err_ty is, we could fallback on From<strum::ParseError>.

Ten0 avatar Apr 20 '20 10:04 Ten0

This would be so nice! I am parsing a big XML with Rust and many fields are implemented as Enum, it uses strong-xml crate and well, returning FromStr(VariantNotFound) isn't really helpful when I have already five different enums and need to know with one did failed when parsing it from String.

dragonnn avatar Sep 15 '20 21:09 dragonnn