use alloc::string::String;
use core::fmt;
pub type Result<T> = core::result::Result<T, Error>;
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Error {
UnexpectedEof {
what: &'static str,
},
UnexpectedByte {
byte: u8,
offset: usize,
what: &'static str,
},
InvalidNumber {
text: String,
},
Malformed {
what: &'static str,
offset: Option<usize>,
},
Io {
message: String,
},
}
impl Error {
pub const fn unexpected_eof(what: &'static str) -> Self {
Self::UnexpectedEof { what }
}
pub const fn malformed(what: &'static str) -> Self {
Self::Malformed { what, offset: None }
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::UnexpectedEof { what } => {
write!(f, "unexpected end of input while reading {what}")
}
Self::UnexpectedByte { byte, offset, what } => write!(
f,
"unexpected byte {byte:#04X} at offset {offset} while reading {what}"
),
Self::InvalidNumber { text } => write!(f, "invalid number {text:?}"),
Self::Malformed {
what,
offset: Some(offset),
} => write!(f, "malformed {what} at offset {offset}"),
Self::Malformed { what, offset: None } => write!(f, "malformed {what}"),
Self::Io { message } => write!(f, "i/o error: {message}"),
}
}
}
impl core::error::Error for Error {}
#[cfg(feature = "std")]
impl From<std::io::Error> for Error {
fn from(error: std::io::Error) -> Self {
Self::Io {
message: error.to_string(),
}
}
}
#[cfg(test)]
mod tests {
use super::Error;
#[test]
fn display_names_the_construct() {
assert_eq!(
Error::unexpected_eof("number").to_string(),
"unexpected end of input while reading number"
);
assert_eq!(
Error::Malformed {
what: "xref table",
offset: Some(12),
}
.to_string(),
"malformed xref table at offset 12"
);
assert_eq!(Error::malformed("stream").to_string(), "malformed stream");
}
#[test]
fn unexpected_byte_is_reported_in_hex() {
assert_eq!(
Error::UnexpectedByte {
byte: 0x0A,
offset: 3,
what: "name",
}
.to_string(),
"unexpected byte 0x0A at offset 3 while reading name"
);
}
}