Derive Macro strum_macros::EnumTable
source · #[derive(EnumTable)]
{
// Attributes available to this derive:
#[strum]
}
Expand description
Creates a new type that maps all the variants of an enum to another generic value.
This macro only supports enums with unit type variants.A new type called YourEnumTable<T>. Essentially, it’s a wrapper
[T; YourEnum::Count] where gets/sets are infallible. Some important caveats to note:
-
The size of
YourEnumTable<T>increases with the number of variants, not the number of values because it’s always fully populated. This means it may not be a good choice for sparsely populated maps. -
Lookups are basically constant time since it’s functionally an array index.
-
Your variants cannot have associated data. You can use
EnumDiscriminantsto generate an Enum with the same names to work around this.
Stability
Several people expressed interest in a data structure like this and pushed the PR through to completion, but the api seems incomplete, and I reserve the right to deprecate it in the future if it becomes clear the design is flawed.
Example
use strum_macros::EnumTable;
#[derive(EnumTable)]
enum Color {
Red,
Yellow,
Green,
Blue,
}
assert_eq!(ColorTable::default(), ColorTable::new(0, 0, 0, 0));
assert_eq!(ColorTable::filled(2), ColorTable::new(2, 2, 2, 2));
assert_eq!(ColorTable::from_closure(|_| 3), ColorTable::new(3, 3, 3, 3));
assert_eq!(ColorTable::default().transform(|_, val| val + 2), ColorTable::new(2, 2, 2, 2));
let mut complex_map = ColorTable::from_closure(|color| match color {
Color::Red => 0,
_ => 3
});
complex_map[Color::Green] = complex_map[Color::Red];
assert_eq!(complex_map, ColorTable::new(0, 3, 0, 3));