#enums #extracting #discriminant #proc-macro #zero #safe #minimalist

no-std safe-discriminant

A minimalistic, no_std compatible trait and procedural macro for extracting discriminants from enums at zero cost

2 unstable releases

0.2.0 Aug 19, 2024
0.1.0 Aug 16, 2024

#609 in Rust patterns

Download history 133/week @ 2024-08-12 167/week @ 2024-08-19 20/week @ 2024-08-26 120/week @ 2024-09-16 40/week @ 2024-09-23 61/week @ 2024-09-30 80/week @ 2024-10-07 98/week @ 2024-10-14 195/week @ 2024-10-21 143/week @ 2024-10-28 13/week @ 2024-11-04 222/week @ 2024-11-11 166/week @ 2024-11-18 26/week @ 2024-11-25

435 downloads per month

BSD-3-Clause

7KB

safe-discriminant

safe-discriminant provides a minimalistic, no_std compatible trait and procedural macro for extracting discriminants from enums at zero cost. It automatically generates unsafe { ... } blocks, ensuring semantic safety so you don’t have to worry about it.

Installation

This crate is available on crates.io and can be easily included in your project by:

  • Adding the following line to your Cargo.toml:
    [dependencies]
    safe-discriminant = "0.2.0"
    
  • Or runing this command in your cargo project:
    $ cargo add safe-discriminant
    

Usage

use safe_discriminant::Discriminant;

#[derive(Discriminant)]
#[repr(i64)]
pub enum Foo<T> {
    A = 1,
    B(T) = -1,
    C { fst: T, snd: T } = -2,
}

fn main() {
    let a: Foo<u8> = Foo::A;
    let b = Foo::B(5);
    let c = Foo::C { fst: 2, snd: 3 };
    assert_eq!(a.discriminant(), 1);
    assert_eq!(b.discriminant(), -1);
    assert_eq!(c.discriminant(), -2);
}

Similar Projects

  • strum provides a collection of macros designed to simplify working with enums. Among these macros is EnumDiscriminants, which extracts the name of each variant from the enum and organizes them into a separate enum.

Dependencies

~215–650KB
~15K SLoC