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

Support custom error type for TryFromPrimitive #121

Closed
qwandor opened this issue Jul 19, 2023 · 4 comments
Closed

Support custom error type for TryFromPrimitive #121

qwandor opened this issue Jul 19, 2023 · 4 comments

Comments

@qwandor
Copy link

qwandor commented Jul 19, 2023

It would be useful for the TryFromPrimitive derive macro to have an option to specify a custom error type to use when the conversion fails, rather than the supplied TryFromPrimitiveError. I'd like to use TryFromPrimitive on some types which are part of my library's public API, and exposing TryFromPrimitiveError as part of this isn't great. It could look something like:

#[derive(TryFromPrimitive)]
#[from_primitive_error(MyError, error_constructor)]
#[repr(u8)]
pub enum MyEnum {
    VariantOne,
    VariantTwo,
}

Where MyError is the error type to use for the TryFrom implementation, and error_constructor is a function of type (u8) -> MyError which the generated TryFrom implementation would call with the invalid input value to make an instance of the error type.

@illicitonion
Copy link
Owner

I really like this idea, and in particular I think it will also help solve #82 (which ideally would be solved by use of something like https://crates.io/crates/transitive rather than with num_enum-specific support)...

I'll have a play with what the API could look like for this - the place I'm not 100% sure of is on how to take the error_constructor, but in general I like the proposed API :)

@illicitonion
Copy link
Owner

I put together a draft in #123 - can you give it a go and see how it works for you?

You can see an example of the syntax in the newly added tests in num_enum/tests/try_from_primitive.rs:

#[derive(TryFromPrimitive)]
#[num_enum(error_type(name = CustomError, constructor = CustomError::new))]
#[repr(u8)]
enum FirstNumber {
    Zero,
    One,
    Two,
}

@qwandor
Copy link
Author

qwandor commented Aug 4, 2023

I just had a go with this in my code and it works well, thanks! Looking forward to seeing a release with this in it.

@illicitonion
Copy link
Owner

Fabulous! I've just published 0.7.0 with this feature :) Thanks again for the feature request, and testing it out!

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