Skip to main content

hexspell/
errors.rs

1//! Error types shared across the crate.
2//!
3//! Binary parsing is prone to a variety of failures ranging from truncated
4//! data to unsupported features. The [`FileParseError`] enum captures these
5//! cases in a single place so that all modules can communicate problems in a
6//! consistent manner. For convenience a `Result` alias is provided as well.
7
8use alloc::string::String;
9
10use core::fmt;
11#[cfg(feature = "std")]
12use std::io;
13
14#[derive(Debug)]
15pub enum FileParseError {
16    /// Underlying I/O failure (read/write).
17    #[cfg(feature = "std")]
18    Io(io::Error),
19    /// Magic bytes or structural invariant does not match the expected format.
20    InvalidFileFormat,
21    /// Read or write would extend past the end of the buffer.
22    BufferOverflow,
23    /// Numeric value does not fit in the on-disk field width.
24    ValueTooLarge,
25    /// Requested capability is not implemented yet.
26    UnsupportedFeature(String),
27}
28
29impl fmt::Display for FileParseError {
30    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
31        match self {
32            #[cfg(feature = "std")]
33            FileParseError::Io(err) => write!(f, "I/O error: {err}"),
34            FileParseError::InvalidFileFormat => write!(f, "Invalid file format."),
35            FileParseError::BufferOverflow => write!(f, "Data out of bounds."),
36            FileParseError::ValueTooLarge => write!(f, "Value exceeds field size."),
37            FileParseError::UnsupportedFeature(feature) => {
38                write!(f, "Unsupported feature: {feature}")
39            }
40        }
41    }
42}
43
44#[cfg(feature = "std")]
45impl From<io::Error> for FileParseError {
46    fn from(err: io::Error) -> Self {
47        FileParseError::Io(err)
48    }
49}
50impl core::error::Error for FileParseError {
51    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
52        match self {
53            #[cfg(feature = "std")]
54            FileParseError::Io(err) => Some(err),
55            _ => None,
56        }
57    }
58}
59/// Convenience alias used by all format parsers.
60pub type Result<T> = core::result::Result<T, FileParseError>;