Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

to_string and serialize when used together causes unreachable code #310

Open
Stefanuk12 opened this issue Oct 25, 2023 · 2 comments
Open

Comments

@Stefanuk12
Copy link

Stefanuk12 commented Oct 25, 2023

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
Copy link
Owner

@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
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants