Skip to main content

ferrijs_std/utils/
macros.rs

1// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2// SPDX-License-Identifier: Apache-2.0
3#[macro_export]
4macro_rules! count_members {
5    () => (0);
6    ($head:tt $(,$tail:tt)*) => (1 + count_members!($($tail),*));
7}
8
9#[macro_export]
10macro_rules! iterable_enum {
11    ($name:ident, $($variant:ident),*) => {
12        impl $name {
13            const VARIANTS: &'static [$name] = &[$($name::$variant,)*];
14            pub fn iter() -> std::slice::Iter<'static, $name> {
15                Self::VARIANTS.iter()
16            }
17
18            #[allow(dead_code)]
19            fn _ensure_all_variants(s: Self) {
20                match s {
21                    $($name::$variant => {},)*
22                }
23            }
24        }
25    };
26}
27
28#[macro_export]
29macro_rules! str_enum {
30    ($name:ident, $($variant:ident => $str:expr),*) => {
31        impl $name {
32            pub fn as_str(&self) -> &'static str {
33                match self {
34                    $($name::$variant => $str,)*
35                }
36            }
37        }
38
39        impl AsRef<str> for $name {
40            fn as_ref(&self) -> &str {
41                self.as_str()
42            }
43        }
44
45        impl TryFrom<&str> for $name {
46            type Error = String;
47            fn try_from(s: &str) -> std::result::Result<Self, Self::Error> {
48                match s {
49                    $($str => Ok($name::$variant),)*
50                    _ => Err(["'", s, "' not available"].concat())
51                }
52            }
53        }
54    };
55}