Skip to main content

structured_zstd/decoding/
errors.rs

1//! Errors that might occur while decoding zstd formatted data
2
3use crate::bit_io::GetBitsError;
4use crate::blocks::block::BlockType;
5use crate::blocks::literals_section::LiteralsSectionType;
6use crate::io::Error;
7use alloc::vec::Vec;
8use core::fmt;
9#[cfg(feature = "std")]
10use std::error::Error as StdError;
11
12#[derive(Debug)]
13#[non_exhaustive]
14pub enum FrameDescriptorError {
15    InvalidFrameContentSizeFlag { got: u8 },
16}
17
18impl fmt::Display for FrameDescriptorError {
19    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
20        match self {
21            Self::InvalidFrameContentSizeFlag { got } => write!(
22                f,
23                "Invalid Frame_Content_Size_Flag; Is: {got}, Should be one of: 0, 1, 2, 3"
24            ),
25        }
26    }
27}
28
29#[cfg(feature = "std")]
30impl StdError for FrameDescriptorError {}
31
32#[derive(Debug)]
33#[non_exhaustive]
34pub enum FrameHeaderError {
35    WindowTooBig { got: u64 },
36    WindowTooSmall { got: u64 },
37    FrameDescriptorError(FrameDescriptorError),
38    DictIdTooSmall { got: usize, expected: usize },
39    MismatchedFrameSize { got: usize, expected: u8 },
40    FrameSizeIsZero,
41    InvalidFrameSize { got: u8 },
42}
43
44impl fmt::Display for FrameHeaderError {
45    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
46        match self {
47            Self::WindowTooBig { got } => write!(
48                f,
49                "window_size bigger than allowed maximum. Is: {}, Should be lower than: {}",
50                got,
51                crate::common::MAX_WINDOW_SIZE
52            ),
53            Self::WindowTooSmall { got } => write!(
54                f,
55                "window_size smaller than allowed minimum. Is: {}, Should be greater than: {}",
56                got,
57                crate::common::MIN_WINDOW_SIZE
58            ),
59            Self::FrameDescriptorError(e) => write!(f, "{e:?}"),
60            Self::DictIdTooSmall { got, expected } => write!(
61                f,
62                "Not enough bytes in dict_id. Is: {got}, Should be: {expected}"
63            ),
64            Self::MismatchedFrameSize { got, expected } => write!(
65                f,
66                "frame_content_size does not have the right length. Is: {got}, Should be: {expected}"
67            ),
68            Self::FrameSizeIsZero => write!(f, "frame_content_size was zero"),
69            Self::InvalidFrameSize { got } => write!(
70                f,
71                "Invalid frame_content_size. Is: {got}, Should be one of 1, 2, 4, 8 bytes"
72            ),
73        }
74    }
75}
76
77#[cfg(feature = "std")]
78impl StdError for FrameHeaderError {
79    fn source(&self) -> Option<&(dyn StdError + 'static)> {
80        match self {
81            FrameHeaderError::FrameDescriptorError(source) => Some(source),
82            _ => None,
83        }
84    }
85}
86
87impl From<FrameDescriptorError> for FrameHeaderError {
88    fn from(error: FrameDescriptorError) -> Self {
89        Self::FrameDescriptorError(error)
90    }
91}
92
93#[derive(Debug)]
94#[non_exhaustive]
95pub enum ReadFrameHeaderError {
96    MagicNumberReadError(Error),
97    BadMagicNumber(u32),
98    FrameDescriptorReadError(Error),
99    InvalidFrameDescriptor(FrameDescriptorError),
100    WindowDescriptorReadError(Error),
101    DictionaryIdReadError(Error),
102    FrameContentSizeReadError(Error),
103    SkipFrame { magic_number: u32, length: u32 },
104}
105
106impl fmt::Display for ReadFrameHeaderError {
107    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
108        match self {
109            Self::MagicNumberReadError(e) => write!(f, "Error while reading magic number: {e}"),
110            Self::BadMagicNumber(e) => write!(f, "Read wrong magic number: 0x{e:X}"),
111            Self::FrameDescriptorReadError(e) => {
112                write!(f, "Error while reading frame descriptor: {e}")
113            }
114            Self::InvalidFrameDescriptor(e) => write!(f, "{e:?}"),
115            Self::WindowDescriptorReadError(e) => {
116                write!(f, "Error while reading window descriptor: {e}")
117            }
118            Self::DictionaryIdReadError(e) => write!(f, "Error while reading dictionary id: {e}"),
119            Self::FrameContentSizeReadError(e) => {
120                write!(f, "Error while reading frame content size: {e}")
121            }
122            Self::SkipFrame {
123                magic_number,
124                length,
125            } => write!(
126                f,
127                "SkippableFrame encountered with MagicNumber 0x{magic_number:X} and length {length} bytes"
128            ),
129        }
130    }
131}
132
133#[cfg(feature = "std")]
134impl StdError for ReadFrameHeaderError {
135    fn source(&self) -> Option<&(dyn StdError + 'static)> {
136        match self {
137            ReadFrameHeaderError::MagicNumberReadError(source) => Some(source),
138            ReadFrameHeaderError::FrameDescriptorReadError(source) => Some(source),
139            ReadFrameHeaderError::InvalidFrameDescriptor(source) => Some(source),
140            ReadFrameHeaderError::WindowDescriptorReadError(source) => Some(source),
141            ReadFrameHeaderError::DictionaryIdReadError(source) => Some(source),
142            ReadFrameHeaderError::FrameContentSizeReadError(source) => Some(source),
143            _ => None,
144        }
145    }
146}
147
148impl From<FrameDescriptorError> for ReadFrameHeaderError {
149    fn from(error: FrameDescriptorError) -> Self {
150        Self::InvalidFrameDescriptor(error)
151    }
152}
153
154#[derive(Debug)]
155#[non_exhaustive]
156pub enum BlockHeaderReadError {
157    ReadError(Error),
158    FoundReservedBlock,
159    BlockTypeError(BlockTypeError),
160    BlockSizeError(BlockSizeError),
161}
162
163#[cfg(feature = "std")]
164impl std::error::Error for BlockHeaderReadError {
165    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
166        match self {
167            BlockHeaderReadError::ReadError(source) => Some(source),
168            BlockHeaderReadError::BlockTypeError(source) => Some(source),
169            BlockHeaderReadError::BlockSizeError(source) => Some(source),
170            BlockHeaderReadError::FoundReservedBlock => None,
171        }
172    }
173}
174
175impl ::core::fmt::Display for BlockHeaderReadError {
176    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> ::core::fmt::Result {
177        match self {
178            BlockHeaderReadError::ReadError(_) => write!(f, "Error while reading the block header"),
179            BlockHeaderReadError::FoundReservedBlock => write!(
180                f,
181                "Reserved block occured. This is considered corruption by the documentation"
182            ),
183            BlockHeaderReadError::BlockTypeError(e) => write!(f, "Error getting block type: {e}"),
184            BlockHeaderReadError::BlockSizeError(e) => {
185                write!(f, "Error getting block content size: {e}")
186            }
187        }
188    }
189}
190
191impl From<Error> for BlockHeaderReadError {
192    fn from(val: Error) -> Self {
193        Self::ReadError(val)
194    }
195}
196
197impl From<BlockTypeError> for BlockHeaderReadError {
198    fn from(val: BlockTypeError) -> Self {
199        Self::BlockTypeError(val)
200    }
201}
202
203impl From<BlockSizeError> for BlockHeaderReadError {
204    fn from(val: BlockSizeError) -> Self {
205        Self::BlockSizeError(val)
206    }
207}
208
209#[derive(Debug)]
210#[non_exhaustive]
211pub enum BlockTypeError {
212    InvalidBlocktypeNumber { num: u8 },
213}
214
215#[cfg(feature = "std")]
216impl std::error::Error for BlockTypeError {}
217
218impl core::fmt::Display for BlockTypeError {
219    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
220        match self {
221            BlockTypeError::InvalidBlocktypeNumber { num } => {
222                write!(
223                    f,
224                    "Invalid Blocktype number. Is: {num}. Should be one of: 0, 1, 2, 3 (3 is reserved).",
225                )
226            }
227        }
228    }
229}
230
231#[derive(Debug)]
232#[non_exhaustive]
233pub enum BlockSizeError {
234    BlockSizeTooLarge { size: u32 },
235}
236
237#[cfg(feature = "std")]
238impl std::error::Error for BlockSizeError {}
239
240impl core::fmt::Display for BlockSizeError {
241    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
242        match self {
243            BlockSizeError::BlockSizeTooLarge { size } => {
244                write!(
245                    f,
246                    "Blocksize was bigger than the absolute maximum {} (128kb). Is: {}",
247                    crate::common::MAX_BLOCK_SIZE,
248                    size,
249                )
250            }
251        }
252    }
253}
254
255#[derive(Debug)]
256#[non_exhaustive]
257pub enum DecompressBlockError {
258    BlockContentReadError(Error),
259    MalformedSectionHeader {
260        expected_len: usize,
261        remaining_bytes: usize,
262    },
263    DecompressLiteralsError(DecompressLiteralsError),
264    LiteralsSectionParseError(LiteralsSectionParseError),
265    SequencesHeaderParseError(SequencesHeaderParseError),
266    DecodeSequenceError(DecodeSequenceError),
267    ExecuteSequencesError(ExecuteSequencesError),
268    /// The block's literals, or its whole output, run past the block maximum
269    /// (RFC 8878 3.1.1.2.4, `Block_Maximum_Size`): `size` bytes where
270    /// `maximum` is the most a block of this frame may produce, the smaller of
271    /// its window and 128 KiB.
272    ExpandsPastBlockMaximum {
273        size: usize,
274        maximum: usize,
275    },
276    /// A block with no sequences whose literals do not fit a fixed-capacity
277    /// backend: `requested` bytes at `tail` against `capacity`. The block is
278    /// within the block maximum, so this says the caller's slice is short, and
279    /// the frame decoder turns it into `TargetTooSmall` (or a content-size
280    /// mismatch for a frame that declared one). Growable backends grow instead
281    /// and never produce it.
282    LiteralsOutputOverflow {
283        tail: usize,
284        requested: usize,
285        capacity: usize,
286    },
287}
288
289#[cfg(feature = "std")]
290impl std::error::Error for DecompressBlockError {
291    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
292        match self {
293            DecompressBlockError::BlockContentReadError(source) => Some(source),
294            DecompressBlockError::DecompressLiteralsError(source) => Some(source),
295            DecompressBlockError::LiteralsSectionParseError(source) => Some(source),
296            DecompressBlockError::SequencesHeaderParseError(source) => Some(source),
297            DecompressBlockError::DecodeSequenceError(source) => Some(source),
298            DecompressBlockError::ExecuteSequencesError(source) => Some(source),
299            _ => None,
300        }
301    }
302}
303
304impl core::fmt::Display for DecompressBlockError {
305    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
306        match self {
307            DecompressBlockError::BlockContentReadError(e) => {
308                write!(f, "Error while reading the block content: {e}")
309            }
310            DecompressBlockError::MalformedSectionHeader {
311                expected_len,
312                remaining_bytes,
313            } => {
314                write!(
315                    f,
316                    "Malformed section header. Says literals would be this long: {expected_len} but there are only {remaining_bytes} bytes left",
317                )
318            }
319            DecompressBlockError::DecompressLiteralsError(e) => write!(f, "{e:?}"),
320            DecompressBlockError::LiteralsSectionParseError(e) => write!(f, "{e:?}"),
321            DecompressBlockError::SequencesHeaderParseError(e) => write!(f, "{e:?}"),
322            DecompressBlockError::DecodeSequenceError(e) => write!(f, "{e:?}"),
323            DecompressBlockError::ExecuteSequencesError(e) => write!(f, "{e:?}"),
324            DecompressBlockError::ExpandsPastBlockMaximum { size, maximum } => write!(
325                f,
326                "Block expands to {size} bytes, past this frame's maximum of {maximum}"
327            ),
328            DecompressBlockError::LiteralsOutputOverflow {
329                tail,
330                requested,
331                capacity,
332            } => write!(
333                f,
334                "Literals would write past the output buffer: tail={tail}, requested={requested}, capacity={capacity}"
335            ),
336        }
337    }
338}
339
340impl From<Error> for DecompressBlockError {
341    fn from(val: Error) -> Self {
342        Self::BlockContentReadError(val)
343    }
344}
345
346impl From<DecompressLiteralsError> for DecompressBlockError {
347    fn from(val: DecompressLiteralsError) -> Self {
348        Self::DecompressLiteralsError(val)
349    }
350}
351
352impl From<LiteralsSectionParseError> for DecompressBlockError {
353    fn from(val: LiteralsSectionParseError) -> Self {
354        Self::LiteralsSectionParseError(val)
355    }
356}
357
358impl From<SequencesHeaderParseError> for DecompressBlockError {
359    fn from(val: SequencesHeaderParseError) -> Self {
360        Self::SequencesHeaderParseError(val)
361    }
362}
363
364impl From<DecodeSequenceError> for DecompressBlockError {
365    fn from(val: DecodeSequenceError) -> Self {
366        Self::DecodeSequenceError(val)
367    }
368}
369
370impl From<ExecuteSequencesError> for DecompressBlockError {
371    fn from(val: ExecuteSequencesError) -> Self {
372        Self::ExecuteSequencesError(val)
373    }
374}
375
376#[derive(Debug)]
377#[non_exhaustive]
378pub enum DecodeBlockContentError {
379    DecoderStateIsFailed,
380    ExpectedHeaderOfPreviousBlock,
381    ReadError {
382        step: BlockType,
383        source: Error,
384    },
385    DecompressBlockError(DecompressBlockError),
386    /// The block's decompressed payload would not fit in the
387    /// caller-provided output buffer (only reachable via the
388    /// direct-decode path with a fixed-capacity backend). Internal
389    /// diagnostic variant — the frame-level decoder always
390    /// converts this into
391    /// `FrameDecoderError::FrameContentSizeMismatch` before
392    /// returning to the user, so external callers never observe
393    /// it. The `step: BlockType` field is kept for in-crate
394    /// debugging (which decode arm triggered the overshoot) but is
395    /// not part of any caller-visible distinction.
396    BackendOverflow {
397        step: BlockType,
398    },
399}
400
401#[cfg(feature = "std")]
402impl std::error::Error for DecodeBlockContentError {
403    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
404        match self {
405            DecodeBlockContentError::ReadError { step: _, source } => Some(source),
406            DecodeBlockContentError::DecompressBlockError(source) => Some(source),
407            _ => None,
408        }
409    }
410}
411
412impl core::fmt::Display for DecodeBlockContentError {
413    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
414        match self {
415            DecodeBlockContentError::DecoderStateIsFailed => {
416                write!(
417                    f,
418                    "Can't decode next block if failed along the way. Results will be nonsense",
419                )
420            }
421            DecodeBlockContentError::ExpectedHeaderOfPreviousBlock => {
422                write!(
423                    f,
424                    "Can't decode next block body, while expecting to decode the header of the previous block. Results will be nonsense",
425                )
426            }
427            DecodeBlockContentError::ReadError { step, source } => {
428                write!(f, "Error while reading bytes for {step}: {source}",)
429            }
430            DecodeBlockContentError::DecompressBlockError(e) => write!(f, "{e:?}"),
431            DecodeBlockContentError::BackendOverflow { step } => write!(
432                f,
433                "{step} block's decompressed payload exceeds the caller-provided output buffer",
434            ),
435        }
436    }
437}
438
439impl From<DecompressBlockError> for DecodeBlockContentError {
440    fn from(val: DecompressBlockError) -> Self {
441        Self::DecompressBlockError(val)
442    }
443}
444
445#[derive(Debug)]
446#[non_exhaustive]
447pub enum DecodeBufferError {
448    NotEnoughBytesInDictionary {
449        got: usize,
450        need: usize,
451    },
452    OffsetTooBig {
453        offset: usize,
454        buf_len: usize,
455    },
456    ZeroOffset,
457    /// Legacy unit variant kept for binary compatibility with earlier
458    /// snapshots of this enum. Not surfaced from any current
459    /// production path — `BufferBackend::try_extend` /
460    /// `try_extend_from_within` and the new `try_reserve` (used by
461    /// `DecodeBuffer::repeat`) carry their failures through the
462    /// richer [`Self::OutputBufferOverflow`] variant below, which
463    /// reports the offending `tail` / `requested` / `capacity`
464    /// triple. New code should pattern-match on
465    /// `OutputBufferOverflow`; this unit variant is retained to keep
466    /// the `#[non_exhaustive]` enum's existing discriminant set
467    /// stable.
468    BackendOverflow,
469    /// Repeat-side match copy would write past the writable tail of
470    /// a fixed-capacity backend (`UserSliceBackend`). Surfaced by
471    /// [`super::decode_buffer::DecodeBuffer::repeat`] / `_lookahead`
472    /// when the new `BufferBackend::try_reserve` rejects the
473    /// pre-write capacity check — keeping the safe public decode
474    /// APIs error-returning instead of panicking via the per-call
475    /// `assert!` inside `extend_from_within_unchecked`. Growable
476    /// backends (`FlatBuf`, `RingBuffer`) never produce this; their
477    /// `try_reserve` falls through to infallible `reserve`.
478    OutputBufferOverflow {
479        tail: usize,
480        requested: usize,
481        capacity: usize,
482    },
483}
484
485#[cfg(feature = "std")]
486impl std::error::Error for DecodeBufferError {}
487
488impl core::fmt::Display for DecodeBufferError {
489    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
490        match self {
491            DecodeBufferError::NotEnoughBytesInDictionary { got, need } => {
492                write!(
493                    f,
494                    "Need {need} bytes from the dictionary but it is only {got} bytes long",
495                )
496            }
497            DecodeBufferError::OffsetTooBig { offset, buf_len } => {
498                write!(f, "offset: {offset} bigger than buffer: {buf_len}",)
499            }
500            DecodeBufferError::ZeroOffset => {
501                write!(f, "Illegal offset: 0 found")
502            }
503            DecodeBufferError::BackendOverflow => {
504                write!(
505                    f,
506                    "Match repeat would overflow the output buffer's fixed capacity"
507                )
508            }
509            DecodeBufferError::OutputBufferOverflow {
510                tail,
511                requested,
512                capacity,
513            } => {
514                write!(
515                    f,
516                    "Match repeat would write past fixed-capacity buffer: tail={tail}, requested={requested}, capacity={capacity}"
517                )
518            }
519        }
520    }
521}
522
523#[derive(Debug)]
524#[non_exhaustive]
525pub enum DictionaryDecodeError {
526    BadMagicNum { got: [u8; 4] },
527    DictionaryTooSmall { got: usize, need: usize },
528    ZeroDictionaryId,
529    ZeroRepeatOffsetInDictionary { index: u8 },
530    FSETableError(FSETableError),
531    HuffmanTableError(HuffmanTableError),
532}
533
534#[cfg(feature = "std")]
535impl std::error::Error for DictionaryDecodeError {
536    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
537        match self {
538            DictionaryDecodeError::FSETableError(source) => Some(source),
539            DictionaryDecodeError::HuffmanTableError(source) => Some(source),
540            _ => None,
541        }
542    }
543}
544
545impl core::fmt::Display for DictionaryDecodeError {
546    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
547        match self {
548            DictionaryDecodeError::BadMagicNum { got } => {
549                write!(
550                    f,
551                    "Bad magic_num at start of the dictionary; Got: {:#04X?}, Expected: {:#04x?}",
552                    got,
553                    crate::decoding::dictionary::MAGIC_NUM,
554                )
555            }
556            DictionaryDecodeError::DictionaryTooSmall { got, need } => {
557                write!(
558                    f,
559                    "Dictionary is too small: got {got} bytes, need at least {need} bytes",
560                )
561            }
562            DictionaryDecodeError::ZeroDictionaryId => {
563                write!(f, "Dictionary id must be non-zero")
564            }
565            DictionaryDecodeError::ZeroRepeatOffsetInDictionary { index } => {
566                write!(f, "Dictionary repeat offset rep{index} must be non-zero")
567            }
568            DictionaryDecodeError::FSETableError(e) => write!(f, "{e:?}"),
569            DictionaryDecodeError::HuffmanTableError(e) => write!(f, "{e:?}"),
570        }
571    }
572}
573
574impl From<FSETableError> for DictionaryDecodeError {
575    fn from(val: FSETableError) -> Self {
576        Self::FSETableError(val)
577    }
578}
579
580impl From<HuffmanTableError> for DictionaryDecodeError {
581    fn from(val: HuffmanTableError) -> Self {
582        Self::HuffmanTableError(val)
583    }
584}
585
586#[derive(Debug)]
587#[non_exhaustive]
588pub enum FrameDecoderError {
589    ReadFrameHeaderError(ReadFrameHeaderError),
590    FrameHeaderError(FrameHeaderError),
591    WindowSizeTooBig {
592        requested: u64,
593    },
594    DictionaryDecodeError(DictionaryDecodeError),
595    FailedToReadBlockHeader(BlockHeaderReadError),
596    FailedToReadBlockBody(DecodeBlockContentError),
597    FailedToReadChecksum(Error),
598    NotYetInitialized,
599    FailedToInitialize(FrameHeaderError),
600    FailedToDrainDecodebuffer(Error),
601    FailedToSkipFrame,
602    TargetTooSmall,
603    /// Decoded block sizes don't sum to the frame's declared
604    /// `frame_content_size` (either a block claims to expand past
605    /// FCS, or the stream ends before reaching FCS). Indicates a
606    /// malformed or corrupt frame — distinct from
607    /// [`Self::TargetTooSmall`] (which is the caller's
608    /// responsibility) so callers can tell decoder-side issues
609    /// apart from their own buffer sizing mistakes.
610    FrameContentSizeMismatch {
611        declared: u64,
612        produced: u64,
613    },
614    /// The frame carried a trailing XXH64 content checksum and the decoder
615    /// was set to [`ContentChecksum::Verify`](crate::decoding::ContentChecksum::Verify),
616    /// but the digest computed over the decompressed output did not match the
617    /// stored value. Indicates corruption in the compressed stream or its
618    /// trailing checksum. `expected` is the value read from the frame tail;
619    /// `calculated` is the digest the decoder computed (both low 32 bits).
620    ChecksumMismatch {
621        expected: u32,
622        calculated: u32,
623    },
624    DictNotProvided {
625        dict_id: u32,
626    },
627    DictIdMismatch {
628        expected: u32,
629        provided: u32,
630    },
631    DictAlreadyRegistered {
632        dict_id: u32,
633    },
634    /// Frame header's `dict_id` did not match the value pinned via
635    /// `FrameDecoder::expect_dict_id`. Returned BEFORE any block
636    /// decode and BEFORE any output is produced — no XXH64 init,
637    /// no partial output. Scratch buffer allocation / reservation
638    /// for the decode pipeline happens during frame-header parsing,
639    /// which is already complete when this validation fires, so
640    /// the cost of scratch sizing is paid even on a mismatched
641    /// header. `expected` is the pinned value (`Some(0)` is
642    /// treated as "no dictionary expected", matching a frame whose
643    /// header omits the optional `Dictionary_ID` field); `found`
644    /// reports what the frame actually carried (`None` when the
645    /// header omits the field, `Some(id)` when it does not).
646    #[cfg(feature = "lsm")]
647    UnexpectedDictId {
648        expected: Option<u32>,
649        found: Option<u32>,
650    },
651    /// Frame header's raw `Window_Descriptor` byte did not match
652    /// the value pinned via `FrameDecoder::expect_window_descriptor`.
653    /// Returned BEFORE any block decode work. Single-segment frames
654    /// (which omit the `Window_Descriptor` byte from the wire) are
655    /// reported via `found: None` so callers can distinguish
656    /// "wrong descriptor" from "no descriptor on the wire".
657    #[cfg(feature = "lsm")]
658    UnexpectedWindowDescriptor {
659        expected: u8,
660        found: Option<u8>,
661    },
662    /// Block-precise variant of [`Self::FailedToReadBlockHeader`]: a block
663    /// header read failed and the decoder captured WHERE. `block_index` is
664    /// the 0-based index of the failing block in the frame; `frame_offset`
665    /// is the frame-absolute byte offset of that block's `Block_Header`
666    /// (matches `FrameEmitInfo.blocks[block_index].offset_in_frame` from the
667    /// encode side). Lets per-block recovery (ECC repair) target the one bad
668    /// block instead of re-fetching the whole frame.
669    #[cfg(feature = "lsm")]
670    FailedToReadBlockHeaderAt {
671        source: BlockHeaderReadError,
672        block_index: u32,
673        frame_offset: u32,
674    },
675    /// Block-precise variant of [`Self::FailedToReadBlockBody`]: a block
676    /// body decode failed. Carries the same `block_index` / `frame_offset`
677    /// coordinates plus the failing block's structural metadata
678    /// ([`FrameBlock`]) reconstructed from its header, so a consumer can
679    /// locate and repair exactly this block.
680    ///
681    /// [`FrameBlock`]: crate::encoding::frame_emit_info::FrameBlock
682    #[cfg(feature = "lsm")]
683    FailedToReadBlockBodyAt {
684        source: DecodeBlockContentError,
685        block_index: u32,
686        frame_offset: u32,
687        block: crate::encoding::frame_emit_info::FrameBlock,
688    },
689    /// `FrameDecoder::decode_blocks_partial` was called with
690    /// `start_block > end_block` (the half-open block range is
691    /// empty-or-inverted and cannot describe a valid subset). API
692    /// misuse, surfaced as `Err` rather than a `PartialDecode`
693    /// outcome — distinct from a corrupt-frame stop, which is
694    /// reported via `PartialDecode::stopped_at`.
695    #[cfg(feature = "lsm")]
696    InvalidBlockRange {
697        start_block: u32,
698        end_block: u32,
699    },
700    /// A resuming [`FrameDecoder::decode_blocks_partial`] was given a
701    /// `window_prime` (via [`ResumeInput`]) shorter than the match window the
702    /// resume block can reach back into. The resumed decode would read past the
703    /// primed history and silently mis-resolve matches, so it is rejected up
704    /// front. `got` is the supplied prime length; `need` is the required
705    /// minimum (`min(window_size, output_offset)`).
706    ///
707    /// [`FrameDecoder::decode_blocks_partial`]: crate::decoding::FrameDecoder::decode_blocks_partial
708    /// [`ResumeInput`]: crate::decoding::ResumeInput
709    #[cfg(feature = "lsm")]
710    ResumeWindowTooShort {
711        got: usize,
712        need: usize,
713    },
714    /// A resuming [`FrameDecoder::decode_blocks_partial`] was given a
715    /// [`ResumeInput`] whose [`ResumeState`] was captured from a frame with a
716    /// different decode-relevant shape (window size, dictionary id,
717    /// single-segment flag, content-checksum flag, or magicless mode) than the
718    /// frame currently [`reset`](crate::decoding::FrameDecoder::reset) into the
719    /// decoder. Applying entropy/repcode state across mismatched frames would
720    /// yield byte-wrong output, so it is rejected up front.
721    ///
722    /// [`FrameDecoder::decode_blocks_partial`]: crate::decoding::FrameDecoder::decode_blocks_partial
723    /// [`ResumeInput`]: crate::decoding::ResumeInput
724    /// [`ResumeState`]: crate::decoding::ResumeState
725    #[cfg(feature = "lsm")]
726    ResumeFrameMismatch,
727    /// A resume was attempted while a dictionary that carries no ID was
728    /// applied, on either the emitting or the resuming side.
729    ///
730    /// The frame key tells dictionaries apart by the ID the decoder recorded,
731    /// and a raw-content dictionary has none — every one of them is ID 0. Two
732    /// different raw dictionaries therefore key alike, so a snapshot captured
733    /// under one would be restored under the other: foreign entropy and repcode
734    /// state, and output that is wrong with nothing to say so. A dictionary that
735    /// cannot be told from another cannot carry a resume across, so it is
736    /// refused. Give the dictionary an ID (a serialized dictionary carries one,
737    /// or supply a non-zero one to
738    /// [`Dictionary::from_raw_content`](crate::decoding::Dictionary::from_raw_content))
739    /// to make it resumable.
740    #[cfg(feature = "lsm")]
741    ResumeUnidentifiedDictionary,
742}
743
744#[cfg(feature = "std")]
745impl StdError for FrameDecoderError {
746    fn source(&self) -> Option<&(dyn StdError + 'static)> {
747        match self {
748            FrameDecoderError::ReadFrameHeaderError(source) => Some(source),
749            FrameDecoderError::FrameHeaderError(source) => Some(source),
750            FrameDecoderError::DictionaryDecodeError(source) => Some(source),
751            FrameDecoderError::FailedToReadBlockHeader(source) => Some(source),
752            FrameDecoderError::FailedToReadBlockBody(source) => Some(source),
753            #[cfg(feature = "lsm")]
754            FrameDecoderError::FailedToReadBlockHeaderAt { source, .. } => Some(source),
755            #[cfg(feature = "lsm")]
756            FrameDecoderError::FailedToReadBlockBodyAt { source, .. } => Some(source),
757            FrameDecoderError::FailedToReadChecksum(source) => Some(source),
758            FrameDecoderError::FailedToInitialize(source) => Some(source),
759            FrameDecoderError::FailedToDrainDecodebuffer(source) => Some(source),
760            _ => None,
761        }
762    }
763}
764
765impl core::fmt::Display for FrameDecoderError {
766    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> ::core::fmt::Result {
767        match self {
768            FrameDecoderError::ReadFrameHeaderError(e) => {
769                write!(f, "{e:?}")
770            }
771            FrameDecoderError::FrameHeaderError(e) => {
772                write!(f, "{e:?}")
773            }
774            FrameDecoderError::WindowSizeTooBig { requested } => {
775                write!(
776                    f,
777                    "Specified window_size is too big; Requested: {}, Allowed: {}",
778                    requested,
779                    crate::common::MAXIMUM_ALLOWED_WINDOW_SIZE,
780                )
781            }
782            FrameDecoderError::DictionaryDecodeError(e) => {
783                write!(f, "{e:?}")
784            }
785            FrameDecoderError::FailedToReadBlockHeader(e) => {
786                write!(f, "Failed to parse/decode block body: {e}")
787            }
788            FrameDecoderError::FailedToReadBlockBody(e) => {
789                write!(f, "Failed to parse block header: {e}")
790            }
791            #[cfg(feature = "lsm")]
792            FrameDecoderError::FailedToReadBlockHeaderAt {
793                source,
794                block_index,
795                frame_offset,
796            } => {
797                write!(
798                    f,
799                    "Failed to read block header at block {block_index} (frame offset {frame_offset}): {source}"
800                )
801            }
802            #[cfg(feature = "lsm")]
803            FrameDecoderError::FailedToReadBlockBodyAt {
804                source,
805                block_index,
806                frame_offset,
807                ..
808            } => {
809                write!(
810                    f,
811                    "Failed to decode block body at block {block_index} (frame offset {frame_offset}): {source}"
812                )
813            }
814            FrameDecoderError::FailedToReadChecksum(e) => {
815                write!(f, "Failed to read checksum: {e}")
816            }
817            FrameDecoderError::NotYetInitialized => {
818                write!(f, "Decoder must initialized or reset before using it",)
819            }
820            FrameDecoderError::FailedToInitialize(e) => {
821                write!(f, "Decoder encountered error while initializing: {e}")
822            }
823            FrameDecoderError::FailedToDrainDecodebuffer(e) => {
824                write!(
825                    f,
826                    "Decoder encountered error while draining the decodebuffer: {e}",
827                )
828            }
829            FrameDecoderError::FailedToSkipFrame => {
830                write!(
831                    f,
832                    "Failed to skip bytes for the length given in the frame header"
833                )
834            }
835            FrameDecoderError::TargetTooSmall => {
836                write!(
837                    f,
838                    "Target must have at least as many bytes as the content size reported by the frame"
839                )
840            }
841            FrameDecoderError::FrameContentSizeMismatch { declared, produced } => {
842                write!(
843                    f,
844                    "Frame content size mismatch (corrupt frame): declared {declared} bytes, blocks summed to {produced} bytes"
845                )
846            }
847            FrameDecoderError::ChecksumMismatch {
848                expected,
849                calculated,
850            } => {
851                write!(
852                    f,
853                    "Content checksum mismatch (corrupt frame): frame stored 0x{expected:08X}, decoder calculated 0x{calculated:08X}"
854                )
855            }
856            FrameDecoderError::DictNotProvided { dict_id } => {
857                write!(
858                    f,
859                    "Frame header specified dictionary id 0x{dict_id:X} that wasn't provided via add_dict()/add_dict_from_bytes() (or add_dict_handle() on atomic targets) or reset_with_dict_handle()/decode_all_with_dict_handle()/decode_all_with_dict_bytes()"
860                )
861            }
862            FrameDecoderError::DictIdMismatch { expected, provided } => {
863                write!(
864                    f,
865                    "Frame header dictionary id 0x{expected:X} does not match provided dictionary id 0x{provided:X}"
866                )
867            }
868            FrameDecoderError::DictAlreadyRegistered { dict_id } => {
869                write!(
870                    f,
871                    "Dictionary id 0x{dict_id:X} already registered in decoder"
872                )
873            }
874            #[cfg(feature = "lsm")]
875            FrameDecoderError::UnexpectedDictId { expected, found } => {
876                write!(f, "Frame header dict_id mismatch: expected ")?;
877                match expected {
878                    Some(id) => write!(f, "0x{id:X}")?,
879                    None => write!(f, "<none>")?,
880                }
881                write!(f, ", found ")?;
882                match found {
883                    Some(id) => write!(f, "0x{id:X}"),
884                    None => write!(f, "<none>"),
885                }
886            }
887            #[cfg(feature = "lsm")]
888            FrameDecoderError::UnexpectedWindowDescriptor { expected, found } => {
889                write!(
890                    f,
891                    "Frame header window_descriptor mismatch: expected 0x{expected:02X}, found "
892                )?;
893                match found {
894                    Some(byte) => write!(f, "0x{byte:02X}"),
895                    None => write!(f, "<none> (single-segment frame omits window_descriptor)"),
896                }
897            }
898            #[cfg(feature = "lsm")]
899            FrameDecoderError::InvalidBlockRange {
900                start_block,
901                end_block,
902            } => {
903                write!(
904                    f,
905                    "Invalid block range for partial decode: start_block {start_block} > end_block {end_block}"
906                )
907            }
908            #[cfg(feature = "lsm")]
909            FrameDecoderError::ResumeWindowTooShort { got, need } => {
910                write!(
911                    f,
912                    "resume window_prime too short: got {got} bytes, need at least {need}"
913                )
914            }
915            #[cfg(feature = "lsm")]
916            FrameDecoderError::ResumeFrameMismatch => {
917                write!(
918                    f,
919                    "resume state was captured from a frame with a different decode shape than the current frame"
920                )
921            }
922            #[cfg(feature = "lsm")]
923            FrameDecoderError::ResumeUnidentifiedDictionary => {
924                write!(
925                    f,
926                    "a dictionary with no ID cannot be told from another one, so it cannot carry a resume state across frames"
927                )
928            }
929        }
930    }
931}
932
933impl From<DictionaryDecodeError> for FrameDecoderError {
934    fn from(val: DictionaryDecodeError) -> Self {
935        Self::DictionaryDecodeError(val)
936    }
937}
938
939impl From<BlockHeaderReadError> for FrameDecoderError {
940    fn from(val: BlockHeaderReadError) -> Self {
941        Self::FailedToReadBlockHeader(val)
942    }
943}
944
945impl From<FrameHeaderError> for FrameDecoderError {
946    fn from(val: FrameHeaderError) -> Self {
947        Self::FrameHeaderError(val)
948    }
949}
950
951impl From<ReadFrameHeaderError> for FrameDecoderError {
952    fn from(val: ReadFrameHeaderError) -> Self {
953        Self::ReadFrameHeaderError(val)
954    }
955}
956
957#[derive(Debug)]
958#[non_exhaustive]
959pub enum DecompressLiteralsError {
960    MissingCompressedSize,
961    MissingNumStreams,
962    GetBitsError(GetBitsError),
963    HuffmanTableError(HuffmanTableError),
964    HuffmanDecoderError(HuffmanDecoderError),
965    UninitializedHuffmanTable,
966    MissingBytesForJumpHeader { got: usize },
967    MissingBytesForLiterals { got: usize, needed: usize },
968    ExtraPadding { skipped_bits: i32 },
969    BitstreamReadMismatch { read_til: isize, expected: isize },
970    DecodedLiteralCountMismatch { decoded: usize, expected: usize },
971}
972
973#[cfg(feature = "std")]
974impl std::error::Error for DecompressLiteralsError {
975    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
976        match self {
977            DecompressLiteralsError::GetBitsError(source) => Some(source),
978            DecompressLiteralsError::HuffmanTableError(source) => Some(source),
979            DecompressLiteralsError::HuffmanDecoderError(source) => Some(source),
980            _ => None,
981        }
982    }
983}
984impl core::fmt::Display for DecompressLiteralsError {
985    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
986        match self {
987            DecompressLiteralsError::MissingCompressedSize => {
988                write!(
989                    f,
990                    "compressed size was none even though it must be set to something for compressed literals",
991                )
992            }
993            DecompressLiteralsError::MissingNumStreams => {
994                write!(
995                    f,
996                    "num_streams was none even though it must be set to something (1 or 4) for compressed literals",
997                )
998            }
999            DecompressLiteralsError::GetBitsError(e) => write!(f, "{e:?}"),
1000            DecompressLiteralsError::HuffmanTableError(e) => write!(f, "{e:?}"),
1001            DecompressLiteralsError::HuffmanDecoderError(e) => write!(f, "{e:?}"),
1002            DecompressLiteralsError::UninitializedHuffmanTable => {
1003                write!(
1004                    f,
1005                    "Tried to reuse huffman table but it was never initialized",
1006                )
1007            }
1008            DecompressLiteralsError::MissingBytesForJumpHeader { got } => {
1009                write!(f, "Need 6 bytes to decode jump header, got {got} bytes",)
1010            }
1011            DecompressLiteralsError::MissingBytesForLiterals { got, needed } => {
1012                write!(
1013                    f,
1014                    "Need at least {needed} bytes to decode literals. Have: {got} bytes",
1015                )
1016            }
1017            DecompressLiteralsError::ExtraPadding { skipped_bits } => {
1018                write!(
1019                    f,
1020                    "Padding at the end of the sequence_section was more than a byte long: {skipped_bits} bits. Probably caused by data corruption",
1021                )
1022            }
1023            DecompressLiteralsError::BitstreamReadMismatch { read_til, expected } => {
1024                write!(
1025                    f,
1026                    "Bitstream was read till: {read_til}, should have been: {expected}",
1027                )
1028            }
1029            DecompressLiteralsError::DecodedLiteralCountMismatch { decoded, expected } => {
1030                write!(
1031                    f,
1032                    "Did not decode enough literals: {decoded}, Should have been: {expected}",
1033                )
1034            }
1035        }
1036    }
1037}
1038
1039impl From<HuffmanDecoderError> for DecompressLiteralsError {
1040    fn from(val: HuffmanDecoderError) -> Self {
1041        Self::HuffmanDecoderError(val)
1042    }
1043}
1044
1045impl From<GetBitsError> for DecompressLiteralsError {
1046    fn from(val: GetBitsError) -> Self {
1047        Self::GetBitsError(val)
1048    }
1049}
1050
1051impl From<HuffmanTableError> for DecompressLiteralsError {
1052    fn from(val: HuffmanTableError) -> Self {
1053        Self::HuffmanTableError(val)
1054    }
1055}
1056
1057#[derive(Debug)]
1058#[non_exhaustive]
1059pub enum ExecuteSequencesError {
1060    DecodebufferError(DecodeBufferError),
1061    NotEnoughBytesForSequence {
1062        wanted: usize,
1063        have: usize,
1064    },
1065    ZeroOffset,
1066    /// An inline sequence (`exec_sequence_inline`) would have written past
1067    /// the writable tail of the output buffer. Raised by every capacity-bounded
1068    /// backend that runs the inline executor (the fixed-capacity user slice and
1069    /// the pre-reserved flat buffer alike). Indicates the frame is corrupt: its
1070    /// sequences expand past the declared `frame_content_size` plus the
1071    /// caller-supplied `WILDCOPY_OVERLENGTH` slack. The fast-path check is
1072    /// per-sequence; the post-block FCS overflow check would also catch the
1073    /// same shape, but the per-sequence guard is what keeps the unsafe write
1074    /// surface inside the buffer on the way to the post-block check.
1075    OutputBufferOverflow {
1076        tail: usize,
1077        requested: usize,
1078        capacity: usize,
1079    },
1080}
1081
1082impl core::fmt::Display for ExecuteSequencesError {
1083    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1084        match self {
1085            ExecuteSequencesError::DecodebufferError(e) => {
1086                write!(f, "{e:?}")
1087            }
1088            ExecuteSequencesError::NotEnoughBytesForSequence { wanted, have } => {
1089                write!(
1090                    f,
1091                    "Sequence wants to copy up to byte {wanted}. Bytes in literalsbuffer: {have}"
1092                )
1093            }
1094            ExecuteSequencesError::ZeroOffset => {
1095                write!(f, "Illegal offset: 0 found")
1096            }
1097            ExecuteSequencesError::OutputBufferOverflow {
1098                tail,
1099                requested,
1100                capacity,
1101            } => {
1102                write!(
1103                    f,
1104                    "Inline sequence would write past the output buffer: tail={tail}, requested={requested}, capacity={capacity}"
1105                )
1106            }
1107        }
1108    }
1109}
1110
1111#[cfg(feature = "std")]
1112impl std::error::Error for ExecuteSequencesError {
1113    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
1114        match self {
1115            ExecuteSequencesError::DecodebufferError(source) => Some(source),
1116            _ => None,
1117        }
1118    }
1119}
1120
1121impl From<DecodeBufferError> for ExecuteSequencesError {
1122    fn from(val: DecodeBufferError) -> Self {
1123        Self::DecodebufferError(val)
1124    }
1125}
1126
1127impl From<crate::decoding::buffer_backend::BackendOverflow> for ExecuteSequencesError {
1128    fn from(val: crate::decoding::buffer_backend::BackendOverflow) -> Self {
1129        Self::OutputBufferOverflow {
1130            tail: val.tail,
1131            requested: val.requested,
1132            capacity: val.capacity,
1133        }
1134    }
1135}
1136
1137impl ExecuteSequencesError {
1138    /// `Some(requested)` when this error is a fixed-capacity output-buffer
1139    /// overshoot from the Compressed-block sequence executor — either the
1140    /// inline-sequence path ([`Self::OutputBufferOverflow`]) or the
1141    /// match-repeat fallback ([`DecodeBufferError::OutputBufferOverflow`]
1142    /// wrapped in [`Self::DecodebufferError`]). `requested` is the byte
1143    /// count the failing write tried to append past the slice end.
1144    ///
1145    /// `None` for every non-overflow variant. Used by
1146    /// `FrameDecoder::run_direct_decode` to fold an in-block Compressed
1147    /// overshoot into the same `FrameContentSizeMismatch` contract the
1148    /// Raw/RLE [`DecodeBlockContentError::BackendOverflow`] arm already
1149    /// produces — both mean "the frame's content expands past the
1150    /// declared `frame_content_size`".
1151    pub(crate) fn output_overflow_requested(&self) -> Option<usize> {
1152        match self {
1153            ExecuteSequencesError::OutputBufferOverflow { requested, .. } => Some(*requested),
1154            ExecuteSequencesError::DecodebufferError(DecodeBufferError::OutputBufferOverflow {
1155                requested,
1156                ..
1157            }) => Some(*requested),
1158            _ => None,
1159        }
1160    }
1161}
1162
1163#[derive(Debug)]
1164#[non_exhaustive]
1165pub enum DecodeSequenceError {
1166    GetBitsError(GetBitsError),
1167    FSEDecoderError(FSEDecoderError),
1168    FSETableError(FSETableError),
1169    ExtraPadding {
1170        skipped_bits: i32,
1171    },
1172    UnsupportedOffset {
1173        offset_code: u8,
1174    },
1175    ZeroOffset,
1176    NotEnoughBytesForNumSequences,
1177    ExtraBits {
1178        bits_remaining: isize,
1179    },
1180    MissingCompressionMode,
1181    MissingByteForRleLlTable,
1182    MissingByteForRleOfTable,
1183    MissingByteForRleMlTable,
1184    /// An RLE-mode sequence table's single symbol code is out of range
1185    /// for its axis (LL/ML/OF). `axis` names the axis; `code` is the
1186    /// offending value read from the stream.
1187    InvalidRleCode {
1188        axis: &'static str,
1189        code: u8,
1190    },
1191}
1192
1193#[cfg(feature = "std")]
1194impl std::error::Error for DecodeSequenceError {
1195    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
1196        match self {
1197            DecodeSequenceError::GetBitsError(source) => Some(source),
1198            DecodeSequenceError::FSEDecoderError(source) => Some(source),
1199            DecodeSequenceError::FSETableError(source) => Some(source),
1200            _ => None,
1201        }
1202    }
1203}
1204
1205impl core::fmt::Display for DecodeSequenceError {
1206    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1207        match self {
1208            DecodeSequenceError::GetBitsError(e) => write!(f, "{e:?}"),
1209            DecodeSequenceError::FSEDecoderError(e) => write!(f, "{e:?}"),
1210            DecodeSequenceError::FSETableError(e) => write!(f, "{e:?}"),
1211            DecodeSequenceError::ExtraPadding { skipped_bits } => {
1212                write!(
1213                    f,
1214                    "Padding at the end of the sequence_section was more than a byte long: {skipped_bits} bits. Probably caused by data corruption",
1215                )
1216            }
1217            DecodeSequenceError::UnsupportedOffset { offset_code } => {
1218                write!(
1219                    f,
1220                    "Do not support offsets bigger than 1<<32; got: {offset_code}",
1221                )
1222            }
1223            DecodeSequenceError::ZeroOffset => write!(
1224                f,
1225                "Read an offset == 0. That is an illegal value for offsets"
1226            ),
1227            DecodeSequenceError::NotEnoughBytesForNumSequences => write!(
1228                f,
1229                "Bytestream did not contain enough bytes to decode num_sequences"
1230            ),
1231            DecodeSequenceError::ExtraBits { bits_remaining } => write!(f, "{bits_remaining}"),
1232            DecodeSequenceError::MissingCompressionMode => write!(
1233                f,
1234                "compression modes are none but they must be set to something"
1235            ),
1236            DecodeSequenceError::MissingByteForRleLlTable => {
1237                write!(f, "Need a byte to read for RLE ll table")
1238            }
1239            DecodeSequenceError::MissingByteForRleOfTable => {
1240                write!(f, "Need a byte to read for RLE of table")
1241            }
1242            DecodeSequenceError::MissingByteForRleMlTable => {
1243                write!(f, "Need a byte to read for RLE ml table")
1244            }
1245            DecodeSequenceError::InvalidRleCode { axis, code } => {
1246                write!(f, "RLE {axis} table code {code} is out of range")
1247            }
1248        }
1249    }
1250}
1251
1252impl From<GetBitsError> for DecodeSequenceError {
1253    fn from(val: GetBitsError) -> Self {
1254        Self::GetBitsError(val)
1255    }
1256}
1257
1258impl From<FSETableError> for DecodeSequenceError {
1259    fn from(val: FSETableError) -> Self {
1260        Self::FSETableError(val)
1261    }
1262}
1263
1264impl From<FSEDecoderError> for DecodeSequenceError {
1265    fn from(val: FSEDecoderError) -> Self {
1266        Self::FSEDecoderError(val)
1267    }
1268}
1269
1270#[derive(Debug)]
1271#[non_exhaustive]
1272pub enum LiteralsSectionParseError {
1273    IllegalLiteralSectionType { got: u8 },
1274    GetBitsError(GetBitsError),
1275    NotEnoughBytes { have: usize, need: u8 },
1276}
1277
1278#[cfg(feature = "std")]
1279impl std::error::Error for LiteralsSectionParseError {
1280    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
1281        match self {
1282            LiteralsSectionParseError::GetBitsError(source) => Some(source),
1283            _ => None,
1284        }
1285    }
1286}
1287impl core::fmt::Display for LiteralsSectionParseError {
1288    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1289        match self {
1290            LiteralsSectionParseError::IllegalLiteralSectionType { got } => {
1291                write!(
1292                    f,
1293                    "Illegal literalssectiontype. Is: {got}, must be in: 0, 1, 2, 3"
1294                )
1295            }
1296            LiteralsSectionParseError::GetBitsError(e) => write!(f, "{e:?}"),
1297            LiteralsSectionParseError::NotEnoughBytes { have, need } => {
1298                write!(
1299                    f,
1300                    "Not enough byte to parse the literals section header. Have: {have}, Need: {need}",
1301                )
1302            }
1303        }
1304    }
1305}
1306
1307impl From<GetBitsError> for LiteralsSectionParseError {
1308    fn from(val: GetBitsError) -> Self {
1309        Self::GetBitsError(val)
1310    }
1311}
1312
1313impl core::fmt::Display for LiteralsSectionType {
1314    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> Result<(), core::fmt::Error> {
1315        match self {
1316            LiteralsSectionType::Compressed => write!(f, "Compressed"),
1317            LiteralsSectionType::Raw => write!(f, "Raw"),
1318            LiteralsSectionType::RLE => write!(f, "RLE"),
1319            LiteralsSectionType::Treeless => write!(f, "Treeless"),
1320        }
1321    }
1322}
1323
1324#[derive(Debug)]
1325#[non_exhaustive]
1326pub enum SequencesHeaderParseError {
1327    NotEnoughBytes { need_at_least: u8, got: usize },
1328}
1329
1330#[cfg(feature = "std")]
1331impl std::error::Error for SequencesHeaderParseError {}
1332
1333impl core::fmt::Display for SequencesHeaderParseError {
1334    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1335        match self {
1336            SequencesHeaderParseError::NotEnoughBytes { need_at_least, got } => {
1337                write!(
1338                    f,
1339                    "source must have at least {need_at_least} bytes to parse header; got {got} bytes",
1340                )
1341            }
1342        }
1343    }
1344}
1345
1346#[derive(Debug)]
1347#[non_exhaustive]
1348pub enum FSETableError {
1349    AccLogIsZero,
1350    AccLogTooBig {
1351        got: u8,
1352        max: u8,
1353    },
1354    GetBitsError(GetBitsError),
1355    ProbabilityCounterMismatch {
1356        got: u32,
1357        expected_sum: u32,
1358        symbol_probabilities: Vec<i32>,
1359    },
1360    TooManySymbols {
1361        got: usize,
1362    },
1363    /// Probability value outside the RFC 8878 §4.1.1 allowed set
1364    /// `{-1, 0, 1..=table_size}`. Carries the violating value, the
1365    /// table size (`1 << accuracy_log`) and `accuracy_log` so the
1366    /// caller can pinpoint the failure without re-deriving the bound.
1367    InvalidProbability {
1368        value: i32,
1369        table_size: u32,
1370        accuracy_log: u8,
1371    },
1372    /// `calc_baseline_and_numbits` produced a state-entry whose bit
1373    /// width exceeds the table's accuracy log, violating the
1374    /// `new_state + (1 << num_bits) - 1 < table_size` invariant that
1375    /// the unchecked `read_entry` decode hot path relies on. The
1376    /// triggering probability is in-range per RFC 8878 §4.1.1; the
1377    /// failure is an internal table-shape inconsistency surfaced
1378    /// against the public `build_from_probabilities` API.
1379    TableInvariantViolation {
1380        prob: i32,
1381        symbol: u8,
1382        num_bits: u8,
1383        accuracy_log: u8,
1384    },
1385}
1386
1387#[cfg(feature = "std")]
1388impl std::error::Error for FSETableError {
1389    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
1390        match self {
1391            FSETableError::GetBitsError(source) => Some(source),
1392            _ => None,
1393        }
1394    }
1395}
1396
1397impl core::fmt::Display for FSETableError {
1398    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1399        match self {
1400            FSETableError::AccLogIsZero => write!(f, "Acclog must be at least 1"),
1401            FSETableError::AccLogTooBig { got, max } => {
1402                write!(
1403                    f,
1404                    "Found FSE acc_log: {got} bigger than allowed maximum in this case: {max}"
1405                )
1406            }
1407            FSETableError::GetBitsError(e) => write!(f, "{e:?}"),
1408            FSETableError::ProbabilityCounterMismatch {
1409                got,
1410                expected_sum,
1411                symbol_probabilities,
1412            } => {
1413                write!(
1414                    f,
1415                    "FSE probability sum mismatch: got {got}, expected {expected_sum}. Indicates corrupted data or an invalid distribution\n {symbol_probabilities:?}",
1416                )
1417            }
1418            FSETableError::TooManySymbols { got } => {
1419                write!(
1420                    f,
1421                    "There are too many symbols in this distribution: {got}. Max: 256",
1422                )
1423            }
1424            FSETableError::InvalidProbability {
1425                value,
1426                table_size,
1427                accuracy_log,
1428            } => {
1429                write!(
1430                    f,
1431                    "FSE probability value {value} is outside the RFC 8878 allowed set (must be -1, 0, or in 1..={table_size}; accuracy_log={accuracy_log})",
1432                )
1433            }
1434            FSETableError::TableInvariantViolation {
1435                prob,
1436                symbol,
1437                num_bits,
1438                accuracy_log,
1439            } => {
1440                write!(
1441                    f,
1442                    "FSE table invariant violation: symbol {symbol} (prob {prob}) produced num_bits {num_bits} > accuracy_log {accuracy_log}",
1443                )
1444            }
1445        }
1446    }
1447}
1448
1449impl From<GetBitsError> for FSETableError {
1450    fn from(val: GetBitsError) -> Self {
1451        Self::GetBitsError(val)
1452    }
1453}
1454
1455#[derive(Debug)]
1456#[non_exhaustive]
1457pub enum FSEDecoderError {
1458    GetBitsError(GetBitsError),
1459    TableIsUninitialized,
1460    /// Externally constructed `FSETable` violates the
1461    /// `decode.len() == 1 << accuracy_log` shape invariant. Only
1462    /// reachable under `feature = "fuzz-exports"`, where fuzz
1463    /// harnesses can set the `FSETable.decode` / `accuracy_log`
1464    /// fields directly and skip `build_decoding_table`.
1465    InvalidTableShape {
1466        decode_len: usize,
1467        accuracy_log: u8,
1468    },
1469}
1470
1471#[cfg(feature = "std")]
1472impl std::error::Error for FSEDecoderError {
1473    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
1474        match self {
1475            FSEDecoderError::GetBitsError(source) => Some(source),
1476            _ => None,
1477        }
1478    }
1479}
1480
1481impl core::fmt::Display for FSEDecoderError {
1482    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1483        match self {
1484            FSEDecoderError::GetBitsError(e) => write!(f, "{e:?}"),
1485            FSEDecoderError::TableIsUninitialized => {
1486                write!(f, "Tried to use an uninitialized table!")
1487            }
1488            FSEDecoderError::InvalidTableShape {
1489                decode_len,
1490                accuracy_log,
1491            } => match 1usize.checked_shl((*accuracy_log).into()) {
1492                Some(expected) => write!(
1493                    f,
1494                    "FSETable shape invariant violated: decode.len() = {decode_len}, expected 1 << accuracy_log = {expected} (accuracy_log = {accuracy_log})",
1495                ),
1496                None => write!(
1497                    f,
1498                    "FSETable shape invariant violated: decode.len() = {decode_len}, accuracy_log = {accuracy_log} overflows 1 << accuracy_log for usize",
1499                ),
1500            },
1501        }
1502    }
1503}
1504
1505impl From<GetBitsError> for FSEDecoderError {
1506    fn from(val: GetBitsError) -> Self {
1507        Self::GetBitsError(val)
1508    }
1509}
1510
1511#[derive(Debug)]
1512#[non_exhaustive]
1513pub enum HuffmanTableError {
1514    GetBitsError(GetBitsError),
1515    FSEDecoderError(FSEDecoderError),
1516    FSETableError(FSETableError),
1517    SourceIsEmpty,
1518    NotEnoughBytesForWeights {
1519        got_bytes: usize,
1520        expected_bytes: u8,
1521    },
1522    ExtraPadding {
1523        skipped_bits: i32,
1524    },
1525    TooManyWeights {
1526        got: usize,
1527    },
1528    MissingWeights,
1529    LeftoverIsNotAPowerOf2 {
1530        got: u32,
1531    },
1532    NotEnoughBytesToDecompressWeights {
1533        have: usize,
1534        need: usize,
1535    },
1536    FSETableUsedTooManyBytes {
1537        used: usize,
1538        available_bytes: u8,
1539    },
1540    NotEnoughBytesInSource {
1541        got: usize,
1542        need: usize,
1543    },
1544    WeightBiggerThanMaxNumBits {
1545        got: u8,
1546    },
1547    MaxBitsTooHigh {
1548        got: u8,
1549    },
1550}
1551
1552#[cfg(feature = "std")]
1553impl StdError for HuffmanTableError {
1554    fn source(&self) -> Option<&(dyn StdError + 'static)> {
1555        match self {
1556            HuffmanTableError::GetBitsError(source) => Some(source),
1557            HuffmanTableError::FSEDecoderError(source) => Some(source),
1558            HuffmanTableError::FSETableError(source) => Some(source),
1559            _ => None,
1560        }
1561    }
1562}
1563
1564impl core::fmt::Display for HuffmanTableError {
1565    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> ::core::fmt::Result {
1566        match self {
1567            HuffmanTableError::GetBitsError(e) => write!(f, "{e:?}"),
1568            HuffmanTableError::FSEDecoderError(e) => write!(f, "{e:?}"),
1569            HuffmanTableError::FSETableError(e) => write!(f, "{e:?}"),
1570            HuffmanTableError::SourceIsEmpty => write!(f, "Source needs to have at least one byte"),
1571            HuffmanTableError::NotEnoughBytesForWeights {
1572                got_bytes,
1573                expected_bytes,
1574            } => {
1575                write!(
1576                    f,
1577                    "Header says there should be {expected_bytes} bytes for the weights but there are only {got_bytes} bytes in the stream"
1578                )
1579            }
1580            HuffmanTableError::ExtraPadding { skipped_bits } => {
1581                write!(
1582                    f,
1583                    "Padding at the end of the sequence_section was more than a byte long: {skipped_bits} bits. Probably caused by data corruption",
1584                )
1585            }
1586            HuffmanTableError::TooManyWeights { got } => {
1587                write!(
1588                    f,
1589                    "More than 255 weights decoded (got {got} weights). Stream is probably corrupted",
1590                )
1591            }
1592            HuffmanTableError::MissingWeights => {
1593                write!(f, "Can\'t build huffman table without any weights")
1594            }
1595            HuffmanTableError::LeftoverIsNotAPowerOf2 { got } => {
1596                write!(f, "Leftover must be power of two but is: {got}")
1597            }
1598            HuffmanTableError::NotEnoughBytesToDecompressWeights { have, need } => {
1599                write!(
1600                    f,
1601                    "Not enough bytes in stream to decompress weights. Is: {have}, Should be: {need}",
1602                )
1603            }
1604            HuffmanTableError::FSETableUsedTooManyBytes {
1605                used,
1606                available_bytes,
1607            } => {
1608                write!(
1609                    f,
1610                    "FSE table used more bytes: {used} than were meant to be used for the whole stream of huffman weights ({available_bytes})",
1611                )
1612            }
1613            HuffmanTableError::NotEnoughBytesInSource { got, need } => {
1614                write!(f, "Source needs to have at least {need} bytes, got: {got}",)
1615            }
1616            HuffmanTableError::WeightBiggerThanMaxNumBits { got } => {
1617                write!(
1618                    f,
1619                    "Cant have weight: {} bigger than max_num_bits: {}",
1620                    got,
1621                    crate::huff0::MAX_MAX_NUM_BITS,
1622                )
1623            }
1624            HuffmanTableError::MaxBitsTooHigh { got } => {
1625                write!(
1626                    f,
1627                    "max_bits derived from weights is: {} should be lower than: {}",
1628                    got,
1629                    crate::huff0::MAX_MAX_NUM_BITS,
1630                )
1631            }
1632        }
1633    }
1634}
1635
1636impl From<GetBitsError> for HuffmanTableError {
1637    fn from(val: GetBitsError) -> Self {
1638        Self::GetBitsError(val)
1639    }
1640}
1641
1642impl From<FSEDecoderError> for HuffmanTableError {
1643    fn from(val: FSEDecoderError) -> Self {
1644        Self::FSEDecoderError(val)
1645    }
1646}
1647
1648impl From<FSETableError> for HuffmanTableError {
1649    fn from(val: FSETableError) -> Self {
1650        Self::FSETableError(val)
1651    }
1652}
1653
1654#[derive(Debug)]
1655#[non_exhaustive]
1656pub enum HuffmanDecoderError {
1657    GetBitsError(GetBitsError),
1658}
1659
1660impl core::fmt::Display for HuffmanDecoderError {
1661    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1662        match self {
1663            HuffmanDecoderError::GetBitsError(e) => write!(f, "{e:?}"),
1664        }
1665    }
1666}
1667
1668#[cfg(feature = "std")]
1669impl StdError for HuffmanDecoderError {
1670    fn source(&self) -> Option<&(dyn StdError + 'static)> {
1671        match self {
1672            HuffmanDecoderError::GetBitsError(source) => Some(source),
1673        }
1674    }
1675}
1676
1677impl From<GetBitsError> for HuffmanDecoderError {
1678    fn from(val: GetBitsError) -> Self {
1679        Self::GetBitsError(val)
1680    }
1681}
1682
1683#[cfg(test)]
1684mod tests;