1 #ifndef LIBRARIES_ZSTD_H
    2 #define LIBRARIES_ZSTD_H
    3 
    4 /*
    5 	zstd.library headers
    6 
    7 	Generated from the official Zstandard source code for the MorphOS SDK.
    8 	Please refer to SYS:Docs/Licenses/Zstandard for license information.
    9 */
   10 
   11 /*
   12  * Copyright (c) Meta Platforms, Inc. and affiliates.
   13  * All rights reserved.
   14  *
   15  * This source code is licensed under both the BSD-style license (found in the
   16  * LICENSE file in the root directory of this source tree) and the GPLv2 (found
   17  * in the COPYING file in the root directory of this source tree).
   18  * You may select, at your option, one of the above-listed licenses.
   19  */
   20 
   21 #ifndef ZSTD_H_235446
   22 #define ZSTD_H_235446
   23 
   24 
   25 /* ======   Dependencies   ======*/
   26 #include <stddef.h>   /* size_t */
   27 
   28 #if defined(ZSTD_STATIC_LINKING_ONLY) && !defined(ZSTD_H_ZSTD_STATIC_LINKING_ONLY)
   29 #include <limits.h>   /* INT_MAX */
   30 #endif /* ZSTD_STATIC_LINKING_ONLY */
   31 
   32 #if defined (__cplusplus)
   33 extern "C" {
   34 #endif
   35 
   36 /* =====   ZSTDLIB_API : control library symbols visibility   ===== */
   37 #ifndef ZSTDLIB_VISIBLE
   38    /* Backwards compatibility with old macro name */
   39 #  ifdef ZSTDLIB_VISIBILITY
   40 #    define ZSTDLIB_VISIBLE ZSTDLIB_VISIBILITY
   41 #  elif defined(__GNUC__) && (__GNUC__ >= 4) && !defined(__MINGW32__)
   42 #    define ZSTDLIB_VISIBLE __attribute__ ((visibility ("default")))
   43 #  else
   44 #    define ZSTDLIB_VISIBLE
   45 #  endif
   46 #endif
   47 
   48 #ifndef ZSTDLIB_HIDDEN
   49 #  if defined(__GNUC__) && (__GNUC__ >= 4) && !defined(__MINGW32__)
   50 #    define ZSTDLIB_HIDDEN __attribute__ ((visibility ("hidden")))
   51 #  else
   52 #    define ZSTDLIB_HIDDEN
   53 #  endif
   54 #endif
   55 
   56 #if defined(ZSTD_DLL_EXPORT) && (ZSTD_DLL_EXPORT==1)
   57 #  define ZSTDLIB_API __declspec(dllexport) ZSTDLIB_VISIBLE
   58 #elif defined(ZSTD_DLL_IMPORT) && (ZSTD_DLL_IMPORT==1)
   59 #  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.*/
   60 #else
   61 #  define ZSTDLIB_API ZSTDLIB_VISIBLE
   62 #endif
   63 
   64 /* Deprecation warnings :
   65  * Should these warnings be a problem, it is generally possible to disable them,
   66  * typically with -Wno-deprecated-declarations for gcc or _CRT_SECURE_NO_WARNINGS in Visual.
   67  * Otherwise, it's also possible to define ZSTD_DISABLE_DEPRECATE_WARNINGS.
   68  */
   69 #ifdef ZSTD_DISABLE_DEPRECATE_WARNINGS
   70 #  define ZSTD_DEPRECATED(message) /* disable deprecation warnings */
   71 #else
   72 #  if defined (__cplusplus) && (__cplusplus >= 201402) /* C++14 or greater */
   73 #    define ZSTD_DEPRECATED(message) [[deprecated(message)]]
   74 #  elif (defined(GNUC) && (GNUC > 4 || (GNUC == 4 && GNUC_MINOR >= 5))) || defined(__clang__) || defined(__IAR_SYSTEMS_ICC__)
   75 #    define ZSTD_DEPRECATED(message) __attribute__((deprecated(message)))
   76 #  elif defined(__GNUC__) && (__GNUC__ >= 3)
   77 #    define ZSTD_DEPRECATED(message) __attribute__((deprecated))
   78 #  elif defined(_MSC_VER)
   79 #    define ZSTD_DEPRECATED(message) __declspec(deprecated(message))
   80 #  else
   81 #    pragma message("WARNING: You need to implement ZSTD_DEPRECATED for this compiler")
   82 #    define ZSTD_DEPRECATED(message)
   83 #  endif
   84 #endif /* ZSTD_DISABLE_DEPRECATE_WARNINGS */
   85 
   86 
   87 /*******************************************************************************
   88   Introduction
   89 
   90   zstd, short for Zstandard, is a fast lossless compression algorithm, targeting
   91   real-time compression scenarios at zlib-level and better compression ratios.
   92   The zstd compression library provides in-memory compression and decompression
   93   functions.
   94 
   95   The library supports regular compression levels from 1 up to ZSTD_maxCLevel(),
   96   which is currently 22. Levels >= 20, labeled `--ultra`, should be used with
   97   caution, as they require more memory. The library also offers negative
   98   compression levels, which extend the range of speed vs. ratio preferences.
   99   The lower the level, the faster the speed (at the cost of compression).
  100 
  101   Compression can be done in:
  102     - a single step (described as Simple API)
  103     - a single step, reusing a context (described as Explicit context)
  104     - unbounded multiple steps (described as Streaming compression)
  105 
  106   The compression ratio achievable on small data can be highly improved using
  107   a dictionary. Dictionary compression can be performed in:
  108     - a single step (described as Simple dictionary API)
  109     - a single step, reusing a dictionary (described as Bulk-processing
  110       dictionary API)
  111 
  112   Advanced experimental functions can be accessed using
  113   `#define ZSTD_STATIC_LINKING_ONLY` before including zstd.h.
  114 
  115   Advanced experimental APIs should never be used with a dynamically-linked
  116   library. They are not "stable"; their definitions or signatures may change in
  117   the future. Only static linking is allowed.
  118 *******************************************************************************/
  119 
  120 /*------   Version   ------*/
  121 #define ZSTD_VERSION_MAJOR    1
  122 #define ZSTD_VERSION_MINOR    5
  123 #define ZSTD_VERSION_RELEASE  7
  124 #define ZSTD_VERSION_NUMBER  (ZSTD_VERSION_MAJOR *100*100 + ZSTD_VERSION_MINOR *100 + ZSTD_VERSION_RELEASE)
  125 
  126 /*! ZSTD_versionNumber() :
  127  *  Return runtime library version, the value is (MAJOR*100*100 + MINOR*100 + RELEASE). */
  128 /* ZSTDLIB_API unsigned ZSTD_versionNumber(void); */
  129 
  130 #define ZSTD_LIB_VERSION ZSTD_VERSION_MAJOR.ZSTD_VERSION_MINOR.ZSTD_VERSION_RELEASE
  131 #define ZSTD_QUOTE(str) #str
  132 #define ZSTD_EXPAND_AND_QUOTE(str) ZSTD_QUOTE(str)
  133 #define ZSTD_VERSION_STRING ZSTD_EXPAND_AND_QUOTE(ZSTD_LIB_VERSION)
  134 
  135 /*! ZSTD_versionString() :
  136  *  Return runtime library version, like "1.4.5". Requires v1.3.0+. */
  137 /* ZSTDLIB_API const char* ZSTD_versionString(void); */
  138 
  139 /* *************************************
  140  *  Default constant
  141  ***************************************/
  142 #ifndef ZSTD_CLEVEL_DEFAULT
  143 #  define ZSTD_CLEVEL_DEFAULT 3
  144 #endif
  145 
  146 /* *************************************
  147  *  Constants
  148  ***************************************/
  149 
  150 /* All magic numbers are supposed read/written to/from files/memory using little-endian convention */
  151 #define ZSTD_MAGICNUMBER            0xFD2FB528    /* valid since v0.8.0 */
  152 #define ZSTD_MAGIC_DICTIONARY       0xEC30A437    /* valid since v0.7.0 */
  153 #define ZSTD_MAGIC_SKIPPABLE_START  0x184D2A50    /* all 16 values, from 0x184D2A50 to 0x184D2A5F, signal the beginning of a skippable frame */
  154 #define ZSTD_MAGIC_SKIPPABLE_MASK   0xFFFFFFF0
  155 
  156 #define ZSTD_BLOCKSIZELOG_MAX  17
  157 #define ZSTD_BLOCKSIZE_MAX     (1<<ZSTD_BLOCKSIZELOG_MAX)
  158 
  159 
  160 /***************************************
  161 *  Simple Core API
  162 ***************************************/
  163 /*! ZSTD_compress() :
  164  *  Compresses `src` content as a single zstd compressed frame into already allocated `dst`.
  165  *  NOTE: Providing `dstCapacity >= ZSTD_compressBound(srcSize)` guarantees that zstd will have
  166  *        enough space to successfully compress the data.
  167  *  @return : compressed size written into `dst` (<= `dstCapacity),
  168  *            or an error code if it fails (which can be tested using ZSTD_isError()). */
  169 /* ZSTDLIB_API size_t ZSTD_compress( void* dst, size_t dstCapacity,
  170                             const void* src, size_t srcSize,
  171                                   int compressionLevel); */
  172 
  173 /*! ZSTD_decompress() :
  174  * `compressedSize` : must be the _exact_ size of some number of compressed and/or skippable frames.
  175  *  Multiple compressed frames can be decompressed at once with this method.
  176  *  The result will be the concatenation of all decompressed frames, back to back.
  177  * `dstCapacity` is an upper bound of originalSize to regenerate.
  178  *  First frame's decompressed size can be extracted using ZSTD_getFrameContentSize().
  179  *  If maximum upper bound isn't known, prefer using streaming mode to decompress data.
  180  * @return : the number of bytes decompressed into `dst` (<= `dstCapacity`),
  181  *           or an errorCode if it fails (which can be tested using ZSTD_isError()). */
  182 /* ZSTDLIB_API size_t ZSTD_decompress( void* dst, size_t dstCapacity,
  183                               const void* src, size_t compressedSize); */
  184 
  185 
  186 /*======  Decompression helper functions  ======*/
  187 
  188 /*! ZSTD_getFrameContentSize() : requires v1.3.0+
  189  * `src` should point to the start of a ZSTD encoded frame.
  190  * `srcSize` must be at least as large as the frame header.
  191  *           hint : any size >= `ZSTD_frameHeaderSize_max` is large enough.
  192  * @return : - decompressed size of `src` frame content, if known
  193  *           - ZSTD_CONTENTSIZE_UNKNOWN if the size cannot be determined
  194  *           - ZSTD_CONTENTSIZE_ERROR if an error occurred (e.g. invalid magic number, srcSize too small)
  195  *  note 1 : a 0 return value means the frame is valid but "empty".
  196  *           When invoking this method on a skippable frame, it will return 0.
  197  *  note 2 : decompressed size is an optional field, it may not be present (typically in streaming mode).
  198  *           When `return==ZSTD_CONTENTSIZE_UNKNOWN`, data to decompress could be any size.
  199  *           In which case, it's necessary to use streaming mode to decompress data.
  200  *           Optionally, application can rely on some implicit limit,
  201  *           as ZSTD_decompress() only needs an upper bound of decompressed size.
  202  *           (For example, data could be necessarily cut into blocks <= 16 KB).
  203  *  note 3 : decompressed size is always present when compression is completed using single-pass functions,
  204  *           such as ZSTD_compress(), ZSTD_compressCCtx() ZSTD_compress_usingDict() or ZSTD_compress_usingCDict().
  205  *  note 4 : decompressed size can be very large (64-bits value),
  206  *           potentially larger than what local system can handle as a single memory segment.
  207  *           In which case, it's necessary to use streaming mode to decompress data.
  208  *  note 5 : If source is untrusted, decompressed size could be wrong or intentionally modified.
  209  *           Always ensure return value fits within application's authorized limits.
  210  *           Each application can set its own limits.
  211  *  note 6 : This function replaces ZSTD_getDecompressedSize() */
  212 #define ZSTD_CONTENTSIZE_UNKNOWN (0ULL - 1)
  213 #define ZSTD_CONTENTSIZE_ERROR   (0ULL - 2)
  214 /* ZSTDLIB_API unsigned long long ZSTD_getFrameContentSize(const void *src, size_t srcSize); */
  215 
  216 /*! ZSTD_getDecompressedSize() (obsolete):
  217  *  This function is now obsolete, in favor of ZSTD_getFrameContentSize().
  218  *  Both functions work the same way, but ZSTD_getDecompressedSize() blends
  219  *  "empty", "unknown" and "error" results to the same return value (0),
  220  *  while ZSTD_getFrameContentSize() gives them separate return values.
  221  * @return : decompressed size of `src` frame content _if known and not empty_, 0 otherwise. *
  222 /* ZSTD_DEPRECATED("Replaced by ZSTD_getFrameContentSize") */
  223 /* ZSTDLIB_API unsigned long long ZSTD_getDecompressedSize(const void* src, size_t srcSize); */
  224 
  225 /*! ZSTD_findFrameCompressedSize() : Requires v1.4.0+
  226  * `src` should point to the start of a ZSTD frame or skippable frame.
  227  * `srcSize` must be >= first frame size
  228  * @return : the compressed size of the first frame starting at `src`,
  229  *           suitable to pass as `srcSize` to `ZSTD_decompress` or similar,
  230  *           or an error code if input is invalid
  231  *  Note 1: this method is called _find*() because it's not enough to read the header,
  232  *          it may have to scan through the frame's content, to reach its end.
  233  *  Note 2: this method also works with Skippable Frames. In which case,
  234  *          it returns the size of the complete skippable frame,
  235  *          which is always equal to its content size + 8 bytes for headers. */
  236 /* ZSTDLIB_API size_t ZSTD_findFrameCompressedSize(const void* src, size_t srcSize); */
  237 
  238 
  239 /*======  Compression helper functions  ======*/
  240 
  241 /*! ZSTD_compressBound() :
  242  * maximum compressed size in worst case single-pass scenario.
  243  * When invoking `ZSTD_compress()`, or any other one-pass compression function,
  244  * it's recommended to provide @dstCapacity >= ZSTD_compressBound(srcSize)
  245  * as it eliminates one potential failure scenario,
  246  * aka not enough room in dst buffer to write the compressed frame.
  247  * Note : ZSTD_compressBound() itself can fail, if @srcSize >= ZSTD_MAX_INPUT_SIZE .
  248  *        In which case, ZSTD_compressBound() will return an error code
  249  *        which can be tested using ZSTD_isError().
  250  *
  251  * ZSTD_COMPRESSBOUND() :
  252  * same as ZSTD_compressBound(), but as a macro.
  253  * It can be used to produce constants, which can be useful for static allocation,
  254  * for example to size a static array on stack.
  255  * Will produce constant value 0 if srcSize is too large.
  256  */
  257 #define ZSTD_MAX_INPUT_SIZE ((sizeof(size_t)==8) ? 0xFF00FF00FF00FF00ULL : 0xFF00FF00U)
  258 #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 */
  259 /* ZSTDLIB_API size_t ZSTD_compressBound(size_t srcSize); */ /*!< maximum compressed size in worst case single-pass scenario */
  260 
  261 
  262 /*======  Error helper functions  ======*/
  263 /* ZSTD_isError() :
  264  * Most ZSTD_* functions returning a size_t value can be tested for error,
  265  * using ZSTD_isError().
  266  * @return 1 if error, 0 otherwise
  267  */
  268 /* ZSTDLIB_API unsigned     ZSTD_isError(size_t result); */      /*!< tells if a `size_t` function result is an error code */
  269 /* ZSTDLIB_API ZSTD_ErrorCode ZSTD_getErrorCode(size_t functionResult); */ /* convert a result into an error code, which can be compared to error enum list */
  270 /* ZSTDLIB_API const char*  ZSTD_getErrorName(size_t result); */ /*!< provides readable string from a function result */
  271 /* ZSTDLIB_API int          ZSTD_minCLevel(void); */             /*!< minimum negative compression level allowed, requires v1.4.0+ */
  272 /* ZSTDLIB_API int          ZSTD_maxCLevel(void); */             /*!< maximum compression level available */
  273 /* ZSTDLIB_API int          ZSTD_defaultCLevel(void); */         /*!< default compression level, specified by ZSTD_CLEVEL_DEFAULT, requires v1.5.0+ */
  274 
  275 
  276 /***************************************
  277 *  Explicit context
  278 ***************************************/
  279 /*= Compression context
  280  *  When compressing many times,
  281  *  it is recommended to allocate a compression context just once,
  282  *  and reuse it for each successive compression operation.
  283  *  This will make the workload easier for system's memory.
  284  *  Note : re-using context is just a speed / resource optimization.
  285  *         It doesn't change the compression ratio, which remains identical.
  286  *  Note 2: For parallel execution in multi-threaded environments,
  287  *         use one different context per thread .
  288  */
  289 typedef struct ZSTD_CCtx_s ZSTD_CCtx;
  290 /* ZSTDLIB_API ZSTD_CCtx* ZSTD_createCCtx(void); */
  291 /* ZSTDLIB_API size_t     ZSTD_freeCCtx(ZSTD_CCtx* cctx); */  /* compatible with NULL pointer */
  292 
  293 /*! ZSTD_compressCCtx() :
  294  *  Same as ZSTD_compress(), using an explicit ZSTD_CCtx.
  295  *  Important : in order to mirror `ZSTD_compress()` behavior,
  296  *  this function compresses at the requested compression level,
  297  *  __ignoring any other advanced parameter__ .
  298  *  If any advanced parameter was set using the advanced API,
  299  *  they will all be reset. Only @compressionLevel remains.
  300  */
  301 /* ZSTDLIB_API size_t ZSTD_compressCCtx(ZSTD_CCtx* cctx,
  302                                      void* dst, size_t dstCapacity,
  303                                const void* src, size_t srcSize,
  304                                      int compressionLevel); */
  305 
  306 /*= Decompression context
  307  *  When decompressing many times,
  308  *  it is recommended to allocate a context only once,
  309  *  and reuse it for each successive compression operation.
  310  *  This will make workload friendlier for system's memory.
  311  *  Use one context per thread for parallel execution. */
  312 typedef struct ZSTD_DCtx_s ZSTD_DCtx;
  313 /* ZSTDLIB_API ZSTD_DCtx* ZSTD_createDCtx(void); */
  314 /* ZSTDLIB_API size_t     ZSTD_freeDCtx(ZSTD_DCtx* dctx); */  /* accept NULL pointer */
  315 
  316 /*! ZSTD_decompressDCtx() :
  317  *  Same as ZSTD_decompress(),
  318  *  requires an allocated ZSTD_DCtx.
  319  *  Compatible with sticky parameters (see below).
  320  */
  321 /* ZSTDLIB_API size_t ZSTD_decompressDCtx(ZSTD_DCtx* dctx,
  322                                        void* dst, size_t dstCapacity,
  323                                  const void* src, size_t srcSize); */
  324 
  325 
  326 /*********************************************
  327 *  Advanced compression API (Requires v1.4.0+)
  328 **********************************************/
  329 
  330 /* API design :
  331  *   Parameters are pushed one by one into an existing context,
  332  *   using ZSTD_CCtx_set*() functions.
  333  *   Pushed parameters are sticky : they are valid for next compressed frame, and any subsequent frame.
  334  *   "sticky" parameters are applicable to `ZSTD_compress2()` and `ZSTD_compressStream*()` !
  335  *   __They do not apply to one-shot variants such as ZSTD_compressCCtx()__ .
  336  *
  337  *   It's possible to reset all parameters to "default" using ZSTD_CCtx_reset().
  338  *
  339  *   This API supersedes all other "advanced" API entry points in the experimental section.
  340  *   In the future, we expect to remove API entry points from experimental which are redundant with this API.
  341  */
  342 
  343 
  344 /* Compression strategies, listed from fastest to strongest */
  345 typedef enum { ZSTD_fast=1,
  346                ZSTD_dfast=2,
  347                ZSTD_greedy=3,
  348                ZSTD_lazy=4,
  349                ZSTD_lazy2=5,
  350                ZSTD_btlazy2=6,
  351                ZSTD_btopt=7,
  352                ZSTD_btultra=8,
  353                ZSTD_btultra2=9
  354                /* note : new strategies _might_ be added in the future.
  355                          Only the order (from fast to strong) is guaranteed */
  356 } ZSTD_strategy;
  357 
  358 typedef enum {
  359 
  360     /* compression parameters
  361      * Note: When compressing with a ZSTD_CDict these parameters are superseded
  362      * by the parameters used to construct the ZSTD_CDict.
  363      * See ZSTD_CCtx_refCDict() for more info (superseded-by-cdict). */
  364     ZSTD_c_compressionLevel=100, /* Set compression parameters according to pre-defined cLevel table.
  365                               * Note that exact compression parameters are dynamically determined,
  366                               * depending on both compression level and srcSize (when known).
  367                               * Default level is ZSTD_CLEVEL_DEFAULT==3.
  368                               * Special: value 0 means default, which is controlled by ZSTD_CLEVEL_DEFAULT.
  369                               * Note 1 : it's possible to pass a negative compression level.
  370                               * Note 2 : setting a level does not automatically set all other compression parameters
  371                               *   to default. Setting this will however eventually dynamically impact the compression
  372                               *   parameters which have not been manually set. The manually set
  373                               *   ones will 'stick'. */
  374     /* Advanced compression parameters :
  375      * It's possible to pin down compression parameters to some specific values.
  376      * In which case, these values are no longer dynamically selected by the compressor */
  377     ZSTD_c_windowLog=101,    /* Maximum allowed back-reference distance, expressed as power of 2.
  378                               * This will set a memory budget for streaming decompression,
  379                               * with larger values requiring more memory
  380                               * and typically compressing more.
  381                               * Must be clamped between ZSTD_WINDOWLOG_MIN and ZSTD_WINDOWLOG_MAX.
  382                               * Special: value 0 means "use default windowLog".
  383                               * Note: Using a windowLog greater than ZSTD_WINDOWLOG_LIMIT_DEFAULT
  384                               *       requires explicitly allowing such size at streaming decompression stage. */
  385     ZSTD_c_hashLog=102,      /* Size of the initial probe table, as a power of 2.
  386                               * Resulting memory usage is (1 << (hashLog+2)).
  387                               * Must be clamped between ZSTD_HASHLOG_MIN and ZSTD_HASHLOG_MAX.
  388                               * Larger tables improve compression ratio of strategies <= dFast,
  389                               * and improve speed of strategies > dFast.
  390                               * Special: value 0 means "use default hashLog". */
  391     ZSTD_c_chainLog=103,     /* Size of the multi-probe search table, as a power of 2.
  392                               * Resulting memory usage is (1 << (chainLog+2)).
  393                               * Must be clamped between ZSTD_CHAINLOG_MIN and ZSTD_CHAINLOG_MAX.
  394                               * Larger tables result in better and slower compression.
  395                               * This parameter is useless for "fast" strategy.
  396                               * It's still useful when using "dfast" strategy,
  397                               * in which case it defines a secondary probe table.
  398                               * Special: value 0 means "use default chainLog". */
  399     ZSTD_c_searchLog=104,    /* Number of search attempts, as a power of 2.
  400                               * More attempts result in better and slower compression.
  401                               * This parameter is useless for "fast" and "dFast" strategies.
  402                               * Special: value 0 means "use default searchLog". */
  403     ZSTD_c_minMatch=105,     /* Minimum size of searched matches.
  404                               * Note that Zstandard can still find matches of smaller size,
  405                               * it just tweaks its search algorithm to look for this size and larger.
  406                               * Larger values increase compression and decompression speed, but decrease ratio.
  407                               * Must be clamped between ZSTD_MINMATCH_MIN and ZSTD_MINMATCH_MAX.
  408                               * Note that currently, for all strategies < btopt, effective minimum is 4.
  409                               *                    , for all strategies > fast, effective maximum is 6.
  410                               * Special: value 0 means "use default minMatchLength". */
  411     ZSTD_c_targetLength=106, /* Impact of this field depends on strategy.
  412                               * For strategies btopt, btultra & btultra2:
  413                               *     Length of Match considered "good enough" to stop search.
  414                               *     Larger values make compression stronger, and slower.
  415                               * For strategy fast:
  416                               *     Distance between match sampling.
  417                               *     Larger values make compression faster, and weaker.
  418                               * Special: value 0 means "use default targetLength". */
  419     ZSTD_c_strategy=107,     /* See ZSTD_strategy enum definition.
  420                               * The higher the value of selected strategy, the more complex it is,
  421                               * resulting in stronger and slower compression.
  422                               * Special: value 0 means "use default strategy". */
  423 
  424     ZSTD_c_targetCBlockSize=130, /* v1.5.6+
  425                                   * Attempts to fit compressed block size into approximately targetCBlockSize.
  426                                   * Bound by ZSTD_TARGETCBLOCKSIZE_MIN and ZSTD_TARGETCBLOCKSIZE_MAX.
  427                                   * Note that it's not a guarantee, just a convergence target (default:0).
  428                                   * No target when targetCBlockSize == 0.
  429                                   * This is helpful in low bandwidth streaming environments to improve end-to-end latency,
  430                                   * when a client can make use of partial documents (a prominent example being Chrome).
  431                                   * Note: this parameter is stable since v1.5.6.
  432                                   * It was present as an experimental parameter in earlier versions,
  433                                   * but it's not recommended using it with earlier library versions
  434                                   * due to massive performance regressions.
  435                                   */
  436     /* LDM mode parameters */
  437     ZSTD_c_enableLongDistanceMatching=160, /* Enable long distance matching.
  438                                      * This parameter is designed to improve compression ratio
  439                                      * for large inputs, by finding large matches at long distance.
  440                                      * It increases memory usage and window size.
  441                                      * Note: enabling this parameter increases default ZSTD_c_windowLog to 128 MB
  442                                      * except when expressly set to a different value.
  443                                      * Note: will be enabled by default if ZSTD_c_windowLog >= 128 MB and
  444                                      * compression strategy >= ZSTD_btopt (== compression level 16+) */
  445     ZSTD_c_ldmHashLog=161,   /* Size of the table for long distance matching, as a power of 2.
  446                               * Larger values increase memory usage and compression ratio,
  447                               * but decrease compression speed.
  448                               * Must be clamped between ZSTD_HASHLOG_MIN and ZSTD_HASHLOG_MAX
  449                               * default: windowlog - 7.
  450                               * Special: value 0 means "automatically determine hashlog". */
  451     ZSTD_c_ldmMinMatch=162,  /* Minimum match size for long distance matcher.
  452                               * Larger/too small values usually decrease compression ratio.
  453                               * Must be clamped between ZSTD_LDM_MINMATCH_MIN and ZSTD_LDM_MINMATCH_MAX.
  454                               * Special: value 0 means "use default value" (default: 64). */
  455     ZSTD_c_ldmBucketSizeLog=163, /* Log size of each bucket in the LDM hash table for collision resolution.
  456                               * Larger values improve collision resolution but decrease compression speed.
  457                               * The maximum value is ZSTD_LDM_BUCKETSIZELOG_MAX.
  458                               * Special: value 0 means "use default value" (default: 3). */
  459     ZSTD_c_ldmHashRateLog=164, /* Frequency of inserting/looking up entries into the LDM hash table.
  460                               * Must be clamped between 0 and (ZSTD_WINDOWLOG_MAX - ZSTD_HASHLOG_MIN).
  461                               * Default is MAX(0, (windowLog - ldmHashLog)), optimizing hash table usage.
  462                               * Larger values improve compression speed.
  463                               * Deviating far from default value will likely result in a compression ratio decrease.
  464                               * Special: value 0 means "automatically determine hashRateLog". */
  465 
  466     /* frame parameters */
  467     ZSTD_c_contentSizeFlag=200, /* Content size will be written into frame header _whenever known_ (default:1)
  468                               * Content size must be known at the beginning of compression.
  469                               * This is automatically the case when using ZSTD_compress2(),
  470                               * For streaming scenarios, content size must be provided with ZSTD_CCtx_setPledgedSrcSize() */
  471     ZSTD_c_checksumFlag=201, /* A 32-bits checksum of content is written at end of frame (default:0) */
  472     ZSTD_c_dictIDFlag=202,   /* When applicable, dictionary's ID is written into frame header (default:1) */
  473 
  474     /* multi-threading parameters */
  475     /* These parameters are only active if multi-threading is enabled (compiled with build macro ZSTD_MULTITHREAD).
  476      * Otherwise, trying to set any other value than default (0) will be a no-op and return an error.
  477      * In a situation where it's unknown if the linked library supports multi-threading or not,
  478      * setting ZSTD_c_nbWorkers to any value >= 1 and consulting the return value provides a quick way to check this property.
  479      */
  480     ZSTD_c_nbWorkers=400,    /* Select how many threads will be spawned to compress in parallel.
  481                               * When nbWorkers >= 1, triggers asynchronous mode when invoking ZSTD_compressStream*() :
  482                               * ZSTD_compressStream*() consumes input and flush output if possible, but immediately gives back control to caller,
  483                               * while compression is performed in parallel, within worker thread(s).
  484                               * (note : a strong exception to this rule is when first invocation of ZSTD_compressStream2() sets ZSTD_e_end :
  485                               *  in which case, ZSTD_compressStream2() delegates to ZSTD_compress2(), which is always a blocking call).
  486                               * More workers improve speed, but also increase memory usage.
  487                               * Default value is `0`, aka "single-threaded mode" : no worker is spawned,
  488                               * compression is performed inside Caller's thread, and all invocations are blocking */
  489     ZSTD_c_jobSize=401,      /* Size of a compression job. This value is enforced only when nbWorkers >= 1.
  490                               * Each compression job is completed in parallel, so this value can indirectly impact the nb of active threads.
  491                               * 0 means default, which is dynamically determined based on compression parameters.
  492                               * Job size must be a minimum of overlap size, or ZSTDMT_JOBSIZE_MIN (= 512 KB), whichever is largest.
  493                               * The minimum size is automatically and transparently enforced. */
  494     ZSTD_c_overlapLog=402,   /* Control the overlap size, as a fraction of window size.
  495                               * The overlap size is an amount of data reloaded from previous job at the beginning of a new job.
  496                               * It helps preserve compression ratio, while each job is compressed in parallel.
  497                               * This value is enforced only when nbWorkers >= 1.
  498                               * Larger values increase compression ratio, but decrease speed.
  499                               * Possible values range from 0 to 9 :
  500                               * - 0 means "default" : value will be determined by the library, depending on strategy
  501                               * - 1 means "no overlap"
  502                               * - 9 means "full overlap", using a full window size.
  503                               * Each intermediate rank increases/decreases load size by a factor 2 :
  504                               * 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
  505                               * default value varies between 6 and 9, depending on strategy */
  506 
  507     /* note : additional experimental parameters are also available
  508      * within the experimental section of the API.
  509      * At the time of this writing, they include :
  510      * ZSTD_c_rsyncable
  511      * ZSTD_c_format
  512      * ZSTD_c_forceMaxWindow
  513      * ZSTD_c_forceAttachDict
  514      * ZSTD_c_literalCompressionMode
  515      * ZSTD_c_srcSizeHint
  516      * ZSTD_c_enableDedicatedDictSearch
  517      * ZSTD_c_stableInBuffer
  518      * ZSTD_c_stableOutBuffer
  519      * ZSTD_c_blockDelimiters
  520      * ZSTD_c_validateSequences
  521      * ZSTD_c_blockSplitterLevel
  522      * ZSTD_c_splitAfterSequences
  523      * ZSTD_c_useRowMatchFinder
  524      * ZSTD_c_prefetchCDictTables
  525      * ZSTD_c_enableSeqProducerFallback
  526      * ZSTD_c_maxBlockSize
  527      * Because they are not stable, it's necessary to define ZSTD_STATIC_LINKING_ONLY to access them.
  528      * note : never ever use experimentalParam? names directly;
  529      *        also, the enums values themselves are unstable and can still change.
  530      */
  531      ZSTD_c_experimentalParam1=500,
  532      ZSTD_c_experimentalParam2=10,
  533      ZSTD_c_experimentalParam3=1000,
  534      ZSTD_c_experimentalParam4=1001,
  535      ZSTD_c_experimentalParam5=1002,
  536      /* was ZSTD_c_experimentalParam6=1003; is now ZSTD_c_targetCBlockSize */
  537      ZSTD_c_experimentalParam7=1004,
  538      ZSTD_c_experimentalParam8=1005,
  539      ZSTD_c_experimentalParam9=1006,
  540      ZSTD_c_experimentalParam10=1007,
  541      ZSTD_c_experimentalParam11=1008,
  542      ZSTD_c_experimentalParam12=1009,
  543      ZSTD_c_experimentalParam13=1010,
  544      ZSTD_c_experimentalParam14=1011,
  545      ZSTD_c_experimentalParam15=1012,
  546      ZSTD_c_experimentalParam16=1013,
  547      ZSTD_c_experimentalParam17=1014,
  548      ZSTD_c_experimentalParam18=1015,
  549      ZSTD_c_experimentalParam19=1016,
  550      ZSTD_c_experimentalParam20=1017
  551 } ZSTD_cParameter;
  552 
  553 typedef struct {
  554     size_t error;
  555     int lowerBound;
  556     int upperBound;
  557 } ZSTD_bounds;
  558 
  559 /*! ZSTD_cParam_getBounds() :
  560  *  All parameters must belong to an interval with lower and upper bounds,
  561  *  otherwise they will either trigger an error or be automatically clamped.
  562  * @return : a structure, ZSTD_bounds, which contains
  563  *         - an error status field, which must be tested using ZSTD_isError()
  564  *         - lower and upper bounds, both inclusive
  565  */
  566 /* ZSTDLIB_API ZSTD_bounds ZSTD_cParam_getBounds(ZSTD_cParameter cParam); */
  567 
  568 /*! ZSTD_CCtx_setParameter() :
  569  *  Set one compression parameter, selected by enum ZSTD_cParameter.
  570  *  All parameters have valid bounds. Bounds can be queried using ZSTD_cParam_getBounds().
  571  *  Providing a value beyond bound will either clamp it, or trigger an error (depending on parameter).
  572  *  Setting a parameter is generally only possible during frame initialization (before starting compression).
  573  *  Exception : when using multi-threading mode (nbWorkers >= 1),
  574  *              the following parameters can be updated _during_ compression (within same frame):
  575  *              => compressionLevel, hashLog, chainLog, searchLog, minMatch, targetLength and strategy.
  576  *              new parameters will be active for next job only (after a flush()).
  577  * @return : an error code (which can be tested using ZSTD_isError()).
  578  */
  579 /* ZSTDLIB_API size_t ZSTD_CCtx_setParameter(ZSTD_CCtx* cctx, ZSTD_cParameter param, int value); */
  580 
  581 /*! ZSTD_CCtx_setPledgedSrcSize() :
  582  *  Total input data size to be compressed as a single frame.
  583  *  Value will be written in frame header, unless if explicitly forbidden using ZSTD_c_contentSizeFlag.
  584  *  This value will also be controlled at end of frame, and trigger an error if not respected.
  585  * @result : 0, or an error code (which can be tested with ZSTD_isError()).
  586  *  Note 1 : pledgedSrcSize==0 actually means zero, aka an empty frame.
  587  *           In order to mean "unknown content size", pass constant ZSTD_CONTENTSIZE_UNKNOWN.
  588  *           ZSTD_CONTENTSIZE_UNKNOWN is default value for any new frame.
  589  *  Note 2 : pledgedSrcSize is only valid once, for the next frame.
  590  *           It's discarded at the end of the frame, and replaced by ZSTD_CONTENTSIZE_UNKNOWN.
  591  *  Note 3 : Whenever all input data is provided and consumed in a single round,
  592  *           for example with ZSTD_compress2(),
  593  *           or invoking immediately ZSTD_compressStream2(,,,ZSTD_e_end),
  594  *           this value is automatically overridden by srcSize instead.
  595  */
  596 /* ZSTDLIB_API size_t ZSTD_CCtx_setPledgedSrcSize(ZSTD_CCtx* cctx, unsigned long long pledgedSrcSize); */
  597 
  598 typedef enum {
  599     ZSTD_reset_session_only = 1,
  600     ZSTD_reset_parameters = 2,
  601     ZSTD_reset_session_and_parameters = 3
  602 } ZSTD_ResetDirective;
  603 
  604 /*! ZSTD_CCtx_reset() :
  605  *  There are 2 different things that can be reset, independently or jointly :
  606  *  - The session : will stop compressing current frame, and make CCtx ready to start a new one.
  607  *                  Useful after an error, or to interrupt any ongoing compression.
  608  *                  Any internal data not yet flushed is cancelled.
  609  *                  Compression parameters and dictionary remain unchanged.
  610  *                  They will be used to compress next frame.
  611  *                  Resetting session never fails.
  612  *  - The parameters : changes all parameters back to "default".
  613  *                  This also removes any reference to any dictionary or external sequence producer.
  614  *                  Parameters can only be changed between 2 sessions (i.e. no compression is currently ongoing)
  615  *                  otherwise the reset fails, and function returns an error value (which can be tested using ZSTD_isError())
  616  *  - Both : similar to resetting the session, followed by resetting parameters.
  617  */
  618 /* ZSTDLIB_API size_t ZSTD_CCtx_reset(ZSTD_CCtx* cctx, ZSTD_ResetDirective reset); */
  619 
  620 /*! ZSTD_compress2() :
  621  *  Behave the same as ZSTD_compressCCtx(), but compression parameters are set using the advanced API.
  622  *  (note that this entry point doesn't even expose a compression level parameter).
  623  *  ZSTD_compress2() always starts a new frame.
  624  *  Should cctx hold data from a previously unfinished frame, everything about it is forgotten.
  625  *  - Compression parameters are pushed into CCtx before starting compression, using ZSTD_CCtx_set*()
  626  *  - The function is always blocking, returns when compression is completed.
  627  *  NOTE: Providing `dstCapacity >= ZSTD_compressBound(srcSize)` guarantees that zstd will have
  628  *        enough space to successfully compress the data, though it is possible it fails for other reasons.
  629  * @return : compressed size written into `dst` (<= `dstCapacity),
  630  *           or an error code if it fails (which can be tested using ZSTD_isError()).
  631  */
  632 /* ZSTDLIB_API size_t ZSTD_compress2( ZSTD_CCtx* cctx,
  633                                    void* dst, size_t dstCapacity,
  634                              const void* src, size_t srcSize); */
  635 
  636 
  637 /***********************************************
  638 *  Advanced decompression API (Requires v1.4.0+)
  639 ************************************************/
  640 
  641 /* The advanced API pushes parameters one by one into an existing DCtx context.
  642  * Parameters are sticky, and remain valid for all following frames
  643  * using the same DCtx context.
  644  * It's possible to reset parameters to default values using ZSTD_DCtx_reset().
  645  * Note : This API is compatible with existing ZSTD_decompressDCtx() and ZSTD_decompressStream().
  646  *        Therefore, no new decompression function is necessary.
  647  */
  648 
  649 typedef enum {
  650 
  651     ZSTD_d_windowLogMax=100, /* Select a size limit (in power of 2) beyond which
  652                               * the streaming API will refuse to allocate memory buffer
  653                               * in order to protect the host from unreasonable memory requirements.
  654                               * This parameter is only useful in streaming mode, since no internal buffer is allocated in single-pass mode.
  655                               * By default, a decompression context accepts window sizes <= (1 << ZSTD_WINDOWLOG_LIMIT_DEFAULT).
  656                               * Special: value 0 means "use default maximum windowLog". */
  657 
  658     /* note : additional experimental parameters are also available
  659      * within the experimental section of the API.
  660      * At the time of this writing, they include :
  661      * ZSTD_d_format
  662      * ZSTD_d_stableOutBuffer
  663      * ZSTD_d_forceIgnoreChecksum
  664      * ZSTD_d_refMultipleDDicts
  665      * ZSTD_d_disableHuffmanAssembly
  666      * ZSTD_d_maxBlockSize
  667      * Because they are not stable, it's necessary to define ZSTD_STATIC_LINKING_ONLY to access them.
  668      * note : never ever use experimentalParam? names directly
  669      */
  670      ZSTD_d_experimentalParam1=1000,
  671      ZSTD_d_experimentalParam2=1001,
  672      ZSTD_d_experimentalParam3=1002,
  673      ZSTD_d_experimentalParam4=1003,
  674      ZSTD_d_experimentalParam5=1004,
  675      ZSTD_d_experimentalParam6=1005
  676 
  677 } ZSTD_dParameter;
  678 
  679 /*! ZSTD_dParam_getBounds() :
  680  *  All parameters must belong to an interval with lower and upper bounds,
  681  *  otherwise they will either trigger an error or be automatically clamped.
  682  * @return : a structure, ZSTD_bounds, which contains
  683  *         - an error status field, which must be tested using ZSTD_isError()
  684  *         - both lower and upper bounds, inclusive
  685  */
  686 /* ZSTDLIB_API ZSTD_bounds ZSTD_dParam_getBounds(ZSTD_dParameter dParam); */
  687 
  688 /*! ZSTD_DCtx_setParameter() :
  689  *  Set one compression parameter, selected by enum ZSTD_dParameter.
  690  *  All parameters have valid bounds. Bounds can be queried using ZSTD_dParam_getBounds().
  691  *  Providing a value beyond bound will either clamp it, or trigger an error (depending on parameter).
  692  *  Setting a parameter is only possible during frame initialization (before starting decompression).
  693  * @return : 0, or an error code (which can be tested using ZSTD_isError()).
  694  */
  695 /* ZSTDLIB_API size_t ZSTD_DCtx_setParameter(ZSTD_DCtx* dctx, ZSTD_dParameter param, int value); */
  696 
  697 /*! ZSTD_DCtx_reset() :
  698  *  Return a DCtx to clean state.
  699  *  Session and parameters can be reset jointly or separately.
  700  *  Parameters can only be reset when no active frame is being decompressed.
  701  * @return : 0, or an error code, which can be tested with ZSTD_isError()
  702  */
  703 /* ZSTDLIB_API size_t ZSTD_DCtx_reset(ZSTD_DCtx* dctx, ZSTD_ResetDirective reset); */
  704 
  705 
  706 /****************************
  707 *  Streaming
  708 ****************************/
  709 
  710 typedef struct ZSTD_inBuffer_s {
  711   const void* src;    /**< start of input buffer */
  712   size_t size;        /**< size of input buffer */
  713   size_t pos;         /**< position where reading stopped. Will be updated. Necessarily 0 <= pos <= size */
  714 } ZSTD_inBuffer;
  715 
  716 typedef struct ZSTD_outBuffer_s {
  717   void*  dst;         /**< start of output buffer */
  718   size_t size;        /**< size of output buffer */
  719   size_t pos;         /**< position where writing stopped. Will be updated. Necessarily 0 <= pos <= size */
  720 } ZSTD_outBuffer;
  721 
  722 
  723 
  724 /*-***********************************************************************
  725 *  Streaming compression - HowTo
  726 *
  727 *  A ZSTD_CStream object is required to track streaming operation.
  728 *  Use ZSTD_createCStream() and ZSTD_freeCStream() to create/release resources.
  729 *  ZSTD_CStream objects can be reused multiple times on consecutive compression operations.
  730 *  It is recommended to reuse ZSTD_CStream since it will play nicer with system's memory, by re-using already allocated memory.
  731 *
  732 *  For parallel execution, use one separate ZSTD_CStream per thread.
  733 *
  734 *  note : since v1.3.0, ZSTD_CStream and ZSTD_CCtx are the same thing.
  735 *
  736 *  Parameters are sticky : when starting a new compression on the same context,
  737 *  it will reuse the same sticky parameters as previous compression session.
  738 *  When in doubt, it's recommended to fully initialize the context before usage.
  739 *  Use ZSTD_CCtx_reset() to reset the context and ZSTD_CCtx_setParameter(),
  740 *  ZSTD_CCtx_setPledgedSrcSize(), or ZSTD_CCtx_loadDictionary() and friends to
  741 *  set more specific parameters, the pledged source size, or load a dictionary.
  742 *
  743 *  Use ZSTD_compressStream2() with ZSTD_e_continue as many times as necessary to
  744 *  consume input stream. The function will automatically update both `pos`
  745 *  fields within `input` and `output`.
  746 *  Note that the function may not consume the entire input, for example, because
  747 *  the output buffer is already full, in which case `input.pos < input.size`.
  748 *  The caller must check if input has been entirely consumed.
  749 *  If not, the caller must make some room to receive more compressed data,
  750 *  and then present again remaining input data.
  751 *  note: ZSTD_e_continue is guaranteed to make some forward progress when called,
  752 *        but doesn't guarantee maximal forward progress. This is especially relevant
  753 *        when compressing with multiple threads. The call won't block if it can
  754 *        consume some input, but if it can't it will wait for some, but not all,
  755 *        output to be flushed.
  756 * @return : provides a minimum amount of data remaining to be flushed from internal buffers
  757 *           or an error code, which can be tested using ZSTD_isError().
  758 *
  759 *  At any moment, it's possible to flush whatever data might remain stuck within internal buffer,
  760 *  using ZSTD_compressStream2() with ZSTD_e_flush. `output->pos` will be updated.
  761 *  Note that, if `output->size` is too small, a single invocation with ZSTD_e_flush might not be enough (return code > 0).
  762 *  In which case, make some room to receive more compressed data, and call again ZSTD_compressStream2() with ZSTD_e_flush.
  763 *  You must continue calling ZSTD_compressStream2() with ZSTD_e_flush until it returns 0, at which point you can change the
  764 *  operation.
  765 *  note: ZSTD_e_flush will flush as much output as possible, meaning when compressing with multiple threads, it will
  766 *        block until the flush is complete or the output buffer is full.
  767 *  @return : 0 if internal buffers are entirely flushed,
  768 *            >0 if some data still present within internal buffer (the value is minimal estimation of remaining size),
  769 *            or an error code, which can be tested using ZSTD_isError().
  770 *
  771 *  Calling ZSTD_compressStream2() with ZSTD_e_end instructs to finish a frame.
  772 *  It will perform a flush and write frame epilogue.
  773 *  The epilogue is required for decoders to consider a frame completed.
  774 *  flush operation is the same, and follows same rules as calling ZSTD_compressStream2() with ZSTD_e_flush.
  775 *  You must continue calling ZSTD_compressStream2() with ZSTD_e_end until it returns 0, at which point you are free to
  776 *  start a new frame.
  777 *  note: ZSTD_e_end will flush as much output as possible, meaning when compressing with multiple threads, it will
  778 *        block until the flush is complete or the output buffer is full.
  779 *  @return : 0 if frame fully completed and fully flushed,
  780 *            >0 if some data still present within internal buffer (the value is minimal estimation of remaining size),
  781 *            or an error code, which can be tested using ZSTD_isError().
  782 *
  783 * *******************************************************************/
  784 
  785 typedef ZSTD_CCtx ZSTD_CStream;  /**< CCtx and CStream are now effectively same object (>= v1.3.0) */
  786                                  /* Continue to distinguish them for compatibility with older versions <= v1.2.0 */
  787 /*===== ZSTD_CStream management functions =====*/
  788 /* ZSTDLIB_API ZSTD_CStream* ZSTD_createCStream(void); */
  789 /* ZSTDLIB_API size_t ZSTD_freeCStream(ZSTD_CStream* zcs); */  /* accept NULL pointer */
  790 
  791 /*===== Streaming compression functions =====*/
  792 typedef enum {
  793     ZSTD_e_continue=0, /* collect more data, encoder decides when to output compressed result, for optimal compression ratio */
  794     ZSTD_e_flush=1,    /* flush any data provided so far,
  795                         * it creates (at least) one new block, that can be decoded immediately on reception;
  796                         * frame will continue: any future data can still reference previously compressed data, improving compression.
  797                         * note : multithreaded compression will block to flush as much output as possible. */
  798     ZSTD_e_end=2       /* flush any remaining data _and_ close current frame.
  799                         * note that frame is only closed after compressed data is fully flushed (return value == 0).
  800                         * After that point, any additional data starts a new frame.
  801                         * note : each frame is independent (does not reference any content from previous frame).
  802                         : note : multithreaded compression will block to flush as much output as possible. */
  803 } ZSTD_EndDirective;
  804 
  805 /*! ZSTD_compressStream2() : Requires v1.4.0+
  806  *  Behaves about the same as ZSTD_compressStream, with additional control on end directive.
  807  *  - Compression parameters are pushed into CCtx before starting compression, using ZSTD_CCtx_set*()
  808  *  - Compression parameters cannot be changed once compression is started (save a list of exceptions in multi-threading mode)
  809  *  - output->pos must be <= dstCapacity, input->pos must be <= srcSize
  810  *  - output->pos and input->pos will be updated. They are guaranteed to remain below their respective limit.
  811  *  - endOp must be a valid directive
  812  *  - When nbWorkers==0 (default), function is blocking : it completes its job before returning to caller.
  813  *  - 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,
  814  *                                                  and then immediately returns, just indicating that there is some data remaining to be flushed.
  815  *                                                  The function nonetheless guarantees forward progress : it will return only after it reads or write at least 1+ byte.
  816  *  - 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.
  817  *  - @return provides a minimum amount of data remaining to be flushed from internal buffers
  818  *            or an error code, which can be tested using ZSTD_isError().
  819  *            if @return != 0, flush is not fully completed, there is still some data left within internal buffers.
  820  *            This is useful for ZSTD_e_flush, since in this case more flushes are necessary to empty all buffers.
  821  *            For ZSTD_e_end, @return == 0 when internal buffers are fully flushed and frame is completed.
  822  *  - after a ZSTD_e_end directive, if internal buffer is not fully flushed (@return != 0),
  823  *            only ZSTD_e_end or ZSTD_e_flush operations are allowed.
  824  *            Before starting a new compression job, or changing compression parameters,
  825  *            it is required to fully flush internal buffers.
  826  *  - note: if an operation ends with an error, it may leave @cctx in an undefined state.
  827  *          Therefore, it's UB to invoke ZSTD_compressStream2() of ZSTD_compressStream() on such a state.
  828  *          In order to be re-employed after an error, a state must be reset,
  829  *          which can be done explicitly (ZSTD_CCtx_reset()),
  830  *          or is sometimes implied by methods starting a new compression job (ZSTD_initCStream(), ZSTD_compressCCtx())
  831  */
  832 /* ZSTDLIB_API size_t ZSTD_compressStream2( ZSTD_CCtx* cctx,
  833                                          ZSTD_outBuffer* output,
  834                                          ZSTD_inBuffer* input,
  835                                          ZSTD_EndDirective endOp); */
  836 
  837 
  838 /* These buffer sizes are softly recommended.
  839  * They are not required : ZSTD_compressStream*() happily accepts any buffer size, for both input and output.
  840  * Respecting the recommended size just makes it a bit easier for ZSTD_compressStream*(),
  841  * reducing the amount of memory shuffling and buffering, resulting in minor performance savings.
  842  *
  843  * However, note that these recommendations are from the perspective of a C caller program.
  844  * If the streaming interface is invoked from some other language,
  845  * especially managed ones such as Java or Go, through a foreign function interface such as jni or cgo,
  846  * a major performance rule is to reduce crossing such interface to an absolute minimum.
  847  * It's not rare that performance ends being spent more into the interface, rather than compression itself.
  848  * In which cases, prefer using large buffers, as large as practical,
  849  * for both input and output, to reduce the nb of roundtrips.
  850  */
  851 /* ZSTDLIB_API size_t ZSTD_CStreamInSize(void); */    /**< recommended size for input buffer */
  852 /* ZSTDLIB_API size_t ZSTD_CStreamOutSize(void); */   /**< recommended size for output buffer. Guarantee to successfully flush at least one complete compressed block. */
  853 
  854 
  855 /* *****************************************************************************
  856  * This following is a legacy streaming API, available since v1.0+ .
  857  * It can be replaced by ZSTD_CCtx_reset() and ZSTD_compressStream2().
  858  * It is redundant, but remains fully supported.
  859  ******************************************************************************/
  860 
  861 /*!
  862  * Equivalent to:
  863  *
  864  *     ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only);
  865  *     ZSTD_CCtx_refCDict(zcs, NULL); // clear the dictionary (if any)
  866  *     ZSTD_CCtx_setParameter(zcs, ZSTD_c_compressionLevel, compressionLevel);
  867  *
  868  * Note that ZSTD_initCStream() clears any previously set dictionary. Use the new API
  869  * to compress with a dictionary.
  870  */
  871 /* ZSTDLIB_API size_t ZSTD_initCStream(ZSTD_CStream* zcs, int compressionLevel); */
  872 /*!
  873  * Alternative for ZSTD_compressStream2(zcs, output, input, ZSTD_e_continue).
  874  * NOTE: The return value is different. ZSTD_compressStream() returns a hint for
  875  * the next read size (if non-zero and not an error). ZSTD_compressStream2()
  876  * returns the minimum nb of bytes left to flush (if non-zero and not an error).
  877  */
  878 /* ZSTDLIB_API size_t ZSTD_compressStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output, ZSTD_inBuffer* input); */
  879 /*! Equivalent to ZSTD_compressStream2(zcs, output, &emptyInput, ZSTD_e_flush). */
  880 /* ZSTDLIB_API size_t ZSTD_flushStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output); */
  881 /*! Equivalent to ZSTD_compressStream2(zcs, output, &emptyInput, ZSTD_e_end). */
  882 /* ZSTDLIB_API size_t ZSTD_endStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output); */
  883 
  884 
  885 /*-***************************************************************************
  886 *  Streaming decompression - HowTo
  887 *
  888 *  A ZSTD_DStream object is required to track streaming operations.
  889 *  Use ZSTD_createDStream() and ZSTD_freeDStream() to create/release resources.
  890 *  ZSTD_DStream objects can be re-employed multiple times.
  891 *
  892 *  Use ZSTD_initDStream() to start a new decompression operation.
  893 * @return : recommended first input size
  894 *  Alternatively, use advanced API to set specific properties.
  895 *
  896 *  Use ZSTD_decompressStream() repetitively to consume your input.
  897 *  The function will update both `pos` fields.
  898 *  If `input.pos < input.size`, some input has not been consumed.
  899 *  It's up to the caller to present again remaining data.
  900 *
  901 *  The function tries to flush all data decoded immediately, respecting output buffer size.
  902 *  If `output.pos < output.size`, decoder has flushed everything it could.
  903 *
  904 *  However, when `output.pos == output.size`, it's more difficult to know.
  905 *  If @return > 0, the frame is not complete, meaning
  906 *  either there is still some data left to flush within internal buffers,
  907 *  or there is more input to read to complete the frame (or both).
  908 *  In which case, call ZSTD_decompressStream() again to flush whatever remains in the buffer.
  909 *  Note : with no additional input provided, amount of data flushed is necessarily <= ZSTD_BLOCKSIZE_MAX.
  910 * @return : 0 when a frame is completely decoded and fully flushed,
  911 *        or an error code, which can be tested using ZSTD_isError(),
  912 *        or any other value > 0, which means there is still some decoding or flushing to do to complete current frame :
  913 *                                the return value is a suggested next input size (just a hint for better latency)
  914 *                                that will never request more than the remaining content of the compressed frame.
  915 * *******************************************************************************/
  916 
  917 typedef ZSTD_DCtx ZSTD_DStream;  /**< DCtx and DStream are now effectively same object (>= v1.3.0) */
  918                                  /* For compatibility with versions <= v1.2.0, prefer differentiating them. */
  919 /*===== ZSTD_DStream management functions =====*/
  920 /* ZSTDLIB_API ZSTD_DStream* ZSTD_createDStream(void); */
  921 /* ZSTDLIB_API size_t ZSTD_freeDStream(ZSTD_DStream* zds); */  /* accept NULL pointer */
  922 
  923 /*===== Streaming decompression functions =====*/
  924 
  925 /*! ZSTD_initDStream() :
  926  * Initialize/reset DStream state for new decompression operation.
  927  * Call before new decompression operation using same DStream.
  928  *
  929  * Note : This function is redundant with the advanced API and equivalent to:
  930  *     ZSTD_DCtx_reset(zds, ZSTD_reset_session_only);
  931  *     ZSTD_DCtx_refDDict(zds, NULL);
  932  */
  933 /* ZSTDLIB_API size_t ZSTD_initDStream(ZSTD_DStream* zds); */
  934 
  935 /*! ZSTD_decompressStream() :
  936  * Streaming decompression function.
  937  * Call repetitively to consume full input updating it as necessary.
  938  * Function will update both input and output `pos` fields exposing current state via these fields:
  939  * - `input.pos < input.size`, some input remaining and caller should provide remaining input
  940  *   on the next call.
  941  * - `output.pos < output.size`, decoder flushed internal output buffer.
  942  * - `output.pos == output.size`, unflushed data potentially present in the internal buffers,
  943  *   check ZSTD_decompressStream() @return value,
  944  *   if > 0, invoke it again to flush remaining data to output.
  945  * Note : with no additional input, amount of data flushed <= ZSTD_BLOCKSIZE_MAX.
  946  *
  947  * @return : 0 when a frame is completely decoded and fully flushed,
  948  *           or an error code, which can be tested using ZSTD_isError(),
  949  *           or any other value > 0, which means there is some decoding or flushing to do to complete current frame.
  950  *
  951  * Note: when an operation returns with an error code, the @zds state may be left in undefined state.
  952  *       It's UB to invoke `ZSTD_decompressStream()` on such a state.
  953  *       In order to re-use such a state, it must be first reset,
  954  *       which can be done explicitly (`ZSTD_DCtx_reset()`),
  955  *       or is implied for operations starting some new decompression job (`ZSTD_initDStream`, `ZSTD_decompressDCtx()`, `ZSTD_decompress_usingDict()`)
  956  */
  957 /* ZSTDLIB_API size_t ZSTD_decompressStream(ZSTD_DStream* zds, ZSTD_outBuffer* output, ZSTD_inBuffer* input); */
  958 
  959 /* ZSTDLIB_API size_t ZSTD_DStreamInSize(void); */    /*!< recommended size for input buffer */
  960 /* ZSTDLIB_API size_t ZSTD_DStreamOutSize(void); */   /*!< recommended size for output buffer. Guarantee to successfully flush at least one complete block in all circumstances. */
  961 
  962 
  963 /**************************
  964 *  Simple dictionary API
  965 ***************************/
  966 /*! ZSTD_compress_usingDict() :
  967  *  Compression at an explicit compression level using a Dictionary.
  968  *  A dictionary can be any arbitrary data segment (also called a prefix),
  969  *  or a buffer with specified information (see zdict.h).
  970  *  Note : This function loads the dictionary, resulting in significant startup delay.
  971  *         It's intended for a dictionary used only once.
  972  *  Note 2 : When `dict == NULL || dictSize < 8` no dictionary is used. */
  973 /* ZSTDLIB_API size_t ZSTD_compress_usingDict(ZSTD_CCtx* ctx,
  974                                            void* dst, size_t dstCapacity,
  975                                      const void* src, size_t srcSize,
  976                                      const void* dict,size_t dictSize,
  977                                            int compressionLevel); */
  978 
  979 /*! ZSTD_decompress_usingDict() :
  980  *  Decompression using a known Dictionary.
  981  *  Dictionary must be identical to the one used during compression.
  982  *  Note : This function loads the dictionary, resulting in significant startup delay.
  983  *         It's intended for a dictionary used only once.
  984  *  Note : When `dict == NULL || dictSize < 8` no dictionary is used. */
  985 /* ZSTDLIB_API size_t ZSTD_decompress_usingDict(ZSTD_DCtx* dctx,
  986                                              void* dst, size_t dstCapacity,
  987                                        const void* src, size_t srcSize,
  988                                        const void* dict,size_t dictSize); */
  989 
  990 
  991 /***********************************
  992  *  Bulk processing dictionary API
  993  **********************************/
  994 typedef struct ZSTD_CDict_s ZSTD_CDict;
  995 
  996 /*! ZSTD_createCDict() :
  997  *  When compressing multiple messages or blocks using the same dictionary,
  998  *  it's recommended to digest the dictionary only once, since it's a costly operation.
  999  *  ZSTD_createCDict() will create a state from digesting a dictionary.
 1000  *  The resulting state can be used for future compression operations with very limited startup cost.
 1001  *  ZSTD_CDict can be created once and shared by multiple threads concurrently, since its usage is read-only.
 1002  * @dictBuffer can be released after ZSTD_CDict creation, because its content is copied within CDict.
 1003  *  Note 1 : Consider experimental function `ZSTD_createCDict_byReference()` if you prefer to not duplicate @dictBuffer content.
 1004  *  Note 2 : A ZSTD_CDict can be created from an empty @dictBuffer,
 1005  *      in which case the only thing that it transports is the @compressionLevel.
 1006  *      This can be useful in a pipeline featuring ZSTD_compress_usingCDict() exclusively,
 1007  *      expecting a ZSTD_CDict parameter with any data, including those without a known dictionary. */
 1008 /* ZSTDLIB_API ZSTD_CDict* ZSTD_createCDict(const void* dictBuffer, size_t dictSize,
 1009                                          int compressionLevel); */
 1010 
 1011 /*! ZSTD_freeCDict() :
 1012  *  Function frees memory allocated by ZSTD_createCDict().
 1013  *  If a NULL pointer is passed, no operation is performed. */
 1014 /* ZSTDLIB_API size_t      ZSTD_freeCDict(ZSTD_CDict* CDict); */
 1015 
 1016 /*! ZSTD_compress_usingCDict() :
 1017  *  Compression using a digested Dictionary.
 1018  *  Recommended when same dictionary is used multiple times.
 1019  *  Note : compression level is _decided at dictionary creation time_,
 1020  *     and frame parameters are hardcoded (dictID=yes, contentSize=yes, checksum=no) */
 1021 /* ZSTDLIB_API size_t ZSTD_compress_usingCDict(ZSTD_CCtx* cctx,
 1022                                             void* dst, size_t dstCapacity,
 1023                                       const void* src, size_t srcSize,
 1024                                       const ZSTD_CDict* cdict); */
 1025 
 1026 
 1027 typedef struct ZSTD_DDict_s ZSTD_DDict;
 1028 
 1029 /*! ZSTD_createDDict() :
 1030  *  Create a digested dictionary, ready to start decompression operation without startup delay.
 1031  *  dictBuffer can be released after DDict creation, as its content is copied inside DDict. */
 1032 /* ZSTDLIB_API ZSTD_DDict* ZSTD_createDDict(const void* dictBuffer, size_t dictSize); */
 1033 
 1034 /*! ZSTD_freeDDict() :
 1035  *  Function frees memory allocated with ZSTD_createDDict()
 1036  *  If a NULL pointer is passed, no operation is performed. */
 1037 /* ZSTDLIB_API size_t      ZSTD_freeDDict(ZSTD_DDict* ddict); */
 1038 
 1039 /*! ZSTD_decompress_usingDDict() :
 1040  *  Decompression using a digested Dictionary.
 1041  *  Recommended when same dictionary is used multiple times. */
 1042 /* ZSTDLIB_API size_t ZSTD_decompress_usingDDict(ZSTD_DCtx* dctx,
 1043                                               void* dst, size_t dstCapacity,
 1044                                         const void* src, size_t srcSize,
 1045                                         const ZSTD_DDict* ddict); */
 1046 
 1047 
 1048 /********************************
 1049  *  Dictionary helper functions
 1050  *******************************/
 1051 
 1052 /*! ZSTD_getDictID_fromDict() : Requires v1.4.0+
 1053  *  Provides the dictID stored within dictionary.
 1054  *  if @return == 0, the dictionary is not conformant with Zstandard specification.
 1055  *  It can still be loaded, but as a content-only dictionary. */
 1056 /* ZSTDLIB_API unsigned ZSTD_getDictID_fromDict(const void* dict, size_t dictSize); */
 1057 
 1058 /*! ZSTD_getDictID_fromCDict() : Requires v1.5.0+
 1059  *  Provides the dictID of the dictionary loaded into `cdict`.
 1060  *  If @return == 0, the dictionary is not conformant to Zstandard specification, or empty.
 1061  *  Non-conformant dictionaries can still be loaded, but as content-only dictionaries. */
 1062 /* ZSTDLIB_API unsigned ZSTD_getDictID_fromCDict(const ZSTD_CDict* cdict); */
 1063 
 1064 /*! ZSTD_getDictID_fromDDict() : Requires v1.4.0+
 1065  *  Provides the dictID of the dictionary loaded into `ddict`.
 1066  *  If @return == 0, the dictionary is not conformant to Zstandard specification, or empty.
 1067  *  Non-conformant dictionaries can still be loaded, but as content-only dictionaries. */
 1068 /* ZSTDLIB_API unsigned ZSTD_getDictID_fromDDict(const ZSTD_DDict* ddict); */
 1069 
 1070 /*! ZSTD_getDictID_fromFrame() : Requires v1.4.0+
 1071  *  Provides the dictID required to decompressed the frame stored within `src`.
 1072  *  If @return == 0, the dictID could not be decoded.
 1073  *  This could for one of the following reasons :
 1074  *  - The frame does not require a dictionary to be decoded (most common case).
 1075  *  - The frame was built with dictID intentionally removed. Whatever dictionary is necessary is a hidden piece of information.
 1076  *    Note : this use case also happens when using a non-conformant dictionary.
 1077  *  - `srcSize` is too small, and as a result, the frame header could not be decoded (only possible if `srcSize < ZSTD_FRAMEHEADERSIZE_MAX`).
 1078  *  - This is not a Zstandard frame.
 1079  *  When identifying the exact failure cause, it's possible to use ZSTD_getFrameHeader(), which will provide a more precise error code. */
 1080 /* ZSTDLIB_API unsigned ZSTD_getDictID_fromFrame(const void* src, size_t srcSize); */
 1081 
 1082 
 1083 /*******************************************************************************
 1084  * Advanced dictionary and prefix API (Requires v1.4.0+)
 1085  *
 1086  * This API allows dictionaries to be used with ZSTD_compress2(),
 1087  * ZSTD_compressStream2(), and ZSTD_decompressDCtx().
 1088  * Dictionaries are sticky, they remain valid when same context is reused,
 1089  * they only reset when the context is reset
 1090  * with ZSTD_reset_parameters or ZSTD_reset_session_and_parameters.
 1091  * In contrast, Prefixes are single-use.
 1092  ******************************************************************************/
 1093 
 1094 
 1095 /*! ZSTD_CCtx_loadDictionary() : Requires v1.4.0+
 1096  *  Create an internal CDict from `dict` buffer.
 1097  *  Decompression will have to use same dictionary.
 1098  * @result : 0, or an error code (which can be tested with ZSTD_isError()).
 1099  *  Special: Loading a NULL (or 0-size) dictionary invalidates previous dictionary,
 1100  *           meaning "return to no-dictionary mode".
 1101  *  Note 1 : Dictionary is sticky, it will be used for all future compressed frames,
 1102  *           until parameters are reset, a new dictionary is loaded, or the dictionary
 1103  *           is explicitly invalidated by loading a NULL dictionary.
 1104  *  Note 2 : Loading a dictionary involves building tables.
 1105  *           It's also a CPU consuming operation, with non-negligible impact on latency.
 1106  *           Tables are dependent on compression parameters, and for this reason,
 1107  *           compression parameters can no longer be changed after loading a dictionary.
 1108  *  Note 3 :`dict` content will be copied internally.
 1109  *           Use experimental ZSTD_CCtx_loadDictionary_byReference() to reference content instead.
 1110  *           In such a case, dictionary buffer must outlive its users.
 1111  *  Note 4 : Use ZSTD_CCtx_loadDictionary_advanced()
 1112  *           to precisely select how dictionary content must be interpreted.
 1113  *  Note 5 : This method does not benefit from LDM (long distance mode).
 1114  *           If you want to employ LDM on some large dictionary content,
 1115  *           prefer employing ZSTD_CCtx_refPrefix() described below.
 1116  */
 1117 /* ZSTDLIB_API size_t ZSTD_CCtx_loadDictionary(ZSTD_CCtx* cctx, const void* dict, size_t dictSize); */
 1118 
 1119 /*! ZSTD_CCtx_refCDict() : Requires v1.4.0+
 1120  *  Reference a prepared dictionary, to be used for all future compressed frames.
 1121  *  Note that compression parameters are enforced from within CDict,
 1122  *  and supersede any compression parameter previously set within CCtx.
 1123  *  The parameters ignored are labelled as "superseded-by-cdict" in the ZSTD_cParameter enum docs.
 1124  *  The ignored parameters will be used again if the CCtx is returned to no-dictionary mode.
 1125  *  The dictionary will remain valid for future compressed frames using same CCtx.
 1126  * @result : 0, or an error code (which can be tested with ZSTD_isError()).
 1127  *  Special : Referencing a NULL CDict means "return to no-dictionary mode".
 1128  *  Note 1 : Currently, only one dictionary can be managed.
 1129  *           Referencing a new dictionary effectively "discards" any previous one.
 1130  *  Note 2 : CDict is just referenced, its lifetime must outlive its usage within CCtx. */
 1131 /* ZSTDLIB_API size_t ZSTD_CCtx_refCDict(ZSTD_CCtx* cctx, const ZSTD_CDict* cdict); */
 1132 
 1133 /*! ZSTD_CCtx_refPrefix() : Requires v1.4.0+
 1134  *  Reference a prefix (single-usage dictionary) for next compressed frame.
 1135  *  A prefix is **only used once**. Tables are discarded at end of frame (ZSTD_e_end).
 1136  *  Decompression will need same prefix to properly regenerate data.
 1137  *  Compressing with a prefix is similar in outcome as performing a diff and compressing it,
 1138  *  but performs much faster, especially during decompression (compression speed is tunable with compression level).
 1139  *  This method is compatible with LDM (long distance mode).
 1140  * @result : 0, or an error code (which can be tested with ZSTD_isError()).
 1141  *  Special: Adding any prefix (including NULL) invalidates any previous prefix or dictionary
 1142  *  Note 1 : Prefix buffer is referenced. It **must** outlive compression.
 1143  *           Its content must remain unmodified during compression.
 1144  *  Note 2 : If the intention is to diff some large src data blob with some prior version of itself,
 1145  *           ensure that the window size is large enough to contain the entire source.
 1146  *           See ZSTD_c_windowLog.
 1147  *  Note 3 : Referencing a prefix involves building tables, which are dependent on compression parameters.
 1148  *           It's a CPU consuming operation, with non-negligible impact on latency.
 1149  *           If there is a need to use the same prefix multiple times, consider loadDictionary instead.
 1150  *  Note 4 : By default, the prefix is interpreted as raw content (ZSTD_dct_rawContent).
 1151  *           Use experimental ZSTD_CCtx_refPrefix_advanced() to alter dictionary interpretation. */
 1152 /* ZSTDLIB_API size_t ZSTD_CCtx_refPrefix(ZSTD_CCtx* cctx,
 1153                                  const void* prefix, size_t prefixSize); */
 1154 
 1155 /*! ZSTD_DCtx_loadDictionary() : Requires v1.4.0+
 1156  *  Create an internal DDict from dict buffer, to be used to decompress all future frames.
 1157  *  The dictionary remains valid for all future frames, until explicitly invalidated, or
 1158  *  a new dictionary is loaded.
 1159  * @result : 0, or an error code (which can be tested with ZSTD_isError()).
 1160  *  Special : Adding a NULL (or 0-size) dictionary invalidates any previous dictionary,
 1161  *            meaning "return to no-dictionary mode".
 1162  *  Note 1 : Loading a dictionary involves building tables,
 1163  *           which has a non-negligible impact on CPU usage and latency.
 1164  *           It's recommended to "load once, use many times", to amortize the cost
 1165  *  Note 2 :`dict` content will be copied internally, so `dict` can be released after loading.
 1166  *           Use ZSTD_DCtx_loadDictionary_byReference() to reference dictionary content instead.
 1167  *  Note 3 : Use ZSTD_DCtx_loadDictionary_advanced() to take control of
 1168  *           how dictionary content is loaded and interpreted.
 1169  */
 1170 /* ZSTDLIB_API size_t ZSTD_DCtx_loadDictionary(ZSTD_DCtx* dctx, const void* dict, size_t dictSize); */
 1171 
 1172 /*! ZSTD_DCtx_refDDict() : Requires v1.4.0+
 1173  *  Reference a prepared dictionary, to be used to decompress next frames.
 1174  *  The dictionary remains active for decompression of future frames using same DCtx.
 1175  *
 1176  *  If called with ZSTD_d_refMultipleDDicts enabled, repeated calls of this function
 1177  *  will store the DDict references in a table, and the DDict used for decompression
 1178  *  will be determined at decompression time, as per the dict ID in the frame.
 1179  *  The memory for the table is allocated on the first call to refDDict, and can be
 1180  *  freed with ZSTD_freeDCtx().
 1181  *
 1182  *  If called with ZSTD_d_refMultipleDDicts disabled (the default), only one dictionary
 1183  *  will be managed, and referencing a dictionary effectively "discards" any previous one.
 1184  *
 1185  * @result : 0, or an error code (which can be tested with ZSTD_isError()).
 1186  *  Special: referencing a NULL DDict means "return to no-dictionary mode".
 1187  *  Note 2 : DDict is just referenced, its lifetime must outlive its usage from DCtx.
 1188  */
 1189 /* ZSTDLIB_API size_t ZSTD_DCtx_refDDict(ZSTD_DCtx* dctx, const ZSTD_DDict* ddict); */
 1190 
 1191 /*! ZSTD_DCtx_refPrefix() : Requires v1.4.0+
 1192  *  Reference a prefix (single-usage dictionary) to decompress next frame.
 1193  *  This is the reverse operation of ZSTD_CCtx_refPrefix(),
 1194  *  and must use the same prefix as the one used during compression.
 1195  *  Prefix is **only used once**. Reference is discarded at end of frame.
 1196  *  End of frame is reached when ZSTD_decompressStream() returns 0.
 1197  * @result : 0, or an error code (which can be tested with ZSTD_isError()).
 1198  *  Note 1 : Adding any prefix (including NULL) invalidates any previously set prefix or dictionary
 1199  *  Note 2 : Prefix buffer is referenced. It **must** outlive decompression.
 1200  *           Prefix buffer must remain unmodified up to the end of frame,
 1201  *           reached when ZSTD_decompressStream() returns 0.
 1202  *  Note 3 : By default, the prefix is treated as raw content (ZSTD_dct_rawContent).
 1203  *           Use ZSTD_CCtx_refPrefix_advanced() to alter dictMode (Experimental section)
 1204  *  Note 4 : Referencing a raw content prefix has almost no cpu nor memory cost.
 1205  *           A full dictionary is more costly, as it requires building tables.
 1206  */
 1207 /* ZSTDLIB_API size_t ZSTD_DCtx_refPrefix(ZSTD_DCtx* dctx,
 1208                                  const void* prefix, size_t prefixSize); */
 1209 
 1210 /* ===   Memory management   === */
 1211 
 1212 /*! ZSTD_sizeof_*() : Requires v1.4.0+
 1213  *  These functions give the _current_ memory usage of selected object.
 1214  *  Note that object memory usage can evolve (increase or decrease) over time. */
 1215 /* ZSTDLIB_API size_t ZSTD_sizeof_CCtx(const ZSTD_CCtx* cctx); */
 1216 /* ZSTDLIB_API size_t ZSTD_sizeof_DCtx(const ZSTD_DCtx* dctx); */
 1217 /* ZSTDLIB_API size_t ZSTD_sizeof_CStream(const ZSTD_CStream* zcs); */
 1218 /* ZSTDLIB_API size_t ZSTD_sizeof_DStream(const ZSTD_DStream* zds); */
 1219 /* ZSTDLIB_API size_t ZSTD_sizeof_CDict(const ZSTD_CDict* cdict); */
 1220 /* ZSTDLIB_API size_t ZSTD_sizeof_DDict(const ZSTD_DDict* ddict); */
 1221 
 1222 #if defined (__cplusplus)
 1223 }
 1224 #endif
 1225 
 1226 #endif  /* ZSTD_H_235446 */
 1227 
 1228 /*
 1229  * Copyright (c) Meta Platforms, Inc. and affiliates.
 1230  * All rights reserved.
 1231  *
 1232  * This source code is licensed under both the BSD-style license (found in the
 1233  * LICENSE file in the root directory of this source tree) and the GPLv2 (found
 1234  * in the COPYING file in the root directory of this source tree).
 1235  * You may select, at your option, one of the above-listed licenses.
 1236  */
 1237 
 1238 #ifndef ZSTD_ERRORS_H_398273423
 1239 #define ZSTD_ERRORS_H_398273423
 1240 
 1241 #if defined (__cplusplus)
 1242 extern "C" {
 1243 #endif
 1244 
 1245 /* =====   ZSTDERRORLIB_API : control library symbols visibility   ===== */
 1246 #ifndef ZSTDERRORLIB_VISIBLE
 1247    /* Backwards compatibility with old macro name */
 1248 #  ifdef ZSTDERRORLIB_VISIBILITY
 1249 #    define ZSTDERRORLIB_VISIBLE ZSTDERRORLIB_VISIBILITY
 1250 #  elif defined(__GNUC__) && (__GNUC__ >= 4) && !defined(__MINGW32__)
 1251 #    define ZSTDERRORLIB_VISIBLE __attribute__ ((visibility ("default")))
 1252 #  else
 1253 #    define ZSTDERRORLIB_VISIBLE
 1254 #  endif
 1255 #endif
 1256 
 1257 #ifndef ZSTDERRORLIB_HIDDEN
 1258 #  if defined(__GNUC__) && (__GNUC__ >= 4) && !defined(__MINGW32__)
 1259 #    define ZSTDERRORLIB_HIDDEN __attribute__ ((visibility ("hidden")))
 1260 #  else
 1261 #    define ZSTDERRORLIB_HIDDEN
 1262 #  endif
 1263 #endif
 1264 
 1265 #if defined(ZSTD_DLL_EXPORT) && (ZSTD_DLL_EXPORT==1)
 1266 #  define ZSTDERRORLIB_API __declspec(dllexport) ZSTDERRORLIB_VISIBLE
 1267 #elif defined(ZSTD_DLL_IMPORT) && (ZSTD_DLL_IMPORT==1)
 1268 #  define ZSTDERRORLIB_API __declspec(dllimport) ZSTDERRORLIB_VISIBLE /* It isn't required but allows to generate better code, saving a function pointer load from the IAT and an indirect jump.*/
 1269 #else
 1270 #  define ZSTDERRORLIB_API ZSTDERRORLIB_VISIBLE
 1271 #endif
 1272 
 1273 /*-*********************************************
 1274  *  Error codes list
 1275  *-*********************************************
 1276  *  Error codes _values_ are pinned down since v1.3.1 only.
 1277  *  Therefore, don't rely on values if you may link to any version < v1.3.1.
 1278  *
 1279  *  Only values < 100 are considered stable.
 1280  *
 1281  *  note 1 : this API shall be used with static linking only.
 1282  *           dynamic linking is not yet officially supported.
 1283  *  note 2 : Prefer relying on the enum than on its value whenever possible
 1284  *           This is the only supported way to use the error list < v1.3.1
 1285  *  note 3 : ZSTD_isError() is always correct, whatever the library version.
 1286  **********************************************/
 1287 typedef enum {
 1288   ZSTD_error_no_error = 0,
 1289   ZSTD_error_GENERIC  = 1,
 1290   ZSTD_error_prefix_unknown                = 10,
 1291   ZSTD_error_version_unsupported           = 12,
 1292   ZSTD_error_frameParameter_unsupported    = 14,
 1293   ZSTD_error_frameParameter_windowTooLarge = 16,
 1294   ZSTD_error_corruption_detected = 20,
 1295   ZSTD_error_checksum_wrong      = 22,
 1296   ZSTD_error_literals_headerWrong = 24,
 1297   ZSTD_error_dictionary_corrupted      = 30,
 1298   ZSTD_error_dictionary_wrong          = 32,
 1299   ZSTD_error_dictionaryCreation_failed = 34,
 1300   ZSTD_error_parameter_unsupported   = 40,
 1301   ZSTD_error_parameter_combination_unsupported = 41,
 1302   ZSTD_error_parameter_outOfBound    = 42,
 1303   ZSTD_error_tableLog_tooLarge       = 44,
 1304   ZSTD_error_maxSymbolValue_tooLarge = 46,
 1305   ZSTD_error_maxSymbolValue_tooSmall = 48,
 1306   ZSTD_error_cannotProduce_uncompressedBlock = 49,
 1307   ZSTD_error_stabilityCondition_notRespected = 50,
 1308   ZSTD_error_stage_wrong       = 60,
 1309   ZSTD_error_init_missing      = 62,
 1310   ZSTD_error_memory_allocation = 64,
 1311   ZSTD_error_workSpace_tooSmall= 66,
 1312   ZSTD_error_dstSize_tooSmall = 70,
 1313   ZSTD_error_srcSize_wrong    = 72,
 1314   ZSTD_error_dstBuffer_null   = 74,
 1315   ZSTD_error_noForwardProgress_destFull = 80,
 1316   ZSTD_error_noForwardProgress_inputEmpty = 82,
 1317   /* following error codes are __NOT STABLE__, they can be removed or changed in future versions */
 1318   ZSTD_error_frameIndex_tooLarge = 100,
 1319   ZSTD_error_seekableIO          = 102,
 1320   ZSTD_error_dstBuffer_wrong     = 104,
 1321   ZSTD_error_srcBuffer_wrong     = 105,
 1322   ZSTD_error_sequenceProducer_failed = 106,
 1323   ZSTD_error_externalSequences_invalid = 107,
 1324   ZSTD_error_maxCode = 120  /* never EVER use this value directly, it can change in future versions! Use ZSTD_isError() instead */
 1325 } ZSTD_ErrorCode;
 1326 
 1327 /* ZSTDERRORLIB_API const char* ZSTD_getErrorString(ZSTD_ErrorCode code); */   /**< Same as ZSTD_getErrorName, but using a `ZSTD_ErrorCode` enum argument */
 1328 
 1329 
 1330 #if defined (__cplusplus)
 1331 }
 1332 #endif
 1333 
 1334 #endif /* ZSTD_ERRORS_H_398273423 */
 1335 
 1336 /*
 1337  * Copyright (c) Meta Platforms, Inc. and affiliates.
 1338  * All rights reserved.
 1339  *
 1340  * This source code is licensed under both the BSD-style license (found in the
 1341  * LICENSE file in the root directory of this source tree) and the GPLv2 (found
 1342  * in the COPYING file in the root directory of this source tree).
 1343  * You may select, at your option, one of the above-listed licenses.
 1344  */
 1345 
 1346 #ifndef ZSTD_ZDICT_H
 1347 #define ZSTD_ZDICT_H
 1348 
 1349 
 1350 /*======  Dependencies  ======*/
 1351 #include <stddef.h>  /* size_t */
 1352 
 1353 #if defined (__cplusplus)
 1354 extern "C" {
 1355 #endif
 1356 
 1357 /* =====   ZDICTLIB_API : control library symbols visibility   ===== */
 1358 #ifndef ZDICTLIB_VISIBLE
 1359    /* Backwards compatibility with old macro name */
 1360 #  ifdef ZDICTLIB_VISIBILITY
 1361 #    define ZDICTLIB_VISIBLE ZDICTLIB_VISIBILITY
 1362 #  elif defined(__GNUC__) && (__GNUC__ >= 4) && !defined(__MINGW32__)
 1363 #    define ZDICTLIB_VISIBLE __attribute__ ((visibility ("default")))
 1364 #  else
 1365 #    define ZDICTLIB_VISIBLE
 1366 #  endif
 1367 #endif
 1368 
 1369 #ifndef ZDICTLIB_HIDDEN
 1370 #  if defined(__GNUC__) && (__GNUC__ >= 4) && !defined(__MINGW32__)
 1371 #    define ZDICTLIB_HIDDEN __attribute__ ((visibility ("hidden")))
 1372 #  else
 1373 #    define ZDICTLIB_HIDDEN
 1374 #  endif
 1375 #endif
 1376 
 1377 #if defined(ZSTD_DLL_EXPORT) && (ZSTD_DLL_EXPORT==1)
 1378 #  define ZDICTLIB_API __declspec(dllexport) ZDICTLIB_VISIBLE
 1379 #elif defined(ZSTD_DLL_IMPORT) && (ZSTD_DLL_IMPORT==1)
 1380 #  define ZDICTLIB_API __declspec(dllimport) ZDICTLIB_VISIBLE /* It isn't required but allows to generate better code, saving a function pointer load from the IAT and an indirect jump.*/
 1381 #else
 1382 #  define ZDICTLIB_API ZDICTLIB_VISIBLE
 1383 #endif
 1384 
 1385 /*******************************************************************************
 1386  * Zstd dictionary builder
 1387  *
 1388  * FAQ
 1389  * ===
 1390  * Why should I use a dictionary?
 1391  * ------------------------------
 1392  *
 1393  * Zstd can use dictionaries to improve compression ratio of small data.
 1394  * Traditionally small files don't compress well because there is very little
 1395  * repetition in a single sample, since it is small. But, if you are compressing
 1396  * many similar files, like a bunch of JSON records that share the same
 1397  * structure, you can train a dictionary on ahead of time on some samples of
 1398  * these files. Then, zstd can use the dictionary to find repetitions that are
 1399  * present across samples. This can vastly improve compression ratio.
 1400  *
 1401  * When is a dictionary useful?
 1402  * ----------------------------
 1403  *
 1404  * Dictionaries are useful when compressing many small files that are similar.
 1405  * The larger a file is, the less benefit a dictionary will have. Generally,
 1406  * we don't expect dictionary compression to be effective past 100KB. And the
 1407  * smaller a file is, the more we would expect the dictionary to help.
 1408  *
 1409  * How do I use a dictionary?
 1410  * --------------------------
 1411  *
 1412  * Simply pass the dictionary to the zstd compressor with
 1413  * `ZSTD_CCtx_loadDictionary()`. The same dictionary must then be passed to
 1414  * the decompressor, using `ZSTD_DCtx_loadDictionary()`. There are other
 1415  * more advanced functions that allow selecting some options, see zstd.h for
 1416  * complete documentation.
 1417  *
 1418  * What is a zstd dictionary?
 1419  * --------------------------
 1420  *
 1421  * A zstd dictionary has two pieces: Its header, and its content. The header
 1422  * contains a magic number, the dictionary ID, and entropy tables. These
 1423  * entropy tables allow zstd to save on header costs in the compressed file,
 1424  * which really matters for small data. The content is just bytes, which are
 1425  * repeated content that is common across many samples.
 1426  *
 1427  * What is a raw content dictionary?
 1428  * ---------------------------------
 1429  *
 1430  * A raw content dictionary is just bytes. It doesn't have a zstd dictionary
 1431  * header, a dictionary ID, or entropy tables. Any buffer is a valid raw
 1432  * content dictionary.
 1433  *
 1434  * How do I train a dictionary?
 1435  * ----------------------------
 1436  *
 1437  * Gather samples from your use case. These samples should be similar to each
 1438  * other. If you have several use cases, you could try to train one dictionary
 1439  * per use case.
 1440  *
 1441  * Pass those samples to `ZDICT_trainFromBuffer()` and that will train your
 1442  * dictionary. There are a few advanced versions of this function, but this
 1443  * is a great starting point. If you want to further tune your dictionary
 1444  * you could try `ZDICT_optimizeTrainFromBuffer_cover()`. If that is too slow
 1445  * you can try `ZDICT_optimizeTrainFromBuffer_fastCover()`.
 1446  *
 1447  * If the dictionary training function fails, that is likely because you
 1448  * either passed too few samples, or a dictionary would not be effective
 1449  * for your data. Look at the messages that the dictionary trainer printed,
 1450  * if it doesn't say too few samples, then a dictionary would not be effective.
 1451  *
 1452  * How large should my dictionary be?
 1453  * ----------------------------------
 1454  *
 1455  * A reasonable dictionary size, the `dictBufferCapacity`, is about 100KB.
 1456  * The zstd CLI defaults to a 110KB dictionary. You likely don't need a
 1457  * dictionary larger than that. But, most use cases can get away with a
 1458  * smaller dictionary. The advanced dictionary builders can automatically
 1459  * shrink the dictionary for you, and select the smallest size that doesn't
 1460  * hurt compression ratio too much. See the `shrinkDict` parameter.
 1461  * A smaller dictionary can save memory, and potentially speed up
 1462  * compression.
 1463  *
 1464  * How many samples should I provide to the dictionary builder?
 1465  * ------------------------------------------------------------
 1466  *
 1467  * We generally recommend passing ~100x the size of the dictionary
 1468  * in samples. A few thousand should suffice. Having too few samples
 1469  * can hurt the dictionaries effectiveness. Having more samples will
 1470  * only improve the dictionaries effectiveness. But having too many
 1471  * samples can slow down the dictionary builder.
 1472  *
 1473  * How do I determine if a dictionary will be effective?
 1474  * -----------------------------------------------------
 1475  *
 1476  * Simply train a dictionary and try it out. You can use zstd's built in
 1477  * benchmarking tool to test the dictionary effectiveness.
 1478  *
 1479  *   # Benchmark levels 1-3 without a dictionary
 1480  *   zstd -b1e3 -r /path/to/my/files
 1481  *   # Benchmark levels 1-3 with a dictionary
 1482  *   zstd -b1e3 -r /path/to/my/files -D /path/to/my/dictionary
 1483  *
 1484  * When should I retrain a dictionary?
 1485  * -----------------------------------
 1486  *
 1487  * You should retrain a dictionary when its effectiveness drops. Dictionary
 1488  * effectiveness drops as the data you are compressing changes. Generally, we do
 1489  * expect dictionaries to "decay" over time, as your data changes, but the rate
 1490  * at which they decay depends on your use case. Internally, we regularly
 1491  * retrain dictionaries, and if the new dictionary performs significantly
 1492  * better than the old dictionary, we will ship the new dictionary.
 1493  *
 1494  * I have a raw content dictionary, how do I turn it into a zstd dictionary?
 1495  * -------------------------------------------------------------------------
 1496  *
 1497  * If you have a raw content dictionary, e.g. by manually constructing it, or
 1498  * using a third-party dictionary builder, you can turn it into a zstd
 1499  * dictionary by using `ZDICT_finalizeDictionary()`. You'll also have to
 1500  * provide some samples of the data. It will add the zstd header to the
 1501  * raw content, which contains a dictionary ID and entropy tables, which
 1502  * will improve compression ratio, and allow zstd to write the dictionary ID
 1503  * into the frame, if you so choose.
 1504  *
 1505  * Do I have to use zstd's dictionary builder?
 1506  * -------------------------------------------
 1507  *
 1508  * No! You can construct dictionary content however you please, it is just
 1509  * bytes. It will always be valid as a raw content dictionary. If you want
 1510  * a zstd dictionary, which can improve compression ratio, use
 1511  * `ZDICT_finalizeDictionary()`.
 1512  *
 1513  * What is the attack surface of a zstd dictionary?
 1514  * ------------------------------------------------
 1515  *
 1516  * Zstd is heavily fuzz tested, including loading fuzzed dictionaries, so
 1517  * zstd should never crash, or access out-of-bounds memory no matter what
 1518  * the dictionary is. However, if an attacker can control the dictionary
 1519  * during decompression, they can cause zstd to generate arbitrary bytes,
 1520  * just like if they controlled the compressed data.
 1521  *
 1522  ******************************************************************************/
 1523 
 1524 
 1525 /*! ZDICT_trainFromBuffer():
 1526  *  Train a dictionary from an array of samples.
 1527  *  Redirect towards ZDICT_optimizeTrainFromBuffer_fastCover() single-threaded, with d=8, steps=4,
 1528  *  f=20, and accel=1.
 1529  *  Samples must be stored concatenated in a single flat buffer `samplesBuffer`,
 1530  *  supplied with an array of sizes `samplesSizes`, providing the size of each sample, in order.
 1531  *  The resulting dictionary will be saved into `dictBuffer`.
 1532  * @return: size of dictionary stored into `dictBuffer` (<= `dictBufferCapacity`)
 1533  *          or an error code, which can be tested with ZDICT_isError().
 1534  *  Note:  Dictionary training will fail if there are not enough samples to construct a
 1535  *         dictionary, or if most of the samples are too small (< 8 bytes being the lower limit).
 1536  *         If dictionary training fails, you should use zstd without a dictionary, as the dictionary
 1537  *         would've been ineffective anyways. If you believe your samples would benefit from a dictionary
 1538  *         please open an issue with details, and we can look into it.
 1539  *  Note: ZDICT_trainFromBuffer()'s memory usage is about 6 MB.
 1540  *  Tips: In general, a reasonable dictionary has a size of ~ 100 KB.
 1541  *        It's possible to select smaller or larger size, just by specifying `dictBufferCapacity`.
 1542  *        In general, it's recommended to provide a few thousands samples, though this can vary a lot.
 1543  *        It's recommended that total size of all samples be about ~x100 times the target size of dictionary.
 1544  */
 1545 /* ZDICTLIB_API size_t ZDICT_trainFromBuffer(void* dictBuffer, size_t dictBufferCapacity,
 1546                                     const void* samplesBuffer,
 1547                                     const size_t* samplesSizes, unsigned nbSamples); */
 1548 
 1549 typedef struct {
 1550     int      compressionLevel;   /**< optimize for a specific zstd compression level; 0 means default */
 1551     unsigned notificationLevel;  /**< Write log to stderr; 0 = none (default); 1 = errors; 2 = progression; 3 = details; 4 = debug; */
 1552     unsigned dictID;             /**< force dictID value; 0 means auto mode (32-bits random value)
 1553                                   *   NOTE: The zstd format reserves some dictionary IDs for future use.
 1554                                   *         You may use them in private settings, but be warned that they
 1555                                   *         may be used by zstd in a public dictionary registry in the future.
 1556                                   *         These dictionary IDs are:
 1557                                   *           - low range  : <= 32767
 1558                                   *           - high range : >= (2^31)
 1559                                   */
 1560 } ZDICT_params_t;
 1561 
 1562 /*! ZDICT_finalizeDictionary():
 1563  * Given a custom content as a basis for dictionary, and a set of samples,
 1564  * finalize dictionary by adding headers and statistics according to the zstd
 1565  * dictionary format.
 1566  *
 1567  * Samples must be stored concatenated in a flat buffer `samplesBuffer`,
 1568  * supplied with an array of sizes `samplesSizes`, providing the size of each
 1569  * sample in order. The samples are used to construct the statistics, so they
 1570  * should be representative of what you will compress with this dictionary.
 1571  *
 1572  * The compression level can be set in `parameters`. You should pass the
 1573  * compression level you expect to use in production. The statistics for each
 1574  * compression level differ, so tuning the dictionary for the compression level
 1575  * can help quite a bit.
 1576  *
 1577  * You can set an explicit dictionary ID in `parameters`, or allow us to pick
 1578  * a random dictionary ID for you, but we can't guarantee no collisions.
 1579  *
 1580  * The dstDictBuffer and the dictContent may overlap, and the content will be
 1581  * appended to the end of the header. If the header + the content doesn't fit in
 1582  * maxDictSize the beginning of the content is truncated to make room, since it
 1583  * is presumed that the most profitable content is at the end of the dictionary,
 1584  * since that is the cheapest to reference.
 1585  *
 1586  * `maxDictSize` must be >= max(dictContentSize, ZDICT_DICTSIZE_MIN).
 1587  *
 1588  * @return: size of dictionary stored into `dstDictBuffer` (<= `maxDictSize`),
 1589  *          or an error code, which can be tested by ZDICT_isError().
 1590  * Note: ZDICT_finalizeDictionary() will push notifications into stderr if
 1591  *       instructed to, using notificationLevel>0.
 1592  * NOTE: This function currently may fail in several edge cases including:
 1593  *         * Not enough samples
 1594  *         * Samples are uncompressible
 1595  *         * Samples are all exactly the same
 1596  */
 1597 /* ZDICTLIB_API size_t ZDICT_finalizeDictionary(void* dstDictBuffer, size_t maxDictSize,
 1598                                 const void* dictContent, size_t dictContentSize,
 1599                                 const void* samplesBuffer, const size_t* samplesSizes, unsigned nbSamples,
 1600                                 ZDICT_params_t parameters); */
 1601 
 1602 
 1603 /*======   Helper functions   ======*/
 1604 /* ZDICTLIB_API unsigned ZDICT_getDictID(const void* dictBuffer, size_t dictSize); */  /**< extracts dictID; @return zero if error (not a valid dictionary) */
 1605 /* ZDICTLIB_API size_t ZDICT_getDictHeaderSize(const void* dictBuffer, size_t dictSize); */  /* returns dict header size; returns a ZSTD error code on failure */
 1606 /* ZDICTLIB_API unsigned ZDICT_isError(size_t errorCode); */
 1607 /* ZDICTLIB_API const char* ZDICT_getErrorName(size_t errorCode); */
 1608 
 1609 #if defined (__cplusplus)
 1610 }
 1611 #endif
 1612 
 1613 #endif   /* ZSTD_ZDICT_H */
 1614 
 1615 #endif /* LIBRARIES_ZSTD_H */