Simple Compression
The simplest way to compress data is using theZSTD_compress() function, which compresses data in a single operation.
Calculate buffer size
Use This guarantees that the destination buffer will have enough space for compression.
ZSTD_compressBound() to determine the maximum size needed for the compressed output:Compress the data
Call The last parameter is the compression level (1-22). Level 1 is the fastest, while higher levels provide better compression at the cost of speed.
ZSTD_compress() with your source data and compression level:Complete Example
Here’s a complete compression function fromexamples/simple_compression.c:
Simple Decompression
Decompression follows a similar pattern but requires knowing the decompressed size.Get the original size
Extract the content size from the compressed frame header:By default, zstd writes the content size in the header when it is known.
Complete Example
Here’s a complete decompression function fromexamples/simple_decompression.c:
Compression Levels
Zstandard supports compression levels from 1 to 22:- Levels 1-3: Fast compression with moderate compression ratio
- Level 3: Default level (
ZSTD_CLEVEL_DEFAULT) - Levels 4-19: Progressively better compression at the cost of speed
- Levels 20-22: Ultra compression levels (require more memory)
- Negative levels: Even faster compression with lower ratios
Reusing Contexts
For better performance when compressing multiple files, reuse the compression context:ZSTD_DCtx.
Error Handling
Most zstd functions return asize_t value that should be checked for errors: