compress_lib/inflate/mod.rs
1//! The raw DEFLATE (RFC 1951) decoder.
2//!
3//! Output goes straight into the caller's buffer. Back-references reach
4//! into the output written in the same call, and, further back, into a ring
5//! of `2^window_bits` bytes updated once per call with the newest output, so
6//! a call costs `O(consumed + produced)` however small the buffers are.
7
8pub(crate) mod tables;
9
10use alloc::{boxed::Box, vec::Vec};
11
12use tables::{
13 Alphabet, DIST_ROOT, END_OF_BLOCK, FIXED_DIST, FIXED_LIT, INVALID, LIT_ROOT, LITERAL, PRE_ROOT,
14 SUBTABLE, Tables,
15};
16
17use crate::{Error, ErrorKind, Limits, Progress, Status};
18
19/// Output room the fast loop needs per symbol: the longest match plus an
20/// eight-byte over-copy, rounded up.
21const FAST_OUT: usize = 258 + 16;
22/// Input the fast loop needs per symbol: one eight-byte refill.
23const FAST_IN: usize = 8;
24/// Order in which code-length code lengths are stored (RFC 1951 3.2.7).
25const PRECODE_ORDER: [u8; 19] = [
26 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15,
27];
28/// Most output `decompress_vec` reserves in one step.
29const VEC_CHUNK: usize = 64 << 10;
30
31#[derive(Clone, Copy, Debug, PartialEq, Eq)]
32enum State {
33 /// Waiting for a block header (3 bits).
34 Header,
35 /// Stored block: skip to a byte boundary, then LEN and NLEN.
36 StoredLength,
37 /// Stored block: `stored_left` bytes to copy.
38 Stored,
39 /// Dynamic block: HLIT, HDIST, HCLEN.
40 Counts,
41 /// Dynamic block: code-length code lengths, `index` of `hclen` read.
42 PrecodeLengths,
43 /// Dynamic block: literal/length and distance code lengths, `index` of
44 /// `hlit + hdist` read.
45 CodeLengths,
46 /// Decoding symbols.
47 Data,
48 /// A length was decoded (`pending_len`); its distance comes next.
49 Distance,
50 /// A match is being copied: `pending_len` bytes left at `pending_dist`.
51 Copy,
52 /// The final block ended.
53 Done,
54}
55
56/// Why the decoding loop stopped.
57#[derive(Clone, Copy, PartialEq, Eq)]
58enum Stop {
59 Done,
60 NeedInput,
61 NeedOutput,
62}
63
64/// A streaming raw DEFLATE decoder (RFC 1951).
65///
66/// Push compressed input and pull decompressed output through buffers you
67/// own. Memory is fixed when the inflater is built: the decode tables (about
68/// 11 KiB) and a history window of `2^window_bits` bytes. Every limit in
69/// [`Limits`] is checked before output is written.
70///
71/// # Examples
72///
73/// ```
74/// use compress_lib::deflate::{Inflater, Status};
75///
76/// // "hello" compressed with fixed Huffman codes.
77/// let compressed = [0xCB, 0x48, 0xCD, 0xC9, 0xC9, 0x07, 0x00];
78/// let mut inflater = Inflater::new();
79/// let mut out = [0u8; 64];
80/// let p = inflater.finish(&compressed, &mut out)?;
81/// assert_eq!(p.status, Status::Done);
82/// assert_eq!(&out[..p.produced], b"hello");
83/// # Ok::<(), compress_lib::Error>(())
84/// ```
85pub struct Inflater {
86 limits: Limits,
87 window_bits: u8,
88 /// Keep a history ring across calls (off only for one-shot decoding).
89 keep_history: bool,
90 state: State,
91 final_block: bool,
92 /// The current block uses the fixed codes.
93 fixed: bool,
94 bitbuf: u64,
95 bitcnt: u32,
96 total_in: u64,
97 total_out: u64,
98 failed: Option<Error>,
99 hlit: u16,
100 hdist: u16,
101 hclen: u16,
102 index: u16,
103 stored_left: u32,
104 pending_len: u32,
105 pending_dist: u32,
106 tables: Box<Tables>,
107 /// History ring: the newest `whave` bytes end just before `wpos`.
108 ring: Vec<u8>,
109 wpos: usize,
110 whave: usize,
111}
112
113impl core::fmt::Debug for Inflater {
114 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
115 f.debug_struct("Inflater")
116 .field("window_bits", &self.window_bits)
117 .field("limits", &self.limits)
118 .field("state", &self.state)
119 .field("total_in", &self.total_in)
120 .field("total_out", &self.total_out)
121 .field("failed", &self.failed)
122 .finish_non_exhaustive()
123 }
124}
125
126impl Default for Inflater {
127 fn default() -> Self {
128 Self::new()
129 }
130}
131
132/// Copies `n` bytes from `buf[src..]` to `buf[dst..]` front to back, so an
133/// overlapping source repeats its pattern (LZ77 semantics). `src < dst`.
134#[inline(always)]
135fn copy_forward(buf: &mut [u8], src: usize, dst: usize, n: usize) {
136 let dist = dst - src;
137 if dist >= n {
138 buf.copy_within(src..src + n, dst);
139 } else if dist == 1 {
140 let b = buf[src];
141 buf[dst..dst + n].fill(b);
142 } else {
143 // `buf[src..dst]` repeats with period `dist`; every copy doubles it.
144 let mut done = 0;
145 while done < n {
146 let chunk = (dist + done).min(n - done);
147 buf.copy_within(src..src + chunk, dst + done);
148 done += chunk;
149 }
150 }
151}
152
153impl Inflater {
154 /// An inflater with window bits 15 and the default [`Limits`].
155 ///
156 /// # Examples
157 ///
158 /// ```
159 /// let inflater = compress_lib::deflate::Inflater::new();
160 /// assert_eq!(inflater.window_bits(), 15);
161 /// ```
162 #[must_use]
163 pub fn new() -> Self {
164 let mut inflater = Self::without_history(Limits::new());
165 inflater.keep_history = true;
166 inflater.ring = alloc::vec![0; 1 << 15];
167 inflater
168 }
169
170 /// An inflater that keeps no history between calls: for one-shot
171 /// decoding, where all output lands in one buffer.
172 pub(crate) fn without_history(limits: Limits) -> Self {
173 Self {
174 limits,
175 window_bits: 15,
176 keep_history: false,
177 state: State::Header,
178 final_block: false,
179 fixed: false,
180 bitbuf: 0,
181 bitcnt: 0,
182 total_in: 0,
183 total_out: 0,
184 failed: None,
185 hlit: 0,
186 hdist: 0,
187 hclen: 0,
188 index: 0,
189 stored_left: 0,
190 pending_len: 0,
191 pending_dist: 0,
192 tables: Box::new(Tables::new()),
193 ring: Vec::new(),
194 wpos: 0,
195 whave: 0,
196 }
197 }
198
199 /// Sets the window size to `2^bits` bytes, 8 to 15. A back-reference
200 /// further than the window is `DistanceTooFar` (RFC 7692 negotiates
201 /// these sizes). Memory: the window shrinks with it.
202 ///
203 /// # Errors
204 ///
205 /// [`ErrorKind::InvalidWindowBits`] outside 8 to 15.
206 ///
207 /// # Examples
208 ///
209 /// ```
210 /// use compress_lib::deflate::Inflater;
211 ///
212 /// let inflater = Inflater::new().with_window_bits(9)?;
213 /// assert_eq!(inflater.window_bits(), 9);
214 /// assert!(Inflater::new().with_window_bits(16).is_err());
215 /// # Ok::<(), compress_lib::Error>(())
216 /// ```
217 pub fn with_window_bits(mut self, bits: u8) -> Result<Self, Error> {
218 if !(8..=15).contains(&bits) {
219 return Err(Error::config(ErrorKind::InvalidWindowBits));
220 }
221 self.window_bits = bits;
222 if self.keep_history {
223 self.ring = alloc::vec![0; 1 << bits];
224 }
225 self.reset();
226 Ok(self)
227 }
228
229 /// Sets the limits checked while decoding.
230 ///
231 /// # Examples
232 ///
233 /// ```
234 /// use compress_lib::{Limits, deflate::Inflater};
235 ///
236 /// let inflater = Inflater::new().with_limits(Limits::new().with_max_output(1 << 20));
237 /// assert_eq!(inflater.limits().max_output(), 1 << 20);
238 /// ```
239 #[must_use]
240 pub fn with_limits(mut self, limits: Limits) -> Self {
241 self.limits = limits;
242 self
243 }
244
245 /// The window size in bits.
246 ///
247 /// # Examples
248 ///
249 /// ```
250 /// assert_eq!(compress_lib::deflate::Inflater::new().window_bits(), 15);
251 /// ```
252 #[must_use]
253 pub fn window_bits(&self) -> u8 {
254 self.window_bits
255 }
256
257 /// The limits in force.
258 ///
259 /// # Examples
260 ///
261 /// ```
262 /// use compress_lib::{Limits, deflate::Inflater};
263 ///
264 /// assert_eq!(Inflater::new().limits(), Limits::new());
265 /// ```
266 #[must_use]
267 pub fn limits(&self) -> Limits {
268 self.limits
269 }
270
271 /// `true` once the final block has ended.
272 ///
273 /// # Examples
274 ///
275 /// ```
276 /// use compress_lib::deflate::Inflater;
277 ///
278 /// let mut inflater = Inflater::new();
279 /// assert!(!inflater.is_done());
280 /// inflater.finish(&[0x03, 0x00], &mut [])?; // an empty stream
281 /// assert!(inflater.is_done());
282 /// # Ok::<(), compress_lib::Error>(())
283 /// ```
284 #[must_use]
285 pub fn is_done(&self) -> bool {
286 self.state == State::Done
287 }
288
289 /// Compressed bytes consumed since the inflater was built or reset.
290 ///
291 /// # Examples
292 ///
293 /// ```
294 /// use compress_lib::deflate::Inflater;
295 ///
296 /// let mut inflater = Inflater::new();
297 /// inflater.finish(&[0x03, 0x00], &mut [])?;
298 /// assert_eq!(inflater.total_in(), 2);
299 /// # Ok::<(), compress_lib::Error>(())
300 /// ```
301 #[must_use]
302 pub fn total_in(&self) -> u64 {
303 self.total_in
304 }
305
306 /// Decompressed bytes produced since the inflater was built or reset.
307 ///
308 /// # Examples
309 ///
310 /// ```
311 /// use compress_lib::deflate::Inflater;
312 ///
313 /// let mut inflater = Inflater::new();
314 /// let mut out = [0u8; 8];
315 /// inflater.finish(&[0xCB, 0x48, 0xCD, 0xC9, 0xC9, 0x07, 0x00], &mut out)?;
316 /// assert_eq!(inflater.total_out(), 5);
317 /// # Ok::<(), compress_lib::Error>(())
318 /// ```
319 #[must_use]
320 pub fn total_out(&self) -> u64 {
321 self.total_out
322 }
323
324 /// Heap bytes this inflater holds: the tables and the window.
325 ///
326 /// # Examples
327 ///
328 /// ```
329 /// use compress_lib::deflate::Inflater;
330 ///
331 /// let small = Inflater::new().with_window_bits(9)?;
332 /// assert!(small.memory_in_use() < Inflater::new().memory_in_use());
333 /// # Ok::<(), compress_lib::Error>(())
334 /// ```
335 #[must_use]
336 pub fn memory_in_use(&self) -> usize {
337 core::mem::size_of::<Tables>() + self.ring.capacity()
338 }
339
340 /// Forgets the stream and its history, keeping the allocations, so the
341 /// inflater can decode an unrelated stream.
342 ///
343 /// # Examples
344 ///
345 /// ```
346 /// use compress_lib::deflate::Inflater;
347 ///
348 /// let mut inflater = Inflater::new();
349 /// inflater.finish(&[0x03, 0x00], &mut [])?;
350 /// inflater.reset();
351 /// assert!(!inflater.is_done());
352 /// assert_eq!(inflater.total_in(), 0);
353 /// # Ok::<(), compress_lib::Error>(())
354 /// ```
355 pub fn reset(&mut self) {
356 self.state = State::Header;
357 self.final_block = false;
358 self.fixed = false;
359 self.bitbuf = 0;
360 self.bitcnt = 0;
361 self.total_in = 0;
362 self.total_out = 0;
363 self.failed = None;
364 self.wpos = 0;
365 self.whave = 0;
366 }
367
368 /// After `Done`, starts a new DEFLATE stream that keeps the window, so
369 /// the next stream may refer back into this one. This is RFC 7692 context
370 /// takeover after a message that ended with a final block.
371 ///
372 /// # Errors
373 ///
374 /// [`ErrorKind::InvalidState`] before the current stream is done.
375 ///
376 /// # Examples
377 ///
378 /// ```
379 /// use compress_lib::deflate::Inflater;
380 ///
381 /// let mut inflater = Inflater::new();
382 /// let mut out = Vec::new();
383 /// inflater.finish_vec(&[0x03, 0x00], &mut out)?;
384 /// inflater.next_stream()?;
385 /// inflater.finish_vec(&[0x03, 0x00], &mut out)?;
386 /// # Ok::<(), compress_lib::Error>(())
387 /// ```
388 pub fn next_stream(&mut self) -> Result<(), Error> {
389 if self.state != State::Done {
390 return Err(Error::config(ErrorKind::InvalidState));
391 }
392 self.state = State::Header;
393 self.final_block = false;
394 self.bitbuf = 0;
395 self.bitcnt = 0;
396 Ok(())
397 }
398
399 /// Presets the history with `dictionary` (its last `2^window_bits`
400 /// bytes), for streams compressed with the same preset dictionary. Only
401 /// before any input.
402 ///
403 /// # Errors
404 ///
405 /// [`ErrorKind::InvalidState`] after input has been given.
406 ///
407 /// # Examples
408 ///
409 /// ```
410 /// use compress_lib::deflate::Inflater;
411 ///
412 /// let mut inflater = Inflater::new();
413 /// inflater.set_dictionary(b"common prefix")?;
414 /// # Ok::<(), compress_lib::Error>(())
415 /// ```
416 pub fn set_dictionary(&mut self, dictionary: &[u8]) -> Result<(), Error> {
417 if self.total_in != 0 || self.state != State::Header || self.failed.is_some() {
418 return Err(Error::config(ErrorKind::InvalidState));
419 }
420 if self.ring.is_empty() {
421 self.ring = alloc::vec![0; 1 << self.window_bits];
422 self.keep_history = true;
423 }
424 self.save_history(dictionary);
425 Ok(())
426 }
427
428 /// Decompresses as much of `input` into `output` as fits. More input may
429 /// follow in later calls.
430 ///
431 /// Returns how much input was consumed, how much output was produced,
432 /// and the [`Status`]: `NeedsInput` (all input consumed, the stream goes
433 /// on), `NeedsOutput` (output is full; call again with more room and the
434 /// rest of the input), or `Done` (the final block ended; `consumed`
435 /// stops at the stream's last byte, so trailing data stays with the
436 /// caller).
437 ///
438 /// # Errors
439 ///
440 /// Any decoding error of [`ErrorKind`], or `OutputLimit` / `RatioLimit`
441 /// when a limit stops the stream. After an error every call returns the
442 /// same error until [`reset`](Inflater::reset).
443 ///
444 /// # Examples
445 ///
446 /// ```
447 /// use compress_lib::deflate::{Inflater, Status};
448 ///
449 /// let compressed = [0xCB, 0x48, 0xCD, 0xC9, 0xC9, 0x07, 0x00];
450 /// let mut inflater = Inflater::new();
451 /// let mut out = Vec::new();
452 /// let mut buf = [0u8; 2]; // tiny on purpose
453 /// let mut input = &compressed[..];
454 /// loop {
455 /// let p = inflater.decompress(input, &mut buf)?;
456 /// input = &input[p.consumed..];
457 /// out.extend_from_slice(&buf[..p.produced]);
458 /// if p.status == Status::Done {
459 /// break;
460 /// }
461 /// }
462 /// assert_eq!(out, b"hello");
463 /// # Ok::<(), compress_lib::Error>(())
464 /// ```
465 pub fn decompress(&mut self, input: &[u8], output: &mut [u8]) -> Result<Progress, Error> {
466 self.run_slice(input, output, false)
467 }
468
469 /// As [`decompress`](Inflater::decompress), with `input` the last of the
470 /// stream: if the stream is unfinished once input runs out, the result
471 /// is `UnexpectedEnd` (unless output was full first, which is
472 /// `NeedsOutput`).
473 ///
474 /// # Errors
475 ///
476 /// As `decompress`, plus [`ErrorKind::UnexpectedEnd`].
477 ///
478 /// # Examples
479 ///
480 /// ```
481 /// use compress_lib::{ErrorKind, deflate::Inflater};
482 ///
483 /// let truncated = [0xCB, 0x48, 0xCD];
484 /// let mut out = [0u8; 16];
485 /// let err = Inflater::new().finish(&truncated, &mut out).unwrap_err();
486 /// assert_eq!(err.kind(), ErrorKind::UnexpectedEnd);
487 /// ```
488 pub fn finish(&mut self, input: &[u8], output: &mut [u8]) -> Result<Progress, Error> {
489 self.run_slice(input, output, true)
490 }
491
492 /// Decompresses `input`, appending to `out`, growing it as needed but
493 /// never past the output cap. Growth doubles what this call has
494 /// produced (at least 64 KiB at a time), so peak memory is at most 1.5
495 /// times `max_output` while a reallocation holds the old buffer and the
496 /// new one. Returns `NeedsInput` or `Done`.
497 ///
498 /// # Errors
499 ///
500 /// As [`decompress`](Inflater::decompress), plus
501 /// [`ErrorKind::AllocationFailed`] when the vector cannot grow.
502 ///
503 /// # Examples
504 ///
505 /// ```
506 /// use compress_lib::deflate::{Inflater, Status};
507 ///
508 /// let mut out = Vec::new();
509 /// let p = Inflater::new().decompress_vec(&[0xCB, 0x48, 0xCD, 0xC9, 0xC9, 0x07, 0x00], &mut out)?;
510 /// assert_eq!(p.status, Status::Done);
511 /// assert_eq!(out, b"hello");
512 /// # Ok::<(), compress_lib::Error>(())
513 /// ```
514 pub fn decompress_vec(&mut self, input: &[u8], out: &mut Vec<u8>) -> Result<Progress, Error> {
515 self.run_vec(input, out, false)
516 }
517
518 /// As [`decompress_vec`](Inflater::decompress_vec), with `input` the last
519 /// of the stream: an unfinished stream is `UnexpectedEnd`.
520 ///
521 /// # Errors
522 ///
523 /// As `decompress_vec`, plus [`ErrorKind::UnexpectedEnd`].
524 ///
525 /// # Examples
526 ///
527 /// ```
528 /// use compress_lib::deflate::Inflater;
529 ///
530 /// let mut out = Vec::new();
531 /// Inflater::new().finish_vec(&[0x03, 0x00], &mut out)?;
532 /// assert!(out.is_empty());
533 /// # Ok::<(), compress_lib::Error>(())
534 /// ```
535 pub fn finish_vec(&mut self, input: &[u8], out: &mut Vec<u8>) -> Result<Progress, Error> {
536 self.run_vec(input, out, true)
537 }
538
539 fn run_slice(
540 &mut self,
541 input: &[u8],
542 output: &mut [u8],
543 last: bool,
544 ) -> Result<Progress, Error> {
545 let (consumed, produced, status) = self.run(input, output, 0, last)?;
546 if self.keep_history {
547 self.save_history(&output[..produced]);
548 }
549 Ok(Progress::new(consumed, produced, status))
550 }
551
552 fn run_vec(&mut self, input: &[u8], out: &mut Vec<u8>, last: bool) -> Result<Progress, Error> {
553 let start = out.len();
554 let p = self.run_vec_from(input, out, start, last)?;
555 if self.keep_history {
556 self.save_history(&out[start..]);
557 }
558 Ok(p)
559 }
560
561 /// Decodes into `out`, treating `out[history_start..]` as this stream's
562 /// output so far (it is the history for back-references). The ring is
563 /// not updated; the caller records the history when it is done with it.
564 pub(crate) fn decompress_into(
565 &mut self,
566 input: &[u8],
567 out: &mut Vec<u8>,
568 history_start: usize,
569 last: bool,
570 ) -> Result<Progress, Error> {
571 self.run_vec_from(input, out, history_start, last)
572 }
573
574 /// Records `data` as the newest history (when a window is kept).
575 pub(crate) fn remember(&mut self, data: &[u8]) {
576 if self.keep_history {
577 self.save_history(data);
578 }
579 }
580
581 /// Replaces the output cap.
582 pub(crate) fn set_max_output(&mut self, max: u64) {
583 self.limits = self.limits.with_max_output(max);
584 }
585
586 fn run_vec_from(
587 &mut self,
588 input: &[u8],
589 out: &mut Vec<u8>,
590 start: usize,
591 last: bool,
592 ) -> Result<Progress, Error> {
593 let first = out.len();
594 let mut consumed = 0;
595 let status = loop {
596 let have = out.len();
597 let made = have - start;
598 let cap_room = usize::try_from(self.limits.max_output().saturating_sub(self.total_out))
599 .unwrap_or(usize::MAX);
600 // Room offered per step: geometric (at least what this stream has
601 // produced) but at most 64 KiB ahead of it, and never past the cap.
602 let want = cap_room.min(VEC_CHUNK.max(made));
603 if out.capacity() - have < want && out.try_reserve_exact(want).is_err() {
604 return Err(self.fail(ErrorKind::AllocationFailed, 0));
605 }
606 let room = (out.capacity() - have).min(want);
607 out.resize(have + room, 0);
608 match self.run(&input[consumed..], &mut out[start..], made, last) {
609 Ok((c, p, status)) => {
610 out.truncate(have + p);
611 consumed += c;
612 if status != Status::NeedsOutput {
613 break status;
614 }
615 }
616 Err(e) => {
617 out.truncate(have);
618 return Err(e);
619 }
620 }
621 };
622 Ok(Progress::new(consumed, out.len() - first, status))
623 }
624
625 /// Records `newest` (this call's output) in the history ring.
626 fn save_history(&mut self, newest: &[u8]) {
627 let size = self.ring.len();
628 if size == 0 || newest.is_empty() {
629 return;
630 }
631 if newest.len() >= size {
632 self.ring.copy_from_slice(&newest[newest.len() - size..]);
633 self.wpos = 0;
634 self.whave = size;
635 return;
636 }
637 let first = (size - self.wpos).min(newest.len());
638 self.ring[self.wpos..self.wpos + first].copy_from_slice(&newest[..first]);
639 let rest = newest.len() - first;
640 self.ring[..rest].copy_from_slice(&newest[first..]);
641 self.wpos = (self.wpos + newest.len()) & (size - 1);
642 self.whave = (self.whave + newest.len()).min(size);
643 }
644
645 /// Marks the inflater failed with `kind` at the current input position.
646 fn fail(&mut self, kind: ErrorKind, ip: usize) -> Error {
647 let offset = (self.total_in + ip as u64).saturating_sub(u64::from(self.bitcnt / 8));
648 let e = Error::new(kind, offset);
649 self.failed = Some(e);
650 e
651 }
652
653 /// Decodes into `buf[op_start..]`, with `buf[..op_start]` already-valid
654 /// output of this stream (history). Returns (consumed, produced, status).
655 fn run(
656 &mut self,
657 input: &[u8],
658 buf: &mut [u8],
659 op_start: usize,
660 last: bool,
661 ) -> Result<(usize, usize, Status), Error> {
662 if let Some(e) = self.failed {
663 return Err(e);
664 }
665 let mut ip = 0;
666 let mut op = op_start;
667 let stop = loop {
668 let cap_room = self
669 .limits
670 .max_output()
671 .saturating_sub(self.total_out + (op - op_start) as u64);
672 let cap_end = op
673 + usize::try_from(cap_room)
674 .unwrap_or(usize::MAX)
675 .min(buf.len() - op);
676 let mut end = cap_end;
677 if self.limits.max_ratio() != 0 {
678 let taken = self.total_in + ip as u64;
679 let allowed = taken
680 .saturating_mul(u64::from(self.limits.max_ratio()))
681 .max(self.limits.ratio_floor());
682 let ratio_room = allowed.saturating_sub(self.total_out + (op - op_start) as u64);
683 end = end.min(op + usize::try_from(ratio_room).unwrap_or(usize::MAX));
684 }
685 let before = (ip, op);
686 let stop = match self.step(input, &mut ip, buf, &mut op, end) {
687 Ok(stop) => stop,
688 Err(kind) => {
689 self.total_out += (op - op_start) as u64;
690 return Err(self.fail(kind, ip));
691 }
692 };
693 if stop != Stop::NeedOutput {
694 break stop;
695 }
696 // More output is pending: past the cap that is the end, whatever
697 // room the caller gave.
698 if op == cap_end && cap_room == (op - before.1) as u64 {
699 self.total_out += (op - op_start) as u64;
700 return Err(self.fail(ErrorKind::OutputLimit, ip));
701 }
702 if op == buf.len() {
703 break stop;
704 }
705 // Stopped at the ratio bound. More input taken since raises it;
706 // if nothing moved, the ratio is exceeded.
707 if (ip, op) == before && op == end {
708 self.total_out += (op - op_start) as u64;
709 return Err(self.fail(ErrorKind::RatioLimit, ip));
710 }
711 };
712
713 let produced = op - op_start;
714 self.total_out += produced as u64;
715 if stop == Stop::NeedInput && last {
716 self.total_in += ip as u64;
717 return Err(self.fail(ErrorKind::UnexpectedEnd, 0));
718 }
719 // Give back whole bytes the bit buffer read ahead, so `consumed`
720 // stops at the last bit used (after `Done`, trailing data stays with
721 // the caller). On `NeedsInput` every buffered bit belongs to the
722 // pending symbol, and all input counts as consumed.
723 if stop != Stop::NeedInput {
724 let give = ((self.bitcnt / 8) as usize).min(ip);
725 ip -= give;
726 self.bitcnt -= 8 * give as u32;
727 }
728 self.bitbuf &= (1u64 << self.bitcnt) - 1;
729 if stop == Stop::Done {
730 self.bitbuf = 0;
731 self.bitcnt = 0;
732 }
733 self.total_in += ip as u64;
734 let status = match stop {
735 Stop::Done => Status::Done,
736 Stop::NeedInput => Status::NeedsInput,
737 Stop::NeedOutput => Status::NeedsOutput,
738 };
739 Ok((ip, produced, status))
740 }
741
742 /// Pulls bytes into the bit buffer until it holds `n` bits. `false` when
743 /// input runs out first.
744 #[inline]
745 fn need(&mut self, n: u32, input: &[u8], ip: &mut usize) -> bool {
746 while self.bitcnt < n {
747 if *ip >= input.len() {
748 return false;
749 }
750 self.bitbuf |= u64::from(input[*ip]) << self.bitcnt;
751 self.bitcnt += 8;
752 *ip += 1;
753 }
754 true
755 }
756
757 #[inline]
758 fn bits(&self, n: u32) -> u32 {
759 (self.bitbuf & ((1u64 << n) - 1)) as u32
760 }
761
762 #[inline]
763 fn consume(&mut self, n: u32) {
764 self.bitbuf >>= n;
765 self.bitcnt -= n;
766 }
767
768 /// Looks up the next symbol in `table`, pulling bytes one at a time
769 /// until the entry's bits are buffered. Returns the entry with the bits
770 /// to consume, or `None` when input runs out first (nothing consumed).
771 fn peek(&mut self, table: Which, input: &[u8], ip: &mut usize) -> Option<(u32, u32)> {
772 loop {
773 let (t, root): (&[u32], u32) = match table {
774 Which::Lit if self.fixed => (&FIXED_LIT, LIT_ROOT),
775 Which::Lit => (&self.tables.lit, LIT_ROOT),
776 Which::Dist if self.fixed => (&FIXED_DIST, DIST_ROOT),
777 Which::Dist => (&self.tables.dist, DIST_ROOT),
778 Which::Pre => (&self.tables.pre, PRE_ROOT),
779 };
780 let mut e = t[(self.bitbuf & ((1u64 << root) - 1)) as usize];
781 let mut skip = 0;
782 if e & SUBTABLE != 0 {
783 let bits = (e >> 8) & 0xF;
784 let index = ((self.bitbuf >> root) & ((1u64 << bits) - 1)) as usize;
785 e = t[(e >> 16) as usize + index];
786 skip = root;
787 }
788 let needed = skip + (e & 0xFF);
789 if self.bitcnt >= needed {
790 return Some((e, skip));
791 }
792 if *ip >= input.len() {
793 return None;
794 }
795 self.bitbuf |= u64::from(input[*ip]) << self.bitcnt;
796 self.bitcnt += 8;
797 *ip += 1;
798 }
799 }
800
801 /// The state that follows the end of a block.
802 fn end_block(&mut self) -> State {
803 if self.final_block {
804 State::Done
805 } else {
806 State::Header
807 }
808 }
809
810 /// Checks a distance against the window and the history available with
811 /// `in_buf` bytes of this stream's output before the write position.
812 #[inline]
813 fn check_distance(&self, dist: usize, in_buf: usize) -> Result<(), ErrorKind> {
814 if dist > (1usize << self.window_bits) || (dist > in_buf && dist - in_buf > self.whave) {
815 Err(ErrorKind::DistanceTooFar)
816 } else {
817 Ok(())
818 }
819 }
820
821 /// Copies `n` bytes of a match at `dist` to `buf[op..]`; the part before
822 /// `buf[0]` comes from the history ring. The distance was checked.
823 fn copy_match(&self, buf: &mut [u8], op: usize, dist: usize, n: usize) {
824 if dist <= op {
825 copy_forward(buf, op - dist, op, n);
826 return;
827 }
828 let back = dist - op;
829 let from_ring = back.min(n);
830 let size = self.ring.len();
831 let mut r = (self.wpos + size - back) & (size - 1);
832 let mut o = op;
833 let mut left = from_ring;
834 while left > 0 {
835 let run = left.min(size - r);
836 buf[o..o + run].copy_from_slice(&self.ring[r..r + run]);
837 o += run;
838 left -= run;
839 r = (r + run) & (size - 1);
840 }
841 if n > from_ring {
842 // The rest of the match starts at buf[0].
843 copy_forward(buf, 0, o, n - from_ring);
844 }
845 }
846
847 /// Runs the state machine until it stops for input, output, or the end.
848 fn step(
849 &mut self,
850 input: &[u8],
851 ip: &mut usize,
852 buf: &mut [u8],
853 op: &mut usize,
854 end: usize,
855 ) -> Result<Stop, ErrorKind> {
856 loop {
857 match self.state {
858 State::Header => {
859 if !self.need(3, input, ip) {
860 return Ok(Stop::NeedInput);
861 }
862 self.final_block = self.bits(1) == 1;
863 let kind = (self.bitbuf >> 1) & 3;
864 self.consume(3);
865 self.state = match kind {
866 0 => State::StoredLength,
867 1 => {
868 self.fixed = true;
869 State::Data
870 }
871 2 => State::Counts,
872 _ => return Err(ErrorKind::InvalidBlockType),
873 };
874 }
875 State::StoredLength => {
876 let pad = self.bitcnt % 8;
877 self.consume(pad);
878 if !self.need(32, input, ip) {
879 return Ok(Stop::NeedInput);
880 }
881 let len = self.bits(16);
882 let nlen = (self.bitbuf >> 16) as u32 & 0xFFFF;
883 if len != !nlen & 0xFFFF {
884 return Err(ErrorKind::InvalidStoredLength);
885 }
886 self.consume(32);
887 self.stored_left = len;
888 self.state = State::Stored;
889 }
890 State::Stored => {
891 while self.stored_left > 0 {
892 if *op >= end {
893 return Ok(Stop::NeedOutput);
894 }
895 if self.bitcnt >= 8 {
896 buf[*op] = self.bits(8) as u8;
897 self.consume(8);
898 *op += 1;
899 self.stored_left -= 1;
900 } else if *ip < input.len() {
901 let n = (self.stored_left as usize)
902 .min(input.len() - *ip)
903 .min(end - *op);
904 buf[*op..*op + n].copy_from_slice(&input[*ip..*ip + n]);
905 *op += n;
906 *ip += n;
907 self.stored_left -= n as u32;
908 } else {
909 return Ok(Stop::NeedInput);
910 }
911 }
912 self.state = self.end_block();
913 }
914 State::Counts => {
915 if !self.need(14, input, ip) {
916 return Ok(Stop::NeedInput);
917 }
918 self.hlit = self.bits(5) as u16 + 257;
919 self.hdist = (self.bitbuf >> 5) as u16 & 0x1F;
920 self.hdist += 1;
921 self.hclen = (self.bitbuf >> 10) as u16 & 0xF;
922 self.hclen += 4;
923 self.consume(14);
924 if self.hlit > 286 || self.hdist > 30 {
925 return Err(ErrorKind::InvalidCodeLengths);
926 }
927 self.tables.lens[..19].fill(0);
928 self.index = 0;
929 self.state = State::PrecodeLengths;
930 }
931 State::PrecodeLengths => {
932 while self.index < self.hclen {
933 if !self.need(3, input, ip) {
934 return Ok(Stop::NeedInput);
935 }
936 let slot = PRECODE_ORDER[self.index as usize] as usize;
937 self.tables.lens[slot] = self.bits(3) as u8;
938 self.consume(3);
939 self.index += 1;
940 }
941 let t = &mut *self.tables;
942 tables::build(
943 &t.lens[..19],
944 &mut t.pre,
945 PRE_ROOT,
946 Alphabet::Precode,
947 false,
948 )?;
949 self.index = 0;
950 self.state = State::CodeLengths;
951 }
952 State::CodeLengths => {
953 let total = self.hlit + self.hdist;
954 while self.index < total {
955 let Some((e, _)) = self.peek(Which::Pre, input, ip) else {
956 return Ok(Stop::NeedInput);
957 };
958 let symbol = e >> 16;
959 let len = e & 0xFF;
960 if symbol < 16 {
961 self.consume(len);
962 self.tables.lens[self.index as usize] = symbol as u8;
963 self.index += 1;
964 continue;
965 }
966 let (extra, base) = match symbol {
967 16 => (2, 3),
968 17 => (3, 3),
969 _ => (7, 11),
970 };
971 if !self.need(len + extra, input, ip) {
972 return Ok(Stop::NeedInput);
973 }
974 let repeat = base + ((self.bitbuf >> len) as u32 & ((1 << extra) - 1));
975 let value = if symbol == 16 {
976 if self.index == 0 {
977 return Err(ErrorKind::InvalidCodeLengths);
978 }
979 self.tables.lens[self.index as usize - 1]
980 } else {
981 0
982 };
983 if u32::from(self.index) + repeat > u32::from(total) {
984 return Err(ErrorKind::InvalidCodeLengths);
985 }
986 self.consume(len + extra);
987 let i = self.index as usize;
988 self.tables.lens[i..i + repeat as usize].fill(value);
989 self.index += repeat as u16;
990 }
991 let (hlit, hdist) = (self.hlit as usize, self.hdist as usize);
992 let t = &mut *self.tables;
993 if t.lens[256] == 0 {
994 return Err(ErrorKind::InvalidCodeLengths);
995 }
996 tables::build(
997 &t.lens[..hlit],
998 &mut t.lit,
999 LIT_ROOT,
1000 Alphabet::LitLen,
1001 true,
1002 )?;
1003 tables::build(
1004 &t.lens[hlit..hlit + hdist],
1005 &mut t.dist,
1006 DIST_ROOT,
1007 Alphabet::Dist,
1008 true,
1009 )?;
1010 self.fixed = false;
1011 self.state = State::Data;
1012 }
1013 State::Data => {
1014 if input.len() - *ip >= FAST_IN && end - *op >= FAST_OUT {
1015 self.fast(input, ip, buf, op, end)?;
1016 continue;
1017 }
1018 let Some((e, skip)) = self.peek(Which::Lit, input, ip) else {
1019 return Ok(Stop::NeedInput);
1020 };
1021 if e & LITERAL != 0 {
1022 if *op >= end {
1023 return Ok(Stop::NeedOutput);
1024 }
1025 self.consume(skip + (e & 0xFF));
1026 buf[*op] = (e >> 16) as u8;
1027 *op += 1;
1028 } else if e & END_OF_BLOCK != 0 {
1029 self.consume(skip + (e & 0xFF));
1030 self.state = self.end_block();
1031 } else if e & INVALID != 0 {
1032 return Err(ErrorKind::InvalidSymbol);
1033 } else {
1034 let code = skip + ((e >> 8) & 0xF);
1035 let extra = (e & 0xFF) - ((e >> 8) & 0xF);
1036 let value = (self.bitbuf >> code) as u32 & ((1 << extra) - 1);
1037 self.consume(skip + (e & 0xFF));
1038 self.pending_len = (e >> 16) + value;
1039 self.state = State::Distance;
1040 }
1041 }
1042 State::Distance => {
1043 let Some((e, skip)) = self.peek(Which::Dist, input, ip) else {
1044 return Ok(Stop::NeedInput);
1045 };
1046 if e & INVALID != 0 {
1047 return Err(ErrorKind::InvalidSymbol);
1048 }
1049 let code = skip + ((e >> 8) & 0xF);
1050 let extra = (e & 0xFF) - ((e >> 8) & 0xF);
1051 let value = (self.bitbuf >> code) as u32 & ((1 << extra) - 1);
1052 let dist = (e >> 16) + value;
1053 self.check_distance(dist as usize, *op)?;
1054 self.consume(skip + (e & 0xFF));
1055 self.pending_dist = dist;
1056 self.state = State::Copy;
1057 }
1058 State::Copy => {
1059 let n = (self.pending_len as usize).min(end - *op);
1060 if n > 0 {
1061 self.copy_match(buf, *op, self.pending_dist as usize, n);
1062 *op += n;
1063 self.pending_len -= n as u32;
1064 }
1065 if self.pending_len > 0 {
1066 return Ok(Stop::NeedOutput);
1067 }
1068 self.state = State::Data;
1069 }
1070 State::Done => return Ok(Stop::Done),
1071 }
1072 }
1073 }
1074
1075 /// The fast loop: decodes symbols while at least `FAST_IN` input bytes
1076 /// and `FAST_OUT` output bytes remain, with one eight-byte refill per
1077 /// symbol and no state saved between symbols. Returns at the end of the
1078 /// block or when the margins run out; the slow path does the rest.
1079 fn fast(
1080 &mut self,
1081 input: &[u8],
1082 ip: &mut usize,
1083 buf: &mut [u8],
1084 op: &mut usize,
1085 end: usize,
1086 ) -> Result<(), ErrorKind> {
1087 let (lit, dist): (&[u32], &[u32]) = if self.fixed {
1088 (&FIXED_LIT, &FIXED_DIST)
1089 } else {
1090 (&self.tables.lit, &self.tables.dist)
1091 };
1092 let window = 1usize << self.window_bits;
1093 let mut bitbuf = self.bitbuf;
1094 let mut bitcnt = self.bitcnt;
1095 let mut i = *ip;
1096 let mut o = *op;
1097 let result = loop {
1098 if input.len() - i < FAST_IN || end - o < FAST_OUT {
1099 break Ok(());
1100 }
1101 let mut word = [0u8; 8];
1102 word.copy_from_slice(&input[i..i + 8]);
1103 bitbuf |= u64::from_le_bytes(word) << bitcnt;
1104 i += ((63 - bitcnt) >> 3) as usize;
1105 bitcnt |= 56;
1106
1107 let mut e = lit[(bitbuf & ((1 << LIT_ROOT) - 1)) as usize];
1108 if e & SUBTABLE != 0 {
1109 bitbuf >>= LIT_ROOT;
1110 bitcnt -= LIT_ROOT;
1111 e = lit[(e >> 16) as usize + (bitbuf & ((1u64 << ((e >> 8) & 0xF)) - 1)) as usize];
1112 }
1113 if e & LITERAL != 0 {
1114 buf[o] = (e >> 16) as u8;
1115 o += 1;
1116 bitbuf >>= e & 0xFF;
1117 bitcnt -= e & 0xFF;
1118 // A second literal often fits in the same refill.
1119 let e2 = lit[(bitbuf & ((1 << LIT_ROOT) - 1)) as usize];
1120 if e2 & LITERAL != 0 && bitcnt >= (e2 & 0xFF) {
1121 buf[o] = (e2 >> 16) as u8;
1122 o += 1;
1123 bitbuf >>= e2 & 0xFF;
1124 bitcnt -= e2 & 0xFF;
1125 }
1126 continue;
1127 }
1128 if e & (END_OF_BLOCK | INVALID) != 0 {
1129 if e & END_OF_BLOCK != 0 {
1130 bitbuf >>= e & 0xFF;
1131 bitcnt -= e & 0xFF;
1132 self.state = if self.final_block {
1133 State::Done
1134 } else {
1135 State::Header
1136 };
1137 break Ok(());
1138 }
1139 break Err(ErrorKind::InvalidSymbol);
1140 }
1141 let code = (e >> 8) & 0xF;
1142 let length = (e >> 16) as usize
1143 + ((bitbuf >> code) & ((1u64 << ((e & 0xFF) - code)) - 1)) as usize;
1144 bitbuf >>= e & 0xFF;
1145 bitcnt -= e & 0xFF;
1146
1147 let mut d = dist[(bitbuf & ((1 << DIST_ROOT) - 1)) as usize];
1148 if d & SUBTABLE != 0 {
1149 bitbuf >>= DIST_ROOT;
1150 bitcnt -= DIST_ROOT;
1151 d = dist[(d >> 16) as usize + (bitbuf & ((1u64 << ((d >> 8) & 0xF)) - 1)) as usize];
1152 }
1153 if d & INVALID != 0 {
1154 break Err(ErrorKind::InvalidSymbol);
1155 }
1156 let code = (d >> 8) & 0xF;
1157 let distance = (d >> 16) as usize
1158 + ((bitbuf >> code) & ((1u64 << ((d & 0xFF) - code)) - 1)) as usize;
1159 bitbuf >>= d & 0xFF;
1160 bitcnt -= d & 0xFF;
1161
1162 if distance > window || (distance > o && distance - o > self.whave) {
1163 break Err(ErrorKind::DistanceTooFar);
1164 }
1165 if distance <= o && distance >= 8 {
1166 // Eight bytes at a time; the source is always written before
1167 // it is read because the distance is at least eight, and the
1168 // over-copy stays inside the FAST_OUT margin.
1169 let mut s = o - distance;
1170 let stop = o + length;
1171 while o < stop {
1172 buf.copy_within(s..s + 8, o);
1173 s += 8;
1174 o += 8;
1175 }
1176 o = stop;
1177 } else {
1178 self.copy_match(buf, o, distance, length);
1179 o += length;
1180 }
1181 };
1182 // The refill leaves read-ahead bits above `bitcnt`; the slow path
1183 // needs them clear.
1184 self.bitbuf = bitbuf & ((1u64 << bitcnt) - 1);
1185 self.bitcnt = bitcnt;
1186 *ip = i;
1187 *op = o;
1188 result
1189 }
1190}
1191
1192/// Which table `peek` reads.
1193#[derive(Clone, Copy)]
1194enum Which {
1195 Lit,
1196 Dist,
1197 Pre,
1198}
1199
1200#[cfg(test)]
1201mod tests;