ruzstd/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: {}, Should be one of: 0, 1, 2, 3",
24                got
25            ),
26        }
27    }
28}
29
30#[cfg(feature = "std")]
31impl StdError for FrameDescriptorError {}
32
33#[derive(Debug)]
34#[non_exhaustive]
35pub enum FrameHeaderError {
36    WindowTooBig { got: u64 },
37    WindowTooSmall { got: u64 },
38    FrameDescriptorError(FrameDescriptorError),
39    DictIdTooSmall { got: usize, expected: usize },
40    MismatchedFrameSize { got: usize, expected: u8 },
41    FrameSizeIsZero,
42    InvalidFrameSize { got: u8 },
43}
44
45impl fmt::Display for FrameHeaderError {
46    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
47        match self {
48            Self::WindowTooBig { got } => write!(
49                f,
50                "window_size bigger than allowed maximum. Is: {}, Should be lower than: {}",
51                got,
52                crate::common::MAX_WINDOW_SIZE
53            ),
54            Self::WindowTooSmall { got } => write!(
55                f,
56                "window_size smaller than allowed minimum. Is: {}, Should be greater than: {}",
57                got,
58                crate::common::MIN_WINDOW_SIZE
59            ),
60            Self::FrameDescriptorError(e) => write!(f, "{:?}", e),
61            Self::DictIdTooSmall { got, expected } => write!(
62                f,
63                "Not enough bytes in dict_id. Is: {}, Should be: {}",
64                got, expected
65            ),
66            Self::MismatchedFrameSize { got, expected } => write!(
67                f,
68                "frame_content_size does not have the right length. Is: {}, Should be: {}",
69                got, expected
70            ),
71            Self::FrameSizeIsZero => write!(f, "frame_content_size was zero"),
72            Self::InvalidFrameSize { got } => write!(
73                f,
74                "Invalid frame_content_size. Is: {}, Should be one of 1, 2, 4, 8 bytes",
75                got
76            ),
77        }
78    }
79}
80
81#[cfg(feature = "std")]
82impl StdError for FrameHeaderError {
83    fn source(&self) -> Option<&(dyn StdError + 'static)> {
84        match self {
85            FrameHeaderError::FrameDescriptorError(source) => Some(source),
86            _ => None,
87        }
88    }
89}
90
91impl From<FrameDescriptorError> for FrameHeaderError {
92    fn from(error: FrameDescriptorError) -> Self {
93        Self::FrameDescriptorError(error)
94    }
95}
96
97#[derive(Debug)]
98#[non_exhaustive]
99pub enum ReadFrameHeaderError {
100    MagicNumberReadError(Error),
101    BadMagicNumber(u32),
102    FrameDescriptorReadError(Error),
103    InvalidFrameDescriptor(FrameDescriptorError),
104    WindowDescriptorReadError(Error),
105    DictionaryIdReadError(Error),
106    FrameContentSizeReadError(Error),
107    SkipFrame { magic_number: u32, length: u32 },
108}
109
110impl fmt::Display for ReadFrameHeaderError {
111    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
112        match self {
113            Self::MagicNumberReadError(e) => write!(f, "Error while reading magic number: {}", e),
114            Self::BadMagicNumber(e) => write!(f, "Read wrong magic number: 0x{:X}", e),
115            Self::FrameDescriptorReadError(e) => {
116                write!(f, "Error while reading frame descriptor: {}", e)
117            }
118            Self::InvalidFrameDescriptor(e) => write!(f, "{:?}", e),
119            Self::WindowDescriptorReadError(e) => {
120                write!(f, "Error while reading window descriptor: {}", e)
121            }
122            Self::DictionaryIdReadError(e) => write!(f, "Error while reading dictionary id: {}", e),
123            Self::FrameContentSizeReadError(e) => {
124                write!(f, "Error while reading frame content size: {}", e)
125            }
126            Self::SkipFrame {
127                magic_number,
128                length,
129            } => write!(
130                f,
131                "SkippableFrame encountered with MagicNumber 0x{:X} and length {} bytes",
132                magic_number, length
133            ),
134        }
135    }
136}
137
138#[cfg(feature = "std")]
139impl StdError for ReadFrameHeaderError {
140    fn source(&self) -> Option<&(dyn StdError + 'static)> {
141        match self {
142            ReadFrameHeaderError::MagicNumberReadError(source) => Some(source),
143            ReadFrameHeaderError::FrameDescriptorReadError(source) => Some(source),
144            ReadFrameHeaderError::InvalidFrameDescriptor(source) => Some(source),
145            ReadFrameHeaderError::WindowDescriptorReadError(source) => Some(source),
146            ReadFrameHeaderError::DictionaryIdReadError(source) => Some(source),
147            ReadFrameHeaderError::FrameContentSizeReadError(source) => Some(source),
148            _ => None,
149        }
150    }
151}
152
153impl From<FrameDescriptorError> for ReadFrameHeaderError {
154    fn from(error: FrameDescriptorError) -> Self {
155        Self::InvalidFrameDescriptor(error)
156    }
157}
158
159#[derive(Debug)]
160#[non_exhaustive]
161pub enum BlockHeaderReadError {
162    ReadError(Error),
163    FoundReservedBlock,
164    BlockTypeError(BlockTypeError),
165    BlockSizeError(BlockSizeError),
166}
167
168#[cfg(feature = "std")]
169impl std::error::Error for BlockHeaderReadError {
170    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
171        match self {
172            BlockHeaderReadError::ReadError(source) => Some(source),
173            BlockHeaderReadError::BlockTypeError(source) => Some(source),
174            BlockHeaderReadError::BlockSizeError(source) => Some(source),
175            BlockHeaderReadError::FoundReservedBlock => None,
176        }
177    }
178}
179
180impl ::core::fmt::Display for BlockHeaderReadError {
181    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> ::core::fmt::Result {
182        match self {
183            BlockHeaderReadError::ReadError(_) => write!(f, "Error while reading the block header"),
184            BlockHeaderReadError::FoundReservedBlock => write!(
185                f,
186                "Reserved block occured. This is considered corruption by the documentation"
187            ),
188            BlockHeaderReadError::BlockTypeError(e) => write!(f, "Error getting block type: {}", e),
189            BlockHeaderReadError::BlockSizeError(e) => {
190                write!(f, "Error getting block content size: {}", e)
191            }
192        }
193    }
194}
195
196impl From<Error> for BlockHeaderReadError {
197    fn from(val: Error) -> Self {
198        Self::ReadError(val)
199    }
200}
201
202impl From<BlockTypeError> for BlockHeaderReadError {
203    fn from(val: BlockTypeError) -> Self {
204        Self::BlockTypeError(val)
205    }
206}
207
208impl From<BlockSizeError> for BlockHeaderReadError {
209    fn from(val: BlockSizeError) -> Self {
210        Self::BlockSizeError(val)
211    }
212}
213
214#[derive(Debug)]
215#[non_exhaustive]
216pub enum BlockTypeError {
217    InvalidBlocktypeNumber { num: u8 },
218}
219
220#[cfg(feature = "std")]
221impl std::error::Error for BlockTypeError {}
222
223impl core::fmt::Display for BlockTypeError {
224    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
225        match self {
226            BlockTypeError::InvalidBlocktypeNumber { num } => {
227                write!(f,
228                    "Invalid Blocktype number. Is: {} Should be one of: 0, 1, 2, 3 (3 is reserved though",
229                    num,
230                )
231            }
232        }
233    }
234}
235
236#[derive(Debug)]
237#[non_exhaustive]
238pub enum BlockSizeError {
239    BlockSizeTooLarge { size: u32 },
240}
241
242#[cfg(feature = "std")]
243impl std::error::Error for BlockSizeError {}
244
245impl core::fmt::Display for BlockSizeError {
246    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
247        match self {
248            BlockSizeError::BlockSizeTooLarge { size } => {
249                write!(
250                    f,
251                    "Blocksize was bigger than the absolute maximum {} (128kb). Is: {}",
252                    crate::common::MAX_BLOCK_SIZE,
253                    size,
254                )
255            }
256        }
257    }
258}
259
260#[derive(Debug)]
261#[non_exhaustive]
262pub enum DecompressBlockError {
263    BlockContentReadError(Error),
264    MalformedSectionHeader {
265        expected_len: usize,
266        remaining_bytes: usize,
267    },
268    DecompressLiteralsError(DecompressLiteralsError),
269    LiteralsSectionParseError(LiteralsSectionParseError),
270    SequencesHeaderParseError(SequencesHeaderParseError),
271    DecodeSequenceError(DecodeSequenceError),
272    ExecuteSequencesError(ExecuteSequencesError),
273}
274
275#[cfg(feature = "std")]
276impl std::error::Error for DecompressBlockError {
277    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
278        match self {
279            DecompressBlockError::BlockContentReadError(source) => Some(source),
280            DecompressBlockError::DecompressLiteralsError(source) => Some(source),
281            DecompressBlockError::LiteralsSectionParseError(source) => Some(source),
282            DecompressBlockError::SequencesHeaderParseError(source) => Some(source),
283            DecompressBlockError::DecodeSequenceError(source) => Some(source),
284            DecompressBlockError::ExecuteSequencesError(source) => Some(source),
285            _ => None,
286        }
287    }
288}
289
290impl core::fmt::Display for DecompressBlockError {
291    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
292        match self {
293            DecompressBlockError::BlockContentReadError(e) => {
294                write!(f, "Error while reading the block content: {}", e)
295            }
296            DecompressBlockError::MalformedSectionHeader {
297                expected_len,
298                remaining_bytes,
299            } => {
300                write!(f,
301                    "Malformed section header. Says literals would be this long: {} but there are only {} bytes left",
302                    expected_len,
303                    remaining_bytes,
304                )
305            }
306            DecompressBlockError::DecompressLiteralsError(e) => write!(f, "{:?}", e),
307            DecompressBlockError::LiteralsSectionParseError(e) => write!(f, "{:?}", e),
308            DecompressBlockError::SequencesHeaderParseError(e) => write!(f, "{:?}", e),
309            DecompressBlockError::DecodeSequenceError(e) => write!(f, "{:?}", e),
310            DecompressBlockError::ExecuteSequencesError(e) => write!(f, "{:?}", e),
311        }
312    }
313}
314
315impl From<Error> for DecompressBlockError {
316    fn from(val: Error) -> Self {
317        Self::BlockContentReadError(val)
318    }
319}
320
321impl From<DecompressLiteralsError> for DecompressBlockError {
322    fn from(val: DecompressLiteralsError) -> Self {
323        Self::DecompressLiteralsError(val)
324    }
325}
326
327impl From<LiteralsSectionParseError> for DecompressBlockError {
328    fn from(val: LiteralsSectionParseError) -> Self {
329        Self::LiteralsSectionParseError(val)
330    }
331}
332
333impl From<SequencesHeaderParseError> for DecompressBlockError {
334    fn from(val: SequencesHeaderParseError) -> Self {
335        Self::SequencesHeaderParseError(val)
336    }
337}
338
339impl From<DecodeSequenceError> for DecompressBlockError {
340    fn from(val: DecodeSequenceError) -> Self {
341        Self::DecodeSequenceError(val)
342    }
343}
344
345impl From<ExecuteSequencesError> for DecompressBlockError {
346    fn from(val: ExecuteSequencesError) -> Self {
347        Self::ExecuteSequencesError(val)
348    }
349}
350
351#[derive(Debug)]
352#[non_exhaustive]
353pub enum DecodeBlockContentError {
354    DecoderStateIsFailed,
355    ExpectedHeaderOfPreviousBlock,
356    ReadError { step: BlockType, source: Error },
357    DecompressBlockError(DecompressBlockError),
358}
359
360#[cfg(feature = "std")]
361impl std::error::Error for DecodeBlockContentError {
362    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
363        match self {
364            DecodeBlockContentError::ReadError { step: _, source } => Some(source),
365            DecodeBlockContentError::DecompressBlockError(source) => Some(source),
366            _ => None,
367        }
368    }
369}
370
371impl core::fmt::Display for DecodeBlockContentError {
372    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
373        match self {
374            DecodeBlockContentError::DecoderStateIsFailed => {
375                write!(
376                    f,
377                    "Can't decode next block if failed along the way. Results will be nonsense",
378                )
379            }
380            DecodeBlockContentError::ExpectedHeaderOfPreviousBlock => {
381                write!(f,
382                            "Can't decode next block body, while expecting to decode the header of the previous block. Results will be nonsense",
383                        )
384            }
385            DecodeBlockContentError::ReadError { step, source } => {
386                write!(f, "Error while reading bytes for {}: {}", step, source,)
387            }
388            DecodeBlockContentError::DecompressBlockError(e) => write!(f, "{:?}", e),
389        }
390    }
391}
392
393impl From<DecompressBlockError> for DecodeBlockContentError {
394    fn from(val: DecompressBlockError) -> Self {
395        Self::DecompressBlockError(val)
396    }
397}
398
399#[derive(Debug)]
400#[non_exhaustive]
401pub enum DecodeBufferError {
402    NotEnoughBytesInDictionary { got: usize, need: usize },
403    OffsetTooBig { offset: usize, buf_len: usize },
404}
405
406#[cfg(feature = "std")]
407impl std::error::Error for DecodeBufferError {}
408
409impl core::fmt::Display for DecodeBufferError {
410    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
411        match self {
412            DecodeBufferError::NotEnoughBytesInDictionary { got, need } => {
413                write!(
414                    f,
415                    "Need {} bytes from the dictionary but it is only {} bytes long",
416                    need, got,
417                )
418            }
419            DecodeBufferError::OffsetTooBig { offset, buf_len } => {
420                write!(f, "offset: {} bigger than buffer: {}", offset, buf_len,)
421            }
422        }
423    }
424}
425
426#[derive(Debug)]
427#[non_exhaustive]
428pub enum DictionaryDecodeError {
429    BadMagicNum { got: [u8; 4] },
430    FSETableError(FSETableError),
431    HuffmanTableError(HuffmanTableError),
432}
433
434#[cfg(feature = "std")]
435impl std::error::Error for DictionaryDecodeError {
436    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
437        match self {
438            DictionaryDecodeError::FSETableError(source) => Some(source),
439            DictionaryDecodeError::HuffmanTableError(source) => Some(source),
440            _ => None,
441        }
442    }
443}
444
445impl core::fmt::Display for DictionaryDecodeError {
446    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
447        match self {
448            DictionaryDecodeError::BadMagicNum { got } => {
449                write!(
450                    f,
451                    "Bad magic_num at start of the dictionary; Got: {:#04X?}, Expected: {:#04x?}",
452                    got,
453                    crate::decoding::dictionary::MAGIC_NUM,
454                )
455            }
456            DictionaryDecodeError::FSETableError(e) => write!(f, "{:?}", e),
457            DictionaryDecodeError::HuffmanTableError(e) => write!(f, "{:?}", e),
458        }
459    }
460}
461
462impl From<FSETableError> for DictionaryDecodeError {
463    fn from(val: FSETableError) -> Self {
464        Self::FSETableError(val)
465    }
466}
467
468impl From<HuffmanTableError> for DictionaryDecodeError {
469    fn from(val: HuffmanTableError) -> Self {
470        Self::HuffmanTableError(val)
471    }
472}
473
474#[derive(Debug)]
475#[non_exhaustive]
476pub enum FrameDecoderError {
477    ReadFrameHeaderError(ReadFrameHeaderError),
478    FrameHeaderError(FrameHeaderError),
479    WindowSizeTooBig { requested: u64 },
480    DictionaryDecodeError(DictionaryDecodeError),
481    FailedToReadBlockHeader(BlockHeaderReadError),
482    FailedToReadBlockBody(DecodeBlockContentError),
483    FailedToReadChecksum(Error),
484    NotYetInitialized,
485    FailedToInitialize(FrameHeaderError),
486    FailedToDrainDecodebuffer(Error),
487    FailedToSkipFrame,
488    TargetTooSmall,
489    DictNotProvided { dict_id: u32 },
490}
491
492#[cfg(feature = "std")]
493impl StdError for FrameDecoderError {
494    fn source(&self) -> Option<&(dyn StdError + 'static)> {
495        match self {
496            FrameDecoderError::ReadFrameHeaderError(source) => Some(source),
497            FrameDecoderError::FrameHeaderError(source) => Some(source),
498            FrameDecoderError::DictionaryDecodeError(source) => Some(source),
499            FrameDecoderError::FailedToReadBlockHeader(source) => Some(source),
500            FrameDecoderError::FailedToReadBlockBody(source) => Some(source),
501            FrameDecoderError::FailedToReadChecksum(source) => Some(source),
502            FrameDecoderError::FailedToInitialize(source) => Some(source),
503            FrameDecoderError::FailedToDrainDecodebuffer(source) => Some(source),
504            _ => None,
505        }
506    }
507}
508
509impl core::fmt::Display for FrameDecoderError {
510    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> ::core::fmt::Result {
511        match self {
512            FrameDecoderError::ReadFrameHeaderError(e) => {
513                write!(f, "{:?}", e)
514            }
515            FrameDecoderError::FrameHeaderError(e) => {
516                write!(f, "{:?}", e)
517            }
518            FrameDecoderError::WindowSizeTooBig { requested } => {
519                write!(
520                    f,
521                    "Specified window_size is too big; Requested: {}, Max: {}",
522                    requested,
523                    crate::common::MAX_WINDOW_SIZE,
524                )
525            }
526            FrameDecoderError::DictionaryDecodeError(e) => {
527                write!(f, "{:?}", e)
528            }
529            FrameDecoderError::FailedToReadBlockHeader(e) => {
530                write!(f, "Failed to parse/decode block body: {}", e)
531            }
532            FrameDecoderError::FailedToReadBlockBody(e) => {
533                write!(f, "Failed to parse block header: {}", e)
534            }
535            FrameDecoderError::FailedToReadChecksum(e) => {
536                write!(f, "Failed to read checksum: {}", e)
537            }
538            FrameDecoderError::NotYetInitialized => {
539                write!(f, "Decoder must initialized or reset before using it",)
540            }
541            FrameDecoderError::FailedToInitialize(e) => {
542                write!(f, "Decoder encountered error while initializing: {}", e)
543            }
544            FrameDecoderError::FailedToDrainDecodebuffer(e) => {
545                write!(
546                    f,
547                    "Decoder encountered error while draining the decodebuffer: {}",
548                    e,
549                )
550            }
551            FrameDecoderError::FailedToSkipFrame => {
552                write!(
553                    f,
554                    "Failed to skip bytes for the length given in the frame header"
555                )
556            }
557            FrameDecoderError::TargetTooSmall => {
558                write!(f, "Target must have at least as many bytes as the contentsize of the frame reports")
559            }
560            FrameDecoderError::DictNotProvided { dict_id } => {
561                write!(f, "Frame header specified dictionary id 0x{:X} that wasnt provided by add_dict() or reset_with_dict()", dict_id)
562            }
563        }
564    }
565}
566
567impl From<DictionaryDecodeError> for FrameDecoderError {
568    fn from(val: DictionaryDecodeError) -> Self {
569        Self::DictionaryDecodeError(val)
570    }
571}
572
573impl From<BlockHeaderReadError> for FrameDecoderError {
574    fn from(val: BlockHeaderReadError) -> Self {
575        Self::FailedToReadBlockHeader(val)
576    }
577}
578
579impl From<FrameHeaderError> for FrameDecoderError {
580    fn from(val: FrameHeaderError) -> Self {
581        Self::FrameHeaderError(val)
582    }
583}
584
585impl From<ReadFrameHeaderError> for FrameDecoderError {
586    fn from(val: ReadFrameHeaderError) -> Self {
587        Self::ReadFrameHeaderError(val)
588    }
589}
590
591#[derive(Debug)]
592#[non_exhaustive]
593pub enum DecompressLiteralsError {
594    MissingCompressedSize,
595    MissingNumStreams,
596    GetBitsError(GetBitsError),
597    HuffmanTableError(HuffmanTableError),
598    HuffmanDecoderError(HuffmanDecoderError),
599    UninitializedHuffmanTable,
600    MissingBytesForJumpHeader { got: usize },
601    MissingBytesForLiterals { got: usize, needed: usize },
602    ExtraPadding { skipped_bits: i32 },
603    BitstreamReadMismatch { read_til: isize, expected: isize },
604    DecodedLiteralCountMismatch { decoded: usize, expected: usize },
605}
606
607#[cfg(feature = "std")]
608impl std::error::Error for DecompressLiteralsError {
609    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
610        match self {
611            DecompressLiteralsError::GetBitsError(source) => Some(source),
612            DecompressLiteralsError::HuffmanTableError(source) => Some(source),
613            DecompressLiteralsError::HuffmanDecoderError(source) => Some(source),
614            _ => None,
615        }
616    }
617}
618impl core::fmt::Display for DecompressLiteralsError {
619    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
620        match self {
621            DecompressLiteralsError::MissingCompressedSize => {
622                write!(f,
623                    "compressed size was none even though it must be set to something for compressed literals",
624                )
625            }
626            DecompressLiteralsError::MissingNumStreams => {
627                write!(f,
628                    "num_streams was none even though it must be set to something (1 or 4) for compressed literals",
629                )
630            }
631            DecompressLiteralsError::GetBitsError(e) => write!(f, "{:?}", e),
632            DecompressLiteralsError::HuffmanTableError(e) => write!(f, "{:?}", e),
633            DecompressLiteralsError::HuffmanDecoderError(e) => write!(f, "{:?}", e),
634            DecompressLiteralsError::UninitializedHuffmanTable => {
635                write!(
636                    f,
637                    "Tried to reuse huffman table but it was never initialized",
638                )
639            }
640            DecompressLiteralsError::MissingBytesForJumpHeader { got } => {
641                write!(f, "Need 6 bytes to decode jump header, got {} bytes", got,)
642            }
643            DecompressLiteralsError::MissingBytesForLiterals { got, needed } => {
644                write!(
645                    f,
646                    "Need at least {} bytes to decode literals. Have: {} bytes",
647                    needed, got,
648                )
649            }
650            DecompressLiteralsError::ExtraPadding { skipped_bits } => {
651                write!(f,
652                    "Padding at the end of the sequence_section was more than a byte long: {} bits. Probably caused by data corruption",
653                    skipped_bits,
654                )
655            }
656            DecompressLiteralsError::BitstreamReadMismatch { read_til, expected } => {
657                write!(
658                    f,
659                    "Bitstream was read till: {}, should have been: {}",
660                    read_til, expected,
661                )
662            }
663            DecompressLiteralsError::DecodedLiteralCountMismatch { decoded, expected } => {
664                write!(
665                    f,
666                    "Did not decode enough literals: {}, Should have been: {}",
667                    decoded, expected,
668                )
669            }
670        }
671    }
672}
673
674impl From<HuffmanDecoderError> for DecompressLiteralsError {
675    fn from(val: HuffmanDecoderError) -> Self {
676        Self::HuffmanDecoderError(val)
677    }
678}
679
680impl From<GetBitsError> for DecompressLiteralsError {
681    fn from(val: GetBitsError) -> Self {
682        Self::GetBitsError(val)
683    }
684}
685
686impl From<HuffmanTableError> for DecompressLiteralsError {
687    fn from(val: HuffmanTableError) -> Self {
688        Self::HuffmanTableError(val)
689    }
690}
691
692#[derive(Debug)]
693#[non_exhaustive]
694pub enum ExecuteSequencesError {
695    DecodebufferError(DecodeBufferError),
696    NotEnoughBytesForSequence { wanted: usize, have: usize },
697    ZeroOffset,
698}
699
700impl core::fmt::Display for ExecuteSequencesError {
701    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
702        match self {
703            ExecuteSequencesError::DecodebufferError(e) => {
704                write!(f, "{:?}", e)
705            }
706            ExecuteSequencesError::NotEnoughBytesForSequence { wanted, have } => {
707                write!(
708                    f,
709                    "Sequence wants to copy up to byte {}. Bytes in literalsbuffer: {}",
710                    wanted, have
711                )
712            }
713            ExecuteSequencesError::ZeroOffset => {
714                write!(f, "Illegal offset: 0 found")
715            }
716        }
717    }
718}
719
720#[cfg(feature = "std")]
721impl std::error::Error for ExecuteSequencesError {
722    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
723        match self {
724            ExecuteSequencesError::DecodebufferError(source) => Some(source),
725            _ => None,
726        }
727    }
728}
729
730impl From<DecodeBufferError> for ExecuteSequencesError {
731    fn from(val: DecodeBufferError) -> Self {
732        Self::DecodebufferError(val)
733    }
734}
735
736#[derive(Debug)]
737#[non_exhaustive]
738pub enum DecodeSequenceError {
739    GetBitsError(GetBitsError),
740    FSEDecoderError(FSEDecoderError),
741    FSETableError(FSETableError),
742    ExtraPadding { skipped_bits: i32 },
743    UnsupportedOffset { offset_code: u8 },
744    ZeroOffset,
745    NotEnoughBytesForNumSequences,
746    ExtraBits { bits_remaining: isize },
747    MissingCompressionMode,
748    MissingByteForRleLlTable,
749    MissingByteForRleOfTable,
750    MissingByteForRleMlTable,
751}
752
753#[cfg(feature = "std")]
754impl std::error::Error for DecodeSequenceError {
755    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
756        match self {
757            DecodeSequenceError::GetBitsError(source) => Some(source),
758            DecodeSequenceError::FSEDecoderError(source) => Some(source),
759            DecodeSequenceError::FSETableError(source) => Some(source),
760            _ => None,
761        }
762    }
763}
764
765impl core::fmt::Display for DecodeSequenceError {
766    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
767        match self {
768            DecodeSequenceError::GetBitsError(e) => write!(f, "{:?}", e),
769            DecodeSequenceError::FSEDecoderError(e) => write!(f, "{:?}", e),
770            DecodeSequenceError::FSETableError(e) => write!(f, "{:?}", e),
771            DecodeSequenceError::ExtraPadding { skipped_bits } => {
772                write!(f,
773                    "Padding at the end of the sequence_section was more than a byte long: {} bits. Probably caused by data corruption",
774                    skipped_bits,
775                )
776            }
777            DecodeSequenceError::UnsupportedOffset { offset_code } => {
778                write!(
779                    f,
780                    "Do not support offsets bigger than 1<<32; got: {}",
781                    offset_code,
782                )
783            }
784            DecodeSequenceError::ZeroOffset => write!(
785                f,
786                "Read an offset == 0. That is an illegal value for offsets"
787            ),
788            DecodeSequenceError::NotEnoughBytesForNumSequences => write!(
789                f,
790                "Bytestream did not contain enough bytes to decode num_sequences"
791            ),
792            DecodeSequenceError::ExtraBits { bits_remaining } => write!(f, "{}", bits_remaining),
793            DecodeSequenceError::MissingCompressionMode => write!(
794                f,
795                "compression modes are none but they must be set to something"
796            ),
797            DecodeSequenceError::MissingByteForRleLlTable => {
798                write!(f, "Need a byte to read for RLE ll table")
799            }
800            DecodeSequenceError::MissingByteForRleOfTable => {
801                write!(f, "Need a byte to read for RLE of table")
802            }
803            DecodeSequenceError::MissingByteForRleMlTable => {
804                write!(f, "Need a byte to read for RLE ml table")
805            }
806        }
807    }
808}
809
810impl From<GetBitsError> for DecodeSequenceError {
811    fn from(val: GetBitsError) -> Self {
812        Self::GetBitsError(val)
813    }
814}
815
816impl From<FSETableError> for DecodeSequenceError {
817    fn from(val: FSETableError) -> Self {
818        Self::FSETableError(val)
819    }
820}
821
822impl From<FSEDecoderError> for DecodeSequenceError {
823    fn from(val: FSEDecoderError) -> Self {
824        Self::FSEDecoderError(val)
825    }
826}
827
828#[derive(Debug)]
829#[non_exhaustive]
830pub enum LiteralsSectionParseError {
831    IllegalLiteralSectionType { got: u8 },
832    GetBitsError(GetBitsError),
833    NotEnoughBytes { have: usize, need: u8 },
834}
835
836#[cfg(feature = "std")]
837impl std::error::Error for LiteralsSectionParseError {
838    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
839        match self {
840            LiteralsSectionParseError::GetBitsError(source) => Some(source),
841            _ => None,
842        }
843    }
844}
845impl core::fmt::Display for LiteralsSectionParseError {
846    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
847        match self {
848            LiteralsSectionParseError::IllegalLiteralSectionType { got } => {
849                write!(
850                    f,
851                    "Illegal literalssectiontype. Is: {}, must be in: 0, 1, 2, 3",
852                    got
853                )
854            }
855            LiteralsSectionParseError::GetBitsError(e) => write!(f, "{:?}", e),
856            LiteralsSectionParseError::NotEnoughBytes { have, need } => {
857                write!(
858                    f,
859                    "Not enough byte to parse the literals section header. Have: {}, Need: {}",
860                    have, need,
861                )
862            }
863        }
864    }
865}
866
867impl From<GetBitsError> for LiteralsSectionParseError {
868    fn from(val: GetBitsError) -> Self {
869        Self::GetBitsError(val)
870    }
871}
872
873impl core::fmt::Display for LiteralsSectionType {
874    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> Result<(), core::fmt::Error> {
875        match self {
876            LiteralsSectionType::Compressed => write!(f, "Compressed"),
877            LiteralsSectionType::Raw => write!(f, "Raw"),
878            LiteralsSectionType::RLE => write!(f, "RLE"),
879            LiteralsSectionType::Treeless => write!(f, "Treeless"),
880        }
881    }
882}
883
884#[derive(Debug)]
885#[non_exhaustive]
886pub enum SequencesHeaderParseError {
887    NotEnoughBytes { need_at_least: u8, got: usize },
888}
889
890#[cfg(feature = "std")]
891impl std::error::Error for SequencesHeaderParseError {}
892
893impl core::fmt::Display for SequencesHeaderParseError {
894    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
895        match self {
896            SequencesHeaderParseError::NotEnoughBytes { need_at_least, got } => {
897                write!(
898                    f,
899                    "source must have at least {} bytes to parse header; got {} bytes",
900                    need_at_least, got,
901                )
902            }
903        }
904    }
905}
906
907#[derive(Debug)]
908#[non_exhaustive]
909pub enum FSETableError {
910    AccLogIsZero,
911    AccLogTooBig {
912        got: u8,
913        max: u8,
914    },
915    GetBitsError(GetBitsError),
916    ProbabilityCounterMismatch {
917        got: u32,
918        expected_sum: u32,
919        symbol_probabilities: Vec<i32>,
920    },
921    TooManySymbols {
922        got: usize,
923    },
924}
925
926#[cfg(feature = "std")]
927impl std::error::Error for FSETableError {
928    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
929        match self {
930            FSETableError::GetBitsError(source) => Some(source),
931            _ => None,
932        }
933    }
934}
935
936impl core::fmt::Display for FSETableError {
937    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
938        match self {
939            FSETableError::AccLogIsZero => write!(f, "Acclog must be at least 1"),
940            FSETableError::AccLogTooBig { got, max } => {
941                write!(
942                    f,
943                    "Found FSE acc_log: {0} bigger than allowed maximum in this case: {1}",
944                    got, max
945                )
946            }
947            FSETableError::GetBitsError(e) => write!(f, "{:?}", e),
948            FSETableError::ProbabilityCounterMismatch {
949                got,
950                expected_sum,
951                symbol_probabilities,
952            } => {
953                write!(f,
954                    "The counter ({}) exceeded the expected sum: {}. This means an error or corrupted data \n {:?}",
955                    got,
956                    expected_sum,
957                    symbol_probabilities,
958                )
959            }
960            FSETableError::TooManySymbols { got } => {
961                write!(
962                    f,
963                    "There are too many symbols in this distribution: {}. Max: 256",
964                    got,
965                )
966            }
967        }
968    }
969}
970
971impl From<GetBitsError> for FSETableError {
972    fn from(val: GetBitsError) -> Self {
973        Self::GetBitsError(val)
974    }
975}
976
977#[derive(Debug)]
978#[non_exhaustive]
979pub enum FSEDecoderError {
980    GetBitsError(GetBitsError),
981    TableIsUninitialized,
982}
983
984#[cfg(feature = "std")]
985impl std::error::Error for FSEDecoderError {
986    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
987        match self {
988            FSEDecoderError::GetBitsError(source) => Some(source),
989            _ => None,
990        }
991    }
992}
993
994impl core::fmt::Display for FSEDecoderError {
995    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
996        match self {
997            FSEDecoderError::GetBitsError(e) => write!(f, "{:?}", e),
998            FSEDecoderError::TableIsUninitialized => {
999                write!(f, "Tried to use an uninitialized table!")
1000            }
1001        }
1002    }
1003}
1004
1005impl From<GetBitsError> for FSEDecoderError {
1006    fn from(val: GetBitsError) -> Self {
1007        Self::GetBitsError(val)
1008    }
1009}
1010
1011#[derive(Debug)]
1012#[non_exhaustive]
1013pub enum HuffmanTableError {
1014    GetBitsError(GetBitsError),
1015    FSEDecoderError(FSEDecoderError),
1016    FSETableError(FSETableError),
1017    SourceIsEmpty,
1018    NotEnoughBytesForWeights {
1019        got_bytes: usize,
1020        expected_bytes: u8,
1021    },
1022    ExtraPadding {
1023        skipped_bits: i32,
1024    },
1025    TooManyWeights {
1026        got: usize,
1027    },
1028    MissingWeights,
1029    LeftoverIsNotAPowerOf2 {
1030        got: u32,
1031    },
1032    NotEnoughBytesToDecompressWeights {
1033        have: usize,
1034        need: usize,
1035    },
1036    FSETableUsedTooManyBytes {
1037        used: usize,
1038        available_bytes: u8,
1039    },
1040    NotEnoughBytesInSource {
1041        got: usize,
1042        need: usize,
1043    },
1044    WeightBiggerThanMaxNumBits {
1045        got: u8,
1046    },
1047    MaxBitsTooHigh {
1048        got: u8,
1049    },
1050}
1051
1052#[cfg(feature = "std")]
1053impl StdError for HuffmanTableError {
1054    fn source(&self) -> Option<&(dyn StdError + 'static)> {
1055        match self {
1056            HuffmanTableError::GetBitsError(source) => Some(source),
1057            HuffmanTableError::FSEDecoderError(source) => Some(source),
1058            HuffmanTableError::FSETableError(source) => Some(source),
1059            _ => None,
1060        }
1061    }
1062}
1063
1064impl core::fmt::Display for HuffmanTableError {
1065    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> ::core::fmt::Result {
1066        match self {
1067            HuffmanTableError::GetBitsError(e) => write!(f, "{:?}", e),
1068            HuffmanTableError::FSEDecoderError(e) => write!(f, "{:?}", e),
1069            HuffmanTableError::FSETableError(e) => write!(f, "{:?}", e),
1070            HuffmanTableError::SourceIsEmpty => write!(f, "Source needs to have at least one byte"),
1071            HuffmanTableError::NotEnoughBytesForWeights {
1072                got_bytes,
1073                expected_bytes,
1074            } => {
1075                write!(f, "Header says there should be {} bytes for the weights but there are only {} bytes in the stream",
1076                    expected_bytes,
1077                    got_bytes)
1078            }
1079            HuffmanTableError::ExtraPadding { skipped_bits } => {
1080                write!(f,
1081                    "Padding at the end of the sequence_section was more than a byte long: {} bits. Probably caused by data corruption",
1082                    skipped_bits,
1083                )
1084            }
1085            HuffmanTableError::TooManyWeights { got } => {
1086                write!(
1087                    f,
1088                    "More than 255 weights decoded (got {} weights). Stream is probably corrupted",
1089                    got,
1090                )
1091            }
1092            HuffmanTableError::MissingWeights => {
1093                write!(f, "Can\'t build huffman table without any weights")
1094            }
1095            HuffmanTableError::LeftoverIsNotAPowerOf2 { got } => {
1096                write!(f, "Leftover must be power of two but is: {}", got)
1097            }
1098            HuffmanTableError::NotEnoughBytesToDecompressWeights { have, need } => {
1099                write!(
1100                    f,
1101                    "Not enough bytes in stream to decompress weights. Is: {}, Should be: {}",
1102                    have, need,
1103                )
1104            }
1105            HuffmanTableError::FSETableUsedTooManyBytes {
1106                used,
1107                available_bytes,
1108            } => {
1109                write!(f,
1110                    "FSE table used more bytes: {} than were meant to be used for the whole stream of huffman weights ({})",
1111                    used,
1112                    available_bytes,
1113                )
1114            }
1115            HuffmanTableError::NotEnoughBytesInSource { got, need } => {
1116                write!(
1117                    f,
1118                    "Source needs to have at least {} bytes, got: {}",
1119                    need, got,
1120                )
1121            }
1122            HuffmanTableError::WeightBiggerThanMaxNumBits { got } => {
1123                write!(
1124                    f,
1125                    "Cant have weight: {} bigger than max_num_bits: {}",
1126                    got,
1127                    crate::huff0::MAX_MAX_NUM_BITS,
1128                )
1129            }
1130            HuffmanTableError::MaxBitsTooHigh { got } => {
1131                write!(
1132                    f,
1133                    "max_bits derived from weights is: {} should be lower than: {}",
1134                    got,
1135                    crate::huff0::MAX_MAX_NUM_BITS,
1136                )
1137            }
1138        }
1139    }
1140}
1141
1142impl From<GetBitsError> for HuffmanTableError {
1143    fn from(val: GetBitsError) -> Self {
1144        Self::GetBitsError(val)
1145    }
1146}
1147
1148impl From<FSEDecoderError> for HuffmanTableError {
1149    fn from(val: FSEDecoderError) -> Self {
1150        Self::FSEDecoderError(val)
1151    }
1152}
1153
1154impl From<FSETableError> for HuffmanTableError {
1155    fn from(val: FSETableError) -> Self {
1156        Self::FSETableError(val)
1157    }
1158}
1159
1160#[derive(Debug)]
1161#[non_exhaustive]
1162pub enum HuffmanDecoderError {
1163    GetBitsError(GetBitsError),
1164}
1165
1166impl core::fmt::Display for HuffmanDecoderError {
1167    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1168        match self {
1169            HuffmanDecoderError::GetBitsError(e) => write!(f, "{:?}", e),
1170        }
1171    }
1172}
1173
1174#[cfg(feature = "std")]
1175impl StdError for HuffmanDecoderError {
1176    fn source(&self) -> Option<&(dyn StdError + 'static)> {
1177        match self {
1178            HuffmanDecoderError::GetBitsError(source) => Some(source),
1179        }
1180    }
1181}
1182
1183impl From<GetBitsError> for HuffmanDecoderError {
1184    fn from(val: GetBitsError) -> Self {
1185        Self::GetBitsError(val)
1186    }
1187}