Skip to main content

lib_jsl_file_io/
deflate.rs

1//! DEFLATE (RFC 1951) and zlib (RFC 1950) compression, as used by PNG.
2//!
3//! The decoder handles all three block types (stored, fixed and dynamic Huffman). The encoder
4//! finds matches with a hash-chain LZ77 search over the 32 KiB window and emits them with the
5//! fixed Huffman code, or uses stored blocks at level 0.
6//!
7//! See the book entry [Image files](https://jwkunz.github.io/lib_jsl/book/foundations/images.html#png-and-deflate).
8
9use lib_jsl_core::ErrorsJSL;
10
11const LENGTH_BASE: [u16; 29] = [3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258];
12const LENGTH_EXTRA: [u8; 29] = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0];
13const DIST_BASE: [u16; 30] = [1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577];
14const DIST_EXTRA: [u8; 30] = [0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13];
15const CODE_LENGTH_ORDER: [usize; 19] = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
16
17fn corrupt(message: &'static str) -> ErrorsJSL {
18    ErrorsJSL::RuntimeError(message)
19}
20
21/// The Adler-32 checksum used by zlib.
22pub fn adler32(data: &[u8]) -> u32 {
23    let (mut a, mut b) = (1u32, 0u32);
24    for chunk in data.chunks(5552) {
25        for &byte in chunk {
26            a += byte as u32;
27            b += a;
28        }
29        a %= 65521;
30        b %= 65521;
31    }
32    (b << 16) | a
33}
34
35struct BitReader<'a> {
36    data: &'a [u8],
37    position: usize,
38    bit_buffer: u32,
39    bit_count: u32,
40}
41
42impl<'a> BitReader<'a> {
43    fn new(data: &'a [u8]) -> Self {
44        BitReader { data, position: 0, bit_buffer: 0, bit_count: 0 }
45    }
46
47    fn bits(&mut self, count: u32) -> Result<u32, ErrorsJSL> {
48        while self.bit_count < count {
49            let byte = *self.data.get(self.position).ok_or(corrupt("DEFLATE stream ended early."))?;
50            self.position += 1;
51            self.bit_buffer |= (byte as u32) << self.bit_count;
52            self.bit_count += 8;
53        }
54        let value = self.bit_buffer & ((1u64 << count) - 1) as u32;
55        self.bit_buffer >>= count;
56        self.bit_count -= count;
57        Ok(value)
58    }
59
60    fn align_to_byte(&mut self) {
61        self.bit_buffer = 0;
62        self.bit_count = 0;
63    }
64}
65
66/// A canonical Huffman decoder in the counts/symbols form (as in zlib's `puff`).
67struct Huffman {
68    counts: [u16; 16],
69    symbols: Vec<u16>,
70}
71
72impl Huffman {
73    fn new(lengths: &[u8]) -> Result<Self, ErrorsJSL> {
74        let mut counts = [0u16; 16];
75        lengths.iter().for_each(|&l| counts[l as usize] += 1);
76        counts[0] = 0;
77        // Reject over-subscribed codes (incomplete codes are allowed, as in zlib).
78        let mut left: i32 = 1;
79        for &c in &counts[1..] {
80            left = 2 * left - c as i32;
81            if left < 0 {
82                return Err(corrupt("Over-subscribed Huffman code."));
83            }
84        }
85        let mut offsets = [0u16; 16];
86        for l in 1..15 {
87            offsets[l + 1] = offsets[l] + counts[l];
88        }
89        let mut symbols = vec![0u16; lengths.len()];
90        for (symbol, &l) in lengths.iter().enumerate() {
91            if l != 0 {
92                symbols[offsets[l as usize] as usize] = symbol as u16;
93                offsets[l as usize] += 1;
94            }
95        }
96        Ok(Huffman { counts, symbols })
97    }
98
99    fn decode(&self, reader: &mut BitReader) -> Result<u16, ErrorsJSL> {
100        let (mut code, mut first, mut index) = (0i32, 0i32, 0i32);
101        for len in 1..16 {
102            code |= reader.bits(1)? as i32;
103            let count = self.counts[len] as i32;
104            if code - count < first {
105                return Ok(self.symbols[(index + code - first) as usize]);
106            }
107            index += count;
108            first = (first + count) << 1;
109            code <<= 1;
110        }
111        Err(corrupt("Invalid Huffman code."))
112    }
113}
114
115fn fixed_tables() -> (Huffman, Huffman) {
116    let mut lengths = [0u8; 288];
117    lengths[..144].fill(8);
118    lengths[144..256].fill(9);
119    lengths[256..280].fill(7);
120    lengths[280..].fill(8);
121    (Huffman::new(&lengths).expect("valid"), Huffman::new(&[5u8; 30]).expect("valid"))
122}
123
124fn dynamic_tables(reader: &mut BitReader) -> Result<(Huffman, Huffman), ErrorsJSL> {
125    let literal_count = reader.bits(5)? as usize + 257;
126    let distance_count = reader.bits(5)? as usize + 1;
127    let code_length_count = reader.bits(4)? as usize + 4;
128    if literal_count > 286 || distance_count > 30 {
129        return Err(corrupt("Too many Huffman codes."));
130    }
131    let mut code_lengths = [0u8; 19];
132    for &i in CODE_LENGTH_ORDER.iter().take(code_length_count) {
133        code_lengths[i] = reader.bits(3)? as u8;
134    }
135    let code_length_code = Huffman::new(&code_lengths)?;
136    let mut lengths = vec![0u8; literal_count + distance_count];
137    let mut i = 0;
138    while i < lengths.len() {
139        let symbol = code_length_code.decode(reader)?;
140        let (value, repeat) = match symbol {
141            0..=15 => (symbol as u8, 1),
142            16 => (*lengths[..i].last().ok_or(corrupt("Repeat with no previous length."))?, 3 + reader.bits(2)? as usize),
143            17 => (0, 3 + reader.bits(3)? as usize),
144            _ => (0, 11 + reader.bits(7)? as usize),
145        };
146        if i + repeat > lengths.len() {
147            return Err(corrupt("Code lengths overrun."));
148        }
149        lengths[i..i + repeat].fill(value);
150        i += repeat;
151    }
152    if lengths[256] == 0 {
153        return Err(corrupt("No end-of-block code."));
154    }
155    Ok((Huffman::new(&lengths[..literal_count])?, Huffman::new(&lengths[literal_count..])?))
156}
157
158/// Decompresses a raw DEFLATE stream.
159pub fn inflate(data: &[u8]) -> Result<Vec<u8>, ErrorsJSL> {
160    inflate_limited(data, usize::MAX)
161}
162
163/// Decompresses a raw DEFLATE stream, failing if the output would exceed `max_output` bytes (a
164/// guard against decompression bombs, which expand up to about 1000 to 1).
165pub fn inflate_limited(data: &[u8], max_output: usize) -> Result<Vec<u8>, ErrorsJSL> {
166    let mut reader = BitReader::new(data);
167    let mut out = Vec::with_capacity(data.len().saturating_mul(4).min(max_output));
168    loop {
169        let last = reader.bits(1)? == 1;
170        match reader.bits(2)? {
171            0 => {
172                reader.align_to_byte();
173                let p = reader.position;
174                if p + 4 > data.len() {
175                    return Err(corrupt("Truncated stored block."));
176                }
177                let len = u16::from_le_bytes([data[p], data[p + 1]]) as usize;
178                let nlen = u16::from_le_bytes([data[p + 2], data[p + 3]]) as usize;
179                if len != !nlen & 0xffff || p + 4 + len > data.len() {
180                    return Err(corrupt("Corrupt stored block."));
181                }
182                if out.len().saturating_add(len) > max_output {
183                    return Err(corrupt("Decompressed data exceed the size limit."));
184                }
185                out.extend_from_slice(&data[p + 4..p + 4 + len]);
186                reader.position = p + 4 + len;
187            }
188            kind @ (1 | 2) => {
189                let (literals, distances) = if kind == 1 { fixed_tables() } else { dynamic_tables(&mut reader)? };
190                loop {
191                    let symbol = literals.decode(&mut reader)? as usize;
192                    match symbol {
193                        0..=255 => {
194                            if out.len() >= max_output {
195                                return Err(corrupt("Decompressed data exceed the size limit."));
196                            }
197                            out.push(symbol as u8)
198                        }
199                        256 => break,
200                        257..=285 => {
201                            let s = symbol - 257;
202                            let length = LENGTH_BASE[s] as usize + reader.bits(LENGTH_EXTRA[s] as u32)? as usize;
203                            let d = distances.decode(&mut reader)? as usize;
204                            if d >= 30 {
205                                return Err(corrupt("Invalid distance code."));
206                            }
207                            let distance = DIST_BASE[d] as usize + reader.bits(DIST_EXTRA[d] as u32)? as usize;
208                            if distance > out.len() {
209                                return Err(corrupt("Distance reaches before the start."));
210                            }
211                            if out.len().saturating_add(length) > max_output {
212                                return Err(corrupt("Decompressed data exceed the size limit."));
213                            }
214                            let start = out.len() - distance;
215                            for k in 0..length {
216                                out.push(out[start + k]);
217                            }
218                        }
219                        _ => return Err(corrupt("Invalid literal/length code.")),
220                    }
221                }
222            }
223            _ => return Err(corrupt("Invalid block type.")),
224        }
225        if last {
226            return Ok(out);
227        }
228    }
229}
230
231struct BitWriter {
232    out: Vec<u8>,
233    buffer: u64,
234    count: u32,
235}
236
237impl BitWriter {
238    fn new() -> Self {
239        BitWriter { out: Vec::new(), buffer: 0, count: 0 }
240    }
241
242    /// Writes the low `count` bits of `value`, least significant first.
243    fn bits(&mut self, value: u32, count: u32) {
244        self.buffer |= (value as u64) << self.count;
245        self.count += count;
246        while self.count >= 8 {
247            self.out.push(self.buffer as u8);
248            self.buffer >>= 8;
249            self.count -= 8;
250        }
251    }
252
253    /// Writes a Huffman code, most significant bit first.
254    fn code(&mut self, code: u32, length: u32) {
255        let reversed = code.reverse_bits() >> (32 - length);
256        self.bits(reversed, length);
257    }
258
259    fn finish(mut self) -> Vec<u8> {
260        if self.count > 0 {
261            self.out.push(self.buffer as u8);
262        }
263        self.out
264    }
265}
266
267fn fixed_literal(writer: &mut BitWriter, symbol: usize) {
268    match symbol {
269        0..=143 => writer.code(0x30 + symbol as u32, 8),
270        144..=255 => writer.code(0x190 + (symbol - 144) as u32, 9),
271        256..=279 => writer.code((symbol - 256) as u32, 7),
272        _ => writer.code(0xc0 + (symbol - 280) as u32, 8),
273    }
274}
275
276fn write_match(writer: &mut BitWriter, length: usize, distance: usize) {
277    let l = LENGTH_BASE.iter().rposition(|&b| b as usize <= length).expect("length >= 3");
278    fixed_literal(writer, 257 + l);
279    writer.bits((length - LENGTH_BASE[l] as usize) as u32, LENGTH_EXTRA[l] as u32);
280    let d = DIST_BASE.iter().rposition(|&b| b as usize <= distance).expect("distance >= 1");
281    writer.code(d as u32, 5);
282    writer.bits((distance - DIST_BASE[d] as usize) as u32, DIST_EXTRA[d] as u32);
283}
284
285/// The data as stored (uncompressed) DEFLATE blocks.
286fn stored(data: &[u8]) -> Vec<u8> {
287    let mut out = Vec::with_capacity(data.len() + 5 * (data.len() / 65535 + 1));
288    let blocks: Vec<&[u8]> = if data.is_empty() { vec![&[][..]] } else { data.chunks(65535).collect() };
289    for (i, block) in blocks.iter().enumerate() {
290        out.push(if i + 1 == blocks.len() { 1 } else { 0 });
291        out.extend_from_slice(&(block.len() as u16).to_le_bytes());
292        out.extend_from_slice(&(!(block.len() as u16)).to_le_bytes());
293        out.extend_from_slice(block);
294    }
295    out
296}
297
298/// Compresses to a raw DEFLATE stream. `level` 0 stores the data; any other level runs the LZ77
299/// search, with longer hash chains (more compression, more time) for higher levels up to 9, and
300/// falls back to stored blocks if the fixed Huffman code would make the data larger (as it does
301/// for random bytes).
302pub fn deflate(data: &[u8], level: u8) -> Vec<u8> {
303    if level == 0 {
304        return stored(data);
305    }
306    let compressed = deflate_fixed(data, level);
307    if compressed.len() > data.len() + 5 * (data.len() / 65535 + 1) { stored(data) } else { compressed }
308}
309
310/// LZ77 with hash chains, coded with the fixed Huffman code in a single block.
311// ANCHOR: lz77
312fn deflate_fixed(data: &[u8], level: u8) -> Vec<u8> {
313    const WINDOW: usize = 32768;
314    const HASH_BITS: u32 = 15;
315    let max_chain = 4usize << level.min(9);
316    let hash = |i: usize| -> usize { (((data[i] as u32) << 16 | (data[i + 1] as u32) << 8 | data[i + 2] as u32).wrapping_mul(2_654_435_761) >> (32 - HASH_BITS)) as usize };
317    let mut head = vec![usize::MAX; 1 << HASH_BITS];
318    let mut previous = vec![usize::MAX; data.len()];
319    let mut writer = BitWriter::new();
320    writer.bits(1, 1); // final block
321    writer.bits(1, 2); // fixed Huffman
322    let mut i = 0;
323    let insert = |head: &mut Vec<usize>, previous: &mut Vec<usize>, k: usize| {
324        if k + 2 < data.len() {
325            let h = hash(k);
326            previous[k] = head[h];
327            head[h] = k;
328        }
329    };
330    while i < data.len() {
331        let (mut best_length, mut best_distance) = (0, 0);
332        if i + 2 < data.len() {
333            let mut candidate = head[hash(i)];
334            let mut chain = 0;
335            while candidate != usize::MAX && i - candidate <= WINDOW && chain < max_chain {
336                let limit = (data.len() - i).min(258);
337                let mut length = 0;
338                while length < limit && data[candidate + length] == data[i + length] {
339                    length += 1;
340                }
341                if length > best_length {
342                    best_length = length;
343                    best_distance = i - candidate;
344                    if length == limit {
345                        break;
346                    }
347                }
348                candidate = previous[candidate];
349                chain += 1;
350            }
351        }
352        if best_length >= 3 {
353            write_match(&mut writer, best_length, best_distance);
354            for k in i..i + best_length {
355                insert(&mut head, &mut previous, k);
356            }
357            i += best_length;
358        } else {
359            fixed_literal(&mut writer, data[i] as usize);
360            insert(&mut head, &mut previous, i);
361            i += 1;
362        }
363    }
364    fixed_literal(&mut writer, 256);
365    writer.finish()
366}
367// ANCHOR_END: lz77
368
369/// Decompresses a zlib stream (header, DEFLATE data, Adler-32 trailer), verifying the checksum.
370pub fn zlib_decompress(data: &[u8]) -> Result<Vec<u8>, ErrorsJSL> {
371    if data.len() < 6 {
372        return Err(corrupt("zlib stream too short."));
373    }
374    let (cmf, flg) = (data[0], data[1]);
375    if cmf & 0x0f != 8 || !((cmf as u16) << 8 | flg as u16).is_multiple_of(31) {
376        return Err(corrupt("Invalid zlib header."));
377    }
378    if flg & 0x20 != 0 {
379        return Err(corrupt("Preset zlib dictionaries are not supported."));
380    }
381    let out = inflate(&data[2..])?;
382    let n = data.len();
383    let expected = u32::from_be_bytes([data[n - 4], data[n - 3], data[n - 2], data[n - 1]]);
384    if adler32(&out) != expected {
385        return Err(corrupt("zlib checksum mismatch."));
386    }
387    Ok(out)
388}
389
390/// Compresses to a zlib stream (see [`deflate`] for `level`).
391pub fn zlib_compress(data: &[u8], level: u8) -> Vec<u8> {
392    let mut out = vec![0x78, 0x01];
393    out.extend(deflate(data, level));
394    out.extend_from_slice(&adler32(data).to_be_bytes());
395    out
396}
397
398#[cfg(test)]
399mod tests {
400    use super::*;
401
402    #[test]
403    fn incompressible_data_is_stored_not_expanded() {
404        let mut seed = 7u64;
405        let random: Vec<u8> = (0..5000)
406            .map(|_| {
407                seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
408                (seed >> 56) as u8
409            })
410            .collect();
411        let packed = zlib_compress(&random, 9);
412        assert!(packed.len() <= random.len() + 11, "{} bytes", packed.len());
413        assert_eq!(zlib_decompress(&packed).unwrap(), random);
414    }
415
416    /// `zlib.compress(text, 9)` from CPython's zlib (dynamic Huffman blocks), where `text` is the
417    /// pangram repeated 20 times followed by the bytes 0..=255.
418    const ZLIB_DYNAMIC: &[u8] = &[
419        120, 218, 11, 201, 72, 85, 40, 44, 205, 76, 206, 86, 72, 42, 202, 47, 207, 83, 72, 203, 175,
420        80, 200, 42, 205, 45, 40, 86, 200, 47, 75, 45, 82, 40, 1, 74, 231, 36, 86, 85, 42, 164, 228,
421        167, 235, 41, 132, 140, 42, 30, 85, 60, 170, 152, 218, 138, 25, 24, 153, 152, 89, 88, 217,
422        216, 57, 56, 185, 184, 121, 120, 249, 248, 5, 4, 133, 132, 69, 68, 197, 196, 37, 36, 165,
423        164, 101, 100, 229, 228, 21, 20, 149, 148, 85, 84, 213, 212, 53, 52, 181, 180, 117, 116,
424        245, 244, 13, 12, 141, 140, 77, 76, 205, 204, 45, 44, 173, 172, 109, 108, 237, 236, 29, 28,
425        157, 156, 93, 92, 221, 220, 61, 60, 189, 188, 125, 124, 253, 252, 3, 2, 131, 130, 67, 66,
426        195, 194, 35, 34, 163, 162, 99, 98, 227, 226, 19, 18, 147, 146, 83, 82, 211, 210, 51, 50,
427        179, 178, 115, 114, 243, 242, 11, 10, 139, 138, 75, 74, 203, 202, 43, 42, 171, 170, 107,
428        106, 235, 234, 27, 26, 155, 154, 91, 90, 219, 218, 59, 58, 187, 186, 123, 122, 251, 250, 39,
429        76, 156, 52, 121, 202, 212, 105, 211, 103, 204, 156, 53, 123, 206, 220, 121, 243, 23, 44,
430        92, 180, 120, 201, 210, 101, 203, 87, 172, 92, 181, 122, 205, 218, 117, 235, 55, 108, 220,
431        180, 121, 203, 214, 109, 219, 119, 236, 220, 181, 123, 207, 222, 125, 251, 15, 28, 60, 116,
432        248, 200, 209, 99, 199, 79, 156, 60, 117, 250, 204, 217, 115, 231, 47, 92, 188, 116, 249,
433        202, 213, 107, 215, 111, 220, 188, 117, 251, 206, 221, 123, 247, 31, 60, 124, 244, 248, 201,
434        211, 103, 207, 95, 188, 124, 245, 250, 205, 219, 119, 239, 63, 124, 252, 244, 249, 203, 215,
435        111, 223, 127, 252, 252, 245, 251, 207, 223, 127, 255, 1, 20, 151, 194, 156,
436    ];
437
438    fn text() -> Vec<u8> {
439        let mut t = b"The quick brown fox jumps over the lazy dog. ".repeat(20);
440        t.extend(0..=255u8);
441        t
442    }
443
444    #[test]
445    fn decodes_a_dynamic_huffman_stream_from_zlib() {
446        assert_eq!(zlib_decompress(ZLIB_DYNAMIC).unwrap(), text());
447        // A corrupted checksum is detected.
448        let mut bad = ZLIB_DYNAMIC.to_vec();
449        let n = bad.len();
450        bad[n - 1] ^= 1;
451        assert!(zlib_decompress(&bad).is_err());
452        assert!(zlib_decompress(&ZLIB_DYNAMIC[..20]).is_err());
453    }
454
455    #[test]
456    fn round_trips_at_every_level_and_compresses_redundant_data() {
457        let mut inputs = vec![Vec::new(), vec![7u8], text(), vec![0u8; 100_000]];
458        let mut s: u32 = 1;
459        inputs.push((0..70_000).map(|_| { s = s.wrapping_mul(1_103_515_245).wrapping_add(12345); (s >> 24) as u8 }).collect());
460        for input in &inputs {
461            for level in [0, 1, 6, 9] {
462                let z = zlib_compress(input, level);
463                assert_eq!(&zlib_decompress(&z).unwrap(), input, "level {level}, {} bytes", input.len());
464            }
465        }
466        assert!(zlib_compress(&text(), 6).len() < text().len() / 2);
467        assert!(zlib_compress(&vec![0u8; 100_000], 6).len() < 1000);
468        assert_eq!(adler32(b"Wikipedia"), 0x11E6_0398);
469    }
470}