#parser #enums #literals #const #macro

thisenum

Assign constant literals to enum arms

4 releases

0.2.1 Aug 15, 2024
0.2.0 Aug 15, 2024
0.1.3 Aug 15, 2024
0.1.2 Jul 18, 2024

#89 in Parser tooling

Download history 182/week @ 2024-07-11 158/week @ 2024-07-18 1/week @ 2024-07-25 281/week @ 2024-08-15 1/week @ 2024-08-22 19/week @ 2024-09-12 14/week @ 2024-09-19 27/week @ 2024-09-26 9/week @ 2024-10-03

69 downloads per month
Used in 5 crates (4 directly)

MIT license

9KB
53 lines

thisenum

LICENSE Crates.io Version

The simplest way to assign constant literals to enum arms in Rust! What fun!

Please also see enum-assoc, which is a more robust alternative.

use thisenum::Const;

#[derive(Const, Debug)]
#[armtype(&[u8])]
/// https://exiftool.org/TagNames/EXIF.html
enum ExifTag {
    // ...
    #[value = b"\x01\x00"]
    ImageWidth,
    #[value = b"\x01\x01"]
    ImageHeight,
    #[value = b"\x01\x02"]
    BitsPerSample,
    #[value = b"\x01\x03"]
    Compression,
    #[value = b"\x01\x06"]
    PhotometricInterpretation,
    // ...
}

assert_eq!(ExifTag::ImageWidth.value(), b"\x01\x00");
#[cfg(feature = "eq")]
assert_eq!(ExifTag::ImageWidth, b"\x01\x00");

If each arm is a different type, this is still possible using ConstEach:

use thisenum::ConstEach;

#[derive(ConstEach, Debug)]
enum CustomEnum {
    #[armtype(&[u8])]
    #[value = b"\x01\x00"]
    A,
    // `armtype` is not required, type is inferred
    #[value = "foo"]
    B,
    #[armtype(f32)]
    #[value = 3.14]
    C,
}

assert_eq!(CustomEnum::A.value::<&[u8]>().unwrap(), b"\x01\x00");
assert!(CustomEnum::B.value::<&str>().is_some());
assert_eq!(CustomEnum::B.value::<&str>().unwrap(), &"foo");
assert_eq!(CustomEnum::B.value::<&str>(), Some("foo").as_ref());
assert_eq!(CustomEnum::C.value::<f32>().unwrap(), &3.14);
// or on failure
assert!(CustomEnum::C.value::<i32>().is_none());

License

thisenum is released under the MIT License http://opensource.org/licenses/MIT.

Dependencies

~255–710KB
~17K SLoC