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