Peternator7 / strum

A small rust library for adding custom derives to enums
https://crates.io/crates/strum
MIT License
1.8k stars 151 forks source link

to_string and serialize when used together causes unreachable code #310

Open Stefanuk12 opened 1 year ago

Stefanuk12 commented 1 year ago

This behaviour is intentional but an option to disable to_string being included within the FromStr implementation would be nice.

Example code

In the following code, each url maps to a key. While a function could be used to map between the two, I prefer this method as the enum can provide additional information.

#[derive(strum::Display, strum::EnumString)]
enum Foo {
    #[strum(serialize = "url 1", to_string = "key 1")]
    A,
    #[strum(serialize = "url 2", to_string = "key 1")]
    B,
    #[strum(serialize = "url 3", to_string ="key 3")]
    C,
}

produces the following impl


#[allow(clippy::use_self)]
impl ::core::str::FromStr for Foo {
    type Err = ::strum::ParseError;
    fn from_str(s: &str) -> ::core::result::Result<Foo, <Self as ::core::str::FromStr>::Err> {
        ::core::result::Result::Ok(match s {
            "url 1" => Foo::A,
            "key 1" => Foo::A,
            "url 2" => Foo::B,
            "key 1" => Foo::B,
            "url 3" => Foo::C,
            "key 3" => Foo::C,
            _ => return ::core::result::Result::Err(::strum::ParseError::VariantNotFound),
        })
    }
}
```.
Peternator7 commented 1 year ago

@Stefanuk12, that's an interesting case. Would your case be solved if we supressed the warning and/or didn't emit the branch if it was a duplicate? The balance I'm trying to hit is that the FromStr macro generates dead simple code, and should, IMO, have a very simple configuration associated with it so I'm trying to avoid adding too many flags.

Stefanuk12 commented 1 year ago

The idea is a one way conversion. Ideally, don't emit the branch associated with to_string, if serialize is also specified on the same variant. If you're not able to, don't worry about it - there's probably a better way of me doing this anyway.