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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
use crate::model::Charset;
use backtrace::Backtrace;
use std::string::FromUtf8Error;

#[derive(Debug, Clone, PartialEq)]
pub struct Error(pub(crate) Box<Inner>);

impl Error {
    #[inline]
    pub fn kind(&self) -> &ErrorKind {
        &self.0.kind
    }

    #[cfg(feature = "descriptive-deserialize-errors")]
    pub fn scope_description(&self) -> &[crate::prelude::ScopeDescription] {
        &self.0.description[..]
    }
}

impl From<ErrorKind> for Error {
    #[cold]
    #[inline(never)]
    fn from(kind: ErrorKind) -> Self {
        Self(Box::new(Inner {
            kind,
            #[cfg(feature = "descriptive-deserialize-errors")]
            description: Vec::new(),
        }))
    }
}

impl std::fmt::Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0.kind)?;
        #[cfg(feature = "descriptive-deserialize-errors")]
        {
            use crate::syn::io::ScopeDescription;

            writeln!(f)?;
            let mut depth = 0;
            for desc in &self.0.description {
                let c = match desc {
                    ScopeDescription::Sequence { .. }
                    | ScopeDescription::SequenceOf { .. }
                    | ScopeDescription::Enumerated { .. }
                    | ScopeDescription::Choice { .. } => '+',
                    ScopeDescription::End(_) => {
                        depth -= 1;
                        '-'
                    }
                    _ => ' ',
                };

                writeln!(f, " {}{c} {desc:?}", "  ".repeat(depth))?;
                match desc {
                    ScopeDescription::Sequence { .. }
                    | ScopeDescription::SequenceOf { .. }
                    | ScopeDescription::Enumerated { .. }
                    | ScopeDescription::Choice { .. } => {
                        depth += 1;
                    }
                    _ => {}
                }
            }
        }
        Ok(())
    }
}

impl std::error::Error for Error {
    fn description(&self) -> &str {
        "encoding or decoding UPER failed"
    }
}

#[derive(Debug, Clone, PartialEq)]
pub(crate) struct Inner {
    pub(crate) kind: ErrorKind,
    #[cfg(feature = "descriptive-deserialize-errors")]
    pub(crate) description: Vec<crate::syn::io::ScopeDescription>,
}

#[derive(Debug, Clone)]
pub enum ErrorKind {
    FromUtf8Error(FromUtf8Error),
    InvalidString(Charset, char, usize),
    UnsupportedOperation(String),
    InsufficientSpaceInDestinationBuffer(Backtrace),
    InsufficientDataInSourceBuffer(Backtrace),
    LengthDeterminantExceedsLimit {
        length: usize,
        limit: usize,
        backtrace: Backtrace,
    },
    InvalidChoiceIndex(u64, u64),
    ExtensionFieldsInconsistent(String),
    ValueNotInRange(i64, i64, i64),
    ValueExceedsMaxInt,
    ValueIsNegativeButExpectedUnsigned(i64),
    SizeNotInRange(u64, u64, u64),
    BitLenNotInRange(u64, u64, u64),
    OptFlagsExhausted,
    EndOfStream,
}

impl Error {
    #[cold]
    #[inline(never)]
    pub fn ensure_string_valid(charset: Charset, str: &str) -> Result<(), Self> {
        match charset.find_invalid(str) {
            None => Ok(()),
            Some((index, char)) => Err(ErrorKind::InvalidString(charset, char, index).into()),
        }
    }

    #[cold]
    #[inline(never)]
    pub fn insufficient_space_in_destination_buffer() -> Self {
        ErrorKind::InsufficientSpaceInDestinationBuffer(Backtrace::new_unresolved()).into()
    }

    #[cold]
    #[inline(never)]
    pub fn insufficient_data_in_source_buffer() -> Self {
        ErrorKind::InsufficientDataInSourceBuffer(Backtrace::new_unresolved()).into()
    }

    #[cold]
    #[inline(never)]
    pub fn length_determinant_exceeds_limit(length: usize, limit: usize) -> Self {
        ErrorKind::LengthDeterminantExceedsLimit {
            length,
            limit,
            backtrace: Backtrace::new_unresolved(),
        }
        .into()
    }
}

impl std::fmt::Display for ErrorKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::FromUtf8Error(err) => {
                write!(f, "Failed to call String::from_utf8: ")?;
                err.fmt(f)
            }
            Self::InvalidString(charset, char, index) => {
                write!(
                    f,
                    "Invalid character for a string with the charset {:?} at index {}: {}",
                    charset, index, char
                )
            }
            Self::UnsupportedOperation(o) => write!(f, "The operation is not supported: {}", o),
            Self::InsufficientSpaceInDestinationBuffer(backtrace) => write!(
                f,
                "There is insufficient space in the destination buffer for this operation:\n{:?}",
                {
                    let mut b = backtrace.clone();
                    b.resolve();
                    b
                }
            ),
            Self::InsufficientDataInSourceBuffer(backtrace) => write!(
                f,
                "There is insufficient data in the source buffer for this operation:\n{:?}",
                {
                    let mut b = backtrace.clone();
                    b.resolve();
                    b
                }
            ),
            ErrorKind::LengthDeterminantExceedsLimit {
                length,
                limit,
                backtrace,
            } => {
                write!(
                    f,
                    "The read length determinant exceeds the byte limit of {} with the value {}:\n{:?}",
                    limit, length,
                    {
                        let mut b = backtrace.clone();
                        b.resolve();
                        b
                    }
                )
            }
            Self::InvalidChoiceIndex(index, variant_count) => write!(
                f,
                "Unexpected choice-index {} with variant count {}",
                index, variant_count
            ),
            Self::ExtensionFieldsInconsistent(name) => {
                write!(
                    f,
                    "The extension fields of {} are inconsistent, either all or none must be present",
                    name
                )
            }
            Self::ValueNotInRange(value, min, max) => write!(
                f,
                "The value {} is not within the inclusive range of {} and {}",
                value, min, max
            ),
            Self::ValueExceedsMaxInt => {
                write!(f, "The value exceeds the maximum supported integer size",)
            }
            Self::ValueIsNegativeButExpectedUnsigned(value) => write!(
                f,
                "The value {} is negative, but expected an unsigned/positive value",
                value
            ),
            Self::SizeNotInRange(size, min, max) => write!(
                f,
                "The size {} is not within the inclusive range of {} and {}",
                size, min, max
            ),
            Self::BitLenNotInRange(size, min, max) => write!(
                f,
                "The length {} is not within the inclusive range of {} and {} for a bit field",
                size, min, max
            ),
            Self::OptFlagsExhausted => write!(f, "All optional flags have already been exhausted"),
            Self::EndOfStream => write!(
                f,
                "Can no longer read or write any bytes from the underlying dataset"
            ),
        }
    }
}

impl PartialEq for ErrorKind {
    fn eq(&self, other: &Self) -> bool {
        match self {
            Self::FromUtf8Error(a) => matches!(other, Self::FromUtf8Error(oa) if a == oa),
            Self::InvalidString(a, b, c) => {
                matches!(other, Self::InvalidString(oa, ob, oc) if (a, b, c) == (oa, ob, oc))
            }
            Self::UnsupportedOperation(a) => {
                matches!(other, Self::UnsupportedOperation(oa) if a == oa)
            }
            Self::InsufficientSpaceInDestinationBuffer(_) => {
                matches!(other, Self::InsufficientSpaceInDestinationBuffer(_))
            }
            Self::InsufficientDataInSourceBuffer(_) => {
                matches!(other, Self::InsufficientDataInSourceBuffer(_))
            }
            Self::LengthDeterminantExceedsLimit { length, limit, .. } => {
                matches!(other, Self::LengthDeterminantExceedsLimit { length: other_length, limit: other_limit, .. } if length == other_length && limit == other_limit)
            }
            Self::InvalidChoiceIndex(a, b) => {
                matches!(other, Self::InvalidChoiceIndex(oa, ob) if (a, b) == (oa, ob))
            }
            Self::ExtensionFieldsInconsistent(a) => {
                matches!(other, Self::ExtensionFieldsInconsistent(oa) if a == oa)
            }
            Self::ValueNotInRange(a, b, c) => {
                matches!(other, Self::ValueNotInRange(oa, ob, oc) if (a, b, c) == (oa, ob, oc))
            }
            Self::ValueExceedsMaxInt => matches!(other, Self::ValueExceedsMaxInt),
            Self::ValueIsNegativeButExpectedUnsigned(a) => {
                matches!(other, Self::ValueIsNegativeButExpectedUnsigned(oa) if a == oa)
            }
            Self::SizeNotInRange(a, b, c) => {
                matches!(other, Self::SizeNotInRange(oa, ob, oc) if (a,b ,c) == (oa, ob,oc))
            }
            Self::BitLenNotInRange(a, b, c) => {
                matches!(other, Self::BitLenNotInRange(oa, ob, oc) if (a,b ,c) == (oa, ob,oc))
            }
            Self::OptFlagsExhausted => matches!(other, Self::OptFlagsExhausted),
            Self::EndOfStream => matches!(other, Self::EndOfStream),
        }
    }
}