Easily create casting traits with unknown field support.
EnumConvert
or EnumTryConvert
into the derive
attribute.```rust use zhi_enum::{EnumConvert, EnumTryConvert};
enum NumberConvert { Zero, One, Two, Three, Four, Ten = 10, Eleven, Twenty = 10 + 10, TwentyOne, #[zhi_enum(unknown)] Unknown(u8), }
enum NumberTryConvert { Zero, One, Two, Three, Four, Ten = 10, Eleven, Twenty = 10 + 10, TwentyOne, #[zhi_enum(unknown)] Unknown(u8), }
```
.from
/.into
convert functions```rust asserteq!(NumberConvert::Three.intou8(), 3u8); asserteq!(NumberTryConvert::Three.tryintou8().unwrap(), 3u8); asserteq!(NumberConvert::Ten.intou8(), 10u8); asserteq!(NumberTryConvert::Ten.tryintou8().unwrap(), 10u8); asserteq!(NumberConvert::Eleven.intou8(), 11u8); asserteq!(NumberTryConvert::Eleven.tryintou8().unwrap(), 11u8); asserteq!(NumberConvert::TwentyOne.intou8(), 21u8); asserteq!(NumberTryConvert::TwentyOne.tryintou8().unwrap(), 21u8);
asserteq!(NumberConvert::from(3u8), NumberConvert::Three); asserteq!(NumberTryConvert::try_from(21u8).unwrap(), NumberTryConvert::TwentyOne) ```
If you have defined a variant with #[zhi_enum(unknown)]
attribute in your enum like this :
```rust
Whatever(repr type),
``
which the
repr typeis the represented type as you define use
#[repr(...)]`.
Then, when you convert a repr type into enum type, an unknown discriminant will be converted to this variant with its unknown value.
If you have not defined, the .try_into()
will returns Err(UnknownVariantError{})
, and the
.into()
will call panic!
.
Error E0658
If you get this error:
error[E0658]: custom discriminant values are not allowed in enums with tuple or struct variants
--> <source>:2:9
It means that your rustc version is lower than 1.56
.
You can just upgrade your rustc. Or if you don't want upgrade, you have to add #![feature(arbitrary_enum_discriminant)]
to your project.
BSD-3-Clause