num_enum
num_enum copied to clipboard
TryFromPrimitive - accept more input types
I'm using this library to help generate a binary protocol so there's lots of repr(u8)
/repr(u16)
going around.
More often than not, the try_from
input type is not a match for the repr type and particularly in the case of larger -> smaller types it is inconvenient to consistently need two try_from
calls in a row that don't add anything
- TryFromPrimitive is going to
match [0..3]
whether the input is au8
or ausize
or anything in between. The conversion tou8
is just additional book-keeping (and one with an incompatible error type -.-) - narrow->wide is better (generally) because of
From
but you still need to know the exact repr type so it's not perfect - signed results from calculations and unsigned encodings are also common so it's not just widening/narrowing that creates papercuts
It makes sense to only handle the repr
type in Into/From but limiting TryFrom
just opens the door for as
(which is the whole point of this crate to begin with)
Not sure what this would best look like (list of alternate try_from reprs? I have a couple of cases where types need different handling (e.g. u8 -> u16 shifts to the high byte) so opt-in would be better).