Open agreyyy opened 3 months ago
dk if I should turn this into an RFC or not, I was working with C-Style Enums for a DNS project and found converting from and to bytes with C-Style Enums to be far too much boilerplate for the complexity of the logic defined by them.
sounds good as long as you have to opt-in, e.g. via #[derive(Into, TryFrom)]
for reference OP submitted an actual RFC at #3604.
Why do we specifically want Into
and TryFrom
instead of a dedicated, probably auto trait for these conversions (like the safe-transmute APIs)?
well, for one, those dedicated traits are already proposed in other RFCs 🙃 (AsRepr, FromRepr @ rust-lang/rust#86772 ← #3040, #3046, not yet implemented)
I would like to propose that the compiler generates an automatic implementation of TryFrom<{Integer}> and Into<{Integer}> for C-style enums. Now I don`t know if they are actually called C-style enums by the community, but I am referring to these types of enums.
One cool thing about C-style enums is that you can convert them to any integer type (u8,u16, etc.) using
as
syntax:However, C-style enums do not auto implement the Into<{Integer}> and TryFrom<{Integer}> traits like other Integers do (i16, u16, etc.), but I think they should. Since C-Style enums are just a subset of all Integers, I think all the common methods of converting them to Integers and converting Integers to C-Style enums except converting Integers to C-Style Enums with the
as
keyword(example below) should be supported by the compiler.Into<{Integer}>
I think The auto-impl of Into<{Itegers}> would make sense since the C-style enum explicitly states that you want states to map to some sort of number. Anyways, the most important part of my proposal in the TryFrom<{Integer}> auto-implementation.
TryFrom<{Integer}>
Imagine If this CStyleEnum that I`ve been reusing for these code examples has more than 3 variants, or if I had made multiple C-style enums in my codebase, it would be a real eyesore to look at all those manual TryFrom implementations, and a waste of time to write a macro for something so trivial, and probably unnecessary to bring in an external crate with a macro to implement the TryFrom for me like Strum, since the compiler already logically does this for conversions between numbers, e.g. this is What a TryFrom would look like for u8:
The drawbacks of this would be if for some reason, the developer would want a different TryFrom implementation for their C-Style enum, but maybe the rust compiler could let the developer implement it themselves, like an ovveride, or instead the developer could opt-in to the compilers implementation via a
#[derive(TryFrom)]
for their C-Style Enum.Conclusion
Anyways, this is just a small Quality Of Life change for Rust, which abstracts a bit of boilerplate away from the developers (us), therefore making our experience better, I think the magnitude of this change is similar to adding a (#[derive(Default)] for enums)[https://github.com/rust-lang/rfcs/pull/3107]