Crate safe_discriminant

Crate safe_discriminant 

Source
Expand description

The Discriminant trait, along with its corresponding derive macro, offers a constant-time and safe method for extracting the primitive form of the discriminant value for enums.

The trait is derivable only when the following conditions are met:

  1. The enum’s is accompanied by #[repr(x)] attribute, where x must be one of the supported primitive types: u8, i8, u16, i16, u32, i32, u64, or i64.

  2. All enum variants have explicit discriminants.

  3. Except for #[repr(x)], there are no #[attr] style proc-macros after #[derive(Discriminant)].

§Usage

To use this macro, simply annotate your enum with #[derive(Discriminant)] as follows:

use safe_discriminant::Discriminant;
#[derive(Discriminant)]
#[repr(u8)]
enum Foo {
    A = 1,
    B(u8) = 2,
    C{inner: u8} = 3,
}
let a = Foo::A;
let b = Foo::B(5);
let c = Foo::C{inner: 6};
assert_eq!(a.discriminant(), 1);
assert_eq!(b.discriminant(), 2);
assert_eq!(c.discriminant(), 3);

Traits§

Discriminant

Derive Macros§

Discriminant
Top level derive macro for Discriminant trait. For more information on how to use refer to safe-discriminant crate.