Skip to main content

bytepeel_core/
error.rs

1use std::fmt;
2
3/// A machine-readable diagnostic: used both for hard errors and node warnings.
4///
5/// `code` is a stable SCREAMING_SNAKE identifier (see `docs/DESIGN.md`);
6/// `offset` is a byte offset into the buffer being decoded, when known.
7#[derive(Debug, Clone, PartialEq, Eq)]
8pub struct Diag {
9    pub code: &'static str,
10    pub message: String,
11    pub offset: Option<usize>,
12}
13
14impl Diag {
15    pub fn new(code: &'static str, message: impl Into<String>, offset: Option<usize>) -> Self {
16        Self {
17            code,
18            message: message.into(),
19            offset,
20        }
21    }
22}
23
24impl fmt::Display for Diag {
25    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
26        write!(f, "{}: {}", self.code, self.message)?;
27        if let Some(o) = self.offset {
28            write!(f, " (offset {o})")?;
29        }
30        Ok(())
31    }
32}
33
34impl std::error::Error for Diag {}