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::error::ParseHardforkError;
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                      _ => Err($crate::error::ParseHardforkError::new(
34                $crate::__private::format!("Unknown hardfork: {s}")
35            )),
36                }
37            }
38        }
39
40        impl $crate::Hardfork for $enum {
41            fn name(&self) -> &'static str {
42                Self::name(self)
43            }
44        }
45
46        impl core::fmt::Display for $enum {
47            fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
48                write!(f, "{self:?}")
49            }
50        }
51    }
52}