font_map_core/
error.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
//! Error type and related utilities

/// Result type for parsing
pub type ParseResult<T> = Result<T, ParseError>;

/// Error type for parsing errors
#[derive(Debug)]
pub enum ParseError {
    /// Unexpected EOF while parsing
    UnexpectedEof {
        /// Byte position of the error in the data
        pos: usize,

        /// Number of bytes expected
        size: usize,

        /// Description of the error
        desc: Option<&'static str>,
    },

    /// Invalid value while parsing
    InvalidValue {
        /// Byte position of the error in the data
        pos: usize,

        /// The invalid value
        value: u32,

        /// Name of the value being parsed
        name: &'static str,
    },

    /// Error while parsing
    Parse {
        /// Byte position of the error in the data
        pos: usize,

        /// Error message
        message: String,
    },

    /// IO Error
    Io(std::io::Error),
}
impl ParseError {
    /// Returns a new error with the given description
    #[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)
    }
}