Skip to main content

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: a first guess from the input (four times
601            // it, at most 64 KiB), then doubling what this stream has
602            // produced, never past the cap. Small messages stay small.
603            let guess = (input.len() - consumed)
604                .saturating_mul(4)
605                .clamp(256, VEC_CHUNK);
606            let want = cap_room.min(made.max(guess));
607            if out.capacity() - have < want && out.try_reserve_exact(want).is_err() {
608                return Err(self.fail(ErrorKind::AllocationFailed, 0));
609            }
610            let room = (out.capacity() - have).min(want);
611            out.resize(have + room, 0);
612            match self.run(&input[consumed..], &mut out[start..], made, last) {
613                Ok((c, p, status)) => {
614                    out.truncate(have + p);
615                    consumed += c;
616                    if status != Status::NeedsOutput {
617                        break status;
618                    }
619                }
620                Err(e) => {
621                    out.truncate(have);
622                    return Err(e);
623                }
624            }
625        };
626        Ok(Progress::new(consumed, out.len() - first, status))
627    }
628
629    /// Records `newest` (this call's output) in the history ring.
630    fn save_history(&mut self, newest: &[u8]) {
631        let size = self.ring.len();
632        if size == 0 || newest.is_empty() {
633            return;
634        }
635        if newest.len() >= size {
636            self.ring.copy_from_slice(&newest[newest.len() - size..]);
637            self.wpos = 0;
638            self.whave = size;
639            return;
640        }
641        let first = (size - self.wpos).min(newest.len());
642        self.ring[self.wpos..self.wpos + first].copy_from_slice(&newest[..first]);
643        let rest = newest.len() - first;
644        self.ring[..rest].copy_from_slice(&newest[first..]);
645        self.wpos = (self.wpos + newest.len()) & (size - 1);
646        self.whave = (self.whave + newest.len()).min(size);
647    }
648
649    /// Marks the inflater failed with `kind` at the current input position.
650    fn fail(&mut self, kind: ErrorKind, ip: usize) -> Error {
651        let offset = (self.total_in + ip as u64).saturating_sub(u64::from(self.bitcnt / 8));
652        let e = Error::new(kind, offset);
653        self.failed = Some(e);
654        e
655    }
656
657    /// Decodes into `buf[op_start..]`, with `buf[..op_start]` already-valid
658    /// output of this stream (history). Returns (consumed, produced, status).
659    fn run(
660        &mut self,
661        input: &[u8],
662        buf: &mut [u8],
663        op_start: usize,
664        last: bool,
665    ) -> Result<(usize, usize, Status), Error> {
666        if let Some(e) = self.failed {
667            return Err(e);
668        }
669        let mut ip = 0;
670        let mut op = op_start;
671        let stop = loop {
672            let cap_room = self
673                .limits
674                .max_output()
675                .saturating_sub(self.total_out + (op - op_start) as u64);
676            let cap_end = op
677                + usize::try_from(cap_room)
678                    .unwrap_or(usize::MAX)
679                    .min(buf.len() - op);
680            let mut end = cap_end;
681            if self.limits.max_ratio() != 0 {
682                let taken = self.total_in + ip as u64;
683                let allowed = taken
684                    .saturating_mul(u64::from(self.limits.max_ratio()))
685                    .max(self.limits.ratio_floor());
686                let ratio_room = allowed.saturating_sub(self.total_out + (op - op_start) as u64);
687                end = end.min(op + usize::try_from(ratio_room).unwrap_or(usize::MAX));
688            }
689            let before = (ip, op);
690            let stop = match self.step(input, &mut ip, buf, &mut op, end) {
691                Ok(stop) => stop,
692                Err(kind) => {
693                    self.total_out += (op - op_start) as u64;
694                    return Err(self.fail(kind, ip));
695                }
696            };
697            if stop != Stop::NeedOutput {
698                break stop;
699            }
700            // More output is pending: past the cap that is the end, whatever
701            // room the caller gave.
702            if op == cap_end && cap_room == (op - before.1) as u64 {
703                self.total_out += (op - op_start) as u64;
704                return Err(self.fail(ErrorKind::OutputLimit, ip));
705            }
706            if op == buf.len() {
707                break stop;
708            }
709            // Stopped at the ratio bound. More input taken since raises it;
710            // if nothing moved, the ratio is exceeded.
711            if (ip, op) == before && op == end {
712                self.total_out += (op - op_start) as u64;
713                return Err(self.fail(ErrorKind::RatioLimit, ip));
714            }
715        };
716
717        let produced = op - op_start;
718        self.total_out += produced as u64;
719        if stop == Stop::NeedInput && last {
720            self.total_in += ip as u64;
721            return Err(self.fail(ErrorKind::UnexpectedEnd, 0));
722        }
723        // Give back whole bytes the bit buffer read ahead, so `consumed`
724        // stops at the last bit used (after `Done`, trailing data stays with
725        // the caller). On `NeedsInput` every buffered bit belongs to the
726        // pending symbol, and all input counts as consumed.
727        if stop != Stop::NeedInput {
728            let give = ((self.bitcnt / 8) as usize).min(ip);
729            ip -= give;
730            self.bitcnt -= 8 * give as u32;
731        }
732        self.bitbuf &= (1u64 << self.bitcnt) - 1;
733        if stop == Stop::Done {
734            self.bitbuf = 0;
735            self.bitcnt = 0;
736        }
737        self.total_in += ip as u64;
738        let status = match stop {
739            Stop::Done => Status::Done,
740            Stop::NeedInput => Status::NeedsInput,
741            Stop::NeedOutput => Status::NeedsOutput,
742        };
743        Ok((ip, produced, status))
744    }
745
746    /// Pulls bytes into the bit buffer until it holds `n` bits. `false` when
747    /// input runs out first.
748    #[inline]
749    fn need(&mut self, n: u32, input: &[u8], ip: &mut usize) -> bool {
750        while self.bitcnt < n {
751            if *ip >= input.len() {
752                return false;
753            }
754            self.bitbuf |= u64::from(input[*ip]) << self.bitcnt;
755            self.bitcnt += 8;
756            *ip += 1;
757        }
758        true
759    }
760
761    #[inline]
762    fn bits(&self, n: u32) -> u32 {
763        (self.bitbuf & ((1u64 << n) - 1)) as u32
764    }
765
766    #[inline]
767    fn consume(&mut self, n: u32) {
768        self.bitbuf >>= n;
769        self.bitcnt -= n;
770    }
771
772    /// Looks up the next symbol in `table`, pulling bytes one at a time
773    /// until the entry's bits are buffered. Returns the entry with the bits
774    /// to consume, or `None` when input runs out first (nothing consumed).
775    fn peek(&mut self, table: Which, input: &[u8], ip: &mut usize) -> Option<(u32, u32)> {
776        loop {
777            let (t, root): (&[u32], u32) = match table {
778                Which::Lit if self.fixed => (&FIXED_LIT, LIT_ROOT),
779                Which::Lit => (&self.tables.lit, LIT_ROOT),
780                Which::Dist if self.fixed => (&FIXED_DIST, DIST_ROOT),
781                Which::Dist => (&self.tables.dist, DIST_ROOT),
782                Which::Pre => (&self.tables.pre, PRE_ROOT),
783            };
784            let mut e = t[(self.bitbuf & ((1u64 << root) - 1)) as usize];
785            let mut skip = 0;
786            if e & SUBTABLE != 0 {
787                let bits = (e >> 8) & 0xF;
788                let index = ((self.bitbuf >> root) & ((1u64 << bits) - 1)) as usize;
789                e = t[(e >> 16) as usize + index];
790                skip = root;
791            }
792            let needed = skip + (e & 0xFF);
793            if self.bitcnt >= needed {
794                return Some((e, skip));
795            }
796            if *ip >= input.len() {
797                return None;
798            }
799            self.bitbuf |= u64::from(input[*ip]) << self.bitcnt;
800            self.bitcnt += 8;
801            *ip += 1;
802        }
803    }
804
805    /// The state that follows the end of a block.
806    fn end_block(&mut self) -> State {
807        if self.final_block {
808            State::Done
809        } else {
810            State::Header
811        }
812    }
813
814    /// Checks a distance against the window and the history available with
815    /// `in_buf` bytes of this stream's output before the write position.
816    #[inline]
817    fn check_distance(&self, dist: usize, in_buf: usize) -> Result<(), ErrorKind> {
818        if dist > (1usize << self.window_bits) || (dist > in_buf && dist - in_buf > self.whave) {
819            Err(ErrorKind::DistanceTooFar)
820        } else {
821            Ok(())
822        }
823    }
824
825    /// Copies `n` bytes of a match at `dist` to `buf[op..]`; the part before
826    /// `buf[0]` comes from the history ring. The distance was checked.
827    fn copy_match(&self, buf: &mut [u8], op: usize, dist: usize, n: usize) {
828        if dist <= op {
829            copy_forward(buf, op - dist, op, n);
830            return;
831        }
832        let back = dist - op;
833        let from_ring = back.min(n);
834        let size = self.ring.len();
835        let mut r = (self.wpos + size - back) & (size - 1);
836        let mut o = op;
837        let mut left = from_ring;
838        while left > 0 {
839            let run = left.min(size - r);
840            buf[o..o + run].copy_from_slice(&self.ring[r..r + run]);
841            o += run;
842            left -= run;
843            r = (r + run) & (size - 1);
844        }
845        if n > from_ring {
846            // The rest of the match starts at buf[0].
847            copy_forward(buf, 0, o, n - from_ring);
848        }
849    }
850
851    /// Runs the state machine until it stops for input, output, or the end.
852    fn step(
853        &mut self,
854        input: &[u8],
855        ip: &mut usize,
856        buf: &mut [u8],
857        op: &mut usize,
858        end: usize,
859    ) -> Result<Stop, ErrorKind> {
860        loop {
861            match self.state {
862                State::Header => {
863                    if !self.need(3, input, ip) {
864                        return Ok(Stop::NeedInput);
865                    }
866                    self.final_block = self.bits(1) == 1;
867                    let kind = (self.bitbuf >> 1) & 3;
868                    self.consume(3);
869                    self.state = match kind {
870                        0 => State::StoredLength,
871                        1 => {
872                            self.fixed = true;
873                            State::Data
874                        }
875                        2 => State::Counts,
876                        _ => return Err(ErrorKind::InvalidBlockType),
877                    };
878                }
879                State::StoredLength => {
880                    let pad = self.bitcnt % 8;
881                    self.consume(pad);
882                    if !self.need(32, input, ip) {
883                        return Ok(Stop::NeedInput);
884                    }
885                    let len = self.bits(16);
886                    let nlen = (self.bitbuf >> 16) as u32 & 0xFFFF;
887                    if len != !nlen & 0xFFFF {
888                        return Err(ErrorKind::InvalidStoredLength);
889                    }
890                    self.consume(32);
891                    self.stored_left = len;
892                    self.state = State::Stored;
893                }
894                State::Stored => {
895                    while self.stored_left > 0 {
896                        if *op >= end {
897                            return Ok(Stop::NeedOutput);
898                        }
899                        if self.bitcnt >= 8 {
900                            buf[*op] = self.bits(8) as u8;
901                            self.consume(8);
902                            *op += 1;
903                            self.stored_left -= 1;
904                        } else if *ip < input.len() {
905                            let n = (self.stored_left as usize)
906                                .min(input.len() - *ip)
907                                .min(end - *op);
908                            buf[*op..*op + n].copy_from_slice(&input[*ip..*ip + n]);
909                            *op += n;
910                            *ip += n;
911                            self.stored_left -= n as u32;
912                        } else {
913                            return Ok(Stop::NeedInput);
914                        }
915                    }
916                    self.state = self.end_block();
917                }
918                State::Counts => {
919                    if !self.need(14, input, ip) {
920                        return Ok(Stop::NeedInput);
921                    }
922                    self.hlit = self.bits(5) as u16 + 257;
923                    self.hdist = (self.bitbuf >> 5) as u16 & 0x1F;
924                    self.hdist += 1;
925                    self.hclen = (self.bitbuf >> 10) as u16 & 0xF;
926                    self.hclen += 4;
927                    self.consume(14);
928                    if self.hlit > 286 || self.hdist > 30 {
929                        return Err(ErrorKind::InvalidCodeLengths);
930                    }
931                    self.tables.lens[..19].fill(0);
932                    self.index = 0;
933                    self.state = State::PrecodeLengths;
934                }
935                State::PrecodeLengths => {
936                    while self.index < self.hclen {
937                        if !self.need(3, input, ip) {
938                            return Ok(Stop::NeedInput);
939                        }
940                        let slot = PRECODE_ORDER[self.index as usize] as usize;
941                        self.tables.lens[slot] = self.bits(3) as u8;
942                        self.consume(3);
943                        self.index += 1;
944                    }
945                    let t = &mut *self.tables;
946                    tables::build(
947                        &t.lens[..19],
948                        &mut t.pre,
949                        PRE_ROOT,
950                        Alphabet::Precode,
951                        false,
952                    )?;
953                    self.index = 0;
954                    self.state = State::CodeLengths;
955                }
956                State::CodeLengths => {
957                    let total = self.hlit + self.hdist;
958                    while self.index < total {
959                        let Some((e, _)) = self.peek(Which::Pre, input, ip) else {
960                            return Ok(Stop::NeedInput);
961                        };
962                        let symbol = e >> 16;
963                        let len = e & 0xFF;
964                        if symbol < 16 {
965                            self.consume(len);
966                            self.tables.lens[self.index as usize] = symbol as u8;
967                            self.index += 1;
968                            continue;
969                        }
970                        let (extra, base) = match symbol {
971                            16 => (2, 3),
972                            17 => (3, 3),
973                            _ => (7, 11),
974                        };
975                        if !self.need(len + extra, input, ip) {
976                            return Ok(Stop::NeedInput);
977                        }
978                        let repeat = base + ((self.bitbuf >> len) as u32 & ((1 << extra) - 1));
979                        let value = if symbol == 16 {
980                            if self.index == 0 {
981                                return Err(ErrorKind::InvalidCodeLengths);
982                            }
983                            self.tables.lens[self.index as usize - 1]
984                        } else {
985                            0
986                        };
987                        if u32::from(self.index) + repeat > u32::from(total) {
988                            return Err(ErrorKind::InvalidCodeLengths);
989                        }
990                        self.consume(len + extra);
991                        let i = self.index as usize;
992                        self.tables.lens[i..i + repeat as usize].fill(value);
993                        self.index += repeat as u16;
994                    }
995                    let (hlit, hdist) = (self.hlit as usize, self.hdist as usize);
996                    let t = &mut *self.tables;
997                    if t.lens[256] == 0 {
998                        return Err(ErrorKind::InvalidCodeLengths);
999                    }
1000                    tables::build(
1001                        &t.lens[..hlit],
1002                        &mut t.lit,
1003                        LIT_ROOT,
1004                        Alphabet::LitLen,
1005                        true,
1006                    )?;
1007                    tables::build(
1008                        &t.lens[hlit..hlit + hdist],
1009                        &mut t.dist,
1010                        DIST_ROOT,
1011                        Alphabet::Dist,
1012                        true,
1013                    )?;
1014                    self.fixed = false;
1015                    self.state = State::Data;
1016                }
1017                State::Data => {
1018                    if input.len() - *ip >= FAST_IN && end - *op >= FAST_OUT {
1019                        self.fast(input, ip, buf, op, end)?;
1020                        continue;
1021                    }
1022                    let Some((e, skip)) = self.peek(Which::Lit, input, ip) else {
1023                        return Ok(Stop::NeedInput);
1024                    };
1025                    if e & LITERAL != 0 {
1026                        if *op >= end {
1027                            return Ok(Stop::NeedOutput);
1028                        }
1029                        self.consume(skip + (e & 0xFF));
1030                        buf[*op] = (e >> 16) as u8;
1031                        *op += 1;
1032                    } else if e & END_OF_BLOCK != 0 {
1033                        self.consume(skip + (e & 0xFF));
1034                        self.state = self.end_block();
1035                    } else if e & INVALID != 0 {
1036                        return Err(ErrorKind::InvalidSymbol);
1037                    } else {
1038                        let code = skip + ((e >> 8) & 0xF);
1039                        let extra = (e & 0xFF) - ((e >> 8) & 0xF);
1040                        let value = (self.bitbuf >> code) as u32 & ((1 << extra) - 1);
1041                        self.consume(skip + (e & 0xFF));
1042                        self.pending_len = (e >> 16) + value;
1043                        self.state = State::Distance;
1044                    }
1045                }
1046                State::Distance => {
1047                    let Some((e, skip)) = self.peek(Which::Dist, input, ip) else {
1048                        return Ok(Stop::NeedInput);
1049                    };
1050                    if e & INVALID != 0 {
1051                        return Err(ErrorKind::InvalidSymbol);
1052                    }
1053                    let code = skip + ((e >> 8) & 0xF);
1054                    let extra = (e & 0xFF) - ((e >> 8) & 0xF);
1055                    let value = (self.bitbuf >> code) as u32 & ((1 << extra) - 1);
1056                    let dist = (e >> 16) + value;
1057                    self.check_distance(dist as usize, *op)?;
1058                    self.consume(skip + (e & 0xFF));
1059                    self.pending_dist = dist;
1060                    self.state = State::Copy;
1061                }
1062                State::Copy => {
1063                    let n = (self.pending_len as usize).min(end - *op);
1064                    if n > 0 {
1065                        self.copy_match(buf, *op, self.pending_dist as usize, n);
1066                        *op += n;
1067                        self.pending_len -= n as u32;
1068                    }
1069                    if self.pending_len > 0 {
1070                        return Ok(Stop::NeedOutput);
1071                    }
1072                    self.state = State::Data;
1073                }
1074                State::Done => return Ok(Stop::Done),
1075            }
1076        }
1077    }
1078
1079    /// The fast loop: decodes symbols while at least `FAST_IN` input bytes
1080    /// and `FAST_OUT` output bytes remain, with one eight-byte refill per
1081    /// symbol and no state saved between symbols. Returns at the end of the
1082    /// block or when the margins run out; the slow path does the rest.
1083    fn fast(
1084        &mut self,
1085        input: &[u8],
1086        ip: &mut usize,
1087        buf: &mut [u8],
1088        op: &mut usize,
1089        end: usize,
1090    ) -> Result<(), ErrorKind> {
1091        let (lit, dist): (&[u32], &[u32]) = if self.fixed {
1092            (&FIXED_LIT, &FIXED_DIST)
1093        } else {
1094            (&self.tables.lit, &self.tables.dist)
1095        };
1096        let window = 1usize << self.window_bits;
1097        let mut bitbuf = self.bitbuf;
1098        let mut bitcnt = self.bitcnt;
1099        let mut i = *ip;
1100        let mut o = *op;
1101        let result = loop {
1102            if input.len() - i < FAST_IN || end - o < FAST_OUT {
1103                break Ok(());
1104            }
1105            let mut word = [0u8; 8];
1106            word.copy_from_slice(&input[i..i + 8]);
1107            bitbuf |= u64::from_le_bytes(word) << bitcnt;
1108            i += ((63 - bitcnt) >> 3) as usize;
1109            bitcnt |= 56;
1110
1111            let mut e = lit[(bitbuf & ((1 << LIT_ROOT) - 1)) as usize];
1112            if e & SUBTABLE != 0 {
1113                bitbuf >>= LIT_ROOT;
1114                bitcnt -= LIT_ROOT;
1115                e = lit[(e >> 16) as usize + (bitbuf & ((1u64 << ((e >> 8) & 0xF)) - 1)) as usize];
1116            }
1117            if e & LITERAL != 0 {
1118                buf[o] = (e >> 16) as u8;
1119                o += 1;
1120                bitbuf >>= e & 0xFF;
1121                bitcnt -= e & 0xFF;
1122                // A second literal often fits in the same refill.
1123                let e2 = lit[(bitbuf & ((1 << LIT_ROOT) - 1)) as usize];
1124                if e2 & LITERAL != 0 && bitcnt >= (e2 & 0xFF) {
1125                    buf[o] = (e2 >> 16) as u8;
1126                    o += 1;
1127                    bitbuf >>= e2 & 0xFF;
1128                    bitcnt -= e2 & 0xFF;
1129                }
1130                continue;
1131            }
1132            if e & (END_OF_BLOCK | INVALID) != 0 {
1133                if e & END_OF_BLOCK != 0 {
1134                    bitbuf >>= e & 0xFF;
1135                    bitcnt -= e & 0xFF;
1136                    self.state = if self.final_block {
1137                        State::Done
1138                    } else {
1139                        State::Header
1140                    };
1141                    break Ok(());
1142                }
1143                break Err(ErrorKind::InvalidSymbol);
1144            }
1145            let code = (e >> 8) & 0xF;
1146            let length = (e >> 16) as usize
1147                + ((bitbuf >> code) & ((1u64 << ((e & 0xFF) - code)) - 1)) as usize;
1148            bitbuf >>= e & 0xFF;
1149            bitcnt -= e & 0xFF;
1150
1151            let mut d = dist[(bitbuf & ((1 << DIST_ROOT) - 1)) as usize];
1152            if d & SUBTABLE != 0 {
1153                bitbuf >>= DIST_ROOT;
1154                bitcnt -= DIST_ROOT;
1155                d = dist[(d >> 16) as usize + (bitbuf & ((1u64 << ((d >> 8) & 0xF)) - 1)) as usize];
1156            }
1157            if d & INVALID != 0 {
1158                break Err(ErrorKind::InvalidSymbol);
1159            }
1160            let code = (d >> 8) & 0xF;
1161            let distance = (d >> 16) as usize
1162                + ((bitbuf >> code) & ((1u64 << ((d & 0xFF) - code)) - 1)) as usize;
1163            bitbuf >>= d & 0xFF;
1164            bitcnt -= d & 0xFF;
1165
1166            if distance > window || (distance > o && distance - o > self.whave) {
1167                break Err(ErrorKind::DistanceTooFar);
1168            }
1169            if distance <= o && distance >= 8 {
1170                // Eight bytes at a time; the source is always written before
1171                // it is read because the distance is at least eight, and the
1172                // over-copy stays inside the FAST_OUT margin.
1173                let mut s = o - distance;
1174                let stop = o + length;
1175                while o < stop {
1176                    buf.copy_within(s..s + 8, o);
1177                    s += 8;
1178                    o += 8;
1179                }
1180                o = stop;
1181            } else {
1182                self.copy_match(buf, o, distance, length);
1183                o += length;
1184            }
1185        };
1186        // The refill leaves read-ahead bits above `bitcnt`; the slow path
1187        // needs them clear.
1188        self.bitbuf = bitbuf & ((1u64 << bitcnt) - 1);
1189        self.bitcnt = bitcnt;
1190        *ip = i;
1191        *op = o;
1192        result
1193    }
1194}
1195
1196/// Which table `peek` reads.
1197#[derive(Clone, Copy)]
1198enum Which {
1199    Lit,
1200    Dist,
1201    Pre,
1202}
1203
1204#[cfg(test)]
1205mod tests;