Derive the From or TryFrom traits for enums with integer values.
Designed to provide a consistant mechanism to work with C-style Enums in Rust such as when implementing a parser.
toml
[dependencies]
renum = "0.1.0"
```rust use renum::Renum;
pub enum MyEnum { VariantA = 0x01, VariantB = 0x02, VariantC = 0x03, Undefined }
let x = MyEnum::try_from(0x04);
assert_eq!(x, Err(MyEnum::Undefined))
```
default behavior
```rust
```
The Result
returned by the derived try_from
will be Ok(Enum::Variant)
unless the variant is explicitly tagged #[renum(Err)]
The default case will return Err(Enum::Default)
unless explicitly tagged #[renum(Ok)]
```rust
```
Inverts the normally_ok
behavior
The Result
returned by the derived try_from
will be Err(Enum::Variant)
unless explicitly tagged #[renum(Ok)]
The default case will return Ok(Enum::Default)
unless explicitly tagged #[renum(Err)]
example usage: status code enums
```rust
pub enum StatusCodes { Success, FailureA = 1, FailureB = 2, FailureC = 3 }
// ...
let statuscode = StatusCodes::tryfrom(2)?;
```
```rust
```
If an enum does not have a default variant allow_panic
will allow the derived method to panic on undefined values.
Example:
```rust
pub enum PanicEnum { A = 0, B = 1, }
fn test() { let _ = PanicEnum::from(0xff); }
```
Only Valid when deriving TryFrom
```rust
```
The error type can be controlled with the Error
option; REPR
, and ENUM
are builtin values which return the value passed in or enum variant.
If a custom error is used it must implement From::<#ErrorFrom>
(discussed below), by default this will be the repr type.
Only Valid when deriving TryFrom
```rust
```
The value used to initialize custom errors can be set to REPR
, ENUM
, or any sequence of ([REPR|ENUM],*)
Example:
```rust
struct CustomError;
impl From<(MyEnum, u16)> for CustomError { fn from(from: (MyEnum, u16)) -> Self { CustomError; } }
pub enum MyEnum { A = 1, B = 2, C = 3, #[renum(Err, values = 4..=34 )] ReservedSome, #[renum(Err)] ReservedRest }
if let Err(error) = MyEnum::try_from(64) { // do something with custom error }
```
Only Valid when deriving TryFrom
```rust
Variant = 0 ```
The variant will always return Ok(Enum::Variant)
when matched even if it would otherwise be an error condition.
Only Valid when deriving TryFrom
```rust
Variant = 0 ```
The variant will always return Err(Enum::Variant)
when matched even if it would otherwise be an error condition.
```rust
Variant ```
If no values match this variant will be returned, if no variants are explicitly annotated with the default
option, default is automatically selected to be the variant without a desciminant or values attribute.
```rust
```
Specify values for a variant where it may take on multiple values.