Skip to main content

quickjs_jit_stdlib/llrt/llrt_utils/
macros.rs

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