2 * Copyright (c) 2016-present, Yann Collet, Facebook, Inc.
5 * This source code is licensed under the BSD-style license found in the
6 * LICENSE file in the root directory of this source tree. An additional grant
7 * of patent rights can be found in the PATENTS file in the same directory.
10 #if defined (__cplusplus)
17 /* ====== Dependency ======*/
18 #include <stddef.h> /* size_t */
21 /* ===== ZSTDLIB_API : control library symbols visibility ===== */
22 #if defined(__GNUC__) && (__GNUC__ >= 4)
23 # define ZSTDLIB_VISIBILITY __attribute__ ((visibility ("default")))
25 # define ZSTDLIB_VISIBILITY
27 #if defined(ZSTD_DLL_EXPORT) && (ZSTD_DLL_EXPORT==1)
28 # define ZSTDLIB_API __declspec(dllexport) ZSTDLIB_VISIBILITY
29 #elif defined(ZSTD_DLL_IMPORT) && (ZSTD_DLL_IMPORT==1)
30 # define ZSTDLIB_API __declspec(dllimport) ZSTDLIB_VISIBILITY /* It isn't required but allows to generate better code, saving a function pointer load from the IAT and an indirect jump.*/
32 # define ZSTDLIB_API ZSTDLIB_VISIBILITY
36 /*******************************************************************************************************
39 zstd, short for Zstandard, is a fast lossless compression algorithm, targeting real-time compression scenarios
40 at zlib-level and better compression ratios. The zstd compression library provides in-memory compression and
41 decompression functions. The library supports compression levels from 1 up to ZSTD_maxCLevel() which is 22.
42 Levels >= 20, labeled `--ultra`, should be used with caution, as they require more memory.
43 Compression can be done in:
44 - a single step (described as Simple API)
45 - a single step, reusing a context (described as Explicit memory management)
46 - unbounded multiple steps (described as Streaming compression)
47 The compression ratio achievable on small data can be highly improved using compression with a dictionary in:
48 - a single step (described as Simple dictionary API)
49 - a single step, reusing a dictionary (described as Fast dictionary API)
51 Advanced experimental functions can be accessed using #define ZSTD_STATIC_LINKING_ONLY before including zstd.h.
52 These APIs shall never be used with a dynamic library.
53 They are not "stable", their definition may change in the future. Only static linking is allowed.
54 *********************************************************************************************************/
56 /*------ Version ------*/
57 #define ZSTD_VERSION_MAJOR 1
58 #define ZSTD_VERSION_MINOR 1
59 #define ZSTD_VERSION_RELEASE 4
61 #define ZSTD_LIB_VERSION ZSTD_VERSION_MAJOR.ZSTD_VERSION_MINOR.ZSTD_VERSION_RELEASE
62 #define ZSTD_QUOTE(str) #str
63 #define ZSTD_EXPAND_AND_QUOTE(str) ZSTD_QUOTE(str)
64 #define ZSTD_VERSION_STRING ZSTD_EXPAND_AND_QUOTE(ZSTD_LIB_VERSION)
66 #define ZSTD_VERSION_NUMBER (ZSTD_VERSION_MAJOR *100*100 + ZSTD_VERSION_MINOR *100 + ZSTD_VERSION_RELEASE)
67 ZSTDLIB_API unsigned ZSTD_versionNumber(void); /**< library version number; to be used when checking dll version */
70 /***************************************
72 ***************************************/
74 Compresses `src` content as a single zstd compressed frame into already allocated `dst`.
75 Hint : compression runs faster if `dstCapacity` >= `ZSTD_compressBound(srcSize)`.
76 @return : compressed size written into `dst` (<= `dstCapacity),
77 or an error code if it fails (which can be tested using ZSTD_isError()). */
78 ZSTDLIB_API size_t ZSTD_compress( void* dst, size_t dstCapacity,
79 const void* src, size_t srcSize,
80 int compressionLevel);
82 /*! ZSTD_decompress() :
83 `compressedSize` : must be the _exact_ size of some number of compressed and/or skippable frames.
84 `dstCapacity` is an upper bound of originalSize.
85 If user cannot imply a maximum upper bound, it's better to use streaming mode to decompress data.
86 @return : the number of bytes decompressed into `dst` (<= `dstCapacity`),
87 or an errorCode if it fails (which can be tested using ZSTD_isError()). */
88 ZSTDLIB_API size_t ZSTD_decompress( void* dst, size_t dstCapacity,
89 const void* src, size_t compressedSize);
91 /*! ZSTD_getDecompressedSize() :
92 * NOTE: This function is planned to be obsolete, in favour of ZSTD_getFrameContentSize.
93 * ZSTD_getFrameContentSize functions the same way, returning the decompressed size of a single
94 * frame, but distinguishes empty frames from frames with an unknown size, or errors.
96 * Additionally, ZSTD_findDecompressedSize can be used instead. It can handle multiple
97 * concatenated frames in one buffer, and so is more general.
98 * As a result however, it requires more computation and entire frames to be passed to it,
99 * as opposed to ZSTD_getFrameContentSize which requires only a single frame's header.
101 * 'src' is the start of a zstd compressed frame.
102 * @return : content size to be decompressed, as a 64-bits value _if known_, 0 otherwise.
103 * note 1 : decompressed size is an optional field, that may not be present, especially in streaming mode.
104 * When `return==0`, data to decompress could be any size.
105 * In which case, it's necessary to use streaming mode to decompress data.
106 * Optionally, application can still use ZSTD_decompress() while relying on implied limits.
107 * (For example, data may be necessarily cut into blocks <= 16 KB).
108 * note 2 : decompressed size is always present when compression is done with ZSTD_compress()
109 * note 3 : decompressed size can be very large (64-bits value),
110 * potentially larger than what local system can handle as a single memory segment.
111 * In which case, it's necessary to use streaming mode to decompress data.
112 * note 4 : If source is untrusted, decompressed size could be wrong or intentionally modified.
113 * Always ensure result fits within application's authorized limits.
114 * Each application can set its own limits.
115 * note 5 : when `return==0`, if precise failure cause is needed, use ZSTD_getFrameParams() to know more. */
116 ZSTDLIB_API unsigned long long ZSTD_getDecompressedSize(const void* src, size_t srcSize);
119 /*====== Helper functions ======*/
120 ZSTDLIB_API int ZSTD_maxCLevel(void); /*!< maximum compression level available */
121 ZSTDLIB_API size_t ZSTD_compressBound(size_t srcSize); /*!< maximum compressed size in worst case scenario */
122 ZSTDLIB_API unsigned ZSTD_isError(size_t code); /*!< tells if a `size_t` function result is an error code */
123 ZSTDLIB_API const char* ZSTD_getErrorName(size_t code); /*!< provides readable string from an error code */
126 /***************************************
127 * Explicit memory management
128 ***************************************/
129 /*= Compression context
130 * When compressing many times,
131 * it is recommended to allocate a context just once, and re-use it for each successive compression operation.
132 * This will make workload friendlier for system's memory.
133 * Use one context per thread for parallel execution in multi-threaded environments. */
134 typedef struct ZSTD_CCtx_s ZSTD_CCtx;
135 ZSTDLIB_API ZSTD_CCtx* ZSTD_createCCtx(void);
136 ZSTDLIB_API size_t ZSTD_freeCCtx(ZSTD_CCtx* cctx);
138 /*! ZSTD_compressCCtx() :
139 Same as ZSTD_compress(), requires an allocated ZSTD_CCtx (see ZSTD_createCCtx()). */
140 ZSTDLIB_API size_t ZSTD_compressCCtx(ZSTD_CCtx* ctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize, int compressionLevel);
142 /*= Decompression context
143 * When decompressing many times,
144 * it is recommended to allocate a context just once, and re-use it for each successive compression operation.
145 * This will make workload friendlier for system's memory.
146 * Use one context per thread for parallel execution in multi-threaded environments. */
147 typedef struct ZSTD_DCtx_s ZSTD_DCtx;
148 ZSTDLIB_API ZSTD_DCtx* ZSTD_createDCtx(void);
149 ZSTDLIB_API size_t ZSTD_freeDCtx(ZSTD_DCtx* dctx);
151 /*! ZSTD_decompressDCtx() :
152 * Same as ZSTD_decompress(), requires an allocated ZSTD_DCtx (see ZSTD_createDCtx()). */
153 ZSTDLIB_API size_t ZSTD_decompressDCtx(ZSTD_DCtx* ctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize);
156 /**************************
157 * Simple dictionary API
158 ***************************/
159 /*! ZSTD_compress_usingDict() :
160 * Compression using a predefined Dictionary (see dictBuilder/zdict.h).
161 * Note : This function loads the dictionary, resulting in significant startup delay.
162 * Note : When `dict == NULL || dictSize < 8` no dictionary is used. */
163 ZSTDLIB_API size_t ZSTD_compress_usingDict(ZSTD_CCtx* ctx,
164 void* dst, size_t dstCapacity,
165 const void* src, size_t srcSize,
166 const void* dict,size_t dictSize,
167 int compressionLevel);
169 /*! ZSTD_decompress_usingDict() :
170 * Decompression using a predefined Dictionary (see dictBuilder/zdict.h).
171 * Dictionary must be identical to the one used during compression.
172 * Note : This function loads the dictionary, resulting in significant startup delay.
173 * Note : When `dict == NULL || dictSize < 8` no dictionary is used. */
174 ZSTDLIB_API size_t ZSTD_decompress_usingDict(ZSTD_DCtx* dctx,
175 void* dst, size_t dstCapacity,
176 const void* src, size_t srcSize,
177 const void* dict,size_t dictSize);
180 /****************************
181 * Fast dictionary API
182 ****************************/
183 typedef struct ZSTD_CDict_s ZSTD_CDict;
185 /*! ZSTD_createCDict() :
186 * When compressing multiple messages / blocks with the same dictionary, it's recommended to load it just once.
187 * ZSTD_createCDict() will create a digested dictionary, ready to start future compression operations without startup delay.
188 * ZSTD_CDict can be created once and used by multiple threads concurrently, as its usage is read-only.
189 * `dictBuffer` can be released after ZSTD_CDict creation, as its content is copied within CDict */
190 ZSTDLIB_API ZSTD_CDict* ZSTD_createCDict(const void* dictBuffer, size_t dictSize, int compressionLevel);
192 /*! ZSTD_freeCDict() :
193 * Function frees memory allocated by ZSTD_createCDict(). */
194 ZSTDLIB_API size_t ZSTD_freeCDict(ZSTD_CDict* CDict);
196 /*! ZSTD_compress_usingCDict() :
197 * Compression using a digested Dictionary.
198 * Faster startup than ZSTD_compress_usingDict(), recommended when same dictionary is used multiple times.
199 * Note that compression level is decided during dictionary creation. */
200 ZSTDLIB_API size_t ZSTD_compress_usingCDict(ZSTD_CCtx* cctx,
201 void* dst, size_t dstCapacity,
202 const void* src, size_t srcSize,
203 const ZSTD_CDict* cdict);
206 typedef struct ZSTD_DDict_s ZSTD_DDict;
208 /*! ZSTD_createDDict() :
209 * Create a digested dictionary, ready to start decompression operation without startup delay.
210 * dictBuffer can be released after DDict creation, as its content is copied inside DDict */
211 ZSTDLIB_API ZSTD_DDict* ZSTD_createDDict(const void* dictBuffer, size_t dictSize);
213 /*! ZSTD_freeDDict() :
214 * Function frees memory allocated with ZSTD_createDDict() */
215 ZSTDLIB_API size_t ZSTD_freeDDict(ZSTD_DDict* ddict);
217 /*! ZSTD_decompress_usingDDict() :
218 * Decompression using a digested Dictionary.
219 * Faster startup than ZSTD_decompress_usingDict(), recommended when same dictionary is used multiple times. */
220 ZSTDLIB_API size_t ZSTD_decompress_usingDDict(ZSTD_DCtx* dctx,
221 void* dst, size_t dstCapacity,
222 const void* src, size_t srcSize,
223 const ZSTD_DDict* ddict);
226 /****************************
228 ****************************/
230 typedef struct ZSTD_inBuffer_s {
231 const void* src; /**< start of input buffer */
232 size_t size; /**< size of input buffer */
233 size_t pos; /**< position where reading stopped. Will be updated. Necessarily 0 <= pos <= size */
236 typedef struct ZSTD_outBuffer_s {
237 void* dst; /**< start of output buffer */
238 size_t size; /**< size of output buffer */
239 size_t pos; /**< position where writing stopped. Will be updated. Necessarily 0 <= pos <= size */
244 /*-***********************************************************************
245 * Streaming compression - HowTo
247 * A ZSTD_CStream object is required to track streaming operation.
248 * Use ZSTD_createCStream() and ZSTD_freeCStream() to create/release resources.
249 * ZSTD_CStream objects can be reused multiple times on consecutive compression operations.
250 * It is recommended to re-use ZSTD_CStream in situations where many streaming operations will be achieved consecutively,
251 * since it will play nicer with system's memory, by re-using already allocated memory.
252 * Use one separate ZSTD_CStream per thread for parallel execution.
254 * Start a new compression by initializing ZSTD_CStream.
255 * Use ZSTD_initCStream() to start a new compression operation.
256 * Use ZSTD_initCStream_usingDict() or ZSTD_initCStream_usingCDict() for a compression which requires a dictionary (experimental section)
258 * Use ZSTD_compressStream() repetitively to consume input stream.
259 * The function will automatically update both `pos` fields.
260 * Note that it may not consume the entire input, in which case `pos < size`,
261 * and it's up to the caller to present again remaining data.
262 * @return : a size hint, preferred nb of bytes to use as input for next function call
263 * or an error code, which can be tested using ZSTD_isError().
264 * Note 1 : it's just a hint, to help latency a little, any other value will work fine.
265 * Note 2 : size hint is guaranteed to be <= ZSTD_CStreamInSize()
267 * At any moment, it's possible to flush whatever data remains within internal buffer, using ZSTD_flushStream().
268 * `output->pos` will be updated.
269 * Note that some content might still be left within internal buffer if `output->size` is too small.
270 * @return : nb of bytes still present within internal buffer (0 if it's empty)
271 * or an error code, which can be tested using ZSTD_isError().
273 * ZSTD_endStream() instructs to finish a frame.
274 * It will perform a flush and write frame epilogue.
275 * The epilogue is required for decoders to consider a frame completed.
276 * Similar to ZSTD_flushStream(), it may not be able to flush the full content if `output->size` is too small.
277 * In which case, call again ZSTD_endStream() to complete the flush.
278 * @return : nb of bytes still present within internal buffer (0 if it's empty, hence compression completed)
279 * or an error code, which can be tested using ZSTD_isError().
281 * *******************************************************************/
283 typedef struct ZSTD_CStream_s ZSTD_CStream;
284 /*===== ZSTD_CStream management functions =====*/
285 ZSTDLIB_API ZSTD_CStream* ZSTD_createCStream(void);
286 ZSTDLIB_API size_t ZSTD_freeCStream(ZSTD_CStream* zcs);
288 /*===== Streaming compression functions =====*/
289 ZSTDLIB_API size_t ZSTD_initCStream(ZSTD_CStream* zcs, int compressionLevel);
290 ZSTDLIB_API size_t ZSTD_compressStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output, ZSTD_inBuffer* input);
291 ZSTDLIB_API size_t ZSTD_flushStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output);
292 ZSTDLIB_API size_t ZSTD_endStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output);
294 ZSTDLIB_API size_t ZSTD_CStreamInSize(void); /**< recommended size for input buffer */
295 ZSTDLIB_API size_t ZSTD_CStreamOutSize(void); /**< recommended size for output buffer. Guarantee to successfully flush at least one complete compressed block in all circumstances. */
299 /*-***************************************************************************
300 * Streaming decompression - HowTo
302 * A ZSTD_DStream object is required to track streaming operations.
303 * Use ZSTD_createDStream() and ZSTD_freeDStream() to create/release resources.
304 * ZSTD_DStream objects can be re-used multiple times.
306 * Use ZSTD_initDStream() to start a new decompression operation,
307 * or ZSTD_initDStream_usingDict() if decompression requires a dictionary.
308 * @return : recommended first input size
310 * Use ZSTD_decompressStream() repetitively to consume your input.
311 * The function will update both `pos` fields.
312 * If `input.pos < input.size`, some input has not been consumed.
313 * It's up to the caller to present again remaining data.
314 * If `output.pos < output.size`, decoder has flushed everything it could.
315 * @return : 0 when a frame is completely decoded and fully flushed,
316 * an error code, which can be tested using ZSTD_isError(),
317 * any other value > 0, which means there is still some decoding to do to complete current frame.
318 * The return value is a suggested next input size (a hint to improve latency) that will never load more than the current frame.
319 * *******************************************************************************/
321 typedef struct ZSTD_DStream_s ZSTD_DStream;
322 /*===== ZSTD_DStream management functions =====*/
323 ZSTDLIB_API ZSTD_DStream* ZSTD_createDStream(void);
324 ZSTDLIB_API size_t ZSTD_freeDStream(ZSTD_DStream* zds);
326 /*===== Streaming decompression functions =====*/
327 ZSTDLIB_API size_t ZSTD_initDStream(ZSTD_DStream* zds);
328 ZSTDLIB_API size_t ZSTD_decompressStream(ZSTD_DStream* zds, ZSTD_outBuffer* output, ZSTD_inBuffer* input);
330 ZSTDLIB_API size_t ZSTD_DStreamInSize(void); /*!< recommended size for input buffer */
331 ZSTDLIB_API size_t ZSTD_DStreamOutSize(void); /*!< recommended size for output buffer. Guarantee to successfully flush at least one complete block in all circumstances. */
333 #endif /* ZSTD_H_235446 */
336 #if defined(ZSTD_STATIC_LINKING_ONLY) && !defined(ZSTD_H_ZSTD_STATIC_LINKING_ONLY)
337 #define ZSTD_H_ZSTD_STATIC_LINKING_ONLY
339 /****************************************************************************************
340 * START OF ADVANCED AND EXPERIMENTAL FUNCTIONS
341 * The definitions in this section are considered experimental.
342 * They should never be used with a dynamic library, as they may change in the future.
343 * They are provided for advanced usages.
344 * Use them only in association with static linking.
345 * ***************************************************************************************/
347 /* --- Constants ---*/
348 #define ZSTD_MAGICNUMBER 0xFD2FB528 /* >= v0.8.0 */
349 #define ZSTD_MAGIC_SKIPPABLE_START 0x184D2A50U
351 #define ZSTD_CONTENTSIZE_UNKNOWN (0ULL - 1)
352 #define ZSTD_CONTENTSIZE_ERROR (0ULL - 2)
354 #define ZSTD_WINDOWLOG_MAX_32 27
355 #define ZSTD_WINDOWLOG_MAX_64 27
356 #define ZSTD_WINDOWLOG_MAX ((unsigned)(sizeof(size_t) == 4 ? ZSTD_WINDOWLOG_MAX_32 : ZSTD_WINDOWLOG_MAX_64))
357 #define ZSTD_WINDOWLOG_MIN 10
358 #define ZSTD_HASHLOG_MAX ZSTD_WINDOWLOG_MAX
359 #define ZSTD_HASHLOG_MIN 6
360 #define ZSTD_CHAINLOG_MAX (ZSTD_WINDOWLOG_MAX+1)
361 #define ZSTD_CHAINLOG_MIN ZSTD_HASHLOG_MIN
362 #define ZSTD_HASHLOG3_MAX 17
363 #define ZSTD_SEARCHLOG_MAX (ZSTD_WINDOWLOG_MAX-1)
364 #define ZSTD_SEARCHLOG_MIN 1
365 #define ZSTD_SEARCHLENGTH_MAX 7 /* only for ZSTD_fast, other strategies are limited to 6 */
366 #define ZSTD_SEARCHLENGTH_MIN 3 /* only for ZSTD_btopt, other strategies are limited to 4 */
367 #define ZSTD_TARGETLENGTH_MIN 4
368 #define ZSTD_TARGETLENGTH_MAX 999
370 #define ZSTD_FRAMEHEADERSIZE_MAX 18 /* for static allocation */
371 #define ZSTD_FRAMEHEADERSIZE_MIN 6
372 static const size_t ZSTD_frameHeaderSize_prefix = 5;
373 static const size_t ZSTD_frameHeaderSize_min = ZSTD_FRAMEHEADERSIZE_MIN;
374 static const size_t ZSTD_frameHeaderSize_max = ZSTD_FRAMEHEADERSIZE_MAX;
375 static const size_t ZSTD_skippableHeaderSize = 8; /* magic number + skippable frame length */
378 /*--- Advanced types ---*/
379 typedef enum { ZSTD_fast, ZSTD_dfast, ZSTD_greedy, ZSTD_lazy, ZSTD_lazy2, ZSTD_btlazy2, ZSTD_btopt, ZSTD_btopt2 } ZSTD_strategy; /* from faster to stronger */
382 unsigned windowLog; /**< largest match distance : larger == more compression, more memory needed during decompression */
383 unsigned chainLog; /**< fully searched segment : larger == more compression, slower, more memory (useless for fast) */
384 unsigned hashLog; /**< dispatch table : larger == faster, more memory */
385 unsigned searchLog; /**< nb of searches : larger == more compression, slower */
386 unsigned searchLength; /**< match length searched : larger == faster decompression, sometimes less compression */
387 unsigned targetLength; /**< acceptable match size for optimal parser (only) : larger == more compression, slower */
388 ZSTD_strategy strategy;
389 } ZSTD_compressionParameters;
392 unsigned contentSizeFlag; /**< 1: content size will be in frame header (when known) */
393 unsigned checksumFlag; /**< 1: generate a 32-bits checksum at end of frame, for error detection */
394 unsigned noDictIDFlag; /**< 1: no dictID will be saved into frame header (if dictionary compression) */
395 } ZSTD_frameParameters;
398 ZSTD_compressionParameters cParams;
399 ZSTD_frameParameters fParams;
402 /*= Custom memory allocation functions */
403 typedef void* (*ZSTD_allocFunction) (void* opaque, size_t size);
404 typedef void (*ZSTD_freeFunction) (void* opaque, void* address);
405 typedef struct { ZSTD_allocFunction customAlloc; ZSTD_freeFunction customFree; void* opaque; } ZSTD_customMem;
407 /***************************************
408 * Compressed size functions
409 ***************************************/
411 /*! ZSTD_findFrameCompressedSize() :
412 * `src` should point to the start of a ZSTD encoded frame or skippable frame
413 * `srcSize` must be at least as large as the frame
414 * @return : the compressed size of the frame pointed to by `src`, suitable to pass to
415 * `ZSTD_decompress` or similar, or an error code if given invalid input. */
416 ZSTDLIB_API size_t ZSTD_findFrameCompressedSize(const void* src, size_t srcSize);
418 /***************************************
419 * Decompressed size functions
420 ***************************************/
421 /*! ZSTD_getFrameContentSize() :
422 * `src` should point to the start of a ZSTD encoded frame
423 * `srcSize` must be at least as large as the frame header. A value greater than or equal
424 * to `ZSTD_frameHeaderSize_max` is guaranteed to be large enough in all cases.
425 * @return : decompressed size of the frame pointed to be `src` if known, otherwise
426 * - ZSTD_CONTENTSIZE_UNKNOWN if the size cannot be determined
427 * - ZSTD_CONTENTSIZE_ERROR if an error occurred (e.g. invalid magic number, srcSize too small) */
428 ZSTDLIB_API unsigned long long ZSTD_getFrameContentSize(const void *src, size_t srcSize);
430 /*! ZSTD_findDecompressedSize() :
431 * `src` should point the start of a series of ZSTD encoded and/or skippable frames
432 * `srcSize` must be the _exact_ size of this series
433 * (i.e. there should be a frame boundary exactly `srcSize` bytes after `src`)
434 * @return : the decompressed size of all data in the contained frames, as a 64-bit value _if known_
435 * - if the decompressed size cannot be determined: ZSTD_CONTENTSIZE_UNKNOWN
436 * - if an error occurred: ZSTD_CONTENTSIZE_ERROR
438 * note 1 : decompressed size is an optional field, that may not be present, especially in streaming mode.
439 * When `return==ZSTD_CONTENTSIZE_UNKNOWN`, data to decompress could be any size.
440 * In which case, it's necessary to use streaming mode to decompress data.
441 * Optionally, application can still use ZSTD_decompress() while relying on implied limits.
442 * (For example, data may be necessarily cut into blocks <= 16 KB).
443 * note 2 : decompressed size is always present when compression is done with ZSTD_compress()
444 * note 3 : decompressed size can be very large (64-bits value),
445 * potentially larger than what local system can handle as a single memory segment.
446 * In which case, it's necessary to use streaming mode to decompress data.
447 * note 4 : If source is untrusted, decompressed size could be wrong or intentionally modified.
448 * Always ensure result fits within application's authorized limits.
449 * Each application can set its own limits.
450 * note 5 : ZSTD_findDecompressedSize handles multiple frames, and so it must traverse the input to
451 * read each contained frame header. This is efficient as most of the data is skipped,
452 * however it does mean that all frame data must be present and valid. */
453 ZSTDLIB_API unsigned long long ZSTD_findDecompressedSize(const void* src, size_t srcSize);
456 /***************************************
457 * Advanced compression functions
458 ***************************************/
459 /*! ZSTD_estimateCCtxSize() :
460 * Gives the amount of memory allocated for a ZSTD_CCtx given a set of compression parameters.
461 * `frameContentSize` is an optional parameter, provide `0` if unknown */
462 ZSTDLIB_API size_t ZSTD_estimateCCtxSize(ZSTD_compressionParameters cParams);
464 /*! ZSTD_createCCtx_advanced() :
465 * Create a ZSTD compression context using external alloc and free functions */
466 ZSTDLIB_API ZSTD_CCtx* ZSTD_createCCtx_advanced(ZSTD_customMem customMem);
468 /*! ZSTD_sizeofCCtx() :
469 * Gives the amount of memory used by a given ZSTD_CCtx */
470 ZSTDLIB_API size_t ZSTD_sizeof_CCtx(const ZSTD_CCtx* cctx);
473 ZSTD_p_forceWindow, /* Force back-references to remain < windowSize, even when referencing Dictionary content (default:0) */
474 ZSTD_p_forceRawDict /* Force loading dictionary in "content-only" mode (no header analysis) */
475 } ZSTD_CCtxParameter;
476 /*! ZSTD_setCCtxParameter() :
477 * Set advanced parameters, selected through enum ZSTD_CCtxParameter
478 * @result : 0, or an error code (which can be tested with ZSTD_isError()) */
479 ZSTDLIB_API size_t ZSTD_setCCtxParameter(ZSTD_CCtx* cctx, ZSTD_CCtxParameter param, unsigned value);
481 /*! ZSTD_createCDict_byReference() :
482 * Create a digested dictionary for compression
483 * Dictionary content is simply referenced, and therefore stays in dictBuffer.
484 * It is important that dictBuffer outlives CDict, it must remain read accessible throughout the lifetime of CDict */
485 ZSTDLIB_API ZSTD_CDict* ZSTD_createCDict_byReference(const void* dictBuffer, size_t dictSize, int compressionLevel);
487 /*! ZSTD_createCDict_advanced() :
488 * Create a ZSTD_CDict using external alloc and free, and customized compression parameters */
489 ZSTDLIB_API ZSTD_CDict* ZSTD_createCDict_advanced(const void* dict, size_t dictSize, unsigned byReference,
490 ZSTD_parameters params, ZSTD_customMem customMem);
492 /*! ZSTD_sizeof_CDict() :
493 * Gives the amount of memory used by a given ZSTD_sizeof_CDict */
494 ZSTDLIB_API size_t ZSTD_sizeof_CDict(const ZSTD_CDict* cdict);
496 /*! ZSTD_getCParams() :
497 * @return ZSTD_compressionParameters structure for a selected compression level and estimated srcSize.
498 * `estimatedSrcSize` value is optional, select 0 if not known */
499 ZSTDLIB_API ZSTD_compressionParameters ZSTD_getCParams(int compressionLevel, unsigned long long estimatedSrcSize, size_t dictSize);
501 /*! ZSTD_getParams() :
502 * same as ZSTD_getCParams(), but @return a full `ZSTD_parameters` object instead of sub-component `ZSTD_compressionParameters`.
503 * All fields of `ZSTD_frameParameters` are set to default (0) */
504 ZSTDLIB_API ZSTD_parameters ZSTD_getParams(int compressionLevel, unsigned long long estimatedSrcSize, size_t dictSize);
506 /*! ZSTD_checkCParams() :
507 * Ensure param values remain within authorized range */
508 ZSTDLIB_API size_t ZSTD_checkCParams(ZSTD_compressionParameters params);
510 /*! ZSTD_adjustCParams() :
511 * optimize params for a given `srcSize` and `dictSize`.
512 * both values are optional, select `0` if unknown. */
513 ZSTDLIB_API ZSTD_compressionParameters ZSTD_adjustCParams(ZSTD_compressionParameters cPar, unsigned long long srcSize, size_t dictSize);
515 /*! ZSTD_compress_advanced() :
516 * Same as ZSTD_compress_usingDict(), with fine-tune control of each compression parameter */
517 ZSTDLIB_API size_t ZSTD_compress_advanced (ZSTD_CCtx* ctx,
518 void* dst, size_t dstCapacity,
519 const void* src, size_t srcSize,
520 const void* dict,size_t dictSize,
521 ZSTD_parameters params);
524 /*--- Advanced decompression functions ---*/
527 * Tells if the content of `buffer` starts with a valid Frame Identifier.
528 * Note : Frame Identifier is 4 bytes. If `size < 4`, @return will always be 0.
529 * Note 2 : Legacy Frame Identifiers are considered valid only if Legacy Support is enabled.
530 * Note 3 : Skippable Frame Identifiers are considered valid. */
531 ZSTDLIB_API unsigned ZSTD_isFrame(const void* buffer, size_t size);
533 /*! ZSTD_estimateDCtxSize() :
534 * Gives the potential amount of memory allocated to create a ZSTD_DCtx */
535 ZSTDLIB_API size_t ZSTD_estimateDCtxSize(void);
537 /*! ZSTD_createDCtx_advanced() :
538 * Create a ZSTD decompression context using external alloc and free functions */
539 ZSTDLIB_API ZSTD_DCtx* ZSTD_createDCtx_advanced(ZSTD_customMem customMem);
541 /*! ZSTD_sizeof_DCtx() :
542 * Gives the amount of memory used by a given ZSTD_DCtx */
543 ZSTDLIB_API size_t ZSTD_sizeof_DCtx(const ZSTD_DCtx* dctx);
545 /*! ZSTD_createDDict_byReference() :
546 * Create a digested dictionary, ready to start decompression operation without startup delay.
547 * Dictionary content is simply referenced, and therefore stays in dictBuffer.
548 * It is important that dictBuffer outlives DDict, it must remain read accessible throughout the lifetime of DDict */
549 ZSTDLIB_API ZSTD_DDict* ZSTD_createDDict_byReference(const void* dictBuffer, size_t dictSize);
551 /*! ZSTD_createDDict_advanced() :
552 * Create a ZSTD_DDict using external alloc and free, optionally by reference */
553 ZSTDLIB_API ZSTD_DDict* ZSTD_createDDict_advanced(const void* dict, size_t dictSize,
554 unsigned byReference, ZSTD_customMem customMem);
556 /*! ZSTD_sizeof_DDict() :
557 * Gives the amount of memory used by a given ZSTD_DDict */
558 ZSTDLIB_API size_t ZSTD_sizeof_DDict(const ZSTD_DDict* ddict);
560 /*! ZSTD_getDictID_fromDict() :
561 * Provides the dictID stored within dictionary.
562 * if @return == 0, the dictionary is not conformant with Zstandard specification.
563 * It can still be loaded, but as a content-only dictionary. */
564 ZSTDLIB_API unsigned ZSTD_getDictID_fromDict(const void* dict, size_t dictSize);
566 /*! ZSTD_getDictID_fromDDict() :
567 * Provides the dictID of the dictionary loaded into `ddict`.
568 * If @return == 0, the dictionary is not conformant to Zstandard specification, or empty.
569 * Non-conformant dictionaries can still be loaded, but as content-only dictionaries. */
570 ZSTDLIB_API unsigned ZSTD_getDictID_fromDDict(const ZSTD_DDict* ddict);
572 /*! ZSTD_getDictID_fromFrame() :
573 * Provides the dictID required to decompressed the frame stored within `src`.
574 * If @return == 0, the dictID could not be decoded.
575 * This could for one of the following reasons :
576 * - The frame does not require a dictionary to be decoded (most common case).
577 * - The frame was built with dictID intentionally removed. Whatever dictionary is necessary is a hidden information.
578 * Note : this use case also happens when using a non-conformant dictionary.
579 * - `srcSize` is too small, and as a result, the frame header could not be decoded (only possible if `srcSize < ZSTD_FRAMEHEADERSIZE_MAX`).
580 * - This is not a Zstandard frame.
581 * When identifying the exact failure cause, it's possible to used ZSTD_getFrameParams(), which will provide a more precise error code. */
582 ZSTDLIB_API unsigned ZSTD_getDictID_fromFrame(const void* src, size_t srcSize);
585 /********************************************************************
586 * Advanced streaming functions
587 ********************************************************************/
589 /*===== Advanced Streaming compression functions =====*/
590 ZSTDLIB_API ZSTD_CStream* ZSTD_createCStream_advanced(ZSTD_customMem customMem);
591 ZSTDLIB_API size_t ZSTD_initCStream_srcSize(ZSTD_CStream* zcs, int compressionLevel, unsigned long long pledgedSrcSize); /**< pledgedSrcSize must be correct, a size of 0 means unknown. for a frame size of 0 use initCStream_advanced */
592 ZSTDLIB_API size_t ZSTD_initCStream_usingDict(ZSTD_CStream* zcs, const void* dict, size_t dictSize, int compressionLevel); /**< note: a dict will not be used if dict == NULL or dictSize < 8 */
593 ZSTDLIB_API size_t ZSTD_initCStream_advanced(ZSTD_CStream* zcs, const void* dict, size_t dictSize,
594 ZSTD_parameters params, unsigned long long pledgedSrcSize); /**< pledgedSrcSize is optional and can be 0 (meaning unknown). note: if the contentSizeFlag is set, pledgedSrcSize == 0 means the source size is actually 0 */
595 ZSTDLIB_API size_t ZSTD_initCStream_usingCDict(ZSTD_CStream* zcs, const ZSTD_CDict* cdict); /**< note : cdict will just be referenced, and must outlive compression session */
596 ZSTDLIB_API size_t ZSTD_resetCStream(ZSTD_CStream* zcs, unsigned long long pledgedSrcSize); /**< re-use compression parameters from previous init; skip dictionary loading stage; zcs must be init at least once before. note: pledgedSrcSize must be correct, a size of 0 means unknown. for a frame size of 0 use initCStream_advanced */
597 ZSTDLIB_API size_t ZSTD_sizeof_CStream(const ZSTD_CStream* zcs);
600 /*===== Advanced Streaming decompression functions =====*/
601 typedef enum { DStream_p_maxWindowSize } ZSTD_DStreamParameter_e;
602 ZSTDLIB_API ZSTD_DStream* ZSTD_createDStream_advanced(ZSTD_customMem customMem);
603 ZSTDLIB_API size_t ZSTD_initDStream_usingDict(ZSTD_DStream* zds, const void* dict, size_t dictSize); /**< note: a dict will not be used if dict == NULL or dictSize < 8 */
604 ZSTDLIB_API size_t ZSTD_setDStreamParameter(ZSTD_DStream* zds, ZSTD_DStreamParameter_e paramType, unsigned paramValue);
605 ZSTDLIB_API size_t ZSTD_initDStream_usingDDict(ZSTD_DStream* zds, const ZSTD_DDict* ddict); /**< note : ddict will just be referenced, and must outlive decompression session */
606 ZSTDLIB_API size_t ZSTD_resetDStream(ZSTD_DStream* zds); /**< re-use decompression parameters from previous init; saves dictionary loading */
607 ZSTDLIB_API size_t ZSTD_sizeof_DStream(const ZSTD_DStream* zds);
610 /*********************************************************************
611 * Buffer-less and synchronous inner streaming functions
613 * This is an advanced API, giving full control over buffer management, for users which need direct control over memory.
614 * But it's also a complex one, with many restrictions (documented below).
615 * Prefer using normal streaming API for an easier experience
616 ********************************************************************* */
619 Buffer-less streaming compression (synchronous mode)
621 A ZSTD_CCtx object is required to track streaming operations.
622 Use ZSTD_createCCtx() / ZSTD_freeCCtx() to manage resource.
623 ZSTD_CCtx object can be re-used multiple times within successive compression operations.
625 Start by initializing a context.
626 Use ZSTD_compressBegin(), or ZSTD_compressBegin_usingDict() for dictionary compression,
627 or ZSTD_compressBegin_advanced(), for finer parameter control.
628 It's also possible to duplicate a reference context which has already been initialized, using ZSTD_copyCCtx()
630 Then, consume your input using ZSTD_compressContinue().
631 There are some important considerations to keep in mind when using this advanced function :
632 - ZSTD_compressContinue() has no internal buffer. It uses externally provided buffer only.
633 - Interface is synchronous : input is consumed entirely and produce 1+ (or more) compressed blocks.
634 - Caller must ensure there is enough space in `dst` to store compressed data under worst case scenario.
635 Worst case evaluation is provided by ZSTD_compressBound().
636 ZSTD_compressContinue() doesn't guarantee recover after a failed compression.
637 - ZSTD_compressContinue() presumes prior input ***is still accessible and unmodified*** (up to maximum distance size, see WindowLog).
638 It remembers all previous contiguous blocks, plus one separated memory segment (which can itself consists of multiple contiguous blocks)
639 - ZSTD_compressContinue() detects that prior input has been overwritten when `src` buffer overlaps.
640 In which case, it will "discard" the relevant memory section from its history.
642 Finish a frame with ZSTD_compressEnd(), which will write the last block(s) and optional checksum.
643 It's possible to use srcSize==0, in which case, it will write a final empty block to end the frame.
644 Without last block mark, frames will be considered unfinished (corrupted) by decoders.
646 `ZSTD_CCtx` object can be re-used (ZSTD_compressBegin()) to compress some new frame.
649 /*===== Buffer-less streaming compression functions =====*/
650 ZSTDLIB_API size_t ZSTD_compressBegin(ZSTD_CCtx* cctx, int compressionLevel);
651 ZSTDLIB_API size_t ZSTD_compressBegin_usingDict(ZSTD_CCtx* cctx, const void* dict, size_t dictSize, int compressionLevel);
652 ZSTDLIB_API size_t ZSTD_compressBegin_advanced(ZSTD_CCtx* cctx, const void* dict, size_t dictSize, ZSTD_parameters params, unsigned long long pledgedSrcSize); /**< pledgedSrcSize is optional and can be 0 (meaning unknown). note: if the contentSizeFlag is set, pledgedSrcSize == 0 means the source size is actually 0 */
653 ZSTDLIB_API size_t ZSTD_copyCCtx(ZSTD_CCtx* cctx, const ZSTD_CCtx* preparedCCtx, unsigned long long pledgedSrcSize); /**< note: if pledgedSrcSize can be 0, indicating unknown size. if it is non-zero, it must be accurate. for 0 size frames, use compressBegin_advanced */
654 ZSTDLIB_API size_t ZSTD_compressBegin_usingCDict(ZSTD_CCtx* cctx, const ZSTD_CDict* cdict, unsigned long long pledgedSrcSize); /**< note: if pledgedSrcSize can be 0, indicating unknown size. if it is non-zero, it must be accurate. for 0 size frames, use compressBegin_advanced */
655 ZSTDLIB_API size_t ZSTD_compressContinue(ZSTD_CCtx* cctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize);
656 ZSTDLIB_API size_t ZSTD_compressEnd(ZSTD_CCtx* cctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize);
661 Buffer-less streaming decompression (synchronous mode)
663 A ZSTD_DCtx object is required to track streaming operations.
664 Use ZSTD_createDCtx() / ZSTD_freeDCtx() to manage it.
665 A ZSTD_DCtx object can be re-used multiple times.
667 First typical operation is to retrieve frame parameters, using ZSTD_getFrameParams().
668 It fills a ZSTD_frameParams structure which provide important information to correctly decode the frame,
669 such as the minimum rolling buffer size to allocate to decompress data (`windowSize`),
670 and the dictionary ID used.
671 (Note : content size is optional, it may not be present. 0 means : content size unknown).
672 Note that these values could be wrong, either because of data malformation, or because an attacker is spoofing deliberate false information.
673 As a consequence, check that values remain within valid application range, especially `windowSize`, before allocation.
674 Each application can set its own limit, depending on local restrictions. For extended interoperability, it is recommended to support at least 8 MB.
675 Frame parameters are extracted from the beginning of the compressed frame.
676 Data fragment must be large enough to ensure successful decoding, typically `ZSTD_frameHeaderSize_max` bytes.
677 @result : 0 : successful decoding, the `ZSTD_frameParams` structure is correctly filled.
678 >0 : `srcSize` is too small, please provide at least @result bytes on next attempt.
679 errorCode, which can be tested using ZSTD_isError().
681 Start decompression, with ZSTD_decompressBegin() or ZSTD_decompressBegin_usingDict().
682 Alternatively, you can copy a prepared context, using ZSTD_copyDCtx().
684 Then use ZSTD_nextSrcSizeToDecompress() and ZSTD_decompressContinue() alternatively.
685 ZSTD_nextSrcSizeToDecompress() tells how many bytes to provide as 'srcSize' to ZSTD_decompressContinue().
686 ZSTD_decompressContinue() requires this _exact_ amount of bytes, or it will fail.
688 @result of ZSTD_decompressContinue() is the number of bytes regenerated within 'dst' (necessarily <= dstCapacity).
689 It can be zero, which is not an error; it just means ZSTD_decompressContinue() has decoded some metadata item.
690 It can also be an error code, which can be tested with ZSTD_isError().
692 ZSTD_decompressContinue() needs previous data blocks during decompression, up to `windowSize`.
693 They should preferably be located contiguously, prior to current block.
694 Alternatively, a round buffer of sufficient size is also possible. Sufficient size is determined by frame parameters.
695 ZSTD_decompressContinue() is very sensitive to contiguity,
696 if 2 blocks don't follow each other, make sure that either the compressor breaks contiguity at the same place,
697 or that previous contiguous segment is large enough to properly handle maximum back-reference.
699 A frame is fully decoded when ZSTD_nextSrcSizeToDecompress() returns zero.
700 Context can then be reset to start a new decompression.
702 Note : it's possible to know if next input to present is a header or a block, using ZSTD_nextInputType().
703 This information is not required to properly decode a frame.
705 == Special case : skippable frames ==
707 Skippable frames allow integration of user-defined data into a flow of concatenated frames.
708 Skippable frames will be ignored (skipped) by a decompressor. The format of skippable frames is as follows :
709 a) Skippable frame ID - 4 Bytes, Little endian format, any value from 0x184D2A50 to 0x184D2A5F
710 b) Frame Size - 4 Bytes, Little endian format, unsigned 32-bits
711 c) Frame Content - any content (User Data) of length equal to Frame Size
712 For skippable frames ZSTD_decompressContinue() always returns 0.
713 For skippable frames ZSTD_getFrameParams() returns fparamsPtr->windowLog==0 what means that a frame is skippable.
714 Note : If fparamsPtr->frameContentSize==0, it is ambiguous: the frame might actually be a Zstd encoded frame with no content.
715 For purposes of decompression, it is valid in both cases to skip the frame using
716 ZSTD_findFrameCompressedSize to find its size in bytes.
717 It also returns Frame Size as fparamsPtr->frameContentSize.
721 unsigned long long frameContentSize;
724 unsigned checksumFlag;
727 /*===== Buffer-less streaming decompression functions =====*/
728 ZSTDLIB_API size_t ZSTD_getFrameParams(ZSTD_frameParams* fparamsPtr, const void* src, size_t srcSize); /**< doesn't consume input, see details below */
729 ZSTDLIB_API size_t ZSTD_decompressBegin(ZSTD_DCtx* dctx);
730 ZSTDLIB_API size_t ZSTD_decompressBegin_usingDict(ZSTD_DCtx* dctx, const void* dict, size_t dictSize);
731 ZSTDLIB_API void ZSTD_copyDCtx(ZSTD_DCtx* dctx, const ZSTD_DCtx* preparedDCtx);
732 ZSTDLIB_API size_t ZSTD_nextSrcSizeToDecompress(ZSTD_DCtx* dctx);
733 ZSTDLIB_API size_t ZSTD_decompressContinue(ZSTD_DCtx* dctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize);
734 typedef enum { ZSTDnit_frameHeader, ZSTDnit_blockHeader, ZSTDnit_block, ZSTDnit_lastBlock, ZSTDnit_checksum, ZSTDnit_skippableFrame } ZSTD_nextInputType_e;
735 ZSTDLIB_API ZSTD_nextInputType_e ZSTD_nextInputType(ZSTD_DCtx* dctx);
740 Block functions produce and decode raw zstd blocks, without frame metadata.
741 Frame metadata cost is typically ~18 bytes, which can be non-negligible for very small blocks (< 100 bytes).
742 User will have to take in charge required information to regenerate data, such as compressed and content sizes.
744 A few rules to respect :
745 - Compressing and decompressing require a context structure
746 + Use ZSTD_createCCtx() and ZSTD_createDCtx()
747 - It is necessary to init context before starting
748 + compression : ZSTD_compressBegin()
749 + decompression : ZSTD_decompressBegin()
750 + variants _usingDict() are also allowed
751 + copyCCtx() and copyDCtx() work too
752 - Block size is limited, it must be <= ZSTD_getBlockSizeMax()
753 + If you need to compress more, cut data into multiple blocks
754 + Consider using the regular ZSTD_compress() instead, as frame metadata costs become negligible when source size is large.
755 - When a block is considered not compressible enough, ZSTD_compressBlock() result will be zero.
756 In which case, nothing is produced into `dst`.
757 + User must test for such outcome and deal directly with uncompressed data
758 + ZSTD_decompressBlock() doesn't accept uncompressed data as input !!!
759 + In case of multiple successive blocks, decoder must be informed of uncompressed block existence to follow proper history.
760 Use ZSTD_insertBlock() in such a case.
763 #define ZSTD_BLOCKSIZE_ABSOLUTEMAX (128 * 1024) /* define, for static allocation */
764 /*===== Raw zstd block functions =====*/
765 ZSTDLIB_API size_t ZSTD_getBlockSizeMax(ZSTD_CCtx* cctx);
766 ZSTDLIB_API size_t ZSTD_compressBlock (ZSTD_CCtx* cctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize);
767 ZSTDLIB_API size_t ZSTD_decompressBlock(ZSTD_DCtx* dctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize);
768 ZSTDLIB_API size_t ZSTD_insertBlock(ZSTD_DCtx* dctx, const void* blockStart, size_t blockSize); /**< insert block into `dctx` history. Useful for uncompressed blocks */
771 #endif /* ZSTD_H_ZSTD_STATIC_LINKING_ONLY */
773 #if defined (__cplusplus)