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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
// SPDX-License-Identifier: AGPL-3.0-or-later
//! This module defines the `Error` and `Result` types used in this crate. It also defines macros,
//! `bterr!` and `btensure!`. The first accepts either a type which is
//! `StdError + Send + Sync + 'static` or the same arguments as `format!`, allowing you to create
//! one-off string errors. `btensure` takes a boolean expression as its first argument, and its
//! remaining arguments are the same as those to `bterr`.

use anyhow::anyhow;
use serde::{Deserialize, Serialize};
use std::{fmt::Display, io};

use crate::Decompose;

/// Creates a new [Error], which contains a stacktrace captured at the point where this macro
/// was evaluated.
#[macro_export]
macro_rules! bterr {
    ($msg:literal $(,)?) => { $crate::Error::new(anyhow::anyhow!($msg)) };
    ($err:expr $(,)?) => { $crate::Error::new(anyhow::anyhow!($err)) };
    ($fmt:expr, $($arg:tt)*) => { $crate::Error::new(anyhow::anyhow!($fmt, $($arg)*)) };
}

/// Ensures that an expression evaluates to true, and if it does'nt, returns an error.
#[macro_export]
macro_rules! btensure {
    ($cond:expr, $msg:literal $(,)?) => {
        if !cond {
            return Err($crate::bterr!($msg));
        }
    };
    ($cond:expr, $err:expr $(,)?) => {
        if !$cond {
            return Err($crate::bterr!($err));
        }
    };
    ($cond:expr, $fmt:expr, $($arg:tt)*) => {
        if !cond {
            return Err($crate::bterr!($msg, $($arg)*));
        }
    };
}

/// Attempts to unwrap the given result.
/// If the result is an error and the given count is positive, then the error is logged and
/// `Ok($count)` is returned.
/// If the result is an error and count is zero, then the `Err` variant is returned
/// containing it.
#[macro_export]
macro_rules! suppress_err_if_non_zero {
    ($count:expr, $result:expr) => {
        match $result {
            Ok(output) => output,
            Err(err) => {
                if $count > 0 {
                    error!("{err}");
                    return Ok($count);
                } else {
                    return Err(err.into());
                }
            }
        }
    };
}

/// The common result type used by the Blocktree crates.
pub type Result<T> = std::result::Result<T, Error>;

/// The top-level error type used by this crate. This is just a newtype wrapper around
/// [anyhow::Error]. A newtype is used so that additional traits can be defined
/// (most importantly `From<Error> for std::io::Error`).
#[derive(Debug)]
pub struct Error(anyhow::Error);

impl Error {
    pub fn new(err: anyhow::Error) -> Self {
        Self(err)
    }

    pub fn map<T>(result: ::anyhow::Result<T>) -> Result<T> {
        result.map_err(Error::new)
    }

    pub fn downcast<E: std::error::Error + Send + Sync + 'static>(
        self,
    ) -> std::result::Result<E, Self> {
        self.0.downcast::<E>().map_err(Self::new)
    }

    pub fn context<C: Display + Send + Sync + 'static>(self, context: C) -> Self {
        Self::new(self.0.context(context))
    }

    pub fn downcast_ref<E: Display + ::std::fmt::Debug + Send + Sync + 'static>(
        &self,
    ) -> Option<&E> {
        self.0.downcast_ref::<E>()
    }

    pub fn downcast_mut<E: Display + ::std::fmt::Debug + Send + Sync + 'static>(
        &mut self,
    ) -> Option<&mut E> {
        self.0.downcast_mut::<E>()
    }
}

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

impl AsRef<anyhow::Error> for Error {
    fn as_ref(&self) -> &anyhow::Error {
        &self.0
    }
}

impl AsMut<anyhow::Error> for Error {
    fn as_mut(&mut self) -> &mut anyhow::Error {
        &mut self.0
    }
}

impl Decompose<anyhow::Error> for Error {
    fn into_inner(self) -> anyhow::Error {
        self.0
    }
}

impl From<Error> for io::Error {
    fn from(value: Error) -> Self {
        let kind = value
            .0
            .downcast_ref::<io::ErrorKind>()
            .copied()
            .unwrap_or(io::ErrorKind::Other);
        io::Error::new(kind, format!("{value}"))
    }
}

impl<E: std::error::Error + Send + Sync + 'static> From<E> for Error {
    fn from(value: E) -> Self {
        Self::new(anyhow!(value))
    }
}

/// A wrapper for `String` which implements `std::error::Error`.
#[derive(Debug, PartialEq, Eq, Clone, PartialOrd, Ord, Serialize, Deserialize, Hash)]
pub struct StringError(String);

impl StringError {
    pub fn new(inner: String) -> StringError {
        Self(inner)
    }

    pub fn take_value(self) -> String {
        self.0
    }

    pub fn ref_value(&self) -> &String {
        &self.0
    }

    pub fn mut_value(&mut self) -> &mut String {
        &mut self.0
    }
}

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

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

impl From<String> for StringError {
    fn from(value: String) -> Self {
        Self::new(value)
    }
}

impl From<StringError> for String {
    fn from(value: StringError) -> Self {
        value.take_value()
    }
}

impl AsRef<String> for StringError {
    fn as_ref(&self) -> &String {
        self.ref_value()
    }
}

impl AsMut<String> for StringError {
    fn as_mut(&mut self) -> &mut String {
        self.mut_value()
    }
}

pub trait BtErr<T> {
    /// Maps the error in the given result to a `btlib::Error`.
    fn bterr(self) -> Result<T>;
}

impl<T, E: ::std::error::Error + Send + Sync + 'static> BtErr<T> for ::std::result::Result<T, E> {
    fn bterr(self) -> Result<T> {
        self.map_err(|err| bterr!(err))
    }
}

pub trait AnyhowErrorExt<T> {
    fn bterr(self) -> Result<T>;
}

impl<T> AnyhowErrorExt<T> for anyhow::Result<T> {
    fn bterr(self) -> Result<T> {
        self.map_err(|err| bterr!(err))
    }
}

pub trait IoErr<T> {
    /// Maps the error in this result to an `io::Error`.
    fn io_err(self) -> io::Result<T>;
}

impl<T> IoErr<T> for Result<T> {
    fn io_err(self) -> io::Result<T> {
        self.map_err(|err| err.into())
    }
}

pub trait DisplayErr<T> {
    /// Uses the `Display` trait to convert the error in a `Result` to a string.
    fn display_err(self) -> Result<T>;
}

impl<T, E: Display> DisplayErr<T> for std::result::Result<T, E> {
    fn display_err(self) -> Result<T> {
        self.map_err(|err| bterr!("{err}"))
    }
}

pub trait BoxInIoErr<T> {
    /// Boxes the error in a `Result` into an `io::Error`.
    fn box_err(self) -> std::result::Result<T, io::Error>;
}

impl<T, E: std::error::Error + Send + Sync + 'static> BoxInIoErr<T> for std::result::Result<T, E> {
    fn box_err(self) -> std::result::Result<T, io::Error> {
        self.map_err(|err| bterr!(err).into())
    }
}