font_map_core/
error.rs

1//! Error type and related utilities
2
3/// Result type for parsing
4pub type ParseResult<T> = Result<T, ParseError>;
5
6/// Error type for parsing errors
7#[derive(Debug)]
8pub enum ParseError {
9    /// Unexpected EOF while parsing
10    UnexpectedEof {
11        /// Byte position of the error in the data
12        pos: usize,
13
14        /// Number of bytes expected
15        size: usize,
16
17        /// Description of the error
18        desc: Option<&'static str>,
19    },
20
21    /// Invalid value while parsing
22    InvalidValue {
23        /// Byte position of the error in the data
24        pos: usize,
25
26        /// The invalid value
27        value: u32,
28
29        /// Name of the value being parsed
30        name: &'static str,
31    },
32
33    /// Error while parsing
34    Parse {
35        /// Byte position of the error in the data
36        pos: usize,
37
38        /// Error message
39        message: String,
40    },
41
42    /// IO Error
43    Io(std::io::Error),
44}
45impl ParseError {
46    /// Returns a new error with the given description
47    #[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}