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        #[non_exhaustive]
9        pub enum $enum {
10            $( $(#[$meta])* $variant ),*
11        }
12
13        impl $enum {
14
15            /// All hardfork variants
16            pub const VARIANTS: &'static [Self] =  &[$(Self::$variant ),*];
17
18            /// Returns variant as `str`.
19            pub const fn name(&self) -> &'static str {
20                match self {
21                    $( $enum::$variant => stringify!($variant), )*
22                }
23            }
24        }
25
26        impl core::str::FromStr for $enum {
27            type Err = $crate::error::ParseHardforkError;
28
29            fn from_str(s: &str) -> Result<Self, Self::Err> {
30                match s.to_lowercase().as_str() {
31                    $(
32                        s if s == stringify!($variant).to_lowercase() => Ok($enum::$variant),
33                    )*
34                      _ => Err($crate::error::ParseHardforkError::new(
35                $crate::__private::format!("Unknown hardfork: {s}")
36            )),
37                }
38            }
39        }
40
41        impl $crate::Hardfork for $enum {
42            fn name(&self) -> &'static str {
43                Self::name(self)
44            }
45        }
46
47        impl core::fmt::Display for $enum {
48            fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
49                write!(f, "{self:?}")
50            }
51        }
52    }
53}