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

Derive TryFrom<T> for enums marked #[repr(T)] #146

Open
abonander opened this issue Nov 10, 2020 · 4 comments · Fixed by #300
Open

Derive TryFrom<T> for enums marked #[repr(T)] #146

abonander opened this issue Nov 10, 2020 · 4 comments · Fixed by #300

Comments

@abonander
Copy link

C-like enums with an explicit #[repr(<int type>)] attribute can be cast to that integer type, but there's no easy way to convert back:

#[repr(i16)]
enum MyEnum {
    Foo = 1,
    Bar = 2,
}

let val = MyEnum::Bar as i16;
let my_enum: MyEnum = // convert `val` back to `MyEnum`

This derive exists in enum-utils but it would be nice not to have to reach for multiple crates.

@ModProg
Copy link
Contributor

ModProg commented Aug 31, 2023

I'm also interrested in this, and might look into implementation.

I wonder what the best API would be here:

Automatically just assume TryFrom should be from repr.

#[derive(TryFrom)]
#[repr(i16)]
enum Enum {}

Have a TryFromRepr derive macro

#[derive(TryFromRepr)]
#[repr(i16)]
enum Enum {}

Specify that it should derive TryFrom for repr.

#[derive(TryFrom)]
#[try_from(rerpr)]
#[repr(i16)]
enum Enum {}

Also, there is a second part to this, deriving IntoRepr. Not as urgent, because there is as, but Into provides better integration with, e.g., generics.

@ModProg
Copy link
Contributor

ModProg commented Aug 31, 2023

Thinking about it a bit more, I think the implicit behavior is fine, because repr(u/i...) can only be e specified on a field less enum, therefor TryFrom could not mean anything else.

Edit: nether mind, you can put repr on enums. so I'm not so sure anymore.

@ModProg
Copy link
Contributor

ModProg commented Sep 5, 2023

So I implemented this now, for now it just automatically does the repl, not sure if that is something that should be controlled by an attribute, but I cannot think of any other usecases to derive right now.

tyranron pushed a commit that referenced this issue Sep 18, 2023
## Synopsis

Conversion from the repr integer to an enum.


## Solution

A `TryFrom` derive macro implementing `TryFrom<integertype> for Enum`.


## Additionally

Bump up MSRV to 1.72.0.
@tyranron
Copy link
Collaborator

Keeping this open because of #300 (comment)

@tyranron tyranron reopened this Sep 18, 2023
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 a pull request may close this issue.

3 participants