Skip to main content

i8051_disassembler/store/
error.rs

1use std::fmt;
2
3#[derive(Debug, Clone, PartialEq, Eq)]
4pub struct DslError {
5    pub message: String,
6    /// The byte offset where a positional parse error occurred. `None` for
7    /// structural/validation errors (e.g. a missing field) that aren't tied to
8    /// a spot in the input.
9    pub offset: Option<usize>,
10}
11
12impl DslError {
13    /// A positional error: something went wrong at a specific byte of input.
14    pub fn at(offset: usize, message: impl Into<String>) -> Self {
15        Self {
16            message: message.into(),
17            offset: Some(offset),
18        }
19    }
20
21    /// A non-positional error: a structural or validation failure with no
22    /// meaningful location in the input (e.g. a missing field).
23    pub fn new(message: impl Into<String>) -> Self {
24        Self {
25            message: message.into(),
26            offset: None,
27        }
28    }
29}
30
31impl fmt::Display for DslError {
32    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
33        match self.offset {
34            Some(offset) => write!(f, "dsl parse error at byte {offset}: {}", self.message),
35            None => write!(f, "dsl error: {}", self.message),
36        }
37    }
38}
39
40impl std::error::Error for DslError {}
41
42impl serde::ser::Error for DslError {
43    fn custom<T: fmt::Display>(msg: T) -> Self {
44        Self::new(msg.to_string())
45    }
46}
47
48impl serde::de::Error for DslError {
49    fn custom<T: fmt::Display>(msg: T) -> Self {
50        Self::new(msg.to_string())
51    }
52}