Crate complex_enum_macros

Source
Expand description

A derive macro for automatically implementing code conversion for enums

This crate provides two derive macros:

  • ToCode generates a to_code() method for converting enum variants to Option<u8> values
  • TryFromCode generates a try_from_code() method for creating enum variants from u8 values

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 ToCode trait for an enum.
TryFromCode
Derives the TryFromCode trait for an enum.