Skip to main content

zrip_core/
error.rs

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