derive_more
derive_more copied to clipboard
Derive `TryFrom<T>` for enums marked `#[repr(T)]`
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.
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.
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.
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.
Keeping this open because of https://github.com/JelteF/derive_more/pull/300#issuecomment-1709853391