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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
use std::{cmp::max, fmt::Display};

/// Macros
mod macros;
#[allow(unused_imports)]
pub use macros::*;

/// Default log level for the crate
pub const DEFAULT_LOG_LEVEL: Level = Level::Debug;

/// Trait for logging errors
pub trait Log {
    /// Log an error via `tracing` utilities, printing it.
    fn log(&self);
}

impl Log for Error {
    fn log(&self) {
        let mut error_level = self.level;
        if error_level == Level::Unspecified {
            error_level = DEFAULT_LOG_LEVEL;
        }

        match error_level {
            Level::Trace => {
                tracing::trace!("{}", self.message);
            }
            Level::Debug => {
                tracing::debug!("{}", self.message);
            }
            Level::Info => {
                tracing::info!("{}", self.message);
            }
            Level::Warn => {
                tracing::warn!("{}", self.message);
            }
            Level::Error => {
                tracing::error!("{}", self.message);
            }
            // impossible
            Level::Unspecified => {}
        }
    }
}

impl<T> Log for Result<T> {
    fn log(&self) {
        let error = match self {
            Ok(_) => {
                return;
            }
            Err(e) => e,
        };

        let mut error_level = error.level;
        if error_level == Level::Unspecified {
            error_level = DEFAULT_LOG_LEVEL;
        }

        match error_level {
            Level::Trace => {
                tracing::trace!("{}", error.message);
            }
            Level::Debug => {
                tracing::debug!("{}", error.message);
            }
            Level::Info => {
                tracing::info!("{}", error.message);
            }
            Level::Warn => {
                tracing::warn!("{}", error.message);
            }
            Level::Error => {
                tracing::error!("{}", error.message);
            }
            // impossible
            Level::Unspecified => {}
        }
    }
}

#[derive(Debug, Clone)]
#[must_use]
/// main error type
pub struct Error {
    /// level
    pub level: Level,
    /// message
    pub message: String,
}

impl std::error::Error for Error {}

/// Trait for a `std::result::Result` that can be wrapped into a `Result`
pub trait Wrap<T> {
    /// Wrap the value into a `Result`
    ///
    /// # Errors
    /// Propagates errors from `self`
    fn wrap(self) -> Result<T>;
}

impl<T, E> Wrap<T> for std::result::Result<T, E>
where
    E: Display,
{
    fn wrap(self) -> Result<T> {
        match self {
            Ok(t) => Ok(t),
            Err(e) => Err(Error {
                level: Level::Unspecified,
                message: format!("{e}"),
            }),
        }
    }
}

impl Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.message)
    }
}

/// Alias for the main `Result` type used by the crate.
pub type Result<T> = std::result::Result<T, Error>;

#[derive(PartialEq, Eq, PartialOrd, Ord, Debug, Clone, Copy)]
/// Possible log levels
pub enum Level {
    /// Unspecified log level
    Unspecified,
    /// TRACE
    Trace,
    /// DEBUG
    Debug,
    /// INFO
    Info,
    /// WARN
    Warn,
    /// ERROR
    Error,
}

/// Prepend an error to its cause
fn concatenate(error: &String, cause: &String) -> String {
    format!("{error}\ncaused by: {cause}")
}

/// Trait for converting error types to a `Result<T>`.
pub trait Context<T, E> {
    /// Attach context to the given error.
    ///
    /// # Errors
    /// Propagates errors from `self`
    fn context(self, error: E) -> Result<T>;
}

impl<T> Context<T, Error> for Result<T> {
    fn context(self, error: Error) -> Result<T> {
        match self {
            Ok(t) => Ok(t),
            Err(cause) => Err(Error {
                level: max(error.level, cause.level),
                message: concatenate(&error.message, &format!("{cause}")),
            }),
        }
    }
}

impl<T, F> Context<T, F> for Result<T>
where
    F: Fn(Error) -> Error,
{
    fn context(self, error: F) -> Result<T> {
        match self {
            Ok(t) => Ok(t),
            Err(cause) => Err(Error {
                level: max(error(cause.clone()).level, cause.level),
                message: concatenate(&error(cause.clone()).message, &format!("{cause}")),
            }),
        }
    }
}

impl<T> Context<T, Error> for Option<T> {
    fn context(self, error: Error) -> Result<T> {
        match self {
            Some(t) => Ok(t),
            None => Err(error),
        }
    }
}

impl<'a, T> Context<&'a mut T, Error> for &'a mut Option<T> {
    fn context(self, error: Error) -> Result<&'a mut T> {
        match self {
            Some(t) => Ok(t),
            None => Err(error),
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn ordering() {
        assert!(Level::Trace < Level::Debug);
        assert!(Level::Debug < Level::Info);
        assert!(Level::Info < Level::Warn);
        assert!(Level::Warn < Level::Error);
        assert!(max(Level::Trace, Level::Error) == Level::Error);
    }
}