codekingpro/portable-devtools
116k
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#if defined (__cplusplus)11extern "C" {12#endif13 14#ifndef ZSTD_H_23544615#define ZSTD_H_23544616 17/* ====== Dependencies ======*/18#include <limits.h> /* INT_MAX */19#include <stddef.h> /* size_t */20 21 22/* ===== ZSTDLIB_API : control library symbols visibility ===== */23#ifndef ZSTDLIB_VISIBLE24 /* Backwards compatibility with old macro name */25# ifdef ZSTDLIB_VISIBILITY26# define ZSTDLIB_VISIBLE ZSTDLIB_VISIBILITY27# elif defined(__GNUC__) && (__GNUC__ >= 4) && !defined(__MINGW32__)28# define ZSTDLIB_VISIBLE __attribute__ ((visibility ("default")))29# else30# define ZSTDLIB_VISIBLE31# endif32#endif33 34#ifndef ZSTDLIB_HIDDEN35# if defined(__GNUC__) && (__GNUC__ >= 4) && !defined(__MINGW32__)36# define ZSTDLIB_HIDDEN __attribute__ ((visibility ("hidden")))37# else38# define ZSTDLIB_HIDDEN39# endif40#endif41 42#if defined(ZSTD_DLL_EXPORT) && (ZSTD_DLL_EXPORT==1)43# define ZSTDLIB_API __declspec(dllexport) ZSTDLIB_VISIBLE44#elif defined(ZSTD_DLL_IMPORT) && (ZSTD_DLL_IMPORT==1)45# 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.*/46#else47# define ZSTDLIB_API ZSTDLIB_VISIBLE48#endif49 50/* Deprecation warnings :51 * Should these warnings be a problem, it is generally possible to disable them,52 * typically with -Wno-deprecated-declarations for gcc or _CRT_SECURE_NO_WARNINGS in Visual.53 * Otherwise, it's also possible to define ZSTD_DISABLE_DEPRECATE_WARNINGS.54 */55#ifdef ZSTD_DISABLE_DEPRECATE_WARNINGS56# define ZSTD_DEPRECATED(message) /* disable deprecation warnings */57#else58# if defined (__cplusplus) && (__cplusplus >= 201402) /* C++14 or greater */59# define ZSTD_DEPRECATED(message) [[deprecated(message)]]60# elif (defined(GNUC) && (GNUC > 4 || (GNUC == 4 && GNUC_MINOR >= 5))) || defined(__clang__)61# define ZSTD_DEPRECATED(message) __attribute__((deprecated(message)))62# elif defined(__GNUC__) && (__GNUC__ >= 3)63# define ZSTD_DEPRECATED(message) __attribute__((deprecated))64# elif defined(_MSC_VER)65# define ZSTD_DEPRECATED(message) __declspec(deprecated(message))66# else67# pragma message("WARNING: You need to implement ZSTD_DEPRECATED for this compiler")68# define ZSTD_DEPRECATED(message)69# endif70#endif /* ZSTD_DISABLE_DEPRECATE_WARNINGS */71 72 73/*******************************************************************************74 Introduction75 76 zstd, short for Zstandard, is a fast lossless compression algorithm, targeting77 real-time compression scenarios at zlib-level and better compression ratios.78 The zstd compression library provides in-memory compression and decompression79 functions.80 81 The library supports regular compression levels from 1 up to ZSTD_maxCLevel(),82 which is currently 22. Levels >= 20, labeled `--ultra`, should be used with83 caution, as they require more memory. The library also offers negative84 compression levels, which extend the range of speed vs. ratio preferences.85 The lower the level, the faster the speed (at the cost of compression).86 87 Compression can be done in:88 - a single step (described as Simple API)89 - a single step, reusing a context (described as Explicit context)90 - unbounded multiple steps (described as Streaming compression)91 92 The compression ratio achievable on small data can be highly improved using93 a dictionary. Dictionary compression can be performed in:94 - a single step (described as Simple dictionary API)95 - a single step, reusing a dictionary (described as Bulk-processing96 dictionary API)97 98 Advanced experimental functions can be accessed using99 `#define ZSTD_STATIC_LINKING_ONLY` before including zstd.h.100 101 Advanced experimental APIs should never be used with a dynamically-linked102 library. They are not "stable"; their definitions or signatures may change in103 the future. Only static linking is allowed.104*******************************************************************************/105 106/*------ Version ------*/107#define ZSTD_VERSION_MAJOR 1108#define ZSTD_VERSION_MINOR 5109#define ZSTD_VERSION_RELEASE 6110#define ZSTD_VERSION_NUMBER (ZSTD_VERSION_MAJOR *100*100 + ZSTD_VERSION_MINOR *100 + ZSTD_VERSION_RELEASE)111 112/*! ZSTD_versionNumber() :113 * Return runtime library version, the value is (MAJOR*100*100 + MINOR*100 + RELEASE). */114ZSTDLIB_API unsigned ZSTD_versionNumber(void);115 116#define ZSTD_LIB_VERSION ZSTD_VERSION_MAJOR.ZSTD_VERSION_MINOR.ZSTD_VERSION_RELEASE117#define ZSTD_QUOTE(str) #str118#define ZSTD_EXPAND_AND_QUOTE(str) ZSTD_QUOTE(str)119#define ZSTD_VERSION_STRING ZSTD_EXPAND_AND_QUOTE(ZSTD_LIB_VERSION)120 121/*! ZSTD_versionString() :122 * Return runtime library version, like "1.4.5". Requires v1.3.0+. */123ZSTDLIB_API const char* ZSTD_versionString(void);124 125/* *************************************126 * Default constant127 ***************************************/128#ifndef ZSTD_CLEVEL_DEFAULT129# define ZSTD_CLEVEL_DEFAULT 3130#endif131 132/* *************************************133 * Constants134 ***************************************/135 136/* All magic numbers are supposed read/written to/from files/memory using little-endian convention */137#define ZSTD_MAGICNUMBER 0xFD2FB528 /* valid since v0.8.0 */138#define ZSTD_MAGIC_DICTIONARY 0xEC30A437 /* valid since v0.7.0 */139#define ZSTD_MAGIC_SKIPPABLE_START 0x184D2A50 /* all 16 values, from 0x184D2A50 to 0x184D2A5F, signal the beginning of a skippable frame */140#define ZSTD_MAGIC_SKIPPABLE_MASK 0xFFFFFFF0141 142#define ZSTD_BLOCKSIZELOG_MAX 17143#define ZSTD_BLOCKSIZE_MAX (1<<ZSTD_BLOCKSIZELOG_MAX)144 145 146/***************************************147* Simple API148***************************************/149/*! ZSTD_compress() :150 * Compresses `src` content as a single zstd compressed frame into already allocated `dst`.151 * NOTE: Providing `dstCapacity >= ZSTD_compressBound(srcSize)` guarantees that zstd will have152 * enough space to successfully compress the data.153 * @return : compressed size written into `dst` (<= `dstCapacity),154 * or an error code if it fails (which can be tested using ZSTD_isError()). */155ZSTDLIB_API size_t ZSTD_compress( void* dst, size_t dstCapacity,156 const void* src, size_t srcSize,157 int compressionLevel);158 159/*! ZSTD_decompress() :160 * `compressedSize` : must be the _exact_ size of some number of compressed and/or skippable frames.161 * `dstCapacity` is an upper bound of originalSize to regenerate.162 * If user cannot imply a maximum upper bound, it's better to use streaming mode to decompress data.163 * @return : the number of bytes decompressed into `dst` (<= `dstCapacity`),164 * or an errorCode if it fails (which can be tested using ZSTD_isError()). */165ZSTDLIB_API size_t ZSTD_decompress( void* dst, size_t dstCapacity,166 const void* src, size_t compressedSize);167 168/*! ZSTD_getFrameContentSize() : requires v1.3.0+169 * `src` should point to the start of a ZSTD encoded frame.170 * `srcSize` must be at least as large as the frame header.171 * hint : any size >= `ZSTD_frameHeaderSize_max` is large enough.172 * @return : - decompressed size of `src` frame content, if known173 * - ZSTD_CONTENTSIZE_UNKNOWN if the size cannot be determined174 * - ZSTD_CONTENTSIZE_ERROR if an error occurred (e.g. invalid magic number, srcSize too small)175 * note 1 : a 0 return value means the frame is valid but "empty".176 * note 2 : decompressed size is an optional field, it may not be present, typically in streaming mode.177 * When `return==ZSTD_CONTENTSIZE_UNKNOWN`, data to decompress could be any size.178 * In which case, it's necessary to use streaming mode to decompress data.179 * Optionally, application can rely on some implicit limit,180 * as ZSTD_decompress() only needs an upper bound of decompressed size.181 * (For example, data could be necessarily cut into blocks <= 16 KB).182 * note 3 : decompressed size is always present when compression is completed using single-pass functions,183 * such as ZSTD_compress(), ZSTD_compressCCtx() ZSTD_compress_usingDict() or ZSTD_compress_usingCDict().184 * note 4 : decompressed size can be very large (64-bits value),185 * potentially larger than what local system can handle as a single memory segment.186 * In which case, it's necessary to use streaming mode to decompress data.187 * note 5 : If source is untrusted, decompressed size could be wrong or intentionally modified.188 * Always ensure return value fits within application's authorized limits.189 * Each application can set its own limits.190 * note 6 : This function replaces ZSTD_getDecompressedSize() */191#define ZSTD_CONTENTSIZE_UNKNOWN (0ULL - 1)192#define ZSTD_CONTENTSIZE_ERROR (0ULL - 2)193ZSTDLIB_API unsigned long long ZSTD_getFrameContentSize(const void *src, size_t srcSize);194 195/*! ZSTD_getDecompressedSize() :196 * NOTE: This function is now obsolete, in favor of ZSTD_getFrameContentSize().197 * Both functions work the same way, but ZSTD_getDecompressedSize() blends198 * "empty", "unknown" and "error" results to the same return value (0),199 * while ZSTD_getFrameContentSize() gives them separate return values.200 * @return : decompressed size of `src` frame content _if known and not empty_, 0 otherwise. */201ZSTD_DEPRECATED("Replaced by ZSTD_getFrameContentSize")202ZSTDLIB_API203unsigned long long ZSTD_getDecompressedSize(const void* src, size_t srcSize);204 205/*! ZSTD_findFrameCompressedSize() : Requires v1.4.0+206 * `src` should point to the start of a ZSTD frame or skippable frame.207 * `srcSize` must be >= first frame size208 * @return : the compressed size of the first frame starting at `src`,209 * suitable to pass as `srcSize` to `ZSTD_decompress` or similar,210 * or an error code if input is invalid */211ZSTDLIB_API size_t ZSTD_findFrameCompressedSize(const void* src, size_t srcSize);212 213 214/*====== Helper functions ======*/215/* ZSTD_compressBound() :216 * maximum compressed size in worst case single-pass scenario.217 * When invoking `ZSTD_compress()` or any other one-pass compression function,218 * it's recommended to provide @dstCapacity >= ZSTD_compressBound(srcSize)219 * as it eliminates one potential failure scenario,220 * aka not enough room in dst buffer to write the compressed frame.221 * Note : ZSTD_compressBound() itself can fail, if @srcSize > ZSTD_MAX_INPUT_SIZE .222 * In which case, ZSTD_compressBound() will return an error code223 * which can be tested using ZSTD_isError().224 *225 * ZSTD_COMPRESSBOUND() :226 * same as ZSTD_compressBound(), but as a macro.227 * It can be used to produce constants, which can be useful for static allocation,228 * for example to size a static array on stack.229 * Will produce constant value 0 if srcSize too large.230 */231#define ZSTD_MAX_INPUT_SIZE ((sizeof(size_t)==8) ? 0xFF00FF00FF00FF00ULL : 0xFF00FF00U)232#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 */233ZSTDLIB_API size_t ZSTD_compressBound(size_t srcSize); /*!< maximum compressed size in worst case single-pass scenario */234/* ZSTD_isError() :235 * Most ZSTD_* functions returning a size_t value can be tested for error,236 * using ZSTD_isError().237 * @return 1 if error, 0 otherwise238 */239ZSTDLIB_API unsigned ZSTD_isError(size_t code); /*!< tells if a `size_t` function result is an error code */240ZSTDLIB_API const char* ZSTD_getErrorName(size_t code); /*!< provides readable string from an error code */241ZSTDLIB_API int ZSTD_minCLevel(void); /*!< minimum negative compression level allowed, requires v1.4.0+ */242ZSTDLIB_API int ZSTD_maxCLevel(void); /*!< maximum compression level available */243ZSTDLIB_API int ZSTD_defaultCLevel(void); /*!< default compression level, specified by ZSTD_CLEVEL_DEFAULT, requires v1.5.0+ */244 245 246/***************************************247* Explicit context248***************************************/249/*= Compression context250 * When compressing many times,251 * it is recommended to allocate a context just once,252 * and reuse it for each successive compression operation.253 * This will make workload friendlier for system's memory.254 * Note : re-using context is just a speed / resource optimization.255 * It doesn't change the compression ratio, which remains identical.256 * Note 2 : In multi-threaded environments,257 * use one different context per thread for parallel execution.258 */259typedef struct ZSTD_CCtx_s ZSTD_CCtx;260ZSTDLIB_API ZSTD_CCtx* ZSTD_createCCtx(void);261ZSTDLIB_API size_t ZSTD_freeCCtx(ZSTD_CCtx* cctx); /* accept NULL pointer */262 263/*! ZSTD_compressCCtx() :264 * Same as ZSTD_compress(), using an explicit ZSTD_CCtx.265 * Important : in order to mirror `ZSTD_compress()` behavior,266 * this function compresses at the requested compression level,267 * __ignoring any other advanced parameter__ .268 * If any advanced parameter was set using the advanced API,269 * they will all be reset. Only `compressionLevel` remains.270 */271ZSTDLIB_API size_t ZSTD_compressCCtx(ZSTD_CCtx* cctx,272 void* dst, size_t dstCapacity,273 const void* src, size_t srcSize,274 int compressionLevel);275 276/*= Decompression context277 * When decompressing many times,278 * it is recommended to allocate a context only once,279 * and reuse it for each successive compression operation.280 * This will make workload friendlier for system's memory.281 * Use one context per thread for parallel execution. */282typedef struct ZSTD_DCtx_s ZSTD_DCtx;283ZSTDLIB_API ZSTD_DCtx* ZSTD_createDCtx(void);284ZSTDLIB_API size_t ZSTD_freeDCtx(ZSTD_DCtx* dctx); /* accept NULL pointer */285 286/*! ZSTD_decompressDCtx() :287 * Same as ZSTD_decompress(),288 * requires an allocated ZSTD_DCtx.289 * Compatible with sticky parameters (see below).290 */291ZSTDLIB_API size_t ZSTD_decompressDCtx(ZSTD_DCtx* dctx,292 void* dst, size_t dstCapacity,293 const void* src, size_t srcSize);294 295 296/*********************************************297* Advanced compression API (Requires v1.4.0+)298**********************************************/299 300/* API design :301 * Parameters are pushed one by one into an existing context,302 * using ZSTD_CCtx_set*() functions.303 * Pushed parameters are sticky : they are valid for next compressed frame, and any subsequent frame.304 * "sticky" parameters are applicable to `ZSTD_compress2()` and `ZSTD_compressStream*()` !305 * __They do not apply to one-shot variants such as ZSTD_compressCCtx()__ .306 *307 * It's possible to reset all parameters to "default" using ZSTD_CCtx_reset().308 *309 * This API supersedes all other "advanced" API entry points in the experimental section.310 * In the future, we expect to remove API entry points from experimental which are redundant with this API.311 */312 313 314/* Compression strategies, listed from fastest to strongest */315typedef enum { ZSTD_fast=1,316 ZSTD_dfast=2,317 ZSTD_greedy=3,318 ZSTD_lazy=4,319 ZSTD_lazy2=5,320 ZSTD_btlazy2=6,321 ZSTD_btopt=7,322 ZSTD_btultra=8,323 ZSTD_btultra2=9324 /* note : new strategies _might_ be added in the future.325 Only the order (from fast to strong) is guaranteed */326} ZSTD_strategy;327 328typedef enum {329 330 /* compression parameters331 * Note: When compressing with a ZSTD_CDict these parameters are superseded332 * by the parameters used to construct the ZSTD_CDict.333 * See ZSTD_CCtx_refCDict() for more info (superseded-by-cdict). */334 ZSTD_c_compressionLevel=100, /* Set compression parameters according to pre-defined cLevel table.335 * Note that exact compression parameters are dynamically determined,336 * depending on both compression level and srcSize (when known).337 * Default level is ZSTD_CLEVEL_DEFAULT==3.338 * Special: value 0 means default, which is controlled by ZSTD_CLEVEL_DEFAULT.339 * Note 1 : it's possible to pass a negative compression level.340 * Note 2 : setting a level does not automatically set all other compression parameters341 * to default. Setting this will however eventually dynamically impact the compression342 * parameters which have not been manually set. The manually set343 * ones will 'stick'. */344 /* Advanced compression parameters :345 * It's possible to pin down compression parameters to some specific values.346 * In which case, these values are no longer dynamically selected by the compressor */347 ZSTD_c_windowLog=101, /* Maximum allowed back-reference distance, expressed as power of 2.348 * This will set a memory budget for streaming decompression,349 * with larger values requiring more memory350 * and typically compressing more.351 * Must be clamped between ZSTD_WINDOWLOG_MIN and ZSTD_WINDOWLOG_MAX.352 * Special: value 0 means "use default windowLog".353 * Note: Using a windowLog greater than ZSTD_WINDOWLOG_LIMIT_DEFAULT354 * requires explicitly allowing such size at streaming decompression stage. */355 ZSTD_c_hashLog=102, /* Size of the initial probe table, as a power of 2.356 * Resulting memory usage is (1 << (hashLog+2)).357 * Must be clamped between ZSTD_HASHLOG_MIN and ZSTD_HASHLOG_MAX.358 * Larger tables improve compression ratio of strategies <= dFast,359 * and improve speed of strategies > dFast.360 * Special: value 0 means "use default hashLog". */361 ZSTD_c_chainLog=103, /* Size of the multi-probe search table, as a power of 2.362 * Resulting memory usage is (1 << (chainLog+2)).363 * Must be clamped between ZSTD_CHAINLOG_MIN and ZSTD_CHAINLOG_MAX.364 * Larger tables result in better and slower compression.365 * This parameter is useless for "fast" strategy.366 * It's still useful when using "dfast" strategy,367 * in which case it defines a secondary probe table.368 * Special: value 0 means "use default chainLog". */369 ZSTD_c_searchLog=104, /* Number of search attempts, as a power of 2.370 * More attempts result in better and slower compression.371 * This parameter is useless for "fast" and "dFast" strategies.372 * Special: value 0 means "use default searchLog". */373 ZSTD_c_minMatch=105, /* Minimum size of searched matches.374 * Note that Zstandard can still find matches of smaller size,375 * it just tweaks its search algorithm to look for this size and larger.376 * Larger values increase compression and decompression speed, but decrease ratio.377 * Must be clamped between ZSTD_MINMATCH_MIN and ZSTD_MINMATCH_MAX.378 * Note that currently, for all strategies < btopt, effective minimum is 4.379 * , for all strategies > fast, effective maximum is 6.380 * Special: value 0 means "use default minMatchLength". */381 ZSTD_c_targetLength=106, /* Impact of this field depends on strategy.382 * For strategies btopt, btultra & btultra2:383 * Length of Match considered "good enough" to stop search.384 * Larger values make compression stronger, and slower.385 * For strategy fast:386 * Distance between match sampling.387 * Larger values make compression faster, and weaker.388 * Special: value 0 means "use default targetLength". */389 ZSTD_c_strategy=107, /* See ZSTD_strategy enum definition.390 * The higher the value of selected strategy, the more complex it is,391 * resulting in stronger and slower compression.392 * Special: value 0 means "use default strategy". */393 394 ZSTD_c_targetCBlockSize=130, /* v1.5.6+395 * Attempts to fit compressed block size into approximatively targetCBlockSize.396 * Bound by ZSTD_TARGETCBLOCKSIZE_MIN and ZSTD_TARGETCBLOCKSIZE_MAX.397 * Note that it's not a guarantee, just a convergence target (default:0).398 * No target when targetCBlockSize == 0.399 * This is helpful in low bandwidth streaming environments to improve end-to-end latency,400 * when a client can make use of partial documents (a prominent example being Chrome).401 * Note: this parameter is stable since v1.5.6.402 * It was present as an experimental parameter in earlier versions,403 * but it's not recommended using it with earlier library versions404 * due to massive performance regressions.405 */406 /* LDM mode parameters */407 ZSTD_c_enableLongDistanceMatching=160, /* Enable long distance matching.408 * This parameter is designed to improve compression ratio409 * for large inputs, by finding large matches at long distance.410 * It increases memory usage and window size.411 * Note: enabling this parameter increases default ZSTD_c_windowLog to 128 MB412 * except when expressly set to a different value.413 * Note: will be enabled by default if ZSTD_c_windowLog >= 128 MB and414 * compression strategy >= ZSTD_btopt (== compression level 16+) */415 ZSTD_c_ldmHashLog=161, /* Size of the table for long distance matching, as a power of 2.416 * Larger values increase memory usage and compression ratio,417 * but decrease compression speed.418 * Must be clamped between ZSTD_HASHLOG_MIN and ZSTD_HASHLOG_MAX419 * default: windowlog - 7.420 * Special: value 0 means "automatically determine hashlog". */421 ZSTD_c_ldmMinMatch=162, /* Minimum match size for long distance matcher.422 * Larger/too small values usually decrease compression ratio.423 * Must be clamped between ZSTD_LDM_MINMATCH_MIN and ZSTD_LDM_MINMATCH_MAX.424 * Special: value 0 means "use default value" (default: 64). */425 ZSTD_c_ldmBucketSizeLog=163, /* Log size of each bucket in the LDM hash table for collision resolution.426 * Larger values improve collision resolution but decrease compression speed.427 * The maximum value is ZSTD_LDM_BUCKETSIZELOG_MAX.428 * Special: value 0 means "use default value" (default: 3). */429 ZSTD_c_ldmHashRateLog=164, /* Frequency of inserting/looking up entries into the LDM hash table.430 * Must be clamped between 0 and (ZSTD_WINDOWLOG_MAX - ZSTD_HASHLOG_MIN).431 * Default is MAX(0, (windowLog - ldmHashLog)), optimizing hash table usage.432 * Larger values improve compression speed.433 * Deviating far from default value will likely result in a compression ratio decrease.434 * Special: value 0 means "automatically determine hashRateLog". */435 436 /* frame parameters */437 ZSTD_c_contentSizeFlag=200, /* Content size will be written into frame header _whenever known_ (default:1)438 * Content size must be known at the beginning of compression.439 * This is automatically the case when using ZSTD_compress2(),440 * For streaming scenarios, content size must be provided with ZSTD_CCtx_setPledgedSrcSize() */441 ZSTD_c_checksumFlag=201, /* A 32-bits checksum of content is written at end of frame (default:0) */442 ZSTD_c_dictIDFlag=202, /* When applicable, dictionary's ID is written into frame header (default:1) */443 444 /* multi-threading parameters */445 /* These parameters are only active if multi-threading is enabled (compiled with build macro ZSTD_MULTITHREAD).446 * Otherwise, trying to set any other value than default (0) will be a no-op and return an error.447 * In a situation where it's unknown if the linked library supports multi-threading or not,448 * setting ZSTD_c_nbWorkers to any value >= 1 and consulting the return value provides a quick way to check this property.449 */450 ZSTD_c_nbWorkers=400, /* Select how many threads will be spawned to compress in parallel.451 * When nbWorkers >= 1, triggers asynchronous mode when invoking ZSTD_compressStream*() :452 * ZSTD_compressStream*() consumes input and flush output if possible, but immediately gives back control to caller,453 * while compression is performed in parallel, within worker thread(s).454 * (note : a strong exception to this rule is when first invocation of ZSTD_compressStream2() sets ZSTD_e_end :455 * in which case, ZSTD_compressStream2() delegates to ZSTD_compress2(), which is always a blocking call).456 * More workers improve speed, but also increase memory usage.457 * Default value is `0`, aka "single-threaded mode" : no worker is spawned,458 * compression is performed inside Caller's thread, and all invocations are blocking */459 ZSTD_c_jobSize=401, /* Size of a compression job. This value is enforced only when nbWorkers >= 1.460 * Each compression job is completed in parallel, so this value can indirectly impact the nb of active threads.461 * 0 means default, which is dynamically determined based on compression parameters.462 * Job size must be a minimum of overlap size, or ZSTDMT_JOBSIZE_MIN (= 512 KB), whichever is largest.463 * The minimum size is automatically and transparently enforced. */464 ZSTD_c_overlapLog=402, /* Control the overlap size, as a fraction of window size.465 * The overlap size is an amount of data reloaded from previous job at the beginning of a new job.466 * It helps preserve compression ratio, while each job is compressed in parallel.467 * This value is enforced only when nbWorkers >= 1.468 * Larger values increase compression ratio, but decrease speed.469 * Possible values range from 0 to 9 :470 * - 0 means "default" : value will be determined by the library, depending on strategy471 * - 1 means "no overlap"472 * - 9 means "full overlap", using a full window size.473 * Each intermediate rank increases/decreases load size by a factor 2 :474 * 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:default475 * default value varies between 6 and 9, depending on strategy */476 477 /* note : additional experimental parameters are also available478 * within the experimental section of the API.479 * At the time of this writing, they include :480 * ZSTD_c_rsyncable481 * ZSTD_c_format482 * ZSTD_c_forceMaxWindow483 * ZSTD_c_forceAttachDict484 * ZSTD_c_literalCompressionMode485 * ZSTD_c_srcSizeHint486 * ZSTD_c_enableDedicatedDictSearch487 * ZSTD_c_stableInBuffer488 * ZSTD_c_stableOutBuffer489 * ZSTD_c_blockDelimiters490 * ZSTD_c_validateSequences491 * ZSTD_c_useBlockSplitter492 * ZSTD_c_useRowMatchFinder493 * ZSTD_c_prefetchCDictTables494 * ZSTD_c_enableSeqProducerFallback495 * ZSTD_c_maxBlockSize496 * Because they are not stable, it's necessary to define ZSTD_STATIC_LINKING_ONLY to access them.497 * note : never ever use experimentalParam? names directly;498 * also, the enums values themselves are unstable and can still change.499 */500 ZSTD_c_experimentalParam1=500,501 ZSTD_c_experimentalParam2=10,502 ZSTD_c_experimentalParam3=1000,503 ZSTD_c_experimentalParam4=1001,504 ZSTD_c_experimentalParam5=1002,505 /* was ZSTD_c_experimentalParam6=1003; is now ZSTD_c_targetCBlockSize */506 ZSTD_c_experimentalParam7=1004,507 ZSTD_c_experimentalParam8=1005,508 ZSTD_c_experimentalParam9=1006,509 ZSTD_c_experimentalParam10=1007,510 ZSTD_c_experimentalParam11=1008,511 ZSTD_c_experimentalParam12=1009,512 ZSTD_c_experimentalParam13=1010,513 ZSTD_c_experimentalParam14=1011,514 ZSTD_c_experimentalParam15=1012,515 ZSTD_c_experimentalParam16=1013,516 ZSTD_c_experimentalParam17=1014,517 ZSTD_c_experimentalParam18=1015,518 ZSTD_c_experimentalParam19=1016519} ZSTD_cParameter;520 521typedef struct {522 size_t error;523 int lowerBound;524 int upperBound;525} ZSTD_bounds;526 527/*! ZSTD_cParam_getBounds() :528 * All parameters must belong to an interval with lower and upper bounds,529 * otherwise they will either trigger an error or be automatically clamped.530 * @return : a structure, ZSTD_bounds, which contains531 * - an error status field, which must be tested using ZSTD_isError()532 * - lower and upper bounds, both inclusive533 */534ZSTDLIB_API ZSTD_bounds ZSTD_cParam_getBounds(ZSTD_cParameter cParam);535 536/*! ZSTD_CCtx_setParameter() :537 * Set one compression parameter, selected by enum ZSTD_cParameter.538 * All parameters have valid bounds. Bounds can be queried using ZSTD_cParam_getBounds().539 * Providing a value beyond bound will either clamp it, or trigger an error (depending on parameter).540 * Setting a parameter is generally only possible during frame initialization (before starting compression).541 * Exception : when using multi-threading mode (nbWorkers >= 1),542 * the following parameters can be updated _during_ compression (within same frame):543 * => compressionLevel, hashLog, chainLog, searchLog, minMatch, targetLength and strategy.544 * new parameters will be active for next job only (after a flush()).545 * @return : an error code (which can be tested using ZSTD_isError()).546 */547ZSTDLIB_API size_t ZSTD_CCtx_setParameter(ZSTD_CCtx* cctx, ZSTD_cParameter param, int value);548 549/*! ZSTD_CCtx_setPledgedSrcSize() :550 * Total input data size to be compressed as a single frame.551 * Value will be written in frame header, unless if explicitly forbidden using ZSTD_c_contentSizeFlag.552 * This value will also be controlled at end of frame, and trigger an error if not respected.553 * @result : 0, or an error code (which can be tested with ZSTD_isError()).554 * Note 1 : pledgedSrcSize==0 actually means zero, aka an empty frame.555 * In order to mean "unknown content size", pass constant ZSTD_CONTENTSIZE_UNKNOWN.556 * ZSTD_CONTENTSIZE_UNKNOWN is default value for any new frame.557 * Note 2 : pledgedSrcSize is only valid once, for the next frame.558 * It's discarded at the end of the frame, and replaced by ZSTD_CONTENTSIZE_UNKNOWN.559 * Note 3 : Whenever all input data is provided and consumed in a single round,560 * for example with ZSTD_compress2(),561 * or invoking immediately ZSTD_compressStream2(,,,ZSTD_e_end),562 * this value is automatically overridden by srcSize instead.563 */564ZSTDLIB_API size_t ZSTD_CCtx_setPledgedSrcSize(ZSTD_CCtx* cctx, unsigned long long pledgedSrcSize);565 566typedef enum {567 ZSTD_reset_session_only = 1,568 ZSTD_reset_parameters = 2,569 ZSTD_reset_session_and_parameters = 3570} ZSTD_ResetDirective;571 572/*! ZSTD_CCtx_reset() :573 * There are 2 different things that can be reset, independently or jointly :574 * - The session : will stop compressing current frame, and make CCtx ready to start a new one.575 * Useful after an error, or to interrupt any ongoing compression.576 * Any internal data not yet flushed is cancelled.577 * Compression parameters and dictionary remain unchanged.578 * They will be used to compress next frame.579 * Resetting session never fails.580 * - The parameters : changes all parameters back to "default".581 * This also removes any reference to any dictionary or external sequence producer.582 * Parameters can only be changed between 2 sessions (i.e. no compression is currently ongoing)583 * otherwise the reset fails, and function returns an error value (which can be tested using ZSTD_isError())584 * - Both : similar to resetting the session, followed by resetting parameters.585 */586ZSTDLIB_API size_t ZSTD_CCtx_reset(ZSTD_CCtx* cctx, ZSTD_ResetDirective reset);587 588/*! ZSTD_compress2() :589 * Behave the same as ZSTD_compressCCtx(), but compression parameters are set using the advanced API.590 * (note that this entry point doesn't even expose a compression level parameter).591 * ZSTD_compress2() always starts a new frame.592 * Should cctx hold data from a previously unfinished frame, everything about it is forgotten.593 * - Compression parameters are pushed into CCtx before starting compression, using ZSTD_CCtx_set*()594 * - The function is always blocking, returns when compression is completed.595 * NOTE: Providing `dstCapacity >= ZSTD_compressBound(srcSize)` guarantees that zstd will have596 * enough space to successfully compress the data, though it is possible it fails for other reasons.597 * @return : compressed size written into `dst` (<= `dstCapacity),598 * or an error code if it fails (which can be tested using ZSTD_isError()).599 */600ZSTDLIB_API size_t ZSTD_compress2( ZSTD_CCtx* cctx,601 void* dst, size_t dstCapacity,602 const void* src, size_t srcSize);603 604 605/***********************************************606* Advanced decompression API (Requires v1.4.0+)607************************************************/608 609/* The advanced API pushes parameters one by one into an existing DCtx context.610 * Parameters are sticky, and remain valid for all following frames611 * using the same DCtx context.612 * It's possible to reset parameters to default values using ZSTD_DCtx_reset().613 * Note : This API is compatible with existing ZSTD_decompressDCtx() and ZSTD_decompressStream().614 * Therefore, no new decompression function is necessary.615 */616 617typedef enum {618 619 ZSTD_d_windowLogMax=100, /* Select a size limit (in power of 2) beyond which620 * the streaming API will refuse to allocate memory buffer621 * in order to protect the host from unreasonable memory requirements.622 * This parameter is only useful in streaming mode, since no internal buffer is allocated in single-pass mode.623 * By default, a decompression context accepts window sizes <= (1 << ZSTD_WINDOWLOG_LIMIT_DEFAULT).624 * Special: value 0 means "use default maximum windowLog". */625 626 /* note : additional experimental parameters are also available627 * within the experimental section of the API.628 * At the time of this writing, they include :629 * ZSTD_d_format630 * ZSTD_d_stableOutBuffer631 * ZSTD_d_forceIgnoreChecksum632 * ZSTD_d_refMultipleDDicts633 * ZSTD_d_disableHuffmanAssembly634 * ZSTD_d_maxBlockSize635 * Because they are not stable, it's necessary to define ZSTD_STATIC_LINKING_ONLY to access them.636 * note : never ever use experimentalParam? names directly637 */638 ZSTD_d_experimentalParam1=1000,639 ZSTD_d_experimentalParam2=1001,640 ZSTD_d_experimentalParam3=1002,641 ZSTD_d_experimentalParam4=1003,642 ZSTD_d_experimentalParam5=1004,643 ZSTD_d_experimentalParam6=1005644 645} ZSTD_dParameter;646 647/*! ZSTD_dParam_getBounds() :648 * All parameters must belong to an interval with lower and upper bounds,649 * otherwise they will either trigger an error or be automatically clamped.650 * @return : a structure, ZSTD_bounds, which contains651 * - an error status field, which must be tested using ZSTD_isError()652 * - both lower and upper bounds, inclusive653 */654ZSTDLIB_API ZSTD_bounds ZSTD_dParam_getBounds(ZSTD_dParameter dParam);655 656/*! ZSTD_DCtx_setParameter() :657 * Set one compression parameter, selected by enum ZSTD_dParameter.658 * All parameters have valid bounds. Bounds can be queried using ZSTD_dParam_getBounds().659 * Providing a value beyond bound will either clamp it, or trigger an error (depending on parameter).660 * Setting a parameter is only possible during frame initialization (before starting decompression).661 * @return : 0, or an error code (which can be tested using ZSTD_isError()).662 */663ZSTDLIB_API size_t ZSTD_DCtx_setParameter(ZSTD_DCtx* dctx, ZSTD_dParameter param, int value);664 665/*! ZSTD_DCtx_reset() :666 * Return a DCtx to clean state.667 * Session and parameters can be reset jointly or separately.668 * Parameters can only be reset when no active frame is being decompressed.669 * @return : 0, or an error code, which can be tested with ZSTD_isError()670 */671ZSTDLIB_API size_t ZSTD_DCtx_reset(ZSTD_DCtx* dctx, ZSTD_ResetDirective reset);672 673 674/****************************675* Streaming676****************************/677 678typedef struct ZSTD_inBuffer_s {679 const void* src; /**< start of input buffer */680 size_t size; /**< size of input buffer */681 size_t pos; /**< position where reading stopped. Will be updated. Necessarily 0 <= pos <= size */682} ZSTD_inBuffer;683 684typedef struct ZSTD_outBuffer_s {685 void* dst; /**< start of output buffer */686 size_t size; /**< size of output buffer */687 size_t pos; /**< position where writing stopped. Will be updated. Necessarily 0 <= pos <= size */688} ZSTD_outBuffer;689 690 691 692/*-***********************************************************************693* Streaming compression - HowTo694*695* A ZSTD_CStream object is required to track streaming operation.696* Use ZSTD_createCStream() and ZSTD_freeCStream() to create/release resources.697* ZSTD_CStream objects can be reused multiple times on consecutive compression operations.698* It is recommended to reuse ZSTD_CStream since it will play nicer with system's memory, by re-using already allocated memory.699*700* For parallel execution, use one separate ZSTD_CStream per thread.701*702* note : since v1.3.0, ZSTD_CStream and ZSTD_CCtx are the same thing.703*704* Parameters are sticky : when starting a new compression on the same context,705* it will reuse the same sticky parameters as previous compression session.706* When in doubt, it's recommended to fully initialize the context before usage.707* Use ZSTD_CCtx_reset() to reset the context and ZSTD_CCtx_setParameter(),708* ZSTD_CCtx_setPledgedSrcSize(), or ZSTD_CCtx_loadDictionary() and friends to709* set more specific parameters, the pledged source size, or load a dictionary.710*711* Use ZSTD_compressStream2() with ZSTD_e_continue as many times as necessary to712* consume input stream. The function will automatically update both `pos`713* fields within `input` and `output`.714* Note that the function may not consume the entire input, for example, because715* the output buffer is already full, in which case `input.pos < input.size`.716* The caller must check if input has been entirely consumed.717* If not, the caller must make some room to receive more compressed data,718* and then present again remaining input data.719* note: ZSTD_e_continue is guaranteed to make some forward progress when called,720* but doesn't guarantee maximal forward progress. This is especially relevant721* when compressing with multiple threads. The call won't block if it can722* consume some input, but if it can't it will wait for some, but not all,723* output to be flushed.724* @return : provides a minimum amount of data remaining to be flushed from internal buffers725* or an error code, which can be tested using ZSTD_isError().726*727* At any moment, it's possible to flush whatever data might remain stuck within internal buffer,728* using ZSTD_compressStream2() with ZSTD_e_flush. `output->pos` will be updated.729* Note that, if `output->size` is too small, a single invocation with ZSTD_e_flush might not be enough (return code > 0).730* In which case, make some room to receive more compressed data, and call again ZSTD_compressStream2() with ZSTD_e_flush.731* You must continue calling ZSTD_compressStream2() with ZSTD_e_flush until it returns 0, at which point you can change the732* operation.733* note: ZSTD_e_flush will flush as much output as possible, meaning when compressing with multiple threads, it will734* block until the flush is complete or the output buffer is full.735* @return : 0 if internal buffers are entirely flushed,736* >0 if some data still present within internal buffer (the value is minimal estimation of remaining size),737* or an error code, which can be tested using ZSTD_isError().738*739* Calling ZSTD_compressStream2() with ZSTD_e_end instructs to finish a frame.740* It will perform a flush and write frame epilogue.741* The epilogue is required for decoders to consider a frame completed.742* flush operation is the same, and follows same rules as calling ZSTD_compressStream2() with ZSTD_e_flush.743* You must continue calling ZSTD_compressStream2() with ZSTD_e_end until it returns 0, at which point you are free to744* start a new frame.745* note: ZSTD_e_end will flush as much output as possible, meaning when compressing with multiple threads, it will746* block until the flush is complete or the output buffer is full.747* @return : 0 if frame fully completed and fully flushed,748* >0 if some data still present within internal buffer (the value is minimal estimation of remaining size),749* or an error code, which can be tested using ZSTD_isError().750*751* *******************************************************************/752 753typedef ZSTD_CCtx ZSTD_CStream; /**< CCtx and CStream are now effectively same object (>= v1.3.0) */754 /* Continue to distinguish them for compatibility with older versions <= v1.2.0 */755/*===== ZSTD_CStream management functions =====*/756ZSTDLIB_API ZSTD_CStream* ZSTD_createCStream(void);757ZSTDLIB_API size_t ZSTD_freeCStream(ZSTD_CStream* zcs); /* accept NULL pointer */758 759/*===== Streaming compression functions =====*/760typedef enum {761 ZSTD_e_continue=0, /* collect more data, encoder decides when to output compressed result, for optimal compression ratio */762 ZSTD_e_flush=1, /* flush any data provided so far,763 * it creates (at least) one new block, that can be decoded immediately on reception;764 * frame will continue: any future data can still reference previously compressed data, improving compression.765 * note : multithreaded compression will block to flush as much output as possible. */766 ZSTD_e_end=2 /* flush any remaining data _and_ close current frame.767 * note that frame is only closed after compressed data is fully flushed (return value == 0).768 * After that point, any additional data starts a new frame.769 * note : each frame is independent (does not reference any content from previous frame).770 : note : multithreaded compression will block to flush as much output as possible. */771} ZSTD_EndDirective;772 773/*! ZSTD_compressStream2() : Requires v1.4.0+774 * Behaves about the same as ZSTD_compressStream, with additional control on end directive.775 * - Compression parameters are pushed into CCtx before starting compression, using ZSTD_CCtx_set*()776 * - Compression parameters cannot be changed once compression is started (save a list of exceptions in multi-threading mode)777 * - output->pos must be <= dstCapacity, input->pos must be <= srcSize778 * - output->pos and input->pos will be updated. They are guaranteed to remain below their respective limit.779 * - endOp must be a valid directive780 * - When nbWorkers==0 (default), function is blocking : it completes its job before returning to caller.781 * - 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,782 * and then immediately returns, just indicating that there is some data remaining to be flushed.783 * The function nonetheless guarantees forward progress : it will return only after it reads or write at least 1+ byte.784 * - 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.785 * - @return provides a minimum amount of data remaining to be flushed from internal buffers786 * or an error code, which can be tested using ZSTD_isError().787 * if @return != 0, flush is not fully completed, there is still some data left within internal buffers.788 * This is useful for ZSTD_e_flush, since in this case more flushes are necessary to empty all buffers.789 * For ZSTD_e_end, @return == 0 when internal buffers are fully flushed and frame is completed.790 * - after a ZSTD_e_end directive, if internal buffer is not fully flushed (@return != 0),791 * only ZSTD_e_end or ZSTD_e_flush operations are allowed.792 * Before starting a new compression job, or changing compression parameters,793 * it is required to fully flush internal buffers.794 * - note: if an operation ends with an error, it may leave @cctx in an undefined state.795 * Therefore, it's UB to invoke ZSTD_compressStream2() of ZSTD_compressStream() on such a state.796 * In order to be re-employed after an error, a state must be reset,797 * which can be done explicitly (ZSTD_CCtx_reset()),798 * or is sometimes implied by methods starting a new compression job (ZSTD_initCStream(), ZSTD_compressCCtx())799 */800ZSTDLIB_API size_t ZSTD_compressStream2( ZSTD_CCtx* cctx,801 ZSTD_outBuffer* output,802 ZSTD_inBuffer* input,803 ZSTD_EndDirective endOp);804 805 806/* These buffer sizes are softly recommended.807 * They are not required : ZSTD_compressStream*() happily accepts any buffer size, for both input and output.808 * Respecting the recommended size just makes it a bit easier for ZSTD_compressStream*(),809 * reducing the amount of memory shuffling and buffering, resulting in minor performance savings.810 *811 * However, note that these recommendations are from the perspective of a C caller program.812 * If the streaming interface is invoked from some other language,813 * especially managed ones such as Java or Go, through a foreign function interface such as jni or cgo,814 * a major performance rule is to reduce crossing such interface to an absolute minimum.815 * It's not rare that performance ends being spent more into the interface, rather than compression itself.816 * In which cases, prefer using large buffers, as large as practical,817 * for both input and output, to reduce the nb of roundtrips.818 */819ZSTDLIB_API size_t ZSTD_CStreamInSize(void); /**< recommended size for input buffer */820ZSTDLIB_API size_t ZSTD_CStreamOutSize(void); /**< recommended size for output buffer. Guarantee to successfully flush at least one complete compressed block. */821 822 823/* *****************************************************************************824 * This following is a legacy streaming API, available since v1.0+ .825 * It can be replaced by ZSTD_CCtx_reset() and ZSTD_compressStream2().826 * It is redundant, but remains fully supported.827 ******************************************************************************/828 829/*!830 * Equivalent to:831 *832 * ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only);833 * ZSTD_CCtx_refCDict(zcs, NULL); // clear the dictionary (if any)834 * ZSTD_CCtx_setParameter(zcs, ZSTD_c_compressionLevel, compressionLevel);835 *836 * Note that ZSTD_initCStream() clears any previously set dictionary. Use the new API837 * to compress with a dictionary.838 */839ZSTDLIB_API size_t ZSTD_initCStream(ZSTD_CStream* zcs, int compressionLevel);840/*!841 * Alternative for ZSTD_compressStream2(zcs, output, input, ZSTD_e_continue).842 * NOTE: The return value is different. ZSTD_compressStream() returns a hint for843 * the next read size (if non-zero and not an error). ZSTD_compressStream2()844 * returns the minimum nb of bytes left to flush (if non-zero and not an error).845 */846ZSTDLIB_API size_t ZSTD_compressStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output, ZSTD_inBuffer* input);847/*! Equivalent to ZSTD_compressStream2(zcs, output, &emptyInput, ZSTD_e_flush). */848ZSTDLIB_API size_t ZSTD_flushStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output);849/*! Equivalent to ZSTD_compressStream2(zcs, output, &emptyInput, ZSTD_e_end). */850ZSTDLIB_API size_t ZSTD_endStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output);851 852 853/*-***************************************************************************854* Streaming decompression - HowTo855*856* A ZSTD_DStream object is required to track streaming operations.857* Use ZSTD_createDStream() and ZSTD_freeDStream() to create/release resources.858* ZSTD_DStream objects can be reused multiple times.859*860* Use ZSTD_initDStream() to start a new decompression operation.861* @return : recommended first input size862* Alternatively, use advanced API to set specific properties.863*864* Use ZSTD_decompressStream() repetitively to consume your input.865* The function will update both `pos` fields.866* If `input.pos < input.size`, some input has not been consumed.867* It's up to the caller to present again remaining data.868* The function tries to flush all data decoded immediately, respecting output buffer size.869* If `output.pos < output.size`, decoder has flushed everything it could.870* But if `output.pos == output.size`, there might be some data left within internal buffers.,871* In which case, call ZSTD_decompressStream() again to flush whatever remains in the buffer.872* Note : with no additional input provided, amount of data flushed is necessarily <= ZSTD_BLOCKSIZE_MAX.873* @return : 0 when a frame is completely decoded and fully flushed,874* or an error code, which can be tested using ZSTD_isError(),875* or any other value > 0, which means there is still some decoding or flushing to do to complete current frame :876* the return value is a suggested next input size (just a hint for better latency)877* that will never request more than the remaining frame size.878* *******************************************************************************/879 880typedef ZSTD_DCtx ZSTD_DStream; /**< DCtx and DStream are now effectively same object (>= v1.3.0) */881 /* For compatibility with versions <= v1.2.0, prefer differentiating them. */882/*===== ZSTD_DStream management functions =====*/883ZSTDLIB_API ZSTD_DStream* ZSTD_createDStream(void);884ZSTDLIB_API size_t ZSTD_freeDStream(ZSTD_DStream* zds); /* accept NULL pointer */885 886/*===== Streaming decompression functions =====*/887 888/*! ZSTD_initDStream() :889 * Initialize/reset DStream state for new decompression operation.890 * Call before new decompression operation using same DStream.891 *892 * Note : This function is redundant with the advanced API and equivalent to:893 * ZSTD_DCtx_reset(zds, ZSTD_reset_session_only);894 * ZSTD_DCtx_refDDict(zds, NULL);895 */896ZSTDLIB_API size_t ZSTD_initDStream(ZSTD_DStream* zds);897 898/*! ZSTD_decompressStream() :899 * Streaming decompression function.900 * Call repetitively to consume full input updating it as necessary.901 * Function will update both input and output `pos` fields exposing current state via these fields:902 * - `input.pos < input.size`, some input remaining and caller should provide remaining input903 * on the next call.904 * - `output.pos < output.size`, decoder finished and flushed all remaining buffers.905 * - `output.pos == output.size`, potentially uncflushed data present in the internal buffers,906 * call ZSTD_decompressStream() again to flush remaining data to output.907 * Note : with no additional input, amount of data flushed <= ZSTD_BLOCKSIZE_MAX.908 *909 * @return : 0 when a frame is completely decoded and fully flushed,910 * or an error code, which can be tested using ZSTD_isError(),911 * or any other value > 0, which means there is some decoding or flushing to do to complete current frame.912 *913 * Note: when an operation returns with an error code, the @zds state may be left in undefined state.914 * It's UB to invoke `ZSTD_decompressStream()` on such a state.915 * In order to re-use such a state, it must be first reset,916 * which can be done explicitly (`ZSTD_DCtx_reset()`),917 * or is implied for operations starting some new decompression job (`ZSTD_initDStream`, `ZSTD_decompressDCtx()`, `ZSTD_decompress_usingDict()`)918 */919ZSTDLIB_API size_t ZSTD_decompressStream(ZSTD_DStream* zds, ZSTD_outBuffer* output, ZSTD_inBuffer* input);920 921ZSTDLIB_API size_t ZSTD_DStreamInSize(void); /*!< recommended size for input buffer */922ZSTDLIB_API size_t ZSTD_DStreamOutSize(void); /*!< recommended size for output buffer. Guarantee to successfully flush at least one complete block in all circumstances. */923 924 925/**************************926* Simple dictionary API927***************************/928/*! ZSTD_compress_usingDict() :929 * Compression at an explicit compression level using a Dictionary.930 * A dictionary can be any arbitrary data segment (also called a prefix),931 * or a buffer with specified information (see zdict.h).932 * Note : This function loads the dictionary, resulting in significant startup delay.933 * It's intended for a dictionary used only once.934 * Note 2 : When `dict == NULL || dictSize < 8` no dictionary is used. */935ZSTDLIB_API size_t ZSTD_compress_usingDict(ZSTD_CCtx* ctx,936 void* dst, size_t dstCapacity,937 const void* src, size_t srcSize,938 const void* dict,size_t dictSize,939 int compressionLevel);940 941/*! ZSTD_decompress_usingDict() :942 * Decompression using a known Dictionary.943 * Dictionary must be identical to the one used during compression.944 * Note : This function loads the dictionary, resulting in significant startup delay.945 * It's intended for a dictionary used only once.946 * Note : When `dict == NULL || dictSize < 8` no dictionary is used. */947ZSTDLIB_API size_t ZSTD_decompress_usingDict(ZSTD_DCtx* dctx,948 void* dst, size_t dstCapacity,949 const void* src, size_t srcSize,950 const void* dict,size_t dictSize);951 952 953/***********************************954 * Bulk processing dictionary API955 **********************************/956typedef struct ZSTD_CDict_s ZSTD_CDict;957 958/*! ZSTD_createCDict() :959 * When compressing multiple messages or blocks using the same dictionary,960 * it's recommended to digest the dictionary only once, since it's a costly operation.961 * ZSTD_createCDict() will create a state from digesting a dictionary.962 * The resulting state can be used for future compression operations with very limited startup cost.963 * ZSTD_CDict can be created once and shared by multiple threads concurrently, since its usage is read-only.964 * @dictBuffer can be released after ZSTD_CDict creation, because its content is copied within CDict.965 * Note 1 : Consider experimental function `ZSTD_createCDict_byReference()` if you prefer to not duplicate @dictBuffer content.966 * Note 2 : A ZSTD_CDict can be created from an empty @dictBuffer,967 * in which case the only thing that it transports is the @compressionLevel.968 * This can be useful in a pipeline featuring ZSTD_compress_usingCDict() exclusively,969 * expecting a ZSTD_CDict parameter with any data, including those without a known dictionary. */970ZSTDLIB_API ZSTD_CDict* ZSTD_createCDict(const void* dictBuffer, size_t dictSize,971 int compressionLevel);972 973/*! ZSTD_freeCDict() :974 * Function frees memory allocated by ZSTD_createCDict().975 * If a NULL pointer is passed, no operation is performed. */976ZSTDLIB_API size_t ZSTD_freeCDict(ZSTD_CDict* CDict);977 978/*! ZSTD_compress_usingCDict() :979 * Compression using a digested Dictionary.980 * Recommended when same dictionary is used multiple times.981 * Note : compression level is _decided at dictionary creation time_,982 * and frame parameters are hardcoded (dictID=yes, contentSize=yes, checksum=no) */983ZSTDLIB_API size_t ZSTD_compress_usingCDict(ZSTD_CCtx* cctx,984 void* dst, size_t dstCapacity,985 const void* src, size_t srcSize,986 const ZSTD_CDict* cdict);987 988 989typedef struct ZSTD_DDict_s ZSTD_DDict;990 991/*! ZSTD_createDDict() :992 * Create a digested dictionary, ready to start decompression operation without startup delay.993 * dictBuffer can be released after DDict creation, as its content is copied inside DDict. */994ZSTDLIB_API ZSTD_DDict* ZSTD_createDDict(const void* dictBuffer, size_t dictSize);995 996/*! ZSTD_freeDDict() :997 * Function frees memory allocated with ZSTD_createDDict()998 * If a NULL pointer is passed, no operation is performed. */999ZSTDLIB_API size_t ZSTD_freeDDict(ZSTD_DDict* ddict);1000 1001/*! ZSTD_decompress_usingDDict() :1002 * Decompression using a digested Dictionary.1003 * Recommended when same dictionary is used multiple times. */1004ZSTDLIB_API size_t ZSTD_decompress_usingDDict(ZSTD_DCtx* dctx,1005 void* dst, size_t dstCapacity,1006 const void* src, size_t srcSize,1007 const ZSTD_DDict* ddict);1008 1009 1010/********************************1011 * Dictionary helper functions1012 *******************************/1013 1014/*! ZSTD_getDictID_fromDict() : Requires v1.4.0+1015 * Provides the dictID stored within dictionary.1016 * if @return == 0, the dictionary is not conformant with Zstandard specification.1017 * It can still be loaded, but as a content-only dictionary. */1018ZSTDLIB_API unsigned ZSTD_getDictID_fromDict(const void* dict, size_t dictSize);1019 1020/*! ZSTD_getDictID_fromCDict() : Requires v1.5.0+1021 * Provides the dictID of the dictionary loaded into `cdict`.1022 * If @return == 0, the dictionary is not conformant to Zstandard specification, or empty.1023 * Non-conformant dictionaries can still be loaded, but as content-only dictionaries. */1024ZSTDLIB_API unsigned ZSTD_getDictID_fromCDict(const ZSTD_CDict* cdict);1025 1026/*! ZSTD_getDictID_fromDDict() : Requires v1.4.0+1027 * Provides the dictID of the dictionary loaded into `ddict`.1028 * If @return == 0, the dictionary is not conformant to Zstandard specification, or empty.1029 * Non-conformant dictionaries can still be loaded, but as content-only dictionaries. */1030ZSTDLIB_API unsigned ZSTD_getDictID_fromDDict(const ZSTD_DDict* ddict);1031 1032/*! ZSTD_getDictID_fromFrame() : Requires v1.4.0+1033 * Provides the dictID required to decompressed the frame stored within `src`.1034 * If @return == 0, the dictID could not be decoded.1035 * This could for one of the following reasons :1036 * - The frame does not require a dictionary to be decoded (most common case).1037 * - The frame was built with dictID intentionally removed. Whatever dictionary is necessary is a hidden piece of information.1038 * Note : this use case also happens when using a non-conformant dictionary.1039 * - `srcSize` is too small, and as a result, the frame header could not be decoded (only possible if `srcSize < ZSTD_FRAMEHEADERSIZE_MAX`).1040 * - This is not a Zstandard frame.1041 * When identifying the exact failure cause, it's possible to use ZSTD_getFrameHeader(), which will provide a more precise error code. */1042ZSTDLIB_API unsigned ZSTD_getDictID_fromFrame(const void* src, size_t srcSize);1043 1044 1045/*******************************************************************************1046 * Advanced dictionary and prefix API (Requires v1.4.0+)1047 *1048 * This API allows dictionaries to be used with ZSTD_compress2(),1049 * ZSTD_compressStream2(), and ZSTD_decompressDCtx().1050 * Dictionaries are sticky, they remain valid when same context is reused,1051 * they only reset when the context is reset1052 * with ZSTD_reset_parameters or ZSTD_reset_session_and_parameters.1053 * In contrast, Prefixes are single-use.1054 ******************************************************************************/1055 1056 1057/*! ZSTD_CCtx_loadDictionary() : Requires v1.4.0+1058 * Create an internal CDict from `dict` buffer.1059 * Decompression will have to use same dictionary.1060 * @result : 0, or an error code (which can be tested with ZSTD_isError()).1061 * Special: Loading a NULL (or 0-size) dictionary invalidates previous dictionary,1062 * meaning "return to no-dictionary mode".1063 * Note 1 : Dictionary is sticky, it will be used for all future compressed frames,1064 * until parameters are reset, a new dictionary is loaded, or the dictionary1065 * is explicitly invalidated by loading a NULL dictionary.1066 * Note 2 : Loading a dictionary involves building tables.1067 * It's also a CPU consuming operation, with non-negligible impact on latency.1068 * Tables are dependent on compression parameters, and for this reason,1069 * compression parameters can no longer be changed after loading a dictionary.1070 * Note 3 :`dict` content will be copied internally.1071 * Use experimental ZSTD_CCtx_loadDictionary_byReference() to reference content instead.1072 * In such a case, dictionary buffer must outlive its users.1073 * Note 4 : Use ZSTD_CCtx_loadDictionary_advanced()1074 * to precisely select how dictionary content must be interpreted.1075 * Note 5 : This method does not benefit from LDM (long distance mode).1076 * If you want to employ LDM on some large dictionary content,1077 * prefer employing ZSTD_CCtx_refPrefix() described below.1078 */1079ZSTDLIB_API size_t ZSTD_CCtx_loadDictionary(ZSTD_CCtx* cctx, const void* dict, size_t dictSize);1080 1081/*! ZSTD_CCtx_refCDict() : Requires v1.4.0+1082 * Reference a prepared dictionary, to be used for all future compressed frames.1083 * Note that compression parameters are enforced from within CDict,1084 * and supersede any compression parameter previously set within CCtx.1085 * The parameters ignored are labelled as "superseded-by-cdict" in the ZSTD_cParameter enum docs.1086 * The ignored parameters will be used again if the CCtx is returned to no-dictionary mode.1087 * The dictionary will remain valid for future compressed frames using same CCtx.1088 * @result : 0, or an error code (which can be tested with ZSTD_isError()).1089 * Special : Referencing a NULL CDict means "return to no-dictionary mode".1090 * Note 1 : Currently, only one dictionary can be managed.1091 * Referencing a new dictionary effectively "discards" any previous one.1092 * Note 2 : CDict is just referenced, its lifetime must outlive its usage within CCtx. */1093ZSTDLIB_API size_t ZSTD_CCtx_refCDict(ZSTD_CCtx* cctx, const ZSTD_CDict* cdict);1094 1095/*! ZSTD_CCtx_refPrefix() : Requires v1.4.0+1096 * Reference a prefix (single-usage dictionary) for next compressed frame.1097 * A prefix is **only used once**. Tables are discarded at end of frame (ZSTD_e_end).1098 * Decompression will need same prefix to properly regenerate data.1099 * Compressing with a prefix is similar in outcome as performing a diff and compressing it,1100 * but performs much faster, especially during decompression (compression speed is tunable with compression level).1101 * This method is compatible with LDM (long distance mode).1102 * @result : 0, or an error code (which can be tested with ZSTD_isError()).1103 * Special: Adding any prefix (including NULL) invalidates any previous prefix or dictionary1104 * Note 1 : Prefix buffer is referenced. It **must** outlive compression.1105 * Its content must remain unmodified during compression.1106 * Note 2 : If the intention is to diff some large src data blob with some prior version of itself,1107 * ensure that the window size is large enough to contain the entire source.1108 * See ZSTD_c_windowLog.1109 * Note 3 : Referencing a prefix involves building tables, which are dependent on compression parameters.1110 * It's a CPU consuming operation, with non-negligible impact on latency.1111 * If there is a need to use the same prefix multiple times, consider loadDictionary instead.1112 * Note 4 : By default, the prefix is interpreted as raw content (ZSTD_dct_rawContent).1113 * Use experimental ZSTD_CCtx_refPrefix_advanced() to alter dictionary interpretation. */1114ZSTDLIB_API size_t ZSTD_CCtx_refPrefix(ZSTD_CCtx* cctx,1115 const void* prefix, size_t prefixSize);1116 1117/*! ZSTD_DCtx_loadDictionary() : Requires v1.4.0+1118 * Create an internal DDict from dict buffer, to be used to decompress all future frames.1119 * The dictionary remains valid for all future frames, until explicitly invalidated, or1120 * a new dictionary is loaded.1121 * @result : 0, or an error code (which can be tested with ZSTD_isError()).1122 * Special : Adding a NULL (or 0-size) dictionary invalidates any previous dictionary,1123 * meaning "return to no-dictionary mode".1124 * Note 1 : Loading a dictionary involves building tables,1125 * which has a non-negligible impact on CPU usage and latency.1126 * It's recommended to "load once, use many times", to amortize the cost1127 * Note 2 :`dict` content will be copied internally, so `dict` can be released after loading.1128 * Use ZSTD_DCtx_loadDictionary_byReference() to reference dictionary content instead.1129 * Note 3 : Use ZSTD_DCtx_loadDictionary_advanced() to take control of1130 * how dictionary content is loaded and interpreted.1131 */1132ZSTDLIB_API size_t ZSTD_DCtx_loadDictionary(ZSTD_DCtx* dctx, const void* dict, size_t dictSize);1133 1134/*! ZSTD_DCtx_refDDict() : Requires v1.4.0+1135 * Reference a prepared dictionary, to be used to decompress next frames.1136 * The dictionary remains active for decompression of future frames using same DCtx.1137 *1138 * If called with ZSTD_d_refMultipleDDicts enabled, repeated calls of this function1139 * will store the DDict references in a table, and the DDict used for decompression1140 * will be determined at decompression time, as per the dict ID in the frame.1141 * The memory for the table is allocated on the first call to refDDict, and can be1142 * freed with ZSTD_freeDCtx().1143 *1144 * If called with ZSTD_d_refMultipleDDicts disabled (the default), only one dictionary1145 * will be managed, and referencing a dictionary effectively "discards" any previous one.1146 *1147 * @result : 0, or an error code (which can be tested with ZSTD_isError()).1148 * Special: referencing a NULL DDict means "return to no-dictionary mode".1149 * Note 2 : DDict is just referenced, its lifetime must outlive its usage from DCtx.1150 */1151ZSTDLIB_API size_t ZSTD_DCtx_refDDict(ZSTD_DCtx* dctx, const ZSTD_DDict* ddict);1152 1153/*! ZSTD_DCtx_refPrefix() : Requires v1.4.0+1154 * Reference a prefix (single-usage dictionary) to decompress next frame.1155 * This is the reverse operation of ZSTD_CCtx_refPrefix(),1156 * and must use the same prefix as the one used during compression.1157 * Prefix is **only used once**. Reference is discarded at end of frame.1158 * End of frame is reached when ZSTD_decompressStream() returns 0.1159 * @result : 0, or an error code (which can be tested with ZSTD_isError()).1160 * Note 1 : Adding any prefix (including NULL) invalidates any previously set prefix or dictionary1161 * Note 2 : Prefix buffer is referenced. It **must** outlive decompression.1162 * Prefix buffer must remain unmodified up to the end of frame,1163 * reached when ZSTD_decompressStream() returns 0.1164 * Note 3 : By default, the prefix is treated as raw content (ZSTD_dct_rawContent).1165 * Use ZSTD_CCtx_refPrefix_advanced() to alter dictMode (Experimental section)1166 * Note 4 : Referencing a raw content prefix has almost no cpu nor memory cost.1167 * A full dictionary is more costly, as it requires building tables.1168 */1169ZSTDLIB_API size_t ZSTD_DCtx_refPrefix(ZSTD_DCtx* dctx,1170 const void* prefix, size_t prefixSize);1171 1172/* === Memory management === */1173 1174/*! ZSTD_sizeof_*() : Requires v1.4.0+1175 * These functions give the _current_ memory usage of selected object.1176 * Note that object memory usage can evolve (increase or decrease) over time. */1177ZSTDLIB_API size_t ZSTD_sizeof_CCtx(const ZSTD_CCtx* cctx);1178ZSTDLIB_API size_t ZSTD_sizeof_DCtx(const ZSTD_DCtx* dctx);1179ZSTDLIB_API size_t ZSTD_sizeof_CStream(const ZSTD_CStream* zcs);1180ZSTDLIB_API size_t ZSTD_sizeof_DStream(const ZSTD_DStream* zds);1181ZSTDLIB_API size_t ZSTD_sizeof_CDict(const ZSTD_CDict* cdict);1182ZSTDLIB_API size_t ZSTD_sizeof_DDict(const ZSTD_DDict* ddict);1183 1184#endif /* ZSTD_H_235446 */1185 1186 1187/* **************************************************************************************1188 * ADVANCED AND EXPERIMENTAL FUNCTIONS1189 ****************************************************************************************1190 * The definitions in the following section are considered experimental.1191 * They are provided for advanced scenarios.1192 * They should never be used with a dynamic library, as prototypes may change in the future.1193 * Use them only in association with static linking.1194 * ***************************************************************************************/1195 1196#if defined(ZSTD_STATIC_LINKING_ONLY) && !defined(ZSTD_H_ZSTD_STATIC_LINKING_ONLY)1197#define ZSTD_H_ZSTD_STATIC_LINKING_ONLY1198 1199/* This can be overridden externally to hide static symbols. */1200#ifndef ZSTDLIB_STATIC_API