Skip to main content

zstd_native/
stream.rs

1//! Streaming decompression (libzstd's `ZSTD_decompressStream`): a push
2//! decoder that takes input and fills output in pieces of any size.
3//!
4//! Blocks are decoded into a window buffer of `window + 2 * block + 64`
5//! bytes (libzstd's sizing) and copied out. When the next block wouldn't
6//! fit, decoding wraps to the start of the buffer and the old segment's
7//! last `window - position` bytes serve as history (the block decoder's
8//! dictionary slot). The sizing keeps that history clear of everything the
9//! next blocks write, wildcopy overrun included. Each frame starts at the
10//! beginning of the buffer, after all earlier output was taken.
11//!
12//! Matches must stay within the window (libzstd's streaming decoder also
13//! allows a little more after a wrap; valid encoders never produce that).
14//!
15//! # Direct output
16//!
17//! When a frame's first block arrives and the caller's output has room for
18//! it, the frame is decoded straight into the caller's output instead
19//! ("direct"), like libzstd's single-pass shortcut in
20//! `ZSTD_decompressStream`, but block by block, so the whole frame needn't
21//! be in the input. The frame's earlier output then lies right before the
22//! write position in the caller's buffer and serves as history. The window
23//! buffer's layout (`cur`, `old_end`) is still tracked, as integers only,
24//! and each block sees exactly the history it would see in the window
25//! buffer: the same bytes come out and the same input is rejected. When a
26//! block doesn't fit, or the call returns mid-frame, the history the next
27//! blocks can reach is copied into the window buffer at the positions the
28//! layout gives it ([`StreamDecoder::leave_direct`]), and decoding goes on
29//! buffered. That copy is at most the output this call decoded directly,
30//! which the buffered path would have copied out anyway. A frame decoded
31//! wholly in one call never touches (or allocates) the window buffer.
32//!
33//! [`Decoder`](crate::Decoder)'s `read_to_end` decodes into the `Vec`
34//! (growing it) for the whole call, so frames there are always direct.
35
36use alloc::boxed::Box;
37use alloc::vec::Vec;
38
39use crate::block::{BlockDecoder, DictEntropy, Output, WILDCOPY_OVERLENGTH};
40use crate::decoder::reserve;
41use crate::dict::Dictionary;
42use crate::error::{Error, Result};
43use crate::frame::{self, FrameHeader};
44use crate::xxhash::Xxh64;
45
46/// libzstd's default window limit for streaming (`ZSTD_WINDOWLOG_LIMIT_DEFAULT`).
47const DEFAULT_WINDOW_LOG_MAX: u32 = 27;
48
49/// What one [`StreamDecoder::decode`] call did.
50#[derive(Debug, Clone, Copy, PartialEq, Eq)]
51pub struct Progress {
52    /// Input bytes consumed.
53    pub read: usize,
54    /// Output bytes written.
55    pub written: usize,
56    /// The decoder is between frames with no output pending: the input so
57    /// far is complete (more frames may follow).
58    pub at_frame_boundary: bool,
59}
60
61#[derive(Debug, Clone, Copy, PartialEq, Eq)]
62enum Stage {
63    /// Collecting the first 5 bytes of a frame (magic + descriptor).
64    Magic,
65    /// Collecting the rest of the frame header (`hdr_need` bytes in all).
66    Header,
67    /// Collecting the 4-byte size of a skippable frame.
68    SkippableSize,
69    /// Skipping skippable frame content.
70    Skip(u64),
71    BlockHeader,
72    /// Collecting/decoding a block.
73    Block {
74        btype: u8,
75        size: usize,
76        last: bool,
77    },
78    Checksum,
79}
80
81/// A streaming decoder: feed it input in any pieces, get output in any
82/// pieces. Handles concatenated and skippable frames. No `std` needed;
83/// [`Decoder`](crate::Decoder) wraps it as a `std::io::Read`.
84///
85/// Output is decoded straight into the buffer passed to
86/// [`decode`](Self::decode), without going through the decoder's window
87/// buffer, from the start of a frame for as long as the buffer has room
88/// for the next block (like libzstd's single-pass shortcut in
89/// `ZSTD_decompressStream`, but needing neither the whole frame in the
90/// input nor its size in the header). An output buffer that holds a whole
91/// frame, given at its start, gets it with no copy and no window buffer.
92///
93/// ```
94/// # let compressed: &[u8] = &[0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x05, 0x29, 0x00, 0x00, 0x68, 0x65, 0x6c, 0x6c, 0x6f];
95/// let mut d = zstd_native::StreamDecoder::new();
96/// let mut out = [0u8; 2];
97/// let mut got = Vec::new();
98/// let mut input = compressed;
99/// loop {
100///     let p = d.decode(input, &mut out)?;
101///     input = &input[p.read..];
102///     got.extend_from_slice(&out[..p.written]);
103///     if input.is_empty() && p.at_frame_boundary {
104///         break;
105///     }
106/// }
107/// assert_eq!(got, b"hello");
108/// # Ok::<(), zstd_native::Error>(())
109/// ```
110pub struct StreamDecoder {
111    block: Box<BlockDecoder>,
112    dict: Option<Dictionary>,
113    window_max: u64,
114    /// The dictionary was installed and no frame has used it yet.
115    dict_fresh: bool,
116    stage: Stage,
117    /// Frame header / small field staging.
118    hdr: [u8; 18],
119    hdr_len: usize,
120    hdr_need: usize,
121    /// Block staging when a block isn't wholly in the caller's input.
122    in_buf: Vec<u8>,
123    /// Window buffer (`cap` bytes; only written parts are ever read).
124    win: Vec<u8>,
125    win_size: usize,
126    fh: Option<FrameHeader>,
127    block_max: usize,
128    window: usize,
129    /// Write position and output not yet copied out (`flush..cur`). The
130    /// current segment always starts at 0 (a frame starts there, and a
131    /// wrap goes back there).
132    cur: usize,
133    flush: usize,
134    /// End of the previous segment after a wrap (its history).
135    old_end: Option<usize>,
136    /// The current frame is decoded into the caller's output: its
137    /// `produced` bytes so far end at the output's write position, and the
138    /// window buffer holds nothing (`cur`, `old_end` give its layout).
139    direct: bool,
140    produced: u64,
141    xxh: Option<Xxh64>,
142    /// An error found after output had already gone into the caller's
143    /// buffer (allocating the window buffer when leaving direct output):
144    /// that call reported its progress, the next one returns this.
145    pending: Option<Error>,
146    /// Tests: allocating the window buffer fails.
147    #[cfg(test)]
148    fail_window: bool,
149}
150
151impl core::fmt::Debug for StreamDecoder {
152    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
153        f.debug_struct("StreamDecoder")
154            .field("stage", &self.stage)
155            .field("window_max", &self.window_max)
156            .finish_non_exhaustive()
157    }
158}
159
160impl Default for StreamDecoder {
161    fn default() -> Self {
162        Self::new()
163    }
164}
165
166impl StreamDecoder {
167    /// A decoder without a dictionary and a 128 MiB (2^27) window limit.
168    pub fn new() -> Self {
169        StreamDecoder {
170            block: Box::new(BlockDecoder::new()),
171            dict: None,
172            window_max: 1 << DEFAULT_WINDOW_LOG_MAX,
173            dict_fresh: false,
174            stage: Stage::Magic,
175            hdr: [0; 18],
176            hdr_len: 0,
177            hdr_need: frame::STARTING_INPUT_LENGTH,
178            in_buf: Vec::new(),
179            win: Vec::new(),
180            win_size: 0,
181            fh: None,
182            block_max: 0,
183            window: 0,
184            cur: 0,
185            flush: 0,
186            old_end: None,
187            direct: false,
188            produced: 0,
189            xxh: None,
190            pending: None,
191            #[cfg(test)]
192            fail_window: false,
193        }
194    }
195
196    /// A decoder that uses `dict` for every frame.
197    pub fn with_dictionary(dict: Dictionary) -> Self {
198        let mut d = Self::new();
199        d.dict = Some(dict);
200        d.dict_fresh = true;
201        d
202    }
203
204    /// Sets the largest window accepted (frames needing more fail with
205    /// [`Error::WindowTooLarge`]), as `1 << log`, `log` 10 to 31 (30 on
206    /// 32-bit targets, as libzstd); values outside are clamped. Frames
207    /// with a window log over 31 (30 on 32-bit) are rejected in every
208    /// mode, one-shot decoding included.
209    /// The default is 27 (128 MiB), libzstd's.
210    pub fn set_window_log_max(&mut self, log: u32) {
211        self.window_max = 1u64 << log.clamp(10, frame::WINDOWLOG_MAX);
212    }
213
214    /// Forgets any partial frame; the next input must start a frame.
215    pub fn reset(&mut self) {
216        self.stage = Stage::Magic;
217        self.hdr_len = 0;
218        self.hdr_need = frame::STARTING_INPUT_LENGTH;
219        self.in_buf.clear();
220        self.cur = 0;
221        self.flush = 0;
222        self.direct = false;
223        self.fh = None;
224        self.pending = None;
225    }
226
227    /// True between frames with no output pending.
228    pub fn at_frame_boundary(&self) -> bool {
229        self.stage == Stage::Magic
230            && self.hdr_len == 0
231            && self.flush == self.cur
232            && self.pending.is_none()
233    }
234
235    /// Consumes input and writes output until the input is used up or the
236    /// output is full.
237    ///
238    /// # Errors
239    ///
240    /// Any [`Error`] for corrupt or unsupported input; the decoder must
241    /// then be [`reset`](Self::reset) before reuse. Output written by an
242    /// erroring call is lost (as libzstd's), except when the window buffer
243    /// can't be allocated ([`Error::OutputTooLarge`]) after output already
244    /// went straight into `output`: that call returns its progress (not at
245    /// a frame boundary) and the next call returns the error.
246    pub fn decode(&mut self, input: &[u8], output: &mut [u8]) -> Result<Progress> {
247        if let Some(e) = self.pending {
248            return Err(e);
249        }
250        let mut out = Output {
251            ptr: output.as_mut_ptr(),
252            cap: output.len(),
253            pos: 0,
254        };
255        let read = self
256            .run(input, &mut out, None)
257            .inspect_err(|_| self.drop_direct())?;
258        // The caller's buffer is gone after this call. If the window buffer
259        // can't take the history, the output written stays reported.
260        if let Err(e) = self.leave_direct(&output[..out.pos]) {
261            self.pending = Some(e);
262        }
263        Ok(Progress {
264            read,
265            written: out.pos,
266            at_frame_boundary: self.at_frame_boundary(),
267        })
268    }
269
270    /// Like [`decode`](Self::decode) but appends to `v`, growing it, until
271    /// the input is used up; returns the input bytes consumed. A frame
272    /// that starts here stays direct across calls: its history is `v`'s
273    /// tail, so `v` must hold everything earlier calls appended, and
274    /// [`leave_direct`](Self::leave_direct) must be called with it before
275    /// any other kind of call.
276    #[cfg(feature = "std")]
277    pub(crate) fn decode_vec(&mut self, input: &[u8], v: &mut Vec<u8>) -> Result<usize> {
278        if let Some(e) = self.pending {
279            return Err(e);
280        }
281        let mut out = Output {
282            ptr: v.as_mut_ptr(),
283            cap: v.capacity(),
284            pos: v.len(),
285        };
286        let r = self.run(input, &mut out, Some(&mut *v));
287        // SAFETY: `out.pos` only advances over bytes the decoder wrote
288        // (`run` keeps `out` in step with `v`'s allocation).
289        #[allow(unsafe_code)]
290        unsafe {
291            v.set_len(out.pos)
292        };
293        r.inspect_err(|_| self.drop_direct())
294    }
295
296    /// After an error in a direct frame: the window buffer doesn't hold
297    /// the history its layout claims, so forget the frame (the caller
298    /// must [`reset`](Self::reset) anyway, but a call without one must
299    /// not read the window buffer where nothing was written).
300    fn drop_direct(&mut self) {
301        if self.direct {
302            self.reset();
303        }
304    }
305
306    /// The decoding loop: into `out`, grown from `vec` when given (`out`
307    /// then describes `vec`'s allocation). Returns the input bytes used.
308    fn run(
309        &mut self,
310        input: &[u8],
311        out: &mut Output,
312        mut vec: Option<&mut Vec<u8>>,
313    ) -> Result<usize> {
314        let mut ip = 0;
315        loop {
316            // Pending output first.
317            if self.flush < self.cur {
318                debug_assert!(!self.direct);
319                if let Some(v) = vec.as_deref_mut() {
320                    reserve(v, out, self.cur - self.flush)?;
321                }
322                let n = (self.cur - self.flush).min(out.cap - out.pos);
323                // SAFETY: `flush..cur` of the window was written and the
324                // output has room for `n` bytes.
325                #[allow(unsafe_code)]
326                unsafe {
327                    core::ptr::copy_nonoverlapping(
328                        self.win.as_ptr().add(self.flush),
329                        out.ptr.add(out.pos),
330                        n,
331                    )
332                };
333                self.flush += n;
334                out.pos += n;
335                if self.flush < self.cur {
336                    break; // output full
337                }
338            }
339            let rest = &input[ip..];
340            match self.stage {
341                Stage::Magic | Stage::Header | Stage::SkippableSize | Stage::Checksum => {
342                    let take = (self.hdr_need - self.hdr_len).min(rest.len());
343                    self.hdr[self.hdr_len..self.hdr_len + take].copy_from_slice(&rest[..take]);
344                    self.hdr_len += take;
345                    ip += take;
346                    if self.hdr_len < self.hdr_need {
347                        break; // need input
348                    }
349                    self.small_field_done()?;
350                }
351                Stage::Skip(left) => {
352                    let n = (left.min(rest.len() as u64)) as usize;
353                    ip += n;
354                    let left = left - n as u64;
355                    if left > 0 {
356                        self.stage = Stage::Skip(left);
357                        break;
358                    }
359                    self.start_magic();
360                }
361                Stage::BlockHeader => {
362                    if self.in_buf.is_empty() && rest.len() >= 3 {
363                        ip += 3;
364                        self.block_header([rest[0], rest[1], rest[2]])?;
365                    } else {
366                        let take = (3 - self.in_buf.len()).min(rest.len());
367                        self.in_buf.extend_from_slice(&rest[..take]);
368                        ip += take;
369                        if self.in_buf.len() < 3 {
370                            break;
371                        }
372                        let h = [self.in_buf[0], self.in_buf[1], self.in_buf[2]];
373                        self.in_buf.clear();
374                        self.block_header(h)?;
375                    }
376                }
377                Stage::Block { btype, size, last } => {
378                    let need = if btype == 1 { 1 } else { size };
379                    let r = if self.in_buf.is_empty() && rest.len() >= need {
380                        // The whole block is in the input: decode in place.
381                        ip += need;
382                        let src = &input[ip - need..ip];
383                        let left = input.len() - ip;
384                        self.decode_block(btype, size, src, left, out, vec.as_deref_mut())
385                    } else {
386                        let take = (need - self.in_buf.len()).min(rest.len());
387                        self.in_buf.extend_from_slice(&rest[..take]);
388                        ip += take;
389                        if self.in_buf.len() < need {
390                            break;
391                        }
392                        let buf = core::mem::take(&mut self.in_buf);
393                        let left = input.len() - ip;
394                        let r = self.decode_block(btype, size, &buf, left, out, vec.as_deref_mut());
395                        self.in_buf = buf;
396                        self.in_buf.clear();
397                        r
398                    };
399                    if let Err(e) = r {
400                        if self.pending.is_some() {
401                            // The output so far stands; the error is the
402                            // next call's (see `decode_block`).
403                            break;
404                        }
405                        return Err(e);
406                    }
407                    self.stage = if !last {
408                        Stage::BlockHeader
409                    } else {
410                        self.end_of_blocks()?
411                    };
412                }
413            }
414        }
415        Ok(ip)
416    }
417
418    fn start_magic(&mut self) {
419        self.stage = Stage::Magic;
420        self.hdr_len = 0;
421        self.hdr_need = frame::STARTING_INPUT_LENGTH;
422    }
423
424    /// A staged header field is complete.
425    fn small_field_done(&mut self) -> Result<()> {
426        match self.stage {
427            Stage::Magic => {
428                let magic = frame::read_le32(&self.hdr, 0);
429                if frame::is_skippable(magic) {
430                    self.stage = Stage::SkippableSize;
431                    self.hdr_need = 8;
432                } else if magic == frame::MAGIC {
433                    self.stage = Stage::Header;
434                    self.hdr_need = frame::header_size(self.hdr[4]);
435                } else {
436                    return Err(Error::UnknownFrame);
437                }
438                // The 5th byte may already be complete for a skippable frame.
439                if self.hdr_len >= self.hdr_need {
440                    return self.small_field_done();
441                }
442                Ok(())
443            }
444            Stage::SkippableSize => {
445                let size = frame::read_le32(&self.hdr, 4);
446                self.stage = Stage::Skip(u64::from(size));
447                if size == 0 {
448                    self.start_magic();
449                }
450                Ok(())
451            }
452            Stage::Header => self.begin_frame(),
453            Stage::Checksum => {
454                let want = frame::read_le32(&self.hdr, 0);
455                let got = self.xxh.take().map_or(0, |x| x.digest() as u32);
456                if want != got {
457                    return Err(Error::ChecksumMismatch);
458                }
459                self.start_magic();
460                Ok(())
461            }
462            _ => unreachable!(),
463        }
464    }
465
466    fn begin_frame(&mut self) -> Result<()> {
467        let fh = FrameHeader::parse(&self.hdr[..self.hdr_need])?;
468        if fh.window_size > self.window_max {
469            return Err(Error::WindowTooLarge);
470        }
471        let dict_id = self.dict.as_ref().map_or(0, Dictionary::id);
472        if fh.dict_id != 0 && fh.dict_id != dict_id {
473            return Err(Error::DictionaryMismatch);
474        }
475        self.block
476            .start_frame(self.dict.as_ref().and_then(Dictionary::entropy));
477        self.block_max = fh.block_size_max();
478        // libzstd's `ddictIsCold`: the first frame after the dictionary was
479        // installed, or after a frame that wrapped the window buffer (libzstd
480        // then compares the history end it moved with the dictionary's end).
481        // The same rule as `Decompressor`'s address comparison: this
482        // decoder's dictionary is fixed at construction, so its content's
483        // end changes only before the first frame.
484        let fresh = core::mem::take(&mut self.dict_fresh);
485        self.block.dict_cold = self.dict.is_some() && (fresh || self.old_end.is_some());
486        // The window never needs to exceed the frame's size.
487        let window = match fh.content_size {
488            Some(cs) => fh.window_size.min(cs),
489            None => fh.window_size,
490        } as usize;
491        self.window = window;
492        // Allocated by the first buffered block (`ensure_window`): a frame
493        // decoded directly never needs it.
494        self.win_size = window + 2 * self.block_max + 2 * WILDCOPY_OVERLENGTH;
495        self.cur = 0;
496        self.flush = 0;
497        self.old_end = None;
498        self.direct = false;
499        self.produced = 0;
500        self.xxh = fh.has_checksum.then(Xxh64::new);
501        self.fh = Some(fh);
502        self.hdr_len = 0;
503        self.stage = Stage::BlockHeader;
504        Ok(())
505    }
506
507    fn block_header(&mut self, h: [u8; 3]) -> Result<()> {
508        let bh = u32::from_le_bytes([h[0], h[1], h[2], 0]);
509        let last = bh & 1 != 0;
510        let btype = ((bh >> 1) & 3) as u8;
511        let size = (bh >> 3) as usize;
512        // libzstd's streaming stages check both the compressed size (1 for
513        // an RLE block) and the regenerated size against `blockSizeMax`
514        // (`ZSTD_decompressContinue`). They differ only for an RLE block in
515        // a window of 0 (a single-segment frame of content size 0), which
516        // libzstd rejects even when it regenerates 0 bytes.
517        let csize = if btype == 1 { 1 } else { size };
518        if btype == 3 || size.max(csize) > self.block_max {
519            return Err(Error::Corrupted);
520        }
521        self.stage = Stage::Block { btype, size, last };
522        Ok(())
523    }
524
525    /// Decodes one block (everything before was flushed): into the
526    /// caller's output when the frame is direct (or can become direct: at
527    /// its start, with room for the block), else into the window at `cur`.
528    /// `src` is the block's content (1 byte for RLE), `input_left` the
529    /// caller's input after it. `out` and `vec` are as in [`run`](Self::run).
530    fn decode_block(
531        &mut self,
532        btype: u8,
533        size: usize,
534        src: &[u8],
535        input_left: usize,
536        out: &mut Output,
537        vec: Option<&mut Vec<u8>>,
538    ) -> Result<()> {
539        debug_assert_eq!(self.flush, self.cur);
540        if self.direct || self.produced == 0 {
541            // The most this block can write: its size for a raw or RLE
542            // block; `block_max` for a compressed one, or what's left of the
543            // content size (more fails the frame anyway).
544            let cs = self.fh.as_ref().and_then(|f| f.content_size);
545            let need = if btype < 2 {
546                size
547            } else {
548                let left = cs.map_or(u64::MAX, |cs| cs.saturating_sub(self.produced));
549                left.min(self.block_max as u64) as usize
550            };
551            if let Some(v) = vec {
552                if !self.direct
553                    && let Some(cs) = cs
554                {
555                    // Frame start: room for the whole frame, within the
556                    // window limit (no more than the window buffer that
557                    // isn't needed now), and no more than the input at
558                    // hand can produce: every further block takes at least
559                    // 4 input bytes (header and RLE byte) for at most
560                    // `block_max` bytes. A few bytes claiming a huge content
561                    // size can't make this allocate; real frames are far
562                    // below that bound and still get the whole size here.
563                    let can = (input_left / 4)
564                        .saturating_mul(self.block_max)
565                        .saturating_add(need) as u64;
566                    let want = cs.min(self.window_max).min(can) as usize;
567                    reserve(v, out, want + WILDCOPY_OVERLENGTH)?;
568                }
569                reserve(v, out, need + WILDCOPY_OVERLENGTH)?;
570            }
571            if out.cap - out.pos >= need {
572                self.direct = true;
573            } else if self.direct {
574                // SAFETY: `out.ptr[..out.pos]` is the caller's output so far
575                // (initialized: written by the caller or this decoder).
576                #[allow(unsafe_code)]
577                let done = unsafe { core::slice::from_raw_parts(out.ptr, out.pos) };
578                if let Err(e) = self.leave_direct(done) {
579                    // This call's output so far went straight into the
580                    // caller's buffer: `run` stops and reports it (this
581                    // block's input counted as read), the error comes next.
582                    self.pending = Some(e);
583                    return Err(e);
584                }
585            }
586        }
587        // Wrap when the block (plus wildcopy overrun) wouldn't fit. Tracked
588        // in direct mode too: the layout decides the history a block sees.
589        if self.cur + self.block_max + WILDCOPY_OVERLENGTH > self.win_size {
590            self.old_end = Some(self.cur);
591            self.cur = 0;
592            self.flush = 0;
593        }
594        let start = self.cur;
595        // History before the segment: the dictionary until the first wrap,
596        // then the old segment's last `hist` bytes (still within the window).
597        let old = self
598            .old_end
599            .map(|old_end| (old_end, self.window.saturating_sub(start).min(old_end)));
600        let written = if self.direct {
601            // The segment is the output's last `start` bytes, the old
602            // segment's history right before it.
603            debug_assert!(start as u64 <= self.produced && out.pos as u64 >= self.produced);
604            let (prefix, dict): (usize, &[u8]) = match old {
605                None => (
606                    out.pos - start,
607                    self.dict.as_ref().map_or(&[][..], |d| d.content()),
608                ),
609                Some((_, hist)) => (out.pos - start - hist, &[]),
610            };
611            let pos = out.pos;
612            write_block(
613                &mut self.block,
614                btype,
615                size,
616                src,
617                out,
618                prefix,
619                dict,
620                self.dict.as_ref().and_then(Dictionary::entropy),
621                self.block_max,
622            )
623            // With room for `need`, a block that doesn't fit is corrupt (as
624            // the window buffer's bound or the content size check finds).
625            .map_err(|e| match e {
626                Error::OutputTooSmall => Error::Corrupted,
627                e => e,
628            })?;
629            let n = out.pos - pos;
630            if let Some(x) = &mut self.xxh {
631                // SAFETY: just written.
632                #[allow(unsafe_code)]
633                x.update(unsafe { core::slice::from_raw_parts(out.ptr.add(pos), n) });
634            }
635            self.cur += n;
636            self.flush = self.cur;
637            n
638        } else {
639            self.ensure_window()?;
640            let base = self.win.as_mut_ptr();
641            let (dict, cap): (&[u8], usize) = match old {
642                None => (
643                    self.dict.as_ref().map_or(&[][..], |d| d.content()),
644                    self.win_size,
645                ),
646                Some((old_end, hist)) => {
647                    let from = old_end - hist;
648                    // SAFETY: `from..old_end` was written by earlier blocks
649                    // (or `leave_direct`). The buffer sizing (window + 2
650                    // blocks + 64) keeps it after `start + block_max +
651                    // WILDCOPY_OVERLENGTH`, so the writes of this block
652                    // (bounded by `cap = from`) never touch it.
653                    debug_assert!(
654                        from == old_end || start + self.block_max + WILDCOPY_OVERLENGTH <= from
655                    );
656                    #[allow(unsafe_code)]
657                    let d = unsafe { core::slice::from_raw_parts(base.add(from), hist) };
658                    (d, if from == old_end { self.win_size } else { from })
659                }
660            };
661            let mut wout = Output {
662                ptr: base,
663                cap,
664                pos: start,
665            };
666            write_block(
667                &mut self.block,
668                btype,
669                size,
670                src,
671                &mut wout,
672                // The segment starts at 0: its history is all in `dict`.
673                0,
674                dict,
675                self.dict.as_ref().and_then(Dictionary::entropy),
676                self.block_max,
677            )?;
678            self.cur = wout.pos;
679            if let Some(x) = &mut self.xxh {
680                // SAFETY: just written.
681                #[allow(unsafe_code)]
682                x.update(unsafe { core::slice::from_raw_parts(base.add(start), self.cur - start) });
683            }
684            self.cur - start
685        };
686        self.produced += written as u64;
687        Ok(())
688    }
689
690    /// Allocates the window buffer for the current frame.
691    fn ensure_window(&mut self) -> Result<()> {
692        if self.win.capacity() < self.win_size {
693            #[cfg(test)]
694            if self.fail_window {
695                return Err(Error::OutputTooLarge);
696            }
697            self.win = Vec::new();
698            self.win
699                .try_reserve_exact(self.win_size)
700                .map_err(|_| Error::OutputTooLarge)?;
701        }
702        Ok(())
703    }
704
705    /// Ends direct output for the current frame, if on: copies the history
706    /// later blocks can reach from `out` (the caller's output, ending at
707    /// the write position) into the window buffer, where the layout (`cur`,
708    /// `old_end`) puts it. Then decoding goes on buffered.
709    pub(crate) fn leave_direct(&mut self, out: &[u8]) -> Result<()> {
710        if !self.direct {
711            return Ok(());
712        }
713        if let Err(e) = self.ensure_window() {
714            self.reset(); // as `drop_direct`
715            return Err(e);
716        }
717        self.direct = false;
718        // The current segment: the output's last `cur` bytes.
719        let seg = out.len() - self.cur;
720        self.fill_window(0, &out[seg..]);
721        if let Some(old_end) = self.old_end {
722            // The old segment's tail that the blocks from `cur` on can
723            // reach (less as `cur` grows), right before the segment.
724            let hist = self.window.saturating_sub(self.cur).min(old_end);
725            debug_assert!(
726                hist == 0 || self.cur + self.block_max + WILDCOPY_OVERLENGTH <= old_end - hist
727            );
728            self.fill_window(old_end - hist, &out[seg - hist..seg]);
729        }
730        self.flush = self.cur;
731        Ok(())
732    }
733
734    /// Copies `src` into the window buffer at `at`, in pieces: one large
735    /// `memcpy` may use non-temporal stores (glibc does from about 1 MiB
736    /// on), which leave the history out of the cache that the next blocks'
737    /// matches read (measured: 11% more cycles for 1 MiB outputs).
738    fn fill_window(&mut self, at: usize, src: &[u8]) {
739        const PIECE: usize = 64 << 10;
740        assert!(at <= self.win.capacity() && src.len() <= self.win.capacity() - at);
741        let dst = self.win.as_mut_ptr();
742        for (i, piece) in src.chunks(PIECE).enumerate() {
743            // SAFETY: `at + src.len() <= capacity` (checked above).
744            #[allow(unsafe_code)]
745            unsafe {
746                core::ptr::copy_nonoverlapping(piece.as_ptr(), dst.add(at + i * PIECE), piece.len())
747            };
748        }
749    }
750
751    fn end_of_blocks(&mut self) -> Result<Stage> {
752        let fh = self.fh.take().ok_or(Error::Corrupted)?;
753        if let Some(cs) = fh.content_size
754            && cs != self.produced
755        {
756            return Err(Error::Corrupted);
757        }
758        // The frame's history isn't needed any more.
759        self.direct = false;
760        self.hdr_len = 0;
761        if fh.has_checksum {
762            self.hdr_need = 4;
763            Ok(Stage::Checksum)
764        } else {
765            self.hdr_need = frame::STARTING_INPUT_LENGTH;
766            Ok(Stage::Magic)
767        }
768    }
769}
770
771/// Writes one block at `out.pos`: copies a raw block, repeats an RLE
772/// block's byte, or decodes a compressed block (history: `out` from
773/// `prefix` on, after `dict`). The caller checked the block's size against
774/// `block_max`, and that a raw or RLE block fits in `out`.
775#[allow(clippy::too_many_arguments)]
776fn write_block(
777    block: &mut BlockDecoder,
778    btype: u8,
779    size: usize,
780    src: &[u8],
781    out: &mut Output,
782    prefix: usize,
783    dict: &[u8],
784    dict_ent: Option<&DictEntropy>,
785    block_max: usize,
786) -> Result<()> {
787    match btype {
788        0 => {
789            debug_assert!(size <= out.cap - out.pos && size <= src.len());
790            // SAFETY: `src` holds the block's `size` bytes and the output
791            // has room for them (the caller's checks, asserted).
792            #[allow(unsafe_code)]
793            unsafe {
794                core::ptr::copy_nonoverlapping(src.as_ptr(), out.ptr.add(out.pos), size)
795            };
796            out.pos += size;
797        }
798        1 => {
799            debug_assert!(size <= out.cap - out.pos);
800            // SAFETY: as above.
801            #[allow(unsafe_code)]
802            unsafe {
803                core::ptr::write_bytes(out.ptr.add(out.pos), src[0], size)
804            };
805            out.pos += size;
806        }
807        _ => {
808            let start = out.pos;
809            block.decode_block(src, out, prefix, dict, dict_ent, block_max)?;
810            // `decode_block` bounds a block by `block_max`.
811            debug_assert!(out.pos - start <= block_max);
812        }
813    }
814    Ok(())
815}
816
817#[cfg(test)]
818mod tests {
819    use super::*;
820    use crate::enc::{EndOp, StreamEncoder};
821    use alloc::vec;
822
823    /// Text from a small vocabulary: matches near and far.
824    fn text(len: usize) -> Vec<u8> {
825        const WORDS: [&[u8]; 8] = [
826            b"zstd ",
827            b"window ",
828            b"block ",
829            b"direct ",
830            b"history ",
831            b"wrap\n",
832            b"a ",
833            b"the ",
834        ];
835        let mut x = 0x9E37_79B9_7F4A_7C15u64;
836        let mut v = Vec::new();
837        while v.len() < len {
838            x ^= x << 13;
839            x ^= x >> 7;
840            x ^= x << 17;
841            v.extend_from_slice(WORDS[(x % 8) as usize]);
842            if x.is_multiple_of(11) {
843                v.push((x >> 32) as u8);
844            }
845        }
846        v.truncate(len);
847        v
848    }
849
850    /// A frame of `data` with window log `wlog` (10: 1 KiB blocks), with
851    /// or without the content size, with a checksum.
852    fn frame(data: &[u8], wlog: u32, fcs: bool) -> Vec<u8> {
853        let mut e = StreamEncoder::new(1);
854        e.set_window_log(wlog);
855        e.set_checksum(true).unwrap();
856        e.set_content_size_flag(fcs).unwrap();
857        let mut out = vec![0u8; crate::compress_bound(data.len()) + 64];
858        let p = e.compress(data, &mut out, EndOp::End).unwrap();
859        assert_eq!((p.read, p.remaining), (data.len(), 0));
860        out.truncate(p.written);
861        out
862    }
863
864    /// Streams `src` in `in_step` pieces into outputs of `out_size`.
865    fn stream(src: &[u8], in_step: usize, out_size: usize) -> Result<Vec<u8>> {
866        let mut d = StreamDecoder::new();
867        let mut got = Vec::new();
868        let mut buf = vec![0u8; out_size];
869        let mut ip = 0;
870        loop {
871            let n = in_step.min(src.len() - ip);
872            let p = d.decode(&src[ip..ip + n], &mut buf)?;
873            ip += p.read;
874            got.extend_from_slice(&buf[..p.written]);
875            if ip == src.len() && p.read == 0 && p.written == 0 {
876                return if p.at_frame_boundary {
877                    Ok(got)
878                } else {
879                    Err(Error::Truncated)
880                };
881            }
882        }
883    }
884
885    /// Direct output (outputs that hold a block or the frame), switching
886    /// to the window buffer mid-frame (input or output running out), and
887    /// frames many windows long, against the window buffer alone
888    /// (1-byte outputs).
889    #[test]
890    fn direct_and_buffered_agree() {
891        let len = if cfg!(miri) { 5000 } else { 300_000 };
892        let data = text(len);
893        let mut two = data.clone();
894        two.extend_from_slice(&data);
895        for (wlog, fcs) in [(10, true), (10, false), (17, true)] {
896            let f = frame(&data, wlog, fcs);
897            let mut f2 = f.clone();
898            f2.extend_from_slice(&f);
899            assert!(stream(&f, 1 << 20, 1).unwrap() == data);
900            let steps: &[usize] = if cfg!(miri) {
901                &[usize::MAX, 700]
902            } else {
903                &[usize::MAX, 1, 700, 4096]
904            };
905            for &in_step in steps {
906                let outs: &[usize] = if cfg!(miri) {
907                    &[1024, len, 2 * len + 7]
908                } else {
909                    &[1000, 1024, 3000, len - 1, len, len + 1, 2 * len + 7]
910                };
911                for &out in outs {
912                    let got = stream(&f, in_step, out).unwrap();
913                    assert!(got == data, "wlog {wlog} fcs {fcs} in {in_step} out {out}");
914                    let got = stream(&f2, in_step, out).unwrap();
915                    assert!(
916                        got == two,
917                        "2 frames: wlog {wlog} fcs {fcs} in {in_step} out {out}"
918                    );
919                }
920            }
921        }
922    }
923
924    /// Corrupt frames: direct output rejects what the window buffer
925    /// rejects and accepts what it accepts, with the same output.
926    #[test]
927    fn direct_rejects_as_buffered() {
928        let data = text(if cfg!(miri) { 3000 } else { 100_000 });
929        let iters = if cfg!(miri) { 2 } else { 2000 };
930        let mut x = 12345u64;
931        for fcs in [true, false] {
932            let f = frame(&data, 10, fcs);
933            for _ in 0..iters {
934                let mut m = f.clone();
935                x = x
936                    .wrapping_mul(6_364_136_223_846_793_005)
937                    .wrapping_add(1_442_695_040_888_963_407);
938                let p = (x >> 33) as usize % m.len();
939                m[p] ^= 1 << ((x >> 20) % 8);
940                let buffered = stream(&m, usize::MAX, 1);
941                let direct = stream(&m, usize::MAX, 2 * data.len());
942                assert_eq!(buffered.is_ok(), direct.is_ok(), "byte {p}");
943                if let (Ok(a), Ok(b)) = (&buffered, &direct) {
944                    assert!(a == b, "byte {p}: output differs");
945                }
946                // Going on after an error without `reset` (misuse) stays
947                // memory safe: no history is read that was not written.
948                let mut d = StreamDecoder::new();
949                let mut buf = vec![0u8; 2 * data.len()];
950                if d.decode(&m, &mut buf).is_err() {
951                    let _ = d.decode(&f[f.len() / 2..], &mut buf[..1]);
952                    let _ = d.decode(&f[f.len() / 2..], &mut buf);
953                }
954            }
955        }
956    }
957
958    /// The window buffer can't be allocated when leaving direct output
959    /// (independent review): the call that wrote output straight into the
960    /// caller's buffer reports it, the next call returns the error, until
961    /// `reset`.
962    #[test]
963    fn window_alloc_failure_keeps_progress() {
964        let data = text(5000);
965        let f = frame(&data, 10, false);
966        // Leaving direct output at the end of the call (input runs out
967        // mid-frame), and mid-call (a block doesn't fit the output).
968        for (input, out_size) in [(&f[..f.len() / 2], 2 * data.len()), (&f[..], 3000)] {
969            let mut d = StreamDecoder::new();
970            d.fail_window = true;
971            let mut buf = vec![0u8; out_size];
972            let p = d.decode(input, &mut buf).unwrap();
973            assert!(p.written > 0 && !p.at_frame_boundary);
974            assert!(buf[..p.written] == data[..p.written]);
975            assert!(!d.at_frame_boundary());
976            assert_eq!(d.decode(&f[p.read..], &mut buf), Err(Error::OutputTooLarge));
977            assert_eq!(d.decode(&f[p.read..], &mut buf), Err(Error::OutputTooLarge));
978            d.reset();
979            d.fail_window = false;
980            assert_eq!(stream_with(&mut d, &f), data);
981        }
982    }
983
984    fn stream_with(d: &mut StreamDecoder, src: &[u8]) -> Vec<u8> {
985        let mut got = Vec::new();
986        let mut buf = vec![0u8; 777];
987        let mut ip = 0;
988        loop {
989            let p = d.decode(&src[ip..], &mut buf).unwrap();
990            ip += p.read;
991            got.extend_from_slice(&buf[..p.written]);
992            if p.read == 0 && p.written == 0 {
993                assert!(p.at_frame_boundary);
994                return got;
995            }
996        }
997    }
998
999    /// `Decoder::read_to_end` (`decode_vec`), and leaving direct output
1000    /// for later `decode` calls.
1001    #[cfg(feature = "std")]
1002    #[test]
1003    fn vec_output() {
1004        let data = text(if cfg!(miri) { 4000 } else { 200_000 });
1005        for fcs in [true, false] {
1006            let f = frame(&data, 10, fcs);
1007            let mut d = StreamDecoder::new();
1008            let mut v = b"prefix".to_vec();
1009            // In pieces: the frame stays direct in `v` across calls.
1010            let mut ip = 0;
1011            while ip < f.len() {
1012                let n = 999.min(f.len() - ip);
1013                ip += d.decode_vec(&f[ip..ip + n], &mut v).unwrap();
1014            }
1015            assert!(d.at_frame_boundary() && v[6..] == data[..]);
1016
1017            // Half the input into the `Vec`, the rest through `decode`.
1018            let mut d = StreamDecoder::new();
1019            let mut v = Vec::new();
1020            let half = f.len() / 2;
1021            assert_eq!(d.decode_vec(&f[..half], &mut v), Ok(half));
1022            d.leave_direct(&v).unwrap();
1023            let mut buf = vec![0u8; 777];
1024            let mut ip = half;
1025            loop {
1026                let p = d.decode(&f[ip..], &mut buf).unwrap();
1027                ip += p.read;
1028                v.extend_from_slice(&buf[..p.written]);
1029                if p.written == 0 && p.read == 0 {
1030                    break;
1031                }
1032            }
1033            assert!(d.at_frame_boundary() && v == data);
1034        }
1035    }
1036}