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
15use alloc::boxed::Box;
16use alloc::vec::Vec;
17
18use crate::block::{BlockDecoder, Output, WILDCOPY_OVERLENGTH};
19use crate::dict::Dictionary;
20use crate::error::{Error, Result};
21use crate::frame::{self, FrameHeader};
22use crate::xxhash::Xxh64;
23
24/// libzstd's default window limit for streaming (`ZSTD_WINDOWLOG_LIMIT_DEFAULT`).
25const DEFAULT_WINDOW_LOG_MAX: u32 = 27;
26
27/// What one [`StreamDecoder::decode`] call did.
28#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29pub struct Progress {
30    /// Input bytes consumed.
31    pub read: usize,
32    /// Output bytes written.
33    pub written: usize,
34    /// The decoder is between frames with no output pending: the input so
35    /// far is complete (more frames may follow).
36    pub at_frame_boundary: bool,
37}
38
39#[derive(Debug, Clone, Copy, PartialEq, Eq)]
40enum Stage {
41    /// Collecting the first 5 bytes of a frame (magic + descriptor).
42    Magic,
43    /// Collecting the rest of the frame header (`hdr_need` bytes in all).
44    Header,
45    /// Collecting the 4-byte size of a skippable frame.
46    SkippableSize,
47    /// Skipping skippable frame content.
48    Skip(u64),
49    BlockHeader,
50    /// Collecting/decoding a block.
51    Block {
52        btype: u8,
53        size: usize,
54        last: bool,
55    },
56    Checksum,
57}
58
59/// A streaming decoder: feed it input in any pieces, get output in any
60/// pieces. Handles concatenated and skippable frames. No `std` needed;
61/// [`Decoder`](crate::Decoder) wraps it as a `std::io::Read`.
62///
63/// ```
64/// # let compressed: &[u8] = &[0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x05, 0x29, 0x00, 0x00, 0x68, 0x65, 0x6c, 0x6c, 0x6f];
65/// let mut d = zstd_native::StreamDecoder::new();
66/// let mut out = [0u8; 2];
67/// let mut got = Vec::new();
68/// let mut input = compressed;
69/// loop {
70///     let p = d.decode(input, &mut out)?;
71///     input = &input[p.read..];
72///     got.extend_from_slice(&out[..p.written]);
73///     if input.is_empty() && p.at_frame_boundary {
74///         break;
75///     }
76/// }
77/// assert_eq!(got, b"hello");
78/// # Ok::<(), zstd_native::Error>(())
79/// ```
80pub struct StreamDecoder {
81    block: Box<BlockDecoder>,
82    dict: Option<Dictionary>,
83    window_max: u64,
84    stage: Stage,
85    /// Frame header / small field staging.
86    hdr: [u8; 18],
87    hdr_len: usize,
88    hdr_need: usize,
89    /// Block staging when a block isn't wholly in the caller's input.
90    in_buf: Vec<u8>,
91    /// Window buffer (`cap` bytes; only written parts are ever read).
92    win: Vec<u8>,
93    win_size: usize,
94    fh: Option<FrameHeader>,
95    block_max: usize,
96    window: usize,
97    /// Write position, start of the current segment, and output not yet
98    /// copied out (`flush..cur`).
99    cur: usize,
100    prefix: usize,
101    flush: usize,
102    /// End of the previous segment after a wrap (its history).
103    old_end: Option<usize>,
104    produced: u64,
105    xxh: Option<Xxh64>,
106}
107
108impl core::fmt::Debug for StreamDecoder {
109    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
110        f.debug_struct("StreamDecoder")
111            .field("stage", &self.stage)
112            .field("window_max", &self.window_max)
113            .finish_non_exhaustive()
114    }
115}
116
117impl Default for StreamDecoder {
118    fn default() -> Self {
119        Self::new()
120    }
121}
122
123impl StreamDecoder {
124    /// A decoder without a dictionary and a 128 MiB (2^27) window limit.
125    pub fn new() -> Self {
126        StreamDecoder {
127            block: Box::new(BlockDecoder::new()),
128            dict: None,
129            window_max: 1 << DEFAULT_WINDOW_LOG_MAX,
130            stage: Stage::Magic,
131            hdr: [0; 18],
132            hdr_len: 0,
133            hdr_need: frame::STARTING_INPUT_LENGTH,
134            in_buf: Vec::new(),
135            win: Vec::new(),
136            win_size: 0,
137            fh: None,
138            block_max: 0,
139            window: 0,
140            cur: 0,
141            prefix: 0,
142            flush: 0,
143            old_end: None,
144            produced: 0,
145            xxh: None,
146        }
147    }
148
149    /// A decoder that uses `dict` for every frame.
150    pub fn with_dictionary(dict: Dictionary) -> Self {
151        let mut d = Self::new();
152        d.dict = Some(dict);
153        d
154    }
155
156    /// Sets the largest window accepted (frames needing more fail with
157    /// [`Error::WindowTooLarge`]), as `1 << log`, `log` 10 to 31 (30 on
158    /// 32-bit targets, as libzstd); values outside are clamped. Frames
159    /// with a window log over 31 (30 on 32-bit) are rejected in every
160    /// mode, one-shot decoding included.
161    /// The default is 27 (128 MiB), libzstd's.
162    pub fn set_window_log_max(&mut self, log: u32) {
163        self.window_max = 1u64 << log.clamp(10, frame::WINDOWLOG_MAX);
164    }
165
166    /// Forgets any partial frame; the next input must start a frame.
167    pub fn reset(&mut self) {
168        self.stage = Stage::Magic;
169        self.hdr_len = 0;
170        self.hdr_need = frame::STARTING_INPUT_LENGTH;
171        self.in_buf.clear();
172        self.cur = 0;
173        self.flush = 0;
174        self.fh = None;
175    }
176
177    /// True between frames with no output pending.
178    pub fn at_frame_boundary(&self) -> bool {
179        self.stage == Stage::Magic && self.hdr_len == 0 && self.flush == self.cur
180    }
181
182    /// Consumes input and writes output until the input is used up or the
183    /// output is full.
184    ///
185    /// # Errors
186    ///
187    /// Any [`Error`] for corrupt or unsupported input; the decoder must
188    /// then be [`reset`](Self::reset) before reuse.
189    pub fn decode(&mut self, input: &[u8], output: &mut [u8]) -> Result<Progress> {
190        let mut ip = 0;
191        let mut op = 0;
192        loop {
193            // Pending output first.
194            if self.flush < self.cur {
195                let n = (self.cur - self.flush).min(output.len() - op);
196                // SAFETY: `flush..cur` of the window was written.
197                #[allow(unsafe_code)]
198                unsafe {
199                    core::ptr::copy_nonoverlapping(
200                        self.win.as_ptr().add(self.flush),
201                        output.as_mut_ptr().add(op),
202                        n,
203                    )
204                };
205                self.flush += n;
206                op += n;
207                if self.flush < self.cur {
208                    break; // output full
209                }
210            }
211            let rest = &input[ip..];
212            match self.stage {
213                Stage::Magic | Stage::Header | Stage::SkippableSize | Stage::Checksum => {
214                    let take = (self.hdr_need - self.hdr_len).min(rest.len());
215                    self.hdr[self.hdr_len..self.hdr_len + take].copy_from_slice(&rest[..take]);
216                    self.hdr_len += take;
217                    ip += take;
218                    if self.hdr_len < self.hdr_need {
219                        break; // need input
220                    }
221                    self.small_field_done()?;
222                }
223                Stage::Skip(left) => {
224                    let n = (left.min(rest.len() as u64)) as usize;
225                    ip += n;
226                    let left = left - n as u64;
227                    if left > 0 {
228                        self.stage = Stage::Skip(left);
229                        break;
230                    }
231                    self.start_magic();
232                }
233                Stage::BlockHeader => {
234                    if self.in_buf.is_empty() && rest.len() >= 3 {
235                        ip += 3;
236                        self.block_header([rest[0], rest[1], rest[2]])?;
237                    } else {
238                        let take = (3 - self.in_buf.len()).min(rest.len());
239                        self.in_buf.extend_from_slice(&rest[..take]);
240                        ip += take;
241                        if self.in_buf.len() < 3 {
242                            break;
243                        }
244                        let h = [self.in_buf[0], self.in_buf[1], self.in_buf[2]];
245                        self.in_buf.clear();
246                        self.block_header(h)?;
247                    }
248                }
249                Stage::Block { btype, size, last } => {
250                    let need = if btype == 1 { 1 } else { size };
251                    if self.in_buf.is_empty() && rest.len() >= need {
252                        // The whole block is in the input: decode in place.
253                        ip += need;
254                        self.decode_block(btype, size, &input[ip - need..ip])?;
255                    } else {
256                        let take = (need - self.in_buf.len()).min(rest.len());
257                        self.in_buf.extend_from_slice(&rest[..take]);
258                        ip += take;
259                        if self.in_buf.len() < need {
260                            break;
261                        }
262                        let buf = core::mem::take(&mut self.in_buf);
263                        let r = self.decode_block(btype, size, &buf);
264                        self.in_buf = buf;
265                        self.in_buf.clear();
266                        r?;
267                    }
268                    self.stage = if !last {
269                        Stage::BlockHeader
270                    } else {
271                        self.end_of_blocks()?
272                    };
273                }
274            }
275        }
276        Ok(Progress {
277            read: ip,
278            written: op,
279            at_frame_boundary: self.at_frame_boundary(),
280        })
281    }
282
283    fn start_magic(&mut self) {
284        self.stage = Stage::Magic;
285        self.hdr_len = 0;
286        self.hdr_need = frame::STARTING_INPUT_LENGTH;
287    }
288
289    /// A staged header field is complete.
290    fn small_field_done(&mut self) -> Result<()> {
291        match self.stage {
292            Stage::Magic => {
293                let magic = frame::read_le32(&self.hdr, 0);
294                if frame::is_skippable(magic) {
295                    self.stage = Stage::SkippableSize;
296                    self.hdr_need = 8;
297                } else if magic == frame::MAGIC {
298                    self.stage = Stage::Header;
299                    self.hdr_need = frame::header_size(self.hdr[4]);
300                } else {
301                    return Err(Error::UnknownFrame);
302                }
303                // The 5th byte may already be complete for a skippable frame.
304                if self.hdr_len >= self.hdr_need {
305                    return self.small_field_done();
306                }
307                Ok(())
308            }
309            Stage::SkippableSize => {
310                let size = frame::read_le32(&self.hdr, 4);
311                self.stage = Stage::Skip(u64::from(size));
312                if size == 0 {
313                    self.start_magic();
314                }
315                Ok(())
316            }
317            Stage::Header => self.begin_frame(),
318            Stage::Checksum => {
319                let want = frame::read_le32(&self.hdr, 0);
320                let got = self.xxh.take().map_or(0, |x| x.digest() as u32);
321                if want != got {
322                    return Err(Error::ChecksumMismatch);
323                }
324                self.start_magic();
325                Ok(())
326            }
327            _ => unreachable!(),
328        }
329    }
330
331    fn begin_frame(&mut self) -> Result<()> {
332        let fh = FrameHeader::parse(&self.hdr[..self.hdr_need])?;
333        if fh.window_size > self.window_max {
334            return Err(Error::WindowTooLarge);
335        }
336        let dict_id = self.dict.as_ref().map_or(0, |d| d.id);
337        if fh.dict_id != 0 && fh.dict_id != dict_id {
338            return Err(Error::DictionaryMismatch);
339        }
340        match self.dict.as_ref().and_then(|d| d.entropy.as_deref()) {
341            Some(e) => self.block.ent.clone_from(e),
342            None => self.block.ent.reset(),
343        }
344        self.block_max = fh.block_size_max();
345        // The window never needs to exceed the frame's size.
346        let window = match fh.content_size {
347            Some(cs) => fh.window_size.min(cs),
348            None => fh.window_size,
349        } as usize;
350        self.window = window;
351        let size = window + 2 * self.block_max + 2 * WILDCOPY_OVERLENGTH;
352        if self.win.capacity() < size {
353            self.win = Vec::new();
354            self.win
355                .try_reserve_exact(size)
356                .map_err(|_| Error::OutputTooLarge)?;
357        }
358        self.win_size = size;
359        self.cur = 0;
360        self.prefix = 0;
361        self.flush = 0;
362        self.old_end = None;
363        self.produced = 0;
364        self.xxh = fh.has_checksum.then(Xxh64::new);
365        self.fh = Some(fh);
366        self.hdr_len = 0;
367        self.stage = Stage::BlockHeader;
368        Ok(())
369    }
370
371    fn block_header(&mut self, h: [u8; 3]) -> Result<()> {
372        let bh = u32::from_le_bytes([h[0], h[1], h[2], 0]);
373        let last = bh & 1 != 0;
374        let btype = ((bh >> 1) & 3) as u8;
375        let size = (bh >> 3) as usize;
376        // libzstd's streaming stages check both the compressed size (1 for
377        // an RLE block) and the regenerated size against `blockSizeMax`
378        // (`ZSTD_decompressContinue`). They differ only for an RLE block in
379        // a window of 0 (a single-segment frame of content size 0), which
380        // libzstd rejects even when it regenerates 0 bytes.
381        let csize = if btype == 1 { 1 } else { size };
382        if btype == 3 || size.max(csize) > self.block_max {
383            return Err(Error::Corrupted);
384        }
385        self.stage = Stage::Block { btype, size, last };
386        Ok(())
387    }
388
389    /// Decodes one block into the window at `cur` (everything before was
390    /// flushed). `src` is the block's content (1 byte for RLE).
391    fn decode_block(&mut self, btype: u8, size: usize, src: &[u8]) -> Result<()> {
392        debug_assert_eq!(self.flush, self.cur);
393        // Wrap when the block (plus wildcopy overrun) wouldn't fit.
394        if self.cur + self.block_max + WILDCOPY_OVERLENGTH > self.win_size {
395            self.old_end = Some(self.cur);
396            self.cur = 0;
397            self.prefix = 0;
398            self.flush = 0;
399        }
400        let start = self.cur;
401        let base = self.win.as_mut_ptr();
402        // History before the segment: the dictionary until the first wrap,
403        // then the part of the old segment still within the window.
404        let (dict, cap): (&[u8], usize) = match self.old_end {
405            None => (
406                self.dict.as_ref().map_or(&[][..], |d| &d.content[..]),
407                self.win_size,
408            ),
409            Some(old_end) => {
410                let need = self.window.saturating_sub(start);
411                let from = old_end - need.min(old_end);
412                // SAFETY: `from..old_end` was written by earlier blocks. The
413                // buffer sizing (window + 2 blocks + 64) keeps it after
414                // `start + block_max + WILDCOPY_OVERLENGTH`, so the writes of
415                // this block (bounded by `cap = from`) never touch it.
416                debug_assert!(
417                    from == old_end || start + self.block_max + WILDCOPY_OVERLENGTH <= from
418                );
419                #[allow(unsafe_code)]
420                let d = unsafe { core::slice::from_raw_parts(base.add(from), old_end - from) };
421                (d, if from == old_end { self.win_size } else { from })
422            }
423        };
424        let mut out = Output {
425            ptr: base,
426            cap,
427            pos: start,
428        };
429        match btype {
430            0 => {
431                // SAFETY: `size <= block_max` and the block fits before `cap`.
432                #[allow(unsafe_code)]
433                unsafe {
434                    core::ptr::copy_nonoverlapping(src.as_ptr(), base.add(start), size)
435                };
436                out.pos += size;
437            }
438            1 => {
439                // SAFETY: as above.
440                #[allow(unsafe_code)]
441                unsafe {
442                    core::ptr::write_bytes(base.add(start), src[0], size)
443                };
444                out.pos += size;
445            }
446            _ => {
447                self.block
448                    .decode_block(src, &mut out, self.prefix, dict, self.block_max)?;
449                // `decode_block` bounds a block by `block_max`.
450                debug_assert!(out.pos - start <= self.block_max);
451            }
452        }
453        self.cur = out.pos;
454        self.produced += (self.cur - start) as u64;
455        if let Some(x) = &mut self.xxh {
456            // SAFETY: just written.
457            #[allow(unsafe_code)]
458            x.update(unsafe { core::slice::from_raw_parts(base.add(start), self.cur - start) });
459        }
460        Ok(())
461    }
462
463    fn end_of_blocks(&mut self) -> Result<Stage> {
464        let fh = self.fh.take().ok_or(Error::Corrupted)?;
465        if let Some(cs) = fh.content_size
466            && cs != self.produced
467        {
468            return Err(Error::Corrupted);
469        }
470        self.hdr_len = 0;
471        if fh.has_checksum {
472            self.hdr_need = 4;
473            Ok(Stage::Checksum)
474        } else {
475            self.hdr_need = frame::STARTING_INPUT_LENGTH;
476            Ok(Stage::Magic)
477        }
478    }
479}