Document the order in which enum items are mapped to usize
As of 2.2.0, the documentation of the Enum derive macro contains the following example:
use enum_map::Enum;
#[derive(Enum, Debug, PartialEq, Eq)]
enum A {
B,
C,
D,
}
assert_eq!(A::B.into_usize(), 0);
assert_eq!(A::C.into_usize(), 1);
assert_eq!(A::D.into_usize(), 2);
assert_eq!(A::from_usize(0), A::B);
assert_eq!(A::from_usize(1), A::C);
assert_eq!(A::from_usize(2), A::D);
Those assert_eq! statements are asserting that enum items are mapped to usize values in a predictable way. However, the documentation doesn't specify any rules of the mapping.
From the source code, I see that the procedure macro visits enum variants in the source code order, and in handle_unit_variant, it maps unit variants in an ascending order.
The project I am working on has some kind of "phase" system where phases are expresses as enum, and the program executes each phase in order. The following program, for example, is expected to print "Prepare", "Exec" and "Finish" in that order.
use enum_map::Enum;
#[derive(Enum, Debug)]
enum Phase {
Prepare,
Exec,
Finish,
}
fn run_phase(phase: Phase) {
println!("Running {:?} phase...", phase);
}
fn main() {
for phase in (0..Phase::LENGTH).map(Phase::from_usize) {
run_phase(phase);
}
}
And it does print in that order with the latest enum-map crate. However, we cannot find such guarantee in the documentation, and we worry that the behaviour may change in future versions of enum-map.
If it is guaranteed to behave that way, could you document the behaviour? Otherwise, could you explicitly note in the documentation that the order of mapping Enum to usize should not be depended on?