alloy_hardforks/hardfork/
macros.rs

1/// Macro that defines different variants of a chain specific enum. See [`crate::Hardfork`] as an
2/// example.
3#[macro_export]
4macro_rules! hardfork {
5    ($(#[$enum_meta:meta])* $enum:ident { $( $(#[$meta:meta])* $variant:ident ),* $(,)? }) => {
6        $(#[$enum_meta])*
7        #[derive(Debug, Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Hash)]
8        pub enum $enum {
9            $( $(#[$meta])* $variant ),*
10        }
11
12        impl $enum {
13
14            /// All hardfork variants
15            pub const VARIANTS: &'static [Self] =  &[$(Self::$variant ),*];
16
17            /// Returns variant as `str`.
18            pub const fn name(&self) -> &'static str {
19                match self {
20                    $( $enum::$variant => stringify!($variant), )*
21                }
22            }
23        }
24
25        impl core::str::FromStr for $enum {
26            type Err = $crate::__private::String;
27
28            fn from_str(s: &str) -> Result<Self, Self::Err> {
29                match s.to_lowercase().as_str() {
30                    $(
31                        s if s == stringify!($variant).to_lowercase() => Ok($enum::$variant),
32                    )*
33                    _ => return Err($crate::__private::format!("Unknown hardfork: {s}")),
34                }
35            }
36        }
37
38        impl $crate::Hardfork for $enum {
39            fn name(&self) -> &'static str {
40                Self::name(self)
41            }
42        }
43
44        impl core::fmt::Display for $enum {
45            fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
46                write!(f, "{self:?}")
47            }
48        }
49    }
50}