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 /// Zeroes the history window and the decode tables (which hold what the
369 /// stream decoded and how it was coded), then resets the inflater for a
370 /// new stream. For connections that carried secrets: call it before the
371 /// inflater is dropped or reused. The allocations are kept.
372 ///
373 /// The zeroing goes through [`core::hint::black_box`] so it is not
374 /// removed as a dead store; without `unsafe` volatile writes that is a
375 /// strong hint to the compiler, not a guarantee.
376 ///
377 /// # Examples
378 ///
379 /// ```
380 /// use compress_lib::deflate::Inflater;
381 ///
382 /// let mut inflater = Inflater::new();
383 /// let mut out = Vec::new();
384 /// inflater.finish_vec(&[0xCB, 0x48, 0xCD, 0xC9, 0xC9, 0x07, 0x00], &mut out)?;
385 /// inflater.wipe();
386 /// assert_eq!(inflater.total_out(), 0);
387 /// # Ok::<(), compress_lib::Error>(())
388 /// ```
389 pub fn wipe(&mut self) {
390 crate::wipe_vec(&mut self.ring);
391 *self.tables = Tables::new();
392 core::hint::black_box(&*self.tables);
393 self.pending_len = 0;
394 self.pending_dist = 0;
395 self.reset();
396 }
397
398 /// After `Done`, starts a new DEFLATE stream that keeps the window, so
399 /// the next stream may refer back into this one. This is RFC 7692 context
400 /// takeover after a message that ended with a final block.
401 ///
402 /// # Errors
403 ///
404 /// [`ErrorKind::InvalidState`] before the current stream is done.
405 ///
406 /// # Examples
407 ///
408 /// ```
409 /// use compress_lib::deflate::Inflater;
410 ///
411 /// let mut inflater = Inflater::new();
412 /// let mut out = Vec::new();
413 /// inflater.finish_vec(&[0x03, 0x00], &mut out)?;
414 /// inflater.next_stream()?;
415 /// inflater.finish_vec(&[0x03, 0x00], &mut out)?;
416 /// # Ok::<(), compress_lib::Error>(())
417 /// ```
418 pub fn next_stream(&mut self) -> Result<(), Error> {
419 if self.state != State::Done {
420 return Err(Error::config(ErrorKind::InvalidState));
421 }
422 self.state = State::Header;
423 self.final_block = false;
424 self.bitbuf = 0;
425 self.bitcnt = 0;
426 Ok(())
427 }
428
429 /// Presets the history with `dictionary` (its last `2^window_bits`
430 /// bytes), for streams compressed with the same preset dictionary. Only
431 /// before any input.
432 ///
433 /// # Errors
434 ///
435 /// [`ErrorKind::InvalidState`] after input has been given.
436 ///
437 /// # Examples
438 ///
439 /// ```
440 /// use compress_lib::deflate::Inflater;
441 ///
442 /// let mut inflater = Inflater::new();
443 /// inflater.set_dictionary(b"common prefix")?;
444 /// # Ok::<(), compress_lib::Error>(())
445 /// ```
446 pub fn set_dictionary(&mut self, dictionary: &[u8]) -> Result<(), Error> {
447 if self.total_in != 0 || self.state != State::Header || self.failed.is_some() {
448 return Err(Error::config(ErrorKind::InvalidState));
449 }
450 if self.ring.is_empty() {
451 self.ring = alloc::vec![0; 1 << self.window_bits];
452 self.keep_history = true;
453 }
454 self.save_history(dictionary);
455 Ok(())
456 }
457
458 /// Decompresses as much of `input` into `output` as fits. More input may
459 /// follow in later calls.
460 ///
461 /// Returns how much input was consumed, how much output was produced,
462 /// and the [`Status`]: `NeedsInput` (all input consumed, the stream goes
463 /// on), `NeedsOutput` (output is full; call again with more room and the
464 /// rest of the input), or `Done` (the final block ended; `consumed`
465 /// stops at the stream's last byte, so trailing data stays with the
466 /// caller).
467 ///
468 /// # Errors
469 ///
470 /// Any decoding error of [`ErrorKind`], or `OutputLimit` / `RatioLimit`
471 /// when a limit stops the stream. After an error every call returns the
472 /// same error until [`reset`](Inflater::reset).
473 ///
474 /// # Examples
475 ///
476 /// ```
477 /// use compress_lib::deflate::{Inflater, Status};
478 ///
479 /// let compressed = [0xCB, 0x48, 0xCD, 0xC9, 0xC9, 0x07, 0x00];
480 /// let mut inflater = Inflater::new();
481 /// let mut out = Vec::new();
482 /// let mut buf = [0u8; 2]; // tiny on purpose
483 /// let mut input = &compressed[..];
484 /// loop {
485 /// let p = inflater.decompress(input, &mut buf)?;
486 /// input = &input[p.consumed..];
487 /// out.extend_from_slice(&buf[..p.produced]);
488 /// if p.status == Status::Done {
489 /// break;
490 /// }
491 /// }
492 /// assert_eq!(out, b"hello");
493 /// # Ok::<(), compress_lib::Error>(())
494 /// ```
495 pub fn decompress(&mut self, input: &[u8], output: &mut [u8]) -> Result<Progress, Error> {
496 self.run_slice(input, output, false)
497 }
498
499 /// As [`decompress`](Inflater::decompress), with `input` the last of the
500 /// stream: if the stream is unfinished once input runs out, the result
501 /// is `UnexpectedEnd` (unless output was full first, which is
502 /// `NeedsOutput`).
503 ///
504 /// # Errors
505 ///
506 /// As `decompress`, plus [`ErrorKind::UnexpectedEnd`].
507 ///
508 /// # Examples
509 ///
510 /// ```
511 /// use compress_lib::{ErrorKind, deflate::Inflater};
512 ///
513 /// let truncated = [0xCB, 0x48, 0xCD];
514 /// let mut out = [0u8; 16];
515 /// let err = Inflater::new().finish(&truncated, &mut out).unwrap_err();
516 /// assert_eq!(err.kind(), ErrorKind::UnexpectedEnd);
517 /// ```
518 pub fn finish(&mut self, input: &[u8], output: &mut [u8]) -> Result<Progress, Error> {
519 self.run_slice(input, output, true)
520 }
521
522 /// Decompresses `input`, appending to `out`, growing it as needed but
523 /// never past the output cap. Growth doubles what this call has
524 /// produced (at least 64 KiB at a time), so peak memory is at most 1.5
525 /// times `max_output` while a reallocation holds the old buffer and the
526 /// new one. Returns `NeedsInput` or `Done`.
527 ///
528 /// # Errors
529 ///
530 /// As [`decompress`](Inflater::decompress), plus
531 /// [`ErrorKind::AllocationFailed`] when the vector cannot grow.
532 ///
533 /// # Examples
534 ///
535 /// ```
536 /// use compress_lib::deflate::{Inflater, Status};
537 ///
538 /// let mut out = Vec::new();
539 /// let p = Inflater::new().decompress_vec(&[0xCB, 0x48, 0xCD, 0xC9, 0xC9, 0x07, 0x00], &mut out)?;
540 /// assert_eq!(p.status, Status::Done);
541 /// assert_eq!(out, b"hello");
542 /// # Ok::<(), compress_lib::Error>(())
543 /// ```
544 pub fn decompress_vec(&mut self, input: &[u8], out: &mut Vec<u8>) -> Result<Progress, Error> {
545 self.run_vec(input, out, false)
546 }
547
548 /// As [`decompress_vec`](Inflater::decompress_vec), with `input` the last
549 /// of the stream: an unfinished stream is `UnexpectedEnd`.
550 ///
551 /// # Errors
552 ///
553 /// As `decompress_vec`, plus [`ErrorKind::UnexpectedEnd`].
554 ///
555 /// # Examples
556 ///
557 /// ```
558 /// use compress_lib::deflate::Inflater;
559 ///
560 /// let mut out = Vec::new();
561 /// Inflater::new().finish_vec(&[0x03, 0x00], &mut out)?;
562 /// assert!(out.is_empty());
563 /// # Ok::<(), compress_lib::Error>(())
564 /// ```
565 pub fn finish_vec(&mut self, input: &[u8], out: &mut Vec<u8>) -> Result<Progress, Error> {
566 self.run_vec(input, out, true)
567 }
568
569 fn run_slice(
570 &mut self,
571 input: &[u8],
572 output: &mut [u8],
573 last: bool,
574 ) -> Result<Progress, Error> {
575 let (consumed, produced, status) = self.run(input, output, 0, last)?;
576 if self.keep_history {
577 self.save_history(&output[..produced]);
578 }
579 Ok(Progress::new(consumed, produced, status))
580 }
581
582 fn run_vec(&mut self, input: &[u8], out: &mut Vec<u8>, last: bool) -> Result<Progress, Error> {
583 let start = out.len();
584 let p = self.run_vec_from(input, out, start, last)?;
585 if self.keep_history {
586 self.save_history(&out[start..]);
587 }
588 Ok(p)
589 }
590
591 /// Decodes into `out`, treating `out[history_start..]` as this stream's
592 /// output so far (it is the history for back-references). The ring is
593 /// not updated; the caller records the history when it is done with it.
594 pub(crate) fn decompress_into(
595 &mut self,
596 input: &[u8],
597 out: &mut Vec<u8>,
598 history_start: usize,
599 last: bool,
600 ) -> Result<Progress, Error> {
601 self.run_vec_from(input, out, history_start, last)
602 }
603
604 /// Whether the decoder is waiting for a block header at a byte boundary,
605 /// with no bits left over: where a sync-flushed message must end.
606 pub(crate) fn at_block_boundary(&self) -> bool {
607 self.state == State::Header && self.bitcnt == 0
608 }
609
610 /// Records `data` as the newest history (when a window is kept).
611 pub(crate) fn remember(&mut self, data: &[u8]) {
612 if self.keep_history {
613 self.save_history(data);
614 }
615 }
616
617 /// Replaces the output cap.
618 pub(crate) fn set_max_output(&mut self, max: u64) {
619 self.limits = self.limits.with_max_output(max);
620 }
621
622 fn run_vec_from(
623 &mut self,
624 input: &[u8],
625 out: &mut Vec<u8>,
626 start: usize,
627 last: bool,
628 ) -> Result<Progress, Error> {
629 let first = out.len();
630 let mut consumed = 0;
631 // Room offered per step: a first guess from this call's input (four
632 // times it, 256 B to 64 KiB), doubling only after the step filled
633 // up, never past the cap. Each call zero-fills O(input + output)
634 // bytes, never the stream's earlier output (T-16).
635 let mut step = input.len().saturating_mul(4).clamp(256, VEC_CHUNK);
636 let status = loop {
637 let have = out.len();
638 let made = have - start;
639 let cap_room = usize::try_from(self.limits.max_output().saturating_sub(self.total_out))
640 .unwrap_or(usize::MAX);
641 let want = cap_room.min(step);
642 if out.capacity() - have < want {
643 // Grow the vector geometrically (as `Vec` does) so that many
644 // small calls reallocate O(log n) times, but never past what
645 // the cap still allows this stream to produce. Once the next
646 // doubling would pass the cap, go straight to it: a last
647 // small step would hold two buffers near the cap at once
648 // (T-1).
649 let limit = have.saturating_add(cap_room);
650 let mut target = (have + want).max(out.capacity().saturating_mul(2));
651 if target.saturating_mul(2) > limit {
652 target = limit;
653 }
654 if out.try_reserve_exact(target - have).is_err() {
655 return Err(self.fail(ErrorKind::AllocationFailed, 0));
656 }
657 }
658 #[cfg(test)]
659 tests::count_zero_fill(want);
660 out.resize(have + want, 0);
661 match self.run(&input[consumed..], &mut out[start..], made, last) {
662 Ok((c, p, status)) => {
663 out.truncate(have + p);
664 consumed += c;
665 if status != Status::NeedsOutput {
666 break status;
667 }
668 step = step.saturating_mul(2);
669 }
670 Err(e) => {
671 out.truncate(have);
672 return Err(e);
673 }
674 }
675 };
676 Ok(Progress::new(consumed, out.len() - first, status))
677 }
678
679 /// Records `newest` (this call's output) in the history ring.
680 fn save_history(&mut self, newest: &[u8]) {
681 let size = self.ring.len();
682 if size == 0 || newest.is_empty() {
683 return;
684 }
685 if newest.len() >= size {
686 self.ring.copy_from_slice(&newest[newest.len() - size..]);
687 self.wpos = 0;
688 self.whave = size;
689 return;
690 }
691 let first = (size - self.wpos).min(newest.len());
692 self.ring[self.wpos..self.wpos + first].copy_from_slice(&newest[..first]);
693 let rest = newest.len() - first;
694 self.ring[..rest].copy_from_slice(&newest[first..]);
695 self.wpos = (self.wpos + newest.len()) & (size - 1);
696 self.whave = (self.whave + newest.len()).min(size);
697 }
698
699 /// Marks the inflater failed with `kind` at the current input position.
700 fn fail(&mut self, kind: ErrorKind, ip: usize) -> Error {
701 let offset = (self.total_in + ip as u64).saturating_sub(u64::from(self.bitcnt / 8));
702 let e = Error::new(kind, offset);
703 self.failed = Some(e);
704 e
705 }
706
707 /// Decodes into `buf[op_start..]`, with `buf[..op_start]` already-valid
708 /// output of this stream (history). Returns (consumed, produced, status).
709 fn run(
710 &mut self,
711 input: &[u8],
712 buf: &mut [u8],
713 op_start: usize,
714 last: bool,
715 ) -> Result<(usize, usize, Status), Error> {
716 if let Some(e) = self.failed {
717 return Err(e);
718 }
719 let mut ip = 0;
720 let mut op = op_start;
721 let stop = loop {
722 let cap_room = self
723 .limits
724 .max_output()
725 .saturating_sub(self.total_out + (op - op_start) as u64);
726 let cap_end = op
727 + usize::try_from(cap_room)
728 .unwrap_or(usize::MAX)
729 .min(buf.len() - op);
730 let mut end = cap_end;
731 if self.limits.max_ratio() != 0 {
732 let taken = self.total_in + ip as u64;
733 let allowed = taken
734 .saturating_mul(u64::from(self.limits.max_ratio()))
735 .max(self.limits.ratio_floor());
736 let ratio_room = allowed.saturating_sub(self.total_out + (op - op_start) as u64);
737 end = end.min(op + usize::try_from(ratio_room).unwrap_or(usize::MAX));
738 }
739 let before = (ip, op);
740 let stop = match self.step(input, &mut ip, buf, &mut op, end) {
741 Ok(stop) => stop,
742 Err(kind) => {
743 self.total_out += (op - op_start) as u64;
744 return Err(self.fail(kind, ip));
745 }
746 };
747 if stop != Stop::NeedOutput {
748 break stop;
749 }
750 // More output is pending: past the cap that is the end, whatever
751 // room the caller gave.
752 if op == cap_end && cap_room == (op - before.1) as u64 {
753 self.total_out += (op - op_start) as u64;
754 return Err(self.fail(ErrorKind::OutputLimit, ip));
755 }
756 if op == buf.len() {
757 break stop;
758 }
759 // Stopped at the ratio bound. More input taken since raises it;
760 // if nothing moved, the ratio is exceeded.
761 if (ip, op) == before && op == end {
762 self.total_out += (op - op_start) as u64;
763 return Err(self.fail(ErrorKind::RatioLimit, ip));
764 }
765 };
766
767 let produced = op - op_start;
768 self.total_out += produced as u64;
769 if stop == Stop::NeedInput && last {
770 self.total_in += ip as u64;
771 return Err(self.fail(ErrorKind::UnexpectedEnd, 0));
772 }
773 // Give back whole bytes the bit buffer read ahead, so `consumed`
774 // stops at the last bit used (after `Done`, trailing data stays with
775 // the caller). On `NeedsInput` every buffered bit belongs to the
776 // pending symbol, and all input counts as consumed.
777 if stop != Stop::NeedInput {
778 let give = ((self.bitcnt / 8) as usize).min(ip);
779 ip -= give;
780 self.bitcnt -= 8 * give as u32;
781 }
782 self.bitbuf &= (1u64 << self.bitcnt) - 1;
783 if stop == Stop::Done {
784 self.bitbuf = 0;
785 self.bitcnt = 0;
786 }
787 self.total_in += ip as u64;
788 let status = match stop {
789 Stop::Done => Status::Done,
790 Stop::NeedInput => Status::NeedsInput,
791 Stop::NeedOutput => Status::NeedsOutput,
792 };
793 Ok((ip, produced, status))
794 }
795
796 /// Pulls bytes into the bit buffer until it holds `n` bits. `false` when
797 /// input runs out first.
798 #[inline]
799 fn need(&mut self, n: u32, input: &[u8], ip: &mut usize) -> bool {
800 while self.bitcnt < n {
801 if *ip >= input.len() {
802 return false;
803 }
804 self.bitbuf |= u64::from(input[*ip]) << self.bitcnt;
805 self.bitcnt += 8;
806 *ip += 1;
807 }
808 true
809 }
810
811 #[inline]
812 fn bits(&self, n: u32) -> u32 {
813 (self.bitbuf & ((1u64 << n) - 1)) as u32
814 }
815
816 #[inline]
817 fn consume(&mut self, n: u32) {
818 self.bitbuf >>= n;
819 self.bitcnt -= n;
820 }
821
822 /// Looks up the next symbol in `table`, pulling bytes one at a time
823 /// until the entry's bits are buffered. Returns the entry with the bits
824 /// to consume, or `None` when input runs out first (nothing consumed).
825 fn peek(&mut self, table: Which, input: &[u8], ip: &mut usize) -> Option<(u32, u32)> {
826 loop {
827 let (t, root): (&[u32], u32) = match table {
828 Which::Lit if self.fixed => (&FIXED_LIT, LIT_ROOT),
829 Which::Lit => (&self.tables.lit, LIT_ROOT),
830 Which::Dist if self.fixed => (&FIXED_DIST, DIST_ROOT),
831 Which::Dist => (&self.tables.dist, DIST_ROOT),
832 Which::Pre => (&self.tables.pre, PRE_ROOT),
833 };
834 let mut e = t[(self.bitbuf & ((1u64 << root) - 1)) as usize];
835 let mut skip = 0;
836 if e & SUBTABLE != 0 {
837 let bits = (e >> 8) & 0xF;
838 let index = ((self.bitbuf >> root) & ((1u64 << bits) - 1)) as usize;
839 e = t[(e >> 16) as usize + index];
840 skip = root;
841 }
842 let needed = skip + (e & 0xFF);
843 if self.bitcnt >= needed {
844 return Some((e, skip));
845 }
846 if *ip >= input.len() {
847 return None;
848 }
849 self.bitbuf |= u64::from(input[*ip]) << self.bitcnt;
850 self.bitcnt += 8;
851 *ip += 1;
852 }
853 }
854
855 /// The state that follows the end of a block.
856 fn end_block(&mut self) -> State {
857 if self.final_block {
858 State::Done
859 } else {
860 State::Header
861 }
862 }
863
864 /// Checks a distance against the window and the history available with
865 /// `in_buf` bytes of this stream's output before the write position.
866 #[inline]
867 fn check_distance(&self, dist: usize, in_buf: usize) -> Result<(), ErrorKind> {
868 if dist > (1usize << self.window_bits) || (dist > in_buf && dist - in_buf > self.whave) {
869 Err(ErrorKind::DistanceTooFar)
870 } else {
871 Ok(())
872 }
873 }
874
875 /// Copies `n` bytes of a match at `dist` to `buf[op..]`; the part before
876 /// `buf[0]` comes from the history ring. The distance was checked.
877 fn copy_match(&self, buf: &mut [u8], op: usize, dist: usize, n: usize) {
878 if dist <= op {
879 copy_forward(buf, op - dist, op, n);
880 return;
881 }
882 let back = dist - op;
883 let from_ring = back.min(n);
884 let size = self.ring.len();
885 let mut r = (self.wpos + size - back) & (size - 1);
886 let mut o = op;
887 let mut left = from_ring;
888 while left > 0 {
889 let run = left.min(size - r);
890 buf[o..o + run].copy_from_slice(&self.ring[r..r + run]);
891 o += run;
892 left -= run;
893 r = (r + run) & (size - 1);
894 }
895 if n > from_ring {
896 // The rest of the match starts at buf[0].
897 copy_forward(buf, 0, o, n - from_ring);
898 }
899 }
900
901 /// Runs the state machine until it stops for input, output, or the end.
902 fn step(
903 &mut self,
904 input: &[u8],
905 ip: &mut usize,
906 buf: &mut [u8],
907 op: &mut usize,
908 end: usize,
909 ) -> Result<Stop, ErrorKind> {
910 loop {
911 match self.state {
912 State::Header => {
913 if !self.need(3, input, ip) {
914 return Ok(Stop::NeedInput);
915 }
916 self.final_block = self.bits(1) == 1;
917 let kind = (self.bitbuf >> 1) & 3;
918 self.consume(3);
919 self.state = match kind {
920 0 => State::StoredLength,
921 1 => {
922 self.fixed = true;
923 State::Data
924 }
925 2 => State::Counts,
926 _ => return Err(ErrorKind::InvalidBlockType),
927 };
928 }
929 State::StoredLength => {
930 let pad = self.bitcnt % 8;
931 self.consume(pad);
932 if !self.need(32, input, ip) {
933 return Ok(Stop::NeedInput);
934 }
935 let len = self.bits(16);
936 let nlen = (self.bitbuf >> 16) as u32 & 0xFFFF;
937 if len != !nlen & 0xFFFF {
938 return Err(ErrorKind::InvalidStoredLength);
939 }
940 self.consume(32);
941 self.stored_left = len;
942 self.state = State::Stored;
943 }
944 State::Stored => {
945 while self.stored_left > 0 {
946 if *op >= end {
947 return Ok(Stop::NeedOutput);
948 }
949 if self.bitcnt >= 8 {
950 buf[*op] = self.bits(8) as u8;
951 self.consume(8);
952 *op += 1;
953 self.stored_left -= 1;
954 } else if *ip < input.len() {
955 let n = (self.stored_left as usize)
956 .min(input.len() - *ip)
957 .min(end - *op);
958 buf[*op..*op + n].copy_from_slice(&input[*ip..*ip + n]);
959 *op += n;
960 *ip += n;
961 self.stored_left -= n as u32;
962 } else {
963 return Ok(Stop::NeedInput);
964 }
965 }
966 self.state = self.end_block();
967 }
968 State::Counts => {
969 if !self.need(14, input, ip) {
970 return Ok(Stop::NeedInput);
971 }
972 self.hlit = self.bits(5) as u16 + 257;
973 self.hdist = (self.bitbuf >> 5) as u16 & 0x1F;
974 self.hdist += 1;
975 self.hclen = (self.bitbuf >> 10) as u16 & 0xF;
976 self.hclen += 4;
977 self.consume(14);
978 if self.hlit > 286 || self.hdist > 30 {
979 return Err(ErrorKind::InvalidCodeLengths);
980 }
981 self.tables.lens[..19].fill(0);
982 self.index = 0;
983 self.state = State::PrecodeLengths;
984 }
985 State::PrecodeLengths => {
986 while self.index < self.hclen {
987 if !self.need(3, input, ip) {
988 return Ok(Stop::NeedInput);
989 }
990 let slot = PRECODE_ORDER[self.index as usize] as usize;
991 self.tables.lens[slot] = self.bits(3) as u8;
992 self.consume(3);
993 self.index += 1;
994 }
995 let t = &mut *self.tables;
996 tables::build(
997 &t.lens[..19],
998 &mut t.pre,
999 PRE_ROOT,
1000 Alphabet::Precode,
1001 false,
1002 )?;
1003 self.index = 0;
1004 self.state = State::CodeLengths;
1005 }
1006 State::CodeLengths => {
1007 let total = self.hlit + self.hdist;
1008 while self.index < total {
1009 let Some((e, _)) = self.peek(Which::Pre, input, ip) else {
1010 return Ok(Stop::NeedInput);
1011 };
1012 let symbol = e >> 16;
1013 let len = e & 0xFF;
1014 if symbol < 16 {
1015 self.consume(len);
1016 self.tables.lens[self.index as usize] = symbol as u8;
1017 self.index += 1;
1018 continue;
1019 }
1020 let (extra, base) = match symbol {
1021 16 => (2, 3),
1022 17 => (3, 3),
1023 _ => (7, 11),
1024 };
1025 if !self.need(len + extra, input, ip) {
1026 return Ok(Stop::NeedInput);
1027 }
1028 let repeat = base + ((self.bitbuf >> len) as u32 & ((1 << extra) - 1));
1029 let value = if symbol == 16 {
1030 if self.index == 0 {
1031 return Err(ErrorKind::InvalidCodeLengths);
1032 }
1033 self.tables.lens[self.index as usize - 1]
1034 } else {
1035 0
1036 };
1037 if u32::from(self.index) + repeat > u32::from(total) {
1038 return Err(ErrorKind::InvalidCodeLengths);
1039 }
1040 self.consume(len + extra);
1041 let i = self.index as usize;
1042 self.tables.lens[i..i + repeat as usize].fill(value);
1043 self.index += repeat as u16;
1044 }
1045 let (hlit, hdist) = (self.hlit as usize, self.hdist as usize);
1046 let t = &mut *self.tables;
1047 if t.lens[256] == 0 {
1048 return Err(ErrorKind::InvalidCodeLengths);
1049 }
1050 tables::build(
1051 &t.lens[..hlit],
1052 &mut t.lit,
1053 LIT_ROOT,
1054 Alphabet::LitLen,
1055 true,
1056 )?;
1057 tables::build(
1058 &t.lens[hlit..hlit + hdist],
1059 &mut t.dist,
1060 DIST_ROOT,
1061 Alphabet::Dist,
1062 true,
1063 )?;
1064 self.fixed = false;
1065 self.state = State::Data;
1066 }
1067 State::Data => {
1068 if input.len() - *ip >= FAST_IN && end - *op >= FAST_OUT {
1069 self.fast(input, ip, buf, op, end)?;
1070 continue;
1071 }
1072 let Some((e, skip)) = self.peek(Which::Lit, input, ip) else {
1073 return Ok(Stop::NeedInput);
1074 };
1075 if e & LITERAL != 0 {
1076 if *op >= end {
1077 return Ok(Stop::NeedOutput);
1078 }
1079 self.consume(skip + (e & 0xFF));
1080 buf[*op] = (e >> 16) as u8;
1081 *op += 1;
1082 } else if e & END_OF_BLOCK != 0 {
1083 self.consume(skip + (e & 0xFF));
1084 self.state = self.end_block();
1085 } else if e & INVALID != 0 {
1086 return Err(ErrorKind::InvalidSymbol);
1087 } else {
1088 let code = skip + ((e >> 8) & 0xF);
1089 let extra = (e & 0xFF) - ((e >> 8) & 0xF);
1090 let value = (self.bitbuf >> code) as u32 & ((1 << extra) - 1);
1091 self.consume(skip + (e & 0xFF));
1092 self.pending_len = (e >> 16) + value;
1093 self.state = State::Distance;
1094 }
1095 }
1096 State::Distance => {
1097 let Some((e, skip)) = self.peek(Which::Dist, input, ip) else {
1098 return Ok(Stop::NeedInput);
1099 };
1100 if e & INVALID != 0 {
1101 return Err(ErrorKind::InvalidSymbol);
1102 }
1103 let code = skip + ((e >> 8) & 0xF);
1104 let extra = (e & 0xFF) - ((e >> 8) & 0xF);
1105 let value = (self.bitbuf >> code) as u32 & ((1 << extra) - 1);
1106 let dist = (e >> 16) + value;
1107 self.check_distance(dist as usize, *op)?;
1108 self.consume(skip + (e & 0xFF));
1109 self.pending_dist = dist;
1110 self.state = State::Copy;
1111 }
1112 State::Copy => {
1113 let n = (self.pending_len as usize).min(end - *op);
1114 if n > 0 {
1115 self.copy_match(buf, *op, self.pending_dist as usize, n);
1116 *op += n;
1117 self.pending_len -= n as u32;
1118 }
1119 if self.pending_len > 0 {
1120 return Ok(Stop::NeedOutput);
1121 }
1122 self.state = State::Data;
1123 }
1124 State::Done => return Ok(Stop::Done),
1125 }
1126 }
1127 }
1128
1129 /// The fast loop: decodes symbols while at least `FAST_IN` input bytes
1130 /// and `FAST_OUT` output bytes remain, with one eight-byte refill per
1131 /// symbol and no state saved between symbols. Returns at the end of the
1132 /// block or when the margins run out; the slow path does the rest.
1133 fn fast(
1134 &mut self,
1135 input: &[u8],
1136 ip: &mut usize,
1137 buf: &mut [u8],
1138 op: &mut usize,
1139 end: usize,
1140 ) -> Result<(), ErrorKind> {
1141 let (lit, dist): (&[u32], &[u32]) = if self.fixed {
1142 (&FIXED_LIT, &FIXED_DIST)
1143 } else {
1144 (&self.tables.lit, &self.tables.dist)
1145 };
1146 let window = 1usize << self.window_bits;
1147 let mut bitbuf = self.bitbuf;
1148 let mut bitcnt = self.bitcnt;
1149 let mut i = *ip;
1150 let mut o = *op;
1151 let result = loop {
1152 if input.len() - i < FAST_IN || end - o < FAST_OUT {
1153 break Ok(());
1154 }
1155 let mut word = [0u8; 8];
1156 word.copy_from_slice(&input[i..i + 8]);
1157 bitbuf |= u64::from_le_bytes(word) << bitcnt;
1158 i += ((63 - bitcnt) >> 3) as usize;
1159 bitcnt |= 56;
1160
1161 let mut e = lit[(bitbuf & ((1 << LIT_ROOT) - 1)) as usize];
1162 if e & SUBTABLE != 0 {
1163 bitbuf >>= LIT_ROOT;
1164 bitcnt -= LIT_ROOT;
1165 e = lit[(e >> 16) as usize + (bitbuf & ((1u64 << ((e >> 8) & 0xF)) - 1)) as usize];
1166 }
1167 if e & LITERAL != 0 {
1168 buf[o] = (e >> 16) as u8;
1169 o += 1;
1170 bitbuf >>= e & 0xFF;
1171 bitcnt -= e & 0xFF;
1172 // A second literal often fits in the same refill.
1173 let e2 = lit[(bitbuf & ((1 << LIT_ROOT) - 1)) as usize];
1174 if e2 & LITERAL != 0 && bitcnt >= (e2 & 0xFF) {
1175 buf[o] = (e2 >> 16) as u8;
1176 o += 1;
1177 bitbuf >>= e2 & 0xFF;
1178 bitcnt -= e2 & 0xFF;
1179 }
1180 continue;
1181 }
1182 if e & (END_OF_BLOCK | INVALID) != 0 {
1183 if e & END_OF_BLOCK != 0 {
1184 bitbuf >>= e & 0xFF;
1185 bitcnt -= e & 0xFF;
1186 self.state = if self.final_block {
1187 State::Done
1188 } else {
1189 State::Header
1190 };
1191 break Ok(());
1192 }
1193 break Err(ErrorKind::InvalidSymbol);
1194 }
1195 let code = (e >> 8) & 0xF;
1196 let length = (e >> 16) as usize
1197 + ((bitbuf >> code) & ((1u64 << ((e & 0xFF) - code)) - 1)) as usize;
1198 bitbuf >>= e & 0xFF;
1199 bitcnt -= e & 0xFF;
1200
1201 let mut d = dist[(bitbuf & ((1 << DIST_ROOT) - 1)) as usize];
1202 if d & SUBTABLE != 0 {
1203 bitbuf >>= DIST_ROOT;
1204 bitcnt -= DIST_ROOT;
1205 d = dist[(d >> 16) as usize + (bitbuf & ((1u64 << ((d >> 8) & 0xF)) - 1)) as usize];
1206 }
1207 if d & INVALID != 0 {
1208 break Err(ErrorKind::InvalidSymbol);
1209 }
1210 let code = (d >> 8) & 0xF;
1211 let distance = (d >> 16) as usize
1212 + ((bitbuf >> code) & ((1u64 << ((d & 0xFF) - code)) - 1)) as usize;
1213 bitbuf >>= d & 0xFF;
1214 bitcnt -= d & 0xFF;
1215
1216 if distance > window || (distance > o && distance - o > self.whave) {
1217 break Err(ErrorKind::DistanceTooFar);
1218 }
1219 if distance <= o && distance >= 8 {
1220 // Eight bytes at a time; the source is always written before
1221 // it is read because the distance is at least eight, and the
1222 // over-copy stays inside the FAST_OUT margin.
1223 let mut s = o - distance;
1224 let stop = o + length;
1225 while o < stop {
1226 buf.copy_within(s..s + 8, o);
1227 s += 8;
1228 o += 8;
1229 }
1230 o = stop;
1231 } else {
1232 self.copy_match(buf, o, distance, length);
1233 o += length;
1234 }
1235 };
1236 // The refill leaves read-ahead bits above `bitcnt`; the slow path
1237 // needs them clear.
1238 self.bitbuf = bitbuf & ((1u64 << bitcnt) - 1);
1239 self.bitcnt = bitcnt;
1240 *ip = i;
1241 *op = o;
1242 result
1243 }
1244}
1245
1246/// Which table `peek` reads.
1247#[derive(Clone, Copy)]
1248enum Which {
1249 Lit,
1250 Dist,
1251 Pre,
1252}
1253
1254#[cfg(test)]
1255mod tests;