rotate-enum crate
Simple derive macros that implement prev()
and next()
methods to an enum in Rust
Motivation
Sometimes you define an enum like this
and you want to rotate them in some logic,
let up = Up;
let left = Left;
let down = Down;
let right = Right;
assert!;
assert!;
assert!;
assert!;
assert!;
assert!;
assert!;
assert!;
You can of course implement these methods manually, but it's repetitive and error prone.
Don't you think it should be automated?
This crate provides a RotateEnum
derive macro to just do this.
Shifting
This crate also provides ShiftEnum
, which will exhaust at the end of the enum list,
rather than rotating.
let up = Up;
let left = Left;
let down = Down;
let right = Right;
assert!;
assert!;
assert!;
assert!;
assert!;
assert!;
assert!;
assert!;
Note that you can only derive either one of RotateEnum
or ShiftEnum
, but not both, because their semantics conflict.
Iterating
This crate also provides IterEnum
, which will implement Iterator
object
that yields enum variants in sequence. The first yield result will be the same
variant as the one started the iterator, i.e. Direction::Up.iter().next() == Some(Direction::Up)
.
let up = Up;
let left = Left;
let down = Down;
let right = Right;
let mut iter = up.iter;
assert!;
assert!;
assert!;
assert!;
assert!;
assert_eq!;
Note that it is not the same as ShiftEnum
in the sense that the iterator is one-directional, which means you can go only forward and not prev()
.
It can also be used with iterator methods like collect()
.
IterEnum
also requires deriving Clone
.
Usage
Use #[derive(...)]
macro to annotate your enum.
use RotateEnum;