deflate/zlib.rs
1//! This module contains functionality for generating a [zlib](https://tools.ietf.org/html/rfc1950)
2//! header.
3//!
4//! The Zlib header contains some metadata (a window size and a compression level), and optionally
5//! a block of data serving as an extra dictionary for the compressor/decompressor.
6//! The dictionary is not implemented in this library.
7//! The data in the header aside from the dictionary doesn't actually have any effect on the
8//! decompressed data, it only offers some hints for the decompressor on how the data was
9//! compressed.
10
11use std::io::{Write, Result};
12
13// CM = 8 means to use the DEFLATE compression method.
14const DEFAULT_CM: u8 = 8;
15// CINFO = 7 Indicates a 32k window size.
16const DEFAULT_CINFO: u8 = 7 << 4;
17const DEFAULT_CMF: u8 = DEFAULT_CM | DEFAULT_CINFO;
18
19// No dict by default.
20#[cfg(test)]
21const DEFAULT_FDICT: u8 = 0;
22// FLEVEL = 0 means fastest compression algorithm.
23const _DEFAULT_FLEVEL: u8 = 0 << 7;
24
25// The 16-bit value consisting of CMF and FLG must be divisible by this to be valid.
26const FCHECK_DIVISOR: u8 = 31;
27
28#[allow(dead_code)]
29#[repr(u8)]
30pub enum CompressionLevel {
31 Fastest = 0 << 6,
32 Fast = 1 << 6,
33 Default = 2 << 6,
34 Maximum = 3 << 6,
35}
36
37/// Generate FCHECK from CMF and FLG (without FCKECH )so that they are correct according to the
38/// specification, i.e (CMF*256 + FCHK) % 31 = 0.
39/// Returns flg with the FCHKECK bits added (any existing FCHECK bits are ignored).
40fn add_fcheck(cmf: u8, flg: u8) -> u8 {
41 let rem = ((usize::from(cmf) * 256) + usize::from(flg)) % usize::from(FCHECK_DIVISOR);
42
43 // Clear existing FCHECK if any
44 let flg = flg & 0b11100000;
45
46 // Casting is safe as rem can't overflow since it is a value mod 31
47 // We can simply add the value to flg as (31 - rem) will never be above 2^5
48 flg + (FCHECK_DIVISOR - rem as u8)
49}
50
51/// Write a zlib header with an empty dictionary to the writer using the specified
52/// compression level preset.
53pub fn write_zlib_header<W: Write>(writer: &mut W, level: CompressionLevel) -> Result<()> {
54 writer.write_all(&get_zlib_header(level))
55}
56
57/// Get the zlib header for the `CompressionLevel` level using the default window size and no
58/// dictionary.
59pub fn get_zlib_header(level: CompressionLevel) -> [u8; 2] {
60 let cmf = DEFAULT_CMF;
61 [cmf, add_fcheck(cmf, level as u8)]
62}
63
64#[cfg(test)]
65mod test {
66 use super::DEFAULT_CMF;
67 use super::*;
68
69 #[test]
70 fn test_gen_fcheck() {
71 let cmf = DEFAULT_CMF;
72 let flg = super::add_fcheck(
73 DEFAULT_CMF,
74 CompressionLevel::Default as u8 | super::DEFAULT_FDICT,
75 );
76 assert_eq!(((usize::from(cmf) * 256) + usize::from(flg)) % 31, 0);
77 }
78
79 #[test]
80 fn test_header() {
81 let header = get_zlib_header(CompressionLevel::Fastest);
82 assert_eq!(
83 ((usize::from(header[0]) * 256) + usize::from(header[1])) % 31,
84 0
85 );
86 }
87}