Coverage Report

Created: 2025-07-11 06:34

/src/zstd/lib/zstd.h
Line
Count
Source (jump to first uncovered line)
1
/*
2
 * Copyright (c) Meta Platforms, Inc. and affiliates.
3
 * All rights reserved.
4
 *
5
 * This source code is licensed under both the BSD-style license (found in the
6
 * LICENSE file in the root directory of this source tree) and the GPLv2 (found
7
 * in the COPYING file in the root directory of this source tree).
8
 * You may select, at your option, one of the above-listed licenses.
9
 */
10
11
#ifndef ZSTD_H_235446
12
#define ZSTD_H_235446
13
14
15
/* ======   Dependencies   ======*/
16
#include <stddef.h>   /* size_t */
17
18
#include "zstd_errors.h" /* list of errors */
19
#if defined(ZSTD_STATIC_LINKING_ONLY) && !defined(ZSTD_H_ZSTD_STATIC_LINKING_ONLY)
20
#include <limits.h>   /* INT_MAX */
21
#endif /* ZSTD_STATIC_LINKING_ONLY */
22
23
#if defined (__cplusplus)
24
extern "C" {
25
#endif
26
27
/* =====   ZSTDLIB_API : control library symbols visibility   ===== */
28
#ifndef ZSTDLIB_VISIBLE
29
   /* Backwards compatibility with old macro name */
30
#  ifdef ZSTDLIB_VISIBILITY
31
#    define ZSTDLIB_VISIBLE ZSTDLIB_VISIBILITY
32
#  elif defined(__GNUC__) && (__GNUC__ >= 4) && !defined(__MINGW32__)
33
#    define ZSTDLIB_VISIBLE __attribute__ ((visibility ("default")))
34
#  else
35
#    define ZSTDLIB_VISIBLE
36
#  endif
37
#endif
38
39
#ifndef ZSTDLIB_HIDDEN
40
#  if defined(__GNUC__) && (__GNUC__ >= 4) && !defined(__MINGW32__)
41
#    define ZSTDLIB_HIDDEN __attribute__ ((visibility ("hidden")))
42
#  else
43
#    define ZSTDLIB_HIDDEN
44
#  endif
45
#endif
46
47
#if defined(ZSTD_DLL_EXPORT) && (ZSTD_DLL_EXPORT==1)
48
#  define ZSTDLIB_API __declspec(dllexport) ZSTDLIB_VISIBLE
49
#elif defined(ZSTD_DLL_IMPORT) && (ZSTD_DLL_IMPORT==1)
50
#  define ZSTDLIB_API __declspec(dllimport) ZSTDLIB_VISIBLE /* It isn't required but allows to generate better code, saving a function pointer load from the IAT and an indirect jump.*/
51
#else
52
#  define ZSTDLIB_API ZSTDLIB_VISIBLE
53
#endif
54
55
/* Deprecation warnings :
56
 * Should these warnings be a problem, it is generally possible to disable them,
57
 * typically with -Wno-deprecated-declarations for gcc or _CRT_SECURE_NO_WARNINGS in Visual.
58
 * Otherwise, it's also possible to define ZSTD_DISABLE_DEPRECATE_WARNINGS.
59
 */
60
#ifdef ZSTD_DISABLE_DEPRECATE_WARNINGS
61
#  define ZSTD_DEPRECATED(message) /* disable deprecation warnings */
62
#else
63
#  if defined (__cplusplus) && (__cplusplus >= 201402) /* C++14 or greater */
64
#    define ZSTD_DEPRECATED(message) [[deprecated(message)]]
65
#  elif (defined(GNUC) && (GNUC > 4 || (GNUC == 4 && GNUC_MINOR >= 5))) || defined(__clang__) || defined(__IAR_SYSTEMS_ICC__)
66
#    define ZSTD_DEPRECATED(message) __attribute__((deprecated(message)))
67
#  elif defined(__GNUC__) && (__GNUC__ >= 3)
68
#    define ZSTD_DEPRECATED(message) __attribute__((deprecated))
69
#  elif defined(_MSC_VER)
70
#    define ZSTD_DEPRECATED(message) __declspec(deprecated(message))
71
#  else
72
#    pragma message("WARNING: You need to implement ZSTD_DEPRECATED for this compiler")
73
#    define ZSTD_DEPRECATED(message)
74
#  endif
75
#endif /* ZSTD_DISABLE_DEPRECATE_WARNINGS */
76
77
78
/*******************************************************************************
79
  Introduction
80
81
  zstd, short for Zstandard, is a fast lossless compression algorithm, targeting
82
  real-time compression scenarios at zlib-level and better compression ratios.
83
  The zstd compression library provides in-memory compression and decompression
84
  functions.
85
86
  The library supports regular compression levels from 1 up to ZSTD_maxCLevel(),
87
  which is currently 22. Levels >= 20, labeled `--ultra`, should be used with
88
  caution, as they require more memory. The library also offers negative
89
  compression levels, which extend the range of speed vs. ratio preferences.
90
  The lower the level, the faster the speed (at the cost of compression).
91
92
  Compression can be done in:
93
    - a single step (described as Simple API)
94
    - a single step, reusing a context (described as Explicit context)
95
    - unbounded multiple steps (described as Streaming compression)
96
97
  The compression ratio achievable on small data can be highly improved using
98
  a dictionary. Dictionary compression can be performed in:
99
    - a single step (described as Simple dictionary API)
100
    - a single step, reusing a dictionary (described as Bulk-processing
101
      dictionary API)
102
103
  Advanced experimental functions can be accessed using
104
  `#define ZSTD_STATIC_LINKING_ONLY` before including zstd.h.
105
106
  Advanced experimental APIs should never be used with a dynamically-linked
107
  library. They are not "stable"; their definitions or signatures may change in
108
  the future. Only static linking is allowed.
109
*******************************************************************************/
110
111
/*------   Version   ------*/
112
0
#define ZSTD_VERSION_MAJOR    1
113
0
#define ZSTD_VERSION_MINOR    5
114
0
#define ZSTD_VERSION_RELEASE  8
115
0
#define ZSTD_VERSION_NUMBER  (ZSTD_VERSION_MAJOR *100*100 + ZSTD_VERSION_MINOR *100 + ZSTD_VERSION_RELEASE)
116
117
/*! ZSTD_versionNumber() :
118
 *  Return runtime library version, the value is (MAJOR*100*100 + MINOR*100 + RELEASE). */
119
ZSTDLIB_API unsigned ZSTD_versionNumber(void);
120
121
#define ZSTD_LIB_VERSION ZSTD_VERSION_MAJOR.ZSTD_VERSION_MINOR.ZSTD_VERSION_RELEASE
122
0
#define ZSTD_QUOTE(str) #str
123
0
#define ZSTD_EXPAND_AND_QUOTE(str) ZSTD_QUOTE(str)
124
0
#define ZSTD_VERSION_STRING ZSTD_EXPAND_AND_QUOTE(ZSTD_LIB_VERSION)
125
126
/*! ZSTD_versionString() :
127
 *  Return runtime library version, like "1.4.5". Requires v1.3.0+. */
128
ZSTDLIB_API const char* ZSTD_versionString(void);
129
130
/* *************************************
131
 *  Default constant
132
 ***************************************/
133
#ifndef ZSTD_CLEVEL_DEFAULT
134
27.4k
#  define ZSTD_CLEVEL_DEFAULT 3
135
#endif
136
137
/* *************************************
138
 *  Constants
139
 ***************************************/
140
141
/* All magic numbers are supposed read/written to/from files/memory using little-endian convention */
142
117k
#define ZSTD_MAGICNUMBER            0xFD2FB528    /* valid since v0.8.0 */
143
0
#define ZSTD_MAGIC_DICTIONARY       0xEC30A437    /* valid since v0.7.0 */
144
44.8k
#define ZSTD_MAGIC_SKIPPABLE_START  0x184D2A50    /* all 16 values, from 0x184D2A50 to 0x184D2A5F, signal the beginning of a skippable frame */
145
44.8k
#define ZSTD_MAGIC_SKIPPABLE_MASK   0xFFFFFFF0
146
147
139M
#define ZSTD_BLOCKSIZELOG_MAX  17
148
167M
#define ZSTD_BLOCKSIZE_MAX     (1<<ZSTD_BLOCKSIZELOG_MAX)
149
150
151
/***************************************
152
*  Simple Core API
153
***************************************/
154
/*! ZSTD_compress() :
155
 *  Compresses `src` content as a single zstd compressed frame into already allocated `dst`.
156
 *  NOTE: Providing `dstCapacity >= ZSTD_compressBound(srcSize)` guarantees that zstd will have
157
 *        enough space to successfully compress the data.
158
 *  @return : compressed size written into `dst` (<= `dstCapacity),
159
 *            or an error code if it fails (which can be tested using ZSTD_isError()). */
160
ZSTDLIB_API size_t ZSTD_compress( void* dst, size_t dstCapacity,
161
                            const void* src, size_t srcSize,
162
                                  int compressionLevel);
163
164
/*! ZSTD_decompress() :
165
 * `compressedSize` : must be the _exact_ size of some number of compressed and/or skippable frames.
166
 *  Multiple compressed frames can be decompressed at once with this method.
167
 *  The result will be the concatenation of all decompressed frames, back to back.
168
 * `dstCapacity` is an upper bound of originalSize to regenerate.
169
 *  First frame's decompressed size can be extracted using ZSTD_getFrameContentSize().
170
 *  If maximum upper bound isn't known, prefer using streaming mode to decompress data.
171
 * @return : the number of bytes decompressed into `dst` (<= `dstCapacity`),
172
 *           or an errorCode if it fails (which can be tested using ZSTD_isError()). */
173
ZSTDLIB_API size_t ZSTD_decompress( void* dst, size_t dstCapacity,
174
                              const void* src, size_t compressedSize);
175
176
177
/*======  Decompression helper functions  ======*/
178
179
/*! ZSTD_getFrameContentSize() : requires v1.3.0+
180
 * `src` should point to the start of a ZSTD encoded frame.
181
 * `srcSize` must be at least as large as the frame header.
182
 *           hint : any size >= `ZSTD_frameHeaderSize_max` is large enough.
183
 * @return : - decompressed size of `src` frame content, if known
184
 *           - ZSTD_CONTENTSIZE_UNKNOWN if the size cannot be determined
185
 *           - ZSTD_CONTENTSIZE_ERROR if an error occurred (e.g. invalid magic number, srcSize too small)
186
 *  note 1 : a 0 return value means the frame is valid but "empty".
187
 *           When invoking this method on a skippable frame, it will return 0.
188
 *  note 2 : decompressed size is an optional field, it may not be present (typically in streaming mode).
189
 *           When `return==ZSTD_CONTENTSIZE_UNKNOWN`, data to decompress could be any size.
190
 *           In which case, it's necessary to use streaming mode to decompress data.
191
 *           Optionally, application can rely on some implicit limit,
192
 *           as ZSTD_decompress() only needs an upper bound of decompressed size.
193
 *           (For example, data could be necessarily cut into blocks <= 16 KB).
194
 *  note 3 : decompressed size is always present when compression is completed using single-pass functions,
195
 *           such as ZSTD_compress(), ZSTD_compressCCtx() ZSTD_compress_usingDict() or ZSTD_compress_usingCDict().
196
 *  note 4 : decompressed size can be very large (64-bits value),
197
 *           potentially larger than what local system can handle as a single memory segment.
198
 *           In which case, it's necessary to use streaming mode to decompress data.
199
 *  note 5 : If source is untrusted, decompressed size could be wrong or intentionally modified.
200
 *           Always ensure return value fits within application's authorized limits.
201
 *           Each application can set its own limits.
202
 *  note 6 : This function replaces ZSTD_getDecompressedSize() */
203
550k
#define ZSTD_CONTENTSIZE_UNKNOWN (0ULL - 1)
204
0
#define ZSTD_CONTENTSIZE_ERROR   (0ULL - 2)
205
ZSTDLIB_API unsigned long long ZSTD_getFrameContentSize(const void *src, size_t srcSize);
206
207
/*! ZSTD_getDecompressedSize() (obsolete):
208
 *  This function is now obsolete, in favor of ZSTD_getFrameContentSize().
209
 *  Both functions work the same way, but ZSTD_getDecompressedSize() blends
210
 *  "empty", "unknown" and "error" results to the same return value (0),
211
 *  while ZSTD_getFrameContentSize() gives them separate return values.
212
 * @return : decompressed size of `src` frame content _if known and not empty_, 0 otherwise. */
213
ZSTD_DEPRECATED("Replaced by ZSTD_getFrameContentSize")
214
ZSTDLIB_API unsigned long long ZSTD_getDecompressedSize(const void* src, size_t srcSize);
215
216
/*! ZSTD_findFrameCompressedSize() : Requires v1.4.0+
217
 * `src` should point to the start of a ZSTD frame or skippable frame.
218
 * `srcSize` must be >= first frame size
219
 * @return : the compressed size of the first frame starting at `src`,
220
 *           suitable to pass as `srcSize` to `ZSTD_decompress` or similar,
221
 *           or an error code if input is invalid
222
 *  Note 1: this method is called _find*() because it's not enough to read the header,
223
 *          it may have to scan through the frame's content, to reach its end.
224
 *  Note 2: this method also works with Skippable Frames. In which case,
225
 *          it returns the size of the complete skippable frame,
226
 *          which is always equal to its content size + 8 bytes for headers. */
227
ZSTDLIB_API size_t ZSTD_findFrameCompressedSize(const void* src, size_t srcSize);
228
229
230
/*======  Compression helper functions  ======*/
231
232
/*! ZSTD_compressBound() :
233
 * maximum compressed size in worst case single-pass scenario.
234
 * When invoking `ZSTD_compress()`, or any other one-pass compression function,
235
 * it's recommended to provide @dstCapacity >= ZSTD_compressBound(srcSize)
236
 * as it eliminates one potential failure scenario,
237
 * aka not enough room in dst buffer to write the compressed frame.
238
 * Note : ZSTD_compressBound() itself can fail, if @srcSize >= ZSTD_MAX_INPUT_SIZE .
239
 *        In which case, ZSTD_compressBound() will return an error code
240
 *        which can be tested using ZSTD_isError().
241
 *
242
 * ZSTD_COMPRESSBOUND() :
243
 * same as ZSTD_compressBound(), but as a macro.
244
 * It can be used to produce constants, which can be useful for static allocation,
245
 * for example to size a static array on stack.
246
 * Will produce constant value 0 if srcSize is too large.
247
 */
248
144k
#define ZSTD_MAX_INPUT_SIZE ((sizeof(size_t)==8) ? 0xFF00FF00FF00FF00ULL : 0xFF00FF00U)
249
144k
#define ZSTD_COMPRESSBOUND(srcSize)   (((size_t)(srcSize) >= ZSTD_MAX_INPUT_SIZE) ? 0 : (srcSize) + ((srcSize)>>8) + (((srcSize) < (128<<10)) ? (((128<<10) - (srcSize)) >> 11) /* margin, from 64 to 0 */ : 0))  /* this formula ensures that bound(A) + bound(B) <= bound(A+B) as long as A and B >= 128 KB */
250
ZSTDLIB_API size_t ZSTD_compressBound(size_t srcSize); /*!< maximum compressed size in worst case single-pass scenario */
251
252
253
/*======  Error helper functions  ======*/
254
/* ZSTD_isError() :
255
 * Most ZSTD_* functions returning a size_t value can be tested for error,
256
 * using ZSTD_isError().
257
 * @return 1 if error, 0 otherwise
258
 */
259
ZSTDLIB_API unsigned     ZSTD_isError(size_t result);      /*!< tells if a `size_t` function result is an error code */
260
ZSTDLIB_API ZSTD_ErrorCode ZSTD_getErrorCode(size_t functionResult); /* convert a result into an error code, which can be compared to error enum list */
261
ZSTDLIB_API const char*  ZSTD_getErrorName(size_t result); /*!< provides readable string from a function result */
262
ZSTDLIB_API int          ZSTD_minCLevel(void);             /*!< minimum negative compression level allowed, requires v1.4.0+ */
263
ZSTDLIB_API int          ZSTD_maxCLevel(void);             /*!< maximum compression level available */
264
ZSTDLIB_API int          ZSTD_defaultCLevel(void);         /*!< default compression level, specified by ZSTD_CLEVEL_DEFAULT, requires v1.5.0+ */
265
266
267
/***************************************
268
*  Explicit context
269
***************************************/
270
/*= Compression context
271
 *  When compressing many times,
272
 *  it is recommended to allocate a compression context just once,
273
 *  and reuse it for each successive compression operation.
274
 *  This will make the workload easier for system's memory.
275
 *  Note : re-using context is just a speed / resource optimization.
276
 *         It doesn't change the compression ratio, which remains identical.
277
 *  Note 2: For parallel execution in multi-threaded environments,
278
 *         use one different context per thread .
279
 */
280
typedef struct ZSTD_CCtx_s ZSTD_CCtx;
281
ZSTDLIB_API ZSTD_CCtx* ZSTD_createCCtx(void);
282
ZSTDLIB_API size_t     ZSTD_freeCCtx(ZSTD_CCtx* cctx);  /* compatible with NULL pointer */
283
284
/*! ZSTD_compressCCtx() :
285
 *  Same as ZSTD_compress(), using an explicit ZSTD_CCtx.
286
 *  Important : in order to mirror `ZSTD_compress()` behavior,
287
 *  this function compresses at the requested compression level,
288
 *  __ignoring any other advanced parameter__ .
289
 *  If any advanced parameter was set using the advanced API,
290
 *  they will all be reset. Only @compressionLevel remains.
291
 */
292
ZSTDLIB_API size_t ZSTD_compressCCtx(ZSTD_CCtx* cctx,
293
                                     void* dst, size_t dstCapacity,
294
                               const void* src, size_t srcSize,
295
                                     int compressionLevel);
296
297
/*= Decompression context
298
 *  When decompressing many times,
299
 *  it is recommended to allocate a context only once,
300
 *  and reuse it for each successive compression operation.
301
 *  This will make workload friendlier for system's memory.
302
 *  Use one context per thread for parallel execution. */
303
typedef struct ZSTD_DCtx_s ZSTD_DCtx;
304
ZSTDLIB_API ZSTD_DCtx* ZSTD_createDCtx(void);
305
ZSTDLIB_API size_t     ZSTD_freeDCtx(ZSTD_DCtx* dctx);  /* accept NULL pointer */
306
307
/*! ZSTD_decompressDCtx() :
308
 *  Same as ZSTD_decompress(),
309
 *  requires an allocated ZSTD_DCtx.
310
 *  Compatible with sticky parameters (see below).
311
 */
312
ZSTDLIB_API size_t ZSTD_decompressDCtx(ZSTD_DCtx* dctx,
313
                                       void* dst, size_t dstCapacity,
314
                                 const void* src, size_t srcSize);
315
316
317
/*********************************************
318
*  Advanced compression API (Requires v1.4.0+)
319
**********************************************/
320
321
/* API design :
322
 *   Parameters are pushed one by one into an existing context,
323
 *   using ZSTD_CCtx_set*() functions.
324
 *   Pushed parameters are sticky : they are valid for next compressed frame, and any subsequent frame.
325
 *   "sticky" parameters are applicable to `ZSTD_compress2()` and `ZSTD_compressStream*()` !
326
 *   __They do not apply to one-shot variants such as ZSTD_compressCCtx()__ .
327
 *
328
 *   It's possible to reset all parameters to "default" using ZSTD_CCtx_reset().
329
 *
330
 *   This API supersedes all other "advanced" API entry points in the experimental section.
331
 *   In the future, we expect to remove API entry points from experimental which are redundant with this API.
332
 */
333
334
335
/* Compression strategies, listed from fastest to strongest */
336
typedef enum { ZSTD_fast=1,
337
               ZSTD_dfast=2,
338
               ZSTD_greedy=3,
339
               ZSTD_lazy=4,
340
               ZSTD_lazy2=5,
341
               ZSTD_btlazy2=6,
342
               ZSTD_btopt=7,
343
               ZSTD_btultra=8,
344
               ZSTD_btultra2=9
345
               /* note : new strategies _might_ be added in the future.
346
                         Only the order (from fast to strong) is guaranteed */
347
} ZSTD_strategy;
348
349
typedef enum {
350
351
    /* compression parameters
352
     * Note: When compressing with a ZSTD_CDict these parameters are superseded
353
     * by the parameters used to construct the ZSTD_CDict.
354
     * See ZSTD_CCtx_refCDict() for more info (superseded-by-cdict). */
355
    ZSTD_c_compressionLevel=100, /* Set compression parameters according to pre-defined cLevel table.
356
                              * Note that exact compression parameters are dynamically determined,
357
                              * depending on both compression level and srcSize (when known).
358
                              * Default level is ZSTD_CLEVEL_DEFAULT==3.
359
                              * Special: value 0 means default, which is controlled by ZSTD_CLEVEL_DEFAULT.
360
                              * Note 1 : it's possible to pass a negative compression level.
361
                              * Note 2 : setting a level does not automatically set all other compression parameters
362
                              *   to default. Setting this will however eventually dynamically impact the compression
363
                              *   parameters which have not been manually set. The manually set
364
                              *   ones will 'stick'. */
365
    /* Advanced compression parameters :
366
     * It's possible to pin down compression parameters to some specific values.
367
     * In which case, these values are no longer dynamically selected by the compressor */
368
    ZSTD_c_windowLog=101,    /* Maximum allowed back-reference distance, expressed as power of 2.
369
                              * This will set a memory budget for streaming decompression,
370
                              * with larger values requiring more memory
371
                              * and typically compressing more.
372
                              * Must be clamped between ZSTD_WINDOWLOG_MIN and ZSTD_WINDOWLOG_MAX.
373
                              * Special: value 0 means "use default windowLog".
374
                              * Note: Using a windowLog greater than ZSTD_WINDOWLOG_LIMIT_DEFAULT
375
                              *       requires explicitly allowing such size at streaming decompression stage. */
376
    ZSTD_c_hashLog=102,      /* Size of the initial probe table, as a power of 2.
377
                              * Resulting memory usage is (1 << (hashLog+2)).
378
                              * Must be clamped between ZSTD_HASHLOG_MIN and ZSTD_HASHLOG_MAX.
379
                              * Larger tables improve compression ratio of strategies <= dFast,
380
                              * and improve speed of strategies > dFast.
381
                              * Special: value 0 means "use default hashLog". */
382
    ZSTD_c_chainLog=103,     /* Size of the multi-probe search table, as a power of 2.
383
                              * Resulting memory usage is (1 << (chainLog+2)).
384
                              * Must be clamped between ZSTD_CHAINLOG_MIN and ZSTD_CHAINLOG_MAX.
385
                              * Larger tables result in better and slower compression.
386
                              * This parameter is useless for "fast" strategy.
387
                              * It's still useful when using "dfast" strategy,
388
                              * in which case it defines a secondary probe table.
389
                              * Special: value 0 means "use default chainLog". */
390
    ZSTD_c_searchLog=104,    /* Number of search attempts, as a power of 2.
391
                              * More attempts result in better and slower compression.
392
                              * This parameter is useless for "fast" and "dFast" strategies.
393
                              * Special: value 0 means "use default searchLog". */
394
    ZSTD_c_minMatch=105,     /* Minimum size of searched matches.
395
                              * Note that Zstandard can still find matches of smaller size,
396
                              * it just tweaks its search algorithm to look for this size and larger.
397
                              * Larger values increase compression and decompression speed, but decrease ratio.
398
                              * Must be clamped between ZSTD_MINMATCH_MIN and ZSTD_MINMATCH_MAX.
399
                              * Note that currently, for all strategies < btopt, effective minimum is 4.
400
                              *                    , for all strategies > fast, effective maximum is 6.
401
                              * Special: value 0 means "use default minMatchLength". */
402
    ZSTD_c_targetLength=106, /* Impact of this field depends on strategy.
403
                              * For strategies btopt, btultra & btultra2:
404
                              *     Length of Match considered "good enough" to stop search.
405
                              *     Larger values make compression stronger, and slower.
406
                              * For strategy fast:
407
                              *     Distance between match sampling.
408
                              *     Larger values make compression faster, and weaker.
409
                              * Special: value 0 means "use default targetLength". */
410
    ZSTD_c_strategy=107,     /* See ZSTD_strategy enum definition.
411
                              * The higher the value of selected strategy, the more complex it is,
412
                              * resulting in stronger and slower compression.
413
                              * Special: value 0 means "use default strategy". */
414
415
    ZSTD_c_targetCBlockSize=130, /* v1.5.6+
416
                                  * Attempts to fit compressed block size into approximately targetCBlockSize.
417
                                  * Bound by ZSTD_TARGETCBLOCKSIZE_MIN and ZSTD_TARGETCBLOCKSIZE_MAX.
418
                                  * Note that it's not a guarantee, just a convergence target (default:0).
419
                                  * No target when targetCBlockSize == 0.
420
                                  * This is helpful in low bandwidth streaming environments to improve end-to-end latency,
421
                                  * when a client can make use of partial documents (a prominent example being Chrome).
422
                                  * Note: this parameter is stable since v1.5.6.
423
                                  * It was present as an experimental parameter in earlier versions,
424
                                  * but it's not recommended using it with earlier library versions
425
                                  * due to massive performance regressions.
426
                                  */
427
    /* LDM mode parameters */
428
    ZSTD_c_enableLongDistanceMatching=160, /* Enable long distance matching.
429
                                     * This parameter is designed to improve compression ratio
430
                                     * for large inputs, by finding large matches at long distance.
431
                                     * It increases memory usage and window size.
432
                                     * Note: enabling this parameter increases default ZSTD_c_windowLog to 128 MB
433
                                     * except when expressly set to a different value.
434
                                     * Note: will be enabled by default if ZSTD_c_windowLog >= 128 MB and
435
                                     * compression strategy >= ZSTD_btopt (== compression level 16+) */
436
    ZSTD_c_ldmHashLog=161,   /* Size of the table for long distance matching, as a power of 2.
437
                              * Larger values increase memory usage and compression ratio,
438
                              * but decrease compression speed.
439
                              * Must be clamped between ZSTD_HASHLOG_MIN and ZSTD_HASHLOG_MAX
440
                              * default: windowlog - 7.
441
                              * Special: value 0 means "automatically determine hashlog". */
442
    ZSTD_c_ldmMinMatch=162,  /* Minimum match size for long distance matcher.
443
                              * Larger/too small values usually decrease compression ratio.
444
                              * Must be clamped between ZSTD_LDM_MINMATCH_MIN and ZSTD_LDM_MINMATCH_MAX.
445
                              * Special: value 0 means "use default value" (default: 64). */
446
    ZSTD_c_ldmBucketSizeLog=163, /* Log size of each bucket in the LDM hash table for collision resolution.
447
                              * Larger values improve collision resolution but decrease compression speed.
448
                              * The maximum value is ZSTD_LDM_BUCKETSIZELOG_MAX.
449
                              * Special: value 0 means "use default value" (default: 3). */
450
    ZSTD_c_ldmHashRateLog=164, /* Frequency of inserting/looking up entries into the LDM hash table.
451
                              * Must be clamped between 0 and (ZSTD_WINDOWLOG_MAX - ZSTD_HASHLOG_MIN).
452
                              * Default is MAX(0, (windowLog - ldmHashLog)), optimizing hash table usage.
453
                              * Larger values improve compression speed.
454
                              * Deviating far from default value will likely result in a compression ratio decrease.
455
                              * Special: value 0 means "automatically determine hashRateLog". */
456
457
    /* frame parameters */
458
    ZSTD_c_contentSizeFlag=200, /* Content size will be written into frame header _whenever known_ (default:1)
459
                              * Content size must be known at the beginning of compression.
460
                              * This is automatically the case when using ZSTD_compress2(),
461
                              * For streaming scenarios, content size must be provided with ZSTD_CCtx_setPledgedSrcSize() */
462
    ZSTD_c_checksumFlag=201, /* A 32-bits checksum of content is written at end of frame (default:0) */
463
    ZSTD_c_dictIDFlag=202,   /* When applicable, dictionary's ID is written into frame header (default:1) */
464
465
    /* multi-threading parameters */
466
    /* These parameters are only active if multi-threading is enabled (compiled with build macro ZSTD_MULTITHREAD).
467
     * Otherwise, trying to set any other value than default (0) will be a no-op and return an error.
468
     * In a situation where it's unknown if the linked library supports multi-threading or not,
469
     * setting ZSTD_c_nbWorkers to any value >= 1 and consulting the return value provides a quick way to check this property.
470
     */
471
    ZSTD_c_nbWorkers=400,    /* Select how many threads will be spawned to compress in parallel.
472
                              * When nbWorkers >= 1, triggers asynchronous mode when invoking ZSTD_compressStream*() :
473
                              * ZSTD_compressStream*() consumes input and flush output if possible, but immediately gives back control to caller,
474
                              * while compression is performed in parallel, within worker thread(s).
475
                              * (note : a strong exception to this rule is when first invocation of ZSTD_compressStream2() sets ZSTD_e_end :
476
                              *  in which case, ZSTD_compressStream2() delegates to ZSTD_compress2(), which is always a blocking call).
477
                              * More workers improve speed, but also increase memory usage.
478
                              * Default value is `0`, aka "single-threaded mode" : no worker is spawned,
479
                              * compression is performed inside Caller's thread, and all invocations are blocking */
480
    ZSTD_c_jobSize=401,      /* Size of a compression job. This value is enforced only when nbWorkers >= 1.
481
                              * Each compression job is completed in parallel, so this value can indirectly impact the nb of active threads.
482
                              * 0 means default, which is dynamically determined based on compression parameters.
483
                              * Job size must be a minimum of overlap size, or ZSTDMT_JOBSIZE_MIN (= 512 KB), whichever is largest.
484
                              * The minimum size is automatically and transparently enforced. */
485
    ZSTD_c_overlapLog=402,   /* Control the overlap size, as a fraction of window size.
486
                              * The overlap size is an amount of data reloaded from previous job at the beginning of a new job.
487
                              * It helps preserve compression ratio, while each job is compressed in parallel.
488
                              * This value is enforced only when nbWorkers >= 1.
489
                              * Larger values increase compression ratio, but decrease speed.
490
                              * Possible values range from 0 to 9 :
491
                              * - 0 means "default" : value will be determined by the library, depending on strategy
492
                              * - 1 means "no overlap"
493
                              * - 9 means "full overlap", using a full window size.
494
                              * Each intermediate rank increases/decreases load size by a factor 2 :
495
                              * 9: full window;  8: w/2;  7: w/4;  6: w/8;  5:w/16;  4: w/32;  3:w/64;  2:w/128;  1:no overlap;  0:default
496
                              * default value varies between 6 and 9, depending on strategy */
497
498
    /* note : additional experimental parameters are also available
499
     * within the experimental section of the API.
500
     * At the time of this writing, they include :
501
     * ZSTD_c_rsyncable
502
     * ZSTD_c_format
503
     * ZSTD_c_forceMaxWindow
504
     * ZSTD_c_forceAttachDict
505
     * ZSTD_c_literalCompressionMode
506
     * ZSTD_c_srcSizeHint
507
     * ZSTD_c_enableDedicatedDictSearch
508
     * ZSTD_c_stableInBuffer
509
     * ZSTD_c_stableOutBuffer
510
     * ZSTD_c_blockDelimiters
511
     * ZSTD_c_validateSequences
512
     * ZSTD_c_blockSplitterLevel
513
     * ZSTD_c_splitAfterSequences
514
     * ZSTD_c_useRowMatchFinder
515
     * ZSTD_c_prefetchCDictTables
516
     * ZSTD_c_enableSeqProducerFallback
517
     * ZSTD_c_maxBlockSize
518
     * Because they are not stable, it's necessary to define ZSTD_STATIC_LINKING_ONLY to access them.
519
     * note : never ever use experimentalParam? names directly;
520
     *        also, the enums values themselves are unstable and can still change.
521
     */
522
     ZSTD_c_experimentalParam1=500,
523
     ZSTD_c_experimentalParam2=10,
524
     ZSTD_c_experimentalParam3=1000,
525
     ZSTD_c_experimentalParam4=1001,
526
     ZSTD_c_experimentalParam5=1002,
527
     /* was ZSTD_c_experimentalParam6=1003; is now ZSTD_c_targetCBlockSize */
528
     ZSTD_c_experimentalParam7=1004,
529
     ZSTD_c_experimentalParam8=1005,
530
     ZSTD_c_experimentalParam9=1006,
531
     ZSTD_c_experimentalParam10=1007,
532
     ZSTD_c_experimentalParam11=1008,
533
     ZSTD_c_experimentalParam12=1009,
534
     ZSTD_c_experimentalParam13=1010,
535
     ZSTD_c_experimentalParam14=1011,
536
     ZSTD_c_experimentalParam15=1012,
537
     ZSTD_c_experimentalParam16=1013,
538
     ZSTD_c_experimentalParam17=1014,
539
     ZSTD_c_experimentalParam18=1015,
540
     ZSTD_c_experimentalParam19=1016,
541
     ZSTD_c_experimentalParam20=1017
542
} ZSTD_cParameter;
543
544
typedef struct {
545
    size_t error;
546
    int lowerBound;
547
    int upperBound;
548
} ZSTD_bounds;
549
550
/*! ZSTD_cParam_getBounds() :
551
 *  All parameters must belong to an interval with lower and upper bounds,
552
 *  otherwise they will either trigger an error or be automatically clamped.
553
 * @return : a structure, ZSTD_bounds, which contains
554
 *         - an error status field, which must be tested using ZSTD_isError()
555
 *         - lower and upper bounds, both inclusive
556
 */
557
ZSTDLIB_API ZSTD_bounds ZSTD_cParam_getBounds(ZSTD_cParameter cParam);
558
559
/*! ZSTD_CCtx_setParameter() :
560
 *  Set one compression parameter, selected by enum ZSTD_cParameter.
561
 *  All parameters have valid bounds. Bounds can be queried using ZSTD_cParam_getBounds().
562
 *  Providing a value beyond bound will either clamp it, or trigger an error (depending on parameter).
563
 *  Setting a parameter is generally only possible during frame initialization (before starting compression).
564
 *  Exception : when using multi-threading mode (nbWorkers >= 1),
565
 *              the following parameters can be updated _during_ compression (within same frame):
566
 *              => compressionLevel, hashLog, chainLog, searchLog, minMatch, targetLength and strategy.
567
 *              new parameters will be active for next job only (after a flush()).
568
 * @return : an error code (which can be tested using ZSTD_isError()).
569
 */
570
ZSTDLIB_API size_t ZSTD_CCtx_setParameter(ZSTD_CCtx* cctx, ZSTD_cParameter param, int value);
571
572
/*! ZSTD_CCtx_setPledgedSrcSize() :
573
 *  Total input data size to be compressed as a single frame.
574
 *  Value will be written in frame header, unless if explicitly forbidden using ZSTD_c_contentSizeFlag.
575
 *  This value will also be controlled at end of frame, and trigger an error if not respected.
576
 * @result : 0, or an error code (which can be tested with ZSTD_isError()).
577
 *  Note 1 : pledgedSrcSize==0 actually means zero, aka an empty frame.
578
 *           In order to mean "unknown content size", pass constant ZSTD_CONTENTSIZE_UNKNOWN.
579
 *           ZSTD_CONTENTSIZE_UNKNOWN is default value for any new frame.
580
 *  Note 2 : pledgedSrcSize is only valid once, for the next frame.
581
 *           It's discarded at the end of the frame, and replaced by ZSTD_CONTENTSIZE_UNKNOWN.
582
 *  Note 3 : Whenever all input data is provided and consumed in a single round,
583
 *           for example with ZSTD_compress2(),
584
 *           or invoking immediately ZSTD_compressStream2(,,,ZSTD_e_end),
585
 *           this value is automatically overridden by srcSize instead.
586
 */
587
ZSTDLIB_API size_t ZSTD_CCtx_setPledgedSrcSize(ZSTD_CCtx* cctx, unsigned long long pledgedSrcSize);
588
589
typedef enum {
590
    ZSTD_reset_session_only = 1,
591
    ZSTD_reset_parameters = 2,
592
    ZSTD_reset_session_and_parameters = 3
593
} ZSTD_ResetDirective;
594
595
/*! ZSTD_CCtx_reset() :
596
 *  There are 2 different things that can be reset, independently or jointly :
597
 *  - The session : will stop compressing current frame, and make CCtx ready to start a new one.
598
 *                  Useful after an error, or to interrupt any ongoing compression.
599
 *                  Any internal data not yet flushed is cancelled.
600
 *                  Compression parameters and dictionary remain unchanged.
601
 *                  They will be used to compress next frame.
602
 *                  Resetting session never fails.
603
 *  - The parameters : changes all parameters back to "default".
604
 *                  This also removes any reference to any dictionary or external sequence producer.
605
 *                  Parameters can only be changed between 2 sessions (i.e. no compression is currently ongoing)
606
 *                  otherwise the reset fails, and function returns an error value (which can be tested using ZSTD_isError())
607
 *  - Both : similar to resetting the session, followed by resetting parameters.
608
 */
609
ZSTDLIB_API size_t ZSTD_CCtx_reset(ZSTD_CCtx* cctx, ZSTD_ResetDirective reset);
610
611
/*! ZSTD_compress2() :
612
 *  Behave the same as ZSTD_compressCCtx(), but compression parameters are set using the advanced API.
613
 *  (note that this entry point doesn't even expose a compression level parameter).
614
 *  ZSTD_compress2() always starts a new frame.
615
 *  Should cctx hold data from a previously unfinished frame, everything about it is forgotten.
616
 *  - Compression parameters are pushed into CCtx before starting compression, using ZSTD_CCtx_set*()
617
 *  - The function is always blocking, returns when compression is completed.
618
 *  NOTE: Providing `dstCapacity >= ZSTD_compressBound(srcSize)` guarantees that zstd will have
619
 *        enough space to successfully compress the data, though it is possible it fails for other reasons.
620
 * @return : compressed size written into `dst` (<= `dstCapacity),
621
 *           or an error code if it fails (which can be tested using ZSTD_isError()).
622
 */
623
ZSTDLIB_API size_t ZSTD_compress2( ZSTD_CCtx* cctx,
624
                                   void* dst, size_t dstCapacity,
625
                             const void* src, size_t srcSize);
626
627
628
/***********************************************
629
*  Advanced decompression API (Requires v1.4.0+)
630
************************************************/
631
632
/* The advanced API pushes parameters one by one into an existing DCtx context.
633
 * Parameters are sticky, and remain valid for all following frames
634
 * using the same DCtx context.
635
 * It's possible to reset parameters to default values using ZSTD_DCtx_reset().
636
 * Note : This API is compatible with existing ZSTD_decompressDCtx() and ZSTD_decompressStream().
637
 *        Therefore, no new decompression function is necessary.
638
 */
639
640
typedef enum {
641
642
    ZSTD_d_windowLogMax=100, /* Select a size limit (in power of 2) beyond which
643
                              * the streaming API will refuse to allocate memory buffer
644
                              * in order to protect the host from unreasonable memory requirements.
645
                              * This parameter is only useful in streaming mode, since no internal buffer is allocated in single-pass mode.
646
                              * By default, a decompression context accepts window sizes <= (1 << ZSTD_WINDOWLOG_LIMIT_DEFAULT).
647
                              * Special: value 0 means "use default maximum windowLog". */
648
649
    /* note : additional experimental parameters are also available
650
     * within the experimental section of the API.
651
     * At the time of this writing, they include :
652
     * ZSTD_d_format
653
     * ZSTD_d_stableOutBuffer
654
     * ZSTD_d_forceIgnoreChecksum
655
     * ZSTD_d_refMultipleDDicts
656
     * ZSTD_d_disableHuffmanAssembly
657
     * ZSTD_d_maxBlockSize
658
     * Because they are not stable, it's necessary to define ZSTD_STATIC_LINKING_ONLY to access them.
659
     * note : never ever use experimentalParam? names directly
660
     */
661
     ZSTD_d_experimentalParam1=1000,
662
     ZSTD_d_experimentalParam2=1001,
663
     ZSTD_d_experimentalParam3=1002,
664
     ZSTD_d_experimentalParam4=1003,
665
     ZSTD_d_experimentalParam5=1004,
666
     ZSTD_d_experimentalParam6=1005
667
668
} ZSTD_dParameter;
669
670
/*! ZSTD_dParam_getBounds() :
671
 *  All parameters must belong to an interval with lower and upper bounds,
672
 *  otherwise they will either trigger an error or be automatically clamped.
673
 * @return : a structure, ZSTD_bounds, which contains
674
 *         - an error status field, which must be tested using ZSTD_isError()
675
 *         - both lower and upper bounds, inclusive
676
 */
677
ZSTDLIB_API ZSTD_bounds ZSTD_dParam_getBounds(ZSTD_dParameter dParam);
678
679
/*! ZSTD_DCtx_setParameter() :
680
 *  Set one compression parameter, selected by enum ZSTD_dParameter.
681
 *  All parameters have valid bounds. Bounds can be queried using ZSTD_dParam_getBounds().
682
 *  Providing a value beyond bound will either clamp it, or trigger an error (depending on parameter).
683
 *  Setting a parameter is only possible during frame initialization (before starting decompression).
684
 * @return : 0, or an error code (which can be tested using ZSTD_isError()).
685
 */
686
ZSTDLIB_API size_t ZSTD_DCtx_setParameter(ZSTD_DCtx* dctx, ZSTD_dParameter param, int value);
687
688
/*! ZSTD_DCtx_reset() :
689
 *  Return a DCtx to clean state.
690
 *  Session and parameters can be reset jointly or separately.
691
 *  Parameters can only be reset when no active frame is being decompressed.
692
 * @return : 0, or an error code, which can be tested with ZSTD_isError()
693
 */
694
ZSTDLIB_API size_t ZSTD_DCtx_reset(ZSTD_DCtx* dctx, ZSTD_ResetDirective reset);
695
696
697
/****************************
698
*  Streaming
699
****************************/
700
701
typedef struct ZSTD_inBuffer_s {
702
  const void* src;    /**< start of input buffer */
703
  size_t size;        /**< size of input buffer */
704
  size_t pos;         /**< position where reading stopped. Will be updated. Necessarily 0 <= pos <= size */
705
} ZSTD_inBuffer;
706
707
typedef struct ZSTD_outBuffer_s {
708
  void*  dst;         /**< start of output buffer */
709
  size_t size;        /**< size of output buffer */
710
  size_t pos;         /**< position where writing stopped. Will be updated. Necessarily 0 <= pos <= size */
711
} ZSTD_outBuffer;
712
713
714
715
/*-***********************************************************************
716
*  Streaming compression - HowTo
717
*
718
*  A ZSTD_CStream object is required to track streaming operation.
719
*  Use ZSTD_createCStream() and ZSTD_freeCStream() to create/release resources.
720
*  ZSTD_CStream objects can be reused multiple times on consecutive compression operations.
721
*  It is recommended to reuse ZSTD_CStream since it will play nicer with system's memory, by re-using already allocated memory.
722
*
723
*  For parallel execution, use one separate ZSTD_CStream per thread.
724
*
725
*  note : since v1.3.0, ZSTD_CStream and ZSTD_CCtx are the same thing.
726
*
727
*  Parameters are sticky : when starting a new compression on the same context,
728
*  it will reuse the same sticky parameters as previous compression session.
729
*  When in doubt, it's recommended to fully initialize the context before usage.
730
*  Use ZSTD_CCtx_reset() to reset the context and ZSTD_CCtx_setParameter(),
731
*  ZSTD_CCtx_setPledgedSrcSize(), or ZSTD_CCtx_loadDictionary() and friends to
732
*  set more specific parameters, the pledged source size, or load a dictionary.
733
*
734
*  Use ZSTD_compressStream2() with ZSTD_e_continue as many times as necessary to
735
*  consume input stream. The function will automatically update both `pos`
736
*  fields within `input` and `output`.
737
*  Note that the function may not consume the entire input, for example, because
738
*  the output buffer is already full, in which case `input.pos < input.size`.
739
*  The caller must check if input has been entirely consumed.
740
*  If not, the caller must make some room to receive more compressed data,
741
*  and then present again remaining input data.
742
*  note: ZSTD_e_continue is guaranteed to make some forward progress when called,
743
*        but doesn't guarantee maximal forward progress. This is especially relevant
744
*        when compressing with multiple threads. The call won't block if it can
745
*        consume some input, but if it can't it will wait for some, but not all,
746
*        output to be flushed.
747
* @return : provides a minimum amount of data remaining to be flushed from internal buffers
748
*           or an error code, which can be tested using ZSTD_isError().
749
*
750
*  At any moment, it's possible to flush whatever data might remain stuck within internal buffer,
751
*  using ZSTD_compressStream2() with ZSTD_e_flush. `output->pos` will be updated.
752
*  Note that, if `output->size` is too small, a single invocation with ZSTD_e_flush might not be enough (return code > 0).
753
*  In which case, make some room to receive more compressed data, and call again ZSTD_compressStream2() with ZSTD_e_flush.
754
*  You must continue calling ZSTD_compressStream2() with ZSTD_e_flush until it returns 0, at which point you can change the
755
*  operation.
756
*  note: ZSTD_e_flush will flush as much output as possible, meaning when compressing with multiple threads, it will
757
*        block until the flush is complete or the output buffer is full.
758
*  @return : 0 if internal buffers are entirely flushed,
759
*            >0 if some data still present within internal buffer (the value is minimal estimation of remaining size),
760
*            or an error code, which can be tested using ZSTD_isError().
761
*
762
*  Calling ZSTD_compressStream2() with ZSTD_e_end instructs to finish a frame.
763
*  It will perform a flush and write frame epilogue.
764
*  The epilogue is required for decoders to consider a frame completed.
765
*  flush operation is the same, and follows same rules as calling ZSTD_compressStream2() with ZSTD_e_flush.
766
*  You must continue calling ZSTD_compressStream2() with ZSTD_e_end until it returns 0, at which point you are free to
767
*  start a new frame.
768
*  note: ZSTD_e_end will flush as much output as possible, meaning when compressing with multiple threads, it will
769
*        block until the flush is complete or the output buffer is full.
770
*  @return : 0 if frame fully completed and fully flushed,
771
*            >0 if some data still present within internal buffer (the value is minimal estimation of remaining size),
772
*            or an error code, which can be tested using ZSTD_isError().
773
*
774
* *******************************************************************/
775
776
typedef ZSTD_CCtx ZSTD_CStream;  /**< CCtx and CStream are now effectively same object (>= v1.3.0) */
777
                                 /* Continue to distinguish them for compatibility with older versions <= v1.2.0 */
778
/*===== ZSTD_CStream management functions =====*/
779
ZSTDLIB_API ZSTD_CStream* ZSTD_createCStream(void);
780
ZSTDLIB_API size_t ZSTD_freeCStream(ZSTD_CStream* zcs);  /* accept NULL pointer */
781
782
/*===== Streaming compression functions =====*/
783
typedef enum {
784
    ZSTD_e_continue=0, /* collect more data, encoder decides when to output compressed result, for optimal compression ratio */
785
    ZSTD_e_flush=1,    /* flush any data provided so far,
786
                        * it creates (at least) one new block, that can be decoded immediately on reception;
787
                        * frame will continue: any future data can still reference previously compressed data, improving compression.
788
                        * note : multithreaded compression will block to flush as much output as possible. */
789
    ZSTD_e_end=2       /* flush any remaining data _and_ close current frame.
790
                        * note that frame is only closed after compressed data is fully flushed (return value == 0).
791
                        * After that point, any additional data starts a new frame.
792
                        * note : each frame is independent (does not reference any content from previous frame).
793
                        : note : multithreaded compression will block to flush as much output as possible. */
794
} ZSTD_EndDirective;
795
796
/*! ZSTD_compressStream2() : Requires v1.4.0+
797
 *  Behaves about the same as ZSTD_compressStream, with additional control on end directive.
798
 *  - Compression parameters are pushed into CCtx before starting compression, using ZSTD_CCtx_set*()
799
 *  - Compression parameters cannot be changed once compression is started (save a list of exceptions in multi-threading mode)
800
 *  - output->pos must be <= dstCapacity, input->pos must be <= srcSize
801
 *  - output->pos and input->pos will be updated. They are guaranteed to remain below their respective limit.
802
 *  - endOp must be a valid directive
803
 *  - When nbWorkers==0 (default), function is blocking : it completes its job before returning to caller.
804
 *  - When nbWorkers>=1, function is non-blocking : it copies a portion of input, distributes jobs to internal worker threads, flush to output whatever is available,
805
 *                                                  and then immediately returns, just indicating that there is some data remaining to be flushed.
806
 *                                                  The function nonetheless guarantees forward progress : it will return only after it reads or write at least 1+ byte.
807
 *  - Exception : if the first call requests a ZSTD_e_end directive and provides enough dstCapacity, the function delegates to ZSTD_compress2() which is always blocking.
808
 *  - @return provides a minimum amount of data remaining to be flushed from internal buffers
809
 *            or an error code, which can be tested using ZSTD_isError().
810
 *            if @return != 0, flush is not fully completed, there is still some data left within internal buffers.
811
 *            This is useful for ZSTD_e_flush, since in this case more flushes are necessary to empty all buffers.
812
 *            For ZSTD_e_end, @return == 0 when internal buffers are fully flushed and frame is completed.
813
 *  - after a ZSTD_e_end directive, if internal buffer is not fully flushed (@return != 0),
814
 *            only ZSTD_e_end or ZSTD_e_flush operations are allowed.
815
 *            Before starting a new compression job, or changing compression parameters,
816
 *            it is required to fully flush internal buffers.
817
 *  - note: if an operation ends with an error, it may leave @cctx in an undefined state.
818
 *          Therefore, it's UB to invoke ZSTD_compressStream2() of ZSTD_compressStream() on such a state.
819
 *          In order to be re-employed after an error, a state must be reset,
820
 *          which can be done explicitly (ZSTD_CCtx_reset()),
821
 *          or is sometimes implied by methods starting a new compression job (ZSTD_initCStream(), ZSTD_compressCCtx())
822
 */
823
ZSTDLIB_API size_t ZSTD_compressStream2( ZSTD_CCtx* cctx,
824
                                         ZSTD_outBuffer* output,
825
                                         ZSTD_inBuffer* input,
826
                                         ZSTD_EndDirective endOp);
827
828
829
/* These buffer sizes are softly recommended.
830
 * They are not required : ZSTD_compressStream*() happily accepts any buffer size, for both input and output.
831
 * Respecting the recommended size just makes it a bit easier for ZSTD_compressStream*(),
832
 * reducing the amount of memory shuffling and buffering, resulting in minor performance savings.
833
 *
834
 * However, note that these recommendations are from the perspective of a C caller program.
835
 * If the streaming interface is invoked from some other language,
836
 * especially managed ones such as Java or Go, through a foreign function interface such as jni or cgo,
837
 * a major performance rule is to reduce crossing such interface to an absolute minimum.
838
 * It's not rare that performance ends being spent more into the interface, rather than compression itself.
839
 * In which cases, prefer using large buffers, as large as practical,
840
 * for both input and output, to reduce the nb of roundtrips.
841
 */
842
ZSTDLIB_API size_t ZSTD_CStreamInSize(void);    /**< recommended size for input buffer */
843
ZSTDLIB_API size_t ZSTD_CStreamOutSize(void);   /**< recommended size for output buffer. Guarantee to successfully flush at least one complete compressed block. */
844
845
846
/* *****************************************************************************
847
 * This following is a legacy streaming API, available since v1.0+ .
848
 * It can be replaced by ZSTD_CCtx_reset() and ZSTD_compressStream2().
849
 * It is redundant, but remains fully supported.
850
 ******************************************************************************/
851
852
/*!
853
 * Equivalent to:
854
 *
855
 *     ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only);
856
 *     ZSTD_CCtx_refCDict(zcs, NULL); // clear the dictionary (if any)
857
 *     ZSTD_CCtx_setParameter(zcs, ZSTD_c_compressionLevel, compressionLevel);
858
 *
859
 * Note that ZSTD_initCStream() clears any previously set dictionary. Use the new API
860
 * to compress with a dictionary.
861
 */
862
ZSTDLIB_API size_t ZSTD_initCStream(ZSTD_CStream* zcs, int compressionLevel);
863
/*!
864
 * Alternative for ZSTD_compressStream2(zcs, output, input, ZSTD_e_continue).
865
 * NOTE: The return value is different. ZSTD_compressStream() returns a hint for
866
 * the next read size (if non-zero and not an error). ZSTD_compressStream2()
867
 * returns the minimum nb of bytes left to flush (if non-zero and not an error).
868
 */
869
ZSTDLIB_API size_t ZSTD_compressStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output, ZSTD_inBuffer* input);
870
/*! Equivalent to ZSTD_compressStream2(zcs, output, &emptyInput, ZSTD_e_flush). */
871
ZSTDLIB_API size_t ZSTD_flushStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output);
872
/*! Equivalent to ZSTD_compressStream2(zcs, output, &emptyInput, ZSTD_e_end). */
873
ZSTDLIB_API size_t ZSTD_endStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output);
874
875
876
/*-***************************************************************************
877
*  Streaming decompression - HowTo
878
*
879
*  A ZSTD_DStream object is required to track streaming operations.
880
*  Use ZSTD_createDStream() and ZSTD_freeDStream() to create/release resources.
881
*  ZSTD_DStream objects can be re-employed multiple times.
882
*
883
*  Use ZSTD_initDStream() to start a new decompression operation.
884
* @return : recommended first input size
885
*  Alternatively, use advanced API to set specific properties.
886
*
887
*  Use ZSTD_decompressStream() repetitively to consume your input.
888
*  The function will update both `pos` fields.
889
*  If `input.pos < input.size`, some input has not been consumed.
890
*  It's up to the caller to present again remaining data.
891
*
892
*  The function tries to flush all data decoded immediately, respecting output buffer size.
893
*  If `output.pos < output.size`, decoder has flushed everything it could.
894
*
895
*  However, when `output.pos == output.size`, it's more difficult to know.
896
*  If @return > 0, the frame is not complete, meaning
897
*  either there is still some data left to flush within internal buffers,
898
*  or there is more input to read to complete the frame (or both).
899
*  In which case, call ZSTD_decompressStream() again to flush whatever remains in the buffer.
900
*  Note : with no additional input provided, amount of data flushed is necessarily <= ZSTD_BLOCKSIZE_MAX.
901
* @return : 0 when a frame is completely decoded and fully flushed,
902
*        or an error code, which can be tested using ZSTD_isError(),
903
*        or any other value > 0, which means there is still some decoding or flushing to do to complete current frame :
904
*                                the return value is a suggested next input size (just a hint for better latency)
905
*                                that will never request more than the remaining content of the compressed frame.
906
* *******************************************************************************/
907
908
typedef ZSTD_DCtx ZSTD_DStream;  /**< DCtx and DStream are now effectively same object (>= v1.3.0) */
909
                                 /* For compatibility with versions <= v1.2.0, prefer differentiating them. */
910
/*===== ZSTD_DStream management functions =====*/
911
ZSTDLIB_API ZSTD_DStream* ZSTD_createDStream(void);
912
ZSTDLIB_API size_t ZSTD_freeDStream(ZSTD_DStream* zds);  /* accept NULL pointer */
913
914
/*===== Streaming decompression functions =====*/
915
916
/*! ZSTD_initDStream() :
917
 * Initialize/reset DStream state for new decompression operation.
918
 * Call before new decompression operation using same DStream.
919
 *
920
 * Note : This function is redundant with the advanced API and equivalent to:
921
 *     ZSTD_DCtx_reset(zds, ZSTD_reset_session_only);
922
 *     ZSTD_DCtx_refDDict(zds, NULL);
923
 */
924
ZSTDLIB_API size_t ZSTD_initDStream(ZSTD_DStream* zds);
925
926
/*! ZSTD_decompressStream() :
927
 * Streaming decompression function.
928
 * Call repetitively to consume full input updating it as necessary.
929
 * Function will update both input and output `pos` fields exposing current state via these fields:
930
 * - `input.pos < input.size`, some input remaining and caller should provide remaining input
931
 *   on the next call.
932
 * - `output.pos < output.size`, decoder flushed internal output buffer.
933
 * - `output.pos == output.size`, unflushed data potentially present in the internal buffers,
934
 *   check ZSTD_decompressStream() @return value,
935
 *   if > 0, invoke it again to flush remaining data to output.
936
 * Note : with no additional input, amount of data flushed <= ZSTD_BLOCKSIZE_MAX.
937
 *
938
 * @return : 0 when a frame is completely decoded and fully flushed,
939
 *           or an error code, which can be tested using ZSTD_isError(),
940
 *           or any other value > 0, which means there is some decoding or flushing to do to complete current frame.
941
 *
942
 * Note: when an operation returns with an error code, the @zds state may be left in undefined state.
943
 *       It's UB to invoke `ZSTD_decompressStream()` on such a state.
944
 *       In order to re-use such a state, it must be first reset,
945
 *       which can be done explicitly (`ZSTD_DCtx_reset()`),
946
 *       or is implied for operations starting some new decompression job (`ZSTD_initDStream`, `ZSTD_decompressDCtx()`, `ZSTD_decompress_usingDict()`)
947
 */
948
ZSTDLIB_API size_t ZSTD_decompressStream(ZSTD_DStream* zds, ZSTD_outBuffer* output, ZSTD_inBuffer* input);
949
950
ZSTDLIB_API size_t ZSTD_DStreamInSize(void);    /*!< recommended size for input buffer */
951
ZSTDLIB_API size_t ZSTD_DStreamOutSize(void);   /*!< recommended size for output buffer. Guarantee to successfully flush at least one complete block in all circumstances. */
952
953
954
/**************************
955
*  Simple dictionary API
956
***************************/
957
/*! ZSTD_compress_usingDict() :
958
 *  Compression at an explicit compression level using a Dictionary.
959
 *  A dictionary can be any arbitrary data segment (also called a prefix),
960
 *  or a buffer with specified information (see zdict.h).
961
 *  Note : This function loads the dictionary, resulting in significant startup delay.
962
 *         It's intended for a dictionary used only once.
963
 *  Note 2 : When `dict == NULL || dictSize < 8` no dictionary is used. */
964
ZSTDLIB_API size_t ZSTD_compress_usingDict(ZSTD_CCtx* ctx,
965
                                           void* dst, size_t dstCapacity,
966
                                     const void* src, size_t srcSize,
967
                                     const void* dict,size_t dictSize,
968
                                           int compressionLevel);
969
970
/*! ZSTD_decompress_usingDict() :
971
 *  Decompression using a known Dictionary.
972
 *  Dictionary must be identical to the one used during compression.
973
 *  Note : This function loads the dictionary, resulting in significant startup delay.
974
 *         It's intended for a dictionary used only once.
975
 *  Note : When `dict == NULL || dictSize < 8` no dictionary is used. */
976
ZSTDLIB_API size_t ZSTD_decompress_usingDict(ZSTD_DCtx* dctx,
977
                                             void* dst, size_t dstCapacity,
978
                                       const void* src, size_t srcSize,
979
                                       const void* dict,size_t dictSize);
980
981
982
/***********************************
983
 *  Bulk processing dictionary API
984
 **********************************/
985
typedef struct ZSTD_CDict_s ZSTD_CDict;
986
987
/*! ZSTD_createCDict() :
988
 *  When compressing multiple messages or blocks using the same dictionary,
989
 *  it's recommended to digest the dictionary only once, since it's a costly operation.
990
 *  ZSTD_createCDict() will create a state from digesting a dictionary.
991
 *  The resulting state can be used for future compression operations with very limited startup cost.
992
 *  ZSTD_CDict can be created once and shared by multiple threads concurrently, since its usage is read-only.
993
 * @dictBuffer can be released after ZSTD_CDict creation, because its content is copied within CDict.
994
 *  Note 1 : Consider experimental function `ZSTD_createCDict_byReference()` if you prefer to not duplicate @dictBuffer content.
995
 *  Note 2 : A ZSTD_CDict can be created from an empty @dictBuffer,
996
 *      in which case the only thing that it transports is the @compressionLevel.
997
 *      This can be useful in a pipeline featuring ZSTD_compress_usingCDict() exclusively,
998
 *      expecting a ZSTD_CDict parameter with any data, including those without a known dictionary. */
999
ZSTDLIB_API ZSTD_CDict* ZSTD_createCDict(const void* dictBuffer, size_t dictSize,
1000
                                         int compressionLevel);
1001
1002
/*! ZSTD_freeCDict() :
1003
 *  Function frees memory allocated by ZSTD_createCDict().
1004
 *  If a NULL pointer is passed, no operation is performed. */
1005
ZSTDLIB_API size_t      ZSTD_freeCDict(ZSTD_CDict* CDict);
1006
1007
/*! ZSTD_compress_usingCDict() :
1008
 *  Compression using a digested Dictionary.
1009
 *  Recommended when same dictionary is used multiple times.
1010
 *  Note : compression level is _decided at dictionary creation time_,
1011
 *     and frame parameters are hardcoded (dictID=yes, contentSize=yes, checksum=no) */
1012
ZSTDLIB_API size_t ZSTD_compress_usingCDict(ZSTD_CCtx* cctx,
1013
                                            void* dst, size_t dstCapacity,
1014
                                      const void* src, size_t srcSize,
1015
                                      const ZSTD_CDict* cdict);
1016
1017
1018
typedef struct ZSTD_DDict_s ZSTD_DDict;
1019
1020
/*! ZSTD_createDDict() :
1021
 *  Create a digested dictionary, ready to start decompression operation without startup delay.
1022
 *  dictBuffer can be released after DDict creation, as its content is copied inside DDict. */
1023
ZSTDLIB_API ZSTD_DDict* ZSTD_createDDict(const void* dictBuffer, size_t dictSize);
1024
1025
/*! ZSTD_freeDDict() :
1026
 *  Function frees memory allocated with ZSTD_createDDict()
1027
 *  If a NULL pointer is passed, no operation is performed. */
1028
ZSTDLIB_API size_t      ZSTD_freeDDict(ZSTD_DDict* ddict);
1029
1030
/*! ZSTD_decompress_usingDDict() :
1031
 *  Decompression using a digested Dictionary.
1032
 *  Recommended when same dictionary is used multiple times. */
1033
ZSTDLIB_API size_t ZSTD_decompress_usingDDict(ZSTD_DCtx* dctx,
1034
                                              void* dst, size_t dstCapacity,
1035
                                        const void* src, size_t srcSize,
1036
                                        const ZSTD_DDict* ddict);
1037
1038
1039
/********************************
1040
 *  Dictionary helper functions
1041
 *******************************/
1042
1043
/*! ZSTD_getDictID_fromDict() : Requires v1.4.0+
1044
 *  Provides the dictID stored within dictionary.
1045
 *  if @return == 0, the dictionary is not conformant with Zstandard specification.
1046
 *  It can still be loaded, but as a content-only dictionary. */
1047
ZSTDLIB_API unsigned ZSTD_getDictID_fromDict(const void* dict, size_t dictSize);
1048
1049
/*! ZSTD_getDictID_fromCDict() : Requires v1.5.0+
1050
 *  Provides the dictID of the dictionary loaded into `cdict`.
1051
 *  If @return == 0, the dictionary is not conformant to Zstandard specification, or empty.
1052
 *  Non-conformant dictionaries can still be loaded, but as content-only dictionaries. */
1053
ZSTDLIB_API unsigned ZSTD_getDictID_fromCDict(const ZSTD_CDict* cdict);
1054
1055
/*! ZSTD_getDictID_fromDDict() : Requires v1.4.0+
1056
 *  Provides the dictID of the dictionary loaded into `ddict`.
1057
 *  If @return == 0, the dictionary is not conformant to Zstandard specification, or empty.
1058
 *  Non-conformant dictionaries can still be loaded, but as content-only dictionaries. */
1059
ZSTDLIB_API unsigned ZSTD_getDictID_fromDDict(const ZSTD_DDict* ddict);
1060
1061
/*! ZSTD_getDictID_fromFrame() : Requires v1.4.0+
1062
 *  Provides the dictID required to decompressed the frame stored within `src`.
1063
 *  If @return == 0, the dictID could not be decoded.
1064
 *  This could for one of the following reasons :
1065
 *  - The frame does not require a dictionary to be decoded (most common case).
1066
 *  - The frame was built with dictID intentionally removed. Whatever dictionary is necessary is a hidden piece of information.
1067
 *    Note : this use case also happens when using a non-conformant dictionary.
1068
 *  - `srcSize` is too small, and as a result, the frame header could not be decoded (only possible if `srcSize < ZSTD_FRAMEHEADERSIZE_MAX`).
1069
 *  - This is not a Zstandard frame.
1070
 *  When identifying the exact failure cause, it's possible to use ZSTD_getFrameHeader(), which will provide a more precise error code. */
1071
ZSTDLIB_API unsigned ZSTD_getDictID_fromFrame(const void* src, size_t srcSize);
1072
1073
1074
/*******************************************************************************
1075
 * Advanced dictionary and prefix API (Requires v1.4.0+)
1076
 *
1077
 * This API allows dictionaries to be used with ZSTD_compress2(),
1078
 * ZSTD_compressStream2(), and ZSTD_decompressDCtx().
1079
 * Dictionaries are sticky, they remain valid when same context is reused,
1080
 * they only reset when the context is reset
1081
 * with ZSTD_reset_parameters or ZSTD_reset_session_and_parameters.
1082
 * In contrast, Prefixes are single-use.
1083
 ******************************************************************************/
1084
1085
1086
/*! ZSTD_CCtx_loadDictionary() : Requires v1.4.0+
1087
 *  Create an internal CDict from `dict` buffer.
1088
 *  Decompression will have to use same dictionary.
1089
 * @result : 0, or an error code (which can be tested with ZSTD_isError()).
1090
 *  Special: Loading a NULL (or 0-size) dictionary invalidates previous dictionary,
1091
 *           meaning "return to no-dictionary mode".
1092
 *  Note 1 : Dictionary is sticky, it will be used for all future compressed frames,
1093
 *           until parameters are reset, a new dictionary is loaded, or the dictionary
1094
 *           is explicitly invalidated by loading a NULL dictionary.
1095
 *  Note 2 : Loading a dictionary involves building tables.
1096
 *           It's also a CPU consuming operation, with non-negligible impact on latency.
1097
 *           Tables are dependent on compression parameters, and for this reason,
1098
 *           compression parameters can no longer be changed after loading a dictionary.
1099
 *  Note 3 :`dict` content will be copied internally.
1100
 *           Use experimental ZSTD_CCtx_loadDictionary_byReference() to reference content instead.
1101
 *           In such a case, dictionary buffer must outlive its users.
1102
 *  Note 4 : Use ZSTD_CCtx_loadDictionary_advanced()
1103
 *           to precisely select how dictionary content must be interpreted.
1104
 *  Note 5 : This method does not benefit from LDM (long distance mode).
1105
 *           If you want to employ LDM on some large dictionary content,
1106
 *           prefer employing ZSTD_CCtx_refPrefix() described below.
1107
 */
1108
ZSTDLIB_API size_t ZSTD_CCtx_loadDictionary(ZSTD_CCtx* cctx, const void* dict, size_t dictSize);
1109
1110
/*! ZSTD_CCtx_refCDict() : Requires v1.4.0+
1111
 *  Reference a prepared dictionary, to be used for all future compressed frames.
1112
 *  Note that compression parameters are enforced from within CDict,
1113
 *  and supersede any compression parameter previously set within CCtx.
1114
 *  The parameters ignored are labelled as "superseded-by-cdict" in the ZSTD_cParameter enum docs.
1115
 *  The ignored parameters will be used again if the CCtx is returned to no-dictionary mode.
1116
 *  The dictionary will remain valid for future compressed frames using same CCtx.
1117
 * @result : 0, or an error code (which can be tested with ZSTD_isError()).
1118
 *  Special : Referencing a NULL CDict means "return to no-dictionary mode".
1119
 *  Note 1 : Currently, only one dictionary can be managed.
1120
 *           Referencing a new dictionary effectively "discards" any previous one.
1121
 *  Note 2 : CDict is just referenced, its lifetime must outlive its usage within CCtx. */
1122
ZSTDLIB_API size_t ZSTD_CCtx_refCDict(ZSTD_CCtx* cctx, const ZSTD_CDict* cdict);
1123
1124
/*! ZSTD_CCtx_refPrefix() : Requires v1.4.0+
1125
 *  Reference a prefix (single-usage dictionary) for next compressed frame.
1126
 *  A prefix is **only used once**. Tables are discarded at end of frame (ZSTD_e_end).
1127
 *  Decompression will need same prefix to properly regenerate data.
1128
 *  Compressing with a prefix is similar in outcome as performing a diff and compressing it,
1129
 *  but performs much faster, especially during decompression (compression speed is tunable with compression level).
1130
 *  This method is compatible with LDM (long distance mode).
1131
 * @result : 0, or an error code (which can be tested with ZSTD_isError()).
1132
 *  Special: Adding any prefix (including NULL) invalidates any previous prefix or dictionary
1133
 *  Note 1 : Prefix buffer is referenced. It **must** outlive compression.
1134
 *           Its content must remain unmodified during compression.
1135
 *  Note 2 : If the intention is to diff some large src data blob with some prior version of itself,
1136
 *           ensure that the window size is large enough to contain the entire source.
1137
 *           See ZSTD_c_windowLog.
1138
 *  Note 3 : Referencing a prefix involves building tables, which are dependent on compression parameters.
1139
 *           It's a CPU consuming operation, with non-negligible impact on latency.
1140
 *           If there is a need to use the same prefix multiple times, consider loadDictionary instead.
1141
 *  Note 4 : By default, the prefix is interpreted as raw content (ZSTD_dct_rawContent).
1142
 *           Use experimental ZSTD_CCtx_refPrefix_advanced() to alter dictionary interpretation. */
1143
ZSTDLIB_API size_t ZSTD_CCtx_refPrefix(ZSTD_CCtx* cctx,
1144
                                 const void* prefix, size_t prefixSize);
1145
1146
/*! ZSTD_DCtx_loadDictionary() : Requires v1.4.0+
1147
 *  Create an internal DDict from dict buffer, to be used to decompress all future frames.
1148
 *  The dictionary remains valid for all future frames, until explicitly invalidated, or
1149
 *  a new dictionary is loaded.
1150
 * @result : 0, or an error code (which can be tested with ZSTD_isError()).
1151
 *  Special : Adding a NULL (or 0-size) dictionary invalidates any previous dictionary,
1152
 *            meaning "return to no-dictionary mode".
1153
 *  Note 1 : Loading a dictionary involves building tables,
1154
 *           which has a non-negligible impact on CPU usage and latency.
1155
 *           It's recommended to "load once, use many times", to amortize the cost
1156
 *  Note 2 :`dict` content will be copied internally, so `dict` can be released after loading.
1157
 *           Use ZSTD_DCtx_loadDictionary_byReference() to reference dictionary content instead.
1158
 *  Note 3 : Use ZSTD_DCtx_loadDictionary_advanced() to take control of
1159
 *           how dictionary content is loaded and interpreted.
1160
 */
1161
ZSTDLIB_API size_t ZSTD_DCtx_loadDictionary(ZSTD_DCtx* dctx, const void* dict, size_t dictSize);
1162
1163
/*! ZSTD_DCtx_refDDict() : Requires v1.4.0+
1164
 *  Reference a prepared dictionary, to be used to decompress next frames.
1165
 *  The dictionary remains active for decompression of future frames using same DCtx.
1166
 *
1167
 *  If called with ZSTD_d_refMultipleDDicts enabled, repeated calls of this function
1168
 *  will store the DDict references in a table, and the DDict used for decompression
1169
 *  will be determined at decompression time, as per the dict ID in the frame.
1170
 *  The memory for the table is allocated on the first call to refDDict, and can be
1171
 *  freed with ZSTD_freeDCtx().
1172
 *
1173
 *  If called with ZSTD_d_refMultipleDDicts disabled (the default), only one dictionary
1174
 *  will be managed, and referencing a dictionary effectively "discards" any previous one.
1175
 *
1176
 * @result : 0, or an error code (which can be tested with ZSTD_isError()).
1177
 *  Special: referencing a NULL DDict means "return to no-dictionary mode".
1178
 *  Note 2 : DDict is just referenced, its lifetime must outlive its usage from DCtx.
1179
 */
1180
ZSTDLIB_API size_t ZSTD_DCtx_refDDict(ZSTD_DCtx* dctx, const ZSTD_DDict* ddict);
1181
1182
/*! ZSTD_DCtx_refPrefix() : Requires v1.4.0+
1183
 *  Reference a prefix (single-usage dictionary) to decompress next frame.
1184
 *  This is the reverse operation of ZSTD_CCtx_refPrefix(),
1185
 *  and must use the same prefix as the one used during compression.
1186
 *  Prefix is **only used once**. Reference is discarded at end of frame.
1187
 *  End of frame is reached when ZSTD_decompressStream() returns 0.
1188
 * @result : 0, or an error code (which can be tested with ZSTD_isError()).
1189
 *  Note 1 : Adding any prefix (including NULL) invalidates any previously set prefix or dictionary
1190
 *  Note 2 : Prefix buffer is referenced. It **must** outlive decompression.
1191
 *           Prefix buffer must remain unmodified up to the end of frame,
1192
 *           reached when ZSTD_decompressStream() returns 0.
1193
 *  Note 3 : By default, the prefix is treated as raw content (ZSTD_dct_rawContent).
1194
 *           Use ZSTD_CCtx_refPrefix_advanced() to alter dictMode (Experimental section)
1195
 *  Note 4 : Referencing a raw content prefix has almost no cpu nor memory cost.
1196
 *           A full dictionary is more costly, as it requires building tables.
1197
 */
1198
ZSTDLIB_API size_t ZSTD_DCtx_refPrefix(ZSTD_DCtx* dctx,
1199
                                 const void* prefix, size_t prefixSize);
1200
1201
/* ===   Memory management   === */
1202
1203
/*! ZSTD_sizeof_*() : Requires v1.4.0+
1204
 *  These functions give the _current_ memory usage of selected object.
1205
 *  Note that object memory usage can evolve (increase or decrease) over time. */
1206
ZSTDLIB_API size_t ZSTD_sizeof_CCtx(const ZSTD_CCtx* cctx);
1207
ZSTDLIB_API size_t ZSTD_sizeof_DCtx(const ZSTD_DCtx* dctx);
1208
ZSTDLIB_API size_t ZSTD_sizeof_CStream(const ZSTD_CStream* zcs);
1209
ZSTDLIB_API size_t ZSTD_sizeof_DStream(const ZSTD_DStream* zds);
1210
ZSTDLIB_API size_t ZSTD_sizeof_CDict(const ZSTD_CDict* cdict);
1211
ZSTDLIB_API size_t ZSTD_sizeof_DDict(const ZSTD_DDict* ddict);
1212
1213
#if defined (__cplusplus)
1214
}
1215
#endif
1216
1217
#endif  /* ZSTD_H_235446 */
1218
1219
1220
/* **************************************************************************************
1221
 *   ADVANCED AND EXPERIMENTAL FUNCTIONS
1222
 ****************************************************************************************
1223
 * The definitions in the following section are considered experimental.
1224
 * They are provided for advanced scenarios.
1225
 * They should never be used with a dynamic library, as prototypes may change in the future.
1226
 * Use them only in association with static linking.
1227
 * ***************************************************************************************/
1228
1229
#if defined(ZSTD_STATIC_LINKING_ONLY) && !defined(ZSTD_H_ZSTD_STATIC_LINKING_ONLY)
1230
#define ZSTD_H_ZSTD_STATIC_LINKING_ONLY
1231
1232
#if defined (__cplusplus)
1233
extern "C" {
1234
#endif
1235
1236
/* This can be overridden externally to hide static symbols. */
1237
#ifndef ZSTDLIB_STATIC_API
1238
#  if defined(ZSTD_DLL_EXPORT) && (ZSTD_DLL_EXPORT==1)
1239
#    define ZSTDLIB_STATIC_API __declspec(dllexport) ZSTDLIB_VISIBLE
1240
#  elif defined(ZSTD_DLL_IMPORT) && (ZSTD_DLL_IMPORT==1)
1241
#    define ZSTDLIB_STATIC_API __declspec(dllimport) ZSTDLIB_VISIBLE
1242
#  else
1243
#    define ZSTDLIB_STATIC_API ZSTDLIB_VISIBLE
1244
#  endif
1245
#endif
1246
1247
/****************************************************************************************
1248
 *   experimental API (static linking only)
1249
 ****************************************************************************************
1250
 * The following symbols and constants
1251
 * are not planned to join "stable API" status in the near future.
1252
 * They can still change in future versions.
1253
 * Some of them are planned to remain in the static_only section indefinitely.
1254
 * Some of them might be removed in the future (especially when redundant with existing stable functions)
1255
 * ***************************************************************************************/
1256
1257
313k
#define ZSTD_FRAMEHEADERSIZE_PREFIX(format) ((format) == ZSTD_f_zstd1 ? 5 : 1)   /* minimum input size required to query frame header size */
1258
0
#define ZSTD_FRAMEHEADERSIZE_MIN(format)    ((format) == ZSTD_f_zstd1 ? 6 : 2)
1259
#define ZSTD_FRAMEHEADERSIZE_MAX   18   /* can be useful for static allocation */
1260
0
#define ZSTD_SKIPPABLEHEADERSIZE    8
1261
1262
/* compression parameter bounds */
1263
0
#define ZSTD_WINDOWLOG_MAX_32    30
1264
1.95M
#define ZSTD_WINDOWLOG_MAX_64    31
1265
1.95M
#define ZSTD_WINDOWLOG_MAX     ((int)(sizeof(size_t) == 4 ? ZSTD_WINDOWLOG_MAX_32 : ZSTD_WINDOWLOG_MAX_64))
1266
543k
#define ZSTD_WINDOWLOG_MIN       10
1267
543k
#define ZSTD_HASHLOG_MAX       ((ZSTD_WINDOWLOG_MAX < 30) ? ZSTD_WINDOWLOG_MAX : 30)
1268
1.41M
#define ZSTD_HASHLOG_MIN          6
1269
0
#define ZSTD_CHAINLOG_MAX_32     29
1270
515k
#define ZSTD_CHAINLOG_MAX_64     30
1271
515k
#define ZSTD_CHAINLOG_MAX      ((int)(sizeof(size_t) == 4 ? ZSTD_CHAINLOG_MAX_32 : ZSTD_CHAINLOG_MAX_64))
1272
543k
#define ZSTD_CHAINLOG_MIN        ZSTD_HASHLOG_MIN
1273
515k
#define ZSTD_SEARCHLOG_MAX      (ZSTD_WINDOWLOG_MAX-1)
1274
543k
#define ZSTD_SEARCHLOG_MIN        1
1275
543k
#define ZSTD_MINMATCH_MAX         7   /* only for ZSTD_fast, other strategies are limited to 6 */
1276
1.77M
#define ZSTD_MINMATCH_MIN         3   /* only for ZSTD_btopt+, faster strategies are limited to 4 */
1277
515k
#define ZSTD_TARGETLENGTH_MAX    ZSTD_BLOCKSIZE_MAX
1278
515k
#define ZSTD_TARGETLENGTH_MIN     0   /* note : comparing this constant to an unsigned results in a tautological test */
1279
1.51M
#define ZSTD_STRATEGY_MIN        ZSTD_fast
1280
1.51M
#define ZSTD_STRATEGY_MAX        ZSTD_btultra2
1281
187k
#define ZSTD_BLOCKSIZE_MAX_MIN (1 << 10) /* The minimum valid max blocksize. Maximum blocksizes smaller than this make compressBound() inaccurate. */
1282
1283
1284
27.4k
#define ZSTD_OVERLAPLOG_MIN       0
1285
27.4k
#define ZSTD_OVERLAPLOG_MAX       9
1286
1287
70.4k
#define ZSTD_WINDOWLOG_LIMIT_DEFAULT 27   /* by default, the streaming decoder will refuse any frame
1288
                                           * requiring larger than (1<<ZSTD_WINDOWLOG_LIMIT_DEFAULT) window size,
1289
                                           * to preserve host's memory from unreasonable requirements.
1290
                                           * This limit can be overridden using ZSTD_DCtx_setParameter(,ZSTD_d_windowLogMax,).
1291
                                           * The limit does not apply for one-pass decoders (such as ZSTD_decompress()), since no additional memory is allocated */
1292
1293
1294
/* LDM parameter bounds */
1295
27.4k
#define ZSTD_LDM_HASHLOG_MIN      ZSTD_HASHLOG_MIN
1296
27.4k
#define ZSTD_LDM_HASHLOG_MAX      ZSTD_HASHLOG_MAX
1297
54.8k
#define ZSTD_LDM_MINMATCH_MIN        4
1298
54.8k
#define ZSTD_LDM_MINMATCH_MAX     4096
1299
12.5k
#define ZSTD_LDM_BUCKETSIZELOG_MIN   1
1300
40.0k
#define ZSTD_LDM_BUCKETSIZELOG_MAX   8
1301
37.3k
#define ZSTD_LDM_HASHRATELOG_MIN     0
1302
37.3k
#define ZSTD_LDM_HASHRATELOG_MAX (ZSTD_WINDOWLOG_MAX - ZSTD_HASHLOG_MIN)
1303
1304
/* Advanced parameter bounds */
1305
49.0k
#define ZSTD_TARGETCBLOCKSIZE_MIN   1340 /* suitable to fit into an ethernet / wifi / 4G transport frame */
1306
49.0k
#define ZSTD_TARGETCBLOCKSIZE_MAX   ZSTD_BLOCKSIZE_MAX
1307
27.0k
#define ZSTD_SRCSIZEHINT_MIN        0
1308
2.55k
#define ZSTD_SRCSIZEHINT_MAX        INT_MAX
1309
1310
1311
/* ---  Advanced types  --- */
1312
1313
typedef struct ZSTD_CCtx_params_s ZSTD_CCtx_params;
1314
1315
typedef struct {
1316
    unsigned int offset;      /* The offset of the match. (NOT the same as the offset code)
1317
                               * If offset == 0 and matchLength == 0, this sequence represents the last
1318
                               * literals in the block of litLength size.
1319
                               */
1320
1321
    unsigned int litLength;   /* Literal length of the sequence. */
1322
    unsigned int matchLength; /* Match length of the sequence. */
1323
1324
                              /* Note: Users of this API may provide a sequence with matchLength == litLength == offset == 0.
1325
                               * In this case, we will treat the sequence as a marker for a block boundary.
1326
                               */
1327
1328
    unsigned int rep;         /* Represents which repeat offset is represented by the field 'offset'.
1329
                               * Ranges from [0, 3].
1330
                               *
1331
                               * Repeat offsets are essentially previous offsets from previous sequences sorted in
1332
                               * recency order. For more detail, see doc/zstd_compression_format.md
1333
                               *
1334
                               * If rep == 0, then 'offset' does not contain a repeat offset.
1335
                               * If rep > 0:
1336
                               *  If litLength != 0:
1337
                               *      rep == 1 --> offset == repeat_offset_1
1338
                               *      rep == 2 --> offset == repeat_offset_2
1339
                               *      rep == 3 --> offset == repeat_offset_3
1340
                               *  If litLength == 0:
1341
                               *      rep == 1 --> offset == repeat_offset_2
1342
                               *      rep == 2 --> offset == repeat_offset_3
1343
                               *      rep == 3 --> offset == repeat_offset_1 - 1
1344
                               *
1345
                               * Note: This field is optional. ZSTD_generateSequences() will calculate the value of
1346
                               * 'rep', but repeat offsets do not necessarily need to be calculated from an external
1347
                               * sequence provider perspective. For example, ZSTD_compressSequences() does not
1348
                               * use this 'rep' field at all (as of now).
1349
                               */
1350
} ZSTD_Sequence;
1351
1352
typedef struct {
1353
    unsigned windowLog;       /**< largest match distance : larger == more compression, more memory needed during decompression */
1354
    unsigned chainLog;        /**< fully searched segment : larger == more compression, slower, more memory (useless for fast) */
1355
    unsigned hashLog;         /**< dispatch table : larger == faster, more memory */
1356
    unsigned searchLog;       /**< nb of searches : larger == more compression, slower */
1357
    unsigned minMatch;        /**< match length searched : larger == faster decompression, sometimes less compression */
1358
    unsigned targetLength;    /**< acceptable match size for optimal parser (only) : larger == more compression, slower */
1359
    ZSTD_strategy strategy;   /**< see ZSTD_strategy definition above */
1360
} ZSTD_compressionParameters;
1361
1362
typedef struct {
1363
    int contentSizeFlag; /**< 1: content size will be in frame header (when known) */
1364
    int checksumFlag;    /**< 1: generate a 32-bits checksum using XXH64 algorithm at end of frame, for error detection */
1365
    int noDictIDFlag;    /**< 1: no dictID will be saved into frame header (dictID is only useful for dictionary compression) */
1366
} ZSTD_frameParameters;
1367
1368
typedef struct {
1369
    ZSTD_compressionParameters cParams;
1370
    ZSTD_frameParameters fParams;
1371
} ZSTD_parameters;
1372
1373
typedef enum {
1374
    ZSTD_dct_auto = 0,       /* dictionary is "full" when starting with ZSTD_MAGIC_DICTIONARY, otherwise it is "rawContent" */
1375
    ZSTD_dct_rawContent = 1, /* ensures dictionary is always loaded as rawContent, even if it starts with ZSTD_MAGIC_DICTIONARY */
1376
    ZSTD_dct_fullDict = 2    /* refuses to load a dictionary if it does not respect Zstandard's specification, starting with ZSTD_MAGIC_DICTIONARY */
1377
} ZSTD_dictContentType_e;
1378
1379
typedef enum {
1380
    ZSTD_dlm_byCopy = 0,  /**< Copy dictionary content internally */
1381
    ZSTD_dlm_byRef = 1    /**< Reference dictionary content -- the dictionary buffer must outlive its users. */
1382
} ZSTD_dictLoadMethod_e;
1383
1384
typedef enum {
1385
    ZSTD_f_zstd1 = 0,           /* zstd frame format, specified in zstd_compression_format.md (default) */
1386
    ZSTD_f_zstd1_magicless = 1  /* Variant of zstd frame format, without initial 4-bytes magic number.
1387
                                 * Useful to save 4 bytes per generated frame.
1388
                                 * Decoder cannot recognise automatically this format, requiring this instruction. */
1389
} ZSTD_format_e;
1390
1391
typedef enum {
1392
    /* Note: this enum controls ZSTD_d_forceIgnoreChecksum */
1393
    ZSTD_d_validateChecksum = 0,
1394
    ZSTD_d_ignoreChecksum = 1
1395
} ZSTD_forceIgnoreChecksum_e;
1396
1397
typedef enum {
1398
    /* Note: this enum controls ZSTD_d_refMultipleDDicts */
1399
    ZSTD_rmd_refSingleDDict = 0,
1400
    ZSTD_rmd_refMultipleDDicts = 1
1401
} ZSTD_refMultipleDDicts_e;
1402
1403
typedef enum {
1404
    /* Note: this enum and the behavior it controls are effectively internal
1405
     * implementation details of the compressor. They are expected to continue
1406
     * to evolve and should be considered only in the context of extremely
1407
     * advanced performance tuning.
1408
     *
1409
     * Zstd currently supports the use of a CDict in three ways:
1410
     *
1411
     * - The contents of the CDict can be copied into the working context. This
1412
     *   means that the compression can search both the dictionary and input
1413
     *   while operating on a single set of internal tables. This makes
1414
     *   the compression faster per-byte of input. However, the initial copy of
1415
     *   the CDict's tables incurs a fixed cost at the beginning of the
1416
     *   compression. For small compressions (< 8 KB), that copy can dominate
1417
     *   the cost of the compression.
1418
     *
1419
     * - The CDict's tables can be used in-place. In this model, compression is
1420
     *   slower per input byte, because the compressor has to search two sets of
1421
     *   tables. However, this model incurs no start-up cost (as long as the
1422
     *   working context's tables can be reused). For small inputs, this can be
1423
     *   faster than copying the CDict's tables.
1424
     *
1425
     * - The CDict's tables are not used at all, and instead we use the working
1426
     *   context alone to reload the dictionary and use params based on the source
1427
     *   size. See ZSTD_compress_insertDictionary() and ZSTD_compress_usingDict().
1428
     *   This method is effective when the dictionary sizes are very small relative
1429
     *   to the input size, and the input size is fairly large to begin with.
1430
     *
1431
     * Zstd has a simple internal heuristic that selects which strategy to use
1432
     * at the beginning of a compression. However, if experimentation shows that
1433
     * Zstd is making poor choices, it is possible to override that choice with
1434
     * this enum.
1435
     */
1436
    ZSTD_dictDefaultAttach = 0, /* Use the default heuristic. */
1437
    ZSTD_dictForceAttach   = 1, /* Never copy the dictionary. */
1438
    ZSTD_dictForceCopy     = 2, /* Always copy the dictionary. */
1439
    ZSTD_dictForceLoad     = 3  /* Always reload the dictionary */
1440
} ZSTD_dictAttachPref_e;
1441
1442
typedef enum {
1443
  ZSTD_lcm_auto = 0,          /**< Automatically determine the compression mode based on the compression level.
1444
                               *   Negative compression levels will be uncompressed, and positive compression
1445
                               *   levels will be compressed. */
1446
  ZSTD_lcm_huffman = 1,       /**< Always attempt Huffman compression. Uncompressed literals will still be
1447
                               *   emitted if Huffman compression is not profitable. */
1448
  ZSTD_lcm_uncompressed = 2   /**< Always emit uncompressed literals. */
1449
} ZSTD_literalCompressionMode_e;
1450
1451
typedef enum {
1452
  /* Note: This enum controls features which are conditionally beneficial.
1453
   * Zstd can take a decision on whether or not to enable the feature (ZSTD_ps_auto),
1454
   * but setting the switch to ZSTD_ps_enable or ZSTD_ps_disable force enable/disable the feature.
1455
   */
1456
  ZSTD_ps_auto = 0,         /* Let the library automatically determine whether the feature shall be enabled */
1457
  ZSTD_ps_enable = 1,       /* Force-enable the feature */
1458
  ZSTD_ps_disable = 2       /* Do not use the feature */
1459
} ZSTD_ParamSwitch_e;
1460
#define ZSTD_paramSwitch_e ZSTD_ParamSwitch_e  /* old name */
1461
1462
/***************************************
1463
*  Frame header and size functions
1464
***************************************/
1465
1466
/*! ZSTD_findDecompressedSize() :
1467
 *  `src` should point to the start of a series of ZSTD encoded and/or skippable frames
1468
 *  `srcSize` must be the _exact_ size of this series
1469
 *       (i.e. there should be a frame boundary at `src + srcSize`)
1470
 *  @return : - decompressed size of all data in all successive frames
1471
 *            - if the decompressed size cannot be determined: ZSTD_CONTENTSIZE_UNKNOWN
1472
 *            - if an error occurred: ZSTD_CONTENTSIZE_ERROR
1473
 *
1474
 *   note 1 : decompressed size is an optional field, that may not be present, especially in streaming mode.
1475
 *            When `return==ZSTD_CONTENTSIZE_UNKNOWN`, data to decompress could be any size.
1476
 *            In which case, it's necessary to use streaming mode to decompress data.
1477
 *   note 2 : decompressed size is always present when compression is done with ZSTD_compress()
1478
 *   note 3 : decompressed size can be very large (64-bits value),
1479
 *            potentially larger than what local system can handle as a single memory segment.
1480
 *            In which case, it's necessary to use streaming mode to decompress data.
1481
 *   note 4 : If source is untrusted, decompressed size could be wrong or intentionally modified.
1482
 *            Always ensure result fits within application's authorized limits.
1483
 *            Each application can set its own limits.
1484
 *   note 5 : ZSTD_findDecompressedSize handles multiple frames, and so it must traverse the input to
1485
 *            read each contained frame header.  This is fast as most of the data is skipped,
1486
 *            however it does mean that all frame data must be present and valid. */
1487
ZSTDLIB_STATIC_API unsigned long long ZSTD_findDecompressedSize(const void* src, size_t srcSize);
1488
1489
/*! ZSTD_decompressBound() :
1490
 *  `src` should point to the start of a series of ZSTD encoded and/or skippable frames
1491
 *  `srcSize` must be the _exact_ size of this series
1492
 *       (i.e. there should be a frame boundary at `src + srcSize`)
1493
 *  @return : - upper-bound for the decompressed size of all data in all successive frames
1494
 *            - if an error occurred: ZSTD_CONTENTSIZE_ERROR
1495
 *
1496
 *  note 1  : an error can occur if `src` contains an invalid or incorrectly formatted frame.
1497
 *  note 2  : the upper-bound is exact when the decompressed size field is available in every ZSTD encoded frame of `src`.
1498
 *            in this case, `ZSTD_findDecompressedSize` and `ZSTD_decompressBound` return the same value.
1499
 *  note 3  : when the decompressed size field isn't available, the upper-bound for that frame is calculated by:
1500
 *              upper-bound = # blocks * min(128 KB, Window_Size)
1501
 */
1502
ZSTDLIB_STATIC_API unsigned long long ZSTD_decompressBound(const void* src, size_t srcSize);
1503
1504
/*! ZSTD_frameHeaderSize() :
1505
 *  srcSize must be large enough, aka >= ZSTD_FRAMEHEADERSIZE_PREFIX.
1506
 * @return : size of the Frame Header,
1507
 *           or an error code (if srcSize is too small) */
1508
ZSTDLIB_STATIC_API size_t ZSTD_frameHeaderSize(const void* src, size_t srcSize);
1509
1510
typedef enum { ZSTD_frame, ZSTD_skippableFrame } ZSTD_FrameType_e;
1511
#define ZSTD_frameType_e ZSTD_FrameType_e /* old name */
1512
typedef struct {
1513
    unsigned long long frameContentSize; /* if == ZSTD_CONTENTSIZE_UNKNOWN, it means this field is not available. 0 means "empty" */
1514
    unsigned long long windowSize;       /* can be very large, up to <= frameContentSize */
1515
    unsigned blockSizeMax;
1516
    ZSTD_FrameType_e frameType;          /* if == ZSTD_skippableFrame, frameContentSize is the size of skippable content */
1517
    unsigned headerSize;
1518
    unsigned dictID;                     /* for ZSTD_skippableFrame, contains the skippable magic variant [0-15] */
1519
    unsigned checksumFlag;
1520
    unsigned _reserved1;
1521
    unsigned _reserved2;
1522
} ZSTD_FrameHeader;
1523
#define ZSTD_frameHeader ZSTD_FrameHeader /* old name */
1524
1525
/*! ZSTD_getFrameHeader() :
1526
 *  decode Frame Header into `zfhPtr`, or requires larger `srcSize`.
1527
 * @return : 0 => header is complete, `zfhPtr` is correctly filled,
1528
 *          >0 => `srcSize` is too small, @return value is the wanted `srcSize` amount, `zfhPtr` is not filled,
1529
 *           or an error code, which can be tested using ZSTD_isError() */
1530
ZSTDLIB_STATIC_API size_t ZSTD_getFrameHeader(ZSTD_FrameHeader* zfhPtr, const void* src, size_t srcSize);
1531
/*! ZSTD_getFrameHeader_advanced() :
1532
 *  same as ZSTD_getFrameHeader(),
1533
 *  with added capability to select a format (like ZSTD_f_zstd1_magicless) */
1534
ZSTDLIB_STATIC_API size_t ZSTD_getFrameHeader_advanced(ZSTD_FrameHeader* zfhPtr, const void* src, size_t srcSize, ZSTD_format_e format);
1535
1536
/*! ZSTD_decompressionMargin() :
1537
 * Zstd supports in-place decompression, where the input and output buffers overlap.
1538
 * In this case, the output buffer must be at least (Margin + Output_Size) bytes large,
1539
 * and the input buffer must be at the end of the output buffer.
1540
 *
1541
 *  _______________________ Output Buffer ________________________
1542
 * |                                                              |
1543
 * |                                        ____ Input Buffer ____|
1544
 * |                                       |                      |
1545
 * v                                       v                      v
1546
 * |---------------------------------------|-----------|----------|
1547
 * ^                                                   ^          ^
1548
 * |___________________ Output_Size ___________________|_ Margin _|
1549
 *
1550
 * NOTE: See also ZSTD_DECOMPRESSION_MARGIN().
1551
 * NOTE: This applies only to single-pass decompression through ZSTD_decompress() or
1552
 * ZSTD_decompressDCtx().
1553
 * NOTE: This function supports multi-frame input.
1554
 *
1555
 * @param src The compressed frame(s)
1556
 * @param srcSize The size of the compressed frame(s)
1557
 * @returns The decompression margin or an error that can be checked with ZSTD_isError().
1558
 */
1559
ZSTDLIB_STATIC_API size_t ZSTD_decompressionMargin(const void* src, size_t srcSize);
1560
1561
/*! ZSTD_DECOMPRESS_MARGIN() :
1562
 * Similar to ZSTD_decompressionMargin(), but instead of computing the margin from
1563
 * the compressed frame, compute it from the original size and the blockSizeLog.
1564
 * See ZSTD_decompressionMargin() for details.
1565
 *
1566
 * WARNING: This macro does not support multi-frame input, the input must be a single
1567
 * zstd frame. If you need that support use the function, or implement it yourself.
1568
 *
1569
 * @param originalSize The original uncompressed size of the data.
1570
 * @param blockSize    The block size == MIN(windowSize, ZSTD_BLOCKSIZE_MAX).
1571
 *                     Unless you explicitly set the windowLog smaller than
1572
 *                     ZSTD_BLOCKSIZELOG_MAX you can just use ZSTD_BLOCKSIZE_MAX.
1573
 */
1574
#define ZSTD_DECOMPRESSION_MARGIN(originalSize, blockSize) ((size_t)(                                              \
1575
        ZSTD_FRAMEHEADERSIZE_MAX                                                              /* Frame header */ + \
1576
        4                                                                                         /* checksum */ + \
1577
        ((originalSize) == 0 ? 0 : 3 * (((originalSize) + (blockSize) - 1) / blockSize)) /* 3 bytes per block */ + \
1578
        (blockSize)                                                                    /* One block of margin */   \
1579
    ))
1580
1581
typedef enum {
1582
  ZSTD_sf_noBlockDelimiters = 0,         /* ZSTD_Sequence[] has no block delimiters, just sequences */
1583
  ZSTD_sf_explicitBlockDelimiters = 1    /* ZSTD_Sequence[] contains explicit block delimiters */
1584
} ZSTD_SequenceFormat_e;
1585
#define ZSTD_sequenceFormat_e ZSTD_SequenceFormat_e /* old name */
1586
1587
/*! ZSTD_sequenceBound() :
1588
 * `srcSize` : size of the input buffer
1589
 *  @return : upper-bound for the number of sequences that can be generated
1590
 *            from a buffer of srcSize bytes
1591
 *
1592
 *  note : returns number of sequences - to get bytes, multiply by sizeof(ZSTD_Sequence).
1593
 */
1594
ZSTDLIB_STATIC_API size_t ZSTD_sequenceBound(size_t srcSize);
1595
1596
/*! ZSTD_generateSequences() :
1597
 * WARNING: This function is meant for debugging and informational purposes ONLY!
1598
 * Its implementation is flawed, and it will be deleted in a future version.
1599
 * It is not guaranteed to succeed, as there are several cases where it will give
1600
 * up and fail. You should NOT use this function in production code.
1601
 *
1602
 * This function is deprecated, and will be removed in a future version.
1603
 *
1604
 * Generate sequences using ZSTD_compress2(), given a source buffer.
1605
 *
1606
 * @param zc The compression context to be used for ZSTD_compress2(). Set any
1607
 *           compression parameters you need on this context.
1608
 * @param outSeqs The output sequences buffer of size @p outSeqsSize
1609
 * @param outSeqsCapacity The size of the output sequences buffer.
1610
 *                    ZSTD_sequenceBound(srcSize) is an upper bound on the number
1611
 *                    of sequences that can be generated.
1612
 * @param src The source buffer to generate sequences from of size @p srcSize.
1613
 * @param srcSize The size of the source buffer.
1614
 *
1615
 * Each block will end with a dummy sequence
1616
 * with offset == 0, matchLength == 0, and litLength == length of last literals.
1617
 * litLength may be == 0, and if so, then the sequence of (of: 0 ml: 0 ll: 0)
1618
 * simply acts as a block delimiter.
1619
 *
1620
 * @returns The number of sequences generated, necessarily less than
1621
 *          ZSTD_sequenceBound(srcSize), or an error code that can be checked
1622
 *          with ZSTD_isError().
1623
 */
1624
ZSTD_DEPRECATED("For debugging only, will be replaced by ZSTD_extractSequences()")
1625
ZSTDLIB_STATIC_API size_t
1626
ZSTD_generateSequences(ZSTD_CCtx* zc,
1627
                       ZSTD_Sequence* outSeqs, size_t outSeqsCapacity,
1628
                       const void* src, size_t srcSize);
1629
1630
/*! ZSTD_mergeBlockDelimiters() :
1631
 * Given an array of ZSTD_Sequence, remove all sequences that represent block delimiters/last literals
1632
 * by merging them into the literals of the next sequence.
1633
 *
1634
 * As such, the final generated result has no explicit representation of block boundaries,
1635
 * and the final last literals segment is not represented in the sequences.
1636
 *
1637
 * The output of this function can be fed into ZSTD_compressSequences() with CCtx
1638
 * setting of ZSTD_c_blockDelimiters as ZSTD_sf_noBlockDelimiters
1639
 * @return : number of sequences left after merging
1640
 */
1641
ZSTDLIB_STATIC_API size_t ZSTD_mergeBlockDelimiters(ZSTD_Sequence* sequences, size_t seqsSize);
1642
1643
/*! ZSTD_compressSequences() :
1644
 * Compress an array of ZSTD_Sequence, associated with @src buffer, into dst.
1645
 * @src contains the entire input (not just the literals).
1646
 * If @srcSize > sum(sequence.length), the remaining bytes are considered all literals
1647
 * If a dictionary is included, then the cctx should reference the dict (see: ZSTD_CCtx_refCDict(), ZSTD_CCtx_loadDictionary(), etc.).
1648
 * The entire source is compressed into a single frame.
1649
 *
1650
 * The compression behavior changes based on cctx params. In particular:
1651
 *    If ZSTD_c_blockDelimiters == ZSTD_sf_noBlockDelimiters, the array of ZSTD_Sequence is expected to contain
1652
 *    no block delimiters (defined in ZSTD_Sequence). Block boundaries are roughly determined based on
1653
 *    the block size derived from the cctx, and sequences may be split. This is the default setting.
1654
 *
1655
 *    If ZSTD_c_blockDelimiters == ZSTD_sf_explicitBlockDelimiters, the array of ZSTD_Sequence is expected to contain
1656
 *    valid block delimiters (defined in ZSTD_Sequence). Behavior is undefined if no block delimiters are provided.
1657
 *
1658
 *    When ZSTD_c_blockDelimiters == ZSTD_sf_explicitBlockDelimiters, it's possible to decide generating repcodes
1659
 *    using the advanced parameter ZSTD_c_repcodeResolution. Repcodes will improve compression ratio, though the benefit
1660
 *    can vary greatly depending on Sequences. On the other hand, repcode resolution is an expensive operation.
1661
 *    By default, it's disabled at low (<10) compression levels, and enabled above the threshold (>=10).
1662
 *    ZSTD_c_repcodeResolution makes it possible to directly manage this processing in either direction.
1663
 *
1664
 *    If ZSTD_c_validateSequences == 0, this function blindly accepts the Sequences provided. Invalid Sequences cause undefined
1665
 *    behavior. If ZSTD_c_validateSequences == 1, then the function will detect invalid Sequences (see doc/zstd_compression_format.md for
1666
 *    specifics regarding offset/matchlength requirements) and then bail out and return an error.
1667
 *
1668
 *    In addition to the two adjustable experimental params, there are other important cctx params.
1669
 *    - ZSTD_c_minMatch MUST be set as less than or equal to the smallest match generated by the match finder. It has a minimum value of ZSTD_MINMATCH_MIN.
1670
 *    - ZSTD_c_compressionLevel accordingly adjusts the strength of the entropy coder, as it would in typical compression.
1671
 *    - ZSTD_c_windowLog affects offset validation: this function will return an error at higher debug levels if a provided offset
1672
 *      is larger than what the spec allows for a given window log and dictionary (if present). See: doc/zstd_compression_format.md
1673
 *
1674
 * Note: Repcodes are, as of now, always re-calculated within this function, ZSTD_Sequence.rep is effectively unused.
1675
 * Dev Note: Once ability to ingest repcodes become available, the explicit block delims mode must respect those repcodes exactly,
1676
 *         and cannot emit an RLE block that disagrees with the repcode history.
1677
 * @return : final compressed size, or a ZSTD error code.
1678
 */
1679
ZSTDLIB_STATIC_API size_t
1680
ZSTD_compressSequences(ZSTD_CCtx* cctx,
1681
                       void* dst, size_t dstCapacity,
1682
                 const ZSTD_Sequence* inSeqs, size_t inSeqsSize,
1683
                 const void* src, size_t srcSize);
1684
1685
1686
/*! ZSTD_compressSequencesAndLiterals() :
1687
 * This is a variant of ZSTD_compressSequences() which,
1688
 * instead of receiving (src,srcSize) as input parameter, receives (literals,litSize),
1689
 * aka all the literals, already extracted and laid out into a single continuous buffer.
1690
 * This can be useful if the process generating the sequences also happens to generate the buffer of literals,
1691
 * thus skipping an extraction + caching stage.
1692
 * It's a speed optimization, useful when the right conditions are met,
1693
 * but it also features the following limitations:
1694
 * - Only supports explicit delimiter mode
1695
 * - Currently does not support Sequences validation (so input Sequences are trusted)
1696
 * - Not compatible with frame checksum, which must be disabled
1697
 * - If any block is incompressible, will fail and return an error
1698
 * - @litSize must be == sum of all @.litLength fields in @inSeqs. Any discrepancy will generate an error.
1699
 * - @litBufCapacity is the size of the underlying buffer into which literals are written, starting at address @literals.
1700
 *   @litBufCapacity must be at least 8 bytes larger than @litSize.
1701
 * - @decompressedSize must be correct, and correspond to the sum of all Sequences. Any discrepancy will generate an error.
1702
 * @return : final compressed size, or a ZSTD error code.
1703
 */
1704
ZSTDLIB_STATIC_API size_t
1705
ZSTD_compressSequencesAndLiterals(ZSTD_CCtx* cctx,
1706
                                  void* dst, size_t dstCapacity,
1707
                            const ZSTD_Sequence* inSeqs, size_t nbSequences,
1708
                            const void* literals, size_t litSize, size_t litBufCapacity,
1709
                            size_t decompressedSize);
1710
1711
1712
/*! ZSTD_writeSkippableFrame() :
1713
 * Generates a zstd skippable frame containing data given by src, and writes it to dst buffer.
1714
 *
1715
 * Skippable frames begin with a 4-byte magic number. There are 16 possible choices of magic number,
1716
 * ranging from ZSTD_MAGIC_SKIPPABLE_START to ZSTD_MAGIC_SKIPPABLE_START+15.
1717
 * As such, the parameter magicVariant controls the exact skippable frame magic number variant used,
1718
 * so the magic number used will be ZSTD_MAGIC_SKIPPABLE_START + magicVariant.
1719
 *
1720
 * Returns an error if destination buffer is not large enough, if the source size is not representable
1721
 * with a 4-byte unsigned int, or if the parameter magicVariant is greater than 15 (and therefore invalid).
1722
 *
1723
 * @return : number of bytes written or a ZSTD error.
1724
 */
1725
ZSTDLIB_STATIC_API size_t ZSTD_writeSkippableFrame(void* dst, size_t dstCapacity,
1726
                                             const void* src, size_t srcSize,
1727
                                                   unsigned magicVariant);
1728
1729
/*! ZSTD_readSkippableFrame() :
1730
 * Retrieves the content of a zstd skippable frame starting at @src, and writes it to @dst buffer.
1731
 *
1732
 * The parameter @magicVariant will receive the magicVariant that was supplied when the frame was written,
1733
 * i.e. magicNumber - ZSTD_MAGIC_SKIPPABLE_START.
1734
 * This can be NULL if the caller is not interested in the magicVariant.
1735
 *
1736
 * Returns an error if destination buffer is not large enough, or if the frame is not skippable.
1737
 *
1738
 * @return : number of bytes written or a ZSTD error.
1739
 */
1740
ZSTDLIB_STATIC_API size_t ZSTD_readSkippableFrame(void* dst, size_t dstCapacity,
1741
                                                  unsigned* magicVariant,
1742
                                                  const void* src, size_t srcSize);
1743
1744
/*! ZSTD_isSkippableFrame() :
1745
 *  Tells if the content of `buffer` starts with a valid Frame Identifier for a skippable frame.
1746
 */
1747
ZSTDLIB_STATIC_API unsigned ZSTD_isSkippableFrame(const void* buffer, size_t size);
1748
1749
1750
1751
/***************************************
1752
*  Memory management
1753
***************************************/
1754
1755
/*! ZSTD_estimate*() :
1756
 *  These functions make it possible to estimate memory usage
1757
 *  of a future {D,C}Ctx, before its creation.
1758
 *  This is useful in combination with ZSTD_initStatic(),
1759
 *  which makes it possible to employ a static buffer for ZSTD_CCtx* state.
1760
 *
1761
 *  ZSTD_estimateCCtxSize() will provide a memory budget large enough
1762
 *  to compress data of any size using one-shot compression ZSTD_compressCCtx() or ZSTD_compress2()
1763
 *  associated with any compression level up to max specified one.
1764
 *  The estimate will assume the input may be arbitrarily large,
1765
 *  which is the worst case.
1766
 *
1767
 *  Note that the size estimation is specific for one-shot compression,
1768
 *  it is not valid for streaming (see ZSTD_estimateCStreamSize*())
1769
 *  nor other potential ways of using a ZSTD_CCtx* state.
1770
 *
1771
 *  When srcSize can be bound by a known and rather "small" value,
1772
 *  this knowledge can be used to provide a tighter budget estimation
1773
 *  because the ZSTD_CCtx* state will need less memory for small inputs.
1774
 *  This tighter estimation can be provided by employing more advanced functions
1775
 *  ZSTD_estimateCCtxSize_usingCParams(), which can be used in tandem with ZSTD_getCParams(),
1776
 *  and ZSTD_estimateCCtxSize_usingCCtxParams(), which can be used in tandem with ZSTD_CCtxParams_setParameter().
1777
 *  Both can be used to estimate memory using custom compression parameters and arbitrary srcSize limits.
1778
 *
1779
 *  Note : only single-threaded compression is supported.
1780
 *  ZSTD_estimateCCtxSize_usingCCtxParams() will return an error code if ZSTD_c_nbWorkers is >= 1.
1781
 */
1782
ZSTDLIB_STATIC_API size_t ZSTD_estimateCCtxSize(int maxCompressionLevel);
1783
ZSTDLIB_STATIC_API size_t ZSTD_estimateCCtxSize_usingCParams(ZSTD_compressionParameters cParams);
1784
ZSTDLIB_STATIC_API size_t ZSTD_estimateCCtxSize_usingCCtxParams(const ZSTD_CCtx_params* params);
1785
ZSTDLIB_STATIC_API size_t ZSTD_estimateDCtxSize(void);
1786
1787
/*! ZSTD_estimateCStreamSize() :
1788
 *  ZSTD_estimateCStreamSize() will provide a memory budget large enough for streaming compression
1789
 *  using any compression level up to the max specified one.
1790
 *  It will also consider src size to be arbitrarily "large", which is a worst case scenario.
1791
 *  If srcSize is known to always be small, ZSTD_estimateCStreamSize_usingCParams() can provide a tighter estimation.
1792
 *  ZSTD_estimateCStreamSize_usingCParams() can be used in tandem with ZSTD_getCParams() to create cParams from compressionLevel.
1793
 *  ZSTD_estimateCStreamSize_usingCCtxParams() can be used in tandem with ZSTD_CCtxParams_setParameter(). Only single-threaded compression is supported. This function will return an error code if ZSTD_c_nbWorkers is >= 1.
1794
 *  Note : CStream size estimation is only correct for single-threaded compression.
1795
 *  ZSTD_estimateCStreamSize_usingCCtxParams() will return an error code if ZSTD_c_nbWorkers is >= 1.
1796
 *  Note 2 : ZSTD_estimateCStreamSize* functions are not compatible with the Block-Level Sequence Producer API at this time.
1797
 *  Size estimates assume that no external sequence producer is registered.
1798
 *
1799
 *  ZSTD_DStream memory budget depends on frame's window Size.
1800
 *  This information can be passed manually, using ZSTD_estimateDStreamSize,
1801
 *  or deducted from a valid frame Header, using ZSTD_estimateDStreamSize_fromFrame();
1802
 *  Any frame requesting a window size larger than max specified one will be rejected.
1803
 *  Note : if streaming is init with function ZSTD_init?Stream_usingDict(),
1804
 *         an internal ?Dict will be created, which additional size is not estimated here.
1805
 *         In this case, get total size by adding ZSTD_estimate?DictSize
1806
 */
1807
ZSTDLIB_STATIC_API size_t ZSTD_estimateCStreamSize(int maxCompressionLevel);
1808
ZSTDLIB_STATIC_API size_t ZSTD_estimateCStreamSize_usingCParams(ZSTD_compressionParameters cParams);
1809
ZSTDLIB_STATIC_API size_t ZSTD_estimateCStreamSize_usingCCtxParams(const ZSTD_CCtx_params* params);
1810
ZSTDLIB_STATIC_API size_t ZSTD_estimateDStreamSize(size_t maxWindowSize);
1811
ZSTDLIB_STATIC_API size_t ZSTD_estimateDStreamSize_fromFrame(const void* src, size_t srcSize);
1812
1813
/*! ZSTD_estimate?DictSize() :
1814
 *  ZSTD_estimateCDictSize() will bet that src size is relatively "small", and content is copied, like ZSTD_createCDict().
1815
 *  ZSTD_estimateCDictSize_advanced() makes it possible to control compression parameters precisely, like ZSTD_createCDict_advanced().
1816
 *  Note : dictionaries created by reference (`ZSTD_dlm_byRef`) are logically smaller.
1817
 */
1818
ZSTDLIB_STATIC_API size_t ZSTD_estimateCDictSize(size_t dictSize, int compressionLevel);
1819
ZSTDLIB_STATIC_API size_t ZSTD_estimateCDictSize_advanced(size_t dictSize, ZSTD_compressionParameters cParams, ZSTD_dictLoadMethod_e dictLoadMethod);
1820
ZSTDLIB_STATIC_API size_t ZSTD_estimateDDictSize(size_t dictSize, ZSTD_dictLoadMethod_e dictLoadMethod);
1821
1822
/*! ZSTD_initStatic*() :
1823
 *  Initialize an object using a pre-allocated fixed-size buffer.
1824
 *  workspace: The memory area to emplace the object into.
1825
 *             Provided pointer *must be 8-bytes aligned*.
1826
 *             Buffer must outlive object.
1827
 *  workspaceSize: Use ZSTD_estimate*Size() to determine
1828
 *                 how large workspace must be to support target scenario.
1829
 * @return : pointer to object (same address as workspace, just different type),
1830
 *           or NULL if error (size too small, incorrect alignment, etc.)
1831
 *  Note : zstd will never resize nor malloc() when using a static buffer.
1832
 *         If the object requires more memory than available,
1833
 *         zstd will just error out (typically ZSTD_error_memory_allocation).
1834
 *  Note 2 : there is no corresponding "free" function.
1835
 *           Since workspace is allocated externally, it must be freed externally too.
1836
 *  Note 3 : cParams : use ZSTD_getCParams() to convert a compression level
1837
 *           into its associated cParams.
1838
 *  Limitation 1 : currently not compatible with internal dictionary creation, triggered by
1839
 *                 ZSTD_CCtx_loadDictionary(), ZSTD_initCStream_usingDict() or ZSTD_initDStream_usingDict().
1840
 *  Limitation 2 : static cctx currently not compatible with multi-threading.
1841
 *  Limitation 3 : static dctx is incompatible with legacy support.
1842
 */
1843
ZSTDLIB_STATIC_API ZSTD_CCtx*    ZSTD_initStaticCCtx(void* workspace, size_t workspaceSize);
1844
ZSTDLIB_STATIC_API ZSTD_CStream* ZSTD_initStaticCStream(void* workspace, size_t workspaceSize);    /**< same as ZSTD_initStaticCCtx() */
1845
1846
ZSTDLIB_STATIC_API ZSTD_DCtx*    ZSTD_initStaticDCtx(void* workspace, size_t workspaceSize);
1847
ZSTDLIB_STATIC_API ZSTD_DStream* ZSTD_initStaticDStream(void* workspace, size_t workspaceSize);    /**< same as ZSTD_initStaticDCtx() */
1848
1849
ZSTDLIB_STATIC_API const ZSTD_CDict* ZSTD_initStaticCDict(
1850
                                        void* workspace, size_t workspaceSize,
1851
                                        const void* dict, size_t dictSize,
1852
                                        ZSTD_dictLoadMethod_e dictLoadMethod,
1853
                                        ZSTD_dictContentType_e dictContentType,
1854
                                        ZSTD_compressionParameters cParams);
1855
1856
ZSTDLIB_STATIC_API const ZSTD_DDict* ZSTD_initStaticDDict(
1857
                                        void* workspace, size_t workspaceSize,
1858
                                        const void* dict, size_t dictSize,
1859
                                        ZSTD_dictLoadMethod_e dictLoadMethod,
1860
                                        ZSTD_dictContentType_e dictContentType);
1861
1862
1863
/*! Custom memory allocation :
1864
 *  These prototypes make it possible to pass your own allocation/free functions.
1865
 *  ZSTD_customMem is provided at creation time, using ZSTD_create*_advanced() variants listed below.
1866
 *  All allocation/free operations will be completed using these custom variants instead of regular <stdlib.h> ones.
1867
 */
1868
typedef void* (*ZSTD_allocFunction) (void* opaque, size_t size);
1869
typedef void  (*ZSTD_freeFunction) (void* opaque, void* address);
1870
typedef struct { ZSTD_allocFunction customAlloc; ZSTD_freeFunction customFree; void* opaque; } ZSTD_customMem;
1871
#if defined(__clang__) && __clang_major__ >= 5
1872
#pragma clang diagnostic push
1873
#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant"
1874
#endif
1875
static
1876
#ifdef __GNUC__
1877
__attribute__((__unused__))
1878
#endif
1879
ZSTD_customMem const ZSTD_defaultCMem = { NULL, NULL, NULL };  /**< this constant defers to stdlib's functions */
1880
#if defined(__clang__) && __clang_major__ >= 5
1881
#pragma clang diagnostic pop
1882
#endif
1883
1884
ZSTDLIB_STATIC_API ZSTD_CCtx*    ZSTD_createCCtx_advanced(ZSTD_customMem customMem);
1885
ZSTDLIB_STATIC_API ZSTD_CStream* ZSTD_createCStream_advanced(ZSTD_customMem customMem);
1886
ZSTDLIB_STATIC_API ZSTD_DCtx*    ZSTD_createDCtx_advanced(ZSTD_customMem customMem);
1887
ZSTDLIB_STATIC_API ZSTD_DStream* ZSTD_createDStream_advanced(ZSTD_customMem customMem);
1888
1889
ZSTDLIB_STATIC_API ZSTD_CDict* ZSTD_createCDict_advanced(const void* dict, size_t dictSize,
1890
                                                  ZSTD_dictLoadMethod_e dictLoadMethod,
1891
                                                  ZSTD_dictContentType_e dictContentType,
1892
                                                  ZSTD_compressionParameters cParams,
1893
                                                  ZSTD_customMem customMem);
1894
1895
/*! Thread pool :
1896
 *  These prototypes make it possible to share a thread pool among multiple compression contexts.
1897
 *  This can limit resources for applications with multiple threads where each one uses
1898
 *  a threaded compression mode (via ZSTD_c_nbWorkers parameter).
1899
 *  ZSTD_createThreadPool creates a new thread pool with a given number of threads.
1900
 *  Note that the lifetime of such pool must exist while being used.
1901
 *  ZSTD_CCtx_refThreadPool assigns a thread pool to a context (use NULL argument value
1902
 *  to use an internal thread pool).
1903
 *  ZSTD_freeThreadPool frees a thread pool, accepts NULL pointer.
1904
 */
1905
typedef struct POOL_ctx_s ZSTD_threadPool;
1906
ZSTDLIB_STATIC_API ZSTD_threadPool* ZSTD_createThreadPool(size_t numThreads);
1907
ZSTDLIB_STATIC_API void ZSTD_freeThreadPool (ZSTD_threadPool* pool);  /* accept NULL pointer */
1908
ZSTDLIB_STATIC_API size_t ZSTD_CCtx_refThreadPool(ZSTD_CCtx* cctx, ZSTD_threadPool* pool);
1909
1910
1911
/*
1912
 * This API is temporary and is expected to change or disappear in the future!
1913
 */
1914
ZSTDLIB_STATIC_API ZSTD_CDict* ZSTD_createCDict_advanced2(
1915
    const void* dict, size_t dictSize,
1916
    ZSTD_dictLoadMethod_e dictLoadMethod,
1917
    ZSTD_dictContentType_e dictContentType,
1918
    const ZSTD_CCtx_params* cctxParams,
1919
    ZSTD_customMem customMem);
1920
1921
ZSTDLIB_STATIC_API ZSTD_DDict* ZSTD_createDDict_advanced(
1922
    const void* dict, size_t dictSize,
1923
    ZSTD_dictLoadMethod_e dictLoadMethod,
1924
    ZSTD_dictContentType_e dictContentType,
1925
    ZSTD_customMem customMem);
1926
1927
1928
/***************************************
1929
*  Advanced compression functions
1930
***************************************/
1931
1932
/*! ZSTD_createCDict_byReference() :
1933
 *  Create a digested dictionary for compression
1934
 *  Dictionary content is just referenced, not duplicated.
1935
 *  As a consequence, `dictBuffer` **must** outlive CDict,
1936
 *  and its content must remain unmodified throughout the lifetime of CDict.
1937
 *  note: equivalent to ZSTD_createCDict_advanced(), with dictLoadMethod==ZSTD_dlm_byRef */
1938
ZSTDLIB_STATIC_API ZSTD_CDict* ZSTD_createCDict_byReference(const void* dictBuffer, size_t dictSize, int compressionLevel);
1939
1940
/*! ZSTD_getCParams() :
1941
 * @return ZSTD_compressionParameters structure for a selected compression level and estimated srcSize.
1942
 * `estimatedSrcSize` value is optional, select 0 if not known */
1943
ZSTDLIB_STATIC_API ZSTD_compressionParameters ZSTD_getCParams(int compressionLevel, unsigned long long estimatedSrcSize, size_t dictSize);
1944
1945
/*! ZSTD_getParams() :
1946
 *  same as ZSTD_getCParams(), but @return a full `ZSTD_parameters` object instead of sub-component `ZSTD_compressionParameters`.
1947
 *  All fields of `ZSTD_frameParameters` are set to default : contentSize=1, checksum=0, noDictID=0 */
1948
ZSTDLIB_STATIC_API ZSTD_parameters ZSTD_getParams(int compressionLevel, unsigned long long estimatedSrcSize, size_t dictSize);
1949
1950
/*! ZSTD_checkCParams() :
1951
 *  Ensure param values remain within authorized range.
1952
 * @return 0 on success, or an error code (can be checked with ZSTD_isError()) */
1953
ZSTDLIB_STATIC_API size_t ZSTD_checkCParams(ZSTD_compressionParameters params);
1954
1955
/*! ZSTD_adjustCParams() :
1956
 *  optimize params for a given `srcSize` and `dictSize`.
1957
 * `srcSize` can be unknown, in which case use ZSTD_CONTENTSIZE_UNKNOWN.
1958
 * `dictSize` must be `0` when there is no dictionary.
1959
 *  cPar can be invalid : all parameters will be clamped within valid range in the @return struct.
1960
 *  This function never fails (wide contract) */
1961
ZSTDLIB_STATIC_API ZSTD_compressionParameters ZSTD_adjustCParams(ZSTD_compressionParameters cPar, unsigned long long srcSize, size_t dictSize);
1962
1963
/*! ZSTD_CCtx_setCParams() :
1964
 *  Set all parameters provided within @p cparams into the working @p cctx.
1965
 *  Note : if modifying parameters during compression (MT mode only),
1966
 *         note that changes to the .windowLog parameter will be ignored.
1967
 * @return 0 on success, or an error code (can be checked with ZSTD_isError()).
1968
 *         On failure, no parameters are updated.
1969
 */
1970
ZSTDLIB_STATIC_API size_t ZSTD_CCtx_setCParams(ZSTD_CCtx* cctx, ZSTD_compressionParameters cparams);
1971
1972
/*! ZSTD_CCtx_setFParams() :
1973
 *  Set all parameters provided within @p fparams into the working @p cctx.
1974
 * @return 0 on success, or an error code (can be checked with ZSTD_isError()).
1975
 */
1976
ZSTDLIB_STATIC_API size_t ZSTD_CCtx_setFParams(ZSTD_CCtx* cctx, ZSTD_frameParameters fparams);
1977
1978
/*! ZSTD_CCtx_setParams() :
1979
 *  Set all parameters provided within @p params into the working @p cctx.
1980
 * @return 0 on success, or an error code (can be checked with ZSTD_isError()).
1981
 */
1982
ZSTDLIB_STATIC_API size_t ZSTD_CCtx_setParams(ZSTD_CCtx* cctx, ZSTD_parameters params);
1983
1984
/*! ZSTD_compress_advanced() :
1985
 *  Note : this function is now DEPRECATED.
1986
 *         It can be replaced by ZSTD_compress2(), in combination with ZSTD_CCtx_setParameter() and other parameter setters.
1987
 *  This prototype will generate compilation warnings. */
1988
ZSTD_DEPRECATED("use ZSTD_compress2")
1989
ZSTDLIB_STATIC_API
1990
size_t ZSTD_compress_advanced(ZSTD_CCtx* cctx,
1991
                              void* dst, size_t dstCapacity,
1992
                        const void* src, size_t srcSize,
1993
                        const void* dict,size_t dictSize,
1994
                              ZSTD_parameters params);
1995
1996
/*! ZSTD_compress_usingCDict_advanced() :
1997
 *  Note : this function is now DEPRECATED.
1998
 *         It can be replaced by ZSTD_compress2(), in combination with ZSTD_CCtx_loadDictionary() and other parameter setters.
1999
 *  This prototype will generate compilation warnings. */
2000
ZSTD_DEPRECATED("use ZSTD_compress2 with ZSTD_CCtx_loadDictionary")
2001
ZSTDLIB_STATIC_API
2002
size_t ZSTD_compress_usingCDict_advanced(ZSTD_CCtx* cctx,
2003
                                              void* dst, size_t dstCapacity,
2004
                                        const void* src, size_t srcSize,
2005
                                        const ZSTD_CDict* cdict,
2006
                                              ZSTD_frameParameters fParams);
2007
2008
2009
/*! ZSTD_CCtx_loadDictionary_byReference() :
2010
 *  Same as ZSTD_CCtx_loadDictionary(), but dictionary content is referenced, instead of being copied into CCtx.
2011
 *  It saves some memory, but also requires that `dict` outlives its usage within `cctx` */
2012
ZSTDLIB_STATIC_API size_t ZSTD_CCtx_loadDictionary_byReference(ZSTD_CCtx* cctx, const void* dict, size_t dictSize);
2013
2014
/*! ZSTD_CCtx_loadDictionary_advanced() :
2015
 *  Same as ZSTD_CCtx_loadDictionary(), but gives finer control over
2016
 *  how to load the dictionary (by copy ? by reference ?)
2017
 *  and how to interpret it (automatic ? force raw mode ? full mode only ?) */
2018
ZSTDLIB_STATIC_API size_t ZSTD_CCtx_loadDictionary_advanced(ZSTD_CCtx* cctx, const void* dict, size_t dictSize, ZSTD_dictLoadMethod_e dictLoadMethod, ZSTD_dictContentType_e dictContentType);
2019
2020
/*! ZSTD_CCtx_refPrefix_advanced() :
2021
 *  Same as ZSTD_CCtx_refPrefix(), but gives finer control over
2022
 *  how to interpret prefix content (automatic ? force raw mode (default) ? full mode only ?) */
2023
ZSTDLIB_STATIC_API size_t ZSTD_CCtx_refPrefix_advanced(ZSTD_CCtx* cctx, const void* prefix, size_t prefixSize, ZSTD_dictContentType_e dictContentType);
2024
2025
/* ===   experimental parameters   === */
2026
/* these parameters can be used with ZSTD_setParameter()
2027
 * they are not guaranteed to remain supported in the future */
2028
2029
 /* Enables rsyncable mode,
2030
  * which makes compressed files more rsync friendly
2031
  * by adding periodic synchronization points to the compressed data.
2032
  * The target average block size is ZSTD_c_jobSize / 2.
2033
  * It's possible to modify the job size to increase or decrease
2034
  * the granularity of the synchronization point.
2035
  * Once the jobSize is smaller than the window size,
2036
  * it will result in compression ratio degradation.
2037
  * NOTE 1: rsyncable mode only works when multithreading is enabled.
2038
  * NOTE 2: rsyncable performs poorly in combination with long range mode,
2039
  * since it will decrease the effectiveness of synchronization points,
2040
  * though mileage may vary.
2041
  * NOTE 3: Rsyncable mode limits maximum compression speed to ~400 MB/s.
2042
  * If the selected compression level is already running significantly slower,
2043
  * the overall speed won't be significantly impacted.
2044
  */
2045
466k
 #define ZSTD_c_rsyncable ZSTD_c_experimentalParam1
2046
2047
/* Select a compression format.
2048
 * The value must be of type ZSTD_format_e.
2049
 * See ZSTD_format_e enum definition for details */
2050
219k
#define ZSTD_c_format ZSTD_c_experimentalParam2
2051
2052
/* Force back-reference distances to remain < windowSize,
2053
 * even when referencing into Dictionary content (default:0) */
2054
383k
#define ZSTD_c_forceMaxWindow ZSTD_c_experimentalParam3
2055
2056
/* Controls whether the contents of a CDict
2057
 * are used in place, or copied into the working context.
2058
 * Accepts values from the ZSTD_dictAttachPref_e enum.
2059
 * See the comments on that enum for an explanation of the feature. */
2060
438k
#define ZSTD_c_forceAttachDict ZSTD_c_experimentalParam4
2061
2062
/* Controlled with ZSTD_ParamSwitch_e enum.
2063
 * Default is ZSTD_ps_auto.
2064
 * Set to ZSTD_ps_disable to never compress literals.
2065
 * Set to ZSTD_ps_enable to always compress literals. (Note: uncompressed literals
2066
 * may still be emitted if huffman is not beneficial to use.)
2067
 *
2068
 * By default, in ZSTD_ps_auto, the library will decide at runtime whether to use
2069
 * literals compression based on the compression parameters - specifically,
2070
 * negative compression levels do not use literal compression.
2071
 */
2072
466k
#define ZSTD_c_literalCompressionMode ZSTD_c_experimentalParam5
2073
2074
/* User's best guess of source size.
2075
 * Hint is not valid when srcSizeHint == 0.
2076
 * There is no guarantee that hint is close to actual source size,
2077
 * but compression ratio may regress significantly if guess considerably underestimates */
2078
676k
#define ZSTD_c_srcSizeHint ZSTD_c_experimentalParam7
2079
2080
/* Controls whether the new and experimental "dedicated dictionary search
2081
 * structure" can be used. This feature is still rough around the edges, be
2082
 * prepared for surprising behavior!
2083
 *
2084
 * How to use it:
2085
 *
2086
 * When using a CDict, whether to use this feature or not is controlled at
2087
 * CDict creation, and it must be set in a CCtxParams set passed into that
2088
 * construction (via ZSTD_createCDict_advanced2()). A compression will then
2089
 * use the feature or not based on how the CDict was constructed; the value of
2090
 * this param, set in the CCtx, will have no effect.
2091
 *
2092
 * However, when a dictionary buffer is passed into a CCtx, such as via
2093
 * ZSTD_CCtx_loadDictionary(), this param can be set on the CCtx to control
2094
 * whether the CDict that is created internally can use the feature or not.
2095
 *
2096
 * What it does:
2097
 *
2098
 * Normally, the internal data structures of the CDict are analogous to what
2099
 * would be stored in a CCtx after compressing the contents of a dictionary.
2100
 * To an approximation, a compression using a dictionary can then use those
2101
 * data structures to simply continue what is effectively a streaming
2102
 * compression where the simulated compression of the dictionary left off.
2103
 * Which is to say, the search structures in the CDict are normally the same
2104
 * format as in the CCtx.
2105
 *
2106
 * It is possible to do better, since the CDict is not like a CCtx: the search
2107
 * structures are written once during CDict creation, and then are only read
2108
 * after that, while the search structures in the CCtx are both read and
2109
 * written as the compression goes along. This means we can choose a search
2110
 * structure for the dictionary that is read-optimized.
2111
 *
2112
 * This feature enables the use of that different structure.
2113
 *
2114
 * Note that some of the members of the ZSTD_compressionParameters struct have
2115
 * different semantics and constraints in the dedicated search structure. It is
2116
 * highly recommended that you simply set a compression level in the CCtxParams
2117
 * you pass into the CDict creation call, and avoid messing with the cParams
2118
 * directly.
2119
 *
2120
 * Effects:
2121
 *
2122
 * This will only have any effect when the selected ZSTD_strategy
2123
 * implementation supports this feature. Currently, that's limited to
2124
 * ZSTD_greedy, ZSTD_lazy, and ZSTD_lazy2.
2125
 *
2126
 * Note that this means that the CDict tables can no longer be copied into the
2127
 * CCtx, so the dict attachment mode ZSTD_dictForceCopy will no longer be
2128
 * usable. The dictionary can only be attached or reloaded.
2129
 *
2130
 * In general, you should expect compression to be faster--sometimes very much
2131
 * so--and CDict creation to be slightly slower. Eventually, we will probably
2132
 * make this mode the default.
2133
 */
2134
493k
#define ZSTD_c_enableDedicatedDictSearch ZSTD_c_experimentalParam8
2135
2136
/* ZSTD_c_stableInBuffer
2137
 * Experimental parameter.
2138
 * Default is 0 == disabled. Set to 1 to enable.
2139
 *
2140
 * Tells the compressor that input data presented with ZSTD_inBuffer
2141
 * will ALWAYS be the same between calls.
2142
 * Technically, the @src pointer must never be changed,
2143
 * and the @pos field can only be updated by zstd.
2144
 * However, it's possible to increase the @size field,
2145
 * allowing scenarios where more data can be appended after compressions starts.
2146
 * These conditions are checked by the compressor,
2147
 * and compression will fail if they are not respected.
2148
 * Also, data in the ZSTD_inBuffer within the range [src, src + pos)
2149
 * MUST not be modified during compression or it will result in data corruption.
2150
 *
2151
 * When this flag is enabled zstd won't allocate an input window buffer,
2152
 * because the user guarantees it can reference the ZSTD_inBuffer until
2153
 * the frame is complete. But, it will still allocate an output buffer
2154
 * large enough to fit a block (see ZSTD_c_stableOutBuffer). This will also
2155
 * avoid the memcpy() from the input buffer to the input window buffer.
2156
 *
2157
 * NOTE: So long as the ZSTD_inBuffer always points to valid memory, using
2158
 * this flag is ALWAYS memory safe, and will never access out-of-bounds
2159
 * memory. However, compression WILL fail if conditions are not respected.
2160
 *
2161
 * WARNING: The data in the ZSTD_inBuffer in the range [src, src + pos) MUST
2162
 * not be modified during compression or it will result in data corruption.
2163
 * This is because zstd needs to reference data in the ZSTD_inBuffer to find
2164
 * matches. Normally zstd maintains its own window buffer for this purpose,
2165
 * but passing this flag tells zstd to rely on user provided buffer instead.
2166
 */
2167
625k
#define ZSTD_c_stableInBuffer ZSTD_c_experimentalParam9
2168
2169
/* ZSTD_c_stableOutBuffer
2170
 * Experimental parameter.
2171
 * Default is 0 == disabled. Set to 1 to enable.
2172
 *
2173
 * Tells he compressor that the ZSTD_outBuffer will not be resized between
2174
 * calls. Specifically: (out.size - out.pos) will never grow. This gives the
2175
 * compressor the freedom to say: If the compressed data doesn't fit in the
2176
 * output buffer then return ZSTD_error_dstSizeTooSmall. This allows us to
2177
 * always decompress directly into the output buffer, instead of decompressing
2178
 * into an internal buffer and copying to the output buffer.
2179
 *
2180
 * When this flag is enabled zstd won't allocate an output buffer, because
2181
 * it can write directly to the ZSTD_outBuffer. It will still allocate the
2182
 * input window buffer (see ZSTD_c_stableInBuffer).
2183
 *
2184
 * Zstd will check that (out.size - out.pos) never grows and return an error
2185
 * if it does. While not strictly necessary, this should prevent surprises.
2186
 */
2187
625k
#define ZSTD_c_stableOutBuffer ZSTD_c_experimentalParam10
2188
2189
/* ZSTD_c_blockDelimiters
2190
 * Default is 0 == ZSTD_sf_noBlockDelimiters.
2191
 *
2192
 * For use with sequence compression API: ZSTD_compressSequences().
2193
 *
2194
 * Designates whether or not the given array of ZSTD_Sequence contains block delimiters
2195
 * and last literals, which are defined as sequences with offset == 0 and matchLength == 0.
2196
 * See the definition of ZSTD_Sequence for more specifics.
2197
 */
2198
804k
#define ZSTD_c_blockDelimiters ZSTD_c_experimentalParam11
2199
2200
/* ZSTD_c_validateSequences
2201
 * Default is 0 == disabled. Set to 1 to enable sequence validation.
2202
 *
2203
 * For use with sequence compression API: ZSTD_compressSequences*().
2204
 * Designates whether or not provided sequences are validated within ZSTD_compressSequences*()
2205
 * during function execution.
2206
 *
2207
 * When Sequence validation is disabled (default), Sequences are compressed as-is,
2208
 * so they must correct, otherwise it would result in a corruption error.
2209
 *
2210
 * Sequence validation adds some protection, by ensuring that all values respect boundary conditions.
2211
 * If a Sequence is detected invalid (see doc/zstd_compression_format.md for
2212
 * specifics regarding offset/matchlength requirements) then the function will bail out and
2213
 * return an error.
2214
 */
2215
779k
#define ZSTD_c_validateSequences ZSTD_c_experimentalParam12
2216
2217
/* ZSTD_c_blockSplitterLevel
2218
 * note: this parameter only influences the first splitter stage,
2219
 *       which is active before producing the sequences.
2220
 *       ZSTD_c_splitAfterSequences controls the next splitter stage,
2221
 *       which is active after sequence production.
2222
 *       Note that both can be combined.
2223
 * Allowed values are between 0 and ZSTD_BLOCKSPLITTER_LEVEL_MAX included.
2224
 * 0 means "auto", which will select a value depending on current ZSTD_c_strategy.
2225
 * 1 means no splitting.
2226
 * Then, values from 2 to 6 are sorted in increasing cpu load order.
2227
 *
2228
 * Note that currently the first block is never split,
2229
 * to ensure expansion guarantees in presence of incompressible data.
2230
 */
2231
54.8k
#define ZSTD_BLOCKSPLITTER_LEVEL_MAX 6
2232
834k
#define ZSTD_c_blockSplitterLevel ZSTD_c_experimentalParam20
2233
2234
/* ZSTD_c_splitAfterSequences
2235
 * This is a stronger splitter algorithm,
2236
 * based on actual sequences previously produced by the selected parser.
2237
 * It's also slower, and as a consequence, mostly used for high compression levels.
2238
 * While the post-splitter does overlap with the pre-splitter,
2239
 * both can nonetheless be combined,
2240
 * notably with ZSTD_c_blockSplitterLevel at ZSTD_BLOCKSPLITTER_LEVEL_MAX,
2241
 * resulting in higher compression ratio than just one of them.
2242
 *
2243
 * Default is ZSTD_ps_auto.
2244
 * Set to ZSTD_ps_disable to never use block splitter.
2245
 * Set to ZSTD_ps_enable to always use block splitter.
2246
 *
2247
 * By default, in ZSTD_ps_auto, the library will decide at runtime whether to use
2248
 * block splitting based on the compression parameters.
2249
 */
2250
807k
#define ZSTD_c_splitAfterSequences ZSTD_c_experimentalParam13
2251
2252
/* ZSTD_c_useRowMatchFinder
2253
 * Controlled with ZSTD_ParamSwitch_e enum.
2254
 * Default is ZSTD_ps_auto.
2255
 * Set to ZSTD_ps_disable to never use row-based matchfinder.
2256
 * Set to ZSTD_ps_enable to force usage of row-based matchfinder.
2257
 *
2258
 * By default, in ZSTD_ps_auto, the library will decide at runtime whether to use
2259
 * the row-based matchfinder based on support for SIMD instructions and the window log.
2260
 * Note that this only pertains to compression strategies: greedy, lazy, and lazy2
2261
 */
2262
861k
#define ZSTD_c_useRowMatchFinder ZSTD_c_experimentalParam14
2263
2264
/* ZSTD_c_deterministicRefPrefix
2265
 * Default is 0 == disabled. Set to 1 to enable.
2266
 *
2267
 * Zstd produces different results for prefix compression when the prefix is
2268
 * directly adjacent to the data about to be compressed vs. when it isn't.
2269
 * This is because zstd detects that the two buffers are contiguous and it can
2270
 * use a more efficient match finding algorithm. However, this produces different
2271
 * results than when the two buffers are non-contiguous. This flag forces zstd
2272
 * to always load the prefix in non-contiguous mode, even if it happens to be
2273
 * adjacent to the data, to guarantee determinism.
2274
 *
2275
 * If you really care about determinism when using a dictionary or prefix,
2276
 * like when doing delta compression, you should select this option. It comes
2277
 * at a speed penalty of about ~2.5% if the dictionary and data happened to be
2278
 * contiguous, and is free if they weren't contiguous. We don't expect that
2279
 * intentionally making the dictionary and data contiguous will be worth the
2280
 * cost to memcpy() the data.
2281
 */
2282
889k
#define ZSTD_c_deterministicRefPrefix ZSTD_c_experimentalParam15
2283
2284
/* ZSTD_c_prefetchCDictTables
2285
 * Controlled with ZSTD_ParamSwitch_e enum. Default is ZSTD_ps_auto.
2286
 *
2287
 * In some situations, zstd uses CDict tables in-place rather than copying them
2288
 * into the working context. (See docs on ZSTD_dictAttachPref_e above for details).
2289
 * In such situations, compression speed is seriously impacted when CDict tables are
2290
 * "cold" (outside CPU cache). This parameter instructs zstd to prefetch CDict tables
2291
 * when they are used in-place.
2292
 *
2293
 * For sufficiently small inputs, the cost of the prefetch will outweigh the benefit.
2294
 * For sufficiently large inputs, zstd will by default memcpy() CDict tables
2295
 * into the working context, so there is no need to prefetch. This parameter is
2296
 * targeted at a middle range of input sizes, where a prefetch is cheap enough to be
2297
 * useful but memcpy() is too expensive. The exact range of input sizes where this
2298
 * makes sense is best determined by careful experimentation.
2299
 *
2300
 * Note: for this parameter, ZSTD_ps_auto is currently equivalent to ZSTD_ps_disable,
2301
 * but in the future zstd may conditionally enable this feature via an auto-detection
2302
 * heuristic for cold CDicts.
2303
 * Use ZSTD_ps_disable to opt out of prefetching under any circumstances.
2304
 */
2305
916k
#define ZSTD_c_prefetchCDictTables ZSTD_c_experimentalParam16
2306
2307
/* ZSTD_c_enableSeqProducerFallback
2308
 * Allowed values are 0 (disable) and 1 (enable). The default setting is 0.
2309
 *
2310
 * Controls whether zstd will fall back to an internal sequence producer if an
2311
 * external sequence producer is registered and returns an error code. This fallback
2312
 * is block-by-block: the internal sequence producer will only be called for blocks
2313
 * where the external sequence producer returns an error code. Fallback parsing will
2314
 * follow any other cParam settings, such as compression level, the same as in a
2315
 * normal (fully-internal) compression operation.
2316
 *
2317
 * The user is strongly encouraged to read the full Block-Level Sequence Producer API
2318
 * documentation (below) before setting this parameter. */
2319
835k
#define ZSTD_c_enableSeqProducerFallback ZSTD_c_experimentalParam17
2320
2321
/* ZSTD_c_maxBlockSize
2322
 * Allowed values are between 1KB and ZSTD_BLOCKSIZE_MAX (128KB).
2323
 * The default is ZSTD_BLOCKSIZE_MAX, and setting to 0 will set to the default.
2324
 *
2325
 * This parameter can be used to set an upper bound on the blocksize
2326
 * that overrides the default ZSTD_BLOCKSIZE_MAX. It cannot be used to set upper
2327
 * bounds greater than ZSTD_BLOCKSIZE_MAX or bounds lower than 1KB (will make
2328
 * compressBound() inaccurate). Only currently meant to be used for testing.
2329
 */
2330
944k
#define ZSTD_c_maxBlockSize ZSTD_c_experimentalParam18
2331
2332
/* ZSTD_c_repcodeResolution
2333
 * This parameter only has an effect if ZSTD_c_blockDelimiters is
2334
 * set to ZSTD_sf_explicitBlockDelimiters (may change in the future).
2335
 *
2336
 * This parameter affects how zstd parses external sequences,
2337
 * provided via the ZSTD_compressSequences*() API
2338
 * or from an external block-level sequence producer.
2339
 *
2340
 * If set to ZSTD_ps_enable, the library will check for repeated offsets within
2341
 * external sequences, even if those repcodes are not explicitly indicated in
2342
 * the "rep" field. Note that this is the only way to exploit repcode matches
2343
 * while using compressSequences*() or an external sequence producer, since zstd
2344
 * currently ignores the "rep" field of external sequences.
2345
 *
2346
 * If set to ZSTD_ps_disable, the library will not exploit repeated offsets in
2347
 * external sequences, regardless of whether the "rep" field has been set. This
2348
 * reduces sequence compression overhead by about 25% while sacrificing some
2349
 * compression ratio.
2350
 *
2351
 * The default value is ZSTD_ps_auto, for which the library will enable/disable
2352
 * based on compression level (currently: level<10 disables, level>=10 enables).
2353
 */
2354
972k
#define ZSTD_c_repcodeResolution ZSTD_c_experimentalParam19
2355
#define ZSTD_c_searchForExternalRepcodes ZSTD_c_experimentalParam19 /* older name */
2356
2357
2358
/*! ZSTD_CCtx_getParameter() :
2359
 *  Get the requested compression parameter value, selected by enum ZSTD_cParameter,
2360
 *  and store it into int* value.
2361
 * @return : 0, or an error code (which can be tested with ZSTD_isError()).
2362
 */
2363
ZSTDLIB_STATIC_API size_t ZSTD_CCtx_getParameter(const ZSTD_CCtx* cctx, ZSTD_cParameter param, int* value);
2364
2365
2366
/*! ZSTD_CCtx_params :
2367
 *  Quick howto :
2368
 *  - ZSTD_createCCtxParams() : Create a ZSTD_CCtx_params structure
2369
 *  - ZSTD_CCtxParams_setParameter() : Push parameters one by one into
2370
 *                                     an existing ZSTD_CCtx_params structure.
2371
 *                                     This is similar to
2372
 *                                     ZSTD_CCtx_setParameter().
2373
 *  - ZSTD_CCtx_setParametersUsingCCtxParams() : Apply parameters to
2374
 *                                    an existing CCtx.
2375
 *                                    These parameters will be applied to
2376
 *                                    all subsequent frames.
2377
 *  - ZSTD_compressStream2() : Do compression using the CCtx.
2378
 *  - ZSTD_freeCCtxParams() : Free the memory, accept NULL pointer.
2379
 *
2380
 *  This can be used with ZSTD_estimateCCtxSize_advanced_usingCCtxParams()
2381
 *  for static allocation of CCtx for single-threaded compression.
2382
 */
2383
ZSTDLIB_STATIC_API ZSTD_CCtx_params* ZSTD_createCCtxParams(void);
2384
ZSTDLIB_STATIC_API size_t ZSTD_freeCCtxParams(ZSTD_CCtx_params* params);  /* accept NULL pointer */
2385
2386
/*! ZSTD_CCtxParams_reset() :
2387
 *  Reset params to default values.
2388
 */
2389
ZSTDLIB_STATIC_API size_t ZSTD_CCtxParams_reset(ZSTD_CCtx_params* params);
2390
2391
/*! ZSTD_CCtxParams_init() :
2392
 *  Initializes the compression parameters of cctxParams according to
2393
 *  compression level. All other parameters are reset to their default values.
2394
 */
2395
ZSTDLIB_STATIC_API size_t ZSTD_CCtxParams_init(ZSTD_CCtx_params* cctxParams, int compressionLevel);
2396
2397
/*! ZSTD_CCtxParams_init_advanced() :
2398
 *  Initializes the compression and frame parameters of cctxParams according to
2399
 *  params. All other parameters are reset to their default values.
2400
 */
2401
ZSTDLIB_STATIC_API size_t ZSTD_CCtxParams_init_advanced(ZSTD_CCtx_params* cctxParams, ZSTD_parameters params);
2402
2403
/*! ZSTD_CCtxParams_setParameter() : Requires v1.4.0+
2404
 *  Similar to ZSTD_CCtx_setParameter.
2405
 *  Set one compression parameter, selected by enum ZSTD_cParameter.
2406
 *  Parameters must be applied to a ZSTD_CCtx using
2407
 *  ZSTD_CCtx_setParametersUsingCCtxParams().
2408
 * @result : a code representing success or failure (which can be tested with
2409
 *           ZSTD_isError()).
2410
 */
2411
ZSTDLIB_STATIC_API size_t ZSTD_CCtxParams_setParameter(ZSTD_CCtx_params* params, ZSTD_cParameter param, int value);
2412
2413
/*! ZSTD_CCtxParams_getParameter() :
2414
 * Similar to ZSTD_CCtx_getParameter.
2415
 * Get the requested value of one compression parameter, selected by enum ZSTD_cParameter.
2416
 * @result : 0, or an error code (which can be tested with ZSTD_isError()).
2417
 */
2418
ZSTDLIB_STATIC_API size_t ZSTD_CCtxParams_getParameter(const ZSTD_CCtx_params* params, ZSTD_cParameter param, int* value);
2419
2420
/*! ZSTD_CCtx_setParametersUsingCCtxParams() :
2421
 *  Apply a set of ZSTD_CCtx_params to the compression context.
2422
 *  This can be done even after compression is started,
2423
 *    if nbWorkers==0, this will have no impact until a new compression is started.
2424
 *    if nbWorkers>=1, new parameters will be picked up at next job,
2425
 *       with a few restrictions (windowLog, pledgedSrcSize, nbWorkers, jobSize, and overlapLog are not updated).
2426
 */
2427
ZSTDLIB_STATIC_API size_t ZSTD_CCtx_setParametersUsingCCtxParams(
2428
        ZSTD_CCtx* cctx, const ZSTD_CCtx_params* params);
2429
2430
/*! ZSTD_compressStream2_simpleArgs() :
2431
 *  Same as ZSTD_compressStream2(),
2432
 *  but using only integral types as arguments.
2433
 *  This variant might be helpful for binders from dynamic languages
2434
 *  which have troubles handling structures containing memory pointers.
2435
 */
2436
ZSTDLIB_STATIC_API size_t ZSTD_compressStream2_simpleArgs (
2437
                            ZSTD_CCtx* cctx,
2438
                            void* dst, size_t dstCapacity, size_t* dstPos,
2439
                      const void* src, size_t srcSize, size_t* srcPos,
2440
                            ZSTD_EndDirective endOp);
2441
2442
2443
/***************************************
2444
*  Advanced decompression functions
2445
***************************************/
2446
2447
/*! ZSTD_isFrame() :
2448
 *  Tells if the content of `buffer` starts with a valid Frame Identifier.
2449
 *  Note : Frame Identifier is 4 bytes. If `size < 4`, @return will always be 0.
2450
 *  Note 2 : Legacy Frame Identifiers are considered valid only if Legacy Support is enabled.
2451
 *  Note 3 : Skippable Frame Identifiers are considered valid. */
2452
ZSTDLIB_STATIC_API unsigned ZSTD_isFrame(const void* buffer, size_t size);
2453
2454
/*! ZSTD_createDDict_byReference() :
2455
 *  Create a digested dictionary, ready to start decompression operation without startup delay.
2456
 *  Dictionary content is referenced, and therefore stays in dictBuffer.
2457
 *  It is important that dictBuffer outlives DDict,
2458
 *  it must remain read accessible throughout the lifetime of DDict */
2459
ZSTDLIB_STATIC_API ZSTD_DDict* ZSTD_createDDict_byReference(const void* dictBuffer, size_t dictSize);
2460
2461
/*! ZSTD_DCtx_loadDictionary_byReference() :
2462
 *  Same as ZSTD_DCtx_loadDictionary(),
2463
 *  but references `dict` content instead of copying it into `dctx`.
2464
 *  This saves memory if `dict` remains around.,
2465
 *  However, it's imperative that `dict` remains accessible (and unmodified) while being used, so it must outlive decompression. */
2466
ZSTDLIB_STATIC_API size_t ZSTD_DCtx_loadDictionary_byReference(ZSTD_DCtx* dctx, const void* dict, size_t dictSize);
2467
2468
/*! ZSTD_DCtx_loadDictionary_advanced() :
2469
 *  Same as ZSTD_DCtx_loadDictionary(),
2470
 *  but gives direct control over
2471
 *  how to load the dictionary (by copy ? by reference ?)
2472
 *  and how to interpret it (automatic ? force raw mode ? full mode only ?). */
2473
ZSTDLIB_STATIC_API size_t ZSTD_DCtx_loadDictionary_advanced(ZSTD_DCtx* dctx, const void* dict, size_t dictSize, ZSTD_dictLoadMethod_e dictLoadMethod, ZSTD_dictContentType_e dictContentType);
2474
2475
/*! ZSTD_DCtx_refPrefix_advanced() :
2476
 *  Same as ZSTD_DCtx_refPrefix(), but gives finer control over
2477
 *  how to interpret prefix content (automatic ? force raw mode (default) ? full mode only ?) */
2478
ZSTDLIB_STATIC_API size_t ZSTD_DCtx_refPrefix_advanced(ZSTD_DCtx* dctx, const void* prefix, size_t prefixSize, ZSTD_dictContentType_e dictContentType);
2479
2480
/*! ZSTD_DCtx_setMaxWindowSize() :
2481
 *  Refuses allocating internal buffers for frames requiring a window size larger than provided limit.
2482
 *  This protects a decoder context from reserving too much memory for itself (potential attack scenario).
2483
 *  This parameter is only useful in streaming mode, since no internal buffer is allocated in single-pass mode.
2484
 *  By default, a decompression context accepts all window sizes <= (1 << ZSTD_WINDOWLOG_LIMIT_DEFAULT)
2485
 * @return : 0, or an error code (which can be tested using ZSTD_isError()).
2486
 */
2487
ZSTDLIB_STATIC_API size_t ZSTD_DCtx_setMaxWindowSize(ZSTD_DCtx* dctx, size_t maxWindowSize);
2488
2489
/*! ZSTD_DCtx_getParameter() :
2490
 *  Get the requested decompression parameter value, selected by enum ZSTD_dParameter,
2491
 *  and store it into int* value.
2492
 * @return : 0, or an error code (which can be tested with ZSTD_isError()).
2493
 */
2494
ZSTDLIB_STATIC_API size_t ZSTD_DCtx_getParameter(ZSTD_DCtx* dctx, ZSTD_dParameter param, int* value);
2495
2496
/* ZSTD_d_format
2497
 * experimental parameter,
2498
 * allowing selection between ZSTD_format_e input compression formats
2499
 */
2500
0
#define ZSTD_d_format ZSTD_d_experimentalParam1
2501
/* ZSTD_d_stableOutBuffer
2502
 * Experimental parameter.
2503
 * Default is 0 == disabled. Set to 1 to enable.
2504
 *
2505
 * Tells the decompressor that the ZSTD_outBuffer will ALWAYS be the same
2506
 * between calls, except for the modifications that zstd makes to pos (the
2507
 * caller must not modify pos). This is checked by the decompressor, and
2508
 * decompression will fail if it ever changes. Therefore the ZSTD_outBuffer
2509
 * MUST be large enough to fit the entire decompressed frame. This will be
2510
 * checked when the frame content size is known. The data in the ZSTD_outBuffer
2511
 * in the range [dst, dst + pos) MUST not be modified during decompression
2512
 * or you will get data corruption.
2513
 *
2514
 * When this flag is enabled zstd won't allocate an output buffer, because
2515
 * it can write directly to the ZSTD_outBuffer, but it will still allocate
2516
 * an input buffer large enough to fit any compressed block. This will also
2517
 * avoid the memcpy() from the internal output buffer to the ZSTD_outBuffer.
2518
 * If you need to avoid the input buffer allocation use the buffer-less
2519
 * streaming API.
2520
 *
2521
 * NOTE: So long as the ZSTD_outBuffer always points to valid memory, using
2522
 * this flag is ALWAYS memory safe, and will never access out-of-bounds
2523
 * memory. However, decompression WILL fail if you violate the preconditions.
2524
 *
2525
 * WARNING: The data in the ZSTD_outBuffer in the range [dst, dst + pos) MUST
2526
 * not be modified during decompression or you will get data corruption. This
2527
 * is because zstd needs to reference data in the ZSTD_outBuffer to regenerate
2528
 * matches. Normally zstd maintains its own buffer for this purpose, but passing
2529
 * this flag tells zstd to use the user provided buffer.
2530
 */
2531
0
#define ZSTD_d_stableOutBuffer ZSTD_d_experimentalParam2
2532
2533
/* ZSTD_d_forceIgnoreChecksum
2534
 * Experimental parameter.
2535
 * Default is 0 == disabled. Set to 1 to enable
2536
 *
2537
 * Tells the decompressor to skip checksum validation during decompression, regardless
2538
 * of whether checksumming was specified during compression. This offers some
2539
 * slight performance benefits, and may be useful for debugging.
2540
 * Param has values of type ZSTD_forceIgnoreChecksum_e
2541
 */
2542
0
#define ZSTD_d_forceIgnoreChecksum ZSTD_d_experimentalParam3
2543
2544
/* ZSTD_d_refMultipleDDicts
2545
 * Experimental parameter.
2546
 * Default is 0 == disabled. Set to 1 to enable
2547
 *
2548
 * If enabled and dctx is allocated on the heap, then additional memory will be allocated
2549
 * to store references to multiple ZSTD_DDict. That is, multiple calls of ZSTD_refDDict()
2550
 * using a given ZSTD_DCtx, rather than overwriting the previous DDict reference, will instead
2551
 * store all references. At decompression time, the appropriate dictID is selected
2552
 * from the set of DDicts based on the dictID in the frame.
2553
 *
2554
 * Usage is simply calling ZSTD_refDDict() on multiple dict buffers.
2555
 *
2556
 * Param has values of byte ZSTD_refMultipleDDicts_e
2557
 *
2558
 * WARNING: Enabling this parameter and calling ZSTD_DCtx_refDDict(), will trigger memory
2559
 * allocation for the hash table. ZSTD_freeDCtx() also frees this memory.
2560
 * Memory is allocated as per ZSTD_DCtx::customMem.
2561
 *
2562
 * Although this function allocates memory for the table, the user is still responsible for
2563
 * memory management of the underlying ZSTD_DDict* themselves.
2564
 */
2565
0
#define ZSTD_d_refMultipleDDicts ZSTD_d_experimentalParam4
2566
2567
/* ZSTD_d_disableHuffmanAssembly
2568
 * Set to 1 to disable the Huffman assembly implementation.
2569
 * The default value is 0, which allows zstd to use the Huffman assembly
2570
 * implementation if available.
2571
 *
2572
 * This parameter can be used to disable Huffman assembly at runtime.
2573
 * If you want to disable it at compile time you can define the macro
2574
 * ZSTD_DISABLE_ASM.
2575
 */
2576
0
#define ZSTD_d_disableHuffmanAssembly ZSTD_d_experimentalParam5
2577
2578
/* ZSTD_d_maxBlockSize
2579
 * Allowed values are between 1KB and ZSTD_BLOCKSIZE_MAX (128KB).
2580
 * The default is ZSTD_BLOCKSIZE_MAX, and setting to 0 will set to the default.
2581
 *
2582
 * Forces the decompressor to reject blocks whose content size is
2583
 * larger than the configured maxBlockSize. When maxBlockSize is
2584
 * larger than the windowSize, the windowSize is used instead.
2585
 * This saves memory on the decoder when you know all blocks are small.
2586
 *
2587
 * This option is typically used in conjunction with ZSTD_c_maxBlockSize.
2588
 *
2589
 * WARNING: This causes the decoder to reject otherwise valid frames
2590
 * that have block sizes larger than the configured maxBlockSize.
2591
 */
2592
0
#define ZSTD_d_maxBlockSize ZSTD_d_experimentalParam6
2593
2594
2595
/*! ZSTD_DCtx_setFormat() :
2596
 *  This function is REDUNDANT. Prefer ZSTD_DCtx_setParameter().
2597
 *  Instruct the decoder context about what kind of data to decode next.
2598
 *  This instruction is mandatory to decode data without a fully-formed header,
2599
 *  such ZSTD_f_zstd1_magicless for example.
2600
 * @return : 0, or an error code (which can be tested using ZSTD_isError()). */
2601
ZSTD_DEPRECATED("use ZSTD_DCtx_setParameter() instead")
2602
ZSTDLIB_STATIC_API
2603
size_t ZSTD_DCtx_setFormat(ZSTD_DCtx* dctx, ZSTD_format_e format);
2604
2605
/*! ZSTD_decompressStream_simpleArgs() :
2606
 *  Same as ZSTD_decompressStream(),
2607
 *  but using only integral types as arguments.
2608
 *  This can be helpful for binders from dynamic languages
2609
 *  which have troubles handling structures containing memory pointers.
2610
 */
2611
ZSTDLIB_STATIC_API size_t ZSTD_decompressStream_simpleArgs (
2612
                            ZSTD_DCtx* dctx,
2613
                            void* dst, size_t dstCapacity, size_t* dstPos,
2614
                      const void* src, size_t srcSize, size_t* srcPos);
2615
2616
2617
/********************************************************************
2618
*  Advanced streaming functions
2619
*  Warning : most of these functions are now redundant with the Advanced API.
2620
*  Once Advanced API reaches "stable" status,
2621
*  redundant functions will be deprecated, and then at some point removed.
2622
********************************************************************/
2623
2624
/*=====   Advanced Streaming compression functions  =====*/
2625
2626
/*! ZSTD_initCStream_srcSize() :
2627
 * This function is DEPRECATED, and equivalent to:
2628
 *     ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only);
2629
 *     ZSTD_CCtx_refCDict(zcs, NULL); // clear the dictionary (if any)
2630
 *     ZSTD_CCtx_setParameter(zcs, ZSTD_c_compressionLevel, compressionLevel);
2631
 *     ZSTD_CCtx_setPledgedSrcSize(zcs, pledgedSrcSize);
2632
 *
2633
 * pledgedSrcSize must be correct. If it is not known at init time, use
2634
 * ZSTD_CONTENTSIZE_UNKNOWN. Note that, for compatibility with older programs,
2635
 * "0" also disables frame content size field. It may be enabled in the future.
2636
 * This prototype will generate compilation warnings.
2637
 */
2638
ZSTD_DEPRECATED("use ZSTD_CCtx_reset, see zstd.h for detailed instructions")
2639
ZSTDLIB_STATIC_API
2640
size_t ZSTD_initCStream_srcSize(ZSTD_CStream* zcs,
2641
                         int compressionLevel,
2642
                         unsigned long long pledgedSrcSize);
2643
2644
/*! ZSTD_initCStream_usingDict() :
2645
 * This function is DEPRECATED, and is equivalent to:
2646
 *     ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only);
2647
 *     ZSTD_CCtx_setParameter(zcs, ZSTD_c_compressionLevel, compressionLevel);
2648
 *     ZSTD_CCtx_loadDictionary(zcs, dict, dictSize);
2649
 *
2650
 * Creates of an internal CDict (incompatible with static CCtx), except if
2651
 * dict == NULL or dictSize < 8, in which case no dict is used.
2652
 * Note: dict is loaded with ZSTD_dct_auto (treated as a full zstd dictionary if
2653
 * it begins with ZSTD_MAGIC_DICTIONARY, else as raw content) and ZSTD_dlm_byCopy.
2654
 * This prototype will generate compilation warnings.
2655
 */
2656
ZSTD_DEPRECATED("use ZSTD_CCtx_reset, see zstd.h for detailed instructions")
2657
ZSTDLIB_STATIC_API
2658
size_t ZSTD_initCStream_usingDict(ZSTD_CStream* zcs,
2659
                     const void* dict, size_t dictSize,
2660
                           int compressionLevel);
2661
2662
/*! ZSTD_initCStream_advanced() :
2663
 * This function is DEPRECATED, and is equivalent to:
2664
 *     ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only);
2665
 *     ZSTD_CCtx_setParams(zcs, params);
2666
 *     ZSTD_CCtx_setPledgedSrcSize(zcs, pledgedSrcSize);
2667
 *     ZSTD_CCtx_loadDictionary(zcs, dict, dictSize);
2668
 *
2669
 * dict is loaded with ZSTD_dct_auto and ZSTD_dlm_byCopy.
2670
 * pledgedSrcSize must be correct.
2671
 * If srcSize is not known at init time, use value ZSTD_CONTENTSIZE_UNKNOWN.
2672
 * This prototype will generate compilation warnings.
2673
 */
2674
ZSTD_DEPRECATED("use ZSTD_CCtx_reset, see zstd.h for detailed instructions")
2675
ZSTDLIB_STATIC_API
2676
size_t ZSTD_initCStream_advanced(ZSTD_CStream* zcs,
2677
                    const void* dict, size_t dictSize,
2678
                          ZSTD_parameters params,
2679
                          unsigned long long pledgedSrcSize);
2680
2681
/*! ZSTD_initCStream_usingCDict() :
2682
 * This function is DEPRECATED, and equivalent to:
2683
 *     ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only);
2684
 *     ZSTD_CCtx_refCDict(zcs, cdict);
2685
 *
2686
 * note : cdict will just be referenced, and must outlive compression session
2687
 * This prototype will generate compilation warnings.
2688
 */
2689
ZSTD_DEPRECATED("use ZSTD_CCtx_reset and ZSTD_CCtx_refCDict, see zstd.h for detailed instructions")
2690
ZSTDLIB_STATIC_API
2691
size_t ZSTD_initCStream_usingCDict(ZSTD_CStream* zcs, const ZSTD_CDict* cdict);
2692
2693
/*! ZSTD_initCStream_usingCDict_advanced() :
2694
 *   This function is DEPRECATED, and is equivalent to:
2695
 *     ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only);
2696
 *     ZSTD_CCtx_setFParams(zcs, fParams);
2697
 *     ZSTD_CCtx_setPledgedSrcSize(zcs, pledgedSrcSize);
2698
 *     ZSTD_CCtx_refCDict(zcs, cdict);
2699
 *
2700
 * same as ZSTD_initCStream_usingCDict(), with control over frame parameters.
2701
 * pledgedSrcSize must be correct. If srcSize is not known at init time, use
2702
 * value ZSTD_CONTENTSIZE_UNKNOWN.
2703
 * This prototype will generate compilation warnings.
2704
 */
2705
ZSTD_DEPRECATED("use ZSTD_CCtx_reset and ZSTD_CCtx_refCDict, see zstd.h for detailed instructions")
2706
ZSTDLIB_STATIC_API
2707
size_t ZSTD_initCStream_usingCDict_advanced(ZSTD_CStream* zcs,
2708
                               const ZSTD_CDict* cdict,
2709
                                     ZSTD_frameParameters fParams,
2710
                                     unsigned long long pledgedSrcSize);
2711
2712
/*! ZSTD_resetCStream() :
2713
 * This function is DEPRECATED, and is equivalent to:
2714
 *     ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only);
2715
 *     ZSTD_CCtx_setPledgedSrcSize(zcs, pledgedSrcSize);
2716
 * Note: ZSTD_resetCStream() interprets pledgedSrcSize == 0 as ZSTD_CONTENTSIZE_UNKNOWN, but
2717
 *       ZSTD_CCtx_setPledgedSrcSize() does not do the same, so ZSTD_CONTENTSIZE_UNKNOWN must be
2718
 *       explicitly specified.
2719
 *
2720
 *  start a new frame, using same parameters from previous frame.
2721
 *  This is typically useful to skip dictionary loading stage, since it will reuse it in-place.
2722
 *  Note that zcs must be init at least once before using ZSTD_resetCStream().
2723
 *  If pledgedSrcSize is not known at reset time, use macro ZSTD_CONTENTSIZE_UNKNOWN.
2724
 *  If pledgedSrcSize > 0, its value must be correct, as it will be written in header, and controlled at the end.
2725
 *  For the time being, pledgedSrcSize==0 is interpreted as "srcSize unknown" for compatibility with older programs,
2726
 *  but it will change to mean "empty" in future version, so use macro ZSTD_CONTENTSIZE_UNKNOWN instead.
2727
 * @return : 0, or an error code (which can be tested using ZSTD_isError())
2728
 *  This prototype will generate compilation warnings.
2729
 */
2730
ZSTD_DEPRECATED("use ZSTD_CCtx_reset, see zstd.h for detailed instructions")
2731
ZSTDLIB_STATIC_API
2732
size_t ZSTD_resetCStream(ZSTD_CStream* zcs, unsigned long long pledgedSrcSize);
2733
2734
2735
typedef struct {
2736
    unsigned long long ingested;   /* nb input bytes read and buffered */
2737
    unsigned long long consumed;   /* nb input bytes actually compressed */
2738
    unsigned long long produced;   /* nb of compressed bytes generated and buffered */
2739
    unsigned long long flushed;    /* nb of compressed bytes flushed : not provided; can be tracked from caller side */
2740
    unsigned currentJobID;         /* MT only : latest started job nb */
2741
    unsigned nbActiveWorkers;      /* MT only : nb of workers actively compressing at probe time */
2742
} ZSTD_frameProgression;
2743
2744
/* ZSTD_getFrameProgression() :
2745
 * tells how much data has been ingested (read from input)
2746
 * consumed (input actually compressed) and produced (output) for current frame.
2747
 * Note : (ingested - consumed) is amount of input data buffered internally, not yet compressed.
2748
 * Aggregates progression inside active worker threads.
2749
 */
2750
ZSTDLIB_STATIC_API ZSTD_frameProgression ZSTD_getFrameProgression(const ZSTD_CCtx* cctx);
2751
2752
/*! ZSTD_toFlushNow() :
2753
 *  Tell how many bytes are ready to be flushed immediately.
2754
 *  Useful for multithreading scenarios (nbWorkers >= 1).
2755
 *  Probe the oldest active job, defined as oldest job not yet entirely flushed,
2756
 *  and check its output buffer.
2757
 * @return : amount of data stored in oldest job and ready to be flushed immediately.
2758
 *  if @return == 0, it means either :
2759
 *  + there is no active job (could be checked with ZSTD_frameProgression()), or
2760
 *  + oldest job is still actively compressing data,
2761
 *    but everything it has produced has also been flushed so far,
2762
 *    therefore flush speed is limited by production speed of oldest job
2763
 *    irrespective of the speed of concurrent (and newer) jobs.
2764
 */
2765
ZSTDLIB_STATIC_API size_t ZSTD_toFlushNow(ZSTD_CCtx* cctx);
2766
2767
2768
/*=====   Advanced Streaming decompression functions  =====*/
2769
2770
/*!
2771
 * This function is deprecated, and is equivalent to:
2772
 *
2773
 *     ZSTD_DCtx_reset(zds, ZSTD_reset_session_only);
2774
 *     ZSTD_DCtx_loadDictionary(zds, dict, dictSize);
2775
 *
2776
 * note: no dictionary will be used if dict == NULL or dictSize < 8
2777
 */
2778
ZSTD_DEPRECATED("use ZSTD_DCtx_reset + ZSTD_DCtx_loadDictionary, see zstd.h for detailed instructions")
2779
ZSTDLIB_STATIC_API size_t ZSTD_initDStream_usingDict(ZSTD_DStream* zds, const void* dict, size_t dictSize);
2780
2781
/*!
2782
 * This function is deprecated, and is equivalent to:
2783
 *
2784
 *     ZSTD_DCtx_reset(zds, ZSTD_reset_session_only);
2785
 *     ZSTD_DCtx_refDDict(zds, ddict);
2786
 *
2787
 * note : ddict is referenced, it must outlive decompression session
2788
 */
2789
ZSTD_DEPRECATED("use ZSTD_DCtx_reset + ZSTD_DCtx_refDDict, see zstd.h for detailed instructions")
2790
ZSTDLIB_STATIC_API size_t ZSTD_initDStream_usingDDict(ZSTD_DStream* zds, const ZSTD_DDict* ddict);
2791
2792
/*!
2793
 * This function is deprecated, and is equivalent to:
2794
 *
2795
 *     ZSTD_DCtx_reset(zds, ZSTD_reset_session_only);
2796
 *
2797
 * reuse decompression parameters from previous init; saves dictionary loading
2798
 */
2799
ZSTD_DEPRECATED("use ZSTD_DCtx_reset, see zstd.h for detailed instructions")
2800
ZSTDLIB_STATIC_API size_t ZSTD_resetDStream(ZSTD_DStream* zds);
2801
2802
2803
/* ********************* BLOCK-LEVEL SEQUENCE PRODUCER API *********************
2804
 *
2805
 * *** OVERVIEW ***
2806
 * The Block-Level Sequence Producer API allows users to provide their own custom
2807
 * sequence producer which libzstd invokes to process each block. The produced list
2808
 * of sequences (literals and matches) is then post-processed by libzstd to produce
2809
 * valid compressed blocks.
2810
 *
2811
 * This block-level offload API is a more granular complement of the existing
2812
 * frame-level offload API compressSequences() (introduced in v1.5.1). It offers
2813
 * an easier migration story for applications already integrated with libzstd: the
2814
 * user application continues to invoke the same compression functions
2815
 * ZSTD_compress2() or ZSTD_compressStream2() as usual, and transparently benefits
2816
 * from the specific advantages of the external sequence producer. For example,
2817
 * the sequence producer could be tuned to take advantage of known characteristics
2818
 * of the input, to offer better speed / ratio, or could leverage hardware
2819
 * acceleration not available within libzstd itself.
2820
 *
2821
 * See contrib/externalSequenceProducer for an example program employing the
2822
 * Block-Level Sequence Producer API.
2823
 *
2824
 * *** USAGE ***
2825
 * The user is responsible for implementing a function of type
2826
 * ZSTD_sequenceProducer_F. For each block, zstd will pass the following
2827
 * arguments to the user-provided function:
2828
 *
2829
 *   - sequenceProducerState: a pointer to a user-managed state for the sequence
2830
 *     producer.
2831
 *
2832
 *   - outSeqs, outSeqsCapacity: an output buffer for the sequence producer.
2833
 *     outSeqsCapacity is guaranteed >= ZSTD_sequenceBound(srcSize). The memory
2834
 *     backing outSeqs is managed by the CCtx.
2835
 *
2836
 *   - src, srcSize: an input buffer for the sequence producer to parse.
2837
 *     srcSize is guaranteed to be <= ZSTD_BLOCKSIZE_MAX.
2838
 *
2839
 *   - dict, dictSize: a history buffer, which may be empty, which the sequence
2840
 *     producer may reference as it parses the src buffer. Currently, zstd will
2841
 *     always pass dictSize == 0 into external sequence producers, but this will
2842
 *     change in the future.
2843
 *
2844
 *   - compressionLevel: a signed integer representing the zstd compression level
2845
 *     set by the user for the current operation. The sequence producer may choose
2846
 *     to use this information to change its compression strategy and speed/ratio
2847
 *     tradeoff. Note: the compression level does not reflect zstd parameters set
2848
 *     through the advanced API.
2849
 *
2850
 *   - windowSize: a size_t representing the maximum allowed offset for external
2851
 *     sequences. Note that sequence offsets are sometimes allowed to exceed the
2852
 *     windowSize if a dictionary is present, see doc/zstd_compression_format.md
2853
 *     for details.
2854
 *
2855
 * The user-provided function shall return a size_t representing the number of
2856
 * sequences written to outSeqs. This return value will be treated as an error
2857
 * code if it is greater than outSeqsCapacity. The return value must be non-zero
2858
 * if srcSize is non-zero. The ZSTD_SEQUENCE_PRODUCER_ERROR macro is provided
2859
 * for convenience, but any value greater than outSeqsCapacity will be treated as
2860
 * an error code.
2861
 *
2862
 * If the user-provided function does not return an error code, the sequences
2863
 * written to outSeqs must be a valid parse of the src buffer. Data corruption may
2864
 * occur if the parse is not valid. A parse is defined to be valid if the
2865
 * following conditions hold:
2866
 *   - The sum of matchLengths and literalLengths must equal srcSize.
2867
 *   - All sequences in the parse, except for the final sequence, must have
2868
 *     matchLength >= ZSTD_MINMATCH_MIN. The final sequence must have
2869
 *     matchLength >= ZSTD_MINMATCH_MIN or matchLength == 0.
2870
 *   - All offsets must respect the windowSize parameter as specified in
2871
 *     doc/zstd_compression_format.md.
2872
 *   - If the final sequence has matchLength == 0, it must also have offset == 0.
2873
 *
2874
 * zstd will only validate these conditions (and fail compression if they do not
2875
 * hold) if the ZSTD_c_validateSequences cParam is enabled. Note that sequence
2876
 * validation has a performance cost.
2877
 *
2878
 * If the user-provided function returns an error, zstd will either fall back
2879
 * to an internal sequence producer or fail the compression operation. The user can
2880
 * choose between the two behaviors by setting the ZSTD_c_enableSeqProducerFallback
2881
 * cParam. Fallback compression will follow any other cParam settings, such as
2882
 * compression level, the same as in a normal compression operation.
2883
 *
2884
 * The user shall instruct zstd to use a particular ZSTD_sequenceProducer_F
2885
 * function by calling
2886
 *         ZSTD_registerSequenceProducer(cctx,
2887
 *                                       sequenceProducerState,
2888
 *                                       sequenceProducer)
2889
 * This setting will persist until the next parameter reset of the CCtx.
2890
 *
2891
 * The sequenceProducerState must be initialized by the user before calling
2892
 * ZSTD_registerSequenceProducer(). The user is responsible for destroying the
2893
 * sequenceProducerState.
2894
 *
2895
 * *** LIMITATIONS ***
2896
 * This API is compatible with all zstd compression APIs which respect advanced parameters.
2897
 * However, there are three limitations:
2898
 *
2899
 * First, the ZSTD_c_enableLongDistanceMatching cParam is not currently supported.
2900
 * COMPRESSION WILL FAIL if it is enabled and the user tries to compress with a block-level
2901
 * external sequence producer.
2902
 *   - Note that ZSTD_c_enableLongDistanceMatching is auto-enabled by default in some
2903
 *     cases (see its documentation for details). Users must explicitly set
2904
 *     ZSTD_c_enableLongDistanceMatching to ZSTD_ps_disable in such cases if an external
2905
 *     sequence producer is registered.
2906
 *   - As of this writing, ZSTD_c_enableLongDistanceMatching is disabled by default
2907
 *     whenever ZSTD_c_windowLog < 128MB, but that's subject to change. Users should
2908
 *     check the docs on ZSTD_c_enableLongDistanceMatching whenever the Block-Level Sequence
2909
 *     Producer API is used in conjunction with advanced settings (like ZSTD_c_windowLog).
2910
 *
2911
 * Second, history buffers are not currently supported. Concretely, zstd will always pass
2912
 * dictSize == 0 to the external sequence producer (for now). This has two implications:
2913
 *   - Dictionaries are not currently supported. Compression will *not* fail if the user
2914
 *     references a dictionary, but the dictionary won't have any effect.
2915
 *   - Stream history is not currently supported. All advanced compression APIs, including
2916
 *     streaming APIs, work with external sequence producers, but each block is treated as
2917
 *     an independent chunk without history from previous blocks.
2918
 *
2919
 * Third, multi-threading within a single compression is not currently supported. In other words,
2920
 * COMPRESSION WILL FAIL if ZSTD_c_nbWorkers > 0 and an external sequence producer is registered.
2921
 * Multi-threading across compressions is fine: simply create one CCtx per thread.
2922
 *
2923
 * Long-term, we plan to overcome all three limitations. There is no technical blocker to
2924
 * overcoming them. It is purely a question of engineering effort.
2925
 */
2926
2927
#define ZSTD_SEQUENCE_PRODUCER_ERROR ((size_t)(-1))
2928
2929
typedef size_t (*ZSTD_sequenceProducer_F) (
2930
  void* sequenceProducerState,
2931
  ZSTD_Sequence* outSeqs, size_t outSeqsCapacity,
2932
  const void* src, size_t srcSize,
2933
  const void* dict, size_t dictSize,
2934
  int compressionLevel,
2935
  size_t windowSize
2936
);
2937
2938
/*! ZSTD_registerSequenceProducer() :
2939
 * Instruct zstd to use a block-level external sequence producer function.
2940
 *
2941
 * The sequenceProducerState must be initialized by the caller, and the caller is
2942
 * responsible for managing its lifetime. This parameter is sticky across
2943
 * compressions. It will remain set until the user explicitly resets compression
2944
 * parameters.
2945
 *
2946
 * Sequence producer registration is considered to be an "advanced parameter",
2947
 * part of the "advanced API". This means it will only have an effect on compression
2948
 * APIs which respect advanced parameters, such as compress2() and compressStream2().
2949
 * Older compression APIs such as compressCCtx(), which predate the introduction of
2950
 * "advanced parameters", will ignore any external sequence producer setting.
2951
 *
2952
 * The sequence producer can be "cleared" by registering a NULL function pointer. This
2953
 * removes all limitations described above in the "LIMITATIONS" section of the API docs.
2954
 *
2955
 * The user is strongly encouraged to read the full API documentation (above) before
2956
 * calling this function. */
2957
ZSTDLIB_STATIC_API void
2958
ZSTD_registerSequenceProducer(
2959
  ZSTD_CCtx* cctx,
2960
  void* sequenceProducerState,
2961
  ZSTD_sequenceProducer_F sequenceProducer
2962
);
2963
2964
/*! ZSTD_CCtxParams_registerSequenceProducer() :
2965
 * Same as ZSTD_registerSequenceProducer(), but operates on ZSTD_CCtx_params.
2966
 * This is used for accurate size estimation with ZSTD_estimateCCtxSize_usingCCtxParams(),
2967
 * which is needed when creating a ZSTD_CCtx with ZSTD_initStaticCCtx().
2968
 *
2969
 * If you are using the external sequence producer API in a scenario where ZSTD_initStaticCCtx()
2970
 * is required, then this function is for you. Otherwise, you probably don't need it.
2971
 *
2972
 * See tests/zstreamtest.c for example usage. */
2973
ZSTDLIB_STATIC_API void
2974
ZSTD_CCtxParams_registerSequenceProducer(
2975
  ZSTD_CCtx_params* params,
2976
  void* sequenceProducerState,
2977
  ZSTD_sequenceProducer_F sequenceProducer
2978
);
2979
2980
2981
/*********************************************************************
2982
*  Buffer-less and synchronous inner streaming functions (DEPRECATED)
2983
*
2984
*  This API is deprecated, and will be removed in a future version.
2985
*  It allows streaming (de)compression with user allocated buffers.
2986
*  However, it is hard to use, and not as well tested as the rest of
2987
*  our API.
2988
*
2989
*  Please use the normal streaming API instead: ZSTD_compressStream2,
2990
*  and ZSTD_decompressStream.
2991
*  If there is functionality that you need, but it doesn't provide,
2992
*  please open an issue on our GitHub.
2993
********************************************************************* */
2994
2995
/**
2996
  Buffer-less streaming compression (synchronous mode)
2997
2998
  A ZSTD_CCtx object is required to track streaming operations.
2999
  Use ZSTD_createCCtx() / ZSTD_freeCCtx() to manage resource.
3000
  ZSTD_CCtx object can be reused multiple times within successive compression operations.
3001
3002
  Start by initializing a context.
3003
  Use ZSTD_compressBegin(), or ZSTD_compressBegin_usingDict() for dictionary compression.
3004
3005
  Then, consume your input using ZSTD_compressContinue().
3006
  There are some important considerations to keep in mind when using this advanced function :
3007
  - ZSTD_compressContinue() has no internal buffer. It uses externally provided buffers only.
3008
  - Interface is synchronous : input is consumed entirely and produces 1+ compressed blocks.
3009
  - Caller must ensure there is enough space in `dst` to store compressed data under worst case scenario.
3010
    Worst case evaluation is provided by ZSTD_compressBound().
3011
    ZSTD_compressContinue() doesn't guarantee recover after a failed compression.
3012
  - ZSTD_compressContinue() presumes prior input ***is still accessible and unmodified*** (up to maximum distance size, see WindowLog).
3013
    It remembers all previous contiguous blocks, plus one separated memory segment (which can itself consists of multiple contiguous blocks)
3014
  - ZSTD_compressContinue() detects that prior input has been overwritten when `src` buffer overlaps.
3015
    In which case, it will "discard" the relevant memory section from its history.
3016
3017
  Finish a frame with ZSTD_compressEnd(), which will write the last block(s) and optional checksum.
3018
  It's possible to use srcSize==0, in which case, it will write a final empty block to end the frame.
3019
  Without last block mark, frames are considered unfinished (hence corrupted) by compliant decoders.
3020
3021
  `ZSTD_CCtx` object can be reused (ZSTD_compressBegin()) to compress again.
3022
*/
3023
3024
/*=====   Buffer-less streaming compression functions  =====*/
3025
ZSTD_DEPRECATED("The buffer-less API is deprecated in favor of the normal streaming API. See docs.")
3026
ZSTDLIB_STATIC_API size_t ZSTD_compressBegin(ZSTD_CCtx* cctx, int compressionLevel);
3027
ZSTD_DEPRECATED("The buffer-less API is deprecated in favor of the normal streaming API. See docs.")
3028
ZSTDLIB_STATIC_API size_t ZSTD_compressBegin_usingDict(ZSTD_CCtx* cctx, const void* dict, size_t dictSize, int compressionLevel);
3029
ZSTD_DEPRECATED("The buffer-less API is deprecated in favor of the normal streaming API. See docs.")
3030
ZSTDLIB_STATIC_API size_t ZSTD_compressBegin_usingCDict(ZSTD_CCtx* cctx, const ZSTD_CDict* cdict); /**< note: fails if cdict==NULL */
3031
3032
ZSTD_DEPRECATED("This function will likely be removed in a future release. It is misleading and has very limited utility.")
3033
ZSTDLIB_STATIC_API
3034
size_t ZSTD_copyCCtx(ZSTD_CCtx* cctx, const ZSTD_CCtx* preparedCCtx, unsigned long long pledgedSrcSize); /**<  note: if pledgedSrcSize is not known, use ZSTD_CONTENTSIZE_UNKNOWN */
3035
3036
ZSTD_DEPRECATED("The buffer-less API is deprecated in favor of the normal streaming API. See docs.")
3037
ZSTDLIB_STATIC_API size_t ZSTD_compressContinue(ZSTD_CCtx* cctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize);
3038
ZSTD_DEPRECATED("The buffer-less API is deprecated in favor of the normal streaming API. See docs.")
3039
ZSTDLIB_STATIC_API size_t ZSTD_compressEnd(ZSTD_CCtx* cctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize);
3040
3041
/* The ZSTD_compressBegin_advanced() and ZSTD_compressBegin_usingCDict_advanced() are now DEPRECATED and will generate a compiler warning */
3042
ZSTD_DEPRECATED("use advanced API to access custom parameters")
3043
ZSTDLIB_STATIC_API
3044
size_t ZSTD_compressBegin_advanced(ZSTD_CCtx* cctx, const void* dict, size_t dictSize, ZSTD_parameters params, unsigned long long pledgedSrcSize); /**< pledgedSrcSize : If srcSize is not known at init time, use ZSTD_CONTENTSIZE_UNKNOWN */
3045
ZSTD_DEPRECATED("use advanced API to access custom parameters")
3046
ZSTDLIB_STATIC_API
3047
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 must be correct. If srcSize is not known, use macro ZSTD_CONTENTSIZE_UNKNOWN */
3048
/**
3049
  Buffer-less streaming decompression (synchronous mode)
3050
3051
  A ZSTD_DCtx object is required to track streaming operations.
3052
  Use ZSTD_createDCtx() / ZSTD_freeDCtx() to manage it.
3053
  A ZSTD_DCtx object can be reused multiple times.
3054
3055
  First typical operation is to retrieve frame parameters, using ZSTD_getFrameHeader().
3056
  Frame header is extracted from the beginning of compressed frame, so providing only the frame's beginning is enough.
3057
  Data fragment must be large enough to ensure successful decoding.
3058
 `ZSTD_frameHeaderSize_max` bytes is guaranteed to always be large enough.
3059
  result  : 0 : successful decoding, the `ZSTD_frameHeader` structure is correctly filled.
3060
           >0 : `srcSize` is too small, please provide at least result bytes on next attempt.
3061
           errorCode, which can be tested using ZSTD_isError().
3062
3063
  It fills a ZSTD_FrameHeader structure with important information to correctly decode the frame,
3064
  such as the dictionary ID, content size, or maximum back-reference distance (`windowSize`).
3065
  Note that these values could be wrong, either because of data corruption, or because a 3rd party deliberately spoofs false information.
3066
  As a consequence, check that values remain within valid application range.
3067
  For example, do not allocate memory blindly, check that `windowSize` is within expectation.
3068
  Each application can set its own limits, depending on local restrictions.
3069
  For extended interoperability, it is recommended to support `windowSize` of at least 8 MB.
3070
3071
  ZSTD_decompressContinue() needs previous data blocks during decompression, up to `windowSize` bytes.
3072
  ZSTD_decompressContinue() is very sensitive to contiguity,
3073
  if 2 blocks don't follow each other, make sure that either the compressor breaks contiguity at the same place,
3074
  or that previous contiguous segment is large enough to properly handle maximum back-reference distance.
3075
  There are multiple ways to guarantee this condition.
3076
3077
  The most memory efficient way is to use a round buffer of sufficient size.
3078
  Sufficient size is determined by invoking ZSTD_decodingBufferSize_min(),
3079
  which can return an error code if required value is too large for current system (in 32-bits mode).
3080
  In a round buffer methodology, ZSTD_decompressContinue() decompresses each block next to previous one,
3081
  up to the moment there is not enough room left in the buffer to guarantee decoding another full block,
3082
  which maximum size is provided in `ZSTD_frameHeader` structure, field `blockSizeMax`.
3083
  At which point, decoding can resume from the beginning of the buffer.
3084
  Note that already decoded data stored in the buffer should be flushed before being overwritten.
3085
3086
  There are alternatives possible, for example using two or more buffers of size `windowSize` each, though they consume more memory.
3087
3088
  Finally, if you control the compression process, you can also ignore all buffer size rules,
3089
  as long as the encoder and decoder progress in "lock-step",
3090
  aka use exactly the same buffer sizes, break contiguity at the same place, etc.
3091
3092
  Once buffers are setup, start decompression, with ZSTD_decompressBegin().
3093
  If decompression requires a dictionary, use ZSTD_decompressBegin_usingDict() or ZSTD_decompressBegin_usingDDict().
3094
3095
  Then use ZSTD_nextSrcSizeToDecompress() and ZSTD_decompressContinue() alternatively.
3096
  ZSTD_nextSrcSizeToDecompress() tells how many bytes to provide as 'srcSize' to ZSTD_decompressContinue().
3097
  ZSTD_decompressContinue() requires this _exact_ amount of bytes, or it will fail.
3098
3099
  result of ZSTD_decompressContinue() is the number of bytes regenerated within 'dst' (necessarily <= dstCapacity).
3100
  It can be zero : it just means ZSTD_decompressContinue() has decoded some metadata item.
3101
  It can also be an error code, which can be tested with ZSTD_isError().
3102
3103
  A frame is fully decoded when ZSTD_nextSrcSizeToDecompress() returns zero.
3104
  Context can then be reset to start a new decompression.
3105
3106
  Note : it's possible to know if next input to present is a header or a block, using ZSTD_nextInputType().
3107
  This information is not required to properly decode a frame.
3108
3109
  == Special case : skippable frames ==
3110
3111
  Skippable frames allow integration of user-defined data into a flow of concatenated frames.
3112
  Skippable frames will be ignored (skipped) by decompressor.
3113
  The format of skippable frames is as follows :
3114
  a) Skippable frame ID - 4 Bytes, Little endian format, any value from 0x184D2A50 to 0x184D2A5F
3115
  b) Frame Size - 4 Bytes, Little endian format, unsigned 32-bits
3116
  c) Frame Content - any content (User Data) of length equal to Frame Size
3117
  For skippable frames ZSTD_getFrameHeader() returns zfhPtr->frameType==ZSTD_skippableFrame.
3118
  For skippable frames ZSTD_decompressContinue() always returns 0 : it only skips the content.
3119
*/
3120
3121
/*=====   Buffer-less streaming decompression functions  =====*/
3122
3123
ZSTDLIB_STATIC_API size_t ZSTD_decodingBufferSize_min(unsigned long long windowSize, unsigned long long frameContentSize);  /**< when frame content size is not known, pass in frameContentSize == ZSTD_CONTENTSIZE_UNKNOWN */
3124
3125
ZSTDLIB_STATIC_API size_t ZSTD_decompressBegin(ZSTD_DCtx* dctx);
3126
ZSTDLIB_STATIC_API size_t ZSTD_decompressBegin_usingDict(ZSTD_DCtx* dctx, const void* dict, size_t dictSize);
3127
ZSTDLIB_STATIC_API size_t ZSTD_decompressBegin_usingDDict(ZSTD_DCtx* dctx, const ZSTD_DDict* ddict);
3128
3129
ZSTDLIB_STATIC_API size_t ZSTD_nextSrcSizeToDecompress(ZSTD_DCtx* dctx);
3130
ZSTDLIB_STATIC_API size_t ZSTD_decompressContinue(ZSTD_DCtx* dctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize);
3131
3132
/* misc */
3133
ZSTD_DEPRECATED("This function will likely be removed in the next minor release. It is misleading and has very limited utility.")
3134
ZSTDLIB_STATIC_API void   ZSTD_copyDCtx(ZSTD_DCtx* dctx, const ZSTD_DCtx* preparedDCtx);
3135
typedef enum { ZSTDnit_frameHeader, ZSTDnit_blockHeader, ZSTDnit_block, ZSTDnit_lastBlock, ZSTDnit_checksum, ZSTDnit_skippableFrame } ZSTD_nextInputType_e;
3136
ZSTDLIB_STATIC_API ZSTD_nextInputType_e ZSTD_nextInputType(ZSTD_DCtx* dctx);
3137
3138
3139
3140
/*! ZSTD_isDeterministicBuild() :
3141
 * Returns 1 if the library is built using standard compilation flags,
3142
 * and participates in determinism guarantees with other builds of the
3143
 * same version.
3144
 * If this function returns 0, it means the library was compiled with
3145
 * non-standard compilation flags that change the output of the
3146
 * compressor.
3147
 * This is mainly used for Zstd's determinism test suite, which is only
3148
 * run when this function returns 1.
3149
 */
3150
ZSTDLIB_API int ZSTD_isDeterministicBuild(void);
3151
3152
3153
/* ========================================= */
3154
/**       Block level API (DEPRECATED)       */
3155
/* ========================================= */
3156
3157
/*!
3158
3159
    This API is deprecated in favor of the regular compression API.
3160
    You can get the frame header down to 2 bytes by setting:
3161
      - ZSTD_c_format = ZSTD_f_zstd1_magicless
3162
      - ZSTD_c_contentSizeFlag = 0
3163
      - ZSTD_c_checksumFlag = 0
3164
      - ZSTD_c_dictIDFlag = 0
3165
3166
    This API is not as well tested as our normal API, so we recommend not using it.
3167
    We will be removing it in a future version. If the normal API doesn't provide
3168
    the functionality you need, please open a GitHub issue.
3169
3170
    Block functions produce and decode raw zstd blocks, without frame metadata.
3171
    Frame metadata cost is typically ~12 bytes, which can be non-negligible for very small blocks (< 100 bytes).
3172
    But users will have to take in charge needed metadata to regenerate data, such as compressed and content sizes.
3173
3174
    A few rules to respect :
3175
    - Compressing and decompressing require a context structure
3176
      + Use ZSTD_createCCtx() and ZSTD_createDCtx()
3177
    - It is necessary to init context before starting
3178
      + compression : any ZSTD_compressBegin*() variant, including with dictionary
3179
      + decompression : any ZSTD_decompressBegin*() variant, including with dictionary
3180
    - Block size is limited, it must be <= ZSTD_getBlockSize() <= ZSTD_BLOCKSIZE_MAX == 128 KB
3181
      + If input is larger than a block size, it's necessary to split input data into multiple blocks
3182
      + For inputs larger than a single block, consider using regular ZSTD_compress() instead.
3183
        Frame metadata is not that costly, and quickly becomes negligible as source size grows larger than a block.
3184
    - When a block is considered not compressible enough, ZSTD_compressBlock() result will be 0 (zero) !
3185
      ===> In which case, nothing is produced into `dst` !
3186
      + User __must__ test for such outcome and deal directly with uncompressed data
3187
      + A block cannot be declared incompressible if ZSTD_compressBlock() return value was != 0.
3188
        Doing so would mess up with statistics history, leading to potential data corruption.
3189
      + ZSTD_decompressBlock() _doesn't accept uncompressed data as input_ !!
3190
      + In case of multiple successive blocks, should some of them be uncompressed,
3191
        decoder must be informed of their existence in order to follow proper history.
3192
        Use ZSTD_insertBlock() for such a case.
3193
*/
3194
3195
/*=====   Raw zstd block functions  =====*/
3196
ZSTD_DEPRECATED("The block API is deprecated in favor of the normal compression API. See docs.")
3197
ZSTDLIB_STATIC_API size_t ZSTD_getBlockSize   (const ZSTD_CCtx* cctx);
3198
ZSTD_DEPRECATED("The block API is deprecated in favor of the normal compression API. See docs.")
3199
ZSTDLIB_STATIC_API size_t ZSTD_compressBlock  (ZSTD_CCtx* cctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize);
3200
ZSTD_DEPRECATED("The block API is deprecated in favor of the normal compression API. See docs.")
3201
ZSTDLIB_STATIC_API size_t ZSTD_decompressBlock(ZSTD_DCtx* dctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize);
3202
ZSTD_DEPRECATED("The block API is deprecated in favor of the normal compression API. See docs.")
3203
ZSTDLIB_STATIC_API size_t ZSTD_insertBlock    (ZSTD_DCtx* dctx, const void* blockStart, size_t blockSize);  /**< insert uncompressed block into `dctx` history. Useful for multi-blocks decompression. */
3204
3205
#if defined (__cplusplus)
3206
}
3207
#endif
3208
3209
#endif   /* ZSTD_H_ZSTD_STATIC_LINKING_ONLY */