17 stable releases (3 major)

3.3.1 Dec 3, 2024
3.3.0 Nov 30, 2024
2.2.0 Nov 26, 2024
1.2.2 Aug 29, 2023
0.1.0 May 29, 2022

#659 in Rust patterns

Download history 6/week @ 2024-09-18 9/week @ 2024-09-25 272/week @ 2024-11-20 1010/week @ 2024-11-27 93/week @ 2024-12-04 34/week @ 2024-12-11

229 downloads per month

MIT license

55KB
652 lines

Provides extension to rust enum

This crate provides Enumeration trait for rust enum with the following features

  • implementation for common traits (Clone, Copy, Hash, etc.)
  • getting number of variants through constant Enumeration::VARIANT_COUNT
  • casting between index (of type Enumeration::Index) and enumeration
  • attaching a constant value to each of the variants
  • runtime representation of enumeration
use enumeration::{prelude::*, OutOfRangeError};

enumerate!(pub Foo(u8; i32 = 11)
    Bar
    Baz = 99
);

pub fn main() -> Result<Foo, OutOfRangeError> {
    assert_eq!(Foo::Bar, Foo::variant(0)?);
    assert_eq!(Foo::Baz.to_index(), 1);
    assert_eq!(Foo::Bar.value(), 11);
    assert_eq!(Foo::Baz.value(), 99);
    
    let variants: Vec<Variant<_>> = vec![Foo::Bar.into(), SomeOtherExternalEnum::SomeVariant.into()];
    
    assert_eq!(variants[0].cast::<Foo>(), Ok(Foo::Bar));
    assert_eq!(variants[1].cast::<SomeOtherExternalEnum>(), Ok(SomeOtherExternalEnum::SomeVariant));
    assert!(variants[1].cast::<Foo>().is_err());
}

No runtime deps

Features