forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

deflate.rs256 lines, 8.5 KiBHistoryRawDownload
1//! DEFLATE compression (RFC 1951) and its zlib wrapper (RFC 1950), for encoders.
2//!
3//! The encoder is deliberately simple: greedy LZ77 over a 32 KiB window with a
4//! bounded hash chain, emitted as one fixed-Huffman block. When stored blocks
5//! would be smaller (incompressible input), the output uses stored blocks
6//! instead, so it never grows past the input by more than the framing. The
7//! ratio is below zlib's dynamic-Huffman output; every stream is valid DEFLATE
8//! and round-trips through [`crate::inflate`].
9
10const WINDOW: usize = 1 << 15;
11const MIN_MATCH: usize = 3;
12const MAX_MATCH: usize = 258;
13/// How many earlier positions with the same hash a match search examines.
14const CHAIN: usize = 16;
15const HASH_BITS: u32 = 15;
16const STORED_MAX: usize = 65_535;
17
18/// Length codes 257..=285: base length, then extra bits.
19const LEN_BASE: [usize; 29] = [
20 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,
21 163, 195, 227, 258,
22];
23const LEN_EXTRA: [u32; 29] = [
24 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,
25];
26/// Distance codes 0..=29: base distance, then extra bits.
27const DIST_BASE: [usize; 30] = [
28 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537,
29 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577,
30];
31const DIST_EXTRA: [u32; 30] = [
32 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,
33 13,
34];
35
36/// Compress `input` to a raw DEFLATE stream (RFC 1951).
37pub fn deflate_raw(input: &[u8]) -> Vec<u8> {
38 let fixed = fixed_block(input);
39 let stored_len = input.len() + 5 * input.len().div_ceil(STORED_MAX).max(1);
40 if fixed.len() <= stored_len {
41 fixed
42 } else {
43 stored_blocks(input)
44 }
45}
46
47/// Compress `input` to a zlib stream (RFC 1950): header, DEFLATE data, Adler-32.
48pub fn deflate_zlib(input: &[u8]) -> Vec<u8> {
49 let body = deflate_raw(input);
50 let mut out = Vec::with_capacity(body.len() + 6);
51 // CMF 0x78 (deflate, 32 KiB window); FLG 0x9c (default level), 0x789c % 31 == 0.
52 out.extend_from_slice(&[0x78, 0x9c]);
53 out.extend_from_slice(&body);
54 out.extend_from_slice(&crate::adler32(input).to_be_bytes());
55 out
56}
57
58/// LSB-first bit writer, as DEFLATE packs its fields.
59struct BitWriter {
60 out: Vec<u8>,
61 acc: u64,
62 held: u32,
63}
64
65impl BitWriter {
66 fn new(capacity: usize) -> Self {
67 Self {
68 out: Vec::with_capacity(capacity),
69 acc: 0,
70 held: 0,
71 }
72 }
73
74 /// Append the low `bits` bits of `value`, least significant first.
75 fn put(&mut self, value: u32, bits: u32) {
76 self.acc |= u64::from(value) << self.held;
77 self.held += bits;
78 while self.held >= 8 {
79 self.out.push(self.acc as u8);
80 self.acc >>= 8;
81 self.held -= 8;
82 }
83 }
84
85 /// Append a Huffman code, which DEFLATE writes most significant bit first.
86 fn put_code(&mut self, code: u32, len: u32) {
87 self.put(code.reverse_bits() >> (32 - len), len);
88 }
89
90 fn finish(mut self) -> Vec<u8> {
91 if self.held > 0 {
92 self.out.push(self.acc as u8);
93 }
94 self.out
95 }
96}
97
98/// One literal or length symbol under the fixed Huffman code (RFC 1951 3.2.6).
99fn put_litlen(w: &mut BitWriter, sym: u32) {
100 match sym {
101 0..=143 => w.put_code(0x30 + sym, 8),
102 144..=255 => w.put_code(0x190 + sym - 144, 9),
103 256..=279 => w.put_code(sym - 256, 7),
104 _ => w.put_code(0xc0 + sym - 280, 8),
105 }
106}
107
108fn put_match(w: &mut BitWriter, len: usize, dist: usize) {
109 let li = LEN_BASE.partition_point(|&b| b <= len) - 1;
110 put_litlen(w, 257 + li as u32);
111 w.put((len - LEN_BASE[li]) as u32, LEN_EXTRA[li]);
112 let di = DIST_BASE.partition_point(|&b| b <= dist) - 1;
113 w.put_code(di as u32, 5);
114 w.put((dist - DIST_BASE[di]) as u32, DIST_EXTRA[di]);
115}
116
117fn hash(s: &[u8]) -> usize {
118 let v = (u32::from(s[0]) << 16) | (u32::from(s[1]) << 8) | u32::from(s[2]);
119 (v.wrapping_mul(2_654_435_761) >> (32 - HASH_BITS)) as usize
120}
121
122/// A single BFINAL fixed-Huffman block over the whole input.
123fn fixed_block(input: &[u8]) -> Vec<u8> {
124 let n = input.len();
125 let mut w = BitWriter::new(n / 2 + 16);
126 w.put(1, 1); // BFINAL
127 w.put(1, 2); // BTYPE 01: fixed Huffman codes
128
129 // head[h] and prev[] hold position + 1 (0 means none), so a chain is a
130 // ring of the last WINDOW positions.
131 let mut head = vec![0u32; 1 << HASH_BITS];
132 let mut prev = vec![0u32; WINDOW];
133 let insert = |head: &mut [u32], prev: &mut [u32], pos: usize| {
134 let h = hash(&input[pos..]);
135 prev[pos & (WINDOW - 1)] = head[h];
136 head[h] = (pos + 1) as u32;
137 };
138
139 let mut i = 0;
140 while i < n {
141 let mut best_len = 0;
142 let mut best_dist = 0;
143 if i + MIN_MATCH <= n {
144 let mut cand = head[hash(&input[i..])] as usize;
145 let max = (n - i).min(MAX_MATCH);
146 for _ in 0..CHAIN {
147 if cand == 0 {
148 break;
149 }
150 let p = cand - 1;
151 if i - p > WINDOW {
152 break;
153 }
154 let mut l = 0;
155 while l < max && input[p + l] == input[i + l] {
156 l += 1;
157 }
158 if l > best_len {
159 best_len = l;
160 best_dist = i - p;
161 if l == max {
162 break;
163 }
164 }
165 cand = prev[p & (WINDOW - 1)] as usize;
166 }
167 insert(&mut head, &mut prev, i);
168 }
169 if best_len >= MIN_MATCH {
170 put_match(&mut w, best_len, best_dist);
171 for pos in i + 1..i + best_len {
172 if pos + MIN_MATCH <= n {
173 insert(&mut head, &mut prev, pos);
174 }
175 }
176 i += best_len;
177 } else {
178 put_litlen(&mut w, u32::from(input[i]));
179 i += 1;
180 }
181 }
182 put_litlen(&mut w, 256); // end of block
183 w.finish()
184}
185
186/// Stored (BTYPE 00) blocks: byte-aligned header, LEN, NLEN, then the bytes.
187fn stored_blocks(input: &[u8]) -> Vec<u8> {
188 let chunks: Vec<&[u8]> = if input.is_empty() {
189 vec![&[]]
190 } else {
191 input.chunks(STORED_MAX).collect()
192 };
193 let mut out = Vec::with_capacity(input.len() + 5 * chunks.len());
194 let last = chunks.len() - 1;
195 for (k, chunk) in chunks.iter().enumerate() {
196 out.push(u8::from(k == last)); // BFINAL in bit 0, BTYPE 00, rest padding
197 let len = chunk.len() as u16;
198 out.extend_from_slice(&len.to_le_bytes());
199 out.extend_from_slice(&(!len).to_le_bytes());
200 out.extend_from_slice(chunk);
201 }
202 out
203}
204
205#[cfg(test)]
206mod tests {
207 use super::*;
208 use crate::{inflate, inflate_zlib};
209
210 fn pseudo_random(n: usize, seed: u32) -> Vec<u8> {
211 let mut s = seed;
212 (0..n)
213 .map(|_| {
214 s = s.wrapping_mul(1_103_515_245).wrapping_add(12_345);
215 (s >> 16) as u8
216 })
217 .collect()
218 }
219
220 #[test]
221 fn empty_and_tiny_inputs_round_trip() {
222 for input in [&b""[..], b"a", b"ab", b"abc", b"abcabcabc"] {
223 let z = deflate_zlib(input);
224 assert_eq!(inflate_zlib(&z, usize::MAX).unwrap(), input);
225 let raw = deflate_raw(input);
226 assert_eq!(inflate(&raw, usize::MAX).unwrap(), input);
227 }
228 }
229
230 #[test]
231 fn repetitive_input_compresses_and_round_trips() {
232 let input: Vec<u8> = (0..100_000u32).map(|i| (i % 7) as u8).collect();
233 let z = deflate_zlib(&input);
234 assert!(z.len() < input.len() / 20, "{} bytes", z.len());
235 assert_eq!(inflate_zlib(&z, usize::MAX).unwrap(), input);
236 }
237
238 #[test]
239 fn random_input_round_trips_within_framing_overhead() {
240 let input = pseudo_random(200_000, 7);
241 let raw = deflate_raw(&input);
242 assert!(raw.len() <= input.len() + 5 * 4, "{} bytes", raw.len());
243 assert_eq!(inflate(&raw, usize::MAX).unwrap(), input);
244 }
245
246 #[test]
247 fn matches_reach_the_longest_and_furthest_codes() {
248 // Long runs use length 258; a repeat 32 KiB back uses the last distance code.
249 let mut input = pseudo_random(32_768, 3);
250 let head = input[..1000].to_vec();
251 input.extend_from_slice(&head);
252 input.extend(std::iter::repeat_n(9u8, 1000));
253 let z = deflate_zlib(&input);
254 assert_eq!(inflate_zlib(&z, usize::MAX).unwrap(), input);
255 }
256}