macbinary/
error.rs

1//! Error types
2
3use core::fmt;
4
5use crate::binary::read::ReadEof;
6
7/// Errors that originate when parsing binary data
8#[derive(Clone, Eq, PartialEq, Debug)]
9pub enum ParseError {
10    /// EOF was reached unexpectedly
11    BadEof,
12    /// A value was outside the expected range
13    BadValue,
14    /// A version field contained an unsupported version
15    BadVersion,
16    /// An offset was outside allowed bounds
17    BadOffset,
18    /// An index was outside the valid range
19    BadIndex,
20    /// A value overflowed its storage type
21    Overflow,
22    /// CRC did not match expected value
23    CrcMismatch,
24}
25
26impl From<ReadEof> for ParseError {
27    fn from(_error: ReadEof) -> Self {
28        ParseError::BadEof
29    }
30}
31
32impl From<core::num::TryFromIntError> for ParseError {
33    fn from(_error: core::num::TryFromIntError) -> Self {
34        ParseError::BadValue
35    }
36}
37
38impl fmt::Display for ParseError {
39    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
40        match self {
41            ParseError::BadEof => write!(f, "end of data reached unexpectedly"),
42            ParseError::BadValue => write!(f, "invalid value"),
43            ParseError::BadVersion => write!(f, "unexpected data version"),
44            ParseError::BadOffset => write!(f, "invalid data offset"),
45            ParseError::BadIndex => write!(f, "invalid data index"),
46            ParseError::Overflow => write!(f, "a value overflowed its range"),
47            ParseError::CrcMismatch => write!(f, "CRC mismatch"),
48        }
49    }
50}
51
52// FIXME: Enable on no_std when https://github.com/rust-lang/rust/issues/103765 is stable
53#[cfg(not(feature = "no_std"))]
54impl std::error::Error for ParseError {}