Derive Macro Const

Source
#[derive(Const)]
{
    // Attributes available to this derive:
    #[value]
    #[armtype]
}
Expand description

Add’s constants to each arm of an enum

  • To get the value as a reference, call the function [<enum_name>::value]
  • However, direct comparison to non-reference values are possible with PartialEq

The #[armtype = ...] attribute is required for this macro to function, and must be applied to the enum, since all values share the same type.

All values set will return a [&'static T] reference. To the input type, of [T] AND [&T]. If multiple references are used (e.g. &&T), then the return type will be [&'static &T].

§Example

use thisenum::Const;
 
#[derive(Const, Debug)]
#[armtype(i32)]
enum MyEnum {
    #[value = 0]
    A,
    #[value = 1]
    B,
}
 
#[derive(Const, Debug)]
#[armtype(&[u8])]
enum Tags {
    #[value = b"\x00\x01\x7f"]
    Key,
    #[value = b"\xba\x5e"]
    Length,
    #[value = b"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f"]
    Data,
}
 
fn main() {
    // it's prefered to use the function call to `value` 
    // to get a [`&'static T`] reference to the value
    assert_eq!(MyEnum::A.value(), &0);
    assert_eq!(MyEnum::B.value(), &1);
    assert_eq!(Tags::Key.value(), b"\x00\x01\x7f");
    assert_eq!(Tags::Length.value(), b"\xba\x5e");
    assert_eq!(Tags::Data.value(), b"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f");
 
    // can also check equality without the function call. This must compare the input 
    // type defined in `#[armtype = ...]`
    //
    // to use this, use the `eq` feature in `Cargo.toml`: thisenum = { version = "x", features = ["eq"] }
    #[cfg(feature = "eq")]
    assert_eq!(Tags::Length, b"\xba\x5e");
}