zstd_native/enc/stream.rs
1//! Streaming compression: a port of libzstd 1.5.7's `ZSTD_compressStream2`
2//! (`ZSTD_compressStream_generic`) in its default buffered mode
3//! (`ZSTD_bm_buffered` for input and output), whose output is
4//! byte-identical to libzstd's for the same input, level and sequence of
5//! operations.
6//!
7//! # The input buffer
8//!
9//! Input is copied into a ring buffer of `windowSize + blockSize` bytes
10//! (`inBuffSize`). A block is compressed (`ZSTD_compressContinue`) when the
11//! buffer holds a full block past `inToCompress` (or on a flush or the
12//! end); the next block then goes after it, or back at the start of the
13//! buffer when it would not fit. Wrapping makes the window non-contiguous:
14//! the older segment, at the end of the buffer, becomes the extDict and the
15//! match finders' `_extDict` variants run until the window has moved past
16//! it. Both segments are in the same buffer, so the window's positions (see
17//! the `fast` module docs) map `base + i` (prefix) and `dictBase + i`
18//! (extDict) into it.
19//!
20//! # Dictionaries
21//!
22//! A dictionary ([`StreamEncoder::with_dictionary`],
23//! [`StreamEncoder::with_prepared_dictionary`]) applies to every frame; the
24//! frame starts from it like a one-shot frame (see the `cdict` module), its
25//! content staying in its own buffer.
26//!
27//! # Parameters
28//!
29//! They are chosen when the first call of a frame starts it
30//! (`ZSTD_CCtx_init_compressStream2`): for the pledged source size if one
31//! was given, else for the size of the input if that first call ends the
32//! frame ([`EndOp::End`]), else for an unknown size (the level's largest
33//! window). The frame header holds the content size when it is known.
34//!
35//! # Multithreading
36//!
37//! With `std` and workers (`StreamEncoder::set_workers`), a frame of
38//! unknown size or over 512 KiB is compressed by the `mt` module instead
39//! (`ZSTDMT_compressStream_generic`): its input goes into job buffers, not
40//! the ring, the shortcut below does not apply, and the output does not
41//! depend on the output buffer sizes.
42//!
43//! # libzstd's shortcut
44//!
45//! An [`EndOp::End`] call that finds the input buffer empty at its start
46//! (nothing loaded yet in the frame, or just wrapped) and an output buffer
47//! of at least [`compress_bound`] of the remaining input compresses that
48//! input directly as the frame's last chunk (`ZSTD_compressEnd`), not block
49//! by block through the input buffer. That changes the block boundaries,
50//! hence the output, which is therefore not a function of the input and the
51//! operations alone: it also depends on the output buffer sizes, exactly as
52//! with libzstd.
53
54use alloc::boxed::Box;
55use alloc::vec::Vec;
56
57use super::cdict::{DictSlot, EncoderDictionary, frame_cparams};
58use super::compress::{FrameCompressor, FrameParams, FrameStage, compress_bound};
59use super::params::{CONTENTSIZE_UNKNOWN, WINDOWLOG_ABSOLUTEMIN, WINDOWLOG_MAX, ldm_enabled};
60use crate::error::{Error, Result};
61
62/// Bytes after the input buffer's ring, never part of the window: reads
63/// near the end of a segment stay inside the allocation.
64const IN_BUFF_SLACK: usize = 32;
65/// Gap between the ring and input appended after it (see
66/// [`StreamEncoder::compress`]'s shortcut): keeps that input non-contiguous
67/// with the window, as a separate buffer is in libzstd.
68const APPEND_GAP: usize = 64;
69
70/// What [`StreamEncoder::compress`] does after taking the input (libzstd's
71/// `ZSTD_EndDirective`).
72#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
73pub enum EndOp {
74 /// `ZSTD_e_continue`: compress whole blocks as they fill up; keep the
75 /// rest buffered.
76 Continue,
77 /// `ZSTD_e_flush`: also compress what is buffered (as a block that
78 /// does not end the frame) and write it out. Flushing often costs
79 /// compression ratio.
80 Flush,
81 /// `ZSTD_e_end`: compress everything and end the frame. The next call
82 /// starts a new frame.
83 End,
84}
85
86/// What one [`StreamEncoder::compress`] call did.
87#[derive(Debug, Clone, Copy, PartialEq, Eq)]
88pub struct CompressProgress {
89 /// Input bytes consumed.
90 pub read: usize,
91 /// Output bytes written.
92 pub written: usize,
93 /// Compressed bytes still waiting for room in the output (libzstd's
94 /// return value of `ZSTD_compressStream2`). After [`EndOp::Flush`],
95 /// 0 means the flush is complete; after [`EndOp::End`], that the frame
96 /// is complete.
97 pub remaining: usize,
98}
99
100/// `zcss_*`: the streaming stage.
101#[derive(Debug, Clone, Copy, PartialEq, Eq)]
102enum Stage {
103 /// No frame started: the next call starts one.
104 Init,
105 /// Loading input into the input buffer.
106 Load,
107 /// Writing out the output buffer.
108 Flush,
109}
110
111/// A streaming compressor (libzstd's `ZSTD_CStream` with
112/// `ZSTD_compressStream2`): feed it input in any pieces, get output in any
113/// pieces, frame after frame. The output is byte-identical to libzstd
114/// 1.5.7's for the same level, input, operations and output buffer sizes
115/// (see [`compress`](StreamEncoder::compress)). No `std` needed;
116/// [`Encoder`](crate::Encoder) wraps it as a `std::io::Write`.
117///
118/// ```
119/// use zstd_native::{EndOp, StreamEncoder};
120///
121/// let data = b"hello hello hello hello hello hello".repeat(100);
122/// let mut enc = StreamEncoder::new(3);
123/// let mut out = Vec::new();
124/// let mut buf = [0u8; 64];
125/// let mut input = &data[..];
126/// // Feed the input in pieces of 100 bytes, then end the frame.
127/// while !input.is_empty() {
128/// let n = input.len().min(100);
129/// let mut piece = &input[..n];
130/// while !piece.is_empty() {
131/// let p = enc.compress(piece, &mut buf, EndOp::Continue)?;
132/// piece = &piece[p.read..];
133/// out.extend_from_slice(&buf[..p.written]);
134/// }
135/// input = &input[n..];
136/// }
137/// loop {
138/// let p = enc.compress(&[], &mut buf, EndOp::End)?;
139/// out.extend_from_slice(&buf[..p.written]);
140/// if p.remaining == 0 {
141/// break;
142/// }
143/// }
144/// assert_eq!(zstd_native::decompress(&out)?, data);
145/// # Ok::<(), zstd_native::Error>(())
146/// ```
147///
148/// At level 22 with a window of 128 MiB, i.e. for unknown sizes and sizes
149/// over 64 MiB, libzstd enables long distance matching by itself, and so
150/// does this encoder, with the same output (and libzstd's memory use: over
151/// 800 MiB for the tables and the input buffer).
152pub struct StreamEncoder {
153 level: i32,
154 /// `ZSTD_c_windowLog` (0: the level's).
155 window_log: u32,
156 /// `ZSTD_c_enableLongDistanceMatching` set to enable (else auto).
157 force_ldm: bool,
158 /// `pledgedSrcSizePlusOne - 1` for the next or current frame.
159 pledged: Option<u64>,
160 /// The frame parameters of the next frames.
161 fparams: FrameParams,
162 stage: Stage,
163 fc: Option<Box<FrameCompressor>>,
164 /// `inBuff`: `in_buff_size` bytes of ring and [`IN_BUFF_SLACK`].
165 in_buff: Vec<u8>,
166 in_buff_size: usize,
167 in_to_compress: usize,
168 in_buff_pos: usize,
169 in_buff_target: usize,
170 /// `outBuff`: `compress_bound(blockSize) + 1` bytes once used.
171 out_buff: Vec<u8>,
172 out_content: usize,
173 out_flushed: usize,
174 frame_ended: bool,
175 /// The dictionary of the next frames.
176 dict: DictSlot,
177 /// Multithreading parameters of the next frames.
178 #[cfg(feature = "std")]
179 mt_params: super::mt::MtParams,
180 /// The multithreaded context, once used.
181 #[cfg(feature = "std")]
182 mt: Option<Box<super::mt::MtCtx>>,
183 /// The current frame is compressed by [`mt`](Self::mt).
184 #[cfg(feature = "std")]
185 mt_on: bool,
186}
187
188impl core::fmt::Debug for StreamEncoder {
189 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
190 f.debug_struct("StreamEncoder")
191 .field("level", &self.level)
192 .field("stage", &self.stage)
193 .field("pledged", &self.pledged)
194 .field("workers", &self.workers_or_0())
195 .finish_non_exhaustive()
196 }
197}
198
199impl StreamEncoder {
200 /// A streaming compressor for `level` (see [`compress`](crate::compress)).
201 pub fn new(level: i32) -> Self {
202 StreamEncoder {
203 level,
204 window_log: 0,
205 force_ldm: false,
206 pledged: None,
207 fparams: FrameParams::default(),
208 stage: Stage::Init,
209 fc: None,
210 in_buff: Vec::new(),
211 in_buff_size: 0,
212 in_to_compress: 0,
213 in_buff_pos: 0,
214 in_buff_target: 0,
215 out_buff: Vec::new(),
216 out_content: 0,
217 out_flushed: 0,
218 frame_ended: false,
219 dict: DictSlot::None,
220 #[cfg(feature = "std")]
221 mt_params: super::mt::MtParams::default(),
222 #[cfg(feature = "std")]
223 mt: None,
224 #[cfg(feature = "std")]
225 mt_on: false,
226 }
227 }
228
229 /// The worker count (0 without `std`).
230 fn workers_or_0(&self) -> u32 {
231 #[cfg(feature = "std")]
232 return self.mt_params.workers;
233 #[cfg(not(feature = "std"))]
234 0
235 }
236
237 /// Compresses the next frames with `n` worker threads (libzstd's
238 /// `ZSTD_c_nbWorkers`; at most 256, 64 on 32-bit targets); 0, the
239 /// default, compresses in the calling thread. The output is
240 /// byte-identical to libzstd's with the same worker count, see
241 /// [`Compressor::set_workers`](crate::Compressor::set_workers) for how
242 /// frames are cut into jobs, threads and memory.
243 ///
244 /// A frame whose pledged size (or, when the first call ends it, input
245 /// size) is at most 512 KiB is still compressed in the calling thread.
246 /// Otherwise, input is buffered until a job is full (or a flush or the
247 /// end comes), then compressed by a worker while more input is taken:
248 /// [`compress`](Self::compress) with [`EndOp::Continue`] returns once
249 /// it has taken some input or written some output (waiting for the
250 /// oldest job when it could do neither), and the output does not
251 /// depend on the output buffer sizes.
252 ///
253 /// # Errors
254 ///
255 /// [`Error::StageWrong`] in the middle of a frame.
256 #[cfg(feature = "std")]
257 pub fn set_workers(&mut self, n: u32) -> Result<()> {
258 if self.stage != Stage::Init {
259 return Err(Error::StageWrong);
260 }
261 self.mt_params.set_workers(n);
262 Ok(())
263 }
264
265 /// The worker thread count (see [`set_workers`](Self::set_workers)).
266 #[cfg(feature = "std")]
267 pub fn workers(&self) -> u32 {
268 self.mt_params.workers
269 }
270
271 /// Sets the job size of multithreaded compression, from the next frame
272 /// on (see [`Compressor::set_job_size`](crate::Compressor::set_job_size)).
273 /// For tests.
274 #[cfg(feature = "std")]
275 #[doc(hidden)]
276 pub fn set_job_size(&mut self, size: usize) {
277 self.mt_params.set_job_size(size);
278 }
279
280 /// Sets the overlap log of multithreaded compression, from the next
281 /// frame on (see
282 /// [`Compressor::set_overlap_log`](crate::Compressor::set_overlap_log)).
283 /// For tests.
284 ///
285 /// # Panics
286 ///
287 /// If `log` is over 9.
288 #[cfg(feature = "std")]
289 #[doc(hidden)]
290 pub fn set_overlap_log(&mut self, log: u32) {
291 self.mt_params.set_overlap_log(log);
292 }
293
294 /// A streaming compressor for `level` with the dictionary `dict` (see
295 /// [`set_dictionary`](Self::set_dictionary)).
296 ///
297 /// # Errors
298 ///
299 /// [`Error::InvalidDictionary`] if a zstd-format dictionary is corrupt.
300 pub fn with_dictionary(level: i32, dict: &[u8]) -> Result<Self> {
301 let mut e = Self::new(level);
302 e.set_dictionary(dict)?;
303 Ok(e)
304 }
305
306 /// A streaming compressor with a prepared dictionary, at its level (see
307 /// [`set_prepared_dictionary`](Self::set_prepared_dictionary)).
308 pub fn with_prepared_dictionary(dict: &EncoderDictionary) -> Self {
309 let mut e = Self::new(dict.level());
310 e.dict = DictSlot::Prepared(dict.inner.clone());
311 e
312 }
313
314 /// Changes the level, from the next frame on. With a prepared
315 /// dictionary, frames take the dictionary's level instead (see
316 /// [`Compressor::set_level`](crate::Compressor::set_level)).
317 pub fn set_level(&mut self, level: i32) {
318 self.level = level;
319 }
320
321 /// Uses `dict` for the next frames (libzstd's
322 /// `ZSTD_CCtx_loadDictionary`; see
323 /// [`Compressor::set_dictionary`](crate::Compressor::set_dictionary)),
324 /// replacing any dictionary; an empty `dict` removes it.
325 ///
326 /// # Errors
327 ///
328 /// [`Error::StageWrong`] in the middle of a frame,
329 /// [`Error::InvalidDictionary`] if a zstd-format dictionary is corrupt
330 /// (the encoder then has no dictionary).
331 pub fn set_dictionary(&mut self, dict: &[u8]) -> Result<()> {
332 if self.stage != Stage::Init {
333 return Err(Error::StageWrong);
334 }
335 self.dict = DictSlot::None;
336 self.dict = DictSlot::local(dict)?;
337 Ok(())
338 }
339
340 /// Uses the prepared `dict` for the next frames, at its level (libzstd's
341 /// `ZSTD_CCtx_refCDict`), replacing any dictionary.
342 ///
343 /// # Errors
344 ///
345 /// [`Error::StageWrong`] in the middle of a frame.
346 pub fn set_prepared_dictionary(&mut self, dict: &EncoderDictionary) -> Result<()> {
347 if self.stage != Stage::Init {
348 return Err(Error::StageWrong);
349 }
350 self.dict = DictSlot::Prepared(dict.inner.clone());
351 Ok(())
352 }
353
354 /// Overrides the window log (libzstd's `ZSTD_c_windowLog`; 0 restores
355 /// the level's), from the next frame on. For tests.
356 ///
357 /// # Panics
358 ///
359 /// If `log` is neither 0 nor in `10..=31` (`10..=30` on 32-bit targets).
360 #[doc(hidden)]
361 pub fn set_window_log(&mut self, log: u32) {
362 assert!(
363 log == 0 || (WINDOWLOG_ABSOLUTEMIN..=WINDOWLOG_MAX).contains(&log),
364 "window log out of range"
365 );
366 self.window_log = log;
367 }
368
369 /// Forces long distance matching on (libzstd's
370 /// `ZSTD_c_enableLongDistanceMatching` set to `ZSTD_ps_enable`; `false`
371 /// restores the default, where it is enabled for `btopt` and above with
372 /// a window of at least 128 MiB), from the next frame on. The window log
373 /// then defaults to 27 (128 MiB) unless set with
374 /// [`set_window_log`](Self::set_window_log). For tests.
375 #[doc(hidden)]
376 pub fn set_long_distance_matching(&mut self, on: bool) {
377 self.force_ldm = on;
378 }
379
380 /// Declares the size of the next frame's content (libzstd's
381 /// `ZSTD_CCtx_setPledgedSrcSize`; `None`: unknown, the default). The
382 /// frame header then holds it, and the parameters are chosen for it
383 /// (a smaller window for small sizes). The frame must then get exactly
384 /// that many bytes. It applies to one frame only.
385 ///
386 /// # Errors
387 ///
388 /// [`Error::StageWrong`] in the middle of a frame.
389 pub fn set_pledged_src_size(&mut self, size: Option<u64>) -> Result<()> {
390 if self.stage != Stage::Init {
391 return Err(Error::StageWrong);
392 }
393 self.pledged = size;
394 Ok(())
395 }
396
397 /// Ends the next frames with a content checksum (libzstd's
398 /// `ZSTD_c_checksumFlag`; off by default; see
399 /// [`Compressor::set_checksum`](crate::Compressor::set_checksum)).
400 ///
401 /// # Errors
402 ///
403 /// [`Error::StageWrong`] in the middle of a frame.
404 pub fn set_checksum(&mut self, on: bool) -> Result<()> {
405 self.set_fparams(|fp| fp.checksum = on)
406 }
407
408 /// Writes the content size into the next frames' headers when it is
409 /// known (libzstd's `ZSTD_c_contentSizeFlag`; on by default; see
410 /// [`Compressor::set_content_size_flag`](crate::Compressor::set_content_size_flag)).
411 /// The pledged size still chooses the parameters and is still checked.
412 ///
413 /// # Errors
414 ///
415 /// [`Error::StageWrong`] in the middle of a frame.
416 pub fn set_content_size_flag(&mut self, on: bool) -> Result<()> {
417 self.set_fparams(|fp| fp.content_size = on)
418 }
419
420 /// Writes the dictionary's ID into the next frames' headers (libzstd's
421 /// `ZSTD_c_dictIDFlag`; on by default; see
422 /// [`Compressor::set_dict_id_flag`](crate::Compressor::set_dict_id_flag)).
423 ///
424 /// # Errors
425 ///
426 /// [`Error::StageWrong`] in the middle of a frame.
427 pub fn set_dict_id_flag(&mut self, on: bool) -> Result<()> {
428 self.set_fparams(|fp| fp.dict_id = on)
429 }
430
431 fn set_fparams(&mut self, f: impl FnOnce(&mut FrameParams)) -> Result<()> {
432 if self.stage != Stage::Init {
433 return Err(Error::StageWrong);
434 }
435 f(&mut self.fparams);
436 Ok(())
437 }
438
439 /// Abandons the current frame, if any (libzstd's `ZSTD_CCtx_reset`
440 /// with `ZSTD_reset_session_only`): the next call starts a new one. The
441 /// pledged source size is forgotten; the level is kept.
442 pub fn reset(&mut self) {
443 self.stage = Stage::Init;
444 self.pledged = None;
445 self.out_content = 0;
446 self.out_flushed = 0;
447 self.frame_ended = false;
448 #[cfg(feature = "std")]
449 if core::mem::take(&mut self.mt_on)
450 && let Some(m) = self.mt.as_deref_mut()
451 {
452 m.abandon();
453 }
454 }
455
456 /// Whether no frame is in progress: the last frame was ended and all its
457 /// output was written (or nothing was compressed yet).
458 pub fn at_frame_boundary(&self) -> bool {
459 self.stage == Stage::Init
460 }
461
462 /// Compresses as much of `input` as possible into `output`, then does
463 /// what `op` asks (libzstd's `ZSTD_compressStream2`). Starts a frame if
464 /// none is in progress.
465 ///
466 /// With [`EndOp::Continue`], it consumes input until the output is full
467 /// (and may consume all of it while writing nothing). With
468 /// [`EndOp::Flush`] and [`EndOp::End`], call again (with the rest of
469 /// the input, if not all was read) until
470 /// [`remaining`](CompressProgress::remaining) is 0.
471 ///
472 /// The output matches libzstd's for the same calls with the same
473 /// input pieces and the same output buffer sizes. Without flushes, it
474 /// doesn't depend on how the input is split across [`EndOp::Continue`]
475 /// calls, nor on the output sizes as long as the frame ends with an
476 /// [`EndOp::End`] call that has no input (see the module docs for why
477 /// an `End` call with input may differ).
478 ///
479 /// # Errors
480 ///
481 /// [`Error::SrcSizeWrong`] if a frame gets more or less input than its
482 /// pledged size. After an error the frame is abandoned (as with
483 /// [`reset`](Self::reset)).
484 pub fn compress(
485 &mut self,
486 input: &[u8],
487 output: &mut [u8],
488 op: EndOp,
489 ) -> Result<CompressProgress> {
490 let r = self.compress_generic(input, output, op);
491 if r.is_err() {
492 self.reset();
493 }
494 r
495 }
496
497 /// `ZSTD_CCtx_init_compressStream2`: starts a frame (with the
498 /// dictionary, if any: `ZSTD_compressBegin_internal`).
499 fn init(&mut self, op: EndOp, in_size: usize) -> Result<()> {
500 if op == EndOp::End {
501 self.pledged = Some(in_size as u64); // auto-determine pledgedSrcSize
502 }
503 let (cd, level) = self.dict.for_frame(self.level)?;
504 // ZSTD_getCParamsFromCCtxParams
505 let cp = frame_cparams(
506 level,
507 cd.as_deref(),
508 self.pledged,
509 self.window_log,
510 self.force_ldm,
511 );
512 // ZSTD_resolveEnableLdm
513 let ldm = self.force_ldm || ldm_enabled(&cp);
514 #[cfg(feature = "std")]
515 {
516 // do not invoke multi-threading when src size is too small
517 self.mt_on = self.mt_params.applies(self.pledged);
518 if self.mt_on {
519 let m = self
520 .mt
521 .get_or_insert_with(|| Box::new(super::mt::MtCtx::new()));
522 m.init_frame(&self.mt_params, cp, ldm, cd, self.pledged, self.fparams)?;
523 self.out_content = 0;
524 self.out_flushed = 0;
525 self.stage = Stage::Load;
526 self.frame_ended = false;
527 return Ok(());
528 }
529 }
530 let fc = FrameCompressor::start_frame(&mut self.fc, cp, cd.as_ref(), self.pledged, ldm);
531 fc.set_frame_params(self.fparams);
532 let bsm = fc.block_size_max;
533 let pledged = self.pledged.unwrap_or(CONTENTSIZE_UNKNOWN);
534 let window_size = (1u64 << cp.window_log).min(pledged).max(1) as usize;
535 self.in_buff_size = window_size + bsm;
536 self.in_to_compress = 0;
537 self.in_buff_pos = 0;
538 // for small input: avoid automatic flush on reaching end of block,
539 // since it would require to add a 3-bytes null block to end frame
540 self.in_buff_target = bsm + usize::from(bsm as u64 == pledged);
541 self.out_content = 0;
542 self.out_flushed = 0;
543 self.stage = Stage::Load;
544 self.frame_ended = false;
545 Ok(())
546 }
547
548 /// The frame is complete and written out: back to the init stage
549 /// (`ZSTD_CCtx_reset(ZSTD_reset_session_only)`).
550 fn end_session(&mut self) {
551 self.stage = Stage::Init;
552 self.pledged = None;
553 }
554
555 /// `ZSTD_compressStream_generic`.
556 fn compress_generic(
557 &mut self,
558 input: &[u8],
559 output: &mut [u8],
560 op: EndOp,
561 ) -> Result<CompressProgress> {
562 if self.stage == Stage::Init {
563 self.init(op, input.len())?;
564 }
565 #[cfg(feature = "std")]
566 if self.mt_on {
567 let m = self.mt.as_deref_mut().expect("multithreaded context");
568 let p = m.compress(input, output, op)?;
569 if op == EndOp::End && p.remaining == 0 {
570 // compression completed
571 self.mt_on = false;
572 self.end_session();
573 }
574 return Ok(p);
575 }
576 let mut ip = 0usize;
577 let mut opos = 0usize;
578 loop {
579 if self.stage == Stage::Load {
580 if op == EndOp::End
581 && output.len() - opos >= compress_bound(input.len() - ip)
582 && self.in_buff_pos == 0
583 {
584 // shortcut to compression pass directly into output buffer
585 opos += self.compress_end_direct(&mut output[opos..], &input[ip..])?;
586 ip = input.len();
587 self.frame_ended = true;
588 self.end_session();
589 break;
590 }
591 // complete loading into the input buffer
592 let need = self.in_buff_size + IN_BUFF_SLACK;
593 if self.in_buff.len() < need {
594 self.in_buff.resize(need, 0);
595 }
596 let loaded = (self.in_buff_target - self.in_buff_pos).min(input.len() - ip);
597 self.in_buff[self.in_buff_pos..self.in_buff_pos + loaded]
598 .copy_from_slice(&input[ip..ip + loaded]);
599 self.in_buff_pos += loaded;
600 ip += loaded;
601 if op == EndOp::Continue && self.in_buff_pos < self.in_buff_target {
602 // not enough input to fill a full block: stop here
603 break;
604 }
605 if op == EndOp::Flush && self.in_buff_pos == self.in_to_compress {
606 // empty
607 break;
608 }
609
610 // compress the current block (this stage cannot be stopped
611 // in the middle)
612 let fc = self.fc.as_deref_mut().expect("frame started");
613 let bsm = fc.block_size_max;
614 let i_size = self.in_buff_pos - self.in_to_compress;
615 let into_output = output.len() - opos >= compress_bound(i_size);
616 let dst: &mut [u8] = if into_output {
617 &mut output[opos..]
618 } else {
619 let n = compress_bound(bsm) + 1;
620 if self.out_buff.len() < n {
621 self.out_buff.resize(n, 0);
622 }
623 &mut self.out_buff[..]
624 };
625 let last = op == EndOp::End && ip == input.len();
626 let (s, e) = (self.in_to_compress, self.in_buff_pos);
627 let c_size = if last {
628 fc.compress_end(dst, &self.in_buff, s, e)?
629 } else {
630 fc.compress_continue(dst, &self.in_buff, s, e, false)?
631 };
632 self.frame_ended = last;
633 // prepare next block
634 self.in_buff_target = self.in_buff_pos + bsm;
635 if self.in_buff_target > self.in_buff_size {
636 self.in_buff_pos = 0;
637 self.in_buff_target = bsm;
638 }
639 debug_assert!(last || self.in_buff_target <= self.in_buff_size);
640 self.in_to_compress = self.in_buff_pos;
641 if into_output {
642 // no need to flush
643 opos += c_size;
644 if self.frame_ended {
645 self.end_session();
646 break;
647 }
648 continue;
649 }
650 self.out_content = c_size;
651 self.out_flushed = 0;
652 self.stage = Stage::Flush;
653 }
654
655 // flush stage
656 debug_assert!(self.stage == Stage::Flush);
657 let to_flush = self.out_content - self.out_flushed;
658 let flushed = to_flush.min(output.len() - opos);
659 output[opos..opos + flushed]
660 .copy_from_slice(&self.out_buff[self.out_flushed..self.out_flushed + flushed]);
661 opos += flushed;
662 self.out_flushed += flushed;
663 if to_flush != flushed {
664 // flush not fully completed, presumably because dst is too small
665 break;
666 }
667 self.out_content = 0;
668 self.out_flushed = 0;
669 if self.frame_ended {
670 self.end_session();
671 break;
672 }
673 self.stage = Stage::Load;
674 }
675 Ok(CompressProgress {
676 read: ip,
677 written: opos,
678 remaining: self.out_content - self.out_flushed,
679 })
680 }
681
682 /// libzstd's `ZSTD_compressEnd` on the caller's input, the shortcut of
683 /// `ZSTD_compressStream_generic`. At the start of a frame the window is
684 /// empty and `src` is compressed in place; after a wrap of the input
685 /// buffer, `src` is a new segment of the window, non-contiguous with
686 /// the buffered history: it is appended after the ring (behind a gap)
687 /// so that both are in one buffer.
688 fn compress_end_direct(&mut self, dst: &mut [u8], src: &[u8]) -> Result<usize> {
689 let fc = self.fc.as_deref_mut().expect("frame started");
690 if fc.stage == FrameStage::Init {
691 // nothing compressed in this frame yet: the window is empty
692 return fc.compress_end(dst, src, 0, src.len());
693 }
694 let start = self.in_buff.len().max(self.in_buff_size) + APPEND_GAP;
695 self.in_buff.resize(start, 0);
696 self.in_buff.extend_from_slice(src);
697 let r = fc.compress_end(dst, &self.in_buff, start, start + src.len());
698 self.in_buff.truncate(self.in_buff_size + IN_BUFF_SLACK);
699 r
700 }
701}
702
703impl Default for StreamEncoder {
704 /// A streaming compressor at the default level (3).
705 fn default() -> Self {
706 Self::new(super::params::CLEVEL_DEFAULT)
707 }
708}