Skip to main content

zrip_core/
error.rs

1#![forbid(unsafe_code)]
2
3use core::fmt;
4
5/// Unified error type wrapping both compression and decompression errors.
6#[derive(Debug, Clone, PartialEq, Eq)]
7pub enum ZstdError {
8    Compress(CompressError),
9    Decompress(DecompressError),
10}
11
12/// Error returned by compression functions.
13#[derive(Debug, Clone, PartialEq, Eq)]
14pub enum CompressError {
15    /// Output buffer passed to [`compress_into`](crate::compress_into) is too small.
16    OutputTooSmall,
17    /// Compression level is outside the supported range (-7..=4; -8 runs
18    /// as -7).
19    InvalidLevel(i32),
20    /// Dictionary bytes failed to parse.
21    InvalidDictionary,
22}
23
24/// Error returned by decompression functions.
25#[derive(Debug, Clone, PartialEq, Eq)]
26pub enum DecompressError {
27    /// Frame magic number is not `0xFD2F_B528`.
28    BadMagic,
29    /// Frame descriptor or field sizes are invalid.
30    BadFrameHeader,
31    /// Block header contains invalid values.
32    BadBlockHeader,
33    /// Block type field is reserved/unknown.
34    BadBlockType,
35    /// Literals section is malformed or truncated.
36    CorruptLiterals,
37    /// Sequences section is malformed.
38    CorruptSequences,
39    /// Raw or RLE block exceeds MAX_BLOCK_SIZE.
40    BlockTooLarge,
41    /// Sequence offset is invalid (zero or beyond available history).
42    InvalidOffset,
43    /// Decoded output size does not match the frame content size field.
44    FrameSizeMismatch,
45    /// FSE table description is invalid.
46    BadFseTable,
47    /// Huffman weight table is malformed.
48    BadHuffmanWeights,
49    /// Huffman bitstream decoding failed.
50    BadHuffmanStream,
51    /// Requested window size exceeds the implementation limit.
52    WindowTooLarge { requested: u64, max: u64 },
53    /// Decompressed output would exceed the configured size limit.
54    OutputTooSmall,
55    /// Content checksum does not match the decompressed data.
56    ChecksumMismatch { expected: u32, got: u32 },
57    /// Frame requires dictionary ID `expected`, but `got` was provided.
58    DictMismatch { expected: u32, got: u32 },
59    /// Frame requires a dictionary but none was provided.
60    DictRequired,
61    /// Dictionary bytes failed to parse.
62    InvalidDictionary,
63    /// Input ended before the frame was complete.
64    InputExhausted,
65    /// Unexpected trailing bytes after a valid frame.
66    ExtraBytes,
67}
68
69impl fmt::Display for ZstdError {
70    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
71        match self {
72            ZstdError::Compress(e) => write!(f, "compress: {e}"),
73            ZstdError::Decompress(e) => write!(f, "decompress: {e}"),
74        }
75    }
76}
77
78impl fmt::Display for CompressError {
79    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
80        match self {
81            CompressError::OutputTooSmall => write!(f, "output buffer too small"),
82            CompressError::InvalidLevel(l) => write!(f, "invalid compression level: {l}"),
83            CompressError::InvalidDictionary => write!(f, "invalid dictionary"),
84        }
85    }
86}
87
88impl fmt::Display for DecompressError {
89    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
90        match self {
91            DecompressError::BadMagic => write!(f, "invalid frame magic number"),
92            DecompressError::BadFrameHeader => write!(f, "malformed frame header"),
93            DecompressError::BadBlockHeader => write!(f, "malformed block header"),
94            DecompressError::BadBlockType => write!(f, "unknown block type"),
95            DecompressError::CorruptLiterals => write!(f, "corrupt literals section"),
96            DecompressError::CorruptSequences => write!(f, "corrupt sequences section"),
97            DecompressError::BlockTooLarge => write!(f, "block size exceeds maximum"),
98            DecompressError::InvalidOffset => write!(f, "invalid match offset"),
99            DecompressError::FrameSizeMismatch => {
100                write!(f, "decoded size does not match frame content size")
101            }
102            DecompressError::BadFseTable => write!(f, "invalid FSE table description"),
103            DecompressError::BadHuffmanWeights => write!(f, "invalid Huffman weights"),
104            DecompressError::BadHuffmanStream => write!(f, "corrupt Huffman stream"),
105            DecompressError::WindowTooLarge { requested, max } => {
106                write!(f, "window size {requested} exceeds max {max}")
107            }
108            DecompressError::OutputTooSmall => write!(f, "output buffer too small"),
109            DecompressError::ChecksumMismatch { expected, got } => {
110                write!(
111                    f,
112                    "checksum mismatch: expected {expected:#010x}, got {got:#010x}"
113                )
114            }
115            DecompressError::DictMismatch { expected, got } => {
116                write!(f, "dictionary ID mismatch: expected {expected}, got {got}")
117            }
118            DecompressError::DictRequired => write!(f, "dictionary required but not provided"),
119            DecompressError::InvalidDictionary => write!(f, "invalid dictionary format"),
120            DecompressError::InputExhausted => write!(f, "unexpected end of input"),
121            DecompressError::ExtraBytes => write!(f, "extra bytes after frame"),
122        }
123    }
124}
125
126#[cfg(feature = "std")]
127impl std::error::Error for ZstdError {}
128#[cfg(feature = "std")]
129impl std::error::Error for CompressError {}
130#[cfg(feature = "std")]
131impl std::error::Error for DecompressError {}
132
133impl From<CompressError> for ZstdError {
134    fn from(e: CompressError) -> Self {
135        ZstdError::Compress(e)
136    }
137}
138
139impl From<DecompressError> for ZstdError {
140    fn from(e: DecompressError) -> Self {
141        ZstdError::Decompress(e)
142    }
143}