Skip to content

Conversation

@scovich
Copy link

@scovich scovich commented Apr 9, 2025

Any enum with a #[strum(default)] variant has infallible parsing in practice, but the compiler does not know this because the error type is still strum::ParseError.

This PR proposes a non-breaking change to address the issue: Define a new type-level attribute parse_infallible, which instructs EnumString to use std::convert::Infallible for FromStr::Err, and to derive From<&str> (always) instead of TryFrom<&str> (1.34+). This allows e.g.

let variant = MyInfallibleEnum::from("some_unknown_variant")

and (in 1.82+)

let Ok(variant) = MyInfallibleEnum::from_str("some_unknown_variant");

Existing EnumString derivations remain unchanged unless the user adds the parse_infallible attribute. As a future breaking change, we could start inferring parse_infallible automatically even for enums that do not carry the annotation. If a breaking change is immediately acceptable, we don't need to define the new attribute at all, and this PR becomes simpler.

NOTE: TryFrom is still available (for 1.34+) with parse_infallible, because the From<&str> derived by EnumString activates a blanket implementation of reverse Into, which in turn activates a blanket implementation of TryFrom.

Also update docs and add new unit tests that exercise infallible parsing for both normal and PHF enums.

Fixes #307

@scovich scovich changed the title Support infallible EnumString for enums with a Fdefault variant Support infallible EnumString for enums with a default variant Apr 9, 2025
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

Successfully merging this pull request may close these issues.

EnumString should derive From<&str> instead of TryFrom<&str> when #[strum(default)] is present

1 participant