#declarative-macro #enums #macro #no-std

no-std numeric-enum-macro

A declarative macro for type-safe enum-to-numbers conversion

2 unstable releases

0.2.0 Mar 2, 2020
0.1.1 Feb 25, 2020
0.1.0 Feb 25, 2020

#2927 in Rust patterns

Download history 447/week @ 2024-11-17 361/week @ 2024-11-24 325/week @ 2024-12-01 386/week @ 2024-12-08 432/week @ 2024-12-15 298/week @ 2024-12-22 464/week @ 2024-12-29 385/week @ 2025-01-05 333/week @ 2025-01-12 214/week @ 2025-01-19 167/week @ 2025-01-26 371/week @ 2025-02-02 293/week @ 2025-02-09 250/week @ 2025-02-16 516/week @ 2025-02-23 934/week @ 2025-03-02

2,026 downloads per month

MIT/Apache

7KB
62 lines

numeric-enum-macro

A declarative macro for type-safe enum-to-numbers conversion. no-std supported!

use numeric_enum_macro::numeric_enum;

numeric_enum! {
    #[repr(i64)] // repr must go first.
    /// Some docs.
    ///
    /// Multiline docs works too.
    #[derive(Debug, PartialEq, PartialOrd, Ord, Eq, Hash)] // all the attributes are forwarded!
    pub enum Lol {
        // All the constants must have explicit values assigned!
        Kek = 14,
        Wow = 87,
    }
}
// Conversion to raw number:
assert_eq!(14i64, Lol::Kek.into());
// Conversion from raw number:
assert_eq!(Ok(Lol::Wow), Lol::try_from(87));
// Unknown number:
assert_eq!(Err(88), Lol::try_from(88));

License: MIT/Apache-2.0


lib.rs:

A declarative macro for type-safe enum-to-numbers conversion. no-std supported!

use numeric_enum_macro::numeric_enum;

numeric_enum! {
    #[repr(i64)] // repr must go first.
    /// Some docs.
    ///
    /// Multiline docs works too.
    #[derive(Debug, PartialEq, PartialOrd, Ord, Eq, Hash)] // all the attributes are forwarded!
    pub enum Lol {
        // All the constants must have explicit values assigned!
        Kek = 14,
        Wow = 87,
    }
}

const KEK: u32 = 0;
const WOW: u32 = 1;

numeric_enum! {
    #[repr(u32)] // repr must go first.
    /// Some docs.
    ///
    /// Multiline docs works too.
    #[derive(Debug, PartialEq, PartialOrd, Ord, Eq, Hash)] // all the attributes are forwarded!
    pub enum Lol2 {
        /// This is KEK
        Kek = KEK,
        /// And this is WOW
        Wow = WOW,
    }
}

// Conversion to raw number:
assert_eq!(14i64, Lol::Kek.into());
// Conversion from raw number:
assert_eq!(Ok(Lol::Wow), Lol::try_from(87));
// Unknown number:
assert_eq!(Err(88), Lol::try_from(88));

assert_eq!(Ok(Lol2::Wow), Lol2::try_from(WOW));

No runtime deps