Skip to main content

mln_engine/storage/
compression.rs

1use std::io::Write;
2
3/// Compresses `raw` into a zlib stream (`windowBits = MAX_WBITS`) at
4/// `Z_DEFAULT_COMPRESSION` (level 6), `memLevel` 8, `Z_DEFAULT_STRATEGY`.
5///
6/// The stream decompresses to the same bytes as zlib's, but the compressed
7/// bytes (and so their length) can differ from those of the zlib the C++
8/// links.
9pub fn compress(raw: &[u8]) -> Result<Vec<u8>, String> {
10    let mut encoder = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::new(6));
11    encoder.write_all(raw).map_err(|_| "failed to deflate".to_string())?;
12    encoder.finish().map_err(|_| "failed to deflate".to_string())
13}
14
15/// Whether `v` is longer than two bytes and starts with a gzip or zlib header
16/// (with one of the four usual zlib compression levels).
17#[must_use]
18pub(crate) fn is_compressed(v: &[u8]) -> bool {
19    if v.len() > 2 {
20        let (byte0, byte1) = (v[0], v[1]);
21        if byte0 == 0x1f && byte1 == 0x8b {
22            // gzip (rfc1952)
23            return true;
24        } else if byte0 == 0x78 {
25            // zlib (rfc1950)
26            return matches!(
27                byte1,
28                0x01 // 78 01 - No Compression/low
29                | 0x5E // 78 5E - Fast Compression
30                | 0x9C // 78 9C - Default Compression
31                | 0xDA // 78 DA - Best Compression
32            );
33        }
34    }
35    false
36}
37
38/// Inflates a zlib or gzip stream (zlib's header auto-detection,
39/// `MAX_WBITS + 32`). Like the C++ loop, bytes after the end of the stream
40/// are ignored, and a stream that ends early is an error. The error message
41/// is flate2's, not zlib's.
42pub(crate) fn decompress(raw: &[u8]) -> Result<Vec<u8>, String> {
43    if raw.len() >= 2 && raw[0] == 0x1f && raw[1] == 0x8b {
44        // gzip (rfc1952): one member; zlib checks the CRC-32 and size trailer.
45        let mut decoder = flate2::bufread::GzDecoder::new(raw);
46        let mut result = Vec::new();
47        std::io::Read::read_to_end(&mut decoder, &mut result).map_err(|e| e.to_string())?;
48        return Ok(result);
49    }
50
51    let mut inflate = flate2::Decompress::new(true);
52    let mut result = Vec::new();
53    let mut out = [0u8; 16384];
54    loop {
55        let consumed = inflate.total_in() as usize;
56        let before = inflate.total_out();
57        let status = inflate
58            .decompress(&raw[consumed.min(raw.len())..], &mut out, flate2::FlushDecompress::None)
59            .map_err(|e| e.to_string())?;
60        let produced = (inflate.total_out() - before) as usize;
61        result.extend_from_slice(&out[..produced]);
62        match status {
63            flate2::Status::StreamEnd => return Ok(result),
64            // zlib's inflate returns Z_BUF_ERROR when no progress is possible.
65            flate2::Status::BufError => return Err("decompression error".to_string()),
66            flate2::Status::Ok => {
67                if produced == 0 && inflate.total_in() as usize == consumed {
68                    return Err("decompression error".to_string());
69                }
70            }
71        }
72    }
73}
74
75#[cfg(test)]
76mod tests {
77    use super::*;
78
79    /// gzip of `raw()` (Python's gzip module, level 6, mtime 0).
80    const GZIP: [u8; 56] = [
81        0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xed, 0xc5, 0xc1, 0x11, 0x00, 0x30, 0x04, 0x00,
82        0x30, 0xb4, 0xec, 0x3f, 0xb2, 0x39, 0xdc, 0x25, 0x9f, 0x44, 0xd6, 0xfb, 0x3d, 0x21, 0x49, 0x92, 0x24, 0x49,
83        0x92, 0x24, 0x49, 0x92, 0x24, 0x49, 0x92, 0x24, 0x49, 0xd2, 0xe5, 0x16, 0xe9, 0x1c, 0xb5, 0x68, 0x10, 0x27,
84        0x00, 0x00,
85    ];
86
87    fn raw() -> Vec<u8> {
88        (0..10_000u32).map(|i| (i % 7) as u8).collect()
89    }
90
91    #[test]
92    fn round_trip() {
93        let raw = raw();
94        let compressed = compress(&raw).unwrap();
95        // zlib header for the default compression level.
96        assert_eq!(&compressed[..2], &[0x78, 0x9C]);
97        assert!(compressed.len() < raw.len());
98        assert_eq!(decompress(&compressed).unwrap(), raw);
99        assert!(decompress(&compressed[..compressed.len() / 2]).is_err());
100        let mut trailing = compressed;
101        trailing.extend_from_slice(b"garbage");
102        assert_eq!(decompress(&trailing).unwrap(), raw);
103        assert!(decompress(&[]).is_err());
104        assert!(decompress(b"not compressed").is_err());
105        assert_eq!(decompress(&compress(&[]).unwrap()).unwrap(), Vec::<u8>::new());
106    }
107
108    #[test]
109    fn gzip() {
110        // gzip is detected by its magic bytes.
111        assert_eq!(decompress(&GZIP).unwrap(), raw());
112        assert!(decompress(&GZIP[..GZIP.len() - 4]).is_err());
113    }
114}