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
use std::fmt;

#[cfg(feature = "backtrace")]
use backtrace::Backtrace;
use thiserror::Error;

//use crate::types::ProtocolVersion;

/// This crate specific `Result` type.
pub type Result<T> = std::result::Result<T, Error>;

#[derive(Debug, Error, Clone, PartialEq)]
#[non_exhaustive]
enum ErrorKind {
    #[error("a value is missing for the attribute {value}")]
    MissingValue { value: String },

    #[error("invalid input")]
    InvalidInput,

    #[error("{source}: {input:?}")]
    ParseIntError {
        input: String,
        source: ::std::num::ParseIntError,
    },

    #[error("{source}: {input:?}")]
    ParseFloatError {
        input: String,
        source: ::std::num::ParseFloatError,
    },

    #[error("expected `{tag}` at the start of {input:?}")]
    MissingTag {
        /// The required tag.
        tag: String,
        /// The unparsed input data.
        input: String,
    },

    #[error("{0}")]
    Custom(String),

    #[error("unmatched group: {0:?}")]
    UnmatchedGroup(String),

    #[error("unknown protocol version {0:?}")]
    UnknownProtocolVersion(String),

    // #[error("required_version: {:?}, specified_version: {:?}", _0, _1)]
    // VersionError(ProtocolVersion, ProtocolVersion),
    #[error("missing attribute: {attribute:?}")]
    MissingAttribute { attribute: String },

    #[error("unexpected attribute: {attribute:?}")]
    UnexpectedAttribute { attribute: String },

    #[error("unexpected tag: {tag:?}")]
    UnexpectedTag { tag: String },

    #[error("{source}")]
    #[cfg(feature = "chrono")]
    Chrono { source: chrono::ParseError },

    #[error("builder error: {message}")]
    Builder { message: String },

    #[error("{source}")]
    Hex { source: hex::FromHexError },
}

/// The Error type of this library.
#[derive(Debug)]
pub struct Error {
    inner: ErrorKind,
    #[cfg(feature = "backtrace")]
    backtrace: Backtrace,
}

impl PartialEq for Error {
    fn eq(&self, other: &Self) -> bool { self.inner == other.inner }
}

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

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

#[allow(clippy::needless_pass_by_value)]
impl Error {
    fn new(inner: ErrorKind) -> Self {
        Self {
            inner,
            #[cfg(feature = "backtrace")]
            backtrace: Backtrace::new(),
        }
    }

    pub(crate) fn custom<T: fmt::Display>(value: T) -> Self {
        Self::new(ErrorKind::Custom(value.to_string()))
    }

    pub(crate) fn missing_value<T: ToString>(value: T) -> Self {
        Self::new(ErrorKind::MissingValue {
            value: value.to_string(),
        })
    }

    pub(crate) fn missing_field<T: fmt::Display, D: fmt::Display>(strct: D, field: T) -> Self {
        Self::new(ErrorKind::Custom(format!(
            "the field `{}` is missing for `{}`",
            field, strct
        )))
    }

    pub(crate) fn unexpected_attribute<T: ToString>(value: T) -> Self {
        Self::new(ErrorKind::UnexpectedAttribute {
            attribute: value.to_string(),
        })
    }

    pub(crate) fn unexpected_tag<T: ToString>(value: T) -> Self {
        Self::new(ErrorKind::UnexpectedTag {
            tag: value.to_string(),
        })
    }

    pub(crate) fn invalid_input() -> Self { Self::new(ErrorKind::InvalidInput) }

    pub(crate) fn parse_int<T: fmt::Display>(input: T, source: ::std::num::ParseIntError) -> Self {
        Self::new(ErrorKind::ParseIntError {
            input: input.to_string(),
            source,
        })
    }

    pub(crate) fn parse_float<T: fmt::Display>(
        input: T,
        source: ::std::num::ParseFloatError,
    ) -> Self {
        Self::new(ErrorKind::ParseFloatError {
            input: input.to_string(),
            source,
        })
    }

    pub(crate) fn missing_tag<T, U>(tag: T, input: U) -> Self
    where
        T: ToString,
        U: ToString,
    {
        Self::new(ErrorKind::MissingTag {
            tag: tag.to_string(),
            input: input.to_string(),
        })
    }

    pub(crate) fn unmatched_group<T: ToString>(value: T) -> Self {
        Self::new(ErrorKind::UnmatchedGroup(value.to_string()))
    }

    pub(crate) fn unknown_protocol_version<T: ToString>(value: T) -> Self {
        Self::new(ErrorKind::UnknownProtocolVersion(value.to_string()))
    }

    pub(crate) fn builder<T: ToString>(value: T) -> Self {
        Self::new(ErrorKind::Builder {
            message: value.to_string(),
        })
    }

    pub(crate) fn missing_attribute<T: ToString>(value: T) -> Self {
        Self::new(ErrorKind::MissingAttribute {
            attribute: value.to_string(),
        })
    }

    pub(crate) fn unexpected_data(value: &str) -> Self {
        Self::custom(format!("Unexpected data in the line: {:?}", value))
    }

    // third party crates:
    #[cfg(feature = "chrono")]
    pub(crate) fn chrono(source: chrono::format::ParseError) -> Self {
        Self::new(ErrorKind::Chrono { source })
    }

    pub(crate) fn hex(source: hex::FromHexError) -> Self {
        //
        Self::new(ErrorKind::Hex { source })
    }

    pub(crate) fn strum(value: strum::ParseError) -> Self {
        Self::new(ErrorKind::Custom(value.to_string()))
    }
}

#[doc(hidden)]
impl From<::strum::ParseError> for Error {
    fn from(value: ::strum::ParseError) -> Self { Self::strum(value) }
}

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

    #[test]
    fn test_parse_float_error() {
        assert_eq!(
            Error::parse_float(
                "1.x234",
                "1.x234"
                    .parse::<f32>()
                    .expect_err("this should not parse as a float!")
            )
            .to_string(),
            "invalid float literal: \"1.x234\"".to_string()
        );
    }

    #[test]
    fn test_parse_int_error() {
        assert_eq!(
            Error::parse_int(
                "1x",
                "1x".parse::<usize>()
                    .expect_err("this should not parse as an usize!")
            )
            .to_string(),
            "invalid digit found in string: \"1x\"".to_string()
        );
    }
}