[][src]Crate numeric_enum_macro

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

use numeric_enum_macro::{numeric_enum, numeric_enum_ident};

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;

// Unfortunately, it is not currently possible to use one macros to parse both literals and
// identifiers, so if you want to set up a macro using constants, use `numeric_enum_ident!`
// macro instead.
numeric_enum_ident! {
    #[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 {
        // All the constants must have explicit values assigned!
        Kek = KEK,
        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));

Macros

numeric_enum

Declares an enum with a given numeric representation defined by literals.

numeric_enum_ident

Declares an enum with a given numeric representation defined by identifiers.