Crate integral_enum

source ·
Expand description

Integral enum

Rust derive-macro that simplifies integral enum creation

Example

use integral_enum::IntegralEnum;

/// Simple meaningful enum
/// (!) repr attribute defaults to u8, to specify custom repr 
/// use built-in attribute #[repr(integral_value)] it
/// can contain only integral values
/// like u8, u16, u32, u64, u128 and its signed equivalents.
/// 
/// WARNING: if no explicit #[repr(...)] specified u8 will be used
/// as the underlying integral type, actual enum still can have u16 representation,
/// for example. For most cases this is enough, but if your enum is large
/// enough - specify explicit representation.
/// FIXME: Add automatic representation determining
#[derive(IntegralEnum)]
pub enum Emotion {
    Pain,
    Hatred,
}

// Test it
assert_eq!(Emotion::try_from(0), Ok(Emotion::Pain));
assert_eq!(Emotion::try_from(1), Ok(Emotion::Hatred));
assert_eq!(Emotion::try_from(123), Err(()));

Macro will automatically generate the following trait implementations: TryFrom, Clone, Copy, PartialEq, Eq, Display, Debug

if you want to disable certain implementation, consider the #[enum_disable(...)] attribute, items can be: clone, copy, display, debug, total_eq, partial_eq, try_from

  • Some of these attributes are dependant, for example Copy depends on Clone, so if you disable Clone generation, Copy generation will be disabled also.
  • total_eq disables Eq trait implementation

Example:

use integral_enum::IntegralEnum;

#[derive(IntegralEnum)]
#[enum_disable(display)]
pub enum Emotion {
    Pain,
    Hatred,
}

println!("{}", Emotion::Pain); // Compile error

TODO

  • Do we really need to implement PartialOrd + Ord also?

Derive Macros

Macro that implements bunch of traits for enums that simply are aliases for integer type
Strict version of the IntegralEnum. It implements only specified implementations, for example this compiles and successfully exits: