]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/zstd/lib/zstd.h
Add supporting changes for `Add limited sandbox capability to "make check"`
[FreeBSD/FreeBSD.git] / contrib / zstd / lib / zstd.h
1 /*
2  * Copyright (c) 2016-present, Yann Collet, Facebook, Inc.
3  * All rights reserved.
4  *
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.
8  */
9
10 #if defined (__cplusplus)
11 extern "C" {
12 #endif
13
14 #ifndef ZSTD_H_235446
15 #define ZSTD_H_235446
16
17 /* ======   Dependency   ======*/
18 #include <stddef.h>   /* size_t */
19
20
21 /* =====   ZSTDLIB_API : control library symbols visibility   ===== */
22 #ifndef ZSTDLIB_VISIBILITY
23 #  if defined(__GNUC__) && (__GNUC__ >= 4)
24 #    define ZSTDLIB_VISIBILITY __attribute__ ((visibility ("default")))
25 #  else
26 #    define ZSTDLIB_VISIBILITY
27 #  endif
28 #endif
29 #if defined(ZSTD_DLL_EXPORT) && (ZSTD_DLL_EXPORT==1)
30 #  define ZSTDLIB_API __declspec(dllexport) ZSTDLIB_VISIBILITY
31 #elif defined(ZSTD_DLL_IMPORT) && (ZSTD_DLL_IMPORT==1)
32 #  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.*/
33 #else
34 #  define ZSTDLIB_API ZSTDLIB_VISIBILITY
35 #endif
36
37
38 /*******************************************************************************************************
39   Introduction
40
41   zstd, short for Zstandard, is a fast lossless compression algorithm,
42   targeting real-time compression scenarios at zlib-level and better compression ratios.
43   The zstd compression library provides in-memory compression and decompression functions.
44   The library supports compression levels from 1 up to ZSTD_maxCLevel() which is currently 22.
45   Levels >= 20, labeled `--ultra`, should be used with caution, as they require more memory.
46   Compression can be done in:
47     - a single step (described as Simple API)
48     - a single step, reusing a context (described as Explicit memory management)
49     - unbounded multiple steps (described as Streaming compression)
50   The compression ratio achievable on small data can be highly improved using a dictionary in:
51     - a single step (described as Simple dictionary API)
52     - a single step, reusing a dictionary (described as Fast dictionary API)
53
54   Advanced experimental functions can be accessed using #define ZSTD_STATIC_LINKING_ONLY before including zstd.h.
55   Advanced experimental APIs shall never be used with a dynamic library.
56   They are not "stable", their definition may change in the future. Only static linking is allowed.
57 *********************************************************************************************************/
58
59 /*------   Version   ------*/
60 #define ZSTD_VERSION_MAJOR    1
61 #define ZSTD_VERSION_MINOR    3
62 #define ZSTD_VERSION_RELEASE  0
63
64 #define ZSTD_VERSION_NUMBER  (ZSTD_VERSION_MAJOR *100*100 + ZSTD_VERSION_MINOR *100 + ZSTD_VERSION_RELEASE)
65 ZSTDLIB_API unsigned ZSTD_versionNumber(void);   /**< useful to check dll version */
66
67 #define ZSTD_LIB_VERSION ZSTD_VERSION_MAJOR.ZSTD_VERSION_MINOR.ZSTD_VERSION_RELEASE
68 #define ZSTD_QUOTE(str) #str
69 #define ZSTD_EXPAND_AND_QUOTE(str) ZSTD_QUOTE(str)
70 #define ZSTD_VERSION_STRING ZSTD_EXPAND_AND_QUOTE(ZSTD_LIB_VERSION)
71 ZSTDLIB_API const char* ZSTD_versionString(void);   /* v1.3.0 */
72
73
74 /***************************************
75 *  Simple API
76 ***************************************/
77 /*! ZSTD_compress() :
78  *  Compresses `src` content as a single zstd compressed frame into already allocated `dst`.
79  *  Hint : compression runs faster if `dstCapacity` >=  `ZSTD_compressBound(srcSize)`.
80  *  @return : compressed size written into `dst` (<= `dstCapacity),
81  *            or an error code if it fails (which can be tested using ZSTD_isError()). */
82 ZSTDLIB_API size_t ZSTD_compress( void* dst, size_t dstCapacity,
83                             const void* src, size_t srcSize,
84                                   int compressionLevel);
85
86 /*! ZSTD_decompress() :
87  *  `compressedSize` : must be the _exact_ size of some number of compressed and/or skippable frames.
88  *  `dstCapacity` is an upper bound of originalSize to regenerate.
89  *  If user cannot imply a maximum upper bound, it's better to use streaming mode to decompress data.
90  *  @return : the number of bytes decompressed into `dst` (<= `dstCapacity`),
91  *            or an errorCode if it fails (which can be tested using ZSTD_isError()). */
92 ZSTDLIB_API size_t ZSTD_decompress( void* dst, size_t dstCapacity,
93                               const void* src, size_t compressedSize);
94
95 /*! ZSTD_getFrameContentSize() : v1.3.0
96  *  `src` should point to the start of a ZSTD encoded frame.
97  *  `srcSize` must be at least as large as the frame header.
98  *            hint : any size >= `ZSTD_frameHeaderSize_max` is large enough.
99  *  @return : - decompressed size of the frame in `src`, if known
100  *            - ZSTD_CONTENTSIZE_UNKNOWN if the size cannot be determined
101  *            - ZSTD_CONTENTSIZE_ERROR if an error occurred (e.g. invalid magic number, srcSize too small)
102  *   note 1 : a 0 return value means the frame is valid but "empty".
103  *   note 2 : decompressed size is an optional field, it may not be present, typically in streaming mode.
104  *            When `return==ZSTD_CONTENTSIZE_UNKNOWN`, 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 rely on some implicit limit,
107  *            as ZSTD_decompress() only needs an upper bound of decompressed size.
108  *            (For example, data could be necessarily cut into blocks <= 16 KB).
109  *   note 3 : decompressed size is always present when compression is done with ZSTD_compress()
110  *   note 4 : decompressed size can be very large (64-bits value),
111  *            potentially larger than what local system can handle as a single memory segment.
112  *            In which case, it's necessary to use streaming mode to decompress data.
113  *   note 5 : If source is untrusted, decompressed size could be wrong or intentionally modified.
114  *            Always ensure return value fits within application's authorized limits.
115  *            Each application can set its own limits.
116  *   note 6 : This function replaces ZSTD_getDecompressedSize() */
117 #define ZSTD_CONTENTSIZE_UNKNOWN (0ULL - 1)
118 #define ZSTD_CONTENTSIZE_ERROR   (0ULL - 2)
119 ZSTDLIB_API unsigned long long ZSTD_getFrameContentSize(const void *src, size_t srcSize);
120
121 /*! ZSTD_getDecompressedSize() :
122  *  NOTE: This function is now obsolete, in favor of ZSTD_getFrameContentSize().
123  *  Both functions work the same way,
124  *  but ZSTD_getDecompressedSize() blends
125  *  "empty", "unknown" and "error" results in the same return value (0),
126  *  while ZSTD_getFrameContentSize() distinguishes them.
127  *
128  *  'src' is the start of a zstd compressed frame.
129  *  @return : content size to be decompressed, as a 64-bits value _if known and not empty_, 0 otherwise. */
130 ZSTDLIB_API unsigned long long ZSTD_getDecompressedSize(const void* src, size_t srcSize);
131
132
133 /*======  Helper functions  ======*/
134 ZSTDLIB_API int         ZSTD_maxCLevel(void);               /*!< maximum compression level available */
135 ZSTDLIB_API size_t      ZSTD_compressBound(size_t srcSize); /*!< maximum compressed size in worst case scenario */
136 ZSTDLIB_API unsigned    ZSTD_isError(size_t code);          /*!< tells if a `size_t` function result is an error code */
137 ZSTDLIB_API const char* ZSTD_getErrorName(size_t code);     /*!< provides readable string from an error code */
138
139
140 /***************************************
141 *  Explicit memory management
142 ***************************************/
143 /*= Compression context
144  *  When compressing many times,
145  *  it is recommended to allocate a context just once, and re-use it for each successive compression operation.
146  *  This will make workload friendlier for system's memory.
147  *  Use one context per thread for parallel execution in multi-threaded environments. */
148 typedef struct ZSTD_CCtx_s ZSTD_CCtx;
149 ZSTDLIB_API ZSTD_CCtx* ZSTD_createCCtx(void);
150 ZSTDLIB_API size_t     ZSTD_freeCCtx(ZSTD_CCtx* cctx);
151
152 /*! ZSTD_compressCCtx() :
153  *  Same as ZSTD_compress(), requires an allocated ZSTD_CCtx (see ZSTD_createCCtx()). */
154 ZSTDLIB_API size_t ZSTD_compressCCtx(ZSTD_CCtx* ctx,
155                                      void* dst, size_t dstCapacity,
156                                const void* src, size_t srcSize,
157                                      int compressionLevel);
158
159 /*= Decompression context
160  *  When decompressing many times,
161  *  it is recommended to allocate a context only once,
162  *  and re-use it for each successive compression operation.
163  *  This will make workload friendlier for system's memory.
164  *  Use one context per thread for parallel execution. */
165 typedef struct ZSTD_DCtx_s ZSTD_DCtx;
166 ZSTDLIB_API ZSTD_DCtx* ZSTD_createDCtx(void);
167 ZSTDLIB_API size_t     ZSTD_freeDCtx(ZSTD_DCtx* dctx);
168
169 /*! ZSTD_decompressDCtx() :
170  *  Same as ZSTD_decompress(), requires an allocated ZSTD_DCtx (see ZSTD_createDCtx()) */
171 ZSTDLIB_API size_t ZSTD_decompressDCtx(ZSTD_DCtx* ctx,
172                                        void* dst, size_t dstCapacity,
173                                  const void* src, size_t srcSize);
174
175
176 /**************************
177 *  Simple dictionary API
178 ***************************/
179 /*! ZSTD_compress_usingDict() :
180  *  Compression using a predefined Dictionary (see dictBuilder/zdict.h).
181  *  Note : This function loads the dictionary, resulting in significant startup delay.
182  *  Note : When `dict == NULL || dictSize < 8` no dictionary is used. */
183 ZSTDLIB_API size_t ZSTD_compress_usingDict(ZSTD_CCtx* ctx,
184                                            void* dst, size_t dstCapacity,
185                                      const void* src, size_t srcSize,
186                                      const void* dict,size_t dictSize,
187                                            int compressionLevel);
188
189 /*! ZSTD_decompress_usingDict() :
190  *  Decompression using a predefined Dictionary (see dictBuilder/zdict.h).
191  *  Dictionary must be identical to the one used during compression.
192  *  Note : This function loads the dictionary, resulting in significant startup delay.
193  *  Note : When `dict == NULL || dictSize < 8` no dictionary is used. */
194 ZSTDLIB_API size_t ZSTD_decompress_usingDict(ZSTD_DCtx* dctx,
195                                              void* dst, size_t dstCapacity,
196                                        const void* src, size_t srcSize,
197                                        const void* dict,size_t dictSize);
198
199
200 /**********************************
201  *  Bulk processing dictionary API
202  *********************************/
203 typedef struct ZSTD_CDict_s ZSTD_CDict;
204
205 /*! ZSTD_createCDict() :
206  *  When compressing multiple messages / blocks with the same dictionary, it's recommended to load it just once.
207  *  ZSTD_createCDict() will create a digested dictionary, ready to start future compression operations without startup delay.
208  *  ZSTD_CDict can be created once and shared by multiple threads concurrently, since its usage is read-only.
209  *  `dictBuffer` can be released after ZSTD_CDict creation, since its content is copied within CDict */
210 ZSTDLIB_API ZSTD_CDict* ZSTD_createCDict(const void* dictBuffer, size_t dictSize,
211                                          int compressionLevel);
212
213 /*! ZSTD_freeCDict() :
214  *  Function frees memory allocated by ZSTD_createCDict(). */
215 ZSTDLIB_API size_t      ZSTD_freeCDict(ZSTD_CDict* CDict);
216
217 /*! ZSTD_compress_usingCDict() :
218  *  Compression using a digested Dictionary.
219  *  Faster startup than ZSTD_compress_usingDict(), recommended when same dictionary is used multiple times.
220  *  Note that compression level is decided during dictionary creation.
221  *  Frame parameters are hardcoded (dictID=yes, contentSize=yes, checksum=no) */
222 ZSTDLIB_API size_t ZSTD_compress_usingCDict(ZSTD_CCtx* cctx,
223                                             void* dst, size_t dstCapacity,
224                                       const void* src, size_t srcSize,
225                                       const ZSTD_CDict* cdict);
226
227
228 typedef struct ZSTD_DDict_s ZSTD_DDict;
229
230 /*! ZSTD_createDDict() :
231  *  Create a digested dictionary, ready to start decompression operation without startup delay.
232  *  dictBuffer can be released after DDict creation, as its content is copied inside DDict */
233 ZSTDLIB_API ZSTD_DDict* ZSTD_createDDict(const void* dictBuffer, size_t dictSize);
234
235 /*! ZSTD_freeDDict() :
236  *  Function frees memory allocated with ZSTD_createDDict() */
237 ZSTDLIB_API size_t      ZSTD_freeDDict(ZSTD_DDict* ddict);
238
239 /*! ZSTD_decompress_usingDDict() :
240  *  Decompression using a digested Dictionary.
241  *  Faster startup than ZSTD_decompress_usingDict(), recommended when same dictionary is used multiple times. */
242 ZSTDLIB_API size_t ZSTD_decompress_usingDDict(ZSTD_DCtx* dctx,
243                                               void* dst, size_t dstCapacity,
244                                         const void* src, size_t srcSize,
245                                         const ZSTD_DDict* ddict);
246
247
248 /****************************
249 *  Streaming
250 ****************************/
251
252 typedef struct ZSTD_inBuffer_s {
253   const void* src;    /**< start of input buffer */
254   size_t size;        /**< size of input buffer */
255   size_t pos;         /**< position where reading stopped. Will be updated. Necessarily 0 <= pos <= size */
256 } ZSTD_inBuffer;
257
258 typedef struct ZSTD_outBuffer_s {
259   void*  dst;         /**< start of output buffer */
260   size_t size;        /**< size of output buffer */
261   size_t pos;         /**< position where writing stopped. Will be updated. Necessarily 0 <= pos <= size */
262 } ZSTD_outBuffer;
263
264
265
266 /*-***********************************************************************
267 *  Streaming compression - HowTo
268 *
269 *  A ZSTD_CStream object is required to track streaming operation.
270 *  Use ZSTD_createCStream() and ZSTD_freeCStream() to create/release resources.
271 *  ZSTD_CStream objects can be reused multiple times on consecutive compression operations.
272 *  It is recommended to re-use ZSTD_CStream in situations where many streaming operations will be achieved consecutively,
273 *  since it will play nicer with system's memory, by re-using already allocated memory.
274 *  Use one separate ZSTD_CStream per thread for parallel execution.
275 *
276 *  Start a new compression by initializing ZSTD_CStream.
277 *  Use ZSTD_initCStream() to start a new compression operation.
278 *  Use ZSTD_initCStream_usingDict() or ZSTD_initCStream_usingCDict() for a compression which requires a dictionary (experimental section)
279 *
280 *  Use ZSTD_compressStream() repetitively to consume input stream.
281 *  The function will automatically update both `pos` fields.
282 *  Note that it may not consume the entire input, in which case `pos < size`,
283 *  and it's up to the caller to present again remaining data.
284 *  @return : a size hint, preferred nb of bytes to use as input for next function call
285 *            or an error code, which can be tested using ZSTD_isError().
286 *            Note 1 : it's just a hint, to help latency a little, any other value will work fine.
287 *            Note 2 : size hint is guaranteed to be <= ZSTD_CStreamInSize()
288 *
289 *  At any moment, it's possible to flush whatever data remains within internal buffer, using ZSTD_flushStream().
290 *  `output->pos` will be updated.
291 *  Note that some content might still be left within internal buffer if `output->size` is too small.
292 *  @return : nb of bytes still present within internal buffer (0 if it's empty)
293 *            or an error code, which can be tested using ZSTD_isError().
294 *
295 *  ZSTD_endStream() instructs to finish a frame.
296 *  It will perform a flush and write frame epilogue.
297 *  The epilogue is required for decoders to consider a frame completed.
298 *  ZSTD_endStream() may not be able to flush full data if `output->size` is too small.
299 *  In which case, call again ZSTD_endStream() to complete the flush.
300 *  @return : 0 if frame fully completed and fully flushed,
301              or >0 if some data is still present within internal buffer
302                   (value is minimum size estimation for remaining data to flush, but it could be more)
303 *            or an error code, which can be tested using ZSTD_isError().
304 *
305 * *******************************************************************/
306
307 typedef ZSTD_CCtx ZSTD_CStream;  /**< CCtx and CStream are now effectively same object (>= v1.3.0) */
308                                  /* Continue to distinguish them for compatibility with versions <= v1.2.0 */
309 /*===== ZSTD_CStream management functions =====*/
310 ZSTDLIB_API ZSTD_CStream* ZSTD_createCStream(void);
311 ZSTDLIB_API size_t ZSTD_freeCStream(ZSTD_CStream* zcs);
312
313 /*===== Streaming compression functions =====*/
314 ZSTDLIB_API size_t ZSTD_initCStream(ZSTD_CStream* zcs, int compressionLevel);
315 ZSTDLIB_API size_t ZSTD_compressStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output, ZSTD_inBuffer* input);
316 ZSTDLIB_API size_t ZSTD_flushStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output);
317 ZSTDLIB_API size_t ZSTD_endStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output);
318
319 ZSTDLIB_API size_t ZSTD_CStreamInSize(void);    /**< recommended size for input buffer */
320 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. */
321
322
323
324 /*-***************************************************************************
325 *  Streaming decompression - HowTo
326 *
327 *  A ZSTD_DStream object is required to track streaming operations.
328 *  Use ZSTD_createDStream() and ZSTD_freeDStream() to create/release resources.
329 *  ZSTD_DStream objects can be re-used multiple times.
330 *
331 *  Use ZSTD_initDStream() to start a new decompression operation,
332 *   or ZSTD_initDStream_usingDict() if decompression requires a dictionary.
333 *   @return : recommended first input size
334 *
335 *  Use ZSTD_decompressStream() repetitively to consume your input.
336 *  The function will update both `pos` fields.
337 *  If `input.pos < input.size`, some input has not been consumed.
338 *  It's up to the caller to present again remaining data.
339 *  If `output.pos < output.size`, decoder has flushed everything it could.
340 *  @return : 0 when a frame is completely decoded and fully flushed,
341 *            an error code, which can be tested using ZSTD_isError(),
342 *            any other value > 0, which means there is still some decoding to do to complete current frame.
343 *            The return value is a suggested next input size (a hint to improve latency) that will never load more than the current frame.
344 * *******************************************************************************/
345
346 typedef ZSTD_DCtx ZSTD_DStream;  /**< DCtx and DStream are now effectively same object (>= v1.3.0) */
347                                  /* Continue to distinguish them for compatibility with versions <= v1.2.0 */
348 /*===== ZSTD_DStream management functions =====*/
349 ZSTDLIB_API ZSTD_DStream* ZSTD_createDStream(void);
350 ZSTDLIB_API size_t ZSTD_freeDStream(ZSTD_DStream* zds);
351
352 /*===== Streaming decompression functions =====*/
353 ZSTDLIB_API size_t ZSTD_initDStream(ZSTD_DStream* zds);
354 ZSTDLIB_API size_t ZSTD_decompressStream(ZSTD_DStream* zds, ZSTD_outBuffer* output, ZSTD_inBuffer* input);
355
356 ZSTDLIB_API size_t ZSTD_DStreamInSize(void);    /*!< recommended size for input buffer */
357 ZSTDLIB_API size_t ZSTD_DStreamOutSize(void);   /*!< recommended size for output buffer. Guarantee to successfully flush at least one complete block in all circumstances. */
358
359 #endif  /* ZSTD_H_235446 */
360
361
362
363 /****************************************************************************************
364  * START OF ADVANCED AND EXPERIMENTAL FUNCTIONS
365  * The definitions in this section are considered experimental.
366  * They should never be used with a dynamic library, as prototypes may change in the future.
367  * They are provided for advanced scenarios.
368  * Use them only in association with static linking.
369  * ***************************************************************************************/
370
371 #if defined(ZSTD_STATIC_LINKING_ONLY) && !defined(ZSTD_H_ZSTD_STATIC_LINKING_ONLY)
372 #define ZSTD_H_ZSTD_STATIC_LINKING_ONLY
373
374 /* --- Constants ---*/
375 #define ZSTD_MAGICNUMBER            0xFD2FB528   /* >= v0.8.0 */
376 #define ZSTD_MAGIC_SKIPPABLE_START  0x184D2A50U
377 #define ZSTD_MAGIC_DICTIONARY       0xEC30A437   /* v0.7+ */
378
379 #define ZSTD_WINDOWLOG_MAX_32  27
380 #define ZSTD_WINDOWLOG_MAX_64  27
381 #define ZSTD_WINDOWLOG_MAX    ((unsigned)(sizeof(size_t) == 4 ? ZSTD_WINDOWLOG_MAX_32 : ZSTD_WINDOWLOG_MAX_64))
382 #define ZSTD_WINDOWLOG_MIN     10
383 #define ZSTD_HASHLOG_MAX       ZSTD_WINDOWLOG_MAX
384 #define ZSTD_HASHLOG_MIN        6
385 #define ZSTD_CHAINLOG_MAX     (ZSTD_WINDOWLOG_MAX+1)
386 #define ZSTD_CHAINLOG_MIN      ZSTD_HASHLOG_MIN
387 #define ZSTD_HASHLOG3_MAX      17
388 #define ZSTD_SEARCHLOG_MAX    (ZSTD_WINDOWLOG_MAX-1)
389 #define ZSTD_SEARCHLOG_MIN      1
390 #define ZSTD_SEARCHLENGTH_MAX   7   /* only for ZSTD_fast, other strategies are limited to 6 */
391 #define ZSTD_SEARCHLENGTH_MIN   3   /* only for ZSTD_btopt, other strategies are limited to 4 */
392 #define ZSTD_TARGETLENGTH_MIN   4
393 #define ZSTD_TARGETLENGTH_MAX 999
394
395 #define ZSTD_FRAMEHEADERSIZE_MAX 18    /* for static allocation */
396 #define ZSTD_FRAMEHEADERSIZE_MIN  6
397 static const size_t ZSTD_frameHeaderSize_prefix = 5;  /* minimum input size to know frame header size */
398 static const size_t ZSTD_frameHeaderSize_max = ZSTD_FRAMEHEADERSIZE_MAX;
399 static const size_t ZSTD_frameHeaderSize_min = ZSTD_FRAMEHEADERSIZE_MIN;
400 static const size_t ZSTD_skippableHeaderSize = 8;  /* magic number + skippable frame length */
401
402
403 /*--- Advanced types ---*/
404 typedef enum { ZSTD_fast=1, ZSTD_dfast, ZSTD_greedy, ZSTD_lazy, ZSTD_lazy2,
405                ZSTD_btlazy2, ZSTD_btopt, ZSTD_btultra } ZSTD_strategy;   /* from faster to stronger */
406
407 typedef struct {
408     unsigned windowLog;      /**< largest match distance : larger == more compression, more memory needed during decompression */
409     unsigned chainLog;       /**< fully searched segment : larger == more compression, slower, more memory (useless for fast) */
410     unsigned hashLog;        /**< dispatch table : larger == faster, more memory */
411     unsigned searchLog;      /**< nb of searches : larger == more compression, slower */
412     unsigned searchLength;   /**< match length searched : larger == faster decompression, sometimes less compression */
413     unsigned targetLength;   /**< acceptable match size for optimal parser (only) : larger == more compression, slower */
414     ZSTD_strategy strategy;
415 } ZSTD_compressionParameters;
416
417 typedef struct {
418     unsigned contentSizeFlag; /**< 1: content size will be in frame header (when known) */
419     unsigned checksumFlag;    /**< 1: generate a 32-bits checksum at end of frame, for error detection */
420     unsigned noDictIDFlag;    /**< 1: no dictID will be saved into frame header (if dictionary compression) */
421 } ZSTD_frameParameters;
422
423 typedef struct {
424     ZSTD_compressionParameters cParams;
425     ZSTD_frameParameters fParams;
426 } ZSTD_parameters;
427
428 typedef struct {
429     unsigned long long frameContentSize;
430     size_t windowSize;
431     unsigned dictID;
432     unsigned checksumFlag;
433 } ZSTD_frameHeader;
434
435 /*= Custom memory allocation functions */
436 typedef void* (*ZSTD_allocFunction) (void* opaque, size_t size);
437 typedef void  (*ZSTD_freeFunction) (void* opaque, void* address);
438 typedef struct { ZSTD_allocFunction customAlloc; ZSTD_freeFunction customFree; void* opaque; } ZSTD_customMem;
439 /* use this constant to defer to stdlib's functions */
440 static const ZSTD_customMem ZSTD_defaultCMem = { NULL, NULL, NULL };
441
442
443 /***************************************
444 *  Frame size functions
445 ***************************************/
446
447 /*! ZSTD_findFrameCompressedSize() :
448  *  `src` should point to the start of a ZSTD encoded frame or skippable frame
449  *  `srcSize` must be at least as large as the frame
450  *  @return : the compressed size of the first frame starting at `src`,
451  *            suitable to pass to `ZSTD_decompress` or similar,
452  *            or an error code if input is invalid */
453 ZSTDLIB_API size_t ZSTD_findFrameCompressedSize(const void* src, size_t srcSize);
454
455 /*! ZSTD_findDecompressedSize() :
456  *  `src` should point the start of a series of ZSTD encoded and/or skippable frames
457  *  `srcSize` must be the _exact_ size of this series
458  *       (i.e. there should be a frame boundary exactly at `srcSize` bytes after `src`)
459  *  @return : - decompressed size of all data in all successive frames
460  *            - if the decompressed size cannot be determined: ZSTD_CONTENTSIZE_UNKNOWN
461  *            - if an error occurred: ZSTD_CONTENTSIZE_ERROR
462  *
463  *   note 1 : decompressed size is an optional field, that may not be present, especially in streaming mode.
464  *            When `return==ZSTD_CONTENTSIZE_UNKNOWN`, data to decompress could be any size.
465  *            In which case, it's necessary to use streaming mode to decompress data.
466  *   note 2 : decompressed size is always present when compression is done with ZSTD_compress()
467  *   note 3 : decompressed size can be very large (64-bits value),
468  *            potentially larger than what local system can handle as a single memory segment.
469  *            In which case, it's necessary to use streaming mode to decompress data.
470  *   note 4 : If source is untrusted, decompressed size could be wrong or intentionally modified.
471  *            Always ensure result fits within application's authorized limits.
472  *            Each application can set its own limits.
473  *   note 5 : ZSTD_findDecompressedSize handles multiple frames, and so it must traverse the input to
474  *            read each contained frame header.  This is fast as most of the data is skipped,
475  *            however it does mean that all frame data must be present and valid. */
476 ZSTDLIB_API unsigned long long ZSTD_findDecompressedSize(const void* src, size_t srcSize);
477
478 /*! ZSTD_frameHeaderSize() :
479 *   `src` should point to the start of a ZSTD frame
480 *   `srcSize` must be >= ZSTD_frameHeaderSize_prefix.
481 *   @return : size of the Frame Header */
482 ZSTDLIB_API size_t ZSTD_frameHeaderSize(const void* src, size_t srcSize);
483
484
485 /***************************************
486 *  Context memory usage
487 ***************************************/
488
489 /*! ZSTD_sizeof_*() :
490  *  These functions give the current memory usage of selected object.
491  *  Object memory usage can evolve if it's re-used multiple times. */
492 ZSTDLIB_API size_t ZSTD_sizeof_CCtx(const ZSTD_CCtx* cctx);
493 ZSTDLIB_API size_t ZSTD_sizeof_DCtx(const ZSTD_DCtx* dctx);
494 ZSTDLIB_API size_t ZSTD_sizeof_CStream(const ZSTD_CStream* zcs);
495 ZSTDLIB_API size_t ZSTD_sizeof_DStream(const ZSTD_DStream* zds);
496 ZSTDLIB_API size_t ZSTD_sizeof_CDict(const ZSTD_CDict* cdict);
497 ZSTDLIB_API size_t ZSTD_sizeof_DDict(const ZSTD_DDict* ddict);
498
499 /*! ZSTD_estimate*() :
500  *  These functions make it possible to estimate memory usage
501  *  of a future {D,C}Ctx, before its creation.
502  *  ZSTD_estimateCCtxSize() will provide a budget large enough for any compression level up to selected one.
503  *  It will also consider src size to be arbitrarily "large", which is worst case.
504  *  If srcSize is known to always be small, ZSTD_estimateCCtxSize_advanced() can provide a tighter estimation.
505  *  ZSTD_estimateCCtxSize_advanced() can be used in tandem with ZSTD_getCParams() to create cParams from compressionLevel.
506  *  Note : CCtx estimation is only correct for single-threaded compression */
507 ZSTDLIB_API size_t ZSTD_estimateCCtxSize(int compressionLevel);
508 ZSTDLIB_API size_t ZSTD_estimateCCtxSize_advanced(ZSTD_compressionParameters cParams);
509 ZSTDLIB_API size_t ZSTD_estimateDCtxSize(void);
510
511 /*! ZSTD_estimate?StreamSize() :
512  *  ZSTD_estimateCStreamSize() will provide a budget large enough for any compression level up to selected one.
513  *  It will also consider src size to be arbitrarily "large", which is worst case.
514  *  If srcSize is known to always be small, ZSTD_estimateCStreamSize_advanced() can provide a tighter estimation.
515  *  ZSTD_estimateCStreamSize_advanced() can be used in tandem with ZSTD_getCParams() to create cParams from compressionLevel.
516  *  Note : CStream estimation is only correct for single-threaded compression.
517  *  ZSTD_DStream memory budget depends on window Size.
518  *  This information can be passed manually, using ZSTD_estimateDStreamSize,
519  *  or deducted from a valid frame Header, using ZSTD_estimateDStreamSize_fromFrame();
520  *  Note : if streaming is init with function ZSTD_init?Stream_usingDict(),
521  *         an internal ?Dict will be created, which additional size is not estimated here.
522  *         In this case, get total size by adding ZSTD_estimate?DictSize */
523 ZSTDLIB_API size_t ZSTD_estimateCStreamSize(int compressionLevel);
524 ZSTDLIB_API size_t ZSTD_estimateCStreamSize_advanced(ZSTD_compressionParameters cParams);
525 ZSTDLIB_API size_t ZSTD_estimateDStreamSize(size_t windowSize);
526 ZSTDLIB_API size_t ZSTD_estimateDStreamSize_fromFrame(const void* src, size_t srcSize);
527
528 /*! ZSTD_estimate?DictSize() :
529  *  ZSTD_estimateCDictSize() will bet that src size is relatively "small", and content is copied, like ZSTD_createCDict().
530  *  ZSTD_estimateCStreamSize_advanced() makes it possible to control precisely compression parameters, like ZSTD_createCDict_advanced().
531  *  Note : dictionary created "byReference" are smaller */
532 ZSTDLIB_API size_t ZSTD_estimateCDictSize(size_t dictSize, int compressionLevel);
533 ZSTDLIB_API size_t ZSTD_estimateCDictSize_advanced(size_t dictSize, ZSTD_compressionParameters cParams, unsigned byReference);
534 ZSTDLIB_API size_t ZSTD_estimateDDictSize(size_t dictSize, unsigned byReference);
535
536
537 /***************************************
538 *  Advanced compression functions
539 ***************************************/
540 /*! ZSTD_createCCtx_advanced() :
541  *  Create a ZSTD compression context using external alloc and free functions */
542 ZSTDLIB_API ZSTD_CCtx* ZSTD_createCCtx_advanced(ZSTD_customMem customMem);
543
544 /*! ZSTD_initStaticCCtx() : initialize a fixed-size zstd compression context
545  *  workspace: The memory area to emplace the context into.
546  *             Provided pointer must 8-bytes aligned.
547  *             It must outlive context usage.
548  *  workspaceSize: Use ZSTD_estimateCCtxSize() or ZSTD_estimateCStreamSize()
549  *                 to determine how large workspace must be to support scenario.
550  * @return : pointer to ZSTD_CCtx*, or NULL if error (size too small)
551  *  Note : zstd will never resize nor malloc() when using a static cctx.
552  *         If it needs more memory than available, it will simply error out.
553  *  Note 2 : there is no corresponding "free" function.
554  *           Since workspace was allocated externally, it must be freed externally too.
555  *  Limitation 1 : currently not compatible with internal CDict creation, such as
556  *                 ZSTD_CCtx_loadDictionary() or ZSTD_initCStream_usingDict().
557  *  Limitation 2 : currently not compatible with multi-threading
558  */
559 ZSTDLIB_API ZSTD_CCtx* ZSTD_initStaticCCtx(void* workspace, size_t workspaceSize);
560
561
562 /* !!! To be deprecated !!! */
563 typedef enum {
564     ZSTD_p_forceWindow,   /* Force back-references to remain < windowSize, even when referencing Dictionary content (default:0) */
565     ZSTD_p_forceRawDict   /* Force loading dictionary in "content-only" mode (no header analysis) */
566 } ZSTD_CCtxParameter;
567 /*! ZSTD_setCCtxParameter() :
568  *  Set advanced parameters, selected through enum ZSTD_CCtxParameter
569  *  @result : 0, or an error code (which can be tested with ZSTD_isError()) */
570 ZSTDLIB_API size_t ZSTD_setCCtxParameter(ZSTD_CCtx* cctx, ZSTD_CCtxParameter param, unsigned value);
571
572
573 /*! ZSTD_createCDict_byReference() :
574  *  Create a digested dictionary for compression
575  *  Dictionary content is simply referenced, and therefore stays in dictBuffer.
576  *  It is important that dictBuffer outlives CDict, it must remain read accessible throughout the lifetime of CDict */
577 ZSTDLIB_API ZSTD_CDict* ZSTD_createCDict_byReference(const void* dictBuffer, size_t dictSize, int compressionLevel);
578
579
580 typedef enum { ZSTD_dm_auto=0,        /* dictionary is "full" if it starts with ZSTD_MAGIC_DICTIONARY, otherwise it is "rawContent" */
581                ZSTD_dm_rawContent,    /* ensures dictionary is always loaded as rawContent, even if it starts with ZSTD_MAGIC_DICTIONARY */
582                ZSTD_dm_fullDict       /* refuses to load a dictionary if it does not respect Zstandard's specification */
583 } ZSTD_dictMode_e;
584 /*! ZSTD_createCDict_advanced() :
585  *  Create a ZSTD_CDict using external alloc and free, and customized compression parameters */
586 ZSTDLIB_API ZSTD_CDict* ZSTD_createCDict_advanced(const void* dict, size_t dictSize,
587                                                   unsigned byReference, ZSTD_dictMode_e dictMode,
588                                                   ZSTD_compressionParameters cParams,
589                                                   ZSTD_customMem customMem);
590
591 /*! ZSTD_initStaticCDict_advanced() :
592  *  Generate a digested dictionary in provided memory area.
593  *  workspace: The memory area to emplace the dictionary into.
594  *             Provided pointer must 8-bytes aligned.
595  *             It must outlive dictionary usage.
596  *  workspaceSize: Use ZSTD_estimateCDictSize()
597  *                 to determine how large workspace must be.
598  *  cParams : use ZSTD_getCParams() to transform a compression level
599  *            into its relevants cParams.
600  * @return : pointer to ZSTD_CDict*, or NULL if error (size too small)
601  *  Note : there is no corresponding "free" function.
602  *         Since workspace was allocated externally, it must be freed externally.
603  */
604 ZSTDLIB_API ZSTD_CDict* ZSTD_initStaticCDict(
605                             void* workspace, size_t workspaceSize,
606                       const void* dict, size_t dictSize,
607                             unsigned byReference, ZSTD_dictMode_e dictMode,
608                             ZSTD_compressionParameters cParams);
609
610 /*! ZSTD_getCParams() :
611 *   @return ZSTD_compressionParameters structure for a selected compression level and estimated srcSize.
612 *   `estimatedSrcSize` value is optional, select 0 if not known */
613 ZSTDLIB_API ZSTD_compressionParameters ZSTD_getCParams(int compressionLevel, unsigned long long estimatedSrcSize, size_t dictSize);
614
615 /*! ZSTD_getParams() :
616 *   same as ZSTD_getCParams(), but @return a full `ZSTD_parameters` object instead of sub-component `ZSTD_compressionParameters`.
617 *   All fields of `ZSTD_frameParameters` are set to default (0) */
618 ZSTDLIB_API ZSTD_parameters ZSTD_getParams(int compressionLevel, unsigned long long estimatedSrcSize, size_t dictSize);
619
620 /*! ZSTD_checkCParams() :
621 *   Ensure param values remain within authorized range */
622 ZSTDLIB_API size_t ZSTD_checkCParams(ZSTD_compressionParameters params);
623
624 /*! ZSTD_adjustCParams() :
625  *  optimize params for a given `srcSize` and `dictSize`.
626  *  both values are optional, select `0` if unknown. */
627 ZSTDLIB_API ZSTD_compressionParameters ZSTD_adjustCParams(ZSTD_compressionParameters cPar, unsigned long long srcSize, size_t dictSize);
628
629 /*! ZSTD_compress_advanced() :
630 *   Same as ZSTD_compress_usingDict(), with fine-tune control over each compression parameter */
631 ZSTDLIB_API size_t ZSTD_compress_advanced (ZSTD_CCtx* cctx,
632                                   void* dst, size_t dstCapacity,
633                             const void* src, size_t srcSize,
634                             const void* dict,size_t dictSize,
635                                   ZSTD_parameters params);
636
637 /*! ZSTD_compress_usingCDict_advanced() :
638 *   Same as ZSTD_compress_usingCDict(), with fine-tune control over frame parameters */
639 ZSTDLIB_API size_t ZSTD_compress_usingCDict_advanced(ZSTD_CCtx* cctx,
640                                   void* dst, size_t dstCapacity,
641                             const void* src, size_t srcSize,
642                             const ZSTD_CDict* cdict, ZSTD_frameParameters fParams);
643
644
645 /*--- Advanced decompression functions ---*/
646
647 /*! ZSTD_isFrame() :
648  *  Tells if the content of `buffer` starts with a valid Frame Identifier.
649  *  Note : Frame Identifier is 4 bytes. If `size < 4`, @return will always be 0.
650  *  Note 2 : Legacy Frame Identifiers are considered valid only if Legacy Support is enabled.
651  *  Note 3 : Skippable Frame Identifiers are considered valid. */
652 ZSTDLIB_API unsigned ZSTD_isFrame(const void* buffer, size_t size);
653
654 /*! ZSTD_createDCtx_advanced() :
655  *  Create a ZSTD decompression context using external alloc and free functions */
656 ZSTDLIB_API ZSTD_DCtx* ZSTD_createDCtx_advanced(ZSTD_customMem customMem);
657
658 /*! ZSTD_initStaticDCtx() : initialize a fixed-size zstd decompression context
659  *  workspace: The memory area to emplace the context into.
660  *             Provided pointer must 8-bytes aligned.
661  *             It must outlive context usage.
662  *  workspaceSize: Use ZSTD_estimateDCtxSize() or ZSTD_estimateDStreamSize()
663  *                 to determine how large workspace must be to support scenario.
664  * @return : pointer to ZSTD_DCtx*, or NULL if error (size too small)
665  *  Note : zstd will never resize nor malloc() when using a static dctx.
666  *         If it needs more memory than available, it will simply error out.
667  *  Note 2 : static dctx is incompatible with legacy support
668  *  Note 3 : there is no corresponding "free" function.
669  *           Since workspace was allocated externally, it must be freed externally.
670  *  Limitation : currently not compatible with internal DDict creation,
671  *               such as ZSTD_initDStream_usingDict().
672  */
673 ZSTDLIB_API ZSTD_DCtx* ZSTD_initStaticDCtx(void* workspace, size_t workspaceSize);
674
675 /*! ZSTD_createDDict_byReference() :
676  *  Create a digested dictionary, ready to start decompression operation without startup delay.
677  *  Dictionary content is referenced, and therefore stays in dictBuffer.
678  *  It is important that dictBuffer outlives DDict,
679  *  it must remain read accessible throughout the lifetime of DDict */
680 ZSTDLIB_API ZSTD_DDict* ZSTD_createDDict_byReference(const void* dictBuffer, size_t dictSize);
681
682 /*! ZSTD_createDDict_advanced() :
683  *  Create a ZSTD_DDict using external alloc and free, optionally by reference */
684 ZSTDLIB_API ZSTD_DDict* ZSTD_createDDict_advanced(const void* dict, size_t dictSize,
685                                                   unsigned byReference, ZSTD_customMem customMem);
686
687 /*! ZSTD_initStaticDDict() :
688  *  Generate a digested dictionary in provided memory area.
689  *  workspace: The memory area to emplace the dictionary into.
690  *             Provided pointer must 8-bytes aligned.
691  *             It must outlive dictionary usage.
692  *  workspaceSize: Use ZSTD_estimateDDictSize()
693  *                 to determine how large workspace must be.
694  * @return : pointer to ZSTD_DDict*, or NULL if error (size too small)
695  *  Note : there is no corresponding "free" function.
696  *         Since workspace was allocated externally, it must be freed externally.
697  */
698 ZSTDLIB_API ZSTD_DDict* ZSTD_initStaticDDict(void* workspace, size_t workspaceSize,
699                                              const void* dict, size_t dictSize,
700                                              unsigned byReference);
701
702 /*! ZSTD_getDictID_fromDict() :
703  *  Provides the dictID stored within dictionary.
704  *  if @return == 0, the dictionary is not conformant with Zstandard specification.
705  *  It can still be loaded, but as a content-only dictionary. */
706 ZSTDLIB_API unsigned ZSTD_getDictID_fromDict(const void* dict, size_t dictSize);
707
708 /*! ZSTD_getDictID_fromDDict() :
709  *  Provides the dictID of the dictionary loaded into `ddict`.
710  *  If @return == 0, the dictionary is not conformant to Zstandard specification, or empty.
711  *  Non-conformant dictionaries can still be loaded, but as content-only dictionaries. */
712 ZSTDLIB_API unsigned ZSTD_getDictID_fromDDict(const ZSTD_DDict* ddict);
713
714 /*! ZSTD_getDictID_fromFrame() :
715  *  Provides the dictID required to decompressed the frame stored within `src`.
716  *  If @return == 0, the dictID could not be decoded.
717  *  This could for one of the following reasons :
718  *  - The frame does not require a dictionary to be decoded (most common case).
719  *  - The frame was built with dictID intentionally removed. Whatever dictionary is necessary is a hidden information.
720  *    Note : this use case also happens when using a non-conformant dictionary.
721  *  - `srcSize` is too small, and as a result, the frame header could not be decoded (only possible if `srcSize < ZSTD_FRAMEHEADERSIZE_MAX`).
722  *  - This is not a Zstandard frame.
723  *  When identifying the exact failure cause, it's possible to use ZSTD_getFrameHeader(), which will provide a more precise error code. */
724 ZSTDLIB_API unsigned ZSTD_getDictID_fromFrame(const void* src, size_t srcSize);
725
726
727 /********************************************************************
728 *  Advanced streaming functions
729 ********************************************************************/
730
731 /*=====   Advanced Streaming compression functions  =====*/
732 ZSTDLIB_API ZSTD_CStream* ZSTD_createCStream_advanced(ZSTD_customMem customMem);
733 ZSTDLIB_API ZSTD_CStream* ZSTD_initStaticCStream(void* workspace, size_t workspaceSize);    /**< same as ZSTD_initStaticCCtx() */
734 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 */
735 ZSTDLIB_API size_t ZSTD_initCStream_usingDict(ZSTD_CStream* zcs, const void* dict, size_t dictSize, int compressionLevel); /**< creates of an internal CDict (incompatible with static CCtx), except if dict == NULL or dictSize < 8, in which case no dict is used. */
736 ZSTDLIB_API size_t ZSTD_initCStream_advanced(ZSTD_CStream* zcs, const void* dict, size_t dictSize,
737                                              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 */
738 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 */
739 ZSTDLIB_API size_t ZSTD_initCStream_usingCDict_advanced(ZSTD_CStream* zcs, const ZSTD_CDict* cdict, ZSTD_frameParameters fParams, unsigned long long pledgedSrcSize);  /**< same as ZSTD_initCStream_usingCDict(), with control over frame parameters */
740
741 /*! ZSTD_resetCStream() :
742  *  start a new compression job, using same parameters from previous job.
743  *  This is typically useful to skip dictionary loading stage, since it will re-use it in-place..
744  *  Note that zcs must be init at least once before using ZSTD_resetCStream().
745  *  pledgedSrcSize==0 means "srcSize unknown".
746  *  If pledgedSrcSize > 0, its value must be correct, as it will be written in header, and controlled at the end.
747  *  @return : 0, or an error code (which can be tested using ZSTD_isError()) */
748 ZSTDLIB_API size_t ZSTD_resetCStream(ZSTD_CStream* zcs, unsigned long long pledgedSrcSize);
749
750
751 /*=====   Advanced Streaming decompression functions  =====*/
752 typedef enum { DStream_p_maxWindowSize } ZSTD_DStreamParameter_e;
753 ZSTDLIB_API ZSTD_DStream* ZSTD_createDStream_advanced(ZSTD_customMem customMem);
754 ZSTDLIB_API ZSTD_DStream* ZSTD_initStaticDStream(void* workspace, size_t workspaceSize);    /**< same as ZSTD_initStaticDCtx() */
755 ZSTDLIB_API size_t ZSTD_setDStreamParameter(ZSTD_DStream* zds, ZSTD_DStreamParameter_e paramType, unsigned paramValue);
756 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 */
757 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 */
758 ZSTDLIB_API size_t ZSTD_resetDStream(ZSTD_DStream* zds);  /**< re-use decompression parameters from previous init; saves dictionary loading */
759
760
761 /*********************************************************************
762 *  Buffer-less and synchronous inner streaming functions
763 *
764 *  This is an advanced API, giving full control over buffer management, for users which need direct control over memory.
765 *  But it's also a complex one, with many restrictions (documented below).
766 *  Prefer using normal streaming API for an easier experience
767 ********************************************************************* */
768
769 /**
770   Buffer-less streaming compression (synchronous mode)
771
772   A ZSTD_CCtx object is required to track streaming operations.
773   Use ZSTD_createCCtx() / ZSTD_freeCCtx() to manage resource.
774   ZSTD_CCtx object can be re-used multiple times within successive compression operations.
775
776   Start by initializing a context.
777   Use ZSTD_compressBegin(), or ZSTD_compressBegin_usingDict() for dictionary compression,
778   or ZSTD_compressBegin_advanced(), for finer parameter control.
779   It's also possible to duplicate a reference context which has already been initialized, using ZSTD_copyCCtx()
780
781   Then, consume your input using ZSTD_compressContinue().
782   There are some important considerations to keep in mind when using this advanced function :
783   - ZSTD_compressContinue() has no internal buffer. It uses externally provided buffer only.
784   - Interface is synchronous : input is consumed entirely and produce 1+ (or more) compressed blocks.
785   - Caller must ensure there is enough space in `dst` to store compressed data under worst case scenario.
786     Worst case evaluation is provided by ZSTD_compressBound().
787     ZSTD_compressContinue() doesn't guarantee recover after a failed compression.
788   - ZSTD_compressContinue() presumes prior input ***is still accessible and unmodified*** (up to maximum distance size, see WindowLog).
789     It remembers all previous contiguous blocks, plus one separated memory segment (which can itself consists of multiple contiguous blocks)
790   - ZSTD_compressContinue() detects that prior input has been overwritten when `src` buffer overlaps.
791     In which case, it will "discard" the relevant memory section from its history.
792
793   Finish a frame with ZSTD_compressEnd(), which will write the last block(s) and optional checksum.
794   It's possible to use srcSize==0, in which case, it will write a final empty block to end the frame.
795   Without last block mark, frames will be considered unfinished (corrupted) by decoders.
796
797   `ZSTD_CCtx` object can be re-used (ZSTD_compressBegin()) to compress some new frame.
798 */
799
800 /*=====   Buffer-less streaming compression functions  =====*/
801 ZSTDLIB_API size_t ZSTD_compressBegin(ZSTD_CCtx* cctx, int compressionLevel);
802 ZSTDLIB_API size_t ZSTD_compressBegin_usingDict(ZSTD_CCtx* cctx, const void* dict, size_t dictSize, int compressionLevel);
803 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 */
804 ZSTDLIB_API size_t ZSTD_compressBegin_usingCDict(ZSTD_CCtx* cctx, const ZSTD_CDict* cdict); /**< note: fails if cdict==NULL */
805 ZSTDLIB_API size_t ZSTD_compressBegin_usingCDict_advanced(ZSTD_CCtx* const cctx, const ZSTD_CDict* const cdict, ZSTD_frameParameters const fParams, unsigned long long const pledgedSrcSize);   /* compression parameters are already set within cdict. pledgedSrcSize=0 means null-size */
806 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 */
807
808 ZSTDLIB_API size_t ZSTD_compressContinue(ZSTD_CCtx* cctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize);
809 ZSTDLIB_API size_t ZSTD_compressEnd(ZSTD_CCtx* cctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize);
810
811
812
813 /*-
814   Buffer-less streaming decompression (synchronous mode)
815
816   A ZSTD_DCtx object is required to track streaming operations.
817   Use ZSTD_createDCtx() / ZSTD_freeDCtx() to manage it.
818   A ZSTD_DCtx object can be re-used multiple times.
819
820   First typical operation is to retrieve frame parameters, using ZSTD_getFrameHeader().
821   It fills a ZSTD_frameHeader structure with important information to correctly decode the frame,
822   such as minimum rolling buffer size to allocate to decompress data (`windowSize`),
823   and the dictionary ID in use.
824   (Note : content size is optional, it may not be present. 0 means : content size unknown).
825   Note that these values could be wrong, either because of data malformation, or because an attacker is spoofing deliberate false information.
826   As a consequence, check that values remain within valid application range, especially `windowSize`, before allocation.
827   Each application can set its own limit, depending on local restrictions.
828   For extended interoperability, it is recommended to support windowSize of at least 8 MB.
829   Frame header is extracted from the beginning of compressed frame, so providing only the frame's beginning is enough.
830   Data fragment must be large enough to ensure successful decoding.
831   `ZSTD_frameHeaderSize_max` bytes is guaranteed to always be large enough.
832   @result : 0 : successful decoding, the `ZSTD_frameHeader` structure is correctly filled.
833            >0 : `srcSize` is too small, please provide at least @result bytes on next attempt.
834            errorCode, which can be tested using ZSTD_isError().
835
836   Start decompression, with ZSTD_decompressBegin().
837   If decompression requires a dictionary, use ZSTD_decompressBegin_usingDict() or ZSTD_decompressBegin_usingDDict().
838   Alternatively, you can copy a prepared context, using ZSTD_copyDCtx().
839
840   Then use ZSTD_nextSrcSizeToDecompress() and ZSTD_decompressContinue() alternatively.
841   ZSTD_nextSrcSizeToDecompress() tells how many bytes to provide as 'srcSize' to ZSTD_decompressContinue().
842   ZSTD_decompressContinue() requires this _exact_ amount of bytes, or it will fail.
843
844   @result of ZSTD_decompressContinue() is the number of bytes regenerated within 'dst' (necessarily <= dstCapacity).
845   It can be zero, which is not an error; it just means ZSTD_decompressContinue() has decoded some metadata item.
846   It can also be an error code, which can be tested with ZSTD_isError().
847
848   ZSTD_decompressContinue() needs previous data blocks during decompression, up to `windowSize`.
849   They should preferably be located contiguously, prior to current block.
850   Alternatively, a round buffer of sufficient size is also possible. Sufficient size is determined by frame parameters.
851   ZSTD_decompressContinue() is very sensitive to contiguity,
852   if 2 blocks don't follow each other, make sure that either the compressor breaks contiguity at the same place,
853   or that previous contiguous segment is large enough to properly handle maximum back-reference.
854
855   A frame is fully decoded when ZSTD_nextSrcSizeToDecompress() returns zero.
856   Context can then be reset to start a new decompression.
857
858   Note : it's possible to know if next input to present is a header or a block, using ZSTD_nextInputType().
859   This information is not required to properly decode a frame.
860
861   == Special case : skippable frames ==
862
863   Skippable frames allow integration of user-defined data into a flow of concatenated frames.
864   Skippable frames will be ignored (skipped) by a decompressor. The format of skippable frames is as follows :
865   a) Skippable frame ID - 4 Bytes, Little endian format, any value from 0x184D2A50 to 0x184D2A5F
866   b) Frame Size - 4 Bytes, Little endian format, unsigned 32-bits
867   c) Frame Content - any content (User Data) of length equal to Frame Size
868   For skippable frames ZSTD_decompressContinue() always returns 0.
869   For skippable frames ZSTD_getFrameHeader() returns fparamsPtr->windowLog==0 what means that a frame is skippable.
870     Note : If fparamsPtr->frameContentSize==0, it is ambiguous: the frame might actually be a Zstd encoded frame with no content.
871            For purposes of decompression, it is valid in both cases to skip the frame using
872            ZSTD_findFrameCompressedSize to find its size in bytes.
873   It also returns Frame Size as fparamsPtr->frameContentSize.
874 */
875
876 /*=====   Buffer-less streaming decompression functions  =====*/
877 ZSTDLIB_API size_t ZSTD_getFrameHeader(ZSTD_frameHeader* zfhPtr, const void* src, size_t srcSize);   /**< doesn't consume input */
878 ZSTDLIB_API size_t ZSTD_decompressBegin(ZSTD_DCtx* dctx);
879 ZSTDLIB_API size_t ZSTD_decompressBegin_usingDict(ZSTD_DCtx* dctx, const void* dict, size_t dictSize);
880 ZSTDLIB_API size_t ZSTD_decompressBegin_usingDDict(ZSTD_DCtx* dctx, const ZSTD_DDict* ddict);
881 ZSTDLIB_API void   ZSTD_copyDCtx(ZSTD_DCtx* dctx, const ZSTD_DCtx* preparedDCtx);
882
883 ZSTDLIB_API size_t ZSTD_nextSrcSizeToDecompress(ZSTD_DCtx* dctx);
884 ZSTDLIB_API size_t ZSTD_decompressContinue(ZSTD_DCtx* dctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize);
885 typedef enum { ZSTDnit_frameHeader, ZSTDnit_blockHeader, ZSTDnit_block, ZSTDnit_lastBlock, ZSTDnit_checksum, ZSTDnit_skippableFrame } ZSTD_nextInputType_e;
886 ZSTDLIB_API ZSTD_nextInputType_e ZSTD_nextInputType(ZSTD_DCtx* dctx);
887
888
889
890 /*===   New advanced API (experimental, and compression only)  ===*/
891
892 /* notes on API design :
893  *   In this proposal, parameters are pushed one by one into an existing CCtx,
894  *   and then applied on all subsequent compression jobs.
895  *   When no parameter is ever provided, CCtx is created with compression level ZSTD_CLEVEL_DEFAULT.
896  *
897  *   This API is intended to replace all others experimental API.
898  *   It can basically do all other use cases, and even new ones.
899  *   It stands a good chance to become "stable",
900  *   after a reasonable testing period.
901  */
902
903 /* note on naming convention :
904  *   Initially, the API favored names like ZSTD_setCCtxParameter() .
905  *   In this proposal, convention is changed towards ZSTD_CCtx_setParameter() .
906  *   The main driver is that it identifies more clearly the target object type.
907  *   It feels clearer in light of potential variants :
908  *   ZSTD_CDict_setParameter() (rather than ZSTD_setCDictParameter())
909  *   ZSTD_DCtx_setParameter()  (rather than ZSTD_setDCtxParameter() )
910  *   Left variant feels easier to distinguish.
911  */
912
913 /* note on enum design :
914  * All enum will be manually set to explicit values before reaching "stable API" status */
915
916 typedef enum {
917     /* compression parameters */
918     ZSTD_p_compressionLevel=100, /* Update all compression parameters according to pre-defined cLevel table
919                               * Default level is ZSTD_CLEVEL_DEFAULT==3.
920                               * Special: value 0 means "do not change cLevel". */
921     ZSTD_p_windowLog,        /* Maximum allowed back-reference distance, expressed as power of 2.
922                               * Must be clamped between ZSTD_WINDOWLOG_MIN and ZSTD_WINDOWLOG_MAX.
923                               * Special: value 0 means "do not change windowLog". */
924     ZSTD_p_hashLog,          /* Size of the probe table, as a power of 2.
925                               * Resulting table size is (1 << (hashLog+2)).
926                               * Must be clamped between ZSTD_HASHLOG_MIN and ZSTD_HASHLOG_MAX.
927                               * Larger tables improve compression ratio of strategies <= dFast,
928                               * and improve speed of strategies > dFast.
929                               * Special: value 0 means "do not change hashLog". */
930     ZSTD_p_chainLog,         /* Size of the full-search table, as a power of 2.
931                               * Resulting table size is (1 << (chainLog+2)).
932                               * Larger tables result in better and slower compression.
933                               * This parameter is useless when using "fast" strategy.
934                               * Special: value 0 means "do not change chainLog". */
935     ZSTD_p_searchLog,        /* Number of search attempts, as a power of 2.
936                               * More attempts result in better and slower compression.
937                               * This parameter is useless when using "fast" and "dFast" strategies.
938                               * Special: value 0 means "do not change searchLog". */
939     ZSTD_p_minMatch,         /* Minimum size of searched matches (note : repCode matches can be smaller).
940                               * Larger values make faster compression and decompression, but decrease ratio.
941                               * Must be clamped between ZSTD_SEARCHLENGTH_MIN and ZSTD_SEARCHLENGTH_MAX.
942                               * Note that currently, for all strategies < btopt, effective minimum is 4.
943                               * Note that currently, for all strategies > fast, effective maximum is 6.
944                               * Special: value 0 means "do not change minMatchLength". */
945     ZSTD_p_targetLength,     /* Only useful for strategies >= btopt.
946                               * Length of Match considered "good enough" to stop search.
947                               * Larger values make compression stronger and slower.
948                               * Special: value 0 means "do not change targetLength". */
949     ZSTD_p_compressionStrategy, /* See ZSTD_strategy enum definition.
950                               * Cast selected strategy as unsigned for ZSTD_CCtx_setParameter() compatibility.
951                               * The higher the value of selected strategy, the more complex it is,
952                               * resulting in stronger and slower compression.
953                               * Special: value 0 means "do not change strategy". */
954
955     /* frame parameters */
956     ZSTD_p_contentSizeFlag=200, /* Content size is written into frame header _whenever known_ (default:1) */
957     ZSTD_p_checksumFlag,     /* A 32-bits checksum of content is written at end of frame (default:0) */
958     ZSTD_p_dictIDFlag,       /* When applicable, dictID of dictionary is provided in frame header (default:1) */
959
960     /* dictionary parameters (must be set before ZSTD_CCtx_loadDictionary) */
961     ZSTD_p_dictMode=300,     /* Select how dictionary content must be interpreted. Value must be from type ZSTD_dictMode_e.
962                               * default : 0==auto : dictionary will be "full" if it respects specification, otherwise it will be "rawContent" */
963     ZSTD_p_refDictContent,   /* Dictionary content will be referenced, instead of copied (default:0==byCopy).
964                               * It requires that dictionary buffer outlives its users */
965
966     /* multi-threading parameters */
967     ZSTD_p_nbThreads=400,    /* Select how many threads a compression job can spawn (default:1)
968                               * More threads improve speed, but also increase memory usage.
969                               * Can only receive a value > 1 if ZSTD_MULTITHREAD is enabled.
970                               * Special: value 0 means "do not change nbThreads" */
971     ZSTD_p_jobSize,          /* Size of a compression job. Each compression job is completed in parallel.
972                               * 0 means default, which is dynamically determined based on compression parameters.
973                               * Job size must be a minimum of overlapSize, or 1 KB, whichever is largest
974                               * The minimum size is automatically and transparently enforced */
975     ZSTD_p_overlapSizeLog,   /* Size of previous input reloaded at the beginning of each job.
976                               * 0 => no overlap, 6(default) => use 1/8th of windowSize, >=9 => use full windowSize */
977
978     /* advanced parameters - may not remain available after API update */
979     ZSTD_p_forceMaxWindow=1100, /* Force back-reference distances to remain < windowSize,
980                               * even when referencing into Dictionary content (default:0) */
981
982 } ZSTD_cParameter;
983
984
985 /*! ZSTD_CCtx_setParameter() :
986  *  Set one compression parameter, selected by enum ZSTD_cParameter.
987  *  Note : when `value` is an enum, cast it to unsigned for proper type checking.
988  *  @result : 0, or an error code (which can be tested with ZSTD_isError()). */
989 ZSTDLIB_API size_t ZSTD_CCtx_setParameter(ZSTD_CCtx* cctx, ZSTD_cParameter param, unsigned value);
990
991 /*! ZSTD_CCtx_setPledgedSrcSize() :
992  *  Total input data size to be compressed as a single frame.
993  *  This value will be controlled at the end, and result in error if not respected.
994  * @result : 0, or an error code (which can be tested with ZSTD_isError()).
995  *  Note 1 : 0 means zero, empty.
996  *           In order to mean "unknown content size", pass constant ZSTD_CONTENTSIZE_UNKNOWN.
997  *           Note that ZSTD_CONTENTSIZE_UNKNOWN is default value for new compression jobs.
998  *  Note 2 : If all data is provided and consumed in a single round,
999  *           this value is overriden by srcSize instead. */
1000 ZSTDLIB_API size_t ZSTD_CCtx_setPledgedSrcSize(ZSTD_CCtx* cctx, unsigned long long pledgedSrcSize);
1001
1002 /*! ZSTD_CCtx_loadDictionary() :
1003  *  Create an internal CDict from dict buffer.
1004  *  Decompression will have to use same buffer.
1005  * @result : 0, or an error code (which can be tested with ZSTD_isError()).
1006  *  Special : Adding a NULL (or 0-size) dictionary invalidates any previous dictionary,
1007  *            meaning "return to no-dictionary mode".
1008  *  Note 1 : `dict` content will be copied internally,
1009  *           except if ZSTD_p_refDictContent is set before loading.
1010  *  Note 2 : Loading a dictionary involves building tables, which are dependent on compression parameters.
1011  *           For this reason, compression parameters cannot be changed anymore after loading a dictionary.
1012  *           It's also a CPU-heavy operation, with non-negligible impact on latency.
1013  *  Note 3 : Dictionary will be used for all future compression jobs.
1014  *           To return to "no-dictionary" situation, load a NULL dictionary */
1015 ZSTDLIB_API size_t ZSTD_CCtx_loadDictionary(ZSTD_CCtx* cctx, const void* dict, size_t dictSize);
1016
1017 /*! ZSTD_CCtx_refCDict() :
1018  *  Reference a prepared dictionary, to be used for all next compression jobs.
1019  *  Note that compression parameters are enforced from within CDict,
1020  *  and supercede any compression parameter previously set within CCtx.
1021  *  The dictionary will remain valid for future compression jobs using same CCtx.
1022  * @result : 0, or an error code (which can be tested with ZSTD_isError()).
1023  *  Special : adding a NULL CDict means "return to no-dictionary mode".
1024  *  Note 1 : Currently, only one dictionary can be managed.
1025  *           Adding a new dictionary effectively "discards" any previous one.
1026  *  Note 2 : CDict is just referenced, its lifetime must outlive CCtx.
1027  */
1028 ZSTDLIB_API size_t ZSTD_CCtx_refCDict(ZSTD_CCtx* cctx, const ZSTD_CDict* cdict);
1029
1030 /*! ZSTD_CCtx_refPrefix() :
1031  *  Reference a prefix (single-usage dictionary) for next compression job.
1032  *  Decompression need same prefix to properly regenerate data.
1033  *  Prefix is **only used once**. Tables are discarded at end of compression job.
1034  *  Subsequent compression jobs will be done without prefix (if none is explicitly referenced).
1035  *  If there is a need to use same prefix multiple times, consider embedding it into a ZSTD_CDict instead.
1036  * @result : 0, or an error code (which can be tested with ZSTD_isError()).
1037  *  Special : Adding any prefix (including NULL) invalidates any previous prefix or dictionary
1038  *  Note 1 : Prefix buffer is referenced. It must outlive compression job.
1039  *  Note 2 : Referencing a prefix involves building tables, which are dependent on compression parameters.
1040  *           It's a CPU-heavy operation, with non-negligible impact on latency.
1041  *  Note 3 : it's possible to alter ZSTD_p_dictMode using ZSTD_CCtx_setParameter() */
1042 ZSTDLIB_API size_t ZSTD_CCtx_refPrefix(ZSTD_CCtx* cctx, const void* prefix, size_t prefixSize);
1043
1044
1045
1046 typedef enum {
1047     ZSTD_e_continue=0, /* collect more data, encoder transparently decides when to output result, for optimal conditions */
1048     ZSTD_e_flush,      /* flush any data provided so far - frame will continue, future data can still reference previous data for better compression */
1049     ZSTD_e_end         /* flush any remaining data and ends current frame. Any future compression starts a new frame. */
1050 } ZSTD_EndDirective;
1051
1052 /*! ZSTD_compress_generic() :
1053  *  Behave about the same as ZSTD_compressStream. To note :
1054  *  - Compression parameters are pushed into CCtx before starting compression, using ZSTD_CCtx_setParameter()
1055  *  - Compression parameters cannot be changed once compression is started.
1056  *  - *dstPos must be <= dstCapacity, *srcPos must be <= srcSize
1057  *  - *dspPos and *srcPos will be updated. They are guaranteed to remain below their respective limit.
1058  *  - @return provides the minimum amount of data still to flush from internal buffers
1059  *            or an error code, which can be tested using ZSTD_isError().
1060  *            if @return != 0, flush is not fully completed, there is some data left within internal buffers.
1061  *  - after a ZSTD_e_end directive, if internal buffer is not fully flushed,
1062  *            only ZSTD_e_end or ZSTD_e_flush operations are allowed.
1063  *            It is necessary to fully flush internal buffers
1064  *            before starting a new compression job, or changing compression parameters.
1065  */
1066 ZSTDLIB_API size_t ZSTD_compress_generic (ZSTD_CCtx* cctx,
1067                                           ZSTD_outBuffer* output,
1068                                           ZSTD_inBuffer* input,
1069                                           ZSTD_EndDirective endOp);
1070
1071 /*! ZSTD_CCtx_reset() :
1072  *  Return a CCtx to clean state.
1073  *  Useful after an error, or to interrupt an ongoing compression job and start a new one.
1074  *  Any internal data not yet flushed is cancelled.
1075  *  Dictionary (if any) is dropped.
1076  *  It's possible to modify compression parameters after a reset.
1077  */
1078 ZSTDLIB_API void ZSTD_CCtx_reset(ZSTD_CCtx* cctx);   /* Not ready yet ! */
1079
1080
1081 /*! ZSTD_compress_generic_simpleArgs() :
1082  *  Same as ZSTD_compress_generic(),
1083  *  but using only integral types as arguments.
1084  *  Argument list is larger and less expressive than ZSTD_{in,out}Buffer,
1085  *  but can be helpful for binders from dynamic languages
1086  *  which have troubles handling structures containing memory pointers.
1087  */
1088 size_t ZSTD_compress_generic_simpleArgs (
1089                             ZSTD_CCtx* cctx,
1090                             void* dst, size_t dstCapacity, size_t* dstPos,
1091                       const void* src, size_t srcSize, size_t* srcPos,
1092                             ZSTD_EndDirective endOp);
1093
1094
1095
1096 /**
1097     Block functions
1098
1099     Block functions produce and decode raw zstd blocks, without frame metadata.
1100     Frame metadata cost is typically ~18 bytes, which can be non-negligible for very small blocks (< 100 bytes).
1101     User will have to take in charge required information to regenerate data, such as compressed and content sizes.
1102
1103     A few rules to respect :
1104     - Compressing and decompressing require a context structure
1105       + Use ZSTD_createCCtx() and ZSTD_createDCtx()
1106     - It is necessary to init context before starting
1107       + compression : any ZSTD_compressBegin*() variant, including with dictionary
1108       + decompression : any ZSTD_decompressBegin*() variant, including with dictionary
1109       + copyCCtx() and copyDCtx() can be used too
1110     - Block size is limited, it must be <= ZSTD_getBlockSize() <= ZSTD_BLOCKSIZE_MAX
1111       + If input is larger than a block size, it's necessary to split input data into multiple blocks
1112       + For inputs larger than a single block size, consider using the regular ZSTD_compress() instead.
1113         Frame metadata is not that costly, and quickly becomes negligible as source size grows larger.
1114     - When a block is considered not compressible enough, ZSTD_compressBlock() result will be zero.
1115       In which case, nothing is produced into `dst`.
1116       + User must test for such outcome and deal directly with uncompressed data
1117       + ZSTD_decompressBlock() doesn't accept uncompressed data as input !!!
1118       + In case of multiple successive blocks, should some of them be uncompressed,
1119         decoder must be informed of their existence in order to follow proper history.
1120         Use ZSTD_insertBlock() for such a case.
1121 */
1122
1123 #define ZSTD_BLOCKSIZELOG_MAX 17
1124 #define ZSTD_BLOCKSIZE_MAX   (1<<ZSTD_BLOCKSIZELOG_MAX)   /* define, for static allocation */
1125 /*=====   Raw zstd block functions  =====*/
1126 ZSTDLIB_API size_t ZSTD_getBlockSize   (const ZSTD_CCtx* cctx);
1127 ZSTDLIB_API size_t ZSTD_compressBlock  (ZSTD_CCtx* cctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize);
1128 ZSTDLIB_API size_t ZSTD_decompressBlock(ZSTD_DCtx* dctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize);
1129 ZSTDLIB_API size_t ZSTD_insertBlock(ZSTD_DCtx* dctx, const void* blockStart, size_t blockSize);  /**< insert block into `dctx` history. Useful for uncompressed blocks */
1130
1131
1132 #endif   /* ZSTD_H_ZSTD_STATIC_LINKING_ONLY */
1133
1134 #if defined (__cplusplus)
1135 }
1136 #endif