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
use std::{borrow::Cow, fmt::Debug, ops::Deref};

#[cfg(nightly)]
use std::backtrace::Backtrace;

use thiserror::Error;

/// Inner error source.
#[derive(Error)]
pub(super) enum Inner {
    /// Raw error message from taos C library.
    #[error("")]
    Empty {
        #[cfg(nightly)]
        backtrace: Backtrace,
    },
    /// Raw error message from taos C library.
    #[error("Internal error: `{}`", .raw)]
    Raw {
        raw: Cow<'static, str>,
        #[cfg(nightly)]
        backtrace: Backtrace,
    },
    /// Source error from other kinds of errors.
    ///
    /// All `std::error::Error`s will be stored as an [anyhow::Error].
    #[error(transparent)]
    Any(#[from] anyhow::Error),
}

impl Clone for Inner {
    fn clone(&self) -> Self {
        match self {
            Self::Empty { .. } => Self::Empty {
                #[cfg(nightly)]
                backtrace: Backtrace::force_capture(),
            },
            Self::Raw { raw, .. } => Self::Raw {
                raw: raw.clone(),
                #[cfg(nightly)]
                backtrace: Backtrace::force_capture(),
            },
            Self::Any(any) => Self::Any(anyhow::format_err!("{:#}", any)),
        }
    }
}

impl Debug for Inner {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Empty { .. } => write!(f, "{:?}", ()),
            Self::Raw { raw, .. } => write!(f, "{:#?}", raw.as_ref()),
            Self::Any(any) => f.debug_tuple("Any").field(any).finish(),
        }
    }
}

impl From<&'static str> for Inner {
    #[inline(always)]
    fn from(value: &'static str) -> Self {
        Self::raw(value.into())
    }
}

impl From<String> for Inner {
    #[inline(always)]
    fn from(value: String) -> Self {
        Self::raw(value.into())
    }
}

impl<'c> From<&'c std::ffi::CStr> for Inner {
    #[inline(always)]
    fn from(value: &'c std::ffi::CStr) -> Self {
        Self::raw(value.to_string_lossy().to_string().into())
    }
}
impl From<std::ffi::CString> for Inner {
    #[inline(always)]
    fn from(value: std::ffi::CString) -> Self {
        Self::raw(value.to_string_lossy().to_string().into())
    }
}

impl Inner {
    /// Empty empty with backtrace only
    pub fn empty() -> Self {
        Inner::Empty {
            #[cfg(nightly)]
            backtrace: Backtrace::force_capture(),
        }
    }

    /// Raw message
    pub fn raw(raw: Cow<'static, str>) -> Self {
        Inner::Raw {
            raw,
            #[cfg(nightly)]
            backtrace: Backtrace::force_capture(),
        }
    }

    pub fn any(error: anyhow::Error) -> Self {
        Inner::Any(error)
    }

    pub fn is_empty(&self) -> bool {
        matches!(self, Self::Empty { .. })
    }

    #[cfg(nightly)]
    #[inline(always)]
    pub fn backtrace(&self) -> &Backtrace {
        match self {
            Inner::Empty { backtrace } => backtrace,
            Inner::Raw {
                raw: _,
                #[cfg(nightly)]
                backtrace,
            } => backtrace,
            Inner::Any(any) => any.backtrace(),
        }
    }

    pub fn chain(&self) -> Chain {
        match self {
            Inner::Empty { .. } => Chain::Empty,
            Inner::Raw { raw, .. } => Chain::Raw([raw.deref()].into_iter()),
            Inner::Any(any) => Chain::Any(any.chain()),
        }
    }

    pub fn deep(&self) -> bool {
        match self {
            Inner::Empty { .. } => false,
            Inner::Raw { .. } => false,
            Inner::Any(any) => any.source().is_some(),
        }
    }
}

pub enum Chain<'a> {
    Empty,
    Raw(std::array::IntoIter<&'a str, 1>),
    Any(anyhow::Chain<'a>),
}
impl<'a> Iterator for Chain<'a> {
    type Item = Cow<'a, str>;

    fn next(&mut self) -> Option<Self::Item> {
        match self {
            Self::Empty => None,
            Chain::Raw(raw) => raw.next().map(Into::into),
            Chain::Any(chain) => chain.next().map(ToString::to_string).map(Into::into),
        }
    }
}
#[test]
fn test_inner() {
    let error = Inner::from(anyhow::anyhow!("error"));
    assert_eq!(error.to_string(), "error");
}