pub type ParseResult<T> = Result<T, ParseError>;
#[derive(Debug)]
pub enum ParseError {
UnexpectedEof {
pos: usize,
size: usize,
desc: Option<&'static str>,
},
InvalidValue {
pos: usize,
value: u32,
name: &'static str,
},
Parse {
pos: usize,
message: String,
},
Io(std::io::Error),
}
impl ParseError {
#[must_use]
pub fn with_desc(self, desc: &'static str) -> ParseError {
match self {
ParseError::UnexpectedEof { pos, size, .. } => ParseError::UnexpectedEof {
pos,
size,
desc: Some(desc),
},
other => other,
}
}
}
impl std::error::Error for ParseError {}
impl std::fmt::Display for ParseError {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
ParseError::UnexpectedEof {
pos,
size,
desc: Some(desc),
} => {
write!(
f,
"Unexpected EOF trying to read {size} bytes from {pos} while parsing {desc}"
)
}
ParseError::UnexpectedEof { pos, size, .. } => {
write!(f, "Unexpected EOF trying to read {size} bytes from {pos}")
}
ParseError::InvalidValue { pos, value, name } => {
write!(f, "Invalid value {value:#0x} at {pos} while parsing {name}")
}
ParseError::Parse { pos, message } => {
write!(f, "Error at {pos}: {message}")
}
ParseError::Io(err) => {
write!(f, "IO Error: {err:#}")
}
}
}
}
impl From<std::io::Error> for ParseError {
fn from(err: std::io::Error) -> ParseError {
ParseError::Io(err)
}
}