3 releases

new 0.1.2 Mar 5, 2025
0.1.1 Mar 5, 2025
0.1.0 Mar 5, 2025

#911 in Algorithms

Download history 322/week @ 2025-03-01

322 downloads per month

Custom license

4KB

Discriminant

Convert a enum (with or without field) with #[repr(...)] to corresponding type. Compatible with #![no_std].

Tested on rust-2021 and rust-2024

Examples

use discriminant::Discriminant;
#[derive(Discriminant)]
#[repr(i16)]
enum Test {
    One = 1,
    Two = 2,
    Four = 4,
}

fn test() {
    assert_eq!(Test::One.discriminant(), 1);
    assert_eq!(Test::Two.discriminant(), 2);
    assert_eq!(Test::Four.discriminant(), 4);
}

Credits

I had been seen such an approach on StackOverflow long time ago, but I can not find the original post, to make it convenient for other developers dealing with lower level data struct, I made this crate. Thank for the author on StackOverflow.


lib.rs:

Discriminant

Convert a enum (with or without field) with #[repr(...)] to corresponding type. Compatible with #![no_std].

Example

use discriminant_rs::Discriminant;
#[derive(Discriminant)]
#[repr(i16)]
enum Test {
    One = 1,
    Two = 2,
    Four = 4,
}

fn test() {
    assert_eq!(Test::One.discriminant(), 1);
    assert_eq!(Test::Two.discriminant(), 2);
    assert_eq!(Test::Four.discriminant(), 4);
}

Dependencies

~0.3–0.8MB
~18K SLoC