Skip to content

API Reference ​

Public API ​

Exported names can be used after using Zstandard; the other public names are used as Zstandard.name.

Zstandard.ZstandardCompressionContext Type
julia
ZstandardCompressionContext(; level=3, checksum=false, dict=nothing, long=false,
                       content_size=true, dict_id=true, magicless=false, prefix=nothing,
                       window_log, hash_log, chain_log, search_log, min_match,
                       target_length, strategy)

A compression context with fixed parameters, reused across calls (as a libzstd ZSTD_CCtx): its match-finder tables, entropy scratch and output buffer persist, and parameters are validated once. Use it with compress(ctx, data), or compress!(ctx, out, data) to write into a vector you reuse as well, which avoids allocating a result per call (worthwhile for many small inputs). The keywords mean the same as for compress.

A context must not be used by several tasks at the same time.

julia
ctx = ZstandardCompressionContext(level=5, checksum=true)
out = UInt8[]
for msg in messages
    compress!(ctx, out, msg)
    send(out)
end
source
Zstandard.ZstandardDecompressionContext Type
julia
ZstandardDecompressionContext(; dict=nothing, magicless=false, prefix=nothing)

A decompression context reused across calls (as a libzstd ZSTD_DCtx): its decoding tables persist. Use it with decompress(ctx, data), or decompress!(ctx, out, data) to decode into a vector you reuse. Data may hold several concatenated and skippable frames; dict is used for frames that need it. dict may also be a ZstandardDictionarySet (or a vector of ZstandardDictionary) to choose each frame's dictionary by its ID. With magicless=true, frames have no magic numbers (see compress).

A context must not be used by several tasks at the same time.

source
Zstandard.ZstandardFrameHeader Type
julia
ZstandardFrameHeader

Information from a Zstandard frame header, as returned by frame_header.

  • content_size: decompressed size, or nothing if the header does not record it

  • window_size: window size required to decode the frame

  • dict_id: dictionary ID, 0 if none

  • checksum: whether the frame ends with an XXH64 content checksum

  • single_segment: whether the frame is a single segment (window = content size)

  • header_size: size of the frame header in bytes, including the magic number

source
Zstandard.ZstandardSeekTable Type
julia
ZstandardSeekTable

The seek table of a seekable Zstandard archive (see compress_seekable): for each frame its compressed and decompressed sizes, offsets, and (if recorded) the low 32 bits of the XXH64 of its content. length(table) is the number of frames; table.content_size the total decompressed size.

source
Zstandard.ZstandardSequence Type
julia
ZstandardSequence(offset, literal_length, match_length)

One Zstandard sequence: literal_length literal bytes, then match_length bytes copied from offset bytes back (as libzstd's ZSTD_Sequence, with offset the actual distance, not a repeat-offset code). A sequence with offset == 0 and match_length == 0 is a block delimiter: its literals end the block.

Experimental

The sequence API mirrors an experimental libzstd feature (ZSTD_generateSequences, ZSTD_compressSequences and ZSTD_Sequence, available only with ZSTD_STATIC_LINKING_ONLY). It may change in a minor release of Zstandard.jl, for example to follow changes in libzstd.

source
Zstandard.ZstandardCompressor Function
julia
ZstandardCompressor(; level=3, checksum=false, dict=nothing, window_log=nothing, ...)

A TranscodingStreams.jl codec compressing to the Zstandard format, for use with transcode, TranscodingStream, etc. Available once TranscodingStreams is loaded. Accepts the parameter and frame keywords of compress (window_log, ..., content_size, dict_id, magicless), and size_hint (see ZstandardCompressorStream) for streams whose size is not pledged, and long and nthreads as for ZstandardCompressorStream.

TranscodingStreams does not pass flush on to codecs, so flushing a TranscodingStream does not make the data written so far decodable; write TranscodingStreams.TOKEN_END to end the frame, or use ZstandardCompressorStream, whose flush emits a block that decoders can read before the frame ends.

julia
using Zstandard, TranscodingStreams
compressed = transcode(ZstandardCompressor(level=5), data)
stream = TranscodingStream(ZstandardCompressor(), open("out.zst", "w"))
source
Zstandard.ZstandardDecompressor Function
julia
ZstandardDecompressor(; dict=nothing, max_window_size=128 MiB, magicless=false)

A TranscodingStreams.jl codec decoding Zstandard data (concatenated and skippable frames included). Frames with a window larger than max_window_size are rejected (see ZstandardDecompressorStream). With magicless=true, frames have no magic numbers (see compress). dict may be a ZstandardDictionary or several (a ZstandardDictionarySet or a vector), chosen per frame by dictionary ID. Available once TranscodingStreams is loaded.

source
Zstandard.compress! Method
julia
compress!(ctx::ZstandardCompressionContext, out::Vector{UInt8}, data) -> out

Compress data into out, which is resized to the compressed frame. Reusing out across calls avoids allocating (its capacity is kept by Julia).

source
Zstandard.compress Method
julia
compress(data; level=3, checksum=false, dict=nothing, nthreads=1, long=false,
         content_size=true, dict_id=true, magicless=false, prefix=nothing, rsyncable=false,
         target_block_size=nothing,
         window_log, hash_log, chain_log, search_log, min_match, target_length, strategy)
    -> Vector{UInt8}

Compress data (a byte vector or string) into a Zstandard frame.

level ranges from -7 (fastest) to 22 (strongest); 0 selects the default level 3, as in libzstd. With checksum=true an XXH64 content checksum is appended. With a ZstandardDictionary, its content serves as history and, for formatted dictionaries, its entropy tables and repeat offsets are used; the frame records the dictionary ID. When compressing many small inputs with one dictionary, pass a PreparedDictionary from prepare_dictionary instead: it is much faster, and its level is then used (a conflicting level throws an ArgumentError). Inputs larger than 1 GiB are written as several concatenated frames.

The remaining keywords override individual parameters of the level (each nothing, the default, keeps the level's value), with the meaning of libzstd's advanced parameters (ZSTD_c_windowLog etc.):

  • window_log (10-30): log2 of the maximum match distance (window size)

  • hash_log (6-27): log2 of the main hash table size

  • chain_log (6-28): log2 of the chain / secondary table size (unused by the greedy and lazy strategies, whose row-based match finder sizes rows from search_log, as in libzstd)

  • search_log (1-26): log2 of the number of match candidates searched

  • min_match (3-7): minimum match length searched for (the match finders use 4-7 for fast/dfast, 4-6 for greedy/lazy, 3-4 for btopt/btultra)

  • target_length (0-131072): for fast, a step size (acceleration); for btopt/btultra, a length taken without optimizing (unused by greedy/lazy, as in libzstd)

  • strategy: :fast, :dfast, :greedy, :lazy, :lazy2, :btlazy2, :btopt, :btultra or :btultra2 (libzstd's strategies)

Values out of range throw an ArgumentError. Parameters are adapted to the input size afterwards, as in libzstd (the window shrinks for small inputs). For example, compress(data; level=19, window_log=24) searches matches up to 16 MiB back. A window_log above 27 makes frames that streaming decoders reject by default (here and in libzstd): decode them with max_window_size set, as libzstd's --long=N, or one-shot with decompress.

With nthreads > 1, inputs larger than a few window sizes are split into jobs compressed in parallel tasks (within a single frame, as libzstd's nbWorkers); start Julia with several threads (julia -t N) to benefit. The output differs slightly from single-threaded compression. Not combined with dict or long (those always run on one thread).

With long=true, long-distance matching finds repetitions up to 128 MiB apart (as zstd --long); the frame then declares a window of up to 128 MiB, which decoders must be willing to allocate.

With target_block_size = n (1340 to 131072; libzstd's ZSTD_c_targetCBlockSize), blocks are split so that each compressed block is about n bytes, which lets a streaming decoder start on each sooner (lower latency, slightly lower ratio). Not applied to multithreaded jobs.

With rsyncable=true (as zstd --rsyncable), the input is cut into jobs at content-defined points (as libzstd's ZSTD_c_rsyncable): each job starts with fresh repeat offsets and entropy tables, so a local change to the input changes the output only near it, and rsync-style tools can transfer the difference efficiently. The ratio is slightly lower. Jobs run in parallel with nthreads > 1.

With prefix = bytes, those bytes serve as history the data may refer to (libzstd's ZSTD_CCtx_refPrefix, as zstd --patch-from): the frame records nothing about them, and must be decoded with the same prefix (decompress(frame; prefix=bytes)). Unless window_log is given, the window is widened to reach back into the whole prefix (up to 128 MiB); combine with long=true for large inputs. Not combined with dict.

Frame header options (libzstd's ZSTD_c_contentSizeFlag, ZSTD_c_dictIDFlag and ZSTD_f_zstd1_magicless): content_size=false leaves the content size out of the header, dict_id=false the dictionary ID (the decoder must then be given the right dictionary), and magicless=true omits the 4-byte magic number; such frames are decoded with decompress(data; magicless=true).

source
Zstandard.compress Method
julia
compress(ctx::ZstandardCompressionContext, data) -> Vector{UInt8}

Compress data (a byte vector or string) with the context's parameters.

source
Zstandard.compress_bound Method
julia
compress_bound(n) -> Int

Largest possible size of the frame compress produces for n bytes of input (libzstd's ZSTD_COMPRESSBOUND): n + n÷256, plus a little for inputs under 128 KiB. Useful to preallocate the output vector of compress!. (Seekable archives add their seek table on top.)

source
Zstandard.compress_seekable Method
julia
compress_seekable(data; frame_size=1 MiB, checksum=true, nthreads=1, level=3, ...) -> Vector{UInt8}

Compress data into the Zstandard seekable format (as libzstd's contrib/seekable_format): independent frames of frame_size bytes of content each (at most 1 GiB), followed by a seek table in a skippable frame. Any Zstandard decoder decodes the whole archive; decompress_range decodes just a range, touching only the frames it overlaps. With checksum=true the seek table records an XXH64-based checksum of each frame's content, verified on decoding. Frames are compressed in parallel on up to nthreads tasks. Other keywords (level, dict, window_log, ...) are passed to compress for each frame, except prefix and magicless=true, which decompress_range could not read back.

source
Zstandard.compress_sequences Method
julia
compress_sequences(data, seqs::AbstractVector{ZstandardSequence}; level=3, checksum=false,
                   validate=true) -> Vector{UInt8}

Encode data, described by the sequences seqs (as libzstd's ZSTD_compressSequences), into a Zstandard frame: the literals come from data, matches from the sequences. If seqs contains block delimiters (see ZstandardSequence), they set the blocks (each at most 128 KiB) and must cover data exactly; otherwise blocks of 128 KiB are formed, splitting sequences as needed, and bytes after the last sequence are literals (as libzstd's ZSTD_sf_explicitBlockDelimiters and ZSTD_sf_noBlockDelimiters). With validate=true every match is also checked against data (otherwise a wrong match silently changes what the frame decodes to). level selects the entropy coding effort.

Experimental

The sequence API mirrors an experimental libzstd feature (ZSTD_generateSequences, ZSTD_compressSequences and ZSTD_Sequence, available only with ZSTD_STATIC_LINKING_ONLY). It may change in a minor release of Zstandard.jl, for example to follow changes in libzstd.

source
Zstandard.decompress Function
julia
decompress(data::AbstractVector{UInt8}; dict=nothing, nthreads=Threads.nthreads())
decompress(data::AbstractVector{UInt8}, dict; kwargs...)

Decompress Zstandard compressed data, which may contain several concatenated and/or skippable frames. Optionally, a ZstandardDictionary can be provided, or several (a ZstandardDictionarySet or a vector of ZstandardDictionary) for data whose frames use different dictionaries, each chosen by the dictionary ID in the frame header. The dictionary may be passed as the dict keyword (as for compress) or as the second argument, not both. Throws a ZstandardError if the data is malformed.

When data holds several frames (at least 128 KiB in total), they are decoded in parallel on up to nthreads tasks; a single frame is always decoded on one thread. The result does not depend on nthreads.

With magicless=true, frames are read without magic numbers (as written by compress(data; magicless=true)); skippable frames cannot occur then. With prefix = bytes, frames written with that reference prefix are decoded (see compress).

source
Zstandard.decompress! Method
julia
decompress!(ctx::ZstandardDecompressionContext, out::Vector{UInt8}, data) -> out

Decompress data into out, which is resized to the decoded content. Reusing out across calls avoids allocating (its capacity is kept by Julia). If decoding throws, out is left empty.

source
Zstandard.decompress Method
julia
decompress(ctx::ZstandardDecompressionContext, data) -> Vector{UInt8}

Decompress data with the context (and its dictionary, if any).

source
Zstandard.decompress_bound Method
julia
decompress_bound(data; magicless=false) -> Int64

Upper bound on the decompressed size of all frames in data (as libzstd's ZSTD_decompressBound): a frame's recorded content size, or for frames that do not record it, its number of blocks times the largest block size its window allows. Skippable frames count as 0. Throws a ZstandardError for malformed or truncated data, and if the total overflows Int64.

source
Zstandard.decompress_range Method
julia
decompress_range(archive, range::UnitRange; table=seek_table(archive), dict=nothing) -> Vector{UInt8}

Decode bytes range (1-based) of the content of a seekable archive (a vector, or a seekable IO such as a file, from which only the needed frames are read). Only frames overlapping range are decoded. dict may be a ZstandardDictionary or several (see ZstandardDictionarySet).

source
Zstandard.decompressed_size Method
julia
decompressed_size(data) -> Union{Int64, Nothing}

Sum of the content sizes of all frames in data (skippable frames count as 0), or nothing if any frame does not record its content size. Throws a ZstandardError if the sizes (taken from untrusted headers) overflow Int64.

source
Zstandard.estimate_compression_memory Method
julia
estimate_compression_memory(; level=3, src_size=nothing, streaming=false, long=false,
                            nthreads=1, dict_size=0, window_log, ...) -> Int

Estimated bytes of working memory to compress with these settings (as libzstd's ZSTD_estimateCCtxSize / ZSTD_estimateCStreamSize): the match-finder tables sized for src_size (unknown when nothing, which sizes them for the level), entropy and parsing scratch, and either the one-shot output scratch (streaming=false) or the stream's window buffer (streaming=true). The input and the returned result are not counted. Parameter keywords are those of compress.

source
Zstandard.estimate_decompression_memory Method
julia
estimate_decompression_memory(; window_size=128 MiB, streaming=true) -> Int

Estimated bytes of working memory to decode frames with windows up to window_size (as libzstd's ZSTD_estimateDStreamSize): decoding tables, plus for streaming a buffer of two windows and two blocks (libzstd needs one window, as it wraps around; two avoid copying the window back for every block). One-shot decompress needs the decoding tables besides the decoded result itself.

source
Zstandard.frame_compressed_size Method
julia
frame_compressed_size(data; offset=1) -> Int

Total size in bytes of the (Zstandard or skippable) frame starting at offset, found by walking its block headers.

source
Zstandard.frame_content_size Method
julia
frame_content_size(data; offset=1) -> Union{Int64, Nothing}

Decompressed size recorded in the header of the frame at offset, or nothing if the frame does not record it. Skippable frames have size 0.

source
Zstandard.frame_dict_id Method
julia
frame_dict_id(data; offset=1) -> UInt32

Dictionary ID required by the frame at offset (0 if none).

source
Zstandard.frame_header Method
julia
frame_header(data; offset=1, magicless=false) -> ZstandardFrameHeader

Parse the header of the Zstandard frame starting at offset. Throws a ZstandardError for skippable frames, unknown magic numbers or truncated headers. With magicless=true, the frame has no magic number (see compress).

source
Zstandard.generate_sequences Method
julia
generate_sequences(data; level=3, window_log, ...) -> Vector{ZstandardSequence}

The sequences the compressor finds for data at level (as libzstd's ZSTD_generateSequences), block by block, each block ending with a delimiter carrying its trailing literals. compress_sequences(data, seqs) turns them back into a frame. Parameter keywords are those of compress.

Experimental

The sequence API mirrors an experimental libzstd feature (ZSTD_generateSequences, ZSTD_compressSequences and ZSTD_Sequence, available only with ZSTD_STATIC_LINKING_ONLY). It may change in a minor release of Zstandard.jl, for example to follow changes in libzstd.

source
Zstandard.is_skippable_frame Method
julia
is_skippable_frame(data; offset=1) -> Bool

Whether a skippable frame starts at offset.

source
Zstandard.is_zstandard_frame Method
julia
is_zstandard_frame(data; offset=1) -> Bool

Whether a Zstandard or skippable frame starts at offset (checks the magic number).

source
Zstandard.read_skippable_frame Method
julia
read_skippable_frame(data; offset=1) -> (variant, content)

Read the skippable frame at offset, returning its magic-number variant and a copy of its content.

source
Zstandard.seek_table Method
julia
seek_table(archive::AbstractVector{UInt8}) -> ZstandardSeekTable
seek_table(io::IO) -> ZstandardSeekTable

Read the seek table at the end of a seekable archive (a vector, or a seekable IO such as a file). Throws a ZstandardError if there is none.

source
Zstandard.skippable_frame Method
julia
skippable_frame(content; variant=0) -> Vector{UInt8}

Build a skippable frame carrying content (user data ignored by decoders). variant (0-15) selects the magic number 0x184D2A50 + variant.

source
Zstandard.Decoder.ZstandardDictionary Type
julia
ZstandardDictionary

A parsed Zstandard dictionary (raw content or formatted with entropy tables). Create with parse_dictionary. Use dictionary_id and dictionary_content to inspect it; its fields are internal.

source
Zstandard.Decoder.ZstandardDictionary Method
julia
ZstandardDictionary(content::AbstractVector{UInt8})

A raw-content dictionary (ID 0): content is used as history preceding the data, without entropy tables. Same as parse_dictionary for data that does not start with the dictionary magic number.

source
Zstandard.Decoder.ZstandardDictionarySet Type
julia
ZstandardDictionarySet(dicts; default=nothing)
ZstandardDictionarySet(dicts::ZstandardDictionary...; default=nothing)

Several dictionaries for decoding data whose frames use different dictionaries (as libzstd's ZSTD_d_refMultipleDDicts). Each frame's dictionary is chosen by the dictionary ID in its header:

  • A frame with a nonzero ID uses the dictionary with that ID; if the set has none, decoding throws a ZstandardError.

  • A frame with ID 0 uses default, or no dictionary when default is nothing.

A frame header does not say whether an ID-0 frame was written without a dictionary, with a raw-content dictionary, or with a formatted dictionary and dict_id=false, so every ID-0 frame gets the same default. A raw-content default is harmless for frames written without a dictionary. A formatted default is not in general: frames are decoded starting from its repeat offsets, so if those differ from the standard 1, 4, 8 (trained dictionaries keep the standard ones), a frame written without a dictionary can decode to wrong bytes. Use a formatted default only when the ID-0 frames in the data were written with it.

A dictionary with ID 0 (raw content) among dicts becomes the default; at most one default can be given. Two dictionaries with the same ID but different contents throw an ArgumentError; repeating the same dictionary (or an equal copy, such as the same file parsed twice) is allowed. A default with a nonzero ID is also selected by its ID.

Anywhere a decoder accepts a ZstandardDictionary (decompress, ZstandardDecompressionContext, ZstandardDecompressorStream, ZstandardDecompressor, decompress_range), it also accepts a ZstandardDictionarySet or a vector of dictionaries.

The set iterates over its dictionaries (the default included); s[id] returns the dictionary a frame with dictionary ID id would use (id = 0: the default), throwing a KeyError if there is none, and haskey(s, id) tells whether there is one.

julia
d1 = parse_dictionary(train_dictionary(samples1))
d2 = parse_dictionary(train_dictionary(samples2))
data = vcat(compress(a; dict=d1), compress(b; dict=d2))
decompress(data, ZstandardDictionarySet(d1, d2)) == vcat(a, b)
source
Zstandard.Decoder.ZstandardError Type
julia
ZstandardError(msg)

Exception thrown when Zstandard data is malformed or cannot be decoded.

source
Zstandard.Decoder.dictionary_content Method
julia
dictionary_content(dict::ZstandardDictionary) -> Vector{UInt8}

The dictionary's content: the bytes that precede each frame's data as match history (for a formatted dictionary, what follows its entropy tables). The returned vector is the dictionary's own and must not be modified.

source
Zstandard.Decoder.dictionary_id Method
julia
dictionary_id(dict::ZstandardDictionary) -> UInt32

The dictionary's ID, as recorded in the frames compressed with it (libzstd's ZDICT_getDictID); 0 for a raw-content dictionary. Compare with frame_dict_id to find the dictionary a frame needs.

source
Zstandard.Decoder.parse_dictionary Method
julia
parse_dictionary(data::AbstractVector{UInt8}) -> ZstandardDictionary

Parse a Zstandard dictionary. Data starting with the dictionary magic number 0xEC30A437 is parsed as a formatted dictionary (ID, entropy tables, repeat offsets, content); anything else is treated as raw content with ID 0.

source
Zstandard.Decoder.ZstandardDictionary Method
julia
ZstandardDictionary(pd::PreparedDictionary) -> ZstandardDictionary

The dictionary pd was prepared from: the one to decompress its frames with.

source
Zstandard.Encoder.PreparedDictionary Type
julia
PreparedDictionary

A dictionary digested for compression at one level: match-finder tables with the dictionary content inserted, and its entropy tables, ready to be copied into a compression context. Create with prepare_dictionary. Read-only after creation, so it can be shared between tasks. Use compression_level and ZstandardDictionary(pd) to inspect it; its fields are internal.

source
Zstandard.Encoder.compression_level Method
julia
compression_level(pd::PreparedDictionary) -> Int

The level pd was prepared for, which every compression with it uses.

source
Zstandard.Encoder.finalize_dictionary Method
julia
finalize_dictionary(content, samples; level=3, dict_size=nothing, dict_id=nothing) -> Vector{UInt8}

Turn raw dictionary content into a formatted Zstandard dictionary: entropy tables are built from statistics of compressing samples with the content (as ZDICT_finalizeDictionary). The result is at most dict_size bytes (content is trimmed from the front if needed).

source
Zstandard.Encoder.prepare_dictionary Method
julia
prepare_dictionary(dict::ZstandardDictionary; level=3, params...) -> PreparedDictionary

Digest dict for compression at level. Pass the result as dict to compress, ZstandardCompressorStream or ZstandardCompressor; it compresses small inputs much faster than the plain dictionary (the output is still decoded with the plain ZstandardDictionary). The level is fixed: compressing with a different level throws an ArgumentError. Explicit compression parameters (window_log, hash_log, ...; see compress) are fixed at preparation as well.

source
Zstandard.Encoder.train_dictionary Method
julia
train_dictionary(samples; dict_size=112640, level=3, algorithm=:fastcover,
                 k=nothing, d=nothing, steps=8, f=20, nthreads=Threads.nthreads()) -> Vector{UInt8}

Train a formatted Zstandard dictionary from samples (a vector of byte vectors), as zstd --train: dictionary content is built from the most frequent segments of the samples, then entropy tables are added (finalize_dictionary). Use the result with parse_dictionary.

algorithm=:fastcover (libzstd's default) counts hashed dmers of d bytes (2^f buckets, f in 1:31); algorithm=:cover counts each distinct dmer exactly, once per sample (ZDICT_trainFromBuffer_cover; slower, sometimes better). Parameters not given are optimized, as ZDICT_optimizeTrainFromBuffer_*: segment sizes k from 50 to 2000 in steps steps and dmer sizes d of 6 and 8 are each tried by compressing a held-out quarter of the samples, in parallel on up to nthreads tasks (the result does not depend on it).

source
Zstandard.Streaming.ZstandardCompressorStream Type
julia
ZstandardCompressorStream(io::IO; level=3, checksum=false, dict=nothing, pledged_size=nothing,
                     close_io=true, size_hint=nothing, content_size=true, dict_id=true,
                     magicless=false, long=false, nthreads=1, window_log, ...)

A streaming Zstandard compressor implementing the writable IO interface. Data written to the stream is compressed into a single frame and written to io block by block. flush emits all pending data as a complete block, so everything written so far can be decoded.

Without pledged_size the frame header does not record the content size. With pledged_size = n, it does (so decoders can preallocate, and frame_content_size reports it), the compression parameters are sized to n as in one-shot compress, and exactly n bytes must be written: writing more throws an ArgumentError, and so does close after writing fewer.

Without a pledge, size_hint = n sizes the parameters for about n bytes (libzstd's ZSTD_c_srcSizeHint) without recording a size or limiting the input.

window_log, hash_log, chain_log, search_log, min_match, target_length and strategy override the level's parameters, content_size, dict_id, magicless and target_block_size set frame options, and prefix sets a reference prefix, as for compress (the window is sized for the prefix plus the pledged size or size hint). With long=true, long-distance matching finds repetitions up to 128 MiB apart, as for compress (the stream then buffers up to 128 MiB of history, less when a smaller pledged_size or size_hint is given). With nthreads > 1, input is cut into jobs compressed in parallel tasks (as libzstd's nbWorkers; jobs are four windows long, so the stream buffers that much); output is written as jobs complete, in order, and flush and close wait for them. nthreads > 1 is not combined with dict, prefix or long.

close finishes the frame and, if close_io is true, closes io (pass close_io=false to keep writing to io, e.g. an IOBuffer read afterwards).

source
Zstandard.Streaming.ZstandardDecompressorStream Type
julia
ZstandardDecompressorStream(io::IO; dict=nothing, max_window_size=128 MiB)
ZstandardDecompressorStream(io::IO, dict; kwargs...)

A streaming Zstandard decompressor that implements the IO interface. Decoded data is produced one block at a time; memory use is bounded by the frame's window size plus one block. Frames declaring a window larger than max_window_size (default 128 MiB, as libzstd) are rejected with a ZstandardError, so untrusted input cannot make the decoder allocate more; raise it to read frames written with a larger window (e.g. zstd --long=30). With magicless=true, frames are read without their magic number, and prefix decodes frames written with that reference prefix (see compress). dict may be a ZstandardDictionary or several (a ZstandardDictionarySet or a vector of ZstandardDictionary), chosen per frame by the frame's dictionary ID. It may be passed as the dict keyword or as the second argument, not both.

After a decoding error (a ZstandardError), the stream is unusable: later reads rethrow the same error (bytes decoded before it can still be read). Other exceptions, such as an interrupt or an error from io, are not sticky.

source
Zstandard.Streaming.stream_progress Method
julia
stream_progress(s::ZstandardDecompressorStream) -> (; consumed, produced, frames)
stream_progress(s::ZstandardCompressorStream) -> (; ingested, consumed, produced, flushed)

Progress of a streaming (de)compressor, as libzstd's ZSTD_getFrameProgression. For a decompressor: compressed bytes read from the source, bytes decoded so far (read or still buffered) and frames completed. For a compressor: bytes written to the stream, bytes of those compressed so far, compressed bytes produced and compressed bytes written to the underlying IO.

source
Base.parse Method
julia
parse(ZstandardDictionary, data::AbstractVector{UInt8}) -> ZstandardDictionary

Same as parse_dictionary(data).

source

Internals ​

These are implementation details and may change without notice.

Zstandard.Decoder.DecoderState Type
julia
DecoderState()

Reusable scratch space and entropy state for decoding. Not thread-safe; use one per task.

source
Zstandard.Decoder.FrameInfo Type
julia
FrameInfo

Parsed Zstandard frame header. content_size is -1 when absent.

source
Zstandard.Decoder.build_fse_table! Method

Build a packed FSE decoding table into table (resized to 2^al) from normalized counts norm[1:nsym]. vbase/vbits map symbols to value base/extra-bit counts.

source
Zstandard.Decoder.decode_compressed_block! Method

Decode one compressed block at src[1:len] and write its output at op. hist is the earliest valid match source within the output buffer (frame start); olimit bounds the output. Returns the new output pointer.

source
Zstandard.Decoder.decompress_frames Function
julia
decompress_frames(data, st, dicts; range=1:length(data)) -> Vector{UInt8}

Decode all (concatenated) frames in data[range] in memory. range must start and end on frame boundaries.

source
Zstandard.Decoder.match_copy! Method

Copy a match of length ml at distance offset to op from earlier output. May write up to WILDCOPY_SLACK bytes beyond op + ml.

source
Zstandard.Decoder.read_frame_info Method
julia
read_frame_info(p::Ptr{UInt8}, len) -> FrameInfo

Parse the frame header following the magic number at p[1:len].

source
Zstandard.Decoder.read_fse_header! Method

Read an FSE normalized-count header from p[1:len] into norm. Returns (nsym, accuracy_log, bytes_consumed).

source
Zstandard.Decoder.read_huf_table! Method

Decode a Huffman tree description at p[1:len] into table. Returns (tablelog, bytes_consumed, nsymbols); ws[1:nsymbols] holds the weights including the implied last one.

source
Zstandard.Decoder.wildcopy16 Method

Copy n bytes in 16-byte chunks. Requires dst - src >= 16 or no overlap; may overwrite up to 15 bytes past dst + n.

source
Zstandard.Decoder.wildcopy8 Method

Copy n bytes in 8-byte chunks. Requires dst - src >= 8; may overwrite up to 7 bytes past dst + n.

source
Zstandard.Encoder.OUT_SCRATCH_MAX Constant
julia
CompressionContext()

Reusable compression state (match-finder tables, entropy tables, scratch buffers). Not thread-safe; use one per task.

source
Zstandard.Encoder.PREPARED_DICT_SRC_HINT Constant

Input size a prepared dictionary's tables are sized for (dictionary plus this many bytes), like libzstd's CDicts, which are sized for small inputs. Inputs for which dictionary + input exceed the prepared window get parameters sized to the input and load the dictionary content afresh instead.

source
Zstandard.Encoder.FrameOptions Type
julia
FrameOptions(; content_size=true, dict_id=true, magicless=false)

Frame header options (libzstd's ZSTD_c_contentSizeFlag, ZSTD_c_dictIDFlag and the ZSTD_f_zstd1_magicless format): whether the header records the content size and the dictionary ID, and whether the frame starts with the magic number. A magicless frame can only be read by a decoder told to expect it.

source
Zstandard.Encoder.LdmState Type

Long-distance matching state, kept across calls so input can be scanned as it arrives (streaming): the bucketed table, the rolling hash and where it stands, and the long matches found so far (cur, consumed by parse_block_ldm!). Positions are 1-based offsets from the buffer base.

source
Zstandard.Encoder.ParameterOverrides Type
julia
ParameterOverrides

Explicit compression parameters replacing a level's defaults (-1 = unset). Build with parameter_overrides.

source
Zstandard.Encoder.StreamCompressor Type
julia
StreamCompressor(; level=3, checksum=false, dict=nothing, pledged_size=nothing)

Incremental compressor producing one frame. Input is fed with stream_write!; compressed bytes accumulate in sc.out[1:sc.olen] and are taken by the caller. Memory use is bounded by the window size of the level.

With pledged_size (or stream_pledge! before the first write), the frame header records that content size and the compression parameters are sized to it, as for one-shot compression. Exactly that many bytes must then be written before the frame is finished.

source
Zstandard.Encoder.accumulate_stats! Method

Parse sample with content as history and accumulate sequence statistics.

source
Zstandard.Encoder.apply_dict_entropy! Method

Start a frame that uses dict: repeat offsets and entropy tables come from it.

source
Zstandard.Encoder.block_size Method

Block size for parameters p: RFC 8878 limits blocks to Block_Maximum_Size = min(Window_Size, 128 KiB).

source
Zstandard.Encoder.bt_find_best Function

Best match at ip for btlazy2, updating the tree with [next, ip]. btlog is the tree's log2 size. A longer match replaces the best one only when its extra length pays for its larger offset, as libzstd does. Returns (length, offset, next); length 0 when ip lies in a region the tree skipped.

source
Zstandard.Encoder.bt_insert1! Function

Insert position ip into the tree. Returns how many positions may be skipped.

source
Zstandard.Encoder.collect_matches! Function

Collect matches at ip with strictly increasing lengths (repeat offsets first).

source
Zstandard.Encoder.compress_block! Function

Compress one block into out[pos]. Returns new pos.

source
Zstandard.Encoder.compress_frame! Method
julia
compress_frame!(cc, data, level; checksum=false) -> Vector{UInt8}

Compress data as a single Zstandard frame.

source
Zstandard.Encoder.compress_job! Method
julia
compress_job!(cc, p, level, data, job_start, job_end, overlap, last) -> Vector{UInt8}

Compress data[job_start:job_end] into blocks (no frame header), using up to overlap preceding bytes as history. Jobs other than the first start with invalidated repeat offsets and no previous entropy tables, so their output can follow any preceding job in the same frame.

source
Zstandard.Encoder.compression_parameters Function
julia
compression_parameters(level, src_size[, overrides]) -> CParams

Parameters for level, shrunk for small inputs as the reference implementation does (smaller tables for small data are faster and lose nothing).

source
Zstandard.Encoder.count_codes! Method

Histogram of the first n codes (values 0:maxcode) into counts, using four interleaved tables so runs of one code do not serialize on the increments (as libzstd's HIST_count).

source
Zstandard.Encoder.cover_ids Method

Dmer ids for COVER (ZDICT_trainFromBuffer_cover): one id per distinct dmer of d bytes (no hash collisions); freqs[id] counts the samples containing it, so a dmer repeated within one sample is not over-weighted.

source
Zstandard.Encoder.emit_parsed_block! Method

Encode the parsed sequences in cc.ss for source [bstart, bstart+n) as one block.

source
Zstandard.Encoder.emit_split_block! Method

Split the parsed block (cc.ss, source [bstart, bstart+n)) if that pays, and emit its parts. Returns the new output position, or 0 when not split.

source
Zstandard.Encoder.emit_target_blocks! Method

Split the parsed block so each part encodes to about target bytes (libzstd's ZSTD_c_targetCBlockSize, without its super-block encoding): parts of equal input size, as many as the block's trial cost needs. Returns the new output position, or 0 when the block already fits.

source
Zstandard.Encoder.encode_literals! Method

Encode literals into dst[pos]. Returns new pos.

source
Zstandard.Encoder.encode_sequences! Method

Encode the sequences section into dst[pos]. Returns new pos.

source
Zstandard.Encoder.fastcover_content Method

Build dictionary content from buf (training samples concatenated; at least 8 bytes of padding after ntrain) with the fastCover algorithm.

source
Zstandard.Encoder.fastcover_ids Method

Dmer ids for fastCover: a hash of the d bytes at each position (2^f ids); freqs[id] counts every occurrence.

source
Zstandard.Encoder.frame_header_bytes Function

Frame header bytes (as written by compress_frame!) for an input of n bytes.

source
Zstandard.Encoder.fse_cost Method

Approximate cost in bits of coding counts with norm (Inf if a symbol is missing).

source
Zstandard.Encoder.h3_find! Method

Insert positions [o.h3next, cur) into the 3-byte table; return its entry for cur.

source
Zstandard.Encoder.huf_codes! Method

Assign canonical codes (longest codes first, symbols ascending) as the decoder expects.

source
Zstandard.Encoder.huf_cost Method

Estimated encoded size in bytes of the literals with table t (Inf if a symbol is missing).

source
Zstandard.Encoder.huf_encode_stream Method

Huffman-encode src[0:n-1] as one bitstream at dst. Returns compressed size.

source
Zstandard.Encoder.huf_lengths! Method

Huffman code lengths for counts[1:maxsym+1], limited to maxbits.

source
Zstandard.Encoder.init_stats! Method

Initialize statistics for a block starting at src (n bytes).

source
Zstandard.Encoder.ldm_rebase! Method

Shift the state down by d positions (the stream buffer was compacted).

source
Zstandard.Encoder.ldm_scan! Method

Scan positions up to upto (the last byte available, 1-based) for long matches, appending them to st.cur. Matches are extended forwards over all available bytes. Positions before st.ipos (a dictionary or prefix) are only indexed.

source
Zstandard.Encoder.ldm_sequences Function
julia
ldm_sequences(base, from, to, window, min_match, hash_log, hist=from) -> LdmCursor

Find long matches in positions from:to of the buffer at base (positions hist:from-1 are indexed as history only).

source
Zstandard.Encoder.limit_lengths! Method

Limit code lengths to maxbits while keeping the prefix code complete.

source
Zstandard.Encoder.load_dict! Method

Insert dictionary positions [1, n) of base into the match-finder tables.

source
Zstandard.Encoder.load_history! Method

Insert history positions [from, to) of base into the match-finder tables.

source
Zstandard.Encoder.mt_job_layout Method
julia
mt_layout(n, level) -> (params, job_size, overlap)

Job layout for multithreaded compression of n bytes, after libzstd's defaults: jobs of four windows (at least 1 MiB), each loading part of the preceding data as history (libzstd's overlapLog: window/8 for fast..lazy, window/4 for lazy2 and btlazy2, window/2 for btopt and btultra, the whole window for btultra2).

source
Zstandard.Encoder.next_block_size Method

Size of the next block starting at p (remaining bytes left, blocks at most bmax): full 128 KiB blocks are split where the data changes, once the frame has saved at least 3 bytes so far (never for incompressible data).

source
Zstandard.Encoder.normalize_counts! Method

Normalize counts[1:maxsym+1] (sum total, at least two nonzero) to sum to 2^al. Low-frequency symbols get the "less than 1" probability -1.

source
Zstandard.Encoder.normalize_level Method

The level as compression uses it: clamped to MIN_LEVEL:MAX_LEVEL, with 0 meaning 3.

source
Zstandard.Encoder.optimal_table_log Method

Choose an accuracy log (FSE_optimalTableLog).

source
Zstandard.Encoder.parameter_overrides Method
julia
parameter_overrides(; window_log, hash_log, chain_log, search_log, min_match,
                      target_length, strategy) -> ParameterOverrides

Validate explicit compression parameters (each nothing = the level's value), with the meaning of libzstd's ZSTD_c_* parameters:

  • window_log (10-30): log2 of the maximum match distance (window size)

  • hash_log (6-27): log2 of the main hash table size

  • chain_log (6-28): log2 of the chain / secondary table size (unused by the greedy and lazy strategies, whose row-based match finder sizes rows from search_log, as in libzstd)

  • search_log (1-26): log2 of the number of match candidates searched

  • min_match (3-7): minimum match length searched for (the match finders use 4-7 for fast/dfast, 4-6 for greedy/lazy, 3-4 for btopt/btultra)

  • target_length (0-131072): for fast, a step size (acceleration); for btopt/btultra, a length taken without optimizing (unused by greedy/lazy, as in libzstd)

  • strategy: :fast, :dfast, :greedy, :lazy, :lazy2, :btlazy2, :btopt, :btultra or :btultra2 (libzstd's strategies)

Parameters are adapted to the input size afterwards, as in libzstd (e.g. the window shrinks for small inputs).

source
Zstandard.Encoder.parse_block_ldm! Method

Parse a block, splicing in the long matches from cur.

source
Zstandard.Encoder.parse_opt! Function

Optimal parse of [istart, iend). rep is the decoder's exact repeat-offset state at the block start. Returns the updated next_to_update.

As libzstd's ZSTD_compressBlock_opt_generic, DP states are "stretches": a match (mlen, off; mlen = 0 for none) followed by litlen literals, with the repeat offsets after that match.

source
Zstandard.Encoder.parse_range! Method

Parse [bstart, bend) and append its sequences (and trailing literals) to the sequence store. first marks the first range of a block (the optimal parser refreshes its statistics then).

source
Zstandard.Encoder.select_mode! Method

Pick the coding mode for one sequence field and prepare its CTable.

source
Zstandard.Encoder.select_segments Method

Build dictionary content of at most capacity bytes from buf (training samples concatenated; at least 8 bytes of padding after them), selecting the best segments of k bytes epoch by epoch as fastCover / COVER do, given each position's dmer id and the ids' frequencies (consumed). Returns the content (most useful segments last).

source
Zstandard.Encoder.stream_finish! Method

Finish the frame: compress remaining input as the last block and append the checksum.

source
Zstandard.Encoder.stream_flush! Method

Compress all pending input into a non-final block, so that it can be decoded.

source
Zstandard.Encoder.stream_pledge! Method
julia
stream_pledge!(sc::StreamCompressor, n)

Pledge that the next frame will contain exactly n bytes (a negative n means unknown). Must be called before the frame's first write.

source
Zstandard.Encoder.stream_write! Method
julia
stream_write!(sc, data::AbstractVector{UInt8})

Feed input. Full blocks are compressed as soon as more input follows them.

source
Zstandard.Encoder.sub_seqstore! Method

Copy sequences [a, b) of ss (with their literals; the block's trailing literals if tail) into sub.

source
Zstandard.Encoder.trial_cost Method

Encoded size of sequences [a, b) from the current entropy state, which is left unchanged.

source
Zstandard.Encoder.use_prepared Function

Whether pd's tables should be used for an input of n bytes at level (dictionary + input fit the prepared window); otherwise its dictionary is loaded normally.

source
Zstandard.Encoder.use_prepared! Method

Set up cc from a prepared dictionary (instead of reset_context! + loading the content).

source
Zstandard.Encoder.write_frame_header! Function

Write a frame header. src_size < 0 means unknown (no Frame_Content_Size); dict_id == 0 omits the dictionary ID.

source
Zstandard.Encoder.write_fse_header! Method

Write an FSE table description (normalized counts) at dst[pos]. Returns new pos.

source
Zstandard.Encoder.write_huf_tree! Method

Write the Huffman tree description for t to dst[pos]. Returns new pos, or 0 if not representable.

source
Zstandard.Encoder.zcount Method

Number of equal bytes at a and b, not reading at or beyond alimit.

source
Zstandard.Streaming.DEFAULT_MAX_WINDOW_SIZE Constant

Default largest window a streaming decoder accepts: 128 MiB, as libzstd's default windowLogMax of 27. Frames Zstandard.jl writes stay within it (long=true included) unless window_log above 27 is passed explicitly; such frames need a larger max_window_size here (or --long=N / windowLogMax with libzstd).

source
Zstandard.Streaming.StreamDecoder Type
julia
StreamDecoder(dict=nothing)

Incremental Zstandard decoder behind ZstandardDecompressorStream and the ZstandardDecompressor codec. Input is fed with feed! (at most needed bytes per call); decoded bytes collect in an internal buffer. Internal: use ZstandardDecompressorStream instead.

source
Zstandard.Streaming.at_boundary Method

True when the decoder is between frames (input may legitimately end here).

source
Zstandard.Streaming.feed! Method
julia
feed!(d::StreamDecoder, p::Ptr{UInt8}, n) -> consumed

Consume up to needed(d) of the n bytes at p, decoding as units complete.

source
Zstandard.Streaming.needed Method

Number of input bytes the decoder wants next (0 never happens).

source
Zstandard.XXHash.XXH64_IMPLEMENTATION Constant
julia
XXH64_IMPLEMENTATION :: ScopedValue{AbstractXXH64}

The XXH64 implementation used for frame checksums in the current scope (default NativeXXH64()). Scoped values propagate into tasks spawned within the scope, including the tasks of multithreaded compression and decoding.

source
Zstandard.XXHash.AbstractXXH64 Type
julia
AbstractXXH64

Supertype of XXH64 implementations used for Zstandard frame content checksums. To use another implementation, define a subtype T and four methods:

julia
xxh64(impl::T, p::Ptr{UInt8}, n::Int, seed::UInt64)::UInt64   # one-shot
xxh64_init(impl::T, seed::UInt64)                             # -> state
xxh64_update!(impl::T, state, p::Ptr{UInt8}, n::Int)          # -> state
xxh64_digest(impl::T, state)::UInt64                          # state not consumed

then run code with it via with_xxh64_implementation. The default is NativeXXH64. Only frame checksums use the selected implementation; internal hashing (long-distance matching, dictionary IDs) always uses the native code.

source
Zstandard.XXHash.ChecksumState Type

Streaming content checksum; keeps the implementation it was created with.

source
Zstandard.XXHash.NativeXXH64 Type
julia
NativeXXH64()

This package's XXH64 implementation (the default).

source
Zstandard.XXHash.XXH64State Type
julia
XXH64State(seed=0)

Incremental XXH64: feed data with update!(state, data) (or a pointer and length), then get the hash with digest!(state).

source
Zstandard.XXHash.with_xxh64_implementation Method
julia
with_xxh64_implementation(f, impl::AbstractXXH64)

Run f() with impl computing and verifying Zstandard frame checksums.

source
Zstandard.XXHash.xxh64 Function
julia
xxh64(p::Ptr{UInt8}, n, seed=0) -> UInt64
xxh64(data::AbstractVector{UInt8}, seed=0) -> UInt64
xxh64(s::AbstractString, seed=0) -> UInt64

XXH64 hash of n bytes at p, or of data. Non-contiguous vectors are read in place (no copy).

source