forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

inflate.rs213 lines, 7.6 KiBHistoryRawDownload
1//! The RFC 1951 block loop.
2
3use std::sync::OnceLock;
4
5use crate::Error;
6use crate::bits::Bits;
7use crate::huffman::Table;
8
9/// First-level table width for the literal/length and code-length alphabets.
10const LIT_ROOT: u32 = 9;
11/// Distances have thirty symbols; a narrower root keeps the table cache-warm.
12const DIST_ROOT: u32 = 6;
13
14/// Match length per literal/length symbol 257..=285, plus its extra-bit count.
15const LEN_BASE: [u16; 29] = [
16 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,
17 163, 195, 227, 258,
18];
19const LEN_EXTRA: [u32; 29] = [
20 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,
21];
22/// Match distance per distance symbol 0..=29, plus its extra-bit count.
23const DIST_BASE: [u32; 30] = [
24 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537,
25 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577,
26];
27const DIST_EXTRA: [u32; 30] = [
28 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,
29 13,
30];
31/// The order dynamic blocks list their code-length code lengths in.
32const CODE_LENGTH_ORDER: [usize; 19] = [
33 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15,
34];
35
36/// The fixed literal/length and distance trees of RFC 1951 §3.2.6, built once.
37fn fixed_tables() -> &'static (Table, Table) {
38 static FIXED: OnceLock<(Table, Table)> = OnceLock::new();
39 FIXED.get_or_init(|| {
40 let mut lit = [0u16; 288];
41 for (sym, l) in lit.iter_mut().enumerate() {
42 *l = match sym {
43 0..=143 => 8,
44 144..=255 => 9,
45 256..=279 => 7,
46 _ => 8,
47 };
48 }
49 // All thirty-two distance slots are five bits wide; 30 and 31 decode to
50 // symbols that no valid stream uses, and are refused below.
51 let dist = [5u16; 32];
52 (
53 Table::new(&lit, LIT_ROOT).expect("fixed literal tree is well formed"),
54 Table::new(&dist, DIST_ROOT).expect("fixed distance tree is well formed"),
55 )
56 })
57}
58
59/// Decode every block of a raw DEFLATE stream into `out`, stopping at the final
60/// one; returns the byte offset just past the stream.
61pub(crate) fn blocks(bits: &mut Bits, out: &mut Vec<u8>, limit: usize) -> Result<usize, Error> {
62 loop {
63 let last = bits.take(1)? == 1;
64 match bits.take(2)? {
65 0 => stored(bits, out, limit)?,
66 1 => {
67 let (lit, dist) = fixed_tables();
68 compressed(bits, out, limit, lit, dist)?;
69 }
70 2 => {
71 let (lit, dist) = dynamic_tables(bits)?;
72 compressed(bits, out, limit, &lit, &dist)?;
73 }
74 _ => return Err(Error::corrupt("reserved DEFLATE block type 3")),
75 }
76 if last {
77 return Ok(bits.align());
78 }
79 }
80}
81
82/// §3.2.4 stored block: byte-aligned, length and its complement, then raw bytes.
83fn stored(bits: &mut Bits, out: &mut Vec<u8>, limit: usize) -> Result<(), Error> {
84 let pos = bits.align();
85 let src = bits.src();
86 let header = src.get(pos..pos + 4).ok_or(Error::Truncated)?;
87 let len = u16::from_le_bytes([header[0], header[1]]);
88 let nlen = u16::from_le_bytes([header[2], header[3]]);
89 if len != !nlen {
90 return Err(Error::corrupt(
91 "stored block length does not match its complement",
92 ));
93 }
94 let len = len as usize;
95 let body = src.get(pos + 4..pos + 4 + len).ok_or(Error::Truncated)?;
96 reserve(out, len, limit)?;
97 out.extend_from_slice(body);
98 bits.seek(pos + 4 + len);
99 Ok(())
100}
101
102/// §3.2.7 dynamic block header: the code-length code, then the two trees it codes.
103fn dynamic_tables(bits: &mut Bits) -> Result<(Table, Table), Error> {
104 let hlit = bits.take(5)? as usize + 257;
105 let hdist = bits.take(5)? as usize + 1;
106 let hclen = bits.take(4)? as usize + 4;
107
108 let mut cl_lengths = [0u16; 19];
109 for &slot in CODE_LENGTH_ORDER.iter().take(hclen) {
110 cl_lengths[slot] = bits.take(3)? as u16;
111 }
112 let cl_table = Table::new(&cl_lengths, LIT_ROOT)?;
113
114 let mut lengths = vec![0u16; hlit + hdist];
115 let mut i = 0;
116 while i < lengths.len() {
117 let (value, run) = match cl_table.decode(bits)? {
118 sym @ 0..=15 => (sym, 1),
119 16 => {
120 let prev = *lengths
121 .get(i.wrapping_sub(1))
122 .ok_or_else(|| Error::corrupt("code-length repeat with nothing to repeat"))?;
123 (prev, 3 + bits.take(2)? as usize)
124 }
125 17 => (0, 3 + bits.take(3)? as usize),
126 18 => (0, 11 + bits.take(7)? as usize),
127 _ => return Err(Error::corrupt("code-length symbol above 18")),
128 };
129 if i + run > lengths.len() {
130 return Err(Error::corrupt("code-length run past the end of the tables"));
131 }
132 lengths[i..i + run].fill(value);
133 i += run;
134 }
135
136 let lit = Table::new(&lengths[..hlit], LIT_ROOT)?;
137 let dist = Table::new(&lengths[hlit..], DIST_ROOT)?;
138 Ok((lit, dist))
139}
140
141/// The literal/match loop shared by fixed and dynamic blocks.
142fn compressed(
143 bits: &mut Bits,
144 out: &mut Vec<u8>,
145 limit: usize,
146 lit: &Table,
147 dist: &Table,
148) -> Result<(), Error> {
149 loop {
150 let sym = lit.decode(bits)?;
151 match sym {
152 0..=255 => {
153 if out.len() == limit {
154 return Err(Error::LimitExceeded { limit });
155 }
156 out.push(sym as u8);
157 }
158 256 => return Ok(()),
159 257..=285 => {
160 let index = sym as usize - 257;
161 let length = LEN_BASE[index] as usize + bits.take(LEN_EXTRA[index])? as usize;
162 let dsym = dist.decode(bits)? as usize;
163 if dsym >= DIST_BASE.len() {
164 return Err(Error::corrupt("distance symbol 30 or 31"));
165 }
166 let distance = DIST_BASE[dsym] as usize + bits.take(DIST_EXTRA[dsym])? as usize;
167 if distance > out.len() {
168 return Err(Error::corrupt("match distance reaches before the output"));
169 }
170 reserve(out, length, limit)?;
171 copy_match(out, distance, length);
172 }
173 _ => return Err(Error::corrupt("literal/length symbol 286 or 287")),
174 }
175 }
176}
177
178/// LZ77 back-reference.
179///
180/// An overlapping match — `distance` one is how DEFLATE spells a run of the
181/// same byte — is defined byte by byte, but it does not have to be *copied*
182/// byte by byte: each pass copies everything already settled, so the window
183/// doubles and a 258-byte run costs eight `memcpy`s rather than 258 pushes.
184#[inline]
185fn copy_match(out: &mut Vec<u8>, distance: usize, length: usize) {
186 let end = out.len();
187 out.resize(end + length, 0);
188 let (head, tail) = out.split_at_mut(end);
189 let pattern = &head[end - distance..];
190 if distance >= length {
191 tail.copy_from_slice(&pattern[..length]);
192 return;
193 }
194 tail[..distance].copy_from_slice(pattern);
195 let mut filled = distance;
196 while filled < length {
197 let take = filled.min(length - filled);
198 let (done, rest) = tail.split_at_mut(filled);
199 rest[..take].copy_from_slice(&done[..take]);
200 filled += take;
201 }
202}
203
204/// The ceiling, checked before every write: a crafted stream must fail, not
205/// take all the memory there is.
206#[inline]
207fn reserve(out: &mut Vec<u8>, extra: usize, limit: usize) -> Result<(), Error> {
208 if out.len() + extra > limit {
209 return Err(Error::LimitExceeded { limit });
210 }
211 out.reserve(extra);
212 Ok(())
213}