Skip to main content

banished_formats/
error.rs

1use std::fmt;
2
3/// Why data could not be read.
4#[derive(Debug, Clone, PartialEq, Eq)]
5pub enum Error {
6    /// Input ended before a read completed.
7    Truncated {
8        /// Where the read started.
9        at: usize,
10        /// How many bytes it wanted.
11        wanted: usize,
12    },
13    /// Structural check failed (bad marker, size mismatch, unread bytes...).
14    Format(String),
15    /// Data is valid but uses a variant this crate does not handle yet.
16    Unsupported(String),
17}
18
19/// A result with this crate's [`Error`].
20pub type Result<T> = std::result::Result<T, Error>;
21
22impl fmt::Display for Error {
23    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
24        match self {
25            Error::Truncated { at, wanted } => {
26                write!(f, "truncated: wanted {wanted} bytes at {at:#x}")
27            }
28            Error::Format(m) => write!(f, "format error: {m}"),
29            Error::Unsupported(m) => write!(f, "unsupported: {m}"),
30        }
31    }
32}
33
34impl std::error::Error for Error {}
35
36pub(crate) fn format_err<T>(msg: impl Into<String>) -> Result<T> {
37    Err(Error::Format(msg.into()))
38}