Skip to main content

pltrs_codec/deflate/
error.rs

1//! Errors reported while decoding DEFLATE streams.
2
3use std::error::Error;
4use std::fmt;
5
6/// The Huffman alphabet an [`InflateError`] refers to.
7#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
8pub enum HuffmanTable {
9    /// The literal/length alphabet (literal bytes, end of block, lengths).
10    LiteralLength,
11    /// The distance alphabet.
12    Distance,
13    /// The code-length alphabet used to transmit dynamic Huffman codes.
14    CodeLength,
15}
16
17impl fmt::Display for HuffmanTable {
18    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
19        f.write_str(match self {
20            Self::LiteralLength => "literal/length",
21            Self::Distance => "distance",
22            Self::CodeLength => "code-length",
23        })
24    }
25}
26
27/// An error found while decompressing a DEFLATE stream.
28#[derive(Clone, Copy, Debug, PartialEq, Eq)]
29pub enum InflateError {
30    /// The input ended before the final block was complete.
31    UnexpectedEof,
32    /// A block header used the reserved block type 3.
33    InvalidBlockType,
34    /// A stored block's length disagrees with its one's complement copy.
35    StoredLengthMismatch {
36        /// The `LEN` field.
37        length: u16,
38        /// The `NLEN` field, which should equal `!length`.
39        complement: u16,
40    },
41    /// A dynamic block declared more codes than the alphabet has symbols.
42    TooManyCodes {
43        /// The alphabet concerned.
44        table: HuffmanTable,
45        /// The declared number of codes.
46        count: usize,
47    },
48    /// The code lengths of an alphabet over-subscribe the code space.
49    OversubscribedCode(HuffmanTable),
50    /// The code lengths of an alphabet leave part of the code space unused,
51    /// which DEFLATE only permits for a single one-bit code.
52    IncompleteCode(HuffmanTable),
53    /// A dynamic block gave the end-of-block symbol no code.
54    MissingEndOfBlock,
55    /// A "repeat previous length" instruction came before any length.
56    RepeatWithoutPrevious,
57    /// A run of code lengths extends past the declared number of codes.
58    CodeLengthOverflow,
59    /// The input holds a bit pattern that is no valid code, or one of the
60    /// reserved symbols (literal/length 286–287, distance 30–31).
61    InvalidCode(HuffmanTable),
62    /// A back-reference points before the start of the output.
63    DistanceTooFarBack {
64        /// The distance of the back-reference.
65        distance: usize,
66        /// The number of bytes decoded so far.
67        available: usize,
68    },
69    /// The decompressed data would exceed the caller's size limit.
70    OutputLimitExceeded {
71        /// The limit, in bytes.
72        limit: usize,
73    },
74}
75
76impl fmt::Display for InflateError {
77    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
78        match *self {
79            Self::UnexpectedEof => f.write_str("DEFLATE stream ended unexpectedly"),
80            Self::InvalidBlockType => f.write_str("invalid DEFLATE block type 3"),
81            Self::StoredLengthMismatch { length, complement } => write!(
82                f,
83                "stored block length {length:#06x} does not match its complement {complement:#06x}"
84            ),
85            Self::TooManyCodes { table, count } => {
86                write!(f, "dynamic block declares {count} {table} codes")
87            }
88            Self::OversubscribedCode(table) => {
89                write!(f, "over-subscribed {table} Huffman code")
90            }
91            Self::IncompleteCode(table) => write!(f, "incomplete {table} Huffman code"),
92            Self::MissingEndOfBlock => f.write_str("dynamic block has no end-of-block code"),
93            Self::RepeatWithoutPrevious => {
94                f.write_str("code-length repeat with no previous length")
95            }
96            Self::CodeLengthOverflow => {
97                f.write_str("code-length run exceeds the number of declared codes")
98            }
99            Self::InvalidCode(table) => write!(f, "invalid {table} code"),
100            Self::DistanceTooFarBack {
101                distance,
102                available,
103            } => write!(
104                f,
105                "back-reference distance {distance} exceeds the {available} bytes decoded so far"
106            ),
107            Self::OutputLimitExceeded { limit } => {
108                write!(f, "decompressed data exceeds the limit of {limit} bytes")
109            }
110        }
111    }
112}
113
114impl Error for InflateError {}