pub struct CCtx<'a>(/* private fields */);Expand description
Compression context
It is recommended to allocate a single context per thread and re-use it for many compression operations.
§Worker threads and leaks
With CParameter::NbWorkers, the jobs of a frame run on worker threads,
which read the dictionary or prefix. Anything that abandons a frame in
progress waits for them, dropping the context included (see
CCtx::wait_for_workers()). A context that is leaked instead
(mem::forget, Box::leak, a reference cycle) never waits, so the
workers only ever read what the context owns, and leaks with it: a
dictionary it copied (CCtx::load_dictionary()) or holds
(CCtx::set_cdict(), and CCtx::ref_cdict() with alloc), or a
prefix it owns (set_prefix()).
A streaming frame that reads borrowed data is compressed on the calling
thread instead, as with NbWorkers(0). That is a prefix given to
CCtx::ref_prefix(), a dictionary made from borrowed bytes
(CDict::create_by_reference()). The parameters that only apply to worker
threads (JobSize, OverlapSizeLog, RSyncable) are still accepted, but
have no effect on that frame: only CCtx::frame_workers() tells.
Worker threads need the zstdmt feature, which enables alloc: a build
with worker threads always has the shared dictionary handles
CCtx::ref_cdict() relies on. Without the feature, NbWorkers is
refused, even when the linked zstd library has worker threads.
CCtx::compress2() and compress_with_*() never return with a frame
that reads borrowed data still in progress, so they use the workers with
borrowed data too. (The one-shot calls that take a compression level
never use worker threads.)
Implementations§
Source§impl<'a> CCtx<'a>
impl<'a> CCtx<'a>
Sourcepub fn try_create() -> Option<Self>
pub fn try_create() -> Option<Self>
Tries to create a new context.
Returns None if zstd returns a NULL pointer - may happen if allocation fails.
With the with-rust-allocator feature enabled, the context’s internal
allocations go through Rust’s global allocator instead of the C
runtime’s malloc.
Sourcepub fn compress<C: WriteBuf + ?Sized>(
&mut self,
dst: &mut C,
src: &[u8],
compression_level: CompressionLevel,
) -> SafeResult
pub fn compress<C: WriteBuf + ?Sized>( &mut self, dst: &mut C, src: &[u8], compression_level: CompressionLevel, ) -> SafeResult
Wraps the ZSTD_compressCCtx() function
Sourcepub fn compress2<C: WriteBuf + ?Sized>(
&mut self,
dst: &mut C,
src: &[u8],
) -> SafeResult
pub fn compress2<C: WriteBuf + ?Sized>( &mut self, dst: &mut C, src: &[u8], ) -> SafeResult
Compresses src into dst as one frame, with the parameters and the
dictionary or prefix set on this context.
This uses the worker threads of NbWorkers even when the frame reads
borrowed data: it then returns only once the frame is done, or
abandoned (when dst is too small, after waiting for the workers).
Otherwise, as with ZSTD_compress2(), a frame that does not fit in
dst is left in progress until the session is reset.
Wraps the ZSTD_compress2() function.
Sourcepub fn compress_using_dict<C: WriteBuf + ?Sized>(
&mut self,
dst: &mut C,
src: &[u8],
dict: &[u8],
compression_level: CompressionLevel,
) -> SafeResult
pub fn compress_using_dict<C: WriteBuf + ?Sized>( &mut self, dst: &mut C, src: &[u8], dict: &[u8], compression_level: CompressionLevel, ) -> SafeResult
Wraps the ZSTD_compress_usingDict() function.
Sourcepub fn compress_using_cdict<C: WriteBuf + ?Sized>(
&mut self,
dst: &mut C,
src: &[u8],
cdict: &CDict<'_>,
) -> SafeResult
pub fn compress_using_cdict<C: WriteBuf + ?Sized>( &mut self, dst: &mut C, src: &[u8], cdict: &CDict<'_>, ) -> SafeResult
Wraps the ZSTD_compress_usingCDict() function.
Sourcepub fn compress_with_cdict<C: WriteBuf + ?Sized>(
&mut self,
dst: &mut C,
src: &[u8],
cdict: &CDict<'_>,
) -> SafeResult
pub fn compress_with_cdict<C: WriteBuf + ?Sized>( &mut self, dst: &mut C, src: &[u8], cdict: &CDict<'_>, ) -> SafeResult
Compresses src into dst as one frame, with cdict for this call
only, and the other parameters set on this context.
The dictionary is only borrowed, and nothing keeps it once this
returns: unlike CCtx::ref_cdict(), this takes no handle (no
reference count to update), and leaves no dictionary alive in the
context. Like CCtx::compress2(), and unlike
CCtx::compress_using_cdict(), it uses the worker threads and the
context’s parameters (a checksum, say).
The dictionary the context referenced (CCtx::ref_cdict(),
CCtx::set_cdict()) is referenced again afterwards; a prefix is
not. With a dictionary loaded with
CCtx::load_dictionary(), which could not be loaded again, this
fails with a dictionary_wrong error: disable it first.
Sourcepub fn compress_with_prefix<C: WriteBuf + ?Sized>(
&mut self,
dst: &mut C,
src: &[u8],
prefix: &[u8],
) -> SafeResult
pub fn compress_with_prefix<C: WriteBuf + ?Sized>( &mut self, dst: &mut C, src: &[u8], prefix: &[u8], ) -> SafeResult
Compresses src into dst as one frame, with prefix as its
single-use dictionary, and the parameters set on this context.
The prefix is only borrowed for this call. Like
CCtx::compress2(), it uses the worker threads.
The prefix stands in for the dictionary, and for the parameters a
prepared one decides: this frame gets the context’s own (its
CompressionLevel, say), not the dictionary’s.
The dictionary the context referenced (CCtx::ref_cdict(),
CCtx::set_cdict()) is referenced again afterwards; another
prefix is not. With a dictionary loaded with
CCtx::load_dictionary(), which could not be loaded again, this
fails with a dictionary_wrong error: disable it first.
Sourcepub fn init(&mut self, compression_level: CompressionLevel) -> SafeResult
pub fn init(&mut self, compression_level: CompressionLevel) -> SafeResult
Initializes the context with the given compression level.
This is equivalent to running:
reset()set_parameter(CompressionLevel, compression_level)
Abandons the current frame, if any. With worker threads, this first
waits for its jobs, see CCtx::wait_for_workers().
Sourcepub fn init_src_size(
&mut self,
compression_level: CompressionLevel,
pledged_src_size: u64,
) -> SafeResult
👎Deprecated: Use reset, set_parameter, and set_pledged_src_size instead.
Available on crate feature experimental only.
pub fn init_src_size( &mut self, compression_level: CompressionLevel, pledged_src_size: u64, ) -> SafeResult
Use reset, set_parameter, and set_pledged_src_size instead.
experimental only.Wraps the ZSTD_initCStream_srcSize() function.
Sourcepub fn init_using_dict(
&mut self,
dict: &[u8],
compression_level: CompressionLevel,
) -> SafeResult
👎Deprecated: Use reset, set_parameter, and load_dictionary instead.
Available on crate feature experimental only.
pub fn init_using_dict( &mut self, dict: &[u8], compression_level: CompressionLevel, ) -> SafeResult
Use reset, set_parameter, and load_dictionary instead.
experimental only.Wraps the ZSTD_initCStream_usingDict() function.
Sourcepub fn init_using_cdict<'b>(&mut self, cdict: &CDict<'b>) -> SafeResultwhere
'b: 'a,
👎Deprecated: Use reset and ref_cdict instead.
Available on crate feature experimental only.
pub fn init_using_cdict<'b>(&mut self, cdict: &CDict<'b>) -> SafeResultwhere
'b: 'a,
Use reset and ref_cdict instead.
experimental only.Wraps the ZSTD_initCStream_usingCDict() function.
With alloc, the context keeps its own handle to the dictionary, see
CCtx::ref_cdict().
Sourcepub fn load_dictionary(&mut self, dict: &[u8]) -> SafeResult
pub fn load_dictionary(&mut self, dict: &[u8]) -> SafeResult
Tries to load a dictionary.
The dictionary content will be copied internally and does not need to be kept alive after calling this function.
If you need to use the same dictionary for multiple contexts, it may be more efficient to
create a CDict first, then loads that.
The dictionary will apply to all compressed frames, until a new dictionary is set.
Like zstd, this fails with a stage_wrong error while a frame is in
progress: reset the session first (see CCtx::wait_for_workers()).
Sourcepub fn load_dictionary_advanced(
&mut self,
dict: &[u8],
content_type: DictContentType,
) -> SafeResult
pub fn load_dictionary_advanced( &mut self, dict: &[u8], content_type: DictContentType, ) -> SafeResult
Loads a dictionary, read as content_type.
Like CCtx::load_dictionary(), which reads it as
DictContentType::Auto: the dictionary is copied.
Wraps the ZSTD_CCtx_loadDictionary_advanced() function.
Sourcepub fn ref_dictionary<'b>(
&mut self,
dict: &'b [u8],
content_type: DictContentType,
) -> SafeResultwhere
'b: 'a,
pub fn ref_dictionary<'b>(
&mut self,
dict: &'b [u8],
content_type: DictContentType,
) -> SafeResultwhere
'b: 'a,
Loads a dictionary without copying it, read as content_type.
The dictionary applies to all compressed frames, until a new one is
set. It is only borrowed: with worker threads, a streaming frame that
reads it runs on the calling thread, as with
CCtx::ref_prefix(), see CCtx.
As with CCtx::load_dictionary(), compress_with_*() refuses
to replace it, with a dictionary_wrong error.
Like zstd, this fails with a stage_wrong error while a frame is in
progress: reset the session first (see CCtx::wait_for_workers()).
Wraps the ZSTD_CCtx_loadDictionary_advanced() function.
Sourcepub fn ref_cdict<'b>(&mut self, cdict: &CDict<'b>) -> SafeResultwhere
'b: 'a,
Available on target_has_atomic=ptr and crate feature alloc only.
pub fn ref_cdict<'b>(&mut self, cdict: &CDict<'b>) -> SafeResultwhere
'b: 'a,
target_has_atomic=ptr and crate feature alloc only.References a prepared dictionary for the next frames.
The context keeps its own handle to it, so the dictionary itself is
not borrowed: it can come from a cache, a static or a local, and be
dropped before the context. Only the bytes a dictionary made with
CDict::create_by_reference() points into must outlive the
context.
Frames with it may use worker threads, unless it points into such
borrowed bytes: a streaming frame then runs on the calling thread,
see CCtx.
The dictionary decides the compression parameters (its level, say); the others stay the context’s.
Like zstd, this fails with a stage_wrong error while a frame is in
progress: reset the session first (see CCtx::wait_for_workers()).
Wraps the ZSTD_CCtx_refCDict() function.
Sourcepub fn set_cdict<'b>(&mut self, cdict: CDict<'b>) -> SafeResultwhere
'b: 'a,
pub fn set_cdict<'b>(&mut self, cdict: CDict<'b>) -> SafeResultwhere
'b: 'a,
References a prepared dictionary for the next frames, moving it into the context.
The dictionary is dropped if this fails (while a frame is in
progress, say). See CCtx::ref_cdict().
Sourcepub fn disable_dictionary(&mut self) -> SafeResult
pub fn disable_dictionary(&mut self) -> SafeResult
Return to “no-dictionary” mode.
This will disable any dictionary/prefix previously registered for future frames.
Like zstd, this fails with a stage_wrong error while a frame is in
progress: reset the session first (see CCtx::wait_for_workers()).
Sourcepub fn ref_prefix<'b>(&mut self, prefix: &'b [u8]) -> SafeResultwhere
'b: 'a,
pub fn ref_prefix<'b>(&mut self, prefix: &'b [u8]) -> SafeResultwhere
'b: 'a,
Use some prefix as single-use dictionary for the next compressed frame.
Just like a dictionary, decompression will need to be given the same prefix.
This is best used if the “prefix” looks like the data to be compressed.
The prefix is only borrowed: with worker threads, a streaming frame
that reads it runs on the calling thread, and the parameters that
need workers (RSyncable, say) have no effect on it, see
CCtx. set_prefix() takes a
prefix the context owns, which can use them.
Like zstd, this fails with a stage_wrong error while a frame is in
progress: reset the session first (see CCtx::wait_for_workers()).
Sourcepub fn set_prefix<P>(&mut self, prefix: P) -> SafeResult
Available on crate feature alloc only.
pub fn set_prefix<P>(&mut self, prefix: P) -> SafeResult
alloc only.Uses a prefix as single-use dictionary for the next compressed frame, owning it.
prefix gives the bytes without copying them: a Vec<u8>, an
Arc<[u8]> or Arc<Vec<u8>>, a memory map, a bytes::Bytes, a
&'static [u8]… The context keeps it for as long as zstd may read
it, so a frame that reads it may use worker threads, unlike with
CCtx::ref_prefix().
It is dropped when something takes its place or unloads it: another
dictionary or prefix, a reset of the parameters, one of the init*
methods, or a call to CCtx::compress_with_cdict() or
CCtx::compress_with_prefix(). Not when a frame is done with it:
zstd uses a prefix for one frame only, but the context does not
track which.
Like zstd, this fails with a stage_wrong error while a frame is in
progress: reset the session first (see CCtx::wait_for_workers()).
Sourcepub fn compress_stream<C: WriteBuf + ?Sized>(
&mut self,
output: &mut OutBuffer<'_, C>,
input: &mut InBuffer<'_>,
) -> SafeResult
pub fn compress_stream<C: WriteBuf + ?Sized>( &mut self, output: &mut OutBuffer<'_, C>, input: &mut InBuffer<'_>, ) -> SafeResult
Performs a step of a streaming compression operation.
This will read some data from input and/or write some data to output.
§Returns
A hint for the “ideal” amount of input data to provide in the next call.
This hint is only for performance purposes.
Wraps the ZSTD_compressStream() function.
Sourcepub fn compress_stream2<C: WriteBuf + ?Sized>(
&mut self,
output: &mut OutBuffer<'_, C>,
input: &mut InBuffer<'_>,
end_op: ZSTD_EndDirective,
) -> SafeResult
pub fn compress_stream2<C: WriteBuf + ?Sized>( &mut self, output: &mut OutBuffer<'_, C>, input: &mut InBuffer<'_>, end_op: ZSTD_EndDirective, ) -> SafeResult
Performs a step of a streaming compression operation.
This will read some data from input and/or write some data to output.
The end_op directive can be used to specify what to do after: nothing special, flush
internal buffers, or end the frame.
§Returns
An lower bound for the amount of data that still needs to be flushed out.
This is useful when flushing or ending the frame: you need to keep calling this function until it returns 0.
Wraps the ZSTD_compressStream2() function.
Sourcepub fn flush_stream<C: WriteBuf + ?Sized>(
&mut self,
output: &mut OutBuffer<'_, C>,
) -> SafeResult
pub fn flush_stream<C: WriteBuf + ?Sized>( &mut self, output: &mut OutBuffer<'_, C>, ) -> SafeResult
Flush any intermediate buffer.
To fully flush, you should keep calling this function until it returns Ok(0).
Wraps the ZSTD_flushStream() function.
Sourcepub fn end_stream<C: WriteBuf + ?Sized>(
&mut self,
output: &mut OutBuffer<'_, C>,
) -> SafeResult
pub fn end_stream<C: WriteBuf + ?Sized>( &mut self, output: &mut OutBuffer<'_, C>, ) -> SafeResult
Ends the stream.
You should keep calling this function until it returns Ok(0).
Wraps the ZSTD_endStream() function.
Sourcepub fn frame_workers(&self) -> u32
pub fn frame_workers(&self) -> u32
How many worker threads the frame in progress uses, or the next frame will use if none is in progress.
This is the NbWorkers set with CCtx::set_parameter(), as zstd
clamped it to its bounds, unless that frame reads borrowed data (a
prefix given to CCtx::ref_prefix(), say): a streaming frame then
runs on the calling thread, see
CCtx. compress2() always may
use the workers.
zstd itself compresses a frame it knows to be short (512 KiB at most) on the calling thread, which this does not tell.
Sourcepub fn wait_for_workers(&mut self) -> SafeResult
pub fn wait_for_workers(&mut self) -> SafeResult
Abandons the current frame, if any, and waits for the worker threads to be done with it.
With CParameter::NbWorkers, the jobs of a frame run on worker
threads, reading the dictionary. Anything that abandons a frame in
progress waits for them first: a session reset (and init(), which
implies one), a one-shot compression, and dropping the context. This
is the same as reset(SessionOnly). Waiting first compresses what was
left of the frame’s input as one more job, and throws the result away.
After a job failed on a worker thread (for instance because the frame
was given more than its pledged size), the context refuses any
frame that would use the workers while NbWorkers is set (a
streaming frame that reads borrowed data does not), and setting
it again (with a stage_wrong error): zstd up to 1.5.7 can leave a
cleared job behind that the next multithreaded frame would hand to a
worker, which crashes. Create a new context then, or set NbWorkers
to 0.
Once a ZSTD_e_end call took all of its input, a frame takes no more:
that is refused with a stage_wrong error too, instead of the worker
threads waiting forever for a job after the last one.
Sourcepub fn sizeof(&self) -> usize
pub fn sizeof(&self) -> usize
Returns the size currently used by this context.
This may change over time.
Sourcepub fn reset(&mut self, reset: ResetDirective) -> SafeResult
pub fn reset(&mut self, reset: ResetDirective) -> SafeResult
Resets the state of the context.
Depending on the reset mode, it can reset the session, the parameters, or both.
Resetting the session abandons the frame in progress, if any: with
worker threads, this first waits for its jobs, see
CCtx::wait_for_workers(). Like zstd, resetting only the parameters
fails with a stage_wrong error while a frame is in progress.
Wraps the ZSTD_CCtx_reset() function.
Sourcepub fn set_parameter(&mut self, param: CParameter) -> SafeResult
pub fn set_parameter(&mut self, param: CParameter) -> SafeResult
Sets a compression parameter.
Some of these parameters need to be set during de-compression as well.
Like zstd, changing NbWorkers fails with a stage_wrong error while
a frame is in progress, and so does setting it to a non-zero value
after a multithreaded call failed (see CCtx::wait_for_workers()).
NbWorkers and StableOutBuffer cannot be used together.
Without the zstdmt feature, a non-zero NbWorkers fails with a
parameter_unsupported error, as it does in a zstd library built
without worker threads, even when the linked library has them.
Sourcepub fn set_pledged_src_size(
&mut self,
pledged_src_size: Option<u64>,
) -> SafeResult
pub fn set_pledged_src_size( &mut self, pledged_src_size: Option<u64>, ) -> SafeResult
Guarantee that the input size will be this value.
If given None, assumes the size is unknown.
Unless explicitly disabled, this will cause the size to be written in the compressed frame header.
If the actual data given to compress has a different size, an error will be returned.
Sourcepub fn get_block_size(&self) -> usize
👎Deprecated: The block API is deprecated; use the normal compression API instead.
Available on crate feature experimental only.
pub fn get_block_size(&self) -> usize
The block API is deprecated; use the normal compression API instead.
experimental only.Wraps the ZSTD_getBlockSize() function.
This is the largest block compress_block takes in the frame the
context has open. Before a block session started, that frame may not
be the session’s: a larger block is then refused with a srcSize_wrong
error. Starting a streaming frame first gives the session’s size, as
the session starts with the same parameters.
Sourcepub unsafe fn compress_block<C: WriteBuf + ?Sized>(
&mut self,
dst: &mut C,
src: &[u8],
) -> SafeResult
👎Deprecated: The block API is deprecated; use compress_stream2 instead.
Available on crate feature experimental only.
pub unsafe fn compress_block<C: WriteBuf + ?Sized>( &mut self, dst: &mut C, src: &[u8], ) -> SafeResult
The block API is deprecated; use compress_stream2 instead.
experimental only.Wraps the ZSTD_compressBlock() function.
The blocks of a session are compressed against each other, and
against the context’s dictionary or prefix. The first call starts the
session, with the parameters set on this context: it abandons the
frame in progress, if any, and the pledged source size with it. Any
other method of this context that takes &mut self ends the session,
and the next call starts a new one, from an empty history. The decoder
has to start a new session at the same points (see
DCtx::decompress_block()).
A call that fails ends the session too, and poisons the context, as a
failed streaming call does: block and streaming calls then return that
error until the context is reset (CCtx::reset()).
Returns an error once NbWorkers was set to a non-zero value on this
context.
§Safety
src becomes this context’s history window, so it must stay allocated and unmodified until
the session ends: until this call fails, or a call to another method of this context that
takes &mut self returns (or until this context is dropped), as the following blocks are
compressed against it.
Sourcepub fn in_size() -> usize
pub fn in_size() -> usize
Returns the recommended input buffer size.
Using this size may result in minor performance boost.
Sourcepub fn out_size() -> usize
pub fn out_size() -> usize
Returns the recommended output buffer size.
Using this may result in minor performance boost.
pub fn get_frame_progression(&self) -> FrameProgression
experimental only.