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
use core::fmt::{Debug, Display, Formatter, Result};

use crate::prelude::*;

/// This wraps an actual backtrace to achieve two things:
/// - being able to fill this with a stub implementation in `no_std` environments
/// - being able to use this in conjunction with [`thiserror::Error`]
pub struct BT(Box<dyn Printable + Sync + Send>);

impl BT {
    #[track_caller]
    pub fn capture() -> Self {
        // in case of no_std, we can fill with a stub here
        #[cfg(feature = "std")]
        {
            #[cfg(target_arch = "wasm32")]
            return BT(Box::new(std::backtrace::Backtrace::disabled()));
            #[cfg(not(target_arch = "wasm32"))]
            return BT(Box::new(std::backtrace::Backtrace::capture()));
        }
        #[cfg(not(feature = "std"))]
        {
            BT(Box::new(Stub))
        }
    }
}

trait Printable: Debug + Display {}
impl<T> Printable for T where T: Debug + Display {}

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

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

#[allow(unused)]
struct Stub;

impl Debug for Stub {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
        write!(f, "<disabled>")
    }
}

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

/// This macro implements `From` for a given error type to a given error type where
/// the target error has a `backtrace` field.
/// This is meant as a replacement for `thiserror`'s `#[from]` attribute, which does not
/// work with our custom backtrace wrapper.
macro_rules! impl_from_err {
    ($from:ty, $to:ty, $map:path) => {
        impl From<$from> for $to {
            fn from(err: $from) -> Self {
                $map {
                    source: err,
                    backtrace: $crate::errors::backtrace::BT::capture(),
                }
            }
        }
    };
}
pub(crate) use impl_from_err;

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

    #[test]
    fn bt_works_without_std() {
        #[derive(Debug)]
        struct BacktraceStub;

        impl Display for BacktraceStub {
            fn fmt(&self, _f: &mut Formatter<'_>) -> Result {
                Ok(())
            }
        }

        _ = BT(Box::new(BacktraceStub));
    }
}