Path: blob/main/sys/contrib/openzfs/module/zstd/lib/zstd.h
48531 views
// SPDX-License-Identifier: BSD-3-Clause OR GPL-2.0-only1/*2* Copyright (c) 2016-2020, Yann Collet, Facebook, Inc.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#endif1314#ifndef ZSTD_H_23544615#define ZSTD_H_2354461617/* ====== Dependency ======*/18#include <limits.h> /* INT_MAX */19#include <stddef.h> /* size_t */202122/* ===== ZSTDLIB_API : control library symbols visibility ===== */23#ifndef ZSTDLIB_VISIBILITY24# if defined(__GNUC__) && (__GNUC__ >= 4)25# define ZSTDLIB_VISIBILITY __attribute__ ((visibility ("default")))26# else27# define ZSTDLIB_VISIBILITY28# endif29#endif30#if defined(ZSTD_DLL_EXPORT) && (ZSTD_DLL_EXPORT==1)31# define ZSTDLIB_API __declspec(dllexport) ZSTDLIB_VISIBILITY32#elif defined(ZSTD_DLL_IMPORT) && (ZSTD_DLL_IMPORT==1)33# define ZSTDLIB_API __declspec(dllimport) ZSTDLIB_VISIBILITY /* It isn't required but allows to generate better code, saving a function pointer load from the IAT and an indirect jump.*/34#else35# define ZSTDLIB_API ZSTDLIB_VISIBILITY36#endif373839/*******************************************************************************40Introduction4142zstd, short for Zstandard, is a fast lossless compression algorithm, targeting43real-time compression scenarios at zlib-level and better compression ratios.44The zstd compression library provides in-memory compression and decompression45functions.4647The library supports regular compression levels from 1 up to ZSTD_maxCLevel(),48which is currently 22. Levels >= 20, labeled `--ultra`, should be used with49caution, as they require more memory. The library also offers negative50compression levels, which extend the range of speed vs. ratio preferences.51The lower the level, the faster the speed (at the cost of compression).5253Compression can be done in:54- a single step (described as Simple API)55- a single step, reusing a context (described as Explicit context)56- unbounded multiple steps (described as Streaming compression)5758The compression ratio achievable on small data can be highly improved using59a dictionary. Dictionary compression can be performed in:60- a single step (described as Simple dictionary API)61- a single step, reusing a dictionary (described as Bulk-processing62dictionary API)6364Advanced experimental functions can be accessed using65`#define ZSTD_STATIC_LINKING_ONLY` before including zstd.h.6667Advanced experimental APIs should never be used with a dynamically-linked68library. They are not "stable"; their definitions or signatures may change in69the future. Only static linking is allowed.70*******************************************************************************/7172/*------ Version ------*/73#define ZSTD_VERSION_MAJOR 174#define ZSTD_VERSION_MINOR 475#define ZSTD_VERSION_RELEASE 57677#define ZSTD_VERSION_NUMBER (ZSTD_VERSION_MAJOR *100*100 + ZSTD_VERSION_MINOR *100 + ZSTD_VERSION_RELEASE)78ZSTDLIB_API unsigned ZSTD_versionNumber(void); /**< to check runtime library version */7980#define ZSTD_LIB_VERSION ZSTD_VERSION_MAJOR.ZSTD_VERSION_MINOR.ZSTD_VERSION_RELEASE81#define ZSTD_QUOTE(str) #str82#define ZSTD_EXPAND_AND_QUOTE(str) ZSTD_QUOTE(str)83#define ZSTD_VERSION_STRING ZSTD_EXPAND_AND_QUOTE(ZSTD_LIB_VERSION)84ZSTDLIB_API const char* ZSTD_versionString(void); /* requires v1.3.0+ */8586/* *************************************87* Default constant88***************************************/89#ifndef ZSTD_CLEVEL_DEFAULT90# define ZSTD_CLEVEL_DEFAULT 391#endif9293/* *************************************94* Constants95***************************************/9697/* All magic numbers are supposed read/written to/from files/memory using little-endian convention */98#define ZSTD_MAGICNUMBER 0xFD2FB528 /* valid since v0.8.0 */99#define ZSTD_MAGIC_DICTIONARY 0xEC30A437 /* valid since v0.7.0 */100#define ZSTD_MAGIC_SKIPPABLE_START 0x184D2A50 /* all 16 values, from 0x184D2A50 to 0x184D2A5F, signal the beginning of a skippable frame */101#define ZSTD_MAGIC_SKIPPABLE_MASK 0xFFFFFFF0102103#define ZSTD_BLOCKSIZELOG_MAX 17104#define ZSTD_BLOCKSIZE_MAX (1<<ZSTD_BLOCKSIZELOG_MAX)105106107108/***************************************109* Simple API110***************************************/111/*! ZSTD_compress() :112* Compresses `src` content as a single zstd compressed frame into already allocated `dst`.113* Hint : compression runs faster if `dstCapacity` >= `ZSTD_compressBound(srcSize)`.114* @return : compressed size written into `dst` (<= `dstCapacity),115* or an error code if it fails (which can be tested using ZSTD_isError()). */116ZSTDLIB_API size_t ZSTD_compress( void* dst, size_t dstCapacity,117const void* src, size_t srcSize,118int compressionLevel);119120/*! ZSTD_decompress() :121* `compressedSize` : must be the _exact_ size of some number of compressed and/or skippable frames.122* `dstCapacity` is an upper bound of originalSize to regenerate.123* If user cannot imply a maximum upper bound, it's better to use streaming mode to decompress data.124* @return : the number of bytes decompressed into `dst` (<= `dstCapacity`),125* or an errorCode if it fails (which can be tested using ZSTD_isError()). */126ZSTDLIB_API size_t ZSTD_decompress( void* dst, size_t dstCapacity,127const void* src, size_t compressedSize);128129/*! ZSTD_getFrameContentSize() : requires v1.3.0+130* `src` should point to the start of a ZSTD encoded frame.131* `srcSize` must be at least as large as the frame header.132* hint : any size >= `ZSTD_frameHeaderSize_max` is large enough.133* @return : - decompressed size of `src` frame content, if known134* - ZSTD_CONTENTSIZE_UNKNOWN if the size cannot be determined135* - ZSTD_CONTENTSIZE_ERROR if an error occurred (e.g. invalid magic number, srcSize too small)136* note 1 : a 0 return value means the frame is valid but "empty".137* note 2 : decompressed size is an optional field, it may not be present, typically in streaming mode.138* When `return==ZSTD_CONTENTSIZE_UNKNOWN`, data to decompress could be any size.139* In which case, it's necessary to use streaming mode to decompress data.140* Optionally, application can rely on some implicit limit,141* as ZSTD_decompress() only needs an upper bound of decompressed size.142* (For example, data could be necessarily cut into blocks <= 16 KB).143* note 3 : decompressed size is always present when compression is completed using single-pass functions,144* such as ZSTD_compress(), ZSTD_compressCCtx() ZSTD_compress_usingDict() or ZSTD_compress_usingCDict().145* note 4 : decompressed size can be very large (64-bits value),146* potentially larger than what local system can handle as a single memory segment.147* In which case, it's necessary to use streaming mode to decompress data.148* note 5 : If source is untrusted, decompressed size could be wrong or intentionally modified.149* Always ensure return value fits within application's authorized limits.150* Each application can set its own limits.151* note 6 : This function replaces ZSTD_getDecompressedSize() */152#define ZSTD_CONTENTSIZE_UNKNOWN (0ULL - 1)153#define ZSTD_CONTENTSIZE_ERROR (0ULL - 2)154ZSTDLIB_API unsigned long long ZSTD_getFrameContentSize(const void *src, size_t srcSize);155156/*! ZSTD_getDecompressedSize() :157* NOTE: This function is now obsolete, in favor of ZSTD_getFrameContentSize().158* Both functions work the same way, but ZSTD_getDecompressedSize() blends159* "empty", "unknown" and "error" results to the same return value (0),160* while ZSTD_getFrameContentSize() gives them separate return values.161* @return : decompressed size of `src` frame content _if known and not empty_, 0 otherwise. */162ZSTDLIB_API unsigned long long ZSTD_getDecompressedSize(const void* src, size_t srcSize);163164/*! ZSTD_findFrameCompressedSize() :165* `src` should point to the start of a ZSTD frame or skippable frame.166* `srcSize` must be >= first frame size167* @return : the compressed size of the first frame starting at `src`,168* suitable to pass as `srcSize` to `ZSTD_decompress` or similar,169* or an error code if input is invalid */170ZSTDLIB_API size_t ZSTD_findFrameCompressedSize(const void* src, size_t srcSize);171172173/*====== Helper functions ======*/174#define ZSTD_COMPRESSBOUND(srcSize) ((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 */175ZSTDLIB_API size_t ZSTD_compressBound(size_t srcSize); /*!< maximum compressed size in worst case single-pass scenario */176ZSTDLIB_API unsigned ZSTD_isError(size_t code); /*!< tells if a `size_t` function result is an error code */177ZSTDLIB_API const char* ZSTD_getErrorName(size_t code); /*!< provides readable string from an error code */178ZSTDLIB_API int ZSTD_minCLevel(void); /*!< minimum negative compression level allowed */179ZSTDLIB_API int ZSTD_maxCLevel(void); /*!< maximum compression level available */180181182/***************************************183* Explicit context184***************************************/185/*= Compression context186* When compressing many times,187* it is recommended to allocate a context just once,188* and re-use it for each successive compression operation.189* This will make workload friendlier for system's memory.190* Note : re-using context is just a speed / resource optimization.191* It doesn't change the compression ratio, which remains identical.192* Note 2 : In multi-threaded environments,193* use one different context per thread for parallel execution.194*/195typedef struct ZSTD_CCtx_s ZSTD_CCtx;196ZSTDLIB_API ZSTD_CCtx* ZSTD_createCCtx(void);197ZSTDLIB_API size_t ZSTD_freeCCtx(ZSTD_CCtx* cctx);198199/*! ZSTD_compressCCtx() :200* Same as ZSTD_compress(), using an explicit ZSTD_CCtx.201* Important : in order to behave similarly to `ZSTD_compress()`,202* this function compresses at requested compression level,203* __ignoring any other parameter__ .204* If any advanced parameter was set using the advanced API,205* they will all be reset. Only `compressionLevel` remains.206*/207ZSTDLIB_API size_t ZSTD_compressCCtx(ZSTD_CCtx* cctx,208void* dst, size_t dstCapacity,209const void* src, size_t srcSize,210int compressionLevel);211212/*= Decompression context213* When decompressing many times,214* it is recommended to allocate a context only once,215* and re-use it for each successive compression operation.216* This will make workload friendlier for system's memory.217* Use one context per thread for parallel execution. */218typedef struct ZSTD_DCtx_s ZSTD_DCtx;219ZSTDLIB_API ZSTD_DCtx* ZSTD_createDCtx(void);220ZSTDLIB_API size_t ZSTD_freeDCtx(ZSTD_DCtx* dctx);221222/*! ZSTD_decompressDCtx() :223* Same as ZSTD_decompress(),224* requires an allocated ZSTD_DCtx.225* Compatible with sticky parameters.226*/227ZSTDLIB_API size_t ZSTD_decompressDCtx(ZSTD_DCtx* dctx,228void* dst, size_t dstCapacity,229const void* src, size_t srcSize);230231232/***************************************233* Advanced compression API234***************************************/235236/* API design :237* Parameters are pushed one by one into an existing context,238* using ZSTD_CCtx_set*() functions.239* Pushed parameters are sticky : they are valid for next compressed frame, and any subsequent frame.240* "sticky" parameters are applicable to `ZSTD_compress2()` and `ZSTD_compressStream*()` !241* __They do not apply to "simple" one-shot variants such as ZSTD_compressCCtx()__ .242*243* It's possible to reset all parameters to "default" using ZSTD_CCtx_reset().244*245* This API supercedes all other "advanced" API entry points in the experimental section.246* In the future, we expect to remove from experimental API entry points which are redundant with this API.247*/248249250/* Compression strategies, listed from fastest to strongest */251typedef enum { ZSTD_fast=1,252ZSTD_dfast=2,253ZSTD_greedy=3,254ZSTD_lazy=4,255ZSTD_lazy2=5,256ZSTD_btlazy2=6,257ZSTD_btopt=7,258ZSTD_btultra=8,259ZSTD_btultra2=9260/* note : new strategies _might_ be added in the future.261Only the order (from fast to strong) is guaranteed */262} ZSTD_strategy;263264265typedef enum {266267/* compression parameters268* Note: When compressing with a ZSTD_CDict these parameters are superseded269* by the parameters used to construct the ZSTD_CDict.270* See ZSTD_CCtx_refCDict() for more info (superseded-by-cdict). */271ZSTD_c_compressionLevel=100, /* Set compression parameters according to pre-defined cLevel table.272* Note that exact compression parameters are dynamically determined,273* depending on both compression level and srcSize (when known).274* Default level is ZSTD_CLEVEL_DEFAULT==3.275* Special: value 0 means default, which is controlled by ZSTD_CLEVEL_DEFAULT.276* Note 1 : it's possible to pass a negative compression level.277* Note 2 : setting a level does not automatically set all other compression parameters278* to default. Setting this will however eventually dynamically impact the compression279* parameters which have not been manually set. The manually set280* ones will 'stick'. */281/* Advanced compression parameters :282* It's possible to pin down compression parameters to some specific values.283* In which case, these values are no longer dynamically selected by the compressor */284ZSTD_c_windowLog=101, /* Maximum allowed back-reference distance, expressed as power of 2.285* This will set a memory budget for streaming decompression,286* with larger values requiring more memory287* and typically compressing more.288* Must be clamped between ZSTD_WINDOWLOG_MIN and ZSTD_WINDOWLOG_MAX.289* Special: value 0 means "use default windowLog".290* Note: Using a windowLog greater than ZSTD_WINDOWLOG_LIMIT_DEFAULT291* requires explicitly allowing such size at streaming decompression stage. */292ZSTD_c_hashLog=102, /* Size of the initial probe table, as a power of 2.293* Resulting memory usage is (1 << (hashLog+2)).294* Must be clamped between ZSTD_HASHLOG_MIN and ZSTD_HASHLOG_MAX.295* Larger tables improve compression ratio of strategies <= dFast,296* and improve speed of strategies > dFast.297* Special: value 0 means "use default hashLog". */298ZSTD_c_chainLog=103, /* Size of the multi-probe search table, as a power of 2.299* Resulting memory usage is (1 << (chainLog+2)).300* Must be clamped between ZSTD_CHAINLOG_MIN and ZSTD_CHAINLOG_MAX.301* Larger tables result in better and slower compression.302* This parameter is useless for "fast" strategy.303* It's still useful when using "dfast" strategy,304* in which case it defines a secondary probe table.305* Special: value 0 means "use default chainLog". */306ZSTD_c_searchLog=104, /* Number of search attempts, as a power of 2.307* More attempts result in better and slower compression.308* This parameter is useless for "fast" and "dFast" strategies.309* Special: value 0 means "use default searchLog". */310ZSTD_c_minMatch=105, /* Minimum size of searched matches.311* Note that Zstandard can still find matches of smaller size,312* it just tweaks its search algorithm to look for this size and larger.313* Larger values increase compression and decompression speed, but decrease ratio.314* Must be clamped between ZSTD_MINMATCH_MIN and ZSTD_MINMATCH_MAX.315* Note that currently, for all strategies < btopt, effective minimum is 4.316* , for all strategies > fast, effective maximum is 6.317* Special: value 0 means "use default minMatchLength". */318ZSTD_c_targetLength=106, /* Impact of this field depends on strategy.319* For strategies btopt, btultra & btultra2:320* Length of Match considered "good enough" to stop search.321* Larger values make compression stronger, and slower.322* For strategy fast:323* Distance between match sampling.324* Larger values make compression faster, and weaker.325* Special: value 0 means "use default targetLength". */326ZSTD_c_strategy=107, /* See ZSTD_strategy enum definition.327* The higher the value of selected strategy, the more complex it is,328* resulting in stronger and slower compression.329* Special: value 0 means "use default strategy". */330331/* LDM mode parameters */332ZSTD_c_enableLongDistanceMatching=160, /* Enable long distance matching.333* This parameter is designed to improve compression ratio334* for large inputs, by finding large matches at long distance.335* It increases memory usage and window size.336* Note: enabling this parameter increases default ZSTD_c_windowLog to 128 MB337* except when expressly set to a different value. */338ZSTD_c_ldmHashLog=161, /* Size of the table for long distance matching, as a power of 2.339* Larger values increase memory usage and compression ratio,340* but decrease compression speed.341* Must be clamped between ZSTD_HASHLOG_MIN and ZSTD_HASHLOG_MAX342* default: windowlog - 7.343* Special: value 0 means "automatically determine hashlog". */344ZSTD_c_ldmMinMatch=162, /* Minimum match size for long distance matcher.345* Larger/too small values usually decrease compression ratio.346* Must be clamped between ZSTD_LDM_MINMATCH_MIN and ZSTD_LDM_MINMATCH_MAX.347* Special: value 0 means "use default value" (default: 64). */348ZSTD_c_ldmBucketSizeLog=163, /* Log size of each bucket in the LDM hash table for collision resolution.349* Larger values improve collision resolution but decrease compression speed.350* The maximum value is ZSTD_LDM_BUCKETSIZELOG_MAX.351* Special: value 0 means "use default value" (default: 3). */352ZSTD_c_ldmHashRateLog=164, /* Frequency of inserting/looking up entries into the LDM hash table.353* Must be clamped between 0 and (ZSTD_WINDOWLOG_MAX - ZSTD_HASHLOG_MIN).354* Default is MAX(0, (windowLog - ldmHashLog)), optimizing hash table usage.355* Larger values improve compression speed.356* Deviating far from default value will likely result in a compression ratio decrease.357* Special: value 0 means "automatically determine hashRateLog". */358359/* frame parameters */360ZSTD_c_contentSizeFlag=200, /* Content size will be written into frame header _whenever known_ (default:1)361* Content size must be known at the beginning of compression.362* This is automatically the case when using ZSTD_compress2(),363* For streaming scenarios, content size must be provided with ZSTD_CCtx_setPledgedSrcSize() */364ZSTD_c_checksumFlag=201, /* A 32-bits checksum of content is written at end of frame (default:0) */365ZSTD_c_dictIDFlag=202, /* When applicable, dictionary's ID is written into frame header (default:1) */366367/* multi-threading parameters */368/* These parameters are only useful if multi-threading is enabled (compiled with build macro ZSTD_MULTITHREAD).369* They return an error otherwise. */370ZSTD_c_nbWorkers=400, /* Select how many threads will be spawned to compress in parallel.371* When nbWorkers >= 1, triggers asynchronous mode when used with ZSTD_compressStream*() :372* ZSTD_compressStream*() consumes input and flush output if possible, but immediately gives back control to caller,373* while compression work is performed in parallel, within worker threads.374* (note : a strong exception to this rule is when first invocation of ZSTD_compressStream2() sets ZSTD_e_end :375* in which case, ZSTD_compressStream2() delegates to ZSTD_compress2(), which is always a blocking call).376* More workers improve speed, but also increase memory usage.377* Default value is `0`, aka "single-threaded mode" : no worker is spawned, compression is performed inside Caller's thread, all invocations are blocking */378ZSTD_c_jobSize=401, /* Size of a compression job. This value is enforced only when nbWorkers >= 1.379* Each compression job is completed in parallel, so this value can indirectly impact the nb of active threads.380* 0 means default, which is dynamically determined based on compression parameters.381* Job size must be a minimum of overlap size, or 1 MB, whichever is largest.382* The minimum size is automatically and transparently enforced. */383ZSTD_c_overlapLog=402, /* Control the overlap size, as a fraction of window size.384* The overlap size is an amount of data reloaded from previous job at the beginning of a new job.385* It helps preserve compression ratio, while each job is compressed in parallel.386* This value is enforced only when nbWorkers >= 1.387* Larger values increase compression ratio, but decrease speed.388* Possible values range from 0 to 9 :389* - 0 means "default" : value will be determined by the library, depending on strategy390* - 1 means "no overlap"391* - 9 means "full overlap", using a full window size.392* Each intermediate rank increases/decreases load size by a factor 2 :393* 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:default394* default value varies between 6 and 9, depending on strategy */395396/* note : additional experimental parameters are also available397* within the experimental section of the API.398* At the time of this writing, they include :399* ZSTD_c_rsyncable400* ZSTD_c_format401* ZSTD_c_forceMaxWindow402* ZSTD_c_forceAttachDict403* ZSTD_c_literalCompressionMode404* ZSTD_c_targetCBlockSize405* ZSTD_c_srcSizeHint406* Because they are not stable, it's necessary to define ZSTD_STATIC_LINKING_ONLY to access them.407* note : never ever use experimentalParam? names directly;408* also, the enums values themselves are unstable and can still change.409*/410ZSTD_c_experimentalParam1=500,411ZSTD_c_experimentalParam2=10,412ZSTD_c_experimentalParam3=1000,413ZSTD_c_experimentalParam4=1001,414ZSTD_c_experimentalParam5=1002,415ZSTD_c_experimentalParam6=1003,416ZSTD_c_experimentalParam7=1004417} ZSTD_cParameter;418419typedef struct {420size_t error;421int lowerBound;422int upperBound;423} ZSTD_bounds;424425/*! ZSTD_cParam_getBounds() :426* All parameters must belong to an interval with lower and upper bounds,427* otherwise they will either trigger an error or be automatically clamped.428* @return : a structure, ZSTD_bounds, which contains429* - an error status field, which must be tested using ZSTD_isError()430* - lower and upper bounds, both inclusive431*/432ZSTDLIB_API ZSTD_bounds ZSTD_cParam_getBounds(ZSTD_cParameter cParam);433434/*! ZSTD_CCtx_setParameter() :435* Set one compression parameter, selected by enum ZSTD_cParameter.436* All parameters have valid bounds. Bounds can be queried using ZSTD_cParam_getBounds().437* Providing a value beyond bound will either clamp it, or trigger an error (depending on parameter).438* Setting a parameter is generally only possible during frame initialization (before starting compression).439* Exception : when using multi-threading mode (nbWorkers >= 1),440* the following parameters can be updated _during_ compression (within same frame):441* => compressionLevel, hashLog, chainLog, searchLog, minMatch, targetLength and strategy.442* new parameters will be active for next job only (after a flush()).443* @return : an error code (which can be tested using ZSTD_isError()).444*/445ZSTDLIB_API size_t ZSTD_CCtx_setParameter(ZSTD_CCtx* cctx, ZSTD_cParameter param, int value);446447/*! ZSTD_CCtx_setPledgedSrcSize() :448* Total input data size to be compressed as a single frame.449* Value will be written in frame header, unless if explicitly forbidden using ZSTD_c_contentSizeFlag.450* This value will also be controlled at end of frame, and trigger an error if not respected.451* @result : 0, or an error code (which can be tested with ZSTD_isError()).452* Note 1 : pledgedSrcSize==0 actually means zero, aka an empty frame.453* In order to mean "unknown content size", pass constant ZSTD_CONTENTSIZE_UNKNOWN.454* ZSTD_CONTENTSIZE_UNKNOWN is default value for any new frame.455* Note 2 : pledgedSrcSize is only valid once, for the next frame.456* It's discarded at the end of the frame, and replaced by ZSTD_CONTENTSIZE_UNKNOWN.457* Note 3 : Whenever all input data is provided and consumed in a single round,458* for example with ZSTD_compress2(),459* or invoking immediately ZSTD_compressStream2(,,,ZSTD_e_end),460* this value is automatically overridden by srcSize instead.461*/462ZSTDLIB_API size_t ZSTD_CCtx_setPledgedSrcSize(ZSTD_CCtx* cctx, unsigned long long pledgedSrcSize);463464typedef enum {465ZSTD_reset_session_only = 1,466ZSTD_reset_parameters = 2,467ZSTD_reset_session_and_parameters = 3468} ZSTD_ResetDirective;469470/*! ZSTD_CCtx_reset() :471* There are 2 different things that can be reset, independently or jointly :472* - The session : will stop compressing current frame, and make CCtx ready to start a new one.473* Useful after an error, or to interrupt any ongoing compression.474* Any internal data not yet flushed is cancelled.475* Compression parameters and dictionary remain unchanged.476* They will be used to compress next frame.477* Resetting session never fails.478* - The parameters : changes all parameters back to "default".479* This removes any reference to any dictionary too.480* Parameters can only be changed between 2 sessions (i.e. no compression is currently ongoing)481* otherwise the reset fails, and function returns an error value (which can be tested using ZSTD_isError())482* - Both : similar to resetting the session, followed by resetting parameters.483*/484ZSTDLIB_API size_t ZSTD_CCtx_reset(ZSTD_CCtx* cctx, ZSTD_ResetDirective reset);485486/*! ZSTD_compress2() :487* Behave the same as ZSTD_compressCCtx(), but compression parameters are set using the advanced API.488* ZSTD_compress2() always starts a new frame.489* Should cctx hold data from a previously unfinished frame, everything about it is forgotten.490* - Compression parameters are pushed into CCtx before starting compression, using ZSTD_CCtx_set*()491* - The function is always blocking, returns when compression is completed.492* Hint : compression runs faster if `dstCapacity` >= `ZSTD_compressBound(srcSize)`.493* @return : compressed size written into `dst` (<= `dstCapacity),494* or an error code if it fails (which can be tested using ZSTD_isError()).495*/496ZSTDLIB_API size_t ZSTD_compress2( ZSTD_CCtx* cctx,497void* dst, size_t dstCapacity,498const void* src, size_t srcSize);499500501/***************************************502* Advanced decompression API503***************************************/504505/* The advanced API pushes parameters one by one into an existing DCtx context.506* Parameters are sticky, and remain valid for all following frames507* using the same DCtx context.508* It's possible to reset parameters to default values using ZSTD_DCtx_reset().509* Note : This API is compatible with existing ZSTD_decompressDCtx() and ZSTD_decompressStream().510* Therefore, no new decompression function is necessary.511*/512513typedef enum {514515ZSTD_d_windowLogMax=100, /* Select a size limit (in power of 2) beyond which516* the streaming API will refuse to allocate memory buffer517* in order to protect the host from unreasonable memory requirements.518* This parameter is only useful in streaming mode, since no internal buffer is allocated in single-pass mode.519* By default, a decompression context accepts window sizes <= (1 << ZSTD_WINDOWLOG_LIMIT_DEFAULT).520* Special: value 0 means "use default maximum windowLog". */521522/* note : additional experimental parameters are also available523* within the experimental section of the API.524* At the time of this writing, they include :525* ZSTD_d_format526* ZSTD_d_stableOutBuffer527* Because they are not stable, it's necessary to define ZSTD_STATIC_LINKING_ONLY to access them.528* note : never ever use experimentalParam? names directly529*/530ZSTD_d_experimentalParam1=1000,531ZSTD_d_experimentalParam2=1001532533} ZSTD_dParameter;534535/*! ZSTD_dParam_getBounds() :536* All parameters must belong to an interval with lower and upper bounds,537* otherwise they will either trigger an error or be automatically clamped.538* @return : a structure, ZSTD_bounds, which contains539* - an error status field, which must be tested using ZSTD_isError()540* - both lower and upper bounds, inclusive541*/542ZSTDLIB_API ZSTD_bounds ZSTD_dParam_getBounds(ZSTD_dParameter dParam);543544/*! ZSTD_DCtx_setParameter() :545* Set one compression parameter, selected by enum ZSTD_dParameter.546* All parameters have valid bounds. Bounds can be queried using ZSTD_dParam_getBounds().547* Providing a value beyond bound will either clamp it, or trigger an error (depending on parameter).548* Setting a parameter is only possible during frame initialization (before starting decompression).549* @return : 0, or an error code (which can be tested using ZSTD_isError()).550*/551ZSTDLIB_API size_t ZSTD_DCtx_setParameter(ZSTD_DCtx* dctx, ZSTD_dParameter param, int value);552553/*! ZSTD_DCtx_reset() :554* Return a DCtx to clean state.555* Session and parameters can be reset jointly or separately.556* Parameters can only be reset when no active frame is being decompressed.557* @return : 0, or an error code, which can be tested with ZSTD_isError()558*/559ZSTDLIB_API size_t ZSTD_DCtx_reset(ZSTD_DCtx* dctx, ZSTD_ResetDirective reset);560561562/****************************563* Streaming564****************************/565566typedef struct ZSTD_inBuffer_s {567const void* src; /**< start of input buffer */568size_t size; /**< size of input buffer */569size_t pos; /**< position where reading stopped. Will be updated. Necessarily 0 <= pos <= size */570} ZSTD_inBuffer;571572typedef struct ZSTD_outBuffer_s {573void* dst; /**< start of output buffer */574size_t size; /**< size of output buffer */575size_t pos; /**< position where writing stopped. Will be updated. Necessarily 0 <= pos <= size */576} ZSTD_outBuffer;577578579580/*-***********************************************************************581* Streaming compression - HowTo582*583* A ZSTD_CStream object is required to track streaming operation.584* Use ZSTD_createCStream() and ZSTD_freeCStream() to create/release resources.585* ZSTD_CStream objects can be reused multiple times on consecutive compression operations.586* It is recommended to re-use ZSTD_CStream since it will play nicer with system's memory, by re-using already allocated memory.587*588* For parallel execution, use one separate ZSTD_CStream per thread.589*590* note : since v1.3.0, ZSTD_CStream and ZSTD_CCtx are the same thing.591*592* Parameters are sticky : when starting a new compression on the same context,593* it will re-use the same sticky parameters as previous compression session.594* When in doubt, it's recommended to fully initialize the context before usage.595* Use ZSTD_CCtx_reset() to reset the context and ZSTD_CCtx_setParameter(),596* ZSTD_CCtx_setPledgedSrcSize(), or ZSTD_CCtx_loadDictionary() and friends to597* set more specific parameters, the pledged source size, or load a dictionary.598*599* Use ZSTD_compressStream2() with ZSTD_e_continue as many times as necessary to600* consume input stream. The function will automatically update both `pos`601* fields within `input` and `output`.602* Note that the function may not consume the entire input, for example, because603* the output buffer is already full, in which case `input.pos < input.size`.604* The caller must check if input has been entirely consumed.605* If not, the caller must make some room to receive more compressed data,606* and then present again remaining input data.607* note: ZSTD_e_continue is guaranteed to make some forward progress when called,608* but doesn't guarantee maximal forward progress. This is especially relevant609* when compressing with multiple threads. The call won't block if it can610* consume some input, but if it can't it will wait for some, but not all,611* output to be flushed.612* @return : provides a minimum amount of data remaining to be flushed from internal buffers613* or an error code, which can be tested using ZSTD_isError().614*615* At any moment, it's possible to flush whatever data might remain stuck within internal buffer,616* using ZSTD_compressStream2() with ZSTD_e_flush. `output->pos` will be updated.617* Note that, if `output->size` is too small, a single invocation with ZSTD_e_flush might not be enough (return code > 0).618* In which case, make some room to receive more compressed data, and call again ZSTD_compressStream2() with ZSTD_e_flush.619* You must continue calling ZSTD_compressStream2() with ZSTD_e_flush until it returns 0, at which point you can change the620* operation.621* note: ZSTD_e_flush will flush as much output as possible, meaning when compressing with multiple threads, it will622* block until the flush is complete or the output buffer is full.623* @return : 0 if internal buffers are entirely flushed,624* >0 if some data still present within internal buffer (the value is minimal estimation of remaining size),625* or an error code, which can be tested using ZSTD_isError().626*627* Calling ZSTD_compressStream2() with ZSTD_e_end instructs to finish a frame.628* It will perform a flush and write frame epilogue.629* The epilogue is required for decoders to consider a frame completed.630* flush operation is the same, and follows same rules as calling ZSTD_compressStream2() with ZSTD_e_flush.631* You must continue calling ZSTD_compressStream2() with ZSTD_e_end until it returns 0, at which point you are free to632* start a new frame.633* note: ZSTD_e_end will flush as much output as possible, meaning when compressing with multiple threads, it will634* block until the flush is complete or the output buffer is full.635* @return : 0 if frame fully completed and fully flushed,636* >0 if some data still present within internal buffer (the value is minimal estimation of remaining size),637* or an error code, which can be tested using ZSTD_isError().638*639* *******************************************************************/640641typedef ZSTD_CCtx ZSTD_CStream; /**< CCtx and CStream are now effectively same object (>= v1.3.0) */642/* Continue to distinguish them for compatibility with older versions <= v1.2.0 */643/*===== ZSTD_CStream management functions =====*/644ZSTDLIB_API ZSTD_CStream* ZSTD_createCStream(void);645ZSTDLIB_API size_t ZSTD_freeCStream(ZSTD_CStream* zcs);646647/*===== Streaming compression functions =====*/648typedef enum {649ZSTD_e_continue=0, /* collect more data, encoder decides when to output compressed result, for optimal compression ratio */650ZSTD_e_flush=1, /* flush any data provided so far,651* it creates (at least) one new block, that can be decoded immediately on reception;652* frame will continue: any future data can still reference previously compressed data, improving compression.653* note : multithreaded compression will block to flush as much output as possible. */654ZSTD_e_end=2 /* flush any remaining data _and_ close current frame.655* note that frame is only closed after compressed data is fully flushed (return value == 0).656* After that point, any additional data starts a new frame.657* note : each frame is independent (does not reference any content from previous frame).658: note : multithreaded compression will block to flush as much output as possible. */659} ZSTD_EndDirective;660661/*! ZSTD_compressStream2() :662* Behaves about the same as ZSTD_compressStream, with additional control on end directive.663* - Compression parameters are pushed into CCtx before starting compression, using ZSTD_CCtx_set*()664* - Compression parameters cannot be changed once compression is started (save a list of exceptions in multi-threading mode)665* - output->pos must be <= dstCapacity, input->pos must be <= srcSize666* - output->pos and input->pos will be updated. They are guaranteed to remain below their respective limit.667* - When nbWorkers==0 (default), function is blocking : it completes its job before returning to caller.668* - When nbWorkers>=1, function is non-blocking : it just acquires a copy of input, and distributes jobs to internal worker threads, flush whatever is available,669* and then immediately returns, just indicating that there is some data remaining to be flushed.670* The function nonetheless guarantees forward progress : it will return only after it reads or write at least 1+ byte.671* - 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.672* - @return provides a minimum amount of data remaining to be flushed from internal buffers673* or an error code, which can be tested using ZSTD_isError().674* if @return != 0, flush is not fully completed, there is still some data left within internal buffers.675* This is useful for ZSTD_e_flush, since in this case more flushes are necessary to empty all buffers.676* For ZSTD_e_end, @return == 0 when internal buffers are fully flushed and frame is completed.677* - after a ZSTD_e_end directive, if internal buffer is not fully flushed (@return != 0),678* only ZSTD_e_end or ZSTD_e_flush operations are allowed.679* Before starting a new compression job, or changing compression parameters,680* it is required to fully flush internal buffers.681*/682ZSTDLIB_API size_t ZSTD_compressStream2( ZSTD_CCtx* cctx,683ZSTD_outBuffer* output,684ZSTD_inBuffer* input,685ZSTD_EndDirective endOp);686687688/* These buffer sizes are softly recommended.689* They are not required : ZSTD_compressStream*() happily accepts any buffer size, for both input and output.690* Respecting the recommended size just makes it a bit easier for ZSTD_compressStream*(),691* reducing the amount of memory shuffling and buffering, resulting in minor performance savings.692*693* However, note that these recommendations are from the perspective of a C caller program.694* If the streaming interface is invoked from some other language,695* especially managed ones such as Java or Go, through a foreign function interface such as jni or cgo,696* a major performance rule is to reduce crossing such interface to an absolute minimum.697* It's not rare that performance ends being spent more into the interface, rather than compression itself.698* In which cases, prefer using large buffers, as large as practical,699* for both input and output, to reduce the nb of roundtrips.700*/701ZSTDLIB_API size_t ZSTD_CStreamInSize(void); /**< recommended size for input buffer */702ZSTDLIB_API size_t ZSTD_CStreamOutSize(void); /**< recommended size for output buffer. Guarantee to successfully flush at least one complete compressed block. */703704705/* *****************************************************************************706* This following is a legacy streaming API.707* It can be replaced by ZSTD_CCtx_reset() and ZSTD_compressStream2().708* It is redundant, but remains fully supported.709* Advanced parameters and dictionary compression can only be used through the710* new API.711******************************************************************************/712713/*!714* Equivalent to:715*716* ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only);717* ZSTD_CCtx_refCDict(zcs, NULL); // clear the dictionary (if any)718* ZSTD_CCtx_setParameter(zcs, ZSTD_c_compressionLevel, compressionLevel);719*/720ZSTDLIB_API size_t ZSTD_initCStream(ZSTD_CStream* zcs, int compressionLevel);721/*!722* Alternative for ZSTD_compressStream2(zcs, output, input, ZSTD_e_continue).723* NOTE: The return value is different. ZSTD_compressStream() returns a hint for724* the next read size (if non-zero and not an error). ZSTD_compressStream2()725* returns the minimum nb of bytes left to flush (if non-zero and not an error).726*/727ZSTDLIB_API size_t ZSTD_compressStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output, ZSTD_inBuffer* input);728/*! Equivalent to ZSTD_compressStream2(zcs, output, &emptyInput, ZSTD_e_flush). */729ZSTDLIB_API size_t ZSTD_flushStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output);730/*! Equivalent to ZSTD_compressStream2(zcs, output, &emptyInput, ZSTD_e_end). */731ZSTDLIB_API size_t ZSTD_endStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output);732733734/*-***************************************************************************735* Streaming decompression - HowTo736*737* A ZSTD_DStream object is required to track streaming operations.738* Use ZSTD_createDStream() and ZSTD_freeDStream() to create/release resources.739* ZSTD_DStream objects can be re-used multiple times.740*741* Use ZSTD_initDStream() to start a new decompression operation.742* @return : recommended first input size743* Alternatively, use advanced API to set specific properties.744*745* Use ZSTD_decompressStream() repetitively to consume your input.746* The function will update both `pos` fields.747* If `input.pos < input.size`, some input has not been consumed.748* It's up to the caller to present again remaining data.749* The function tries to flush all data decoded immediately, respecting output buffer size.750* If `output.pos < output.size`, decoder has flushed everything it could.751* But if `output.pos == output.size`, there might be some data left within internal buffers.,752* In which case, call ZSTD_decompressStream() again to flush whatever remains in the buffer.753* Note : with no additional input provided, amount of data flushed is necessarily <= ZSTD_BLOCKSIZE_MAX.754* @return : 0 when a frame is completely decoded and fully flushed,755* or an error code, which can be tested using ZSTD_isError(),756* or any other value > 0, which means there is still some decoding or flushing to do to complete current frame :757* the return value is a suggested next input size (just a hint for better latency)758* that will never request more than the remaining frame size.759* *******************************************************************************/760761typedef ZSTD_DCtx ZSTD_DStream; /**< DCtx and DStream are now effectively same object (>= v1.3.0) */762/* For compatibility with versions <= v1.2.0, prefer differentiating them. */763/*===== ZSTD_DStream management functions =====*/764ZSTDLIB_API ZSTD_DStream* ZSTD_createDStream(void);765ZSTDLIB_API size_t ZSTD_freeDStream(ZSTD_DStream* zds);766767/*===== Streaming decompression functions =====*/768769/* This function is redundant with the advanced API and equivalent to:770*771* ZSTD_DCtx_reset(zds, ZSTD_reset_session_only);772* ZSTD_DCtx_refDDict(zds, NULL);773*/774ZSTDLIB_API size_t ZSTD_initDStream(ZSTD_DStream* zds);775776ZSTDLIB_API size_t ZSTD_decompressStream(ZSTD_DStream* zds, ZSTD_outBuffer* output, ZSTD_inBuffer* input);777778ZSTDLIB_API size_t ZSTD_DStreamInSize(void); /*!< recommended size for input buffer */779ZSTDLIB_API size_t ZSTD_DStreamOutSize(void); /*!< recommended size for output buffer. Guarantee to successfully flush at least one complete block in all circumstances. */780781782/**************************783* Simple dictionary API784***************************/785/*! ZSTD_compress_usingDict() :786* Compression at an explicit compression level using a Dictionary.787* A dictionary can be any arbitrary data segment (also called a prefix),788* or a buffer with specified information (see dictBuilder/zdict.h).789* Note : This function loads the dictionary, resulting in significant startup delay.790* It's intended for a dictionary used only once.791* Note 2 : When `dict == NULL || dictSize < 8` no dictionary is used. */792ZSTDLIB_API size_t ZSTD_compress_usingDict(ZSTD_CCtx* ctx,793void* dst, size_t dstCapacity,794const void* src, size_t srcSize,795const void* dict,size_t dictSize,796int compressionLevel);797798/*! ZSTD_decompress_usingDict() :799* Decompression using a known Dictionary.800* Dictionary must be identical to the one used during compression.801* Note : This function loads the dictionary, resulting in significant startup delay.802* It's intended for a dictionary used only once.803* Note : When `dict == NULL || dictSize < 8` no dictionary is used. */804ZSTDLIB_API size_t ZSTD_decompress_usingDict(ZSTD_DCtx* dctx,805void* dst, size_t dstCapacity,806const void* src, size_t srcSize,807const void* dict,size_t dictSize);808809810/***********************************811* Bulk processing dictionary API812**********************************/813typedef struct ZSTD_CDict_s ZSTD_CDict;814815/*! ZSTD_createCDict() :816* When compressing multiple messages or blocks using the same dictionary,817* it's recommended to digest the dictionary only once, since it's a costly operation.818* ZSTD_createCDict() will create a state from digesting a dictionary.819* The resulting state can be used for future compression operations with very limited startup cost.820* ZSTD_CDict can be created once and shared by multiple threads concurrently, since its usage is read-only.821* @dictBuffer can be released after ZSTD_CDict creation, because its content is copied within CDict.822* Note 1 : Consider experimental function `ZSTD_createCDict_byReference()` if you prefer to not duplicate @dictBuffer content.823* Note 2 : A ZSTD_CDict can be created from an empty @dictBuffer,824* in which case the only thing that it transports is the @compressionLevel.825* This can be useful in a pipeline featuring ZSTD_compress_usingCDict() exclusively,826* expecting a ZSTD_CDict parameter with any data, including those without a known dictionary. */827ZSTDLIB_API ZSTD_CDict* ZSTD_createCDict(const void* dictBuffer, size_t dictSize,828int compressionLevel);829830/*! ZSTD_freeCDict() :831* Function frees memory allocated by ZSTD_createCDict(). */832ZSTDLIB_API size_t ZSTD_freeCDict(ZSTD_CDict* CDict);833834/*! ZSTD_compress_usingCDict() :835* Compression using a digested Dictionary.836* Recommended when same dictionary is used multiple times.837* Note : compression level is _decided at dictionary creation time_,838* and frame parameters are hardcoded (dictID=yes, contentSize=yes, checksum=no) */839ZSTDLIB_API size_t ZSTD_compress_usingCDict(ZSTD_CCtx* cctx,840void* dst, size_t dstCapacity,841const void* src, size_t srcSize,842const ZSTD_CDict* cdict);843844845typedef struct ZSTD_DDict_s ZSTD_DDict;846847/*! ZSTD_createDDict() :848* Create a digested dictionary, ready to start decompression operation without startup delay.849* dictBuffer can be released after DDict creation, as its content is copied inside DDict. */850ZSTDLIB_API ZSTD_DDict* ZSTD_createDDict(const void* dictBuffer, size_t dictSize);851852/*! ZSTD_freeDDict() :853* Function frees memory allocated with ZSTD_createDDict() */854ZSTDLIB_API size_t ZSTD_freeDDict(ZSTD_DDict* ddict);855856/*! ZSTD_decompress_usingDDict() :857* Decompression using a digested Dictionary.858* Recommended when same dictionary is used multiple times. */859ZSTDLIB_API size_t ZSTD_decompress_usingDDict(ZSTD_DCtx* dctx,860void* dst, size_t dstCapacity,861const void* src, size_t srcSize,862const ZSTD_DDict* ddict);863864865/********************************866* Dictionary helper functions867*******************************/868869/*! ZSTD_getDictID_fromDict() :870* Provides the dictID stored within dictionary.871* if @return == 0, the dictionary is not conformant with Zstandard specification.872* It can still be loaded, but as a content-only dictionary. */873ZSTDLIB_API unsigned ZSTD_getDictID_fromDict(const void* dict, size_t dictSize);874875/*! ZSTD_getDictID_fromDDict() :876* Provides the dictID of the dictionary loaded into `ddict`.877* If @return == 0, the dictionary is not conformant to Zstandard specification, or empty.878* Non-conformant dictionaries can still be loaded, but as content-only dictionaries. */879ZSTDLIB_API unsigned ZSTD_getDictID_fromDDict(const ZSTD_DDict* ddict);880881/*! ZSTD_getDictID_fromFrame() :882* Provides the dictID required to decompressed the frame stored within `src`.883* If @return == 0, the dictID could not be decoded.884* This could for one of the following reasons :885* - The frame does not require a dictionary to be decoded (most common case).886* - The frame was built with dictID intentionally removed. Whatever dictionary is necessary is a hidden information.887* Note : this use case also happens when using a non-conformant dictionary.888* - `srcSize` is too small, and as a result, the frame header could not be decoded (only possible if `srcSize < ZSTD_FRAMEHEADERSIZE_MAX`).889* - This is not a Zstandard frame.890* When identifying the exact failure cause, it's possible to use ZSTD_getFrameHeader(), which will provide a more precise error code. */891ZSTDLIB_API unsigned ZSTD_getDictID_fromFrame(const void* src, size_t srcSize);892893894/*******************************************************************************895* Advanced dictionary and prefix API896*897* This API allows dictionaries to be used with ZSTD_compress2(),898* ZSTD_compressStream2(), and ZSTD_decompress(). Dictionaries are sticky, and899* only reset with the context is reset with ZSTD_reset_parameters or900* ZSTD_reset_session_and_parameters. Prefixes are single-use.901******************************************************************************/902903904/*! ZSTD_CCtx_loadDictionary() :905* Create an internal CDict from `dict` buffer.906* Decompression will have to use same dictionary.907* @result : 0, or an error code (which can be tested with ZSTD_isError()).908* Special: Loading a NULL (or 0-size) dictionary invalidates previous dictionary,909* meaning "return to no-dictionary mode".910* Note 1 : Dictionary is sticky, it will be used for all future compressed frames.911* To return to "no-dictionary" situation, load a NULL dictionary (or reset parameters).912* Note 2 : Loading a dictionary involves building tables.913* It's also a CPU consuming operation, with non-negligible impact on latency.914* Tables are dependent on compression parameters, and for this reason,915* compression parameters can no longer be changed after loading a dictionary.916* Note 3 :`dict` content will be copied internally.917* Use experimental ZSTD_CCtx_loadDictionary_byReference() to reference content instead.918* In such a case, dictionary buffer must outlive its users.919* Note 4 : Use ZSTD_CCtx_loadDictionary_advanced()920* to precisely select how dictionary content must be interpreted. */921ZSTDLIB_API size_t ZSTD_CCtx_loadDictionary(ZSTD_CCtx* cctx, const void* dict, size_t dictSize);922923/*! ZSTD_CCtx_refCDict() :924* Reference a prepared dictionary, to be used for all next compressed frames.925* Note that compression parameters are enforced from within CDict,926* and supersede any compression parameter previously set within CCtx.927* The parameters ignored are labled as "superseded-by-cdict" in the ZSTD_cParameter enum docs.928* The ignored parameters will be used again if the CCtx is returned to no-dictionary mode.929* The dictionary will remain valid for future compressed frames using same CCtx.930* @result : 0, or an error code (which can be tested with ZSTD_isError()).931* Special : Referencing a NULL CDict means "return to no-dictionary mode".932* Note 1 : Currently, only one dictionary can be managed.933* Referencing a new dictionary effectively "discards" any previous one.934* Note 2 : CDict is just referenced, its lifetime must outlive its usage within CCtx. */935ZSTDLIB_API size_t ZSTD_CCtx_refCDict(ZSTD_CCtx* cctx, const ZSTD_CDict* cdict);936937/*! ZSTD_CCtx_refPrefix() :938* Reference a prefix (single-usage dictionary) for next compressed frame.939* A prefix is **only used once**. Tables are discarded at end of frame (ZSTD_e_end).940* Decompression will need same prefix to properly regenerate data.941* Compressing with a prefix is similar in outcome as performing a diff and compressing it,942* but performs much faster, especially during decompression (compression speed is tunable with compression level).943* @result : 0, or an error code (which can be tested with ZSTD_isError()).944* Special: Adding any prefix (including NULL) invalidates any previous prefix or dictionary945* Note 1 : Prefix buffer is referenced. It **must** outlive compression.946* Its content must remain unmodified during compression.947* Note 2 : If the intention is to diff some large src data blob with some prior version of itself,948* ensure that the window size is large enough to contain the entire source.949* See ZSTD_c_windowLog.950* Note 3 : Referencing a prefix involves building tables, which are dependent on compression parameters.951* It's a CPU consuming operation, with non-negligible impact on latency.952* If there is a need to use the same prefix multiple times, consider loadDictionary instead.953* Note 4 : By default, the prefix is interpreted as raw content (ZSTD_dct_rawContent).954* Use experimental ZSTD_CCtx_refPrefix_advanced() to alter dictionary interpretation. */955ZSTDLIB_API size_t ZSTD_CCtx_refPrefix(ZSTD_CCtx* cctx,956const void* prefix, size_t prefixSize);957958/*! ZSTD_DCtx_loadDictionary() :959* Create an internal DDict from dict buffer,960* to be used to decompress next frames.961* The dictionary remains valid for all future frames, until explicitly invalidated.962* @result : 0, or an error code (which can be tested with ZSTD_isError()).963* Special : Adding a NULL (or 0-size) dictionary invalidates any previous dictionary,964* meaning "return to no-dictionary mode".965* Note 1 : Loading a dictionary involves building tables,966* which has a non-negligible impact on CPU usage and latency.967* It's recommended to "load once, use many times", to amortize the cost968* Note 2 :`dict` content will be copied internally, so `dict` can be released after loading.969* Use ZSTD_DCtx_loadDictionary_byReference() to reference dictionary content instead.970* Note 3 : Use ZSTD_DCtx_loadDictionary_advanced() to take control of971* how dictionary content is loaded and interpreted.972*/973ZSTDLIB_API size_t ZSTD_DCtx_loadDictionary(ZSTD_DCtx* dctx, const void* dict, size_t dictSize);974975/*! ZSTD_DCtx_refDDict() :976* Reference a prepared dictionary, to be used to decompress next frames.977* The dictionary remains active for decompression of future frames using same DCtx.978* @result : 0, or an error code (which can be tested with ZSTD_isError()).979* Note 1 : Currently, only one dictionary can be managed.980* Referencing a new dictionary effectively "discards" any previous one.981* Special: referencing a NULL DDict means "return to no-dictionary mode".982* Note 2 : DDict is just referenced, its lifetime must outlive its usage from DCtx.983*/984ZSTDLIB_API size_t ZSTD_DCtx_refDDict(ZSTD_DCtx* dctx, const ZSTD_DDict* ddict);985986/*! ZSTD_DCtx_refPrefix() :987* Reference a prefix (single-usage dictionary) to decompress next frame.988* This is the reverse operation of ZSTD_CCtx_refPrefix(),989* and must use the same prefix as the one used during compression.990* Prefix is **only used once**. Reference is discarded at end of frame.991* End of frame is reached when ZSTD_decompressStream() returns 0.992* @result : 0, or an error code (which can be tested with ZSTD_isError()).993* Note 1 : Adding any prefix (including NULL) invalidates any previously set prefix or dictionary994* Note 2 : Prefix buffer is referenced. It **must** outlive decompression.995* Prefix buffer must remain unmodified up to the end of frame,996* reached when ZSTD_decompressStream() returns 0.997* Note 3 : By default, the prefix is treated as raw content (ZSTD_dct_rawContent).998* Use ZSTD_CCtx_refPrefix_advanced() to alter dictMode (Experimental section)999* Note 4 : Referencing a raw content prefix has almost no cpu nor memory cost.1000* A full dictionary is more costly, as it requires building tables.1001*/1002ZSTDLIB_API size_t ZSTD_DCtx_refPrefix(ZSTD_DCtx* dctx,1003const void* prefix, size_t prefixSize);10041005/* === Memory management === */10061007/*! ZSTD_sizeof_*() :1008* These functions give the _current_ memory usage of selected object.1009* Note that object memory usage can evolve (increase or decrease) over time. */1010ZSTDLIB_API size_t ZSTD_sizeof_CCtx(const ZSTD_CCtx* cctx);1011ZSTDLIB_API size_t ZSTD_sizeof_DCtx(const ZSTD_DCtx* dctx);1012ZSTDLIB_API size_t ZSTD_sizeof_CStream(const ZSTD_CStream* zcs);1013ZSTDLIB_API size_t ZSTD_sizeof_DStream(const ZSTD_DStream* zds);1014ZSTDLIB_API size_t ZSTD_sizeof_CDict(const ZSTD_CDict* cdict);1015ZSTDLIB_API size_t ZSTD_sizeof_DDict(const ZSTD_DDict* ddict);10161017#endif /* ZSTD_H_235446 */101810191020/* **************************************************************************************1021* ADVANCED AND EXPERIMENTAL FUNCTIONS1022****************************************************************************************1023* The definitions in the following section are considered experimental.1024* They are provided for advanced scenarios.1025* They should never be used with a dynamic library, as prototypes may change in the future.1026* Use them only in association with static linking.1027* ***************************************************************************************/10281029#if defined(ZSTD_STATIC_LINKING_ONLY) && !defined(ZSTD_H_ZSTD_STATIC_LINKING_ONLY)1030#define ZSTD_H_ZSTD_STATIC_LINKING_ONLY10311032/****************************************************************************************1033* experimental API (static linking only)1034****************************************************************************************1035* The following symbols and constants1036* are not planned to join "stable API" status in the near future.1037* They can still change in future versions.1038* Some of them are planned to remain in the static_only section indefinitely.1039* Some of them might be removed in the future (especially when redundant with existing stable functions)1040* ***************************************************************************************/10411042#define ZSTD_FRAMEHEADERSIZE_PREFIX(format) ((format) == ZSTD_f_zstd1 ? 5 : 1) /* minimum input size required to query frame header size */1043#define ZSTD_FRAMEHEADERSIZE_MIN(format) ((format) == ZSTD_f_zstd1 ? 6 : 2)1044#define ZSTD_FRAMEHEADERSIZE_MAX 18 /* can be useful for static allocation */1045#define ZSTD_SKIPPABLEHEADERSIZE 810461047/* compression parameter bounds */1048#define ZSTD_WINDOWLOG_MAX_32 301049#define ZSTD_WINDOWLOG_MAX_64 311050#define ZSTD_WINDOWLOG_MAX ((int)(sizeof(size_t) == 4 ? ZSTD_WINDOWLOG_MAX_32 : ZSTD_WINDOWLOG_MAX_64))1051#define ZSTD_WINDOWLOG_MIN 101052#define ZSTD_HASHLOG_MAX ((ZSTD_WINDOWLOG_MAX < 30) ? ZSTD_WINDOWLOG_MAX : 30)1053#define ZSTD_HASHLOG_MIN 61054#define ZSTD_CHAINLOG_MAX_32 291055#define ZSTD_CHAINLOG_MAX_64 301056#define ZSTD_CHAINLOG_MAX ((int)(sizeof(size_t) == 4 ? ZSTD_CHAINLOG_MAX_32 : ZSTD_CHAINLOG_MAX_64))1057#define ZSTD_CHAINLOG_MIN ZSTD_HASHLOG_MIN1058#define ZSTD_SEARCHLOG_MAX (ZSTD_WINDOWLOG_MAX-1)1059#define ZSTD_SEARCHLOG_MIN 11060#define ZSTD_MINMATCH_MAX 7 /* only for ZSTD_fast, other strategies are limited to 6 */1061#define ZSTD_MINMATCH_MIN 3 /* only for ZSTD_btopt+, faster strategies are limited to 4 */1062#define ZSTD_TARGETLENGTH_MAX ZSTD_BLOCKSIZE_MAX1063#define ZSTD_TARGETLENGTH_MIN 0 /* note : comparing this constant to an unsigned results in a tautological test */1064#define ZSTD_STRATEGY_MIN ZSTD_fast1065#define ZSTD_STRATEGY_MAX ZSTD_btultra2106610671068#define ZSTD_OVERLAPLOG_MIN 01069#define ZSTD_OVERLAPLOG_MAX 910701071#define ZSTD_WINDOWLOG_LIMIT_DEFAULT 27 /* by default, the streaming decoder will refuse any frame1072* requiring larger than (1<<ZSTD_WINDOWLOG_LIMIT_DEFAULT) window size,1073* to preserve host's memory from unreasonable requirements.1074* This limit can be overridden using ZSTD_DCtx_setParameter(,ZSTD_d_windowLogMax,).1075* The limit does not apply for one-pass decoders (such as ZSTD_decompress()), since no additional memory is allocated */107610771078/* LDM parameter bounds */1079#define ZSTD_LDM_HASHLOG_MIN ZSTD_HASHLOG_MIN1080#define ZSTD_LDM_HASHLOG_MAX ZSTD_HASHLOG_MAX1081#define ZSTD_LDM_MINMATCH_MIN 41082#define ZSTD_LDM_MINMATCH_MAX 40961083#define ZSTD_LDM_BUCKETSIZELOG_MIN 11084#define ZSTD_LDM_BUCKETSIZELOG_MAX 81085#define ZSTD_LDM_HASHRATELOG_MIN 01086#define ZSTD_LDM_HASHRATELOG_MAX (ZSTD_WINDOWLOG_MAX - ZSTD_HASHLOG_MIN)10871088/* Advanced parameter bounds */1089#define ZSTD_TARGETCBLOCKSIZE_MIN 641090#define ZSTD_TARGETCBLOCKSIZE_MAX ZSTD_BLOCKSIZE_MAX1091#define ZSTD_SRCSIZEHINT_MIN 01092#define ZSTD_SRCSIZEHINT_MAX INT_MAX10931094/* internal */1095#define ZSTD_HASHLOG3_MAX 17109610971098/* --- Advanced types --- */10991100typedef struct ZSTD_CCtx_params_s ZSTD_CCtx_params;11011102typedef struct {1103unsigned int matchPos; /* Match pos in dst */1104/* If seqDef.offset > 3, then this is seqDef.offset - 31105* If seqDef.offset < 3, then this is the corresponding repeat offset1106* But if seqDef.offset < 3 and litLength == 0, this is the1107* repeat offset before the corresponding repeat offset1108* And if seqDef.offset == 3 and litLength == 0, this is the1109* most recent repeat offset - 11110*/1111unsigned int offset;1112unsigned int litLength; /* Literal length */1113unsigned int matchLength; /* Match length */1114/* 0 when seq not rep and seqDef.offset otherwise1115* when litLength == 0 this will be <= 4, otherwise <= 3 like normal1116*/1117unsigned int rep;1118} ZSTD_Sequence;11191120typedef struct {1121unsigned windowLog; /**< largest match distance : larger == more compression, more memory needed during decompression */1122unsigned chainLog; /**< fully searched segment : larger == more compression, slower, more memory (useless for fast) */1123unsigned hashLog; /**< dispatch table : larger == faster, more memory */1124unsigned searchLog; /**< nb of searches : larger == more compression, slower */1125unsigned minMatch; /**< match length searched : larger == faster decompression, sometimes less compression */1126unsigned targetLength; /**< acceptable match size for optimal parser (only) : larger == more compression, slower */1127ZSTD_strategy strategy; /**< see ZSTD_strategy definition above */1128} ZSTD_compressionParameters;11291130typedef struct {1131int contentSizeFlag; /**< 1: content size will be in frame header (when known) */1132int checksumFlag; /**< 1: generate a 32-bits checksum using XXH64 algorithm at end of frame, for error detection */1133int noDictIDFlag; /**< 1: no dictID will be saved into frame header (dictID is only useful for dictionary compression) */1134} ZSTD_frameParameters;11351136typedef struct {1137ZSTD_compressionParameters cParams;1138ZSTD_frameParameters fParams;1139} ZSTD_parameters;11401141typedef enum {1142ZSTD_dct_auto = 0, /* dictionary is "full" when starting with ZSTD_MAGIC_DICTIONARY, otherwise it is "rawContent" */1143ZSTD_dct_rawContent = 1, /* ensures dictionary is always loaded as rawContent, even if it starts with ZSTD_MAGIC_DICTIONARY */1144ZSTD_dct_fullDict = 2 /* refuses to load a dictionary if it does not respect Zstandard's specification, starting with ZSTD_MAGIC_DICTIONARY */1145} ZSTD_dictContentType_e;11461147typedef enum {1148ZSTD_dlm_byCopy = 0, /**< Copy dictionary content internally */1149ZSTD_dlm_byRef = 1 /**< Reference dictionary content -- the dictionary buffer must outlive its users. */1150} ZSTD_dictLoadMethod_e;11511152typedef enum {1153ZSTD_f_zstd1 = 0, /* zstd frame format, specified in zstd_compression_format.md (default) */1154ZSTD_f_zstd1_magicless = 1 /* Variant of zstd frame format, without initial 4-bytes magic number.1155* Useful to save 4 bytes per generated frame.1156* Decoder cannot recognise automatically this format, requiring this instruction. */1157} ZSTD_format_e;11581159typedef enum {1160/* Note: this enum and the behavior it controls are effectively internal1161* implementation details of the compressor. They are expected to continue1162* to evolve and should be considered only in the context of extremely1163* advanced performance tuning.1164*1165* Zstd currently supports the use of a CDict in three ways:1166*1167* - The contents of the CDict can be copied into the working context. This1168* means that the compression can search both the dictionary and input1169* while operating on a single set of internal tables. This makes1170* the compression faster per-byte of input. However, the initial copy of1171* the CDict's tables incurs a fixed cost at the beginning of the1172* compression. For small compressions (< 8 KB), that copy can dominate1173* the cost of the compression.1174*1175* - The CDict's tables can be used in-place. In this model, compression is1176* slower per input byte, because the compressor has to search two sets of1177* tables. However, this model incurs no start-up cost (as long as the1178* working context's tables can be reused). For small inputs, this can be1179* faster than copying the CDict's tables.1180*1181* - The CDict's tables are not used at all, and instead we use the working1182* context alone to reload the dictionary and use params based on the source1183* size. See ZSTD_compress_insertDictionary() and ZSTD_compress_usingDict().1184* This method is effective when the dictionary sizes are very small relative1185* to the input size, and the input size is fairly large to begin with.1186*1187* Zstd has a simple internal heuristic that selects which strategy to use1188* at the beginning of a compression. However, if experimentation shows that1189* Zstd is making poor choices, it is possible to override that choice with1190* this enum.1191*/1192ZSTD_dictDefaultAttach = 0, /* Use the default heuristic. */1193ZSTD_dictForceAttach = 1, /* Never copy the dictionary. */1194ZSTD_dictForceCopy = 2, /* Always copy the dictionary. */1195ZSTD_dictForceLoad = 3 /* Always reload the dictionary */1196} ZSTD_dictAttachPref_e;11971198typedef enum {1199ZSTD_lcm_auto = 0, /**< Automatically determine the compression mode based on the compression level.1200* Negative compression levels will be uncompressed, and positive compression1201* levels will be compressed. */1202ZSTD_lcm_huffman = 1, /**< Always attempt Huffman compression. Uncompressed literals will still be1203* emitted if Huffman compression is not profitable. */1204ZSTD_lcm_uncompressed = 2 /**< Always emit uncompressed literals. */1205} ZSTD_literalCompressionMode_e;120612071208/***************************************1209* Frame size functions1210***************************************/12111212/*! ZSTD_findDecompressedSize() :1213* `src` should point to the start of a series of ZSTD encoded and/or skippable frames1214* `srcSize` must be the _exact_ size of this series1215* (i.e. there should be a frame boundary at `src + srcSize`)1216* @return : - decompressed size of all data in all successive frames1217* - if the decompressed size cannot be determined: ZSTD_CONTENTSIZE_UNKNOWN1218* - if an error occurred: ZSTD_CONTENTSIZE_ERROR1219*1220* note 1 : decompressed size is an optional field, that may not be present, especially in streaming mode.1221* When `return==ZSTD_CONTENTSIZE_UNKNOWN`, data to decompress could be any size.1222* In which case, it's necessary to use streaming mode to decompress data.1223* note 2 : decompressed size is always present when compression is done with ZSTD_compress()1224* note 3 : decompressed size can be very large (64-bits value),1225* potentially larger than what local system can handle as a single memory segment.1226* In which case, it's necessary to use streaming mode to decompress data.1227* note 4 : If source is untrusted, decompressed size could be wrong or intentionally modified.1228* Always ensure result fits within application's authorized limits.1229* Each application can set its own limits.1230* note 5 : ZSTD_findDecompressedSize handles multiple frames, and so it must traverse the input to1231* read each contained frame header. This is fast as most of the data is skipped,1232* however it does mean that all frame data must be present and valid. */1233ZSTDLIB_API unsigned long long ZSTD_findDecompressedSize(const void* src, size_t srcSize);12341235/*! ZSTD_decompressBound() :1236* `src` should point to the start of a series of ZSTD encoded and/or skippable frames1237* `srcSize` must be the _exact_ size of this series1238* (i.e. there should be a frame boundary at `src + srcSize`)1239* @return : - upper-bound for the decompressed size of all data in all successive frames1240* - if an error occured: ZSTD_CONTENTSIZE_ERROR1241*1242* note 1 : an error can occur if `src` contains an invalid or incorrectly formatted frame.1243* note 2 : the upper-bound is exact when the decompressed size field is available in every ZSTD encoded frame of `src`.1244* in this case, `ZSTD_findDecompressedSize` and `ZSTD_decompressBound` return the same value.1245* note 3 : when the decompressed size field isn't available, the upper-bound for that frame is calculated by:1246* upper-bound = # blocks * min(128 KB, Window_Size)1247*/1248ZSTDLIB_API unsigned long long ZSTD_decompressBound(const void* src, size_t srcSize);12491250/*! ZSTD_frameHeaderSize() :1251* srcSize must be >= ZSTD_FRAMEHEADERSIZE_PREFIX.1252* @return : size of the Frame Header,1253* or an error code (if srcSize is too small) */1254ZSTDLIB_API size_t ZSTD_frameHeaderSize(const void* src, size_t srcSize);12551256/*! ZSTD_getSequences() :1257* Extract sequences from the sequence store1258* zc can be used to insert custom compression params.1259* This function invokes ZSTD_compress21260* @return : number of sequences extracted1261*/1262ZSTDLIB_API size_t ZSTD_getSequences(ZSTD_CCtx* zc, ZSTD_Sequence* outSeqs,1263size_t outSeqsSize, const void* src, size_t srcSize);126412651266/***************************************1267* Memory management1268***************************************/12691270/*! ZSTD_estimate*() :1271* These functions make it possible to estimate memory usage1272* of a future {D,C}Ctx, before its creation.1273*1274* ZSTD_estimateCCtxSize() will provide a memory budget large enough1275* for any compression level up to selected one.1276* Note : Unlike ZSTD_estimateCStreamSize*(), this estimate1277* does not include space for a window buffer.1278* Therefore, the estimation is only guaranteed for single-shot compressions, not streaming.1279* The estimate will assume the input may be arbitrarily large,1280* which is the worst case.1281*1282* When srcSize can be bound by a known and rather "small" value,1283* this fact can be used to provide a tighter estimation1284* because the CCtx compression context will need less memory.1285* This tighter estimation can be provided by more advanced functions1286* ZSTD_estimateCCtxSize_usingCParams(), which can be used in tandem with ZSTD_getCParams(),1287* and ZSTD_estimateCCtxSize_usingCCtxParams(), which can be used in tandem with ZSTD_CCtxParams_setParameter().1288* Both can be used to estimate memory using custom compression parameters and arbitrary srcSize limits.1289*1290* Note 2 : only single-threaded compression is supported.1291* ZSTD_estimateCCtxSize_usingCCtxParams() will return an error code if ZSTD_c_nbWorkers is >= 1.1292*/1293ZSTDLIB_API size_t ZSTD_estimateCCtxSize(int compressionLevel);1294ZSTDLIB_API size_t ZSTD_estimateCCtxSize_usingCParams(ZSTD_compressionParameters cParams);1295ZSTDLIB_API size_t ZSTD_estimateCCtxSize_usingCCtxParams(const ZSTD_CCtx_params* params);1296ZSTDLIB_API size_t ZSTD_estimateDCtxSize(void);12971298/*! ZSTD_estimateCStreamSize() :1299* ZSTD_estimateCStreamSize() will provide a budget large enough for any compression level up to selected one.1300* It will also consider src size to be arbitrarily "large", which is worst case.1301* If srcSize is known to always be small, ZSTD_estimateCStreamSize_usingCParams() can provide a tighter estimation.1302* ZSTD_estimateCStreamSize_usingCParams() can be used in tandem with ZSTD_getCParams() to create cParams from compressionLevel.1303* ZSTD_estimateCStreamSize_usingCCtxParams() can be used in tandem with ZSTD_CCtxParams_setParameter(). Only single-threaded compression is supported. This function will return an error code if ZSTD_c_nbWorkers is >= 1.1304* Note : CStream size estimation is only correct for single-threaded compression.1305* ZSTD_DStream memory budget depends on window Size.1306* This information can be passed manually, using ZSTD_estimateDStreamSize,1307* or deducted from a valid frame Header, using ZSTD_estimateDStreamSize_fromFrame();1308* Note : if streaming is init with function ZSTD_init?Stream_usingDict(),1309* an internal ?Dict will be created, which additional size is not estimated here.1310* In this case, get total size by adding ZSTD_estimate?DictSize */1311ZSTDLIB_API size_t ZSTD_estimateCStreamSize(int compressionLevel);1312ZSTDLIB_API size_t ZSTD_estimateCStreamSize_usingCParams(ZSTD_compressionParameters cParams);1313ZSTDLIB_API size_t ZSTD_estimateCStreamSize_usingCCtxParams(const ZSTD_CCtx_params* params);1314ZSTDLIB_API size_t ZSTD_estimateDStreamSize(size_t windowSize);1315ZSTDLIB_API size_t ZSTD_estimateDStreamSize_fromFrame(const void* src, size_t srcSize);13161317/*! ZSTD_estimate?DictSize() :1318* ZSTD_estimateCDictSize() will bet that src size is relatively "small", and content is copied, like ZSTD_createCDict().1319* ZSTD_estimateCDictSize_advanced() makes it possible to control compression parameters precisely, like ZSTD_createCDict_advanced().1320* Note : dictionaries created by reference (`ZSTD_dlm_byRef`) are logically smaller.1321*/1322ZSTDLIB_API size_t ZSTD_estimateCDictSize(size_t dictSize, int compressionLevel);1323ZSTDLIB_API size_t ZSTD_estimateCDictSize_advanced(size_t dictSize, ZSTD_compressionParameters cParams, ZSTD_dictLoadMethod_e dictLoadMethod);1324ZSTDLIB_API size_t ZSTD_estimateDDictSize(size_t dictSize, ZSTD_dictLoadMethod_e dictLoadMethod);13251326/*! ZSTD_initStatic*() :1327* Initialize an object using a pre-allocated fixed-size buffer.1328* workspace: The memory area to emplace the object into.1329* Provided pointer *must be 8-bytes aligned*.1330* Buffer must outlive object.1331* workspaceSize: Use ZSTD_estimate*Size() to determine1332* how large workspace must be to support target scenario.1333* @return : pointer to object (same address as workspace, just different type),1334* or NULL if error (size too small, incorrect alignment, etc.)1335* Note : zstd will never resize nor malloc() when using a static buffer.1336* If the object requires more memory than available,1337* zstd will just error out (typically ZSTD_error_memory_allocation).1338* Note 2 : there is no corresponding "free" function.1339* Since workspace is allocated externally, it must be freed externally too.1340* Note 3 : cParams : use ZSTD_getCParams() to convert a compression level1341* into its associated cParams.1342* Limitation 1 : currently not compatible with internal dictionary creation, triggered by1343* ZSTD_CCtx_loadDictionary(), ZSTD_initCStream_usingDict() or ZSTD_initDStream_usingDict().1344* Limitation 2 : static cctx currently not compatible with multi-threading.1345* Limitation 3 : static dctx is incompatible with legacy support.1346*/1347ZSTDLIB_API ZSTD_CCtx* ZSTD_initStaticCCtx(void* workspace, size_t workspaceSize);1348ZSTDLIB_API ZSTD_CStream* ZSTD_initStaticCStream(void* workspace, size_t workspaceSize); /**< same as ZSTD_initStaticCCtx() */13491350ZSTDLIB_API ZSTD_DCtx* ZSTD_initStaticDCtx(void* workspace, size_t workspaceSize);1351ZSTDLIB_API ZSTD_DStream* ZSTD_initStaticDStream(void* workspace, size_t workspaceSize); /**< same as ZSTD_initStaticDCtx() */13521353ZSTDLIB_API const ZSTD_CDict* ZSTD_initStaticCDict(1354void* workspace, size_t workspaceSize,1355const void* dict, size_t dictSize,1356ZSTD_dictLoadMethod_e dictLoadMethod,1357ZSTD_dictContentType_e dictContentType,1358ZSTD_compressionParameters cParams);13591360ZSTDLIB_API const ZSTD_DDict* ZSTD_initStaticDDict(1361void* workspace, size_t workspaceSize,1362const void* dict, size_t dictSize,1363ZSTD_dictLoadMethod_e dictLoadMethod,1364ZSTD_dictContentType_e dictContentType);136513661367/*! Custom memory allocation :1368* These prototypes make it possible to pass your own allocation/free functions.1369* ZSTD_customMem is provided at creation time, using ZSTD_create*_advanced() variants listed below.1370* All allocation/free operations will be completed using these custom variants instead of regular <stdlib.h> ones.1371*/1372typedef void* (*ZSTD_allocFunction) (void* opaque, size_t size);1373typedef void (*ZSTD_freeFunction) (void* opaque, void* address);1374typedef struct { ZSTD_allocFunction customAlloc; ZSTD_freeFunction customFree; void* opaque; } ZSTD_customMem;1375static ZSTD_customMem const ZSTD_defaultCMem = { NULL, NULL, NULL }; /**< this constant defers to stdlib's functions */13761377ZSTDLIB_API ZSTD_CCtx* ZSTD_createCCtx_advanced(ZSTD_customMem customMem);1378ZSTDLIB_API ZSTD_CStream* ZSTD_createCStream_advanced(ZSTD_customMem customMem);1379ZSTDLIB_API ZSTD_DCtx* ZSTD_createDCtx_advanced(ZSTD_customMem customMem);1380ZSTDLIB_API ZSTD_DStream* ZSTD_createDStream_advanced(ZSTD_customMem customMem);13811382ZSTDLIB_API ZSTD_CDict* ZSTD_createCDict_advanced(const void* dict, size_t dictSize,1383ZSTD_dictLoadMethod_e dictLoadMethod,1384ZSTD_dictContentType_e dictContentType,1385ZSTD_compressionParameters cParams,1386ZSTD_customMem customMem);13871388ZSTDLIB_API ZSTD_DDict* ZSTD_createDDict_advanced(const void* dict, size_t dictSize,1389ZSTD_dictLoadMethod_e dictLoadMethod,1390ZSTD_dictContentType_e dictContentType,1391ZSTD_customMem customMem);1392139313941395/***************************************1396* Advanced compression functions1397***************************************/13981399/*! ZSTD_createCDict_byReference() :1400* Create a digested dictionary for compression1401* Dictionary content is just referenced, not duplicated.1402* As a consequence, `dictBuffer` **must** outlive CDict,1403* and its content must remain unmodified throughout the lifetime of CDict.1404* note: equivalent to ZSTD_createCDict_advanced(), with dictLoadMethod==ZSTD_dlm_byRef */1405ZSTDLIB_API ZSTD_CDict* ZSTD_createCDict_byReference(const void* dictBuffer, size_t dictSize, int compressionLevel);14061407/*! ZSTD_getCParams() :1408* @return ZSTD_compressionParameters structure for a selected compression level and estimated srcSize.1409* `estimatedSrcSize` value is optional, select 0 if not known */1410ZSTDLIB_API ZSTD_compressionParameters ZSTD_getCParams(int compressionLevel, unsigned long long estimatedSrcSize, size_t dictSize);14111412/*! ZSTD_getParams() :1413* same as ZSTD_getCParams(), but @return a full `ZSTD_parameters` object instead of sub-component `ZSTD_compressionParameters`.1414* All fields of `ZSTD_frameParameters` are set to default : contentSize=1, checksum=0, noDictID=0 */1415ZSTDLIB_API ZSTD_parameters ZSTD_getParams(int compressionLevel, unsigned long long estimatedSrcSize, size_t dictSize);14161417/*! ZSTD_checkCParams() :1418* Ensure param values remain within authorized range.1419* @return 0 on success, or an error code (can be checked with ZSTD_isError()) */1420ZSTDLIB_API size_t ZSTD_checkCParams(ZSTD_compressionParameters params);14211422/*! ZSTD_adjustCParams() :1423* optimize params for a given `srcSize` and `dictSize`.1424* `srcSize` can be unknown, in which case use ZSTD_CONTENTSIZE_UNKNOWN.1425* `dictSize` must be `0` when there is no dictionary.1426* cPar can be invalid : all parameters will be clamped within valid range in the @return struct.1427* This function never fails (wide contract) */1428ZSTDLIB_API ZSTD_compressionParameters ZSTD_adjustCParams(ZSTD_compressionParameters cPar, unsigned long long srcSize, size_t dictSize);14291430/*! ZSTD_compress_advanced() :1431* Note : this function is now DEPRECATED.1432* It can be replaced by ZSTD_compress2(), in combination with ZSTD_CCtx_setParameter() and other parameter setters.1433* This prototype will be marked as deprecated and generate compilation warning on reaching v1.5.x */1434ZSTDLIB_API size_t ZSTD_compress_advanced(ZSTD_CCtx* cctx,1435void* dst, size_t dstCapacity,1436const void* src, size_t srcSize,1437const void* dict,size_t dictSize,1438ZSTD_parameters params);14391440/*! ZSTD_compress_usingCDict_advanced() :1441* Note : this function is now REDUNDANT.1442* It can be replaced by ZSTD_compress2(), in combination with ZSTD_CCtx_loadDictionary() and other parameter setters.1443* This prototype will be marked as deprecated and generate compilation warning in some future version */1444ZSTDLIB_API size_t ZSTD_compress_usingCDict_advanced(ZSTD_CCtx* cctx,1445void* dst, size_t dstCapacity,1446const void* src, size_t srcSize,1447const ZSTD_CDict* cdict,1448ZSTD_frameParameters fParams);144914501451/*! ZSTD_CCtx_loadDictionary_byReference() :1452* Same as ZSTD_CCtx_loadDictionary(), but dictionary content is referenced, instead of being copied into CCtx.1453* It saves some memory, but also requires that `dict` outlives its usage within `cctx` */1454ZSTDLIB_API size_t ZSTD_CCtx_loadDictionary_byReference(ZSTD_CCtx* cctx, const void* dict, size_t dictSize);14551456/*! ZSTD_CCtx_loadDictionary_advanced() :1457* Same as ZSTD_CCtx_loadDictionary(), but gives finer control over1458* how to load the dictionary (by copy ? by reference ?)1459* and how to interpret it (automatic ? force raw mode ? full mode only ?) */1460ZSTDLIB_API size_t ZSTD_CCtx_loadDictionary_advanced(ZSTD_CCtx* cctx, const void* dict, size_t dictSize, ZSTD_dictLoadMethod_e dictLoadMethod, ZSTD_dictContentType_e dictContentType);14611462/*! ZSTD_CCtx_refPrefix_advanced() :1463* Same as ZSTD_CCtx_refPrefix(), but gives finer control over1464* how to interpret prefix content (automatic ? force raw mode (default) ? full mode only ?) */1465ZSTDLIB_API size_t ZSTD_CCtx_refPrefix_advanced(ZSTD_CCtx* cctx, const void* prefix, size_t prefixSize, ZSTD_dictContentType_e dictContentType);14661467/* === experimental parameters === */1468/* these parameters can be used with ZSTD_setParameter()1469* they are not guaranteed to remain supported in the future */14701471/* Enables rsyncable mode,1472* which makes compressed files more rsync friendly1473* by adding periodic synchronization points to the compressed data.1474* The target average block size is ZSTD_c_jobSize / 2.1475* It's possible to modify the job size to increase or decrease1476* the granularity of the synchronization point.1477* Once the jobSize is smaller than the window size,1478* it will result in compression ratio degradation.1479* NOTE 1: rsyncable mode only works when multithreading is enabled.1480* NOTE 2: rsyncable performs poorly in combination with long range mode,1481* since it will decrease the effectiveness of synchronization points,1482* though mileage may vary.1483* NOTE 3: Rsyncable mode limits maximum compression speed to ~400 MB/s.1484* If the selected compression level is already running significantly slower,1485* the overall speed won't be significantly impacted.1486*/1487#define ZSTD_c_rsyncable ZSTD_c_experimentalParam114881489/* Select a compression format.1490* The value must be of type ZSTD_format_e.1491* See ZSTD_format_e enum definition for details */1492#define ZSTD_c_format ZSTD_c_experimentalParam214931494/* Force back-reference distances to remain < windowSize,1495* even when referencing into Dictionary content (default:0) */1496#define ZSTD_c_forceMaxWindow ZSTD_c_experimentalParam314971498/* Controls whether the contents of a CDict1499* are used in place, or copied into the working context.1500* Accepts values from the ZSTD_dictAttachPref_e enum.1501* See the comments on that enum for an explanation of the feature. */1502#define ZSTD_c_forceAttachDict ZSTD_c_experimentalParam415031504/* Controls how the literals are compressed (default is auto).1505* The value must be of type ZSTD_literalCompressionMode_e.1506* See ZSTD_literalCompressionMode_t enum definition for details.1507*/1508#define ZSTD_c_literalCompressionMode ZSTD_c_experimentalParam515091510/* Tries to fit compressed block size to be around targetCBlockSize.1511* No target when targetCBlockSize == 0.1512* There is no guarantee on compressed block size (default:0) */1513#define ZSTD_c_targetCBlockSize ZSTD_c_experimentalParam615141515/* User's best guess of source size.1516* Hint is not valid when srcSizeHint == 0.1517* There is no guarantee that hint is close to actual source size,1518* but compression ratio may regress significantly if guess considerably underestimates */1519#define ZSTD_c_srcSizeHint ZSTD_c_experimentalParam715201521/*! ZSTD_CCtx_getParameter() :1522* Get the requested compression parameter value, selected by enum ZSTD_cParameter,1523* and store it into int* value.1524* @return : 0, or an error code (which can be tested with ZSTD_isError()).1525*/1526ZSTDLIB_API size_t ZSTD_CCtx_getParameter(ZSTD_CCtx* cctx, ZSTD_cParameter param, int* value);152715281529/*! ZSTD_CCtx_params :1530* Quick howto :1531* - ZSTD_createCCtxParams() : Create a ZSTD_CCtx_params structure1532* - ZSTD_CCtxParams_setParameter() : Push parameters one by one into1533* an existing ZSTD_CCtx_params structure.1534* This is similar to1535* ZSTD_CCtx_setParameter().1536* - ZSTD_CCtx_setParametersUsingCCtxParams() : Apply parameters to1537* an existing CCtx.1538* These parameters will be applied to1539* all subsequent frames.1540* - ZSTD_compressStream2() : Do compression using the CCtx.1541* - ZSTD_freeCCtxParams() : Free the memory.1542*1543* This can be used with ZSTD_estimateCCtxSize_advanced_usingCCtxParams()1544* for static allocation of CCtx for single-threaded compression.1545*/1546ZSTDLIB_API ZSTD_CCtx_params* ZSTD_createCCtxParams(void);1547ZSTDLIB_API size_t ZSTD_freeCCtxParams(ZSTD_CCtx_params* params);15481549/*! ZSTD_CCtxParams_reset() :1550* Reset params to default values.1551*/1552ZSTDLIB_API size_t ZSTD_CCtxParams_reset(ZSTD_CCtx_params* params);15531554/*! ZSTD_CCtxParams_init() :1555* Initializes the compression parameters of cctxParams according to1556* compression level. All other parameters are reset to their default values.1557*/1558ZSTDLIB_API size_t ZSTD_CCtxParams_init(ZSTD_CCtx_params* cctxParams, int compressionLevel);15591560/*! ZSTD_CCtxParams_init_advanced() :1561* Initializes the compression and frame parameters of cctxParams according to1562* params. All other parameters are reset to their default values.1563*/1564ZSTDLIB_API size_t ZSTD_CCtxParams_init_advanced(ZSTD_CCtx_params* cctxParams, ZSTD_parameters params);15651566/*! ZSTD_CCtxParams_setParameter() :1567* Similar to ZSTD_CCtx_setParameter.1568* Set one compression parameter, selected by enum ZSTD_cParameter.1569* Parameters must be applied to a ZSTD_CCtx using ZSTD_CCtx_setParametersUsingCCtxParams().1570* @result : 0, or an error code (which can be tested with ZSTD_isError()).1571*/1572ZSTDLIB_API size_t ZSTD_CCtxParams_setParameter(ZSTD_CCtx_params* params, ZSTD_cParameter param, int value);15731574/*! ZSTD_CCtxParams_getParameter() :1575* Similar to ZSTD_CCtx_getParameter.1576* Get the requested value of one compression parameter, selected by enum ZSTD_cParameter.1577* @result : 0, or an error code (which can be tested with ZSTD_isError()).1578*/1579ZSTDLIB_API size_t ZSTD_CCtxParams_getParameter(ZSTD_CCtx_params* params, ZSTD_cParameter param, int* value);15801581/*! ZSTD_CCtx_setParametersUsingCCtxParams() :1582* Apply a set of ZSTD_CCtx_params to the compression context.1583* This can be done even after compression is started,1584* if nbWorkers==0, this will have no impact until a new compression is started.1585* if nbWorkers>=1, new parameters will be picked up at next job,1586* with a few restrictions (windowLog, pledgedSrcSize, nbWorkers, jobSize, and overlapLog are not updated).1587*/1588ZSTDLIB_API size_t ZSTD_CCtx_setParametersUsingCCtxParams(1589ZSTD_CCtx* cctx, const ZSTD_CCtx_params* params);15901591/*! ZSTD_compressStream2_simpleArgs() :1592* Same as ZSTD_compressStream2(),1593* but using only integral types as arguments.1594* This variant might be helpful for binders from dynamic languages1595* which have troubles handling structures containing memory pointers.1596*/1597ZSTDLIB_API size_t ZSTD_compressStream2_simpleArgs (1598ZSTD_CCtx* cctx,1599void* dst, size_t dstCapacity, size_t* dstPos,1600const void* src, size_t srcSize, size_t* srcPos,1601ZSTD_EndDirective endOp);160216031604/***************************************1605* Advanced decompression functions1606***************************************/16071608/*! ZSTD_isFrame() :1609* Tells if the content of `buffer` starts with a valid Frame Identifier.1610* Note : Frame Identifier is 4 bytes. If `size < 4`, @return will always be 0.1611* Note 2 : Legacy Frame Identifiers are considered valid only if Legacy Support is enabled.1612* Note 3 : Skippable Frame Identifiers are considered valid. */1613ZSTDLIB_API unsigned ZSTD_isFrame(const void* buffer, size_t size);16141615/*! ZSTD_createDDict_byReference() :1616* Create a digested dictionary, ready to start decompression operation without startup delay.1617* Dictionary content is referenced, and therefore stays in dictBuffer.1618* It is important that dictBuffer outlives DDict,1619* it must remain read accessible throughout the lifetime of DDict */1620ZSTDLIB_API ZSTD_DDict* ZSTD_createDDict_byReference(const void* dictBuffer, size_t dictSize);16211622/*! ZSTD_DCtx_loadDictionary_byReference() :1623* Same as ZSTD_DCtx_loadDictionary(),1624* but references `dict` content instead of copying it into `dctx`.1625* This saves memory if `dict` remains around.,1626* However, it's imperative that `dict` remains accessible (and unmodified) while being used, so it must outlive decompression. */1627ZSTDLIB_API size_t ZSTD_DCtx_loadDictionary_byReference(ZSTD_DCtx* dctx, const void* dict, size_t dictSize);16281629/*! ZSTD_DCtx_loadDictionary_advanced() :1630* Same as ZSTD_DCtx_loadDictionary(),1631* but gives direct control over1632* how to load the dictionary (by copy ? by reference ?)1633* and how to interpret it (automatic ? force raw mode ? full mode only ?). */1634ZSTDLIB_API size_t ZSTD_DCtx_loadDictionary_advanced(ZSTD_DCtx* dctx, const void* dict, size_t dictSize, ZSTD_dictLoadMethod_e dictLoadMethod, ZSTD_dictContentType_e dictContentType);16351636/*! ZSTD_DCtx_refPrefix_advanced() :1637* Same as ZSTD_DCtx_refPrefix(), but gives finer control over1638* how to interpret prefix content (automatic ? force raw mode (default) ? full mode only ?) */1639ZSTDLIB_API size_t ZSTD_DCtx_refPrefix_advanced(ZSTD_DCtx* dctx, const void* prefix, size_t prefixSize, ZSTD_dictContentType_e dictContentType);16401641/*! ZSTD_DCtx_setMaxWindowSize() :1642* Refuses allocating internal buffers for frames requiring a window size larger than provided limit.1643* This protects a decoder context from reserving too much memory for itself (potential attack scenario).1644* This parameter is only useful in streaming mode, since no internal buffer is allocated in single-pass mode.1645* By default, a decompression context accepts all window sizes <= (1 << ZSTD_WINDOWLOG_LIMIT_DEFAULT)1646* @return : 0, or an error code (which can be tested using ZSTD_isError()).1647*/1648ZSTDLIB_API size_t ZSTD_DCtx_setMaxWindowSize(ZSTD_DCtx* dctx, size_t maxWindowSize);16491650/* ZSTD_d_format1651* experimental parameter,1652* allowing selection between ZSTD_format_e input compression formats1653*/1654#define ZSTD_d_format ZSTD_d_experimentalParam11655/* ZSTD_d_stableOutBuffer1656* Experimental parameter.1657* Default is 0 == disabled. Set to 1 to enable.1658*1659* Tells the decompressor that the ZSTD_outBuffer will ALWAYS be the same1660* between calls, except for the modifications that zstd makes to pos (the1661* caller must not modify pos). This is checked by the decompressor, and1662* decompression will fail if it ever changes. Therefore the ZSTD_outBuffer1663* MUST be large enough to fit the entire decompressed frame. This will be1664* checked when the frame content size is known. The data in the ZSTD_outBuffer1665* in the range [dst, dst + pos) MUST not be modified during decompression1666* or you will get data corruption.1667*1668* When this flags is enabled zstd won't allocate an output buffer, because1669* it can write directly to the ZSTD_outBuffer, but it will still allocate1670* an input buffer large enough to fit any compressed block. This will also1671* avoid the memcpy() from the internal output buffer to the ZSTD_outBuffer.1672* If you need to avoid the input buffer allocation use the buffer-less1673* streaming API.1674*1675* NOTE: So long as the ZSTD_outBuffer always points to valid memory, using1676* this flag is ALWAYS memory safe, and will never access out-of-bounds1677* memory. However, decompression WILL fail if you violate the preconditions.1678*1679* WARNING: The data in the ZSTD_outBuffer in the range [dst, dst + pos) MUST1680* not be modified during decompression or you will get data corruption. This1681* is because zstd needs to reference data in the ZSTD_outBuffer to regenerate1682* matches. Normally zstd maintains its own buffer for this purpose, but passing1683* this flag tells zstd to use the user provided buffer.1684*/1685#define ZSTD_d_stableOutBuffer ZSTD_d_experimentalParam216861687/*! ZSTD_DCtx_setFormat() :1688* Instruct the decoder context about what kind of data to decode next.1689* This instruction is mandatory to decode data without a fully-formed header,1690* such ZSTD_f_zstd1_magicless for example.1691* @return : 0, or an error code (which can be tested using ZSTD_isError()). */1692ZSTDLIB_API size_t ZSTD_DCtx_setFormat(ZSTD_DCtx* dctx, ZSTD_format_e format);16931694/*! ZSTD_decompressStream_simpleArgs() :1695* Same as ZSTD_decompressStream(),1696* but using only integral types as arguments.1697* This can be helpful for binders from dynamic languages1698* which have troubles handling structures containing memory pointers.1699*/1700ZSTDLIB_API size_t ZSTD_decompressStream_simpleArgs (1701ZSTD_DCtx* dctx,1702void* dst, size_t dstCapacity, size_t* dstPos,1703const void* src, size_t srcSize, size_t* srcPos);170417051706/********************************************************************1707* Advanced streaming functions1708* Warning : most of these functions are now redundant with the Advanced API.1709* Once Advanced API reaches "stable" status,1710* redundant functions will be deprecated, and then at some point removed.1711********************************************************************/17121713/*===== Advanced Streaming compression functions =====*/1714/**! ZSTD_initCStream_srcSize() :1715* This function is deprecated, and equivalent to:1716* ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only);1717* ZSTD_CCtx_refCDict(zcs, NULL); // clear the dictionary (if any)1718* ZSTD_CCtx_setParameter(zcs, ZSTD_c_compressionLevel, compressionLevel);1719* ZSTD_CCtx_setPledgedSrcSize(zcs, pledgedSrcSize);1720*1721* pledgedSrcSize must be correct. If it is not known at init time, use1722* ZSTD_CONTENTSIZE_UNKNOWN. Note that, for compatibility with older programs,1723* "0" also disables frame content size field. It may be enabled in the future.1724* Note : this prototype will be marked as deprecated and generate compilation warnings on reaching v1.5.x1725*/1726ZSTDLIB_API size_t1727ZSTD_initCStream_srcSize(ZSTD_CStream* zcs,1728int compressionLevel,1729unsigned long long pledgedSrcSize);17301731/**! ZSTD_initCStream_usingDict() :1732* This function is deprecated, and is equivalent to:1733* ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only);1734* ZSTD_CCtx_setParameter(zcs, ZSTD_c_compressionLevel, compressionLevel);1735* ZSTD_CCtx_loadDictionary(zcs, dict, dictSize);1736*1737* Creates of an internal CDict (incompatible with static CCtx), except if1738* dict == NULL or dictSize < 8, in which case no dict is used.1739* Note: dict is loaded with ZSTD_dct_auto (treated as a full zstd dictionary if1740* it begins with ZSTD_MAGIC_DICTIONARY, else as raw content) and ZSTD_dlm_byCopy.1741* Note : this prototype will be marked as deprecated and generate compilation warnings on reaching v1.5.x1742*/1743ZSTDLIB_API size_t1744ZSTD_initCStream_usingDict(ZSTD_CStream* zcs,1745const void* dict, size_t dictSize,1746int compressionLevel);17471748/**! ZSTD_initCStream_advanced() :1749* This function is deprecated, and is approximately equivalent to:1750* ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only);1751* // Pseudocode: Set each zstd parameter and leave the rest as-is.1752* for ((param, value) : params) {1753* ZSTD_CCtx_setParameter(zcs, param, value);1754* }1755* ZSTD_CCtx_setPledgedSrcSize(zcs, pledgedSrcSize);1756* ZSTD_CCtx_loadDictionary(zcs, dict, dictSize);1757*1758* dict is loaded with ZSTD_dct_auto and ZSTD_dlm_byCopy.1759* pledgedSrcSize must be correct.1760* If srcSize is not known at init time, use value ZSTD_CONTENTSIZE_UNKNOWN.1761* Note : this prototype will be marked as deprecated and generate compilation warnings on reaching v1.5.x1762*/1763ZSTDLIB_API size_t1764ZSTD_initCStream_advanced(ZSTD_CStream* zcs,1765const void* dict, size_t dictSize,1766ZSTD_parameters params,1767unsigned long long pledgedSrcSize);17681769/**! ZSTD_initCStream_usingCDict() :1770* This function is deprecated, and equivalent to:1771* ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only);1772* ZSTD_CCtx_refCDict(zcs, cdict);1773*1774* note : cdict will just be referenced, and must outlive compression session1775* Note : this prototype will be marked as deprecated and generate compilation warnings on reaching v1.5.x1776*/1777ZSTDLIB_API size_t ZSTD_initCStream_usingCDict(ZSTD_CStream* zcs, const ZSTD_CDict* cdict);17781779/**! ZSTD_initCStream_usingCDict_advanced() :1780* This function is DEPRECATED, and is approximately equivalent to:1781* ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only);1782* // Pseudocode: Set each zstd frame parameter and leave the rest as-is.1783* for ((fParam, value) : fParams) {1784* ZSTD_CCtx_setParameter(zcs, fParam, value);1785* }1786* ZSTD_CCtx_setPledgedSrcSize(zcs, pledgedSrcSize);1787* ZSTD_CCtx_refCDict(zcs, cdict);1788*1789* same as ZSTD_initCStream_usingCDict(), with control over frame parameters.1790* pledgedSrcSize must be correct. If srcSize is not known at init time, use1791* value ZSTD_CONTENTSIZE_UNKNOWN.1792* Note : this prototype will be marked as deprecated and generate compilation warnings on reaching v1.5.x1793*/1794ZSTDLIB_API size_t1795ZSTD_initCStream_usingCDict_advanced(ZSTD_CStream* zcs,1796const ZSTD_CDict* cdict,1797ZSTD_frameParameters fParams,1798unsigned long long pledgedSrcSize);17991800/*! ZSTD_resetCStream() :1801* This function is deprecated, and is equivalent to:1802* ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only);1803* ZSTD_CCtx_setPledgedSrcSize(zcs, pledgedSrcSize);1804*1805* start a new frame, using same parameters from previous frame.1806* This is typically useful to skip dictionary loading stage, since it will re-use it in-place.1807* Note that zcs must be init at least once before using ZSTD_resetCStream().1808* If pledgedSrcSize is not known at reset time, use macro ZSTD_CONTENTSIZE_UNKNOWN.1809* If pledgedSrcSize > 0, its value must be correct, as it will be written in header, and controlled at the end.1810* For the time being, pledgedSrcSize==0 is interpreted as "srcSize unknown" for compatibility with older programs,1811* but it will change to mean "empty" in future version, so use macro ZSTD_CONTENTSIZE_UNKNOWN instead.1812* @return : 0, or an error code (which can be tested using ZSTD_isError())1813* Note : this prototype will be marked as deprecated and generate compilation warnings on reaching v1.5.x1814*/1815ZSTDLIB_API size_t ZSTD_resetCStream(ZSTD_CStream* zcs, unsigned long long pledgedSrcSize);181618171818typedef struct {1819unsigned long long ingested; /* nb input bytes read and buffered */1820unsigned long long consumed; /* nb input bytes actually compressed */1821unsigned long long produced; /* nb of compressed bytes generated and buffered */1822unsigned long long flushed; /* nb of compressed bytes flushed : not provided; can be tracked from caller side */1823unsigned currentJobID; /* MT only : latest started job nb */1824unsigned nbActiveWorkers; /* MT only : nb of workers actively compressing at probe time */1825} ZSTD_frameProgression;18261827/* ZSTD_getFrameProgression() :1828* tells how much data has been ingested (read from input)1829* consumed (input actually compressed) and produced (output) for current frame.1830* Note : (ingested - consumed) is amount of input data buffered internally, not yet compressed.1831* Aggregates progression inside active worker threads.1832*/1833ZSTDLIB_API ZSTD_frameProgression ZSTD_getFrameProgression(const ZSTD_CCtx* cctx);18341835/*! ZSTD_toFlushNow() :1836* Tell how many bytes are ready to be flushed immediately.1837* Useful for multithreading scenarios (nbWorkers >= 1).1838* Probe the oldest active job, defined as oldest job not yet entirely flushed,1839* and check its output buffer.1840* @return : amount of data stored in oldest job and ready to be flushed immediately.1841* if @return == 0, it means either :1842* + there is no active job (could be checked with ZSTD_frameProgression()), or1843* + oldest job is still actively compressing data,1844* but everything it has produced has also been flushed so far,1845* therefore flush speed is limited by production speed of oldest job1846* irrespective of the speed of concurrent (and newer) jobs.1847*/1848ZSTDLIB_API size_t ZSTD_toFlushNow(ZSTD_CCtx* cctx);184918501851/*===== Advanced Streaming decompression functions =====*/1852/**1853* This function is deprecated, and is equivalent to:1854*1855* ZSTD_DCtx_reset(zds, ZSTD_reset_session_only);1856* ZSTD_DCtx_loadDictionary(zds, dict, dictSize);1857*1858* note: no dictionary will be used if dict == NULL or dictSize < 81859* Note : this prototype will be marked as deprecated and generate compilation warnings on reaching v1.5.x1860*/1861ZSTDLIB_API size_t ZSTD_initDStream_usingDict(ZSTD_DStream* zds, const void* dict, size_t dictSize);18621863/**1864* This function is deprecated, and is equivalent to:1865*1866* ZSTD_DCtx_reset(zds, ZSTD_reset_session_only);1867* ZSTD_DCtx_refDDict(zds, ddict);1868*1869* note : ddict is referenced, it must outlive decompression session1870* Note : this prototype will be marked as deprecated and generate compilation warnings on reaching v1.5.x1871*/1872ZSTDLIB_API size_t ZSTD_initDStream_usingDDict(ZSTD_DStream* zds, const ZSTD_DDict* ddict);18731874/**1875* This function is deprecated, and is equivalent to:1876*1877* ZSTD_DCtx_reset(zds, ZSTD_reset_session_only);1878*1879* re-use decompression parameters from previous init; saves dictionary loading1880* Note : this prototype will be marked as deprecated and generate compilation warnings on reaching v1.5.x1881*/1882ZSTDLIB_API size_t ZSTD_resetDStream(ZSTD_DStream* zds);188318841885/*********************************************************************1886* Buffer-less and synchronous inner streaming functions1887*1888* This is an advanced API, giving full control over buffer management, for users which need direct control over memory.1889* But it's also a complex one, with several restrictions, documented below.1890* Prefer normal streaming API for an easier experience.1891********************************************************************* */18921893/**1894Buffer-less streaming compression (synchronous mode)18951896A ZSTD_CCtx object is required to track streaming operations.1897Use ZSTD_createCCtx() / ZSTD_freeCCtx() to manage resource.1898ZSTD_CCtx object can be re-used multiple times within successive compression operations.18991900Start by initializing a context.1901Use ZSTD_compressBegin(), or ZSTD_compressBegin_usingDict() for dictionary compression,1902or ZSTD_compressBegin_advanced(), for finer parameter control.1903It's also possible to duplicate a reference context which has already been initialized, using ZSTD_copyCCtx()19041905Then, consume your input using ZSTD_compressContinue().1906There are some important considerations to keep in mind when using this advanced function :1907- ZSTD_compressContinue() has no internal buffer. It uses externally provided buffers only.1908- Interface is synchronous : input is consumed entirely and produces 1+ compressed blocks.1909- Caller must ensure there is enough space in `dst` to store compressed data under worst case scenario.1910Worst case evaluation is provided by ZSTD_compressBound().1911ZSTD_compressContinue() doesn't guarantee recover after a failed compression.1912- ZSTD_compressContinue() presumes prior input ***is still accessible and unmodified*** (up to maximum distance size, see WindowLog).1913It remembers all previous contiguous blocks, plus one separated memory segment (which can itself consists of multiple contiguous blocks)1914- ZSTD_compressContinue() detects that prior input has been overwritten when `src` buffer overlaps.1915In which case, it will "discard" the relevant memory section from its history.19161917Finish a frame with ZSTD_compressEnd(), which will write the last block(s) and optional checksum.1918It's possible to use srcSize==0, in which case, it will write a final empty block to end the frame.1919Without last block mark, frames are considered unfinished (hence corrupted) by compliant decoders.19201921`ZSTD_CCtx` object can be re-used (ZSTD_compressBegin()) to compress again.1922*/19231924/*===== Buffer-less streaming compression functions =====*/1925ZSTDLIB_API size_t ZSTD_compressBegin(ZSTD_CCtx* cctx, int compressionLevel);1926ZSTDLIB_API size_t ZSTD_compressBegin_usingDict(ZSTD_CCtx* cctx, const void* dict, size_t dictSize, int compressionLevel);1927ZSTDLIB_API size_t ZSTD_compressBegin_advanced(ZSTD_CCtx* cctx, const void* dict, size_t dictSize, ZSTD_parameters params, unsigned long long pledgedSrcSize); /**< pledgedSrcSize : If srcSize is not known at init time, use ZSTD_CONTENTSIZE_UNKNOWN */1928ZSTDLIB_API size_t ZSTD_compressBegin_usingCDict(ZSTD_CCtx* cctx, const ZSTD_CDict* cdict); /**< note: fails if cdict==NULL */1929ZSTDLIB_API size_t ZSTD_compressBegin_usingCDict_advanced(ZSTD_CCtx* const cctx, const ZSTD_CDict* const cdict, ZSTD_frameParameters const fParams, unsigned long long const pledgedSrcSize); /* compression parameters are already set within cdict. pledgedSrcSize must be correct. If srcSize is not known, use macro ZSTD_CONTENTSIZE_UNKNOWN */1930ZSTDLIB_API size_t ZSTD_copyCCtx(ZSTD_CCtx* cctx, const ZSTD_CCtx* preparedCCtx, unsigned long long pledgedSrcSize); /**< note: if pledgedSrcSize is not known, use ZSTD_CONTENTSIZE_UNKNOWN */19311932ZSTDLIB_API size_t ZSTD_compressContinue(ZSTD_CCtx* cctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize);1933ZSTDLIB_API size_t ZSTD_compressEnd(ZSTD_CCtx* cctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize);193419351936/*-1937Buffer-less streaming decompression (synchronous mode)19381939A ZSTD_DCtx object is required to track streaming operations.1940Use ZSTD_createDCtx() / ZSTD_freeDCtx() to manage it.1941A ZSTD_DCtx object can be re-used multiple times.19421943First typical operation is to retrieve frame parameters, using ZSTD_getFrameHeader().1944Frame header is extracted from the beginning of compressed frame, so providing only the frame's beginning is enough.1945Data fragment must be large enough to ensure successful decoding.1946`ZSTD_frameHeaderSize_max` bytes is guaranteed to always be large enough.1947@result : 0 : successful decoding, the `ZSTD_frameHeader` structure is correctly filled.1948>0 : `srcSize` is too small, please provide at least @result bytes on next attempt.1949errorCode, which can be tested using ZSTD_isError().19501951It fills a ZSTD_frameHeader structure with important information to correctly decode the frame,1952such as the dictionary ID, content size, or maximum back-reference distance (`windowSize`).1953Note that these values could be wrong, either because of data corruption, or because a 3rd party deliberately spoofs false information.1954As a consequence, check that values remain within valid application range.1955For example, do not allocate memory blindly, check that `windowSize` is within expectation.1956Each application can set its own limits, depending on local restrictions.1957For extended interoperability, it is recommended to support `windowSize` of at least 8 MB.19581959ZSTD_decompressContinue() needs previous data blocks during decompression, up to `windowSize` bytes.1960ZSTD_decompressContinue() is very sensitive to contiguity,1961if 2 blocks don't follow each other, make sure that either the compressor breaks contiguity at the same place,1962or that previous contiguous segment is large enough to properly handle maximum back-reference distance.1963There are multiple ways to guarantee this condition.19641965The most memory efficient way is to use a round buffer of sufficient size.1966Sufficient size is determined by invoking ZSTD_decodingBufferSize_min(),1967which can @return an error code if required value is too large for current system (in 32-bits mode).1968In a round buffer methodology, ZSTD_decompressContinue() decompresses each block next to previous one,1969up to the moment there is not enough room left in the buffer to guarantee decoding another full block,1970which maximum size is provided in `ZSTD_frameHeader` structure, field `blockSizeMax`.1971At which point, decoding can resume from the beginning of the buffer.1972Note that already decoded data stored in the buffer should be flushed before being overwritten.19731974There are alternatives possible, for example using two or more buffers of size `windowSize` each, though they consume more memory.19751976Finally, if you control the compression process, you can also ignore all buffer size rules,1977as long as the encoder and decoder progress in "lock-step",1978aka use exactly the same buffer sizes, break contiguity at the same place, etc.19791980Once buffers are setup, start decompression, with ZSTD_decompressBegin().1981If decompression requires a dictionary, use ZSTD_decompressBegin_usingDict() or ZSTD_decompressBegin_usingDDict().19821983Then use ZSTD_nextSrcSizeToDecompress() and ZSTD_decompressContinue() alternatively.1984ZSTD_nextSrcSizeToDecompress() tells how many bytes to provide as 'srcSize' to ZSTD_decompressContinue().1985ZSTD_decompressContinue() requires this _exact_ amount of bytes, or it will fail.19861987@result of ZSTD_decompressContinue() is the number of bytes regenerated within 'dst' (necessarily <= dstCapacity).1988It can be zero : it just means ZSTD_decompressContinue() has decoded some metadata item.1989It can also be an error code, which can be tested with ZSTD_isError().19901991A frame is fully decoded when ZSTD_nextSrcSizeToDecompress() returns zero.1992Context can then be reset to start a new decompression.19931994Note : it's possible to know if next input to present is a header or a block, using ZSTD_nextInputType().1995This information is not required to properly decode a frame.19961997== Special case : skippable frames ==19981999Skippable frames allow integration of user-defined data into a flow of concatenated frames.2000Skippable frames will be ignored (skipped) by decompressor.2001The format of skippable frames is as follows :2002a) Skippable frame ID - 4 Bytes, Little endian format, any value from 0x184D2A50 to 0x184D2A5F2003b) Frame Size - 4 Bytes, Little endian format, unsigned 32-bits2004c) Frame Content - any content (User Data) of length equal to Frame Size2005For skippable frames ZSTD_getFrameHeader() returns zfhPtr->frameType==ZSTD_skippableFrame.2006For skippable frames ZSTD_decompressContinue() always returns 0 : it only skips the content.2007*/20082009/*===== Buffer-less streaming decompression functions =====*/2010typedef enum { ZSTD_frame, ZSTD_skippableFrame } ZSTD_frameType_e;2011typedef struct {2012unsigned long long frameContentSize; /* if == ZSTD_CONTENTSIZE_UNKNOWN, it means this field is not available. 0 means "empty" */2013unsigned long long windowSize; /* can be very large, up to <= frameContentSize */2014unsigned blockSizeMax;2015ZSTD_frameType_e frameType; /* if == ZSTD_skippableFrame, frameContentSize is the size of skippable content */2016unsigned headerSize;2017unsigned dictID;2018unsigned checksumFlag;2019} ZSTD_frameHeader;20202021/*! ZSTD_getFrameHeader() :2022* decode Frame Header, or requires larger `srcSize`.2023* @return : 0, `zfhPtr` is correctly filled,2024* >0, `srcSize` is too small, value is wanted `srcSize` amount,2025* or an error code, which can be tested using ZSTD_isError() */2026ZSTDLIB_API size_t ZSTD_getFrameHeader(ZSTD_frameHeader* zfhPtr, const void* src, size_t srcSize); /**< doesn't consume input */2027/*! ZSTD_getFrameHeader_advanced() :2028* same as ZSTD_getFrameHeader(),2029* with added capability to select a format (like ZSTD_f_zstd1_magicless) */2030ZSTDLIB_API size_t ZSTD_getFrameHeader_advanced(ZSTD_frameHeader* zfhPtr, const void* src, size_t srcSize, ZSTD_format_e format);2031ZSTDLIB_API size_t ZSTD_decodingBufferSize_min(unsigned long long windowSize, unsigned long long frameContentSize); /**< when frame content size is not known, pass in frameContentSize == ZSTD_CONTENTSIZE_UNKNOWN */20322033ZSTDLIB_API size_t ZSTD_decompressBegin(ZSTD_DCtx* dctx);2034ZSTDLIB_API size_t ZSTD_decompressBegin_usingDict(ZSTD_DCtx* dctx, const void* dict, size_t dictSize);2035ZSTDLIB_API size_t ZSTD_decompressBegin_usingDDict(ZSTD_DCtx* dctx, const ZSTD_DDict* ddict);20362037ZSTDLIB_API size_t ZSTD_nextSrcSizeToDecompress(ZSTD_DCtx* dctx);2038ZSTDLIB_API size_t ZSTD_decompressContinue(ZSTD_DCtx* dctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize);20392040/* misc */2041ZSTDLIB_API void ZSTD_copyDCtx(ZSTD_DCtx* dctx, const ZSTD_DCtx* preparedDCtx);2042typedef enum { ZSTDnit_frameHeader, ZSTDnit_blockHeader, ZSTDnit_block, ZSTDnit_lastBlock, ZSTDnit_checksum, ZSTDnit_skippableFrame } ZSTD_nextInputType_e;2043ZSTDLIB_API ZSTD_nextInputType_e ZSTD_nextInputType(ZSTD_DCtx* dctx);20442045204620472048/* ============================ */2049/** Block level API */2050/* ============================ */20512052/*!2053Block functions produce and decode raw zstd blocks, without frame metadata.2054Frame metadata cost is typically ~12 bytes, which can be non-negligible for very small blocks (< 100 bytes).2055But users will have to take in charge needed metadata to regenerate data, such as compressed and content sizes.20562057A few rules to respect :2058- Compressing and decompressing require a context structure2059+ Use ZSTD_createCCtx() and ZSTD_createDCtx()2060- It is necessary to init context before starting2061+ compression : any ZSTD_compressBegin*() variant, including with dictionary2062+ decompression : any ZSTD_decompressBegin*() variant, including with dictionary2063+ copyCCtx() and copyDCtx() can be used too2064- Block size is limited, it must be <= ZSTD_getBlockSize() <= ZSTD_BLOCKSIZE_MAX == 128 KB2065+ If input is larger than a block size, it's necessary to split input data into multiple blocks2066+ For inputs larger than a single block, consider using regular ZSTD_compress() instead.2067Frame metadata is not that costly, and quickly becomes negligible as source size grows larger than a block.2068- When a block is considered not compressible enough, ZSTD_compressBlock() result will be 0 (zero) !2069===> In which case, nothing is produced into `dst` !2070+ User __must__ test for such outcome and deal directly with uncompressed data2071+ A block cannot be declared incompressible if ZSTD_compressBlock() return value was != 0.2072Doing so would mess up with statistics history, leading to potential data corruption.2073+ ZSTD_decompressBlock() _doesn't accept uncompressed data as input_ !!2074+ In case of multiple successive blocks, should some of them be uncompressed,2075decoder must be informed of their existence in order to follow proper history.2076Use ZSTD_insertBlock() for such a case.2077*/20782079/*===== Raw zstd block functions =====*/2080ZSTDLIB_API size_t ZSTD_getBlockSize (const ZSTD_CCtx* cctx);2081ZSTDLIB_API size_t ZSTD_compressBlock (ZSTD_CCtx* cctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize);2082ZSTDLIB_API size_t ZSTD_decompressBlock(ZSTD_DCtx* dctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize);2083ZSTDLIB_API size_t ZSTD_insertBlock (ZSTD_DCtx* dctx, const void* blockStart, size_t blockSize); /**< insert uncompressed block into `dctx` history. Useful for multi-blocks decompression. */208420852086#endif /* ZSTD_H_ZSTD_STATIC_LINKING_ONLY */20872088#if defined (__cplusplus)2089}2090#endif209120922093