1pub type ParseResult<T> = Result<T, ParseError>;
5
6#[derive(Debug)]
8pub enum ParseError {
9 UnexpectedEof {
11 pos: usize,
13
14 size: usize,
16
17 desc: Option<&'static str>,
19 },
20
21 InvalidValue {
23 pos: usize,
25
26 value: u32,
28
29 name: &'static str,
31 },
32
33 Parse {
35 pos: usize,
37
38 message: String,
40 },
41
42 Io(std::io::Error),
44}
45impl ParseError {
46 #[must_use]
48 pub fn with_desc(self, desc: &'static str) -> ParseError {
49 match self {
50 ParseError::UnexpectedEof { pos, size, .. } => ParseError::UnexpectedEof {
51 pos,
52 size,
53 desc: Some(desc),
54 },
55 other => other,
56 }
57 }
58}
59impl std::error::Error for ParseError {}
60impl std::fmt::Display for ParseError {
61 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
62 match self {
63 ParseError::UnexpectedEof {
64 pos,
65 size,
66 desc: Some(desc),
67 } => {
68 write!(
69 f,
70 "Unexpected EOF trying to read {size} bytes from {pos} while parsing {desc}"
71 )
72 }
73 ParseError::UnexpectedEof { pos, size, .. } => {
74 write!(f, "Unexpected EOF trying to read {size} bytes from {pos}")
75 }
76 ParseError::InvalidValue { pos, value, name } => {
77 write!(f, "Invalid value {value:#0x} at {pos} while parsing {name}")
78 }
79 ParseError::Parse { pos, message } => {
80 write!(f, "Error at {pos}: {message}")
81 }
82 ParseError::Io(err) => {
83 write!(f, "IO Error: {err:#}")
84 }
85 }
86 }
87}
88
89impl From<std::io::Error> for ParseError {
90 fn from(err: std::io::Error) -> ParseError {
91 ParseError::Io(err)
92 }
93}