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