Skip to main content

csp_format/
error.rs

1//! Error type shared by every reader and writer in this crate.
2
3use std::fmt;
4
5/// Why a file could not be read or written.
6#[derive(Debug)]
7#[non_exhaustive]
8pub enum Error {
9    /// The data does not follow the layout this crate understands.
10    Format(String),
11    /// Reading or writing a file failed.
12    Io(std::io::Error),
13    /// The embedded SQLite database could not be read or written.
14    Sqlite(rusqlite::Error),
15}
16
17/// Result with this crate's [`Error`].
18pub type Result<T> = std::result::Result<T, Error>;
19
20impl Error {
21    /// An [`Error::Format`] with this message.
22    pub fn format(message: impl Into<String>) -> Self {
23        Error::Format(message.into())
24    }
25}
26
27impl fmt::Display for Error {
28    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
29        match self {
30            Error::Format(message) => write!(f, "{message}"),
31            Error::Io(error) => write!(f, "{error}"),
32            Error::Sqlite(error) => write!(f, "SQLite: {error}"),
33        }
34    }
35}
36
37impl std::error::Error for Error {
38    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
39        match self {
40            Error::Format(_) => None,
41            Error::Io(error) => Some(error),
42            Error::Sqlite(error) => Some(error),
43        }
44    }
45}
46
47impl From<std::io::Error> for Error {
48    fn from(error: std::io::Error) -> Self {
49        Error::Io(error)
50    }
51}
52
53impl From<rusqlite::Error> for Error {
54    fn from(error: rusqlite::Error) -> Self {
55        Error::Sqlite(error)
56    }
57}
58
59/// Shorthand for `Err(Error::Format(...))` with `format!` arguments.
60macro_rules! bail {
61    ($($arg:tt)*) => {
62        return Err($crate::error::Error::Format(format!($($arg)*)))
63    };
64}
65pub(crate) use bail;