pineapple_core/ut/
macros.rs

1// Copyright (c) 2025, Tom Ouellette
2// Licensed under the BSD 3-Clause License
3
4#[macro_export]
5macro_rules! impl_enum_dispatch {
6    // Case when the method takes &self with a lifetime and has NO arguments
7    ($enum_name:ident<$lifetime:lifetime>, $($variant:ident),*; $fn_name:ident(&$self_lifetime:lifetime self) -> $ret:ty) => {
8        impl<$lifetime> $enum_name<$lifetime> {
9            pub fn $fn_name(&$self_lifetime self) -> $ret {
10                match self {
11                    $(Self::$variant(v) => v.$fn_name(),)*
12                }
13            }
14        }
15    };
16
17    // Case when the method takes &self and has arguments
18    ($enum_name:ident, $($variant:ident),*; $fn_name:ident(&self, $($arg:ident : $arg_ty:ty),+) -> $ret:ty) => {
19        impl $enum_name {
20            pub fn $fn_name(&self, $($arg: $arg_ty),+) -> $ret {
21                match self {
22                    $(Self::$variant(v) => v.$fn_name($($arg),+),)*
23                }
24            }
25        }
26    };
27
28    // Case when the method takes &self and has NO arguments
29    ($enum_name:ident, $($variant:ident),*; $fn_name:ident(&self) -> $ret:ty) => {
30        impl $enum_name {
31            pub fn $fn_name(&self) -> $ret {
32                match self {
33                    $(Self::$variant(v) => v.$fn_name(),)*
34                }
35            }
36        }
37    };
38
39    // Case when the method takes &mut self and has arguments
40    ($enum_name:ident, $($variant:ident),*; $fn_name:ident(&mut self, $($arg:ident : $arg_ty:ty),+) -> $ret:ty) => {
41        impl $enum_name {
42            pub fn $fn_name(&mut self, $($arg: $arg_ty),+) -> $ret {
43                match self {
44                    $(Self::$variant(v) => v.$fn_name($($arg),+),)*
45                }
46            }
47        }
48    };
49
50    // Case when the method takes &mut self and has NO arguments
51    ($enum_name:ident, $($variant:ident),*; $fn_name:ident(&mut self) -> $ret:ty) => {
52        impl $enum_name {
53            pub fn $fn_name(&mut self) -> $ret {
54                match self {
55                    $(Self::$variant(v) => v.$fn_name(),)*
56                }
57            }
58        }
59    };
60}