enum_table/macros.rs
1/// A macro to create an `EnumTable` for a given enumeration and value type.
2///
3/// # Arguments
4///
5/// * `$variant` - The enumeration type that implements the `Enumable` trait.
6/// * `$value` - The type of values to be associated with each enumeration variant.
7/// * `$count` - The number of variants in the enumeration.
8/// * `$variable` - The variable name to use in the closure for each variant.
9/// * `$($tt:tt)*` - The closure that maps each variant to a value.
10///
11/// # Example
12///
13/// ```rust
14/// use enum_table::{EnumTable, Enumable, et};
15///
16/// enum Test {
17/// A,
18/// B,
19/// C,
20/// }
21///
22/// impl enum_table::Enumable for Test {
23/// const VARIANTS: &'static [Self] = &[Test::A, Test::B, Test::C];
24/// }
25///
26/// const TABLE: EnumTable<Test, &'static str, { Test::COUNT }> =
27/// et!(Test, &'static str, |t| match t {
28/// Test::A => "A",
29/// Test::B => "B",
30/// Test::C => "C",
31/// });
32///
33/// assert_eq!(TABLE.get(&Test::A), &"A");
34/// assert_eq!(TABLE.get(&Test::B), &"B");
35/// assert_eq!(TABLE.get(&Test::C), &"C");
36///
37#[macro_export]
38macro_rules! et {
39 ($variant:ty, $value:ty, |$variable:ident| $($tt:tt)*) => {
40 {
41 let mut builder = $crate::builder::EnumTableBuilder::<$variant, $value, { <$variant as $crate::Enumable>::COUNT }>::new();
42
43 let mut i = 0;
44 while i < builder.len() {
45 let $variable = &<$variant as $crate::Enumable>::VARIANTS[i];
46 builder.push(
47 $variable,
48 $($tt)*
49 );
50 i += 1;
51 }
52
53 builder.build_to()
54 }
55 };
56}
57
58#[cfg(test)]
59mod tests {
60 use crate::{EnumTable, Enumable};
61
62 #[test]
63 fn et_macro() {
64 #[derive(Enumable)]
65 enum Test {
66 A,
67 B,
68 C,
69 }
70
71 const TABLE: EnumTable<Test, &'static str, { Test::COUNT }> =
72 et!(Test, &'static str, |t| match t {
73 Test::A => "A",
74 Test::B => "B",
75 Test::C => "C",
76 });
77
78 assert_eq!(TABLE.get(&Test::A), &"A");
79 assert_eq!(TABLE.get(&Test::B), &"B");
80 assert_eq!(TABLE.get(&Test::C), &"C");
81 }
82}