15 releases

0.5.0 Jul 9, 2022
0.4.4 Dec 8, 2021
0.4.3 Aug 11, 2021
0.4.2 May 25, 2020
0.3.3 May 11, 2018

#1177 in Rust patterns

Download history 1/week @ 2024-03-09 1/week @ 2024-03-23 105/week @ 2024-03-30 20/week @ 2024-04-06

94 downloads per month

Apache-2.0

14KB
246 lines

enum-unitary

Trait and macro for unitary enums

Documentation

The EnumUnitary trait carries a number of constraints for primitive conversions iterating over variants of a unitary enum (i.e. enum variants do not have payloads).

The enum_unitary! macro defines a new enum implementing EnumUnitary and required traits.

Usage

For the macro to derive Sequence, the enum-iterator crate must also be added to Cargo.toml:

enum-iterator = "1.0"
enum-unitary = "0.5"

Define a unitary enum:

use enum_unitary::{enum_unitary, EnumUnitary, FromPrimitive, ToPrimitive};

enum_unitary! {
  #[derive(Debug, PartialEq)]
  pub enum E {
    A, B, C
  }
}

assert_eq!(enum_iterator::cardinality::<E>(), 3);
assert_eq!(Into::<usize>::into (E::A), 0);
assert_eq!(Into::<usize>::into (E::B), 1);
assert_eq!(Into::<usize>::into (E::C), 2);
assert_eq!(enum_iterator::first::<E>().unwrap(), E::A);
assert_eq!(enum_iterator::last::<E>().unwrap(),  E::C);
let mut i = enum_iterator::all::<E>();
assert_eq!(i.next(), Some (E::A));
assert_eq!(i.next(), Some (E::B));
assert_eq!(i.next(), Some (E::C));
assert_eq!(i.next(), None);
assert_eq!(enum_iterator::next (&E::A), Some (E::B));
assert_eq!(enum_iterator::previous (&E::A), None);
assert_eq!(enum_iterator::next (&E::B), Some (E::C));
assert_eq!(enum_iterator::previous (&E::B), Some (E::A));
assert_eq!(enum_iterator::next (&E::C), None);
assert_eq!(enum_iterator::previous (&E::C), Some (E::B));

Dependencies

~0.4–1MB
~21K SLoC