Team Ai
Datasetpublic

codekingpro/portable-devtools

sourceHugging Faceupdated 5mo agoView on Hugging Face
1likes14kdownloads
zstd.h3199 linesDownload Raw Back to include
1/*2 * Copyright (c) Meta Platforms, Inc. and affiliates.3 * All rights reserved.4 *5 * This source code is licensed under both the BSD-style license (found in the6 * LICENSE file in the root directory of this source tree) and the GPLv2 (found7 * in the COPYING file in the root directory of this source tree).8 * You may select, at your option, one of the above-listed licenses.9 */10 11#ifndef ZSTD_H_23544612#define ZSTD_H_23544613 14 15/* ======   Dependencies   ======*/16#include <stddef.h>   /* size_t */17 18#include "zstd_errors.h" /* list of errors */19#if defined(ZSTD_STATIC_LINKING_ONLY) && !defined(ZSTD_H_ZSTD_STATIC_LINKING_ONLY)20#include <limits.h>   /* INT_MAX */21#endif /* ZSTD_STATIC_LINKING_ONLY */22 23#if defined (__cplusplus)24extern "C" {25#endif26 27/* =====   ZSTDLIB_API : control library symbols visibility   ===== */28#ifndef ZSTDLIB_VISIBLE29   /* Backwards compatibility with old macro name */30#  ifdef ZSTDLIB_VISIBILITY31#    define ZSTDLIB_VISIBLE ZSTDLIB_VISIBILITY32#  elif defined(__GNUC__) && (__GNUC__ >= 4) && !defined(__MINGW32__)33#    define ZSTDLIB_VISIBLE __attribute__ ((visibility ("default")))34#  else35#    define ZSTDLIB_VISIBLE36#  endif37#endif38 39#ifndef ZSTDLIB_HIDDEN40#  if defined(__GNUC__) && (__GNUC__ >= 4) && !defined(__MINGW32__)41#    define ZSTDLIB_HIDDEN __attribute__ ((visibility ("hidden")))42#  else43#    define ZSTDLIB_HIDDEN44#  endif45#endif46 47#if defined(ZSTD_DLL_EXPORT) && (ZSTD_DLL_EXPORT==1)48#  define ZSTDLIB_API __declspec(dllexport) ZSTDLIB_VISIBLE49#elif defined(ZSTD_DLL_IMPORT) && (ZSTD_DLL_IMPORT==1)50#  define ZSTDLIB_API __declspec(dllimport) ZSTDLIB_VISIBLE /* It isn't required but allows to generate better code, saving a function pointer load from the IAT and an indirect jump.*/51#else52#  define ZSTDLIB_API ZSTDLIB_VISIBLE53#endif54 55/* Deprecation warnings :56 * Should these warnings be a problem, it is generally possible to disable them,57 * typically with -Wno-deprecated-declarations for gcc or _CRT_SECURE_NO_WARNINGS in Visual.58 * Otherwise, it's also possible to define ZSTD_DISABLE_DEPRECATE_WARNINGS.59 */60#ifdef ZSTD_DISABLE_DEPRECATE_WARNINGS61#  define ZSTD_DEPRECATED(message) /* disable deprecation warnings */62#else63#  if defined (__cplusplus) && (__cplusplus >= 201402) /* C++14 or greater */64#    define ZSTD_DEPRECATED(message) [[deprecated(message)]]65#  elif (defined(GNUC) && (GNUC > 4 || (GNUC == 4 && GNUC_MINOR >= 5))) || defined(__clang__) || defined(__IAR_SYSTEMS_ICC__)66#    define ZSTD_DEPRECATED(message) __attribute__((deprecated(message)))67#  elif defined(__GNUC__) && (__GNUC__ >= 3)68#    define ZSTD_DEPRECATED(message) __attribute__((deprecated))69#  elif defined(_MSC_VER)70#    define ZSTD_DEPRECATED(message) __declspec(deprecated(message))71#  else72#    pragma message("WARNING: You need to implement ZSTD_DEPRECATED for this compiler")73#    define ZSTD_DEPRECATED(message)74#  endif75#endif /* ZSTD_DISABLE_DEPRECATE_WARNINGS */76 77 78/*******************************************************************************79  Introduction80 81  zstd, short for Zstandard, is a fast lossless compression algorithm, targeting82  real-time compression scenarios at zlib-level and better compression ratios.83  The zstd compression library provides in-memory compression and decompression84  functions.85 86  The library supports regular compression levels from 1 up to ZSTD_maxCLevel(),87  which is currently 22. Levels >= 20, labeled `--ultra`, should be used with88  caution, as they require more memory. The library also offers negative89  compression levels, which extend the range of speed vs. ratio preferences.90  The lower the level, the faster the speed (at the cost of compression).91 92  Compression can be done in:93    - a single step (described as Simple API)94    - a single step, reusing a context (described as Explicit context)95    - unbounded multiple steps (described as Streaming compression)96 97  The compression ratio achievable on small data can be highly improved using98  a dictionary. Dictionary compression can be performed in:99    - a single step (described as Simple dictionary API)100    - a single step, reusing a dictionary (described as Bulk-processing101      dictionary API)102 103  Advanced experimental functions can be accessed using104  `#define ZSTD_STATIC_LINKING_ONLY` before including zstd.h.105 106  Advanced experimental APIs should never be used with a dynamically-linked107  library. They are not "stable"; their definitions or signatures may change in108  the future. Only static linking is allowed.109*******************************************************************************/110 111/*------   Version   ------*/112#define ZSTD_VERSION_MAJOR    1113#define ZSTD_VERSION_MINOR    5114#define ZSTD_VERSION_RELEASE  7115#define ZSTD_VERSION_NUMBER  (ZSTD_VERSION_MAJOR *100*100 + ZSTD_VERSION_MINOR *100 + ZSTD_VERSION_RELEASE)116 117/*! ZSTD_versionNumber() :118 *  Return runtime library version, the value is (MAJOR*100*100 + MINOR*100 + RELEASE). */119ZSTDLIB_API unsigned ZSTD_versionNumber(void);120 121#define ZSTD_LIB_VERSION ZSTD_VERSION_MAJOR.ZSTD_VERSION_MINOR.ZSTD_VERSION_RELEASE122#define ZSTD_QUOTE(str) #str123#define ZSTD_EXPAND_AND_QUOTE(str) ZSTD_QUOTE(str)124#define ZSTD_VERSION_STRING ZSTD_EXPAND_AND_QUOTE(ZSTD_LIB_VERSION)125 126/*! ZSTD_versionString() :127 *  Return runtime library version, like "1.4.5". Requires v1.3.0+. */128ZSTDLIB_API const char* ZSTD_versionString(void);129 130/* *************************************131 *  Default constant132 ***************************************/133#ifndef ZSTD_CLEVEL_DEFAULT134#  define ZSTD_CLEVEL_DEFAULT 3135#endif136 137/* *************************************138 *  Constants139 ***************************************/140 141/* All magic numbers are supposed read/written to/from files/memory using little-endian convention */142#define ZSTD_MAGICNUMBER            0xFD2FB528    /* valid since v0.8.0 */143#define ZSTD_MAGIC_DICTIONARY       0xEC30A437    /* valid since v0.7.0 */144#define ZSTD_MAGIC_SKIPPABLE_START  0x184D2A50    /* all 16 values, from 0x184D2A50 to 0x184D2A5F, signal the beginning of a skippable frame */145#define ZSTD_MAGIC_SKIPPABLE_MASK   0xFFFFFFF0146 147#define ZSTD_BLOCKSIZELOG_MAX  17148#define ZSTD_BLOCKSIZE_MAX     (1<<ZSTD_BLOCKSIZELOG_MAX)149 150 151/***************************************152*  Simple Core API153***************************************/154/*! ZSTD_compress() :155 *  Compresses `src` content as a single zstd compressed frame into already allocated `dst`.156 *  NOTE: Providing `dstCapacity >= ZSTD_compressBound(srcSize)` guarantees that zstd will have157 *        enough space to successfully compress the data.158 *  @return : compressed size written into `dst` (<= `dstCapacity),159 *            or an error code if it fails (which can be tested using ZSTD_isError()). */160ZSTDLIB_API size_t ZSTD_compress( void* dst, size_t dstCapacity,161                            const void* src, size_t srcSize,162                                  int compressionLevel);163 164/*! ZSTD_decompress() :165 * `compressedSize` : must be the _exact_ size of some number of compressed and/or skippable frames.166 *  Multiple compressed frames can be decompressed at once with this method.167 *  The result will be the concatenation of all decompressed frames, back to back.168 * `dstCapacity` is an upper bound of originalSize to regenerate.169 *  First frame's decompressed size can be extracted using ZSTD_getFrameContentSize().170 *  If maximum upper bound isn't known, prefer using streaming mode to decompress data.171 * @return : the number of bytes decompressed into `dst` (<= `dstCapacity`),172 *           or an errorCode if it fails (which can be tested using ZSTD_isError()). */173ZSTDLIB_API size_t ZSTD_decompress( void* dst, size_t dstCapacity,174                              const void* src, size_t compressedSize);175 176 177/*======  Decompression helper functions  ======*/178 179/*! ZSTD_getFrameContentSize() : requires v1.3.0+180 * `src` should point to the start of a ZSTD encoded frame.181 * `srcSize` must be at least as large as the frame header.182 *           hint : any size >= `ZSTD_frameHeaderSize_max` is large enough.183 * @return : - decompressed size of `src` frame content, if known184 *           - ZSTD_CONTENTSIZE_UNKNOWN if the size cannot be determined185 *           - ZSTD_CONTENTSIZE_ERROR if an error occurred (e.g. invalid magic number, srcSize too small)186 *  note 1 : a 0 return value means the frame is valid but "empty".187 *           When invoking this method on a skippable frame, it will return 0.188 *  note 2 : decompressed size is an optional field, it may not be present (typically in streaming mode).189 *           When `return==ZSTD_CONTENTSIZE_UNKNOWN`, data to decompress could be any size.190 *           In which case, it's necessary to use streaming mode to decompress data.191 *           Optionally, application can rely on some implicit limit,192 *           as ZSTD_decompress() only needs an upper bound of decompressed size.193 *           (For example, data could be necessarily cut into blocks <= 16 KB).194 *  note 3 : decompressed size is always present when compression is completed using single-pass functions,195 *           such as ZSTD_compress(), ZSTD_compressCCtx() ZSTD_compress_usingDict() or ZSTD_compress_usingCDict().196 *  note 4 : decompressed size can be very large (64-bits value),197 *           potentially larger than what local system can handle as a single memory segment.198 *           In which case, it's necessary to use streaming mode to decompress data.199 *  note 5 : If source is untrusted, decompressed size could be wrong or intentionally modified.200 *           Always ensure return value fits within application's authorized limits.201 *           Each application can set its own limits.202 *  note 6 : This function replaces ZSTD_getDecompressedSize() */203#define ZSTD_CONTENTSIZE_UNKNOWN (0ULL - 1)204#define ZSTD_CONTENTSIZE_ERROR   (0ULL - 2)205ZSTDLIB_API unsigned long long ZSTD_getFrameContentSize(const void *src, size_t srcSize);206 207/*! ZSTD_getDecompressedSize() (obsolete):208 *  This function is now obsolete, in favor of ZSTD_getFrameContentSize().209 *  Both functions work the same way, but ZSTD_getDecompressedSize() blends210 *  "empty", "unknown" and "error" results to the same return value (0),211 *  while ZSTD_getFrameContentSize() gives them separate return values.212 * @return : decompressed size of `src` frame content _if known and not empty_, 0 otherwise. */213ZSTD_DEPRECATED("Replaced by ZSTD_getFrameContentSize")214ZSTDLIB_API unsigned long long ZSTD_getDecompressedSize(const void* src, size_t srcSize);215 216/*! ZSTD_findFrameCompressedSize() : Requires v1.4.0+217 * `src` should point to the start of a ZSTD frame or skippable frame.218 * `srcSize` must be >= first frame size219 * @return : the compressed size of the first frame starting at `src`,220 *           suitable to pass as `srcSize` to `ZSTD_decompress` or similar,221 *           or an error code if input is invalid222 *  Note 1: this method is called _find*() because it's not enough to read the header,223 *          it may have to scan through the frame's content, to reach its end.224 *  Note 2: this method also works with Skippable Frames. In which case,225 *          it returns the size of the complete skippable frame,226 *          which is always equal to its content size + 8 bytes for headers. */227ZSTDLIB_API size_t ZSTD_findFrameCompressedSize(const void* src, size_t srcSize);228 229 230/*======  Compression helper functions  ======*/231 232/*! ZSTD_compressBound() :233 * maximum compressed size in worst case single-pass scenario.234 * When invoking `ZSTD_compress()`, or any other one-pass compression function,235 * it's recommended to provide @dstCapacity >= ZSTD_compressBound(srcSize)236 * as it eliminates one potential failure scenario,237 * aka not enough room in dst buffer to write the compressed frame.238 * Note : ZSTD_compressBound() itself can fail, if @srcSize >= ZSTD_MAX_INPUT_SIZE .239 *        In which case, ZSTD_compressBound() will return an error code240 *        which can be tested using ZSTD_isError().241 *242 * ZSTD_COMPRESSBOUND() :243 * same as ZSTD_compressBound(), but as a macro.244 * It can be used to produce constants, which can be useful for static allocation,245 * for example to size a static array on stack.246 * Will produce constant value 0 if srcSize is too large.247 */248#define ZSTD_MAX_INPUT_SIZE ((sizeof(size_t)==8) ? 0xFF00FF00FF00FF00ULL : 0xFF00FF00U)249#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 */250ZSTDLIB_API size_t ZSTD_compressBound(size_t srcSize); /*!< maximum compressed size in worst case single-pass scenario */251 252 253/*======  Error helper functions  ======*/254/* ZSTD_isError() :255 * Most ZSTD_* functions returning a size_t value can be tested for error,256 * using ZSTD_isError().257 * @return 1 if error, 0 otherwise258 */259ZSTDLIB_API unsigned     ZSTD_isError(size_t result);      /*!< tells if a `size_t` function result is an error code */260ZSTDLIB_API ZSTD_ErrorCode ZSTD_getErrorCode(size_t functionResult); /* convert a result into an error code, which can be compared to error enum list */261ZSTDLIB_API const char*  ZSTD_getErrorName(size_t result); /*!< provides readable string from a function result */262ZSTDLIB_API int          ZSTD_minCLevel(void);             /*!< minimum negative compression level allowed, requires v1.4.0+ */263ZSTDLIB_API int          ZSTD_maxCLevel(void);             /*!< maximum compression level available */264ZSTDLIB_API int          ZSTD_defaultCLevel(void);         /*!< default compression level, specified by ZSTD_CLEVEL_DEFAULT, requires v1.5.0+ */265 266 267/***************************************268*  Explicit context269***************************************/270/*= Compression context271 *  When compressing many times,272 *  it is recommended to allocate a compression context just once,273 *  and reuse it for each successive compression operation.274 *  This will make the workload easier for system's memory.275 *  Note : re-using context is just a speed / resource optimization.276 *         It doesn't change the compression ratio, which remains identical.277 *  Note 2: For parallel execution in multi-threaded environments,278 *         use one different context per thread .279 */280typedef struct ZSTD_CCtx_s ZSTD_CCtx;281ZSTDLIB_API ZSTD_CCtx* ZSTD_createCCtx(void);282ZSTDLIB_API size_t     ZSTD_freeCCtx(ZSTD_CCtx* cctx);  /* compatible with NULL pointer */283 284/*! ZSTD_compressCCtx() :285 *  Same as ZSTD_compress(), using an explicit ZSTD_CCtx.286 *  Important : in order to mirror `ZSTD_compress()` behavior,287 *  this function compresses at the requested compression level,288 *  __ignoring any other advanced parameter__ .289 *  If any advanced parameter was set using the advanced API,290 *  they will all be reset. Only @compressionLevel remains.291 */292ZSTDLIB_API size_t ZSTD_compressCCtx(ZSTD_CCtx* cctx,293                                     void* dst, size_t dstCapacity,294                               const void* src, size_t srcSize,295                                     int compressionLevel);296 297/*= Decompression context298 *  When decompressing many times,299 *  it is recommended to allocate a context only once,300 *  and reuse it for each successive compression operation.301 *  This will make workload friendlier for system's memory.302 *  Use one context per thread for parallel execution. */303typedef struct ZSTD_DCtx_s ZSTD_DCtx;304ZSTDLIB_API ZSTD_DCtx* ZSTD_createDCtx(void);305ZSTDLIB_API size_t     ZSTD_freeDCtx(ZSTD_DCtx* dctx);  /* accept NULL pointer */306 307/*! ZSTD_decompressDCtx() :308 *  Same as ZSTD_decompress(),309 *  requires an allocated ZSTD_DCtx.310 *  Compatible with sticky parameters (see below).311 */312ZSTDLIB_API size_t ZSTD_decompressDCtx(ZSTD_DCtx* dctx,313                                       void* dst, size_t dstCapacity,314                                 const void* src, size_t srcSize);315 316 317/*********************************************318*  Advanced compression API (Requires v1.4.0+)319**********************************************/320 321/* API design :322 *   Parameters are pushed one by one into an existing context,323 *   using ZSTD_CCtx_set*() functions.324 *   Pushed parameters are sticky : they are valid for next compressed frame, and any subsequent frame.325 *   "sticky" parameters are applicable to `ZSTD_compress2()` and `ZSTD_compressStream*()` !326 *   __They do not apply to one-shot variants such as ZSTD_compressCCtx()__ .327 *328 *   It's possible to reset all parameters to "default" using ZSTD_CCtx_reset().329 *330 *   This API supersedes all other "advanced" API entry points in the experimental section.331 *   In the future, we expect to remove API entry points from experimental which are redundant with this API.332 */333 334 335/* Compression strategies, listed from fastest to strongest */336typedef enum { ZSTD_fast=1,337               ZSTD_dfast=2,338               ZSTD_greedy=3,339               ZSTD_lazy=4,340               ZSTD_lazy2=5,341               ZSTD_btlazy2=6,342               ZSTD_btopt=7,343               ZSTD_btultra=8,344               ZSTD_btultra2=9345               /* note : new strategies _might_ be added in the future.346                         Only the order (from fast to strong) is guaranteed */347} ZSTD_strategy;348 349typedef enum {350 351    /* compression parameters352     * Note: When compressing with a ZSTD_CDict these parameters are superseded353     * by the parameters used to construct the ZSTD_CDict.354     * See ZSTD_CCtx_refCDict() for more info (superseded-by-cdict). */355    ZSTD_c_compressionLevel=100, /* Set compression parameters according to pre-defined cLevel table.356                              * Note that exact compression parameters are dynamically determined,357                              * depending on both compression level and srcSize (when known).358                              * Default level is ZSTD_CLEVEL_DEFAULT==3.359                              * Special: value 0 means default, which is controlled by ZSTD_CLEVEL_DEFAULT.360                              * Note 1 : it's possible to pass a negative compression level.361                              * Note 2 : setting a level does not automatically set all other compression parameters362                              *   to default. Setting this will however eventually dynamically impact the compression363                              *   parameters which have not been manually set. The manually set364                              *   ones will 'stick'. */365    /* Advanced compression parameters :366     * It's possible to pin down compression parameters to some specific values.367     * In which case, these values are no longer dynamically selected by the compressor */368    ZSTD_c_windowLog=101,    /* Maximum allowed back-reference distance, expressed as power of 2.369                              * This will set a memory budget for streaming decompression,370                              * with larger values requiring more memory371                              * and typically compressing more.372                              * Must be clamped between ZSTD_WINDOWLOG_MIN and ZSTD_WINDOWLOG_MAX.373                              * Special: value 0 means "use default windowLog".374                              * Note: Using a windowLog greater than ZSTD_WINDOWLOG_LIMIT_DEFAULT375                              *       requires explicitly allowing such size at streaming decompression stage. */376    ZSTD_c_hashLog=102,      /* Size of the initial probe table, as a power of 2.377                              * Resulting memory usage is (1 << (hashLog+2)).378                              * Must be clamped between ZSTD_HASHLOG_MIN and ZSTD_HASHLOG_MAX.379                              * Larger tables improve compression ratio of strategies <= dFast,380                              * and improve speed of strategies > dFast.381                              * Special: value 0 means "use default hashLog". */382    ZSTD_c_chainLog=103,     /* Size of the multi-probe search table, as a power of 2.383                              * Resulting memory usage is (1 << (chainLog+2)).384                              * Must be clamped between ZSTD_CHAINLOG_MIN and ZSTD_CHAINLOG_MAX.385                              * Larger tables result in better and slower compression.386                              * This parameter is useless for "fast" strategy.387                              * It's still useful when using "dfast" strategy,388                              * in which case it defines a secondary probe table.389                              * Special: value 0 means "use default chainLog". */390    ZSTD_c_searchLog=104,    /* Number of search attempts, as a power of 2.391                              * More attempts result in better and slower compression.392                              * This parameter is useless for "fast" and "dFast" strategies.393                              * Special: value 0 means "use default searchLog". */394    ZSTD_c_minMatch=105,     /* Minimum size of searched matches.395                              * Note that Zstandard can still find matches of smaller size,396                              * it just tweaks its search algorithm to look for this size and larger.397                              * Larger values increase compression and decompression speed, but decrease ratio.398                              * Must be clamped between ZSTD_MINMATCH_MIN and ZSTD_MINMATCH_MAX.399                              * Note that currently, for all strategies < btopt, effective minimum is 4.400                              *                    , for all strategies > fast, effective maximum is 6.401                              * Special: value 0 means "use default minMatchLength". */402    ZSTD_c_targetLength=106, /* Impact of this field depends on strategy.403                              * For strategies btopt, btultra & btultra2:404                              *     Length of Match considered "good enough" to stop search.405                              *     Larger values make compression stronger, and slower.406                              * For strategy fast:407                              *     Distance between match sampling.408                              *     Larger values make compression faster, and weaker.409                              * Special: value 0 means "use default targetLength". */410    ZSTD_c_strategy=107,     /* See ZSTD_strategy enum definition.411                              * The higher the value of selected strategy, the more complex it is,412                              * resulting in stronger and slower compression.413                              * Special: value 0 means "use default strategy". */414 415    ZSTD_c_targetCBlockSize=130, /* v1.5.6+416                                  * Attempts to fit compressed block size into approximately targetCBlockSize.417                                  * Bound by ZSTD_TARGETCBLOCKSIZE_MIN and ZSTD_TARGETCBLOCKSIZE_MAX.418                                  * Note that it's not a guarantee, just a convergence target (default:0).419                                  * No target when targetCBlockSize == 0.420                                  * This is helpful in low bandwidth streaming environments to improve end-to-end latency,421                                  * when a client can make use of partial documents (a prominent example being Chrome).422                                  * Note: this parameter is stable since v1.5.6.423                                  * It was present as an experimental parameter in earlier versions,424                                  * but it's not recommended using it with earlier library versions425                                  * due to massive performance regressions.426                                  */427    /* LDM mode parameters */428    ZSTD_c_enableLongDistanceMatching=160, /* Enable long distance matching.429                                     * This parameter is designed to improve compression ratio430                                     * for large inputs, by finding large matches at long distance.431                                     * It increases memory usage and window size.432                                     * Note: enabling this parameter increases default ZSTD_c_windowLog to 128 MB433                                     * except when expressly set to a different value.434                                     * Note: will be enabled by default if ZSTD_c_windowLog >= 128 MB and435                                     * compression strategy >= ZSTD_btopt (== compression level 16+) */436    ZSTD_c_ldmHashLog=161,   /* Size of the table for long distance matching, as a power of 2.437                              * Larger values increase memory usage and compression ratio,438                              * but decrease compression speed.439                              * Must be clamped between ZSTD_HASHLOG_MIN and ZSTD_HASHLOG_MAX440                              * default: windowlog - 7.441                              * Special: value 0 means "automatically determine hashlog". */442    ZSTD_c_ldmMinMatch=162,  /* Minimum match size for long distance matcher.443                              * Larger/too small values usually decrease compression ratio.444                              * Must be clamped between ZSTD_LDM_MINMATCH_MIN and ZSTD_LDM_MINMATCH_MAX.445                              * Special: value 0 means "use default value" (default: 64). */446    ZSTD_c_ldmBucketSizeLog=163, /* Log size of each bucket in the LDM hash table for collision resolution.447                              * Larger values improve collision resolution but decrease compression speed.448                              * The maximum value is ZSTD_LDM_BUCKETSIZELOG_MAX.449                              * Special: value 0 means "use default value" (default: 3). */450    ZSTD_c_ldmHashRateLog=164, /* Frequency of inserting/looking up entries into the LDM hash table.451                              * Must be clamped between 0 and (ZSTD_WINDOWLOG_MAX - ZSTD_HASHLOG_MIN).452                              * Default is MAX(0, (windowLog - ldmHashLog)), optimizing hash table usage.453                              * Larger values improve compression speed.454                              * Deviating far from default value will likely result in a compression ratio decrease.455                              * Special: value 0 means "automatically determine hashRateLog". */456 457    /* frame parameters */458    ZSTD_c_contentSizeFlag=200, /* Content size will be written into frame header _whenever known_ (default:1)459                              * Content size must be known at the beginning of compression.460                              * This is automatically the case when using ZSTD_compress2(),461                              * For streaming scenarios, content size must be provided with ZSTD_CCtx_setPledgedSrcSize() */462    ZSTD_c_checksumFlag=201, /* A 32-bits checksum of content is written at end of frame (default:0) */463    ZSTD_c_dictIDFlag=202,   /* When applicable, dictionary's ID is written into frame header (default:1) */464 465    /* multi-threading parameters */466    /* These parameters are only active if multi-threading is enabled (compiled with build macro ZSTD_MULTITHREAD).467     * Otherwise, trying to set any other value than default (0) will be a no-op and return an error.468     * In a situation where it's unknown if the linked library supports multi-threading or not,469     * setting ZSTD_c_nbWorkers to any value >= 1 and consulting the return value provides a quick way to check this property.470     */471    ZSTD_c_nbWorkers=400,    /* Select how many threads will be spawned to compress in parallel.472                              * When nbWorkers >= 1, triggers asynchronous mode when invoking ZSTD_compressStream*() :473                              * ZSTD_compressStream*() consumes input and flush output if possible, but immediately gives back control to caller,474                              * while compression is performed in parallel, within worker thread(s).475                              * (note : a strong exception to this rule is when first invocation of ZSTD_compressStream2() sets ZSTD_e_end :476                              *  in which case, ZSTD_compressStream2() delegates to ZSTD_compress2(), which is always a blocking call).477                              * More workers improve speed, but also increase memory usage.478                              * Default value is `0`, aka "single-threaded mode" : no worker is spawned,479                              * compression is performed inside Caller's thread, and all invocations are blocking */480    ZSTD_c_jobSize=401,      /* Size of a compression job. This value is enforced only when nbWorkers >= 1.481                              * Each compression job is completed in parallel, so this value can indirectly impact the nb of active threads.482                              * 0 means default, which is dynamically determined based on compression parameters.483                              * Job size must be a minimum of overlap size, or ZSTDMT_JOBSIZE_MIN (= 512 KB), whichever is largest.484                              * The minimum size is automatically and transparently enforced. */485    ZSTD_c_overlapLog=402,   /* Control the overlap size, as a fraction of window size.486                              * The overlap size is an amount of data reloaded from previous job at the beginning of a new job.487                              * It helps preserve compression ratio, while each job is compressed in parallel.488                              * This value is enforced only when nbWorkers >= 1.489                              * Larger values increase compression ratio, but decrease speed.490                              * Possible values range from 0 to 9 :491                              * - 0 means "default" : value will be determined by the library, depending on strategy492                              * - 1 means "no overlap"493                              * - 9 means "full overlap", using a full window size.494                              * Each intermediate rank increases/decreases load size by a factor 2 :495                              * 9: full window;  8: w/2;  7: w/4;  6: w/8;  5:w/16;  4: w/32;  3:w/64;  2:w/128;  1:no overlap;  0:default496                              * default value varies between 6 and 9, depending on strategy */497 498    /* note : additional experimental parameters are also available499     * within the experimental section of the API.500     * At the time of this writing, they include :501     * ZSTD_c_rsyncable502     * ZSTD_c_format503     * ZSTD_c_forceMaxWindow504     * ZSTD_c_forceAttachDict505     * ZSTD_c_literalCompressionMode506     * ZSTD_c_srcSizeHint507     * ZSTD_c_enableDedicatedDictSearch508     * ZSTD_c_stableInBuffer509     * ZSTD_c_stableOutBuffer510     * ZSTD_c_blockDelimiters511     * ZSTD_c_validateSequences512     * ZSTD_c_blockSplitterLevel513     * ZSTD_c_splitAfterSequences514     * ZSTD_c_useRowMatchFinder515     * ZSTD_c_prefetchCDictTables516     * ZSTD_c_enableSeqProducerFallback517     * ZSTD_c_maxBlockSize518     * Because they are not stable, it's necessary to define ZSTD_STATIC_LINKING_ONLY to access them.519     * note : never ever use experimentalParam? names directly;520     *        also, the enums values themselves are unstable and can still change.521     */522     ZSTD_c_experimentalParam1=500,523     ZSTD_c_experimentalParam2=10,524     ZSTD_c_experimentalParam3=1000,525     ZSTD_c_experimentalParam4=1001,526     ZSTD_c_experimentalParam5=1002,527     /* was ZSTD_c_experimentalParam6=1003; is now ZSTD_c_targetCBlockSize */528     ZSTD_c_experimentalParam7=1004,529     ZSTD_c_experimentalParam8=1005,530     ZSTD_c_experimentalParam9=1006,531     ZSTD_c_experimentalParam10=1007,532     ZSTD_c_experimentalParam11=1008,533     ZSTD_c_experimentalParam12=1009,534     ZSTD_c_experimentalParam13=1010,535     ZSTD_c_experimentalParam14=1011,536     ZSTD_c_experimentalParam15=1012,537     ZSTD_c_experimentalParam16=1013,538     ZSTD_c_experimentalParam17=1014,539     ZSTD_c_experimentalParam18=1015,540     ZSTD_c_experimentalParam19=1016,541     ZSTD_c_experimentalParam20=1017542} ZSTD_cParameter;543 544typedef struct {545    size_t error;546    int lowerBound;547    int upperBound;548} ZSTD_bounds;549 550/*! ZSTD_cParam_getBounds() :551 *  All parameters must belong to an interval with lower and upper bounds,552 *  otherwise they will either trigger an error or be automatically clamped.553 * @return : a structure, ZSTD_bounds, which contains554 *         - an error status field, which must be tested using ZSTD_isError()555 *         - lower and upper bounds, both inclusive556 */557ZSTDLIB_API ZSTD_bounds ZSTD_cParam_getBounds(ZSTD_cParameter cParam);558 559/*! ZSTD_CCtx_setParameter() :560 *  Set one compression parameter, selected by enum ZSTD_cParameter.561 *  All parameters have valid bounds. Bounds can be queried using ZSTD_cParam_getBounds().562 *  Providing a value beyond bound will either clamp it, or trigger an error (depending on parameter).563 *  Setting a parameter is generally only possible during frame initialization (before starting compression).564 *  Exception : when using multi-threading mode (nbWorkers >= 1),565 *              the following parameters can be updated _during_ compression (within same frame):566 *              => compressionLevel, hashLog, chainLog, searchLog, minMatch, targetLength and strategy.567 *              new parameters will be active for next job only (after a flush()).568 * @return : an error code (which can be tested using ZSTD_isError()).569 */570ZSTDLIB_API size_t ZSTD_CCtx_setParameter(ZSTD_CCtx* cctx, ZSTD_cParameter param, int value);571 572/*! ZSTD_CCtx_setPledgedSrcSize() :573 *  Total input data size to be compressed as a single frame.574 *  Value will be written in frame header, unless if explicitly forbidden using ZSTD_c_contentSizeFlag.575 *  This value will also be controlled at end of frame, and trigger an error if not respected.576 * @result : 0, or an error code (which can be tested with ZSTD_isError()).577 *  Note 1 : pledgedSrcSize==0 actually means zero, aka an empty frame.578 *           In order to mean "unknown content size", pass constant ZSTD_CONTENTSIZE_UNKNOWN.579 *           ZSTD_CONTENTSIZE_UNKNOWN is default value for any new frame.580 *  Note 2 : pledgedSrcSize is only valid once, for the next frame.581 *           It's discarded at the end of the frame, and replaced by ZSTD_CONTENTSIZE_UNKNOWN.582 *  Note 3 : Whenever all input data is provided and consumed in a single round,583 *           for example with ZSTD_compress2(),584 *           or invoking immediately ZSTD_compressStream2(,,,ZSTD_e_end),585 *           this value is automatically overridden by srcSize instead.586 */587ZSTDLIB_API size_t ZSTD_CCtx_setPledgedSrcSize(ZSTD_CCtx* cctx, unsigned long long pledgedSrcSize);588 589typedef enum {590    ZSTD_reset_session_only = 1,591    ZSTD_reset_parameters = 2,592    ZSTD_reset_session_and_parameters = 3593} ZSTD_ResetDirective;594 595/*! ZSTD_CCtx_reset() :596 *  There are 2 different things that can be reset, independently or jointly :597 *  - The session : will stop compressing current frame, and make CCtx ready to start a new one.598 *                  Useful after an error, or to interrupt any ongoing compression.599 *                  Any internal data not yet flushed is cancelled.600 *                  Compression parameters and dictionary remain unchanged.601 *                  They will be used to compress next frame.602 *                  Resetting session never fails.603 *  - The parameters : changes all parameters back to "default".604 *                  This also removes any reference to any dictionary or external sequence producer.605 *                  Parameters can only be changed between 2 sessions (i.e. no compression is currently ongoing)606 *                  otherwise the reset fails, and function returns an error value (which can be tested using ZSTD_isError())607 *  - Both : similar to resetting the session, followed by resetting parameters.608 */609ZSTDLIB_API size_t ZSTD_CCtx_reset(ZSTD_CCtx* cctx, ZSTD_ResetDirective reset);610 611/*! ZSTD_compress2() :612 *  Behave the same as ZSTD_compressCCtx(), but compression parameters are set using the advanced API.613 *  (note that this entry point doesn't even expose a compression level parameter).614 *  ZSTD_compress2() always starts a new frame.615 *  Should cctx hold data from a previously unfinished frame, everything about it is forgotten.616 *  - Compression parameters are pushed into CCtx before starting compression, using ZSTD_CCtx_set*()617 *  - The function is always blocking, returns when compression is completed.618 *  NOTE: Providing `dstCapacity >= ZSTD_compressBound(srcSize)` guarantees that zstd will have619 *        enough space to successfully compress the data, though it is possible it fails for other reasons.620 * @return : compressed size written into `dst` (<= `dstCapacity),621 *           or an error code if it fails (which can be tested using ZSTD_isError()).622 */623ZSTDLIB_API size_t ZSTD_compress2( ZSTD_CCtx* cctx,624                                   void* dst, size_t dstCapacity,625                             const void* src, size_t srcSize);626 627 628/***********************************************629*  Advanced decompression API (Requires v1.4.0+)630************************************************/631 632/* The advanced API pushes parameters one by one into an existing DCtx context.633 * Parameters are sticky, and remain valid for all following frames634 * using the same DCtx context.635 * It's possible to reset parameters to default values using ZSTD_DCtx_reset().636 * Note : This API is compatible with existing ZSTD_decompressDCtx() and ZSTD_decompressStream().637 *        Therefore, no new decompression function is necessary.638 */639 640typedef enum {641 642    ZSTD_d_windowLogMax=100, /* Select a size limit (in power of 2) beyond which643                              * the streaming API will refuse to allocate memory buffer644                              * in order to protect the host from unreasonable memory requirements.645                              * This parameter is only useful in streaming mode, since no internal buffer is allocated in single-pass mode.646                              * By default, a decompression context accepts window sizes <= (1 << ZSTD_WINDOWLOG_LIMIT_DEFAULT).647                              * Special: value 0 means "use default maximum windowLog". */648 649    /* note : additional experimental parameters are also available650     * within the experimental section of the API.651     * At the time of this writing, they include :652     * ZSTD_d_format653     * ZSTD_d_stableOutBuffer654     * ZSTD_d_forceIgnoreChecksum655     * ZSTD_d_refMultipleDDicts656     * ZSTD_d_disableHuffmanAssembly657     * ZSTD_d_maxBlockSize658     * Because they are not stable, it's necessary to define ZSTD_STATIC_LINKING_ONLY to access them.659     * note : never ever use experimentalParam? names directly660     */661     ZSTD_d_experimentalParam1=1000,662     ZSTD_d_experimentalParam2=1001,663     ZSTD_d_experimentalParam3=1002,664     ZSTD_d_experimentalParam4=1003,665     ZSTD_d_experimentalParam5=1004,666     ZSTD_d_experimentalParam6=1005667 668} ZSTD_dParameter;669 670/*! ZSTD_dParam_getBounds() :671 *  All parameters must belong to an interval with lower and upper bounds,672 *  otherwise they will either trigger an error or be automatically clamped.673 * @return : a structure, ZSTD_bounds, which contains674 *         - an error status field, which must be tested using ZSTD_isError()675 *         - both lower and upper bounds, inclusive676 */677ZSTDLIB_API ZSTD_bounds ZSTD_dParam_getBounds(ZSTD_dParameter dParam);678 679/*! ZSTD_DCtx_setParameter() :680 *  Set one compression parameter, selected by enum ZSTD_dParameter.681 *  All parameters have valid bounds. Bounds can be queried using ZSTD_dParam_getBounds().682 *  Providing a value beyond bound will either clamp it, or trigger an error (depending on parameter).683 *  Setting a parameter is only possible during frame initialization (before starting decompression).684 * @return : 0, or an error code (which can be tested using ZSTD_isError()).685 */686ZSTDLIB_API size_t ZSTD_DCtx_setParameter(ZSTD_DCtx* dctx, ZSTD_dParameter param, int value);687 688/*! ZSTD_DCtx_reset() :689 *  Return a DCtx to clean state.690 *  Session and parameters can be reset jointly or separately.691 *  Parameters can only be reset when no active frame is being decompressed.692 * @return : 0, or an error code, which can be tested with ZSTD_isError()693 */694ZSTDLIB_API size_t ZSTD_DCtx_reset(ZSTD_DCtx* dctx, ZSTD_ResetDirective reset);695 696 697/****************************698*  Streaming699****************************/700 701typedef struct ZSTD_inBuffer_s {702  const void* src;    /**< start of input buffer */703  size_t size;        /**< size of input buffer */704  size_t pos;         /**< position where reading stopped. Will be updated. Necessarily 0 <= pos <= size */705} ZSTD_inBuffer;706 707typedef struct ZSTD_outBuffer_s {708  void*  dst;         /**< start of output buffer */709  size_t size;        /**< size of output buffer */710  size_t pos;         /**< position where writing stopped. Will be updated. Necessarily 0 <= pos <= size */711} ZSTD_outBuffer;712 713 714 715/*-***********************************************************************716*  Streaming compression - HowTo717*718*  A ZSTD_CStream object is required to track streaming operation.719*  Use ZSTD_createCStream() and ZSTD_freeCStream() to create/release resources.720*  ZSTD_CStream objects can be reused multiple times on consecutive compression operations.721*  It is recommended to reuse ZSTD_CStream since it will play nicer with system's memory, by re-using already allocated memory.722*723*  For parallel execution, use one separate ZSTD_CStream per thread.724*725*  note : since v1.3.0, ZSTD_CStream and ZSTD_CCtx are the same thing.726*727*  Parameters are sticky : when starting a new compression on the same context,728*  it will reuse the same sticky parameters as previous compression session.729*  When in doubt, it's recommended to fully initialize the context before usage.730*  Use ZSTD_CCtx_reset() to reset the context and ZSTD_CCtx_setParameter(),731*  ZSTD_CCtx_setPledgedSrcSize(), or ZSTD_CCtx_loadDictionary() and friends to732*  set more specific parameters, the pledged source size, or load a dictionary.733*734*  Use ZSTD_compressStream2() with ZSTD_e_continue as many times as necessary to735*  consume input stream. The function will automatically update both `pos`736*  fields within `input` and `output`.737*  Note that the function may not consume the entire input, for example, because738*  the output buffer is already full, in which case `input.pos < input.size`.739*  The caller must check if input has been entirely consumed.740*  If not, the caller must make some room to receive more compressed data,741*  and then present again remaining input data.742*  note: ZSTD_e_continue is guaranteed to make some forward progress when called,743*        but doesn't guarantee maximal forward progress. This is especially relevant744*        when compressing with multiple threads. The call won't block if it can745*        consume some input, but if it can't it will wait for some, but not all,746*        output to be flushed.747* @return : provides a minimum amount of data remaining to be flushed from internal buffers748*           or an error code, which can be tested using ZSTD_isError().749*750*  At any moment, it's possible to flush whatever data might remain stuck within internal buffer,751*  using ZSTD_compressStream2() with ZSTD_e_flush. `output->pos` will be updated.752*  Note that, if `output->size` is too small, a single invocation with ZSTD_e_flush might not be enough (return code > 0).753*  In which case, make some room to receive more compressed data, and call again ZSTD_compressStream2() with ZSTD_e_flush.754*  You must continue calling ZSTD_compressStream2() with ZSTD_e_flush until it returns 0, at which point you can change the755*  operation.756*  note: ZSTD_e_flush will flush as much output as possible, meaning when compressing with multiple threads, it will757*        block until the flush is complete or the output buffer is full.758*  @return : 0 if internal buffers are entirely flushed,759*            >0 if some data still present within internal buffer (the value is minimal estimation of remaining size),760*            or an error code, which can be tested using ZSTD_isError().761*762*  Calling ZSTD_compressStream2() with ZSTD_e_end instructs to finish a frame.763*  It will perform a flush and write frame epilogue.764*  The epilogue is required for decoders to consider a frame completed.765*  flush operation is the same, and follows same rules as calling ZSTD_compressStream2() with ZSTD_e_flush.766*  You must continue calling ZSTD_compressStream2() with ZSTD_e_end until it returns 0, at which point you are free to767*  start a new frame.768*  note: ZSTD_e_end will flush as much output as possible, meaning when compressing with multiple threads, it will769*        block until the flush is complete or the output buffer is full.770*  @return : 0 if frame fully completed and fully flushed,771*            >0 if some data still present within internal buffer (the value is minimal estimation of remaining size),772*            or an error code, which can be tested using ZSTD_isError().773*774* *******************************************************************/775 776typedef ZSTD_CCtx ZSTD_CStream;  /**< CCtx and CStream are now effectively same object (>= v1.3.0) */777                                 /* Continue to distinguish them for compatibility with older versions <= v1.2.0 */778/*===== ZSTD_CStream management functions =====*/779ZSTDLIB_API ZSTD_CStream* ZSTD_createCStream(void);780ZSTDLIB_API size_t ZSTD_freeCStream(ZSTD_CStream* zcs);  /* accept NULL pointer */781 782/*===== Streaming compression functions =====*/783typedef enum {784    ZSTD_e_continue=0, /* collect more data, encoder decides when to output compressed result, for optimal compression ratio */785    ZSTD_e_flush=1,    /* flush any data provided so far,786                        * it creates (at least) one new block, that can be decoded immediately on reception;787                        * frame will continue: any future data can still reference previously compressed data, improving compression.788                        * note : multithreaded compression will block to flush as much output as possible. */789    ZSTD_e_end=2       /* flush any remaining data _and_ close current frame.790                        * note that frame is only closed after compressed data is fully flushed (return value == 0).791                        * After that point, any additional data starts a new frame.792                        * note : each frame is independent (does not reference any content from previous frame).793                        : note : multithreaded compression will block to flush as much output as possible. */794} ZSTD_EndDirective;795 796/*! ZSTD_compressStream2() : Requires v1.4.0+797 *  Behaves about the same as ZSTD_compressStream, with additional control on end directive.798 *  - Compression parameters are pushed into CCtx before starting compression, using ZSTD_CCtx_set*()799 *  - Compression parameters cannot be changed once compression is started (save a list of exceptions in multi-threading mode)800 *  - output->pos must be <= dstCapacity, input->pos must be <= srcSize801 *  - output->pos and input->pos will be updated. They are guaranteed to remain below their respective limit.802 *  - endOp must be a valid directive803 *  - When nbWorkers==0 (default), function is blocking : it completes its job before returning to caller.804 *  - When nbWorkers>=1, function is non-blocking : it copies a portion of input, distributes jobs to internal worker threads, flush to output whatever is available,805 *                                                  and then immediately returns, just indicating that there is some data remaining to be flushed.806 *                                                  The function nonetheless guarantees forward progress : it will return only after it reads or write at least 1+ byte.807 *  - Exception : if the first call requests a ZSTD_e_end directive and provides enough dstCapacity, the function delegates to ZSTD_compress2() which is always blocking.808 *  - @return provides a minimum amount of data remaining to be flushed from internal buffers809 *            or an error code, which can be tested using ZSTD_isError().810 *            if @return != 0, flush is not fully completed, there is still some data left within internal buffers.811 *            This is useful for ZSTD_e_flush, since in this case more flushes are necessary to empty all buffers.812 *            For ZSTD_e_end, @return == 0 when internal buffers are fully flushed and frame is completed.813 *  - after a ZSTD_e_end directive, if internal buffer is not fully flushed (@return != 0),814 *            only ZSTD_e_end or ZSTD_e_flush operations are allowed.815 *            Before starting a new compression job, or changing compression parameters,816 *            it is required to fully flush internal buffers.817 *  - note: if an operation ends with an error, it may leave @cctx in an undefined state.818 *          Therefore, it's UB to invoke ZSTD_compressStream2() of ZSTD_compressStream() on such a state.819 *          In order to be re-employed after an error, a state must be reset,820 *          which can be done explicitly (ZSTD_CCtx_reset()),821 *          or is sometimes implied by methods starting a new compression job (ZSTD_initCStream(), ZSTD_compressCCtx())822 */823ZSTDLIB_API size_t ZSTD_compressStream2( ZSTD_CCtx* cctx,824                                         ZSTD_outBuffer* output,825                                         ZSTD_inBuffer* input,826                                         ZSTD_EndDirective endOp);827 828 829/* These buffer sizes are softly recommended.830 * They are not required : ZSTD_compressStream*() happily accepts any buffer size, for both input and output.831 * Respecting the recommended size just makes it a bit easier for ZSTD_compressStream*(),832 * reducing the amount of memory shuffling and buffering, resulting in minor performance savings.833 *834 * However, note that these recommendations are from the perspective of a C caller program.835 * If the streaming interface is invoked from some other language,836 * especially managed ones such as Java or Go, through a foreign function interface such as jni or cgo,837 * a major performance rule is to reduce crossing such interface to an absolute minimum.838 * It's not rare that performance ends being spent more into the interface, rather than compression itself.839 * In which cases, prefer using large buffers, as large as practical,840 * for both input and output, to reduce the nb of roundtrips.841 */842ZSTDLIB_API size_t ZSTD_CStreamInSize(void);    /**< recommended size for input buffer */843ZSTDLIB_API size_t ZSTD_CStreamOutSize(void);   /**< recommended size for output buffer. Guarantee to successfully flush at least one complete compressed block. */844 845 846/* *****************************************************************************847 * This following is a legacy streaming API, available since v1.0+ .848 * It can be replaced by ZSTD_CCtx_reset() and ZSTD_compressStream2().849 * It is redundant, but remains fully supported.850 ******************************************************************************/851 852/*!853 * Equivalent to:854 *855 *     ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only);856 *     ZSTD_CCtx_refCDict(zcs, NULL); // clear the dictionary (if any)857 *     ZSTD_CCtx_setParameter(zcs, ZSTD_c_compressionLevel, compressionLevel);858 *859 * Note that ZSTD_initCStream() clears any previously set dictionary. Use the new API860 * to compress with a dictionary.861 */862ZSTDLIB_API size_t ZSTD_initCStream(ZSTD_CStream* zcs, int compressionLevel);863/*!864 * Alternative for ZSTD_compressStream2(zcs, output, input, ZSTD_e_continue).865 * NOTE: The return value is different. ZSTD_compressStream() returns a hint for866 * the next read size (if non-zero and not an error). ZSTD_compressStream2()867 * returns the minimum nb of bytes left to flush (if non-zero and not an error).868 */869ZSTDLIB_API size_t ZSTD_compressStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output, ZSTD_inBuffer* input);870/*! Equivalent to ZSTD_compressStream2(zcs, output, &emptyInput, ZSTD_e_flush). */871ZSTDLIB_API size_t ZSTD_flushStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output);872/*! Equivalent to ZSTD_compressStream2(zcs, output, &emptyInput, ZSTD_e_end). */873ZSTDLIB_API size_t ZSTD_endStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output);874 875 876/*-***************************************************************************877*  Streaming decompression - HowTo878*879*  A ZSTD_DStream object is required to track streaming operations.880*  Use ZSTD_createDStream() and ZSTD_freeDStream() to create/release resources.881*  ZSTD_DStream objects can be re-employed multiple times.882*883*  Use ZSTD_initDStream() to start a new decompression operation.884* @return : recommended first input size885*  Alternatively, use advanced API to set specific properties.886*887*  Use ZSTD_decompressStream() repetitively to consume your input.888*  The function will update both `pos` fields.889*  If `input.pos < input.size`, some input has not been consumed.890*  It's up to the caller to present again remaining data.891*892*  The function tries to flush all data decoded immediately, respecting output buffer size.893*  If `output.pos < output.size`, decoder has flushed everything it could.894*895*  However, when `output.pos == output.size`, it's more difficult to know.896*  If @return > 0, the frame is not complete, meaning897*  either there is still some data left to flush within internal buffers,898*  or there is more input to read to complete the frame (or both).899*  In which case, call ZSTD_decompressStream() again to flush whatever remains in the buffer.900*  Note : with no additional input provided, amount of data flushed is necessarily <= ZSTD_BLOCKSIZE_MAX.901* @return : 0 when a frame is completely decoded and fully flushed,902*        or an error code, which can be tested using ZSTD_isError(),903*        or any other value > 0, which means there is still some decoding or flushing to do to complete current frame :904*                                the return value is a suggested next input size (just a hint for better latency)905*                                that will never request more than the remaining content of the compressed frame.906* *******************************************************************************/907 908typedef ZSTD_DCtx ZSTD_DStream;  /**< DCtx and DStream are now effectively same object (>= v1.3.0) */909                                 /* For compatibility with versions <= v1.2.0, prefer differentiating them. */910/*===== ZSTD_DStream management functions =====*/911ZSTDLIB_API ZSTD_DStream* ZSTD_createDStream(void);912ZSTDLIB_API size_t ZSTD_freeDStream(ZSTD_DStream* zds);  /* accept NULL pointer */913 914/*===== Streaming decompression functions =====*/915 916/*! ZSTD_initDStream() :917 * Initialize/reset DStream state for new decompression operation.918 * Call before new decompression operation using same DStream.919 *920 * Note : This function is redundant with the advanced API and equivalent to:921 *     ZSTD_DCtx_reset(zds, ZSTD_reset_session_only);922 *     ZSTD_DCtx_refDDict(zds, NULL);923 */924ZSTDLIB_API size_t ZSTD_initDStream(ZSTD_DStream* zds);925 926/*! ZSTD_decompressStream() :927 * Streaming decompression function.928 * Call repetitively to consume full input updating it as necessary.929 * Function will update both input and output `pos` fields exposing current state via these fields:930 * - `input.pos < input.size`, some input remaining and caller should provide remaining input931 *   on the next call.932 * - `output.pos < output.size`, decoder flushed internal output buffer.933 * - `output.pos == output.size`, unflushed data potentially present in the internal buffers,934 *   check ZSTD_decompressStream() @return value,935 *   if > 0, invoke it again to flush remaining data to output.936 * Note : with no additional input, amount of data flushed <= ZSTD_BLOCKSIZE_MAX.937 *938 * @return : 0 when a frame is completely decoded and fully flushed,939 *           or an error code, which can be tested using ZSTD_isError(),940 *           or any other value > 0, which means there is some decoding or flushing to do to complete current frame.941 *942 * Note: when an operation returns with an error code, the @zds state may be left in undefined state.943 *       It's UB to invoke `ZSTD_decompressStream()` on such a state.944 *       In order to re-use such a state, it must be first reset,945 *       which can be done explicitly (`ZSTD_DCtx_reset()`),946 *       or is implied for operations starting some new decompression job (`ZSTD_initDStream`, `ZSTD_decompressDCtx()`, `ZSTD_decompress_usingDict()`)947 */948ZSTDLIB_API size_t ZSTD_decompressStream(ZSTD_DStream* zds, ZSTD_outBuffer* output, ZSTD_inBuffer* input);949 950ZSTDLIB_API size_t ZSTD_DStreamInSize(void);    /*!< recommended size for input buffer */951ZSTDLIB_API size_t ZSTD_DStreamOutSize(void);   /*!< recommended size for output buffer. Guarantee to successfully flush at least one complete block in all circumstances. */952 953 954/**************************955*  Simple dictionary API956***************************/957/*! ZSTD_compress_usingDict() :958 *  Compression at an explicit compression level using a Dictionary.959 *  A dictionary can be any arbitrary data segment (also called a prefix),960 *  or a buffer with specified information (see zdict.h).961 *  Note : This function loads the dictionary, resulting in significant startup delay.962 *         It's intended for a dictionary used only once.963 *  Note 2 : When `dict == NULL || dictSize < 8` no dictionary is used. */964ZSTDLIB_API size_t ZSTD_compress_usingDict(ZSTD_CCtx* ctx,965                                           void* dst, size_t dstCapacity,966                                     const void* src, size_t srcSize,967                                     const void* dict,size_t dictSize,968                                           int compressionLevel);969 970/*! ZSTD_decompress_usingDict() :971 *  Decompression using a known Dictionary.972 *  Dictionary must be identical to the one used during compression.973 *  Note : This function loads the dictionary, resulting in significant startup delay.974 *         It's intended for a dictionary used only once.975 *  Note : When `dict == NULL || dictSize < 8` no dictionary is used. */976ZSTDLIB_API size_t ZSTD_decompress_usingDict(ZSTD_DCtx* dctx,977                                             void* dst, size_t dstCapacity,978                                       const void* src, size_t srcSize,979                                       const void* dict,size_t dictSize);980 981 982/***********************************983 *  Bulk processing dictionary API984 **********************************/985typedef struct ZSTD_CDict_s ZSTD_CDict;986 987/*! ZSTD_createCDict() :988 *  When compressing multiple messages or blocks using the same dictionary,989 *  it's recommended to digest the dictionary only once, since it's a costly operation.990 *  ZSTD_createCDict() will create a state from digesting a dictionary.991 *  The resulting state can be used for future compression operations with very limited startup cost.992 *  ZSTD_CDict can be created once and shared by multiple threads concurrently, since its usage is read-only.993 * @dictBuffer can be released after ZSTD_CDict creation, because its content is copied within CDict.994 *  Note 1 : Consider experimental function `ZSTD_createCDict_byReference()` if you prefer to not duplicate @dictBuffer content.995 *  Note 2 : A ZSTD_CDict can be created from an empty @dictBuffer,996 *      in which case the only thing that it transports is the @compressionLevel.997 *      This can be useful in a pipeline featuring ZSTD_compress_usingCDict() exclusively,998 *      expecting a ZSTD_CDict parameter with any data, including those without a known dictionary. */999ZSTDLIB_API ZSTD_CDict* ZSTD_createCDict(const void* dictBuffer, size_t dictSize,1000                                         int compressionLevel);1001 1002/*! ZSTD_freeCDict() :1003 *  Function frees memory allocated by ZSTD_createCDict().1004 *  If a NULL pointer is passed, no operation is performed. */1005ZSTDLIB_API size_t      ZSTD_freeCDict(ZSTD_CDict* CDict);1006 1007/*! ZSTD_compress_usingCDict() :1008 *  Compression using a digested Dictionary.1009 *  Recommended when same dictionary is used multiple times.1010 *  Note : compression level is _decided at dictionary creation time_,1011 *     and frame parameters are hardcoded (dictID=yes, contentSize=yes, checksum=no) */1012ZSTDLIB_API size_t ZSTD_compress_usingCDict(ZSTD_CCtx* cctx,1013                                            void* dst, size_t dstCapacity,1014                                      const void* src, size_t srcSize,1015                                      const ZSTD_CDict* cdict);1016 1017 1018typedef struct ZSTD_DDict_s ZSTD_DDict;1019 1020/*! ZSTD_createDDict() :1021 *  Create a digested dictionary, ready to start decompression operation without startup delay.1022 *  dictBuffer can be released after DDict creation, as its content is copied inside DDict. */1023ZSTDLIB_API ZSTD_DDict* ZSTD_createDDict(const void* dictBuffer, size_t dictSize);1024 1025/*! ZSTD_freeDDict() :1026 *  Function frees memory allocated with ZSTD_createDDict()1027 *  If a NULL pointer is passed, no operation is performed. */1028ZSTDLIB_API size_t      ZSTD_freeDDict(ZSTD_DDict* ddict);1029 1030/*! ZSTD_decompress_usingDDict() :1031 *  Decompression using a digested Dictionary.1032 *  Recommended when same dictionary is used multiple times. */1033ZSTDLIB_API size_t ZSTD_decompress_usingDDict(ZSTD_DCtx* dctx,1034                                              void* dst, size_t dstCapacity,1035                                        const void* src, size_t srcSize,1036                                        const ZSTD_DDict* ddict);1037 1038 1039/********************************1040 *  Dictionary helper functions1041 *******************************/1042 1043/*! ZSTD_getDictID_fromDict() : Requires v1.4.0+1044 *  Provides the dictID stored within dictionary.1045 *  if @return == 0, the dictionary is not conformant with Zstandard specification.1046 *  It can still be loaded, but as a content-only dictionary. */1047ZSTDLIB_API unsigned ZSTD_getDictID_fromDict(const void* dict, size_t dictSize);1048 1049/*! ZSTD_getDictID_fromCDict() : Requires v1.5.0+1050 *  Provides the dictID of the dictionary loaded into `cdict`.1051 *  If @return == 0, the dictionary is not conformant to Zstandard specification, or empty.1052 *  Non-conformant dictionaries can still be loaded, but as content-only dictionaries. */1053ZSTDLIB_API unsigned ZSTD_getDictID_fromCDict(const ZSTD_CDict* cdict);1054 1055/*! ZSTD_getDictID_fromDDict() : Requires v1.4.0+1056 *  Provides the dictID of the dictionary loaded into `ddict`.1057 *  If @return == 0, the dictionary is not conformant to Zstandard specification, or empty.1058 *  Non-conformant dictionaries can still be loaded, but as content-only dictionaries. */1059ZSTDLIB_API unsigned ZSTD_getDictID_fromDDict(const ZSTD_DDict* ddict);1060 1061/*! ZSTD_getDictID_fromFrame() : Requires v1.4.0+1062 *  Provides the dictID required to decompressed the frame stored within `src`.1063 *  If @return == 0, the dictID could not be decoded.1064 *  This could for one of the following reasons :1065 *  - The frame does not require a dictionary to be decoded (most common case).1066 *  - The frame was built with dictID intentionally removed. Whatever dictionary is necessary is a hidden piece of information.1067 *    Note : this use case also happens when using a non-conformant dictionary.1068 *  - `srcSize` is too small, and as a result, the frame header could not be decoded (only possible if `srcSize < ZSTD_FRAMEHEADERSIZE_MAX`).1069 *  - This is not a Zstandard frame.1070 *  When identifying the exact failure cause, it's possible to use ZSTD_getFrameHeader(), which will provide a more precise error code. */1071ZSTDLIB_API unsigned ZSTD_getDictID_fromFrame(const void* src, size_t srcSize);1072 1073 1074/*******************************************************************************1075 * Advanced dictionary and prefix API (Requires v1.4.0+)1076 *1077 * This API allows dictionaries to be used with ZSTD_compress2(),1078 * ZSTD_compressStream2(), and ZSTD_decompressDCtx().1079 * Dictionaries are sticky, they remain valid when same context is reused,1080 * they only reset when the context is reset1081 * with ZSTD_reset_parameters or ZSTD_reset_session_and_parameters.1082 * In contrast, Prefixes are single-use.1083 ******************************************************************************/1084 1085 1086/*! ZSTD_CCtx_loadDictionary() : Requires v1.4.0+1087 *  Create an internal CDict from `dict` buffer.1088 *  Decompression will have to use same dictionary.1089 * @result : 0, or an error code (which can be tested with ZSTD_isError()).1090 *  Special: Loading a NULL (or 0-size) dictionary invalidates previous dictionary,1091 *           meaning "return to no-dictionary mode".1092 *  Note 1 : Dictionary is sticky, it will be used for all future compressed frames,1093 *           until parameters are reset, a new dictionary is loaded, or the dictionary1094 *           is explicitly invalidated by loading a NULL dictionary.1095 *  Note 2 : Loading a dictionary involves building tables.1096 *           It's also a CPU consuming operation, with non-negligible impact on latency.1097 *           Tables are dependent on compression parameters, and for this reason,1098 *           compression parameters can no longer be changed after loading a dictionary.1099 *  Note 3 :`dict` content will be copied internally.1100 *           Use experimental ZSTD_CCtx_loadDictionary_byReference() to reference content instead.1101 *           In such a case, dictionary buffer must outlive its users.1102 *  Note 4 : Use ZSTD_CCtx_loadDictionary_advanced()1103 *           to precisely select how dictionary content must be interpreted.1104 *  Note 5 : This method does not benefit from LDM (long distance mode).1105 *           If you want to employ LDM on some large dictionary content,1106 *           prefer employing ZSTD_CCtx_refPrefix() described below.1107 */1108ZSTDLIB_API size_t ZSTD_CCtx_loadDictionary(ZSTD_CCtx* cctx, const void* dict, size_t dictSize);1109 1110/*! ZSTD_CCtx_refCDict() : Requires v1.4.0+1111 *  Reference a prepared dictionary, to be used for all future compressed frames.1112 *  Note that compression parameters are enforced from within CDict,1113 *  and supersede any compression parameter previously set within CCtx.1114 *  The parameters ignored are labelled as "superseded-by-cdict" in the ZSTD_cParameter enum docs.1115 *  The ignored parameters will be used again if the CCtx is returned to no-dictionary mode.1116 *  The dictionary will remain valid for future compressed frames using same CCtx.1117 * @result : 0, or an error code (which can be tested with ZSTD_isError()).1118 *  Special : Referencing a NULL CDict means "return to no-dictionary mode".1119 *  Note 1 : Currently, only one dictionary can be managed.1120 *           Referencing a new dictionary effectively "discards" any previous one.1121 *  Note 2 : CDict is just referenced, its lifetime must outlive its usage within CCtx. */1122ZSTDLIB_API size_t ZSTD_CCtx_refCDict(ZSTD_CCtx* cctx, const ZSTD_CDict* cdict);1123 1124/*! ZSTD_CCtx_refPrefix() : Requires v1.4.0+1125 *  Reference a prefix (single-usage dictionary) for next compressed frame.1126 *  A prefix is **only used once**. Tables are discarded at end of frame (ZSTD_e_end).1127 *  Decompression will need same prefix to properly regenerate data.1128 *  Compressing with a prefix is similar in outcome as performing a diff and compressing it,1129 *  but performs much faster, especially during decompression (compression speed is tunable with compression level).1130 *  This method is compatible with LDM (long distance mode).1131 * @result : 0, or an error code (which can be tested with ZSTD_isError()).1132 *  Special: Adding any prefix (including NULL) invalidates any previous prefix or dictionary1133 *  Note 1 : Prefix buffer is referenced. It **must** outlive compression.1134 *           Its content must remain unmodified during compression.1135 *  Note 2 : If the intention is to diff some large src data blob with some prior version of itself,1136 *           ensure that the window size is large enough to contain the entire source.1137 *           See ZSTD_c_windowLog.1138 *  Note 3 : Referencing a prefix involves building tables, which are dependent on compression parameters.1139 *           It's a CPU consuming operation, with non-negligible impact on latency.1140 *           If there is a need to use the same prefix multiple times, consider loadDictionary instead.1141 *  Note 4 : By default, the prefix is interpreted as raw content (ZSTD_dct_rawContent).1142 *           Use experimental ZSTD_CCtx_refPrefix_advanced() to alter dictionary interpretation. */1143ZSTDLIB_API size_t ZSTD_CCtx_refPrefix(ZSTD_CCtx* cctx,1144                                 const void* prefix, size_t prefixSize);1145 1146/*! ZSTD_DCtx_loadDictionary() : Requires v1.4.0+1147 *  Create an internal DDict from dict buffer, to be used to decompress all future frames.1148 *  The dictionary remains valid for all future frames, until explicitly invalidated, or1149 *  a new dictionary is loaded.1150 * @result : 0, or an error code (which can be tested with ZSTD_isError()).1151 *  Special : Adding a NULL (or 0-size) dictionary invalidates any previous dictionary,1152 *            meaning "return to no-dictionary mode".1153 *  Note 1 : Loading a dictionary involves building tables,1154 *           which has a non-negligible impact on CPU usage and latency.1155 *           It's recommended to "load once, use many times", to amortize the cost1156 *  Note 2 :`dict` content will be copied internally, so `dict` can be released after loading.1157 *           Use ZSTD_DCtx_loadDictionary_byReference() to reference dictionary content instead.1158 *  Note 3 : Use ZSTD_DCtx_loadDictionary_advanced() to take control of1159 *           how dictionary content is loaded and interpreted.1160 */1161ZSTDLIB_API size_t ZSTD_DCtx_loadDictionary(ZSTD_DCtx* dctx, const void* dict, size_t dictSize);1162 1163/*! ZSTD_DCtx_refDDict() : Requires v1.4.0+1164 *  Reference a prepared dictionary, to be used to decompress next frames.1165 *  The dictionary remains active for decompression of future frames using same DCtx.1166 *1167 *  If called with ZSTD_d_refMultipleDDicts enabled, repeated calls of this function1168 *  will store the DDict references in a table, and the DDict used for decompression1169 *  will be determined at decompression time, as per the dict ID in the frame.1170 *  The memory for the table is allocated on the first call to refDDict, and can be1171 *  freed with ZSTD_freeDCtx().1172 *1173 *  If called with ZSTD_d_refMultipleDDicts disabled (the default), only one dictionary1174 *  will be managed, and referencing a dictionary effectively "discards" any previous one.1175 *1176 * @result : 0, or an error code (which can be tested with ZSTD_isError()).1177 *  Special: referencing a NULL DDict means "return to no-dictionary mode".1178 *  Note 2 : DDict is just referenced, its lifetime must outlive its usage from DCtx.1179 */1180ZSTDLIB_API size_t ZSTD_DCtx_refDDict(ZSTD_DCtx* dctx, const ZSTD_DDict* ddict);1181 1182/*! ZSTD_DCtx_refPrefix() : Requires v1.4.0+1183 *  Reference a prefix (single-usage dictionary) to decompress next frame.1184 *  This is the reverse operation of ZSTD_CCtx_refPrefix(),1185 *  and must use the same prefix as the one used during compression.1186 *  Prefix is **only used once**. Reference is discarded at end of frame.1187 *  End of frame is reached when ZSTD_decompressStream() returns 0.1188 * @result : 0, or an error code (which can be tested with ZSTD_isError()).1189 *  Note 1 : Adding any prefix (including NULL) invalidates any previously set prefix or dictionary1190 *  Note 2 : Prefix buffer is referenced. It **must** outlive decompression.1191 *           Prefix buffer must remain unmodified up to the end of frame,1192 *           reached when ZSTD_decompressStream() returns 0.1193 *  Note 3 : By default, the prefix is treated as raw content (ZSTD_dct_rawContent).1194 *           Use ZSTD_CCtx_refPrefix_advanced() to alter dictMode (Experimental section)1195 *  Note 4 : Referencing a raw content prefix has almost no cpu nor memory cost.1196 *           A full dictionary is more costly, as it requires building tables.1197 */1198ZSTDLIB_API size_t ZSTD_DCtx_refPrefix(ZSTD_DCtx* dctx,1199                                 const void* prefix, size_t prefixSize);1200 

Showing the first 1,200 of 3199 lines. Download the file for the rest.

codekingpro/portable-devtools · Team Ai