Skip to main content

lzf_rust/
error.rs

1// SPDX-License-Identifier: ISC
2use core::fmt;
3
4/// Result type used by this crate.
5pub type Result<T> = core::result::Result<T, Error>;
6
7/// Error type for LZF encode/decode operations.
8///
9/// The variants are shared by raw token APIs, framed block APIs, and streaming
10/// reader/writer adapters.
11#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12pub enum Error {
13    /// End of input reached unexpectedly.
14    Eof,
15    /// Operation was interrupted.
16    Interrupted,
17    /// Output buffer is too small for the requested operation.
18    OutputTooSmall,
19    /// Could not write any bytes.
20    WriteZero,
21    /// Input stream is malformed.
22    InvalidData,
23    /// Framed input has an invalid header.
24    InvalidHeader,
25    /// Framed input contains an unsupported block type.
26    ///
27    /// The contained byte is the unknown `ZV` block type value.
28    UnknownBlockType(u8),
29    /// Configuration is invalid.
30    InvalidParameter,
31    /// Other I/O error.
32    Other,
33}
34
35impl fmt::Display for Error {
36    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
37        match self {
38            Self::Eof => f.write_str("unexpected end of input"),
39            Self::Interrupted => f.write_str("operation interrupted"),
40            Self::OutputTooSmall => f.write_str("output buffer too small"),
41            Self::WriteZero => f.write_str("failed to write data"),
42            Self::InvalidData => f.write_str("invalid compressed data"),
43            Self::InvalidHeader => f.write_str("invalid LZF block header"),
44            Self::UnknownBlockType(kind) => write!(f, "unknown LZF block type: {kind}"),
45            Self::InvalidParameter => f.write_str("invalid parameter"),
46            Self::Other => f.write_str("I/O error"),
47        }
48    }
49}
50
51#[cfg(feature = "std")]
52impl std::error::Error for Error {}
53
54#[cfg(feature = "std")]
55impl From<std::io::Error> for Error {
56    fn from(value: std::io::Error) -> Self {
57        match value.kind() {
58            std::io::ErrorKind::UnexpectedEof => Self::Eof,
59            std::io::ErrorKind::Interrupted => Self::Interrupted,
60            std::io::ErrorKind::InvalidData => Self::InvalidData,
61            std::io::ErrorKind::InvalidInput => Self::InvalidParameter,
62            std::io::ErrorKind::WriteZero => Self::WriteZero,
63            _ => Self::Other,
64        }
65    }
66}