Skip to main content

xisf_core/
error.rs

1//! One error type for the whole engine.
2
3use core::fmt;
4
5/// What went wrong, in a form a caller can branch on.
6#[derive(Clone, Copy, PartialEq, Eq, Debug)]
7pub enum ErrorKind {
8    /// The file does not begin with the XISF signature.
9    NotXisf,
10    /// The file is shorter than its own structure claims.
11    Truncated,
12    /// The XML header could not be parsed.
13    BadHeader,
14    /// An attribute's value does not match the grammar the spec gives it.
15    BadAttribute,
16    /// A value is well-formed but not one the spec allows here.
17    Unsupported,
18    /// A checksum did not match.
19    ChecksumMismatch,
20    /// Decompression failed.
21    Compression,
22    /// The caller asked for something that is not there.
23    NotFound,
24    /// An argument was out of range or otherwise unusable.
25    InvalidArgument,
26    /// An I/O error.
27    Io,
28}
29
30impl ErrorKind {
31    /// A short name, stable enough to appear in messages and tests.
32    pub fn name(self) -> &'static str {
33        match self {
34            ErrorKind::NotXisf => "not-xisf",
35            ErrorKind::Truncated => "truncated",
36            ErrorKind::BadHeader => "bad-header",
37            ErrorKind::BadAttribute => "bad-attribute",
38            ErrorKind::Unsupported => "unsupported",
39            ErrorKind::ChecksumMismatch => "checksum-mismatch",
40            ErrorKind::Compression => "compression",
41            ErrorKind::NotFound => "not-found",
42            ErrorKind::InvalidArgument => "invalid-argument",
43            ErrorKind::Io => "io",
44        }
45    }
46}
47
48/// An engine error: a kind, and a message saying what specifically failed.
49#[derive(Debug)]
50pub struct Error {
51    kind: ErrorKind,
52    message: String,
53}
54
55impl Error {
56    pub fn new(kind: ErrorKind, message: impl Into<String>) -> Self {
57        Self { kind, message: message.into() }
58    }
59
60    pub fn kind(&self) -> ErrorKind {
61        self.kind
62    }
63
64    pub fn message(&self) -> &str {
65        &self.message
66    }
67}
68
69impl fmt::Display for Error {
70    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
71        write!(f, "{}: {}", self.kind.name(), self.message)
72    }
73}
74
75impl core::error::Error for Error {}
76
77impl From<std::io::Error> for Error {
78    fn from(e: std::io::Error) -> Self {
79        Error::new(ErrorKind::Io, e.to_string())
80    }
81}
82
83/// The engine's result type.
84pub type Result<T> = core::result::Result<T, Error>;
85
86/// Build an [`Error`] with a formatted message.
87#[macro_export]
88macro_rules! err {
89    ($kind:ident, $($arg:tt)*) => {
90        $crate::error::Error::new($crate::error::ErrorKind::$kind, format!($($arg)*))
91    };
92}