derive_more icon indicating copy to clipboard operation
derive_more copied to clipboard

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

Open abonander opened this issue 4 years ago • 4 comments

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.

abonander avatar Nov 10 '20 16:11 abonander

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 avatar Aug 31 '23 10:08 ModProg

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 avatar Aug 31 '23 10:08 ModProg

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.

ModProg avatar Sep 05 '23 22:09 ModProg

Keeping this open because of https://github.com/JelteF/derive_more/pull/300#issuecomment-1709853391

tyranron avatar Sep 18 '23 13:09 tyranron