2 releases

0.1.1 Mar 25, 2024
0.1.0 Mar 25, 2024

#1131 in Rust patterns

28 downloads per month

MIT/Apache

8KB

Enum Rotate

Version Minimum Rust version: 1.36

Treat your enums as iterators.

This crate provides the EnumRotate trait along with the accompanying derive macro allowing you to

  • Get the next and previous variant for any variant of an enum
  • Iterate over variants of an enum in a predefined (and customizable) order
  • Iterate over variants of an enum starting from a particular variant

Usage

use enum_rotate::EnumRotate;
use Enum::*;

#[derive(EnumRotate, PartialEq)]
enum Enum { A, B, C }

fn main() {
    assert_eq!(A.next(), B);
    assert_eq!(A.prev(), C);

    assert_eq!(
        Enum::iter().collect::<Vec<_>>(),
        vec![A, B, C],
    );
    
    assert_eq!(
        C.iter_from().collect::<Vec<_>>(),
        vec![C, A, B],
    );
}

It is also possible to specify a custom iteration order for the enum variants.

use enum_rotate::EnumRotate;
use Enum::*;

#[derive(EnumRotate, PartialEq)]
#[iteration_order(B, A, C)]
enum Enum { A, B, C }

fn main() {
    assert_eq!(
        Enum::iter().collect::<Vec<_>>(),
        vec![B, A, C],
    );
}

Dependencies

~295–750KB
~17K SLoC