Skip to main content

StreamEncoder

Struct StreamEncoder 

Source
pub struct StreamEncoder { /* private fields */ }
Expand description

A streaming compressor (libzstd’s ZSTD_CStream with ZSTD_compressStream2): feed it input in any pieces, get output in any pieces, frame after frame. The output is byte-identical to libzstd 1.6.0’s for the same level, input, operations and output buffer sizes (see compress). No std needed; Encoder wraps it as a std::io::Write.

use zstd_native::{EndOp, StreamEncoder};

let data = b"hello hello hello hello hello hello".repeat(100);
let mut enc = StreamEncoder::new(3);
let mut out = Vec::new();
let mut buf = [0u8; 64];
let mut input = &data[..];
// Feed the input in pieces of 100 bytes, then end the frame.
while !input.is_empty() {
    let n = input.len().min(100);
    let mut piece = &input[..n];
    while !piece.is_empty() {
        let p = enc.compress(piece, &mut buf, EndOp::Continue)?;
        piece = &piece[p.read..];
        out.extend_from_slice(&buf[..p.written]);
    }
    input = &input[n..];
}
loop {
    let p = enc.compress(&[], &mut buf, EndOp::End)?;
    out.extend_from_slice(&buf[..p.written]);
    if p.remaining == 0 {
        break;
    }
}
assert_eq!(zstd_native::decompress(&out)?, data);

At level 22 with a window of 128 MiB, i.e. for unknown sizes and sizes over 64 MiB, libzstd enables long distance matching by itself, and so does this encoder, with the same output (and libzstd’s memory use: over 800 MiB for the tables and the input buffer).

Implementations§

Source§

impl StreamEncoder

Source

pub fn new(level: i32) -> Self

A streaming compressor for level (see compress).

Source

pub fn set_workers(&mut self, n: u32) -> Result<(), Error>

Available on crate feature std only.

Compresses the next frames with n worker threads (libzstd’s ZSTD_c_nbWorkers; at most 256, 64 on 32-bit targets); 0, the default, compresses in the calling thread. The output is byte-identical to libzstd’s with the same worker count, see Compressor::set_workers for how frames are cut into jobs, threads and memory.

A frame whose pledged size (or, when the first call ends it, input size) is at most 512 KiB is still compressed in the calling thread. Otherwise, input is buffered until a job is full (or a flush or the end comes), then compressed by a worker while more input is taken: compress with EndOp::Continue returns once it has taken some input or written some output (waiting for the oldest job when it could do neither), and the output does not depend on the output buffer sizes.

§Errors

Error::StageWrong in the middle of a frame.

Source

pub fn workers(&self) -> u32

Available on crate feature std only.

The worker thread count (see set_workers).

Source

pub fn with_dictionary(level: i32, dict: &[u8]) -> Result<Self, Error>

A streaming compressor for level with the dictionary dict (see set_dictionary).

§Errors

Error::InvalidDictionary if a zstd-format dictionary is corrupt.

Source

pub fn with_prepared_dictionary(dict: &EncoderDictionary) -> Self

A streaming compressor with a prepared dictionary, at its level (see set_prepared_dictionary).

Source

pub fn set_level(&mut self, level: i32)

Changes the level, from the next frame on. With a prepared dictionary, frames take the dictionary’s level instead (see Compressor::set_level).

Source

pub fn set_dictionary(&mut self, dict: &[u8]) -> Result<(), Error>

Uses dict for the next frames (libzstd’s ZSTD_CCtx_loadDictionary; see Compressor::set_dictionary), replacing any dictionary; an empty dict removes it.

§Errors

Error::StageWrong in the middle of a frame, Error::InvalidDictionary if a zstd-format dictionary is corrupt (the encoder then has no dictionary).

Source

pub fn set_prepared_dictionary( &mut self, dict: &EncoderDictionary, ) -> Result<(), Error>

Uses the prepared dict for the next frames, at its level (libzstd’s ZSTD_CCtx_refCDict), replacing any dictionary.

§Errors

Error::StageWrong in the middle of a frame.

Source

pub fn set_pledged_src_size(&mut self, size: Option<u64>) -> Result<(), Error>

Declares the size of the next frame’s content (libzstd’s ZSTD_CCtx_setPledgedSrcSize; None: unknown, the default). The frame header then holds it, and the parameters are chosen for it (a smaller window for small sizes). The frame must then get exactly that many bytes. It applies to one frame only.

§Errors

Error::StageWrong in the middle of a frame.

Source

pub fn set_checksum(&mut self, on: bool) -> Result<(), Error>

Ends the next frames with a content checksum (libzstd’s ZSTD_c_checksumFlag; off by default; see Compressor::set_checksum).

§Errors

Error::StageWrong in the middle of a frame.

Source

pub fn set_content_size_flag(&mut self, on: bool) -> Result<(), Error>

Writes the content size into the next frames’ headers when it is known (libzstd’s ZSTD_c_contentSizeFlag; on by default; see Compressor::set_content_size_flag). The pledged size still chooses the parameters and is still checked.

§Errors

Error::StageWrong in the middle of a frame.

Source

pub fn set_dict_id_flag(&mut self, on: bool) -> Result<(), Error>

Writes the dictionary’s ID into the next frames’ headers (libzstd’s ZSTD_c_dictIDFlag; on by default; see Compressor::set_dict_id_flag).

§Errors

Error::StageWrong in the middle of a frame.

Source

pub fn reset(&mut self)

Abandons the current frame, if any (libzstd’s ZSTD_CCtx_reset with ZSTD_reset_session_only): the next call starts a new one. The pledged source size is forgotten; the level is kept.

Source

pub fn at_frame_boundary(&self) -> bool

Whether no frame is in progress: the last frame was ended and all its output was written (or nothing was compressed yet).

Source

pub fn compress( &mut self, input: &[u8], output: &mut [u8], op: EndOp, ) -> Result<CompressProgress, Error>

Compresses as much of input as possible into output, then does what op asks (libzstd’s ZSTD_compressStream2). Starts a frame if none is in progress.

With EndOp::Continue, it consumes input until the output is full (and may consume all of it while writing nothing). With EndOp::Flush and EndOp::End, call again (with the rest of the input, if not all was read) until remaining is 0.

The output matches libzstd’s for the same calls with the same input pieces and the same output buffer sizes. Without flushes, it doesn’t depend on how the input is split across EndOp::Continue calls, nor on the output sizes as long as the frame ends with an EndOp::End call that has no input (see the module docs for why an End call with input may differ).

§Errors

Error::SrcSizeWrong if a frame gets more or less input than its pledged size. After an error the frame is abandoned (as with reset).

Trait Implementations§

Source§

impl Debug for StreamEncoder

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for StreamEncoder

Source§

fn default() -> Self

A streaming compressor at the default level (3).

Auto Trait Implementations§

§

impl !RefUnwindSafe for StreamEncoder

§

impl !UnwindSafe for StreamEncoder

§

impl Forget for StreamEncoder

§

impl Freeze for StreamEncoder
where *const FrameCompressor is !null: Freeze, PhantomData<FrameCompressor>: Freeze, *const u8 is !null: Freeze, PhantomData<u8>: Freeze, *const ArcInner<[u8]> is !null: Freeze, PhantomData<ArcInner<[u8]>>: Freeze, *const ArcInner<CDict> is !null: Freeze, PhantomData<ArcInner<CDict>>: Freeze, *const MtCtx is !null: Freeze, PhantomData<MtCtx>: Freeze,

§

impl Move for StreamEncoder

§

impl Send for StreamEncoder
where BoxRaw<FrameCompressor>: Send, RawVecInner: Send, Arc<[u8]>: Send, Arc<CDict>: Send, BoxRaw<MtCtx>: Send,

§

impl Sync for StreamEncoder
where BoxRaw<FrameCompressor>: Sync, RawVecInner: Sync, Arc<[u8]>: Sync, Arc<CDict>: Sync, BoxRaw<MtCtx>: Sync,

§

impl Unpin for StreamEncoder
where Box<FrameCompressor>: Unpin, *const u8 is !null: Unpin, Arc<[u8]>: Unpin, Arc<CDict>: Unpin, Box<MtCtx>: Unpin,

§

impl UnsafeUnpin for StreamEncoder
where *const FrameCompressor is !null: UnsafeUnpin, PhantomData<FrameCompressor>: UnsafeUnpin, *const u8 is !null: UnsafeUnpin, PhantomData<u8>: UnsafeUnpin, *const ArcInner<[u8]> is !null: UnsafeUnpin, PhantomData<ArcInner<[u8]>>: UnsafeUnpin, *const ArcInner<CDict> is !null: UnsafeUnpin, PhantomData<ArcInner<CDict>>: UnsafeUnpin, *const MtCtx is !null: UnsafeUnpin, PhantomData<MtCtx>: UnsafeUnpin,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.