macro_rules! caret_int {
    {
       $(#[$meta:meta])*
       $v:vis struct $name:ident ( $numtype:ty ) {
           $(
               $(#[$item_meta:meta])*
               $id:ident = $num:literal
           ),*
           $(,)?
      }
    } => { ... };
}
Expand description

Declare an integer type with some named elements.

This macro declares a struct that wraps an integer type, and allows any integer type as a value. Some values of this type have names, and others do not, but they are all allowed.

This macro is suitable for protocol implementations that accept any integer on the wire, and have definitions for some of those integers. For example, Tor cell commands are 8-bit integers, but not every u8 is a currently recognized Tor command.

Examples

use caret::caret_int;
caret_int! {
    pub struct FruitID(u8) {
        AVOCADO = 7,
        PERSIMMON = 8,
        LONGAN = 99
    }
}

// Known fruits work the way we would expect...
let a_num: u8 = FruitID::AVOCADO.into();
assert_eq!(a_num, 7);
let a_fruit: FruitID = 8.into();
assert_eq!(a_fruit, FruitID::PERSIMMON);
assert_eq!(format!("I'd like a {}", FruitID::PERSIMMON),
           "I'd like a PERSIMMON");

// And we can construct unknown fruits, if we encounter any.
let weird_fruit: FruitID = 202.into();
assert_eq!(format!("I'd like a {}", weird_fruit),
           "I'd like a 202");