1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// SPDX-License-Identifier: MIT
// Copyright 2023 IROX Contributors
//

//!
//! Macros to aid in the creation of crate-level error structs

#[macro_export]
macro_rules! impl_error {
    ($ErrorName:ident, $ErrorType:ident) => {
        extern crate alloc;
        #[derive(Debug, Clone, Eq, PartialEq)]
        pub struct $ErrorName {
            error_type: $ErrorType,
            msg: alloc::string::String,
        }
        impl core::fmt::Display for $ErrorName {
            fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
                f.write_fmt(format_args!("{:?}: {}", self.error_type, self.msg))
            }
        }
        #[cfg(feature = "std")]
        impl std::error::Error for $ErrorName {}
    };
}
#[macro_export]
macro_rules! impl_from_error {
    ($ErrorName:ident,$source:ty,$ty:expr) => {
        impl From<$source> for $ErrorName {
            fn from(value: $source) -> Self {
                Error {
                    error_type: $ty,
                    msg: value.to_string(),
                }
            }
        }
    };
}

#[macro_export]
macro_rules! impl_err_fn {
    ($ErrorName:ident, $ty:expr, $name:ident, $name_err:ident) => {
        impl $ErrorName {
            pub fn $name(msg: String) -> Self {
                Self {
                    error_type: $ty,
                    msg,
                }
            }
            pub fn $name_err<T>(msg: String) -> Result<T, Self> {
                Err(Self::$name(msg))
            }
        }
    };
}