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
254
255
256
257
258
259
#![cfg_attr(nightly, feature(backtrace))]
#![cfg_attr(nightly, feature(no_coverage))]

use std::{
    borrow::Cow,
    fmt::{self, Debug, Display},
    ops::{Deref, DerefMut},
    str::FromStr,
};

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

use mdsn::DsnError;

macro_rules! _impl_fmt {
    ($fmt:ident) => {
        impl fmt::$fmt for Code {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                fmt::$fmt::fmt(&self.0, f)
            }
        }
    };
}

_impl_fmt!(LowerHex);
_impl_fmt!(UpperHex);

/// TDengine error code.
#[derive(Clone, Copy, Eq, PartialEq, Hash, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[repr(transparent)]
pub struct Code(i32);

impl Code {
    pub const COLUMN_EXISTS: Code = Code(0x036B);
    pub const COLUMN_NOT_EXIST: Code = Code(0x036C);
    pub const TAG_ALREADY_EXIST: Code = Code(0x0369);
    pub const TAG_NOT_EXIST: Code = Code(0x036A);
    pub const MODIFIED_ALREADY: Code = Code(0x264B);
    pub const INVALID_COLUMN_NAME: Code = Code(0x2602);
    pub const TABLE_NOT_EXIST: Code = Code(0x2603);
    pub const STABLE_NOT_EXIST: Code = Code(0x0362);
    pub const INVALID_ROW_BYTES: Code = Code(0x036F);
    pub const DUPLICATED_COLUMN_NAMES: Code = Code(0x263C);
    pub const NO_COLUMN_CAN_BE_DROPPED: Code = Code(0x2651);
}

impl Display for Code {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_fmt(format_args!("{:#06X}", *self))
    }
}

impl Debug for Code {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_fmt(format_args!(
            "Code([{:#06X}] {})",
            self.0,
            self.as_error_str()
        ))
    }
}

macro_rules! _impl_from {
    ($($from:ty) *) => {
        $(
            impl From<$from> for Code {
                #[inline]
                fn from(c: $from) -> Self {
                    Self(c as i32 & 0xFFFF)
                }
            }
            impl From<Code> for $from {
                #[inline]
                fn from(c: Code) -> Self {
                    c.0 as _
                }
            }
        )*
    };
}

_impl_from!(i8 u8 i16 i32 u16 u32 i64 u64);

impl Deref for Code {
    type Target = i32;

    fn deref(&self) -> &i32 {
        &self.0
    }
}

impl DerefMut for Code {
    fn deref_mut(&mut self) -> &mut i32 {
        &mut self.0
    }
}

impl Code {
    /// Code from raw primitive type.
    pub const fn new(code: i32) -> Self {
        Code(code)
    }
}

impl PartialEq<usize> for Code {
    fn eq(&self, other: &usize) -> bool {
        self.0 == *other as i32
    }
}

impl PartialEq<isize> for Code {
    fn eq(&self, other: &isize) -> bool {
        self.0 == *other as i32
    }
}

impl PartialEq<i32> for Code {
    fn eq(&self, other: &i32) -> bool {
        self.0 == *other
    }
}

#[allow(non_upper_case_globals, non_snake_case)]
#[cfg_attr(feature = "no_coverage", no_coverage)]
mod code {
    include!(concat!(env!("OUT_DIR"), "/code.rs"));
}

#[derive(Debug, thiserror::Error)]
pub struct Error {
    code: Code,
    err: Cow<'static, str>,
    #[cfg(nightly)]
    backtrace: Backtrace,
}

impl From<DsnError> for Error {
    fn from(dsn: DsnError) -> Self {
        Self::new(Code::Failed, dsn.to_string())
    }
}

pub type Result<T> = std::result::Result<T, Error>;

impl Error {
    #[inline]
    pub fn new(code: impl Into<Code>, err: impl Into<Cow<'static, str>>) -> Self {
        Self {
            code: code.into(),
            err: err.into(),
            #[cfg(nightly)]
            #[cfg_attr(nightly, no_coverage)]
            backtrace: Backtrace::capture(),
        }
    }

    #[inline]
    pub fn errno(&self) -> Code {
        self.code
    }

    #[inline]
    pub const fn code(&self) -> Code {
        self.code
    }
    #[inline]
    pub fn message(&self) -> &str {
        &self.err
    }

    #[inline]
    pub fn from_code(code: impl Into<Code>) -> Self {
        Self::new(code, "")
    }

    #[inline]
    pub fn from_string(err: impl Into<Cow<'static, str>>) -> Self {
        Self::new(Code::Failed, err)
    }

    #[inline]
    pub fn from_any(err: impl Display) -> Self {
        Self::new(Code::Failed, err.to_string())
    }
}

impl FromStr for Error {
    type Err = ();

    #[inline]
    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        Ok(Self::from_string(s.to_string()))
    }
}

impl Display for Error {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.code == Code::Failed {
            write!(f, "{}", self.err)
        } else {
            write!(f, "[{:#06X}] {}", self.code, self.err)
        }
    }
}

#[cfg(feature = "serde")]
impl serde::de::Error for Error {
    #[inline]
    fn custom<T: fmt::Display>(msg: T) -> Error {
        Error::from_string(format!("{}", msg))
    }
}

#[test]
fn test_code() {
    let c: i32 = Code::new(0).into();
    assert_eq!(c, 0);
    let c = Code::from(0).to_string();
    assert_eq!(c, "0x0000");
    dbg!(Code::from(0x200));

    let c: i8 = Code::new(0).into();
    let mut c: Code = c.into();

    let _: &i32 = c.deref();
    let _: &mut i32 = c.deref_mut();
}

#[test]
fn test_display() {
    let err = Error::new(Code::Success, "Success");
    assert_eq!(format!("{err}"), "[0x0000] Success");
    let err = Error::new(Code::Failed, "failed");
    assert_eq!(format!("{err}"), "failed");
}

#[test]
fn test_error() {
    let err = Error::new(Code::Success, "success");
    assert_eq!(err.code(), err.errno());
    assert_eq!(err.message(), "success");

    let _ = Error::from_code(1);
    assert_eq!(Error::from_any("any").to_string(), "any");
    assert_eq!(Error::from_string("any").to_string(), "any");

    let _ = Error::from(DsnError::InvalidDriver("".to_string()));
}

#[cfg(feature = "serde")]
#[test]
fn test_serde_error() {
    use serde::de::Error as DeError;

    let _ = Error::custom("");
}