Expand description
A derive macro for automatically implementing code conversion for enums
This crate provides two derive macros:
ToCodegenerates ato_code()method for converting enum variants toOption<u8>valuesTryFromCodegenerates atry_from_code()method for creating enum variants fromu8values
Both macros work with unit variants, named fields, and tuple variants. For using TryFromCode fields in variants must implement
the Default trait as they will be initialized with default values during conversion from codes.
§Example
use complex_enum_macros::{ToCode, TryFromCode};
#[derive(ToCode, TryFromCode, Debug, PartialEq)]
#[repr(u8)]
enum Command {
Unknown,
Start = 0x01,
SetConfig { value: Option<u32> } = 0x02,
SendData(String) = 0x03,
Stop = 0x04,
}
// Convert enum to code
let cmd = Command::SetConfig { value: Some(42) };
assert_eq!(cmd.to_code(), Some(0x02));
// Create enum from code and modify
let mut cmd = Command::try_from_code(0x02).unwrap();
match cmd {
Command::SetConfig { ref mut value } => *value = Some(42),
_ => unreachable!(),
}
assert_eq!(cmd.to_code(), Some(0x02));
match cmd {
Command::SetConfig { value } => assert_eq!(value, Some(42)),
_ => unreachable!(),
}
// Unknown codes return None
assert_eq!(Command::try_from_code(0xFF), None);
// Variants without codes return None
assert_eq!(Command::Unknown.to_code(), None);§Features
- Automatic code conversion in both directions
- Support for all enum variant types
- Default initialization of fields
§Requirements
- Enum must have
#[repr(u8)] - For TryFromCode field types must implement
Default - Variants with codes must have explicit discriminants
Derive Macros§
- ToCode
- Derives the
ToCodetrait for an enum. - TryFrom
Code - Derives the
TryFromCodetrait for an enum.