1 /* 2 * Copyright (c) 2016-present, Yann Collet, Facebook, Inc. 3 * All rights reserved. 4 * 5 * This source code is licensed under both the BSD-style license (found in the 6 * LICENSE file in the root directory of this source tree) and the GPLv2 (found 7 * in the COPYING file in the root directory of this source tree). 8 * You may select, at your option, one of the above-listed licenses. 9 */ 10 #if defined (__cplusplus) 11 extern "C" { 12 #endif 13 14 #ifndef ZSTD_H_235446 15 #define ZSTD_H_235446 16 17 /* ====== Dependency ======*/ 18 #include <stddef.h> /* size_t */ 19 20 21 /* ===== ZSTDLIB_API : control library symbols visibility ===== */ 22 #ifndef ZSTDLIB_VISIBILITY 23 # if defined(__GNUC__) && (__GNUC__ >= 4) 24 # define ZSTDLIB_VISIBILITY __attribute__ ((visibility ("default"))) 25 # else 26 # define ZSTDLIB_VISIBILITY 27 # endif 28 #endif 29 #if defined(ZSTD_DLL_EXPORT) && (ZSTD_DLL_EXPORT==1) 30 # define ZSTDLIB_API __declspec(dllexport) ZSTDLIB_VISIBILITY 31 #elif defined(ZSTD_DLL_IMPORT) && (ZSTD_DLL_IMPORT==1) 32 # 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.*/ 33 #else 34 # define ZSTDLIB_API ZSTDLIB_VISIBILITY 35 #endif 36 37 38 /******************************************************************************************************* 39 Introduction 40 41 zstd, short for Zstandard, is a fast lossless compression algorithm, 42 targeting real-time compression scenarios at zlib-level and better compression ratios. 43 The zstd compression library provides in-memory compression and decompression functions. 44 The library supports compression levels from 1 up to ZSTD_maxCLevel() which is currently 22. 45 Levels >= 20, labeled `--ultra`, should be used with caution, as they require more memory. 46 Compression can be done in: 47 - a single step (described as Simple API) 48 - a single step, reusing a context (described as Explicit memory management) 49 - unbounded multiple steps (described as Streaming compression) 50 The compression ratio achievable on small data can be highly improved using a dictionary in: 51 - a single step (described as Simple dictionary API) 52 - a single step, reusing a dictionary (described as Fast dictionary API) 53 54 Advanced experimental functions can be accessed using #define ZSTD_STATIC_LINKING_ONLY before including zstd.h. 55 Advanced experimental APIs shall never be used with a dynamic library. 56 They are not "stable", their definition may change in the future. Only static linking is allowed. 57 *********************************************************************************************************/ 58 59 /*------ Version ------*/ 60 #define ZSTD_VERSION_MAJOR 1 61 #define ZSTD_VERSION_MINOR 3 62 #define ZSTD_VERSION_RELEASE 2 63 64 #define ZSTD_VERSION_NUMBER (ZSTD_VERSION_MAJOR *100*100 + ZSTD_VERSION_MINOR *100 + ZSTD_VERSION_RELEASE) 65 ZSTDLIB_API unsigned ZSTD_versionNumber(void); /**< useful to check dll version */ 66 67 #define ZSTD_LIB_VERSION ZSTD_VERSION_MAJOR.ZSTD_VERSION_MINOR.ZSTD_VERSION_RELEASE 68 #define ZSTD_QUOTE(str) #str 69 #define ZSTD_EXPAND_AND_QUOTE(str) ZSTD_QUOTE(str) 70 #define ZSTD_VERSION_STRING ZSTD_EXPAND_AND_QUOTE(ZSTD_LIB_VERSION) 71 ZSTDLIB_API const char* ZSTD_versionString(void); /* v1.3.0 */ 72 73 74 /*************************************** 75 * Simple API 76 ***************************************/ 77 /*! ZSTD_compress() : 78 * Compresses `src` content as a single zstd compressed frame into already allocated `dst`. 79 * Hint : compression runs faster if `dstCapacity` >= `ZSTD_compressBound(srcSize)`. 80 * @return : compressed size written into `dst` (<= `dstCapacity), 81 * or an error code if it fails (which can be tested using ZSTD_isError()). */ 82 ZSTDLIB_API size_t ZSTD_compress( void* dst, size_t dstCapacity, 83 const void* src, size_t srcSize, 84 int compressionLevel); 85 86 /*! ZSTD_decompress() : 87 * `compressedSize` : must be the _exact_ size of some number of compressed and/or skippable frames. 88 * `dstCapacity` is an upper bound of originalSize to regenerate. 89 * If user cannot imply a maximum upper bound, it's better to use streaming mode to decompress data. 90 * @return : the number of bytes decompressed into `dst` (<= `dstCapacity`), 91 * or an errorCode if it fails (which can be tested using ZSTD_isError()). */ 92 ZSTDLIB_API size_t ZSTD_decompress( void* dst, size_t dstCapacity, 93 const void* src, size_t compressedSize); 94 95 /*! ZSTD_getFrameContentSize() : v1.3.0 96 * `src` should point to the start of a ZSTD encoded frame. 97 * `srcSize` must be at least as large as the frame header. 98 * hint : any size >= `ZSTD_frameHeaderSize_max` is large enough. 99 * @return : - decompressed size of the frame in `src`, if known 100 * - ZSTD_CONTENTSIZE_UNKNOWN if the size cannot be determined 101 * - ZSTD_CONTENTSIZE_ERROR if an error occurred (e.g. invalid magic number, srcSize too small) 102 * note 1 : a 0 return value means the frame is valid but "empty". 103 * note 2 : decompressed size is an optional field, it may not be present, typically in streaming mode. 104 * When `return==ZSTD_CONTENTSIZE_UNKNOWN`, data to decompress could be any size. 105 * In which case, it's necessary to use streaming mode to decompress data. 106 * Optionally, application can rely on some implicit limit, 107 * as ZSTD_decompress() only needs an upper bound of decompressed size. 108 * (For example, data could be necessarily cut into blocks <= 16 KB). 109 * note 3 : decompressed size is always present when compression is done with ZSTD_compress() 110 * note 4 : decompressed size can be very large (64-bits value), 111 * potentially larger than what local system can handle as a single memory segment. 112 * In which case, it's necessary to use streaming mode to decompress data. 113 * note 5 : If source is untrusted, decompressed size could be wrong or intentionally modified. 114 * Always ensure return value fits within application's authorized limits. 115 * Each application can set its own limits. 116 * note 6 : This function replaces ZSTD_getDecompressedSize() */ 117 #define ZSTD_CONTENTSIZE_UNKNOWN (0ULL - 1) 118 #define ZSTD_CONTENTSIZE_ERROR (0ULL - 2) 119 ZSTDLIB_API unsigned long long ZSTD_getFrameContentSize(const void *src, size_t srcSize); 120 121 /*! ZSTD_getDecompressedSize() : 122 * NOTE: This function is now obsolete, in favor of ZSTD_getFrameContentSize(). 123 * Both functions work the same way, 124 * but ZSTD_getDecompressedSize() blends 125 * "empty", "unknown" and "error" results in the same return value (0), 126 * while ZSTD_getFrameContentSize() distinguishes them. 127 * 128 * 'src' is the start of a zstd compressed frame. 129 * @return : content size to be decompressed, as a 64-bits value _if known and not empty_, 0 otherwise. */ 130 ZSTDLIB_API unsigned long long ZSTD_getDecompressedSize(const void* src, size_t srcSize); 131 132 133 /*====== Helper functions ======*/ 134 #define ZSTD_COMPRESSBOUND(srcSize) ((srcSize) + ((srcSize)>>8) + (((srcSize) < 128 KB) ? ((128 KB - (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 */ 135 ZSTDLIB_API size_t ZSTD_compressBound(size_t srcSize); /*!< maximum compressed size in worst case scenario */ 136 ZSTDLIB_API unsigned ZSTD_isError(size_t code); /*!< tells if a `size_t` function result is an error code */ 137 ZSTDLIB_API const char* ZSTD_getErrorName(size_t code); /*!< provides readable string from an error code */ 138 ZSTDLIB_API int ZSTD_maxCLevel(void); /*!< maximum compression level available */ 139 140 141 /*************************************** 142 * Explicit memory management 143 ***************************************/ 144 /*= Compression context 145 * When compressing many times, 146 * it is recommended to allocate a context just once, and re-use it for each successive compression operation. 147 * This will make workload friendlier for system's memory. 148 * Use one context per thread for parallel execution in multi-threaded environments. */ 149 typedef struct ZSTD_CCtx_s ZSTD_CCtx; 150 ZSTDLIB_API ZSTD_CCtx* ZSTD_createCCtx(void); 151 ZSTDLIB_API size_t ZSTD_freeCCtx(ZSTD_CCtx* cctx); 152 153 /*! ZSTD_compressCCtx() : 154 * Same as ZSTD_compress(), requires an allocated ZSTD_CCtx (see ZSTD_createCCtx()). */ 155 ZSTDLIB_API size_t ZSTD_compressCCtx(ZSTD_CCtx* ctx, 156 void* dst, size_t dstCapacity, 157 const void* src, size_t srcSize, 158 int compressionLevel); 159 160 /*= Decompression context 161 * When decompressing many times, 162 * it is recommended to allocate a context only once, 163 * and re-use it for each successive compression operation. 164 * This will make workload friendlier for system's memory. 165 * Use one context per thread for parallel execution. */ 166 typedef struct ZSTD_DCtx_s ZSTD_DCtx; 167 ZSTDLIB_API ZSTD_DCtx* ZSTD_createDCtx(void); 168 ZSTDLIB_API size_t ZSTD_freeDCtx(ZSTD_DCtx* dctx); 169 170 /*! ZSTD_decompressDCtx() : 171 * Same as ZSTD_decompress(), requires an allocated ZSTD_DCtx (see ZSTD_createDCtx()) */ 172 ZSTDLIB_API size_t ZSTD_decompressDCtx(ZSTD_DCtx* ctx, 173 void* dst, size_t dstCapacity, 174 const void* src, size_t srcSize); 175 176 177 /************************** 178 * Simple dictionary API 179 ***************************/ 180 /*! ZSTD_compress_usingDict() : 181 * Compression using a predefined Dictionary (see dictBuilder/zdict.h). 182 * Note : This function loads the dictionary, resulting in significant startup delay. 183 * Note : When `dict == NULL || dictSize < 8` no dictionary is used. */ 184 ZSTDLIB_API size_t ZSTD_compress_usingDict(ZSTD_CCtx* ctx, 185 void* dst, size_t dstCapacity, 186 const void* src, size_t srcSize, 187 const void* dict,size_t dictSize, 188 int compressionLevel); 189 190 /*! ZSTD_decompress_usingDict() : 191 * Decompression using a predefined Dictionary (see dictBuilder/zdict.h). 192 * Dictionary must be identical to the one used during compression. 193 * Note : This function loads the dictionary, resulting in significant startup delay. 194 * Note : When `dict == NULL || dictSize < 8` no dictionary is used. */ 195 ZSTDLIB_API size_t ZSTD_decompress_usingDict(ZSTD_DCtx* dctx, 196 void* dst, size_t dstCapacity, 197 const void* src, size_t srcSize, 198 const void* dict,size_t dictSize); 199 200 201 /********************************** 202 * Bulk processing dictionary API 203 *********************************/ 204 typedef struct ZSTD_CDict_s ZSTD_CDict; 205 206 /*! ZSTD_createCDict() : 207 * When compressing multiple messages / blocks with the same dictionary, it's recommended to load it just once. 208 * ZSTD_createCDict() will create a digested dictionary, ready to start future compression operations without startup delay. 209 * ZSTD_CDict can be created once and shared by multiple threads concurrently, since its usage is read-only. 210 * `dictBuffer` can be released after ZSTD_CDict creation, since its content is copied within CDict */ 211 ZSTDLIB_API ZSTD_CDict* ZSTD_createCDict(const void* dictBuffer, size_t dictSize, 212 int compressionLevel); 213 214 /*! ZSTD_freeCDict() : 215 * Function frees memory allocated by ZSTD_createCDict(). */ 216 ZSTDLIB_API size_t ZSTD_freeCDict(ZSTD_CDict* CDict); 217 218 /*! ZSTD_compress_usingCDict() : 219 * Compression using a digested Dictionary. 220 * Faster startup than ZSTD_compress_usingDict(), recommended when same dictionary is used multiple times. 221 * Note that compression level is decided during dictionary creation. 222 * Frame parameters are hardcoded (dictID=yes, contentSize=yes, checksum=no) */ 223 ZSTDLIB_API size_t ZSTD_compress_usingCDict(ZSTD_CCtx* cctx, 224 void* dst, size_t dstCapacity, 225 const void* src, size_t srcSize, 226 const ZSTD_CDict* cdict); 227 228 229 typedef struct ZSTD_DDict_s ZSTD_DDict; 230 231 /*! ZSTD_createDDict() : 232 * Create a digested dictionary, ready to start decompression operation without startup delay. 233 * dictBuffer can be released after DDict creation, as its content is copied inside DDict */ 234 ZSTDLIB_API ZSTD_DDict* ZSTD_createDDict(const void* dictBuffer, size_t dictSize); 235 236 /*! ZSTD_freeDDict() : 237 * Function frees memory allocated with ZSTD_createDDict() */ 238 ZSTDLIB_API size_t ZSTD_freeDDict(ZSTD_DDict* ddict); 239 240 /*! ZSTD_decompress_usingDDict() : 241 * Decompression using a digested Dictionary. 242 * Faster startup than ZSTD_decompress_usingDict(), recommended when same dictionary is used multiple times. */ 243 ZSTDLIB_API size_t ZSTD_decompress_usingDDict(ZSTD_DCtx* dctx, 244 void* dst, size_t dstCapacity, 245 const void* src, size_t srcSize, 246 const ZSTD_DDict* ddict); 247 248 249 /**************************** 250 * Streaming 251 ****************************/ 252 253 typedef struct ZSTD_inBuffer_s { 254 const void* src; /**< start of input buffer */ 255 size_t size; /**< size of input buffer */ 256 size_t pos; /**< position where reading stopped. Will be updated. Necessarily 0 <= pos <= size */ 257 } ZSTD_inBuffer; 258 259 typedef struct ZSTD_outBuffer_s { 260 void* dst; /**< start of output buffer */ 261 size_t size; /**< size of output buffer */ 262 size_t pos; /**< position where writing stopped. Will be updated. Necessarily 0 <= pos <= size */ 263 } ZSTD_outBuffer; 264 265 266 267 /*-*********************************************************************** 268 * Streaming compression - HowTo 269 * 270 * A ZSTD_CStream object is required to track streaming operation. 271 * Use ZSTD_createCStream() and ZSTD_freeCStream() to create/release resources. 272 * ZSTD_CStream objects can be reused multiple times on consecutive compression operations. 273 * It is recommended to re-use ZSTD_CStream in situations where many streaming operations will be achieved consecutively, 274 * since it will play nicer with system's memory, by re-using already allocated memory. 275 * Use one separate ZSTD_CStream per thread for parallel execution. 276 * 277 * Start a new compression by initializing ZSTD_CStream. 278 * Use ZSTD_initCStream() to start a new compression operation. 279 * Use ZSTD_initCStream_usingDict() or ZSTD_initCStream_usingCDict() for a compression which requires a dictionary (experimental section) 280 * 281 * Use ZSTD_compressStream() repetitively to consume input stream. 282 * The function will automatically update both `pos` fields. 283 * Note that it may not consume the entire input, in which case `pos < size`, 284 * and it's up to the caller to present again remaining data. 285 * @return : a size hint, preferred nb of bytes to use as input for next function call 286 * or an error code, which can be tested using ZSTD_isError(). 287 * Note 1 : it's just a hint, to help latency a little, any other value will work fine. 288 * Note 2 : size hint is guaranteed to be <= ZSTD_CStreamInSize() 289 * 290 * At any moment, it's possible to flush whatever data remains within internal buffer, using ZSTD_flushStream(). 291 * `output->pos` will be updated. 292 * Note that some content might still be left within internal buffer if `output->size` is too small. 293 * @return : nb of bytes still present within internal buffer (0 if it's empty) 294 * or an error code, which can be tested using ZSTD_isError(). 295 * 296 * ZSTD_endStream() instructs to finish a frame. 297 * It will perform a flush and write frame epilogue. 298 * The epilogue is required for decoders to consider a frame completed. 299 * ZSTD_endStream() may not be able to flush full data if `output->size` is too small. 300 * In which case, call again ZSTD_endStream() to complete the flush. 301 * @return : 0 if frame fully completed and fully flushed, 302 or >0 if some data is still present within internal buffer 303 (value is minimum size estimation for remaining data to flush, but it could be more) 304 * or an error code, which can be tested using ZSTD_isError(). 305 * 306 * *******************************************************************/ 307 308 typedef ZSTD_CCtx ZSTD_CStream; /**< CCtx and CStream are now effectively same object (>= v1.3.0) */ 309 /* Continue to distinguish them for compatibility with versions <= v1.2.0 */ 310 /*===== ZSTD_CStream management functions =====*/ 311 ZSTDLIB_API ZSTD_CStream* ZSTD_createCStream(void); 312 ZSTDLIB_API size_t ZSTD_freeCStream(ZSTD_CStream* zcs); 313 314 /*===== Streaming compression functions =====*/ 315 ZSTDLIB_API size_t ZSTD_initCStream(ZSTD_CStream* zcs, int compressionLevel); 316 ZSTDLIB_API size_t ZSTD_compressStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output, ZSTD_inBuffer* input); 317 ZSTDLIB_API size_t ZSTD_flushStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output); 318 ZSTDLIB_API size_t ZSTD_endStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output); 319 320 ZSTDLIB_API size_t ZSTD_CStreamInSize(void); /**< recommended size for input buffer */ 321 ZSTDLIB_API size_t ZSTD_CStreamOutSize(void); /**< recommended size for output buffer. Guarantee to successfully flush at least one complete compressed block in all circumstances. */ 322 323 324 325 /*-*************************************************************************** 326 * Streaming decompression - HowTo 327 * 328 * A ZSTD_DStream object is required to track streaming operations. 329 * Use ZSTD_createDStream() and ZSTD_freeDStream() to create/release resources. 330 * ZSTD_DStream objects can be re-used multiple times. 331 * 332 * Use ZSTD_initDStream() to start a new decompression operation, 333 * or ZSTD_initDStream_usingDict() if decompression requires a dictionary. 334 * @return : recommended first input size 335 * 336 * Use ZSTD_decompressStream() repetitively to consume your input. 337 * The function will update both `pos` fields. 338 * If `input.pos < input.size`, some input has not been consumed. 339 * It's up to the caller to present again remaining data. 340 * If `output.pos < output.size`, decoder has flushed everything it could. 341 * @return : 0 when a frame is completely decoded and fully flushed, 342 * an error code, which can be tested using ZSTD_isError(), 343 * any other value > 0, which means there is still some decoding to do to complete current frame. 344 * The return value is a suggested next input size (a hint to improve latency) that will never load more than the current frame. 345 * *******************************************************************************/ 346 347 typedef ZSTD_DCtx ZSTD_DStream; /**< DCtx and DStream are now effectively same object (>= v1.3.0) */ 348 /* Continue to distinguish them for compatibility with versions <= v1.2.0 */ 349 /*===== ZSTD_DStream management functions =====*/ 350 ZSTDLIB_API ZSTD_DStream* ZSTD_createDStream(void); 351 ZSTDLIB_API size_t ZSTD_freeDStream(ZSTD_DStream* zds); 352 353 /*===== Streaming decompression functions =====*/ 354 ZSTDLIB_API size_t ZSTD_initDStream(ZSTD_DStream* zds); 355 ZSTDLIB_API size_t ZSTD_decompressStream(ZSTD_DStream* zds, ZSTD_outBuffer* output, ZSTD_inBuffer* input); 356 357 ZSTDLIB_API size_t ZSTD_DStreamInSize(void); /*!< recommended size for input buffer */ 358 ZSTDLIB_API size_t ZSTD_DStreamOutSize(void); /*!< recommended size for output buffer. Guarantee to successfully flush at least one complete block in all circumstances. */ 359 360 #endif /* ZSTD_H_235446 */ 361 362 363 364 /**************************************************************************************** 365 * START OF ADVANCED AND EXPERIMENTAL FUNCTIONS 366 * The definitions in this section are considered experimental. 367 * They should never be used with a dynamic library, as prototypes may change in the future. 368 * They are provided for advanced scenarios. 369 * Use them only in association with static linking. 370 * ***************************************************************************************/ 371 372 #if defined(ZSTD_STATIC_LINKING_ONLY) && !defined(ZSTD_H_ZSTD_STATIC_LINKING_ONLY) 373 #define ZSTD_H_ZSTD_STATIC_LINKING_ONLY 374 375 /* --- Constants ---*/ 376 #define ZSTD_MAGICNUMBER 0xFD2FB528 /* >= v0.8.0 */ 377 #define ZSTD_MAGIC_SKIPPABLE_START 0x184D2A50U 378 #define ZSTD_MAGIC_DICTIONARY 0xEC30A437 /* v0.7+ */ 379 380 #define ZSTD_WINDOWLOG_MAX_32 30 381 #define ZSTD_WINDOWLOG_MAX_64 31 382 #define ZSTD_WINDOWLOG_MAX ((unsigned)(sizeof(size_t) == 4 ? ZSTD_WINDOWLOG_MAX_32 : ZSTD_WINDOWLOG_MAX_64)) 383 #define ZSTD_WINDOWLOG_MIN 10 384 #define ZSTD_HASHLOG_MAX MIN(ZSTD_WINDOWLOG_MAX, 30) 385 #define ZSTD_HASHLOG_MIN 6 386 #define ZSTD_CHAINLOG_MAX MIN(ZSTD_WINDOWLOG_MAX+1, 30) 387 #define ZSTD_CHAINLOG_MIN ZSTD_HASHLOG_MIN 388 #define ZSTD_HASHLOG3_MAX 17 389 #define ZSTD_SEARCHLOG_MAX (ZSTD_WINDOWLOG_MAX-1) 390 #define ZSTD_SEARCHLOG_MIN 1 391 #define ZSTD_SEARCHLENGTH_MAX 7 /* only for ZSTD_fast, other strategies are limited to 6 */ 392 #define ZSTD_SEARCHLENGTH_MIN 3 /* only for ZSTD_btopt, other strategies are limited to 4 */ 393 #define ZSTD_TARGETLENGTH_MIN 4 /* only useful for btopt */ 394 #define ZSTD_TARGETLENGTH_MAX 999 /* only useful for btopt */ 395 #define ZSTD_LDM_MINMATCH_MIN 4 396 #define ZSTD_LDM_MINMATCH_MAX 4096 397 #define ZSTD_LDM_BUCKETSIZELOG_MAX 8 398 399 #define ZSTD_FRAMEHEADERSIZE_PREFIX 5 /* minimum input size to know frame header size */ 400 #define ZSTD_FRAMEHEADERSIZE_MIN 6 401 #define ZSTD_FRAMEHEADERSIZE_MAX 18 /* for static allocation */ 402 static const size_t ZSTD_frameHeaderSize_prefix = ZSTD_FRAMEHEADERSIZE_PREFIX; 403 static const size_t ZSTD_frameHeaderSize_min = ZSTD_FRAMEHEADERSIZE_MIN; 404 static const size_t ZSTD_frameHeaderSize_max = ZSTD_FRAMEHEADERSIZE_MAX; 405 static const size_t ZSTD_skippableHeaderSize = 8; /* magic number + skippable frame length */ 406 407 408 /*--- Advanced types ---*/ 409 typedef enum { ZSTD_fast=1, ZSTD_dfast, ZSTD_greedy, ZSTD_lazy, ZSTD_lazy2, 410 ZSTD_btlazy2, ZSTD_btopt, ZSTD_btultra } ZSTD_strategy; /* from faster to stronger */ 411 412 typedef struct { 413 unsigned windowLog; /**< largest match distance : larger == more compression, more memory needed during decompression */ 414 unsigned chainLog; /**< fully searched segment : larger == more compression, slower, more memory (useless for fast) */ 415 unsigned hashLog; /**< dispatch table : larger == faster, more memory */ 416 unsigned searchLog; /**< nb of searches : larger == more compression, slower */ 417 unsigned searchLength; /**< match length searched : larger == faster decompression, sometimes less compression */ 418 unsigned targetLength; /**< acceptable match size for optimal parser (only) : larger == more compression, slower */ 419 ZSTD_strategy strategy; 420 } ZSTD_compressionParameters; 421 422 typedef struct { 423 unsigned contentSizeFlag; /**< 1: content size will be in frame header (when known) */ 424 unsigned checksumFlag; /**< 1: generate a 32-bits checksum at end of frame, for error detection */ 425 unsigned noDictIDFlag; /**< 1: no dictID will be saved into frame header (if dictionary compression) */ 426 } ZSTD_frameParameters; 427 428 typedef struct { 429 ZSTD_compressionParameters cParams; 430 ZSTD_frameParameters fParams; 431 } ZSTD_parameters; 432 433 typedef struct ZSTD_CCtx_params_s ZSTD_CCtx_params; 434 435 /*= Custom memory allocation functions */ 436 typedef void* (*ZSTD_allocFunction) (void* opaque, size_t size); 437 typedef void (*ZSTD_freeFunction) (void* opaque, void* address); 438 typedef struct { ZSTD_allocFunction customAlloc; ZSTD_freeFunction customFree; void* opaque; } ZSTD_customMem; 439 /* use this constant to defer to stdlib's functions */ 440 static const ZSTD_customMem ZSTD_defaultCMem = { NULL, NULL, NULL }; 441 442 443 /*************************************** 444 * Frame size functions 445 ***************************************/ 446 447 /*! ZSTD_findFrameCompressedSize() : 448 * `src` should point to the start of a ZSTD encoded frame or skippable frame 449 * `srcSize` must be at least as large as the frame 450 * @return : the compressed size of the first frame starting at `src`, 451 * suitable to pass to `ZSTD_decompress` or similar, 452 * or an error code if input is invalid */ 453 ZSTDLIB_API size_t ZSTD_findFrameCompressedSize(const void* src, size_t srcSize); 454 455 /*! ZSTD_findDecompressedSize() : 456 * `src` should point the start of a series of ZSTD encoded and/or skippable frames 457 * `srcSize` must be the _exact_ size of this series 458 * (i.e. there should be a frame boundary exactly at `srcSize` bytes after `src`) 459 * @return : - decompressed size of all data in all successive frames 460 * - if the decompressed size cannot be determined: ZSTD_CONTENTSIZE_UNKNOWN 461 * - if an error occurred: ZSTD_CONTENTSIZE_ERROR 462 * 463 * note 1 : decompressed size is an optional field, that may not be present, especially in streaming mode. 464 * When `return==ZSTD_CONTENTSIZE_UNKNOWN`, data to decompress could be any size. 465 * In which case, it's necessary to use streaming mode to decompress data. 466 * note 2 : decompressed size is always present when compression is done with ZSTD_compress() 467 * note 3 : decompressed size can be very large (64-bits value), 468 * potentially larger than what local system can handle as a single memory segment. 469 * In which case, it's necessary to use streaming mode to decompress data. 470 * note 4 : If source is untrusted, decompressed size could be wrong or intentionally modified. 471 * Always ensure result fits within application's authorized limits. 472 * Each application can set its own limits. 473 * note 5 : ZSTD_findDecompressedSize handles multiple frames, and so it must traverse the input to 474 * read each contained frame header. This is fast as most of the data is skipped, 475 * however it does mean that all frame data must be present and valid. */ 476 ZSTDLIB_API unsigned long long ZSTD_findDecompressedSize(const void* src, size_t srcSize); 477 478 /*! ZSTD_frameHeaderSize() : 479 * `src` should point to the start of a ZSTD frame 480 * `srcSize` must be >= ZSTD_frameHeaderSize_prefix. 481 * @return : size of the Frame Header */ 482 ZSTDLIB_API size_t ZSTD_frameHeaderSize(const void* src, size_t srcSize); 483 484 485 /*************************************** 486 * Context memory usage 487 ***************************************/ 488 489 /*! ZSTD_sizeof_*() : 490 * These functions give the current memory usage of selected object. 491 * Object memory usage can evolve when re-used multiple times. */ 492 ZSTDLIB_API size_t ZSTD_sizeof_CCtx(const ZSTD_CCtx* cctx); 493 ZSTDLIB_API size_t ZSTD_sizeof_DCtx(const ZSTD_DCtx* dctx); 494 ZSTDLIB_API size_t ZSTD_sizeof_CStream(const ZSTD_CStream* zcs); 495 ZSTDLIB_API size_t ZSTD_sizeof_DStream(const ZSTD_DStream* zds); 496 ZSTDLIB_API size_t ZSTD_sizeof_CDict(const ZSTD_CDict* cdict); 497 ZSTDLIB_API size_t ZSTD_sizeof_DDict(const ZSTD_DDict* ddict); 498 499 /*! ZSTD_estimate*() : 500 * These functions make it possible to estimate memory usage 501 * of a future {D,C}Ctx, before its creation. 502 * ZSTD_estimateCCtxSize() will provide a budget large enough for any compression level up to selected one. 503 * It will also consider src size to be arbitrarily "large", which is worst case. 504 * If srcSize is known to always be small, ZSTD_estimateCCtxSize_usingCParams() can provide a tighter estimation. 505 * ZSTD_estimateCCtxSize_usingCParams() can be used in tandem with ZSTD_getCParams() to create cParams from compressionLevel. 506 * ZSTD_estimateCCtxSize_usingCCtxParams() can be used in tandem with ZSTD_CCtxParam_setParameter(). Only single-threaded compression is supported. This function will return an error code if ZSTD_p_nbThreads is > 1. 507 * Note : CCtx estimation is only correct for single-threaded compression */ 508 ZSTDLIB_API size_t ZSTD_estimateCCtxSize(int compressionLevel); 509 ZSTDLIB_API size_t ZSTD_estimateCCtxSize_usingCParams(ZSTD_compressionParameters cParams); 510 ZSTDLIB_API size_t ZSTD_estimateCCtxSize_usingCCtxParams(const ZSTD_CCtx_params* params); 511 ZSTDLIB_API size_t ZSTD_estimateDCtxSize(void); 512 513 /*! ZSTD_estimateCStreamSize() : 514 * ZSTD_estimateCStreamSize() will provide a budget large enough for any compression level up to selected one. 515 * It will also consider src size to be arbitrarily "large", which is worst case. 516 * If srcSize is known to always be small, ZSTD_estimateCStreamSize_usingCParams() can provide a tighter estimation. 517 * ZSTD_estimateCStreamSize_usingCParams() can be used in tandem with ZSTD_getCParams() to create cParams from compressionLevel. 518 * ZSTD_estimateCStreamSize_usingCCtxParams() can be used in tandem with ZSTD_CCtxParam_setParameter(). Only single-threaded compression is supported. This function will return an error code if ZSTD_p_nbThreads is set to a value > 1. 519 * Note : CStream estimation is only correct for single-threaded compression. 520 * ZSTD_DStream memory budget depends on window Size. 521 * This information can be passed manually, using ZSTD_estimateDStreamSize, 522 * or deducted from a valid frame Header, using ZSTD_estimateDStreamSize_fromFrame(); 523 * Note : if streaming is init with function ZSTD_init?Stream_usingDict(), 524 * an internal ?Dict will be created, which additional size is not estimated here. 525 * In this case, get total size by adding ZSTD_estimate?DictSize */ 526 ZSTDLIB_API size_t ZSTD_estimateCStreamSize(int compressionLevel); 527 ZSTDLIB_API size_t ZSTD_estimateCStreamSize_usingCParams(ZSTD_compressionParameters cParams); 528 ZSTDLIB_API size_t ZSTD_estimateCStreamSize_usingCCtxParams(const ZSTD_CCtx_params* params); 529 ZSTDLIB_API size_t ZSTD_estimateDStreamSize(size_t windowSize); 530 ZSTDLIB_API size_t ZSTD_estimateDStreamSize_fromFrame(const void* src, size_t srcSize); 531 532 typedef enum { 533 ZSTD_dlm_byCopy = 0, /**< Copy dictionary content internally */ 534 ZSTD_dlm_byRef, /**< Reference dictionary content -- the dictionary buffer must outlive its users. */ 535 } ZSTD_dictLoadMethod_e; 536 537 /*! ZSTD_estimate?DictSize() : 538 * ZSTD_estimateCDictSize() will bet that src size is relatively "small", and content is copied, like ZSTD_createCDict(). 539 * ZSTD_estimateCStreamSize_advanced_usingCParams() makes it possible to control precisely compression parameters, like ZSTD_createCDict_advanced(). 540 * Note : dictionary created by reference using ZSTD_dlm_byRef are smaller 541 */ 542 ZSTDLIB_API size_t ZSTD_estimateCDictSize(size_t dictSize, int compressionLevel); 543 ZSTDLIB_API size_t ZSTD_estimateCDictSize_advanced(size_t dictSize, ZSTD_compressionParameters cParams, ZSTD_dictLoadMethod_e dictLoadMethod); 544 ZSTDLIB_API size_t ZSTD_estimateDDictSize(size_t dictSize, ZSTD_dictLoadMethod_e dictLoadMethod); 545 546 547 /*************************************** 548 * Advanced compression functions 549 ***************************************/ 550 /*! ZSTD_createCCtx_advanced() : 551 * Create a ZSTD compression context using external alloc and free functions */ 552 ZSTDLIB_API ZSTD_CCtx* ZSTD_createCCtx_advanced(ZSTD_customMem customMem); 553 554 /*! ZSTD_initStaticCCtx() : initialize a fixed-size zstd compression context 555 * workspace: The memory area to emplace the context into. 556 * Provided pointer must 8-bytes aligned. 557 * It must outlive context usage. 558 * workspaceSize: Use ZSTD_estimateCCtxSize() or ZSTD_estimateCStreamSize() 559 * to determine how large workspace must be to support scenario. 560 * @return : pointer to ZSTD_CCtx*, or NULL if error (size too small) 561 * Note : zstd will never resize nor malloc() when using a static cctx. 562 * If it needs more memory than available, it will simply error out. 563 * Note 2 : there is no corresponding "free" function. 564 * Since workspace was allocated externally, it must be freed externally too. 565 * Limitation 1 : currently not compatible with internal CDict creation, such as 566 * ZSTD_CCtx_loadDictionary() or ZSTD_initCStream_usingDict(). 567 * Limitation 2 : currently not compatible with multi-threading 568 */ 569 ZSTDLIB_API ZSTD_CCtx* ZSTD_initStaticCCtx(void* workspace, size_t workspaceSize); 570 571 572 /*! ZSTD_createCDict_byReference() : 573 * Create a digested dictionary for compression 574 * Dictionary content is simply referenced, and therefore stays in dictBuffer. 575 * It is important that dictBuffer outlives CDict, it must remain read accessible throughout the lifetime of CDict */ 576 ZSTDLIB_API ZSTD_CDict* ZSTD_createCDict_byReference(const void* dictBuffer, size_t dictSize, int compressionLevel); 577 578 typedef enum { ZSTD_dm_auto=0, /* dictionary is "full" if it starts with ZSTD_MAGIC_DICTIONARY, otherwise it is "rawContent" */ 579 ZSTD_dm_rawContent, /* ensures dictionary is always loaded as rawContent, even if it starts with ZSTD_MAGIC_DICTIONARY */ 580 ZSTD_dm_fullDict /* refuses to load a dictionary if it does not respect Zstandard's specification */ 581 } ZSTD_dictMode_e; 582 /*! ZSTD_createCDict_advanced() : 583 * Create a ZSTD_CDict using external alloc and free, and customized compression parameters */ 584 ZSTDLIB_API ZSTD_CDict* ZSTD_createCDict_advanced(const void* dict, size_t dictSize, 585 ZSTD_dictLoadMethod_e dictLoadMethod, 586 ZSTD_dictMode_e dictMode, 587 ZSTD_compressionParameters cParams, 588 ZSTD_customMem customMem); 589 590 /*! ZSTD_initStaticCDict_advanced() : 591 * Generate a digested dictionary in provided memory area. 592 * workspace: The memory area to emplace the dictionary into. 593 * Provided pointer must 8-bytes aligned. 594 * It must outlive dictionary usage. 595 * workspaceSize: Use ZSTD_estimateCDictSize() 596 * to determine how large workspace must be. 597 * cParams : use ZSTD_getCParams() to transform a compression level 598 * into its relevants cParams. 599 * @return : pointer to ZSTD_CDict*, or NULL if error (size too small) 600 * Note : there is no corresponding "free" function. 601 * Since workspace was allocated externally, it must be freed externally. 602 */ 603 ZSTDLIB_API ZSTD_CDict* ZSTD_initStaticCDict( 604 void* workspace, size_t workspaceSize, 605 const void* dict, size_t dictSize, 606 ZSTD_dictLoadMethod_e dictLoadMethod, ZSTD_dictMode_e dictMode, 607 ZSTD_compressionParameters cParams); 608 609 /*! ZSTD_getCParams() : 610 * @return ZSTD_compressionParameters structure for a selected compression level and estimated srcSize. 611 * `estimatedSrcSize` value is optional, select 0 if not known */ 612 ZSTDLIB_API ZSTD_compressionParameters ZSTD_getCParams(int compressionLevel, unsigned long long estimatedSrcSize, size_t dictSize); 613 614 /*! ZSTD_getParams() : 615 * same as ZSTD_getCParams(), but @return a full `ZSTD_parameters` object instead of sub-component `ZSTD_compressionParameters`. 616 * All fields of `ZSTD_frameParameters` are set to default (0) */ 617 ZSTDLIB_API ZSTD_parameters ZSTD_getParams(int compressionLevel, unsigned long long estimatedSrcSize, size_t dictSize); 618 619 /*! ZSTD_checkCParams() : 620 * Ensure param values remain within authorized range */ 621 ZSTDLIB_API size_t ZSTD_checkCParams(ZSTD_compressionParameters params); 622 623 /*! ZSTD_adjustCParams() : 624 * optimize params for a given `srcSize` and `dictSize`. 625 * both values are optional, select `0` if unknown. */ 626 ZSTDLIB_API ZSTD_compressionParameters ZSTD_adjustCParams(ZSTD_compressionParameters cPar, unsigned long long srcSize, size_t dictSize); 627 628 /*! ZSTD_compress_advanced() : 629 * Same as ZSTD_compress_usingDict(), with fine-tune control over each compression parameter */ 630 ZSTDLIB_API size_t ZSTD_compress_advanced (ZSTD_CCtx* cctx, 631 void* dst, size_t dstCapacity, 632 const void* src, size_t srcSize, 633 const void* dict,size_t dictSize, 634 ZSTD_parameters params); 635 636 /*! ZSTD_compress_usingCDict_advanced() : 637 * Same as ZSTD_compress_usingCDict(), with fine-tune control over frame parameters */ 638 ZSTDLIB_API size_t ZSTD_compress_usingCDict_advanced(ZSTD_CCtx* cctx, 639 void* dst, size_t dstCapacity, 640 const void* src, size_t srcSize, 641 const ZSTD_CDict* cdict, ZSTD_frameParameters fParams); 642 643 644 /*--- Advanced decompression functions ---*/ 645 646 /*! ZSTD_isFrame() : 647 * Tells if the content of `buffer` starts with a valid Frame Identifier. 648 * Note : Frame Identifier is 4 bytes. If `size < 4`, @return will always be 0. 649 * Note 2 : Legacy Frame Identifiers are considered valid only if Legacy Support is enabled. 650 * Note 3 : Skippable Frame Identifiers are considered valid. */ 651 ZSTDLIB_API unsigned ZSTD_isFrame(const void* buffer, size_t size); 652 653 /*! ZSTD_createDCtx_advanced() : 654 * Create a ZSTD decompression context using external alloc and free functions */ 655 ZSTDLIB_API ZSTD_DCtx* ZSTD_createDCtx_advanced(ZSTD_customMem customMem); 656 657 /*! ZSTD_initStaticDCtx() : initialize a fixed-size zstd decompression context 658 * workspace: The memory area to emplace the context into. 659 * Provided pointer must 8-bytes aligned. 660 * It must outlive context usage. 661 * workspaceSize: Use ZSTD_estimateDCtxSize() or ZSTD_estimateDStreamSize() 662 * to determine how large workspace must be to support scenario. 663 * @return : pointer to ZSTD_DCtx*, or NULL if error (size too small) 664 * Note : zstd will never resize nor malloc() when using a static dctx. 665 * If it needs more memory than available, it will simply error out. 666 * Note 2 : static dctx is incompatible with legacy support 667 * Note 3 : there is no corresponding "free" function. 668 * Since workspace was allocated externally, it must be freed externally. 669 * Limitation : currently not compatible with internal DDict creation, 670 * such as ZSTD_initDStream_usingDict(). 671 */ 672 ZSTDLIB_API ZSTD_DCtx* ZSTD_initStaticDCtx(void* workspace, size_t workspaceSize); 673 674 /*! ZSTD_createDDict_byReference() : 675 * Create a digested dictionary, ready to start decompression operation without startup delay. 676 * Dictionary content is referenced, and therefore stays in dictBuffer. 677 * It is important that dictBuffer outlives DDict, 678 * it must remain read accessible throughout the lifetime of DDict */ 679 ZSTDLIB_API ZSTD_DDict* ZSTD_createDDict_byReference(const void* dictBuffer, size_t dictSize); 680 681 /*! ZSTD_createDDict_advanced() : 682 * Create a ZSTD_DDict using external alloc and free, optionally by reference */ 683 ZSTDLIB_API ZSTD_DDict* ZSTD_createDDict_advanced(const void* dict, size_t dictSize, 684 ZSTD_dictLoadMethod_e dictLoadMethod, 685 ZSTD_customMem customMem); 686 687 /*! ZSTD_initStaticDDict() : 688 * Generate a digested dictionary in provided memory area. 689 * workspace: The memory area to emplace the dictionary into. 690 * Provided pointer must 8-bytes aligned. 691 * It must outlive dictionary usage. 692 * workspaceSize: Use ZSTD_estimateDDictSize() 693 * to determine how large workspace must be. 694 * @return : pointer to ZSTD_DDict*, or NULL if error (size too small) 695 * Note : there is no corresponding "free" function. 696 * Since workspace was allocated externally, it must be freed externally. 697 */ 698 ZSTDLIB_API ZSTD_DDict* ZSTD_initStaticDDict(void* workspace, size_t workspaceSize, 699 const void* dict, size_t dictSize, 700 ZSTD_dictLoadMethod_e dictLoadMethod); 701 702 /*! ZSTD_getDictID_fromDict() : 703 * Provides the dictID stored within dictionary. 704 * if @return == 0, the dictionary is not conformant with Zstandard specification. 705 * It can still be loaded, but as a content-only dictionary. */ 706 ZSTDLIB_API unsigned ZSTD_getDictID_fromDict(const void* dict, size_t dictSize); 707 708 /*! ZSTD_getDictID_fromDDict() : 709 * Provides the dictID of the dictionary loaded into `ddict`. 710 * If @return == 0, the dictionary is not conformant to Zstandard specification, or empty. 711 * Non-conformant dictionaries can still be loaded, but as content-only dictionaries. */ 712 ZSTDLIB_API unsigned ZSTD_getDictID_fromDDict(const ZSTD_DDict* ddict); 713 714 /*! ZSTD_getDictID_fromFrame() : 715 * Provides the dictID required to decompressed the frame stored within `src`. 716 * If @return == 0, the dictID could not be decoded. 717 * This could for one of the following reasons : 718 * - The frame does not require a dictionary to be decoded (most common case). 719 * - The frame was built with dictID intentionally removed. Whatever dictionary is necessary is a hidden information. 720 * Note : this use case also happens when using a non-conformant dictionary. 721 * - `srcSize` is too small, and as a result, the frame header could not be decoded (only possible if `srcSize < ZSTD_FRAMEHEADERSIZE_MAX`). 722 * - This is not a Zstandard frame. 723 * When identifying the exact failure cause, it's possible to use ZSTD_getFrameHeader(), which will provide a more precise error code. */ 724 ZSTDLIB_API unsigned ZSTD_getDictID_fromFrame(const void* src, size_t srcSize); 725 726 727 /******************************************************************** 728 * Advanced streaming functions 729 ********************************************************************/ 730 731 /*===== Advanced Streaming compression functions =====*/ 732 ZSTDLIB_API ZSTD_CStream* ZSTD_createCStream_advanced(ZSTD_customMem customMem); 733 ZSTDLIB_API ZSTD_CStream* ZSTD_initStaticCStream(void* workspace, size_t workspaceSize); /**< same as ZSTD_initStaticCCtx() */ 734 ZSTDLIB_API size_t ZSTD_initCStream_srcSize(ZSTD_CStream* zcs, int compressionLevel, unsigned long long pledgedSrcSize); /**< pledgedSrcSize must be correct, a size of 0 means unknown. for a frame size of 0 use initCStream_advanced */ 735 ZSTDLIB_API size_t ZSTD_initCStream_usingDict(ZSTD_CStream* zcs, const void* dict, size_t dictSize, int compressionLevel); /**< creates of an internal CDict (incompatible with static CCtx), except if dict == NULL or dictSize < 8, in which case no dict is used. Note: dict is loaded with ZSTD_dm_auto (treated as a full zstd dictionary if it begins with ZSTD_MAGIC_DICTIONARY, else as raw content) and ZSTD_dlm_byCopy.*/ 736 ZSTDLIB_API size_t ZSTD_initCStream_advanced(ZSTD_CStream* zcs, const void* dict, size_t dictSize, 737 ZSTD_parameters params, unsigned long long pledgedSrcSize); /**< pledgedSrcSize is optional and can be 0 (meaning unknown). note: if the contentSizeFlag is set, pledgedSrcSize == 0 means the source size is actually 0. dict is loaded with ZSTD_dm_auto and ZSTD_dlm_byCopy. */ 738 ZSTDLIB_API size_t ZSTD_initCStream_usingCDict(ZSTD_CStream* zcs, const ZSTD_CDict* cdict); /**< note : cdict will just be referenced, and must outlive compression session */ 739 ZSTDLIB_API size_t ZSTD_initCStream_usingCDict_advanced(ZSTD_CStream* zcs, const ZSTD_CDict* cdict, ZSTD_frameParameters fParams, unsigned long long pledgedSrcSize); /**< same as ZSTD_initCStream_usingCDict(), with control over frame parameters */ 740 741 /*! ZSTD_resetCStream() : 742 * start a new compression job, using same parameters from previous job. 743 * This is typically useful to skip dictionary loading stage, since it will re-use it in-place.. 744 * Note that zcs must be init at least once before using ZSTD_resetCStream(). 745 * pledgedSrcSize==0 means "srcSize unknown". 746 * If pledgedSrcSize > 0, its value must be correct, as it will be written in header, and controlled at the end. 747 * @return : 0, or an error code (which can be tested using ZSTD_isError()) */ 748 ZSTDLIB_API size_t ZSTD_resetCStream(ZSTD_CStream* zcs, unsigned long long pledgedSrcSize); 749 750 751 /*===== Advanced Streaming decompression functions =====*/ 752 ZSTDLIB_API ZSTD_DStream* ZSTD_createDStream_advanced(ZSTD_customMem customMem); 753 ZSTDLIB_API ZSTD_DStream* ZSTD_initStaticDStream(void* workspace, size_t workspaceSize); /**< same as ZSTD_initStaticDCtx() */ 754 typedef enum { DStream_p_maxWindowSize } ZSTD_DStreamParameter_e; 755 ZSTDLIB_API size_t ZSTD_setDStreamParameter(ZSTD_DStream* zds, ZSTD_DStreamParameter_e paramType, unsigned paramValue); /* obsolete : this API will be removed in a future version */ 756 ZSTDLIB_API size_t ZSTD_initDStream_usingDict(ZSTD_DStream* zds, const void* dict, size_t dictSize); /**< note: no dictionary will be used if dict == NULL or dictSize < 8 */ 757 ZSTDLIB_API size_t ZSTD_initDStream_usingDDict(ZSTD_DStream* zds, const ZSTD_DDict* ddict); /**< note : ddict is referenced, it must outlive decompression session */ 758 ZSTDLIB_API size_t ZSTD_resetDStream(ZSTD_DStream* zds); /**< re-use decompression parameters from previous init; saves dictionary loading */ 759 760 761 /********************************************************************* 762 * Buffer-less and synchronous inner streaming functions 763 * 764 * This is an advanced API, giving full control over buffer management, for users which need direct control over memory. 765 * But it's also a complex one, with several restrictions, documented below. 766 * Prefer normal streaming API for an easier experience. 767 ********************************************************************* */ 768 769 /** 770 Buffer-less streaming compression (synchronous mode) 771 772 A ZSTD_CCtx object is required to track streaming operations. 773 Use ZSTD_createCCtx() / ZSTD_freeCCtx() to manage resource. 774 ZSTD_CCtx object can be re-used multiple times within successive compression operations. 775 776 Start by initializing a context. 777 Use ZSTD_compressBegin(), or ZSTD_compressBegin_usingDict() for dictionary compression, 778 or ZSTD_compressBegin_advanced(), for finer parameter control. 779 It's also possible to duplicate a reference context which has already been initialized, using ZSTD_copyCCtx() 780 781 Then, consume your input using ZSTD_compressContinue(). 782 There are some important considerations to keep in mind when using this advanced function : 783 - ZSTD_compressContinue() has no internal buffer. It uses externally provided buffers only. 784 - Interface is synchronous : input is consumed entirely and produces 1+ compressed blocks. 785 - Caller must ensure there is enough space in `dst` to store compressed data under worst case scenario. 786 Worst case evaluation is provided by ZSTD_compressBound(). 787 ZSTD_compressContinue() doesn't guarantee recover after a failed compression. 788 - ZSTD_compressContinue() presumes prior input ***is still accessible and unmodified*** (up to maximum distance size, see WindowLog). 789 It remembers all previous contiguous blocks, plus one separated memory segment (which can itself consists of multiple contiguous blocks) 790 - ZSTD_compressContinue() detects that prior input has been overwritten when `src` buffer overlaps. 791 In which case, it will "discard" the relevant memory section from its history. 792 793 Finish a frame with ZSTD_compressEnd(), which will write the last block(s) and optional checksum. 794 It's possible to use srcSize==0, in which case, it will write a final empty block to end the frame. 795 Without last block mark, frames are considered unfinished (hence corrupted) by compliant decoders. 796 797 `ZSTD_CCtx` object can be re-used (ZSTD_compressBegin()) to compress again. 798 */ 799 800 /*===== Buffer-less streaming compression functions =====*/ 801 ZSTDLIB_API size_t ZSTD_compressBegin(ZSTD_CCtx* cctx, int compressionLevel); 802 ZSTDLIB_API size_t ZSTD_compressBegin_usingDict(ZSTD_CCtx* cctx, const void* dict, size_t dictSize, int compressionLevel); 803 ZSTDLIB_API size_t ZSTD_compressBegin_advanced(ZSTD_CCtx* cctx, const void* dict, size_t dictSize, ZSTD_parameters params, unsigned long long pledgedSrcSize); /**< pledgedSrcSize is optional and can be 0 (meaning unknown). note: if the contentSizeFlag is set, pledgedSrcSize == 0 means the source size is actually 0 */ 804 ZSTDLIB_API size_t ZSTD_compressBegin_usingCDict(ZSTD_CCtx* cctx, const ZSTD_CDict* cdict); /**< note: fails if cdict==NULL */ 805 ZSTDLIB_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=0 means null-size */ 806 ZSTDLIB_API size_t ZSTD_copyCCtx(ZSTD_CCtx* cctx, const ZSTD_CCtx* preparedCCtx, unsigned long long pledgedSrcSize); /**< note: if pledgedSrcSize can be 0, indicating unknown size. if it is non-zero, it must be accurate. for 0 size frames, use compressBegin_advanced */ 807 808 ZSTDLIB_API size_t ZSTD_compressContinue(ZSTD_CCtx* cctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize); 809 ZSTDLIB_API size_t ZSTD_compressEnd(ZSTD_CCtx* cctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize); 810 811 812 /*- 813 Buffer-less streaming decompression (synchronous mode) 814 815 A ZSTD_DCtx object is required to track streaming operations. 816 Use ZSTD_createDCtx() / ZSTD_freeDCtx() to manage it. 817 A ZSTD_DCtx object can be re-used multiple times. 818 819 First typical operation is to retrieve frame parameters, using ZSTD_getFrameHeader(). 820 Frame header is extracted from the beginning of compressed frame, so providing only the frame's beginning is enough. 821 Data fragment must be large enough to ensure successful decoding. 822 `ZSTD_frameHeaderSize_max` bytes is guaranteed to always be large enough. 823 @result : 0 : successful decoding, the `ZSTD_frameHeader` structure is correctly filled. 824 >0 : `srcSize` is too small, please provide at least @result bytes on next attempt. 825 errorCode, which can be tested using ZSTD_isError(). 826 827 It fills a ZSTD_frameHeader structure with important information to correctly decode the frame, 828 such as the dictionary ID, content size, or maximum back-reference distance (`windowSize`). 829 Note that these values could be wrong, either because of data corruption, or because a 3rd party deliberately spoofs false information. 830 As a consequence, check that values remain within valid application range. 831 For example, do not allocate memory blindly, check that `windowSize` is within expectation. 832 Each application can set its own limits, depending on local restrictions. 833 For extended interoperability, it is recommended to support `windowSize` of at least 8 MB. 834 835 ZSTD_decompressContinue() needs previous data blocks during decompression, up to `windowSize` bytes. 836 ZSTD_decompressContinue() is very sensitive to contiguity, 837 if 2 blocks don't follow each other, make sure that either the compressor breaks contiguity at the same place, 838 or that previous contiguous segment is large enough to properly handle maximum back-reference distance. 839 There are multiple ways to guarantee this condition. 840 841 The most memory efficient way is to use a round buffer of sufficient size. 842 Sufficient size is determined by invoking ZSTD_decodingBufferSize_min(), 843 which can @return an error code if required value is too large for current system (in 32-bits mode). 844 In a round buffer methodology, ZSTD_decompressContinue() decompresses each block next to previous one, 845 up to the moment there is not enough room left in the buffer to guarantee decoding another full block, 846 which maximum size is provided in `ZSTD_frameHeader` structure, field `blockSizeMax`. 847 At which point, decoding can resume from the beginning of the buffer. 848 Note that already decoded data stored in the buffer should be flushed before being overwritten. 849 850 There are alternatives possible, for example using two or more buffers of size `windowSize` each, though they consume more memory. 851 852 Finally, if you control the compression process, you can also ignore all buffer size rules, 853 as long as the encoder and decoder progress in "lock-step", 854 aka use exactly the same buffer sizes, break contiguity at the same place, etc. 855 856 Once buffers are setup, start decompression, with ZSTD_decompressBegin(). 857 If decompression requires a dictionary, use ZSTD_decompressBegin_usingDict() or ZSTD_decompressBegin_usingDDict(). 858 859 Then use ZSTD_nextSrcSizeToDecompress() and ZSTD_decompressContinue() alternatively. 860 ZSTD_nextSrcSizeToDecompress() tells how many bytes to provide as 'srcSize' to ZSTD_decompressContinue(). 861 ZSTD_decompressContinue() requires this _exact_ amount of bytes, or it will fail. 862 863 @result of ZSTD_decompressContinue() is the number of bytes regenerated within 'dst' (necessarily <= dstCapacity). 864 It can be zero : it just means ZSTD_decompressContinue() has decoded some metadata item. 865 It can also be an error code, which can be tested with ZSTD_isError(). 866 867 A frame is fully decoded when ZSTD_nextSrcSizeToDecompress() returns zero. 868 Context can then be reset to start a new decompression. 869 870 Note : it's possible to know if next input to present is a header or a block, using ZSTD_nextInputType(). 871 This information is not required to properly decode a frame. 872 873 == Special case : skippable frames == 874 875 Skippable frames allow integration of user-defined data into a flow of concatenated frames. 876 Skippable frames will be ignored (skipped) by decompressor. 877 The format of skippable frames is as follows : 878 a) Skippable frame ID - 4 Bytes, Little endian format, any value from 0x184D2A50 to 0x184D2A5F 879 b) Frame Size - 4 Bytes, Little endian format, unsigned 32-bits 880 c) Frame Content - any content (User Data) of length equal to Frame Size 881 For skippable frames ZSTD_getFrameHeader() returns zfhPtr->frameType==ZSTD_skippableFrame. 882 For skippable frames ZSTD_decompressContinue() always returns 0 : it only skips the content. 883 */ 884 885 /*===== Buffer-less streaming decompression functions =====*/ 886 typedef enum { ZSTD_frame, ZSTD_skippableFrame } ZSTD_frameType_e; 887 typedef struct { 888 unsigned long long frameContentSize; /* if == ZSTD_CONTENTSIZE_UNKNOWN, it means this field is not available. 0 means "empty" */ 889 unsigned long long windowSize; /* can be very large, up to <= frameContentSize */ 890 unsigned blockSizeMax; 891 ZSTD_frameType_e frameType; /* if == ZSTD_skippableFrame, frameContentSize is the size of skippable content */ 892 unsigned headerSize; 893 unsigned dictID; 894 unsigned checksumFlag; 895 } ZSTD_frameHeader; 896 ZSTDLIB_API size_t ZSTD_getFrameHeader(ZSTD_frameHeader* zfhPtr, const void* src, size_t srcSize); /**< doesn't consume input */ 897 ZSTDLIB_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 */ 898 899 ZSTDLIB_API size_t ZSTD_decompressBegin(ZSTD_DCtx* dctx); 900 ZSTDLIB_API size_t ZSTD_decompressBegin_usingDict(ZSTD_DCtx* dctx, const void* dict, size_t dictSize); 901 ZSTDLIB_API size_t ZSTD_decompressBegin_usingDDict(ZSTD_DCtx* dctx, const ZSTD_DDict* ddict); 902 903 ZSTDLIB_API size_t ZSTD_nextSrcSizeToDecompress(ZSTD_DCtx* dctx); 904 ZSTDLIB_API size_t ZSTD_decompressContinue(ZSTD_DCtx* dctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize); 905 906 /* misc */ 907 ZSTDLIB_API void ZSTD_copyDCtx(ZSTD_DCtx* dctx, const ZSTD_DCtx* preparedDCtx); 908 typedef enum { ZSTDnit_frameHeader, ZSTDnit_blockHeader, ZSTDnit_block, ZSTDnit_lastBlock, ZSTDnit_checksum, ZSTDnit_skippableFrame } ZSTD_nextInputType_e; 909 ZSTDLIB_API ZSTD_nextInputType_e ZSTD_nextInputType(ZSTD_DCtx* dctx); 910 911 912 913 /* ============================================ */ 914 /** New advanced API (experimental) */ 915 /* ============================================ */ 916 917 /* notes on API design : 918 * In this proposal, parameters are pushed one by one into an existing context, 919 * and then applied on all subsequent compression jobs. 920 * When no parameter is ever provided, CCtx is created with compression level ZSTD_CLEVEL_DEFAULT. 921 * 922 * This API is intended to replace all others experimental API. 923 * It can basically do all other use cases, and even new ones. 924 * In constrast with _advanced() variants, it stands a reasonable chance to become "stable", 925 * after a good testing period. 926 */ 927 928 /* note on naming convention : 929 * Initially, the API favored names like ZSTD_setCCtxParameter() . 930 * In this proposal, convention is changed towards ZSTD_CCtx_setParameter() . 931 * The main driver is that it identifies more clearly the target object type. 932 * It feels clearer when considering multiple targets : 933 * ZSTD_CDict_setParameter() (rather than ZSTD_setCDictParameter()) 934 * ZSTD_CCtxParams_setParameter() (rather than ZSTD_setCCtxParamsParameter() ) 935 * etc... 936 */ 937 938 /* note on enum design : 939 * All enum will be pinned to explicit values before reaching "stable API" status */ 940 941 typedef enum { 942 /* Question : should we have a format ZSTD_f_auto ? 943 * For the time being, it would mean exactly the same as ZSTD_f_zstd1. 944 * But, in the future, should several formats be supported, 945 * on the compression side, it would mean "default format". 946 * On the decompression side, it would mean "multi format", 947 * and ZSTD_f_zstd1 could be reserved to mean "accept *only* zstd frames". 948 * Since meaning is a little different, another option could be to define different enums for compression and decompression. 949 * This question could be kept for later, when there are actually multiple formats to support, 950 * but there is also the question of pinning enum values, and pinning value `0` is especially important */ 951 ZSTD_f_zstd1 = 0, /* zstd frame format, specified in zstd_compression_format.md (default) */ 952 ZSTD_f_zstd1_magicless, /* Variant of zstd frame format, without initial 4-bytes magic number. 953 * Useful to save 4 bytes per generated frame. 954 * Decoder cannot recognise automatically this format, requiring instructions. */ 955 } ZSTD_format_e; 956 957 typedef enum { 958 /* compression format */ 959 ZSTD_p_format = 10, /* See ZSTD_format_e enum definition. 960 * Cast selected format as unsigned for ZSTD_CCtx_setParameter() compatibility. */ 961 962 /* compression parameters */ 963 ZSTD_p_compressionLevel=100, /* Update all compression parameters according to pre-defined cLevel table 964 * Default level is ZSTD_CLEVEL_DEFAULT==3. 965 * Special: value 0 means "do not change cLevel". */ 966 ZSTD_p_windowLog, /* Maximum allowed back-reference distance, expressed as power of 2. 967 * Must be clamped between ZSTD_WINDOWLOG_MIN and ZSTD_WINDOWLOG_MAX. 968 * Special: value 0 means "do not change windowLog". 969 * Note: Using a window size greater than ZSTD_MAXWINDOWSIZE_DEFAULT (default: 2^27) 970 * requires setting the maximum window size at least as large during decompression. */ 971 ZSTD_p_hashLog, /* Size of the probe table, as a power of 2. 972 * Resulting table size is (1 << (hashLog+2)). 973 * Must be clamped between ZSTD_HASHLOG_MIN and ZSTD_HASHLOG_MAX. 974 * Larger tables improve compression ratio of strategies <= dFast, 975 * and improve speed of strategies > dFast. 976 * Special: value 0 means "do not change hashLog". */ 977 ZSTD_p_chainLog, /* Size of the full-search table, as a power of 2. 978 * Resulting table size is (1 << (chainLog+2)). 979 * Larger tables result in better and slower compression. 980 * This parameter is useless when using "fast" strategy. 981 * Special: value 0 means "do not change chainLog". */ 982 ZSTD_p_searchLog, /* Number of search attempts, as a power of 2. 983 * More attempts result in better and slower compression. 984 * This parameter is useless when using "fast" and "dFast" strategies. 985 * Special: value 0 means "do not change searchLog". */ 986 ZSTD_p_minMatch, /* Minimum size of searched matches (note : repCode matches can be smaller). 987 * Larger values make faster compression and decompression, but decrease ratio. 988 * Must be clamped between ZSTD_SEARCHLENGTH_MIN and ZSTD_SEARCHLENGTH_MAX. 989 * Note that currently, for all strategies < btopt, effective minimum is 4. 990 * Note that currently, for all strategies > fast, effective maximum is 6. 991 * Special: value 0 means "do not change minMatchLength". */ 992 ZSTD_p_targetLength, /* Only useful for strategies >= btopt. 993 * Length of Match considered "good enough" to stop search. 994 * Larger values make compression stronger and slower. 995 * Special: value 0 means "do not change targetLength". */ 996 ZSTD_p_compressionStrategy, /* See ZSTD_strategy enum definition. 997 * Cast selected strategy as unsigned for ZSTD_CCtx_setParameter() compatibility. 998 * The higher the value of selected strategy, the more complex it is, 999 * resulting in stronger and slower compression. 1000 * Special: value 0 means "do not change strategy". */ 1001 1002 /* frame parameters */ 1003 ZSTD_p_contentSizeFlag=200, /* Content size is written into frame header _whenever known_ (default:1) 1004 * note that content size must be known at the beginning, 1005 * it is sent using ZSTD_CCtx_setPledgedSrcSize() */ 1006 ZSTD_p_checksumFlag, /* A 32-bits checksum of content is written at end of frame (default:0) */ 1007 ZSTD_p_dictIDFlag, /* When applicable, dictID of dictionary is provided in frame header (default:1) */ 1008 1009 /* multi-threading parameters */ 1010 ZSTD_p_nbThreads=400, /* Select how many threads a compression job can spawn (default:1) 1011 * More threads improve speed, but also increase memory usage. 1012 * Can only receive a value > 1 if ZSTD_MULTITHREAD is enabled. 1013 * Special: value 0 means "do not change nbThreads" */ 1014 ZSTD_p_jobSize, /* Size of a compression job. Each compression job is completed in parallel. 1015 * 0 means default, which is dynamically determined based on compression parameters. 1016 * Job size must be a minimum of overlapSize, or 1 KB, whichever is largest 1017 * The minimum size is automatically and transparently enforced */ 1018 ZSTD_p_overlapSizeLog, /* Size of previous input reloaded at the beginning of each job. 1019 * 0 => no overlap, 6(default) => use 1/8th of windowSize, >=9 => use full windowSize */ 1020 1021 /* advanced parameters - may not remain available after API update */ 1022 ZSTD_p_forceMaxWindow=1100, /* Force back-reference distances to remain < windowSize, 1023 * even when referencing into Dictionary content (default:0) */ 1024 ZSTD_p_enableLongDistanceMatching=1200, /* Enable long distance matching. 1025 * This parameter is designed to improve the compression 1026 * ratio for large inputs with long distance matches. 1027 * This increases the memory usage as well as window size. 1028 * Note: setting this parameter sets all the LDM parameters 1029 * as well as ZSTD_p_windowLog. It should be set after 1030 * ZSTD_p_compressionLevel and before ZSTD_p_windowLog and 1031 * other LDM parameters. Setting the compression level 1032 * after this parameter overrides the window log, though LDM 1033 * will remain enabled until explicitly disabled. */ 1034 ZSTD_p_ldmHashLog, /* Size of the table for long distance matching, as a power of 2. 1035 * Larger values increase memory usage and compression ratio, but decrease 1036 * compression speed. 1037 * Must be clamped between ZSTD_HASHLOG_MIN and ZSTD_HASHLOG_MAX 1038 * (default: windowlog - 7). */ 1039 ZSTD_p_ldmMinMatch, /* Minimum size of searched matches for long distance matcher. 1040 * Larger/too small values usually decrease compression ratio. 1041 * Must be clamped between ZSTD_LDM_MINMATCH_MIN 1042 * and ZSTD_LDM_MINMATCH_MAX (default: 64). */ 1043 ZSTD_p_ldmBucketSizeLog, /* Log size of each bucket in the LDM hash table for collision resolution. 1044 * Larger values usually improve collision resolution but may decrease 1045 * compression speed. 1046 * The maximum value is ZSTD_LDM_BUCKETSIZELOG_MAX (default: 3). */ 1047 ZSTD_p_ldmHashEveryLog, /* Frequency of inserting/looking up entries in the LDM hash table. 1048 * The default is MAX(0, (windowLog - ldmHashLog)) to 1049 * optimize hash table usage. 1050 * Larger values improve compression speed. Deviating far from the 1051 * default value will likely result in a decrease in compression ratio. 1052 * Must be clamped between 0 and ZSTD_WINDOWLOG_MAX - ZSTD_HASHLOG_MIN. */ 1053 1054 } ZSTD_cParameter; 1055 1056 1057 /*! ZSTD_CCtx_setParameter() : 1058 * Set one compression parameter, selected by enum ZSTD_cParameter. 1059 * Note : when `value` is an enum, cast it to unsigned for proper type checking. 1060 * @result : 0, or an error code (which can be tested with ZSTD_isError()). */ 1061 ZSTDLIB_API size_t ZSTD_CCtx_setParameter(ZSTD_CCtx* cctx, ZSTD_cParameter param, unsigned value); 1062 1063 /*! ZSTD_CCtx_setPledgedSrcSize() : 1064 * Total input data size to be compressed as a single frame. 1065 * This value will be controlled at the end, and result in error if not respected. 1066 * @result : 0, or an error code (which can be tested with ZSTD_isError()). 1067 * Note 1 : 0 means zero, empty. 1068 * In order to mean "unknown content size", pass constant ZSTD_CONTENTSIZE_UNKNOWN. 1069 * Note that ZSTD_CONTENTSIZE_UNKNOWN is default value for new compression jobs. 1070 * Note 2 : If all data is provided and consumed in a single round, 1071 * this value is overriden by srcSize instead. */ 1072 ZSTDLIB_API size_t ZSTD_CCtx_setPledgedSrcSize(ZSTD_CCtx* cctx, unsigned long long pledgedSrcSize); 1073 1074 /*! ZSTD_CCtx_loadDictionary() : 1075 * Create an internal CDict from dict buffer. 1076 * Decompression will have to use same buffer. 1077 * @result : 0, or an error code (which can be tested with ZSTD_isError()). 1078 * Special : Adding a NULL (or 0-size) dictionary invalidates any previous dictionary, 1079 * meaning "return to no-dictionary mode". 1080 * Note 1 : `dict` content will be copied internally. Use 1081 * ZSTD_CCtx_loadDictionary_byReference() to reference dictionary 1082 * content instead. The dictionary buffer must then outlive its 1083 * users. 1084 * Note 2 : Loading a dictionary involves building tables, which are dependent on compression parameters. 1085 * For this reason, compression parameters cannot be changed anymore after loading a dictionary. 1086 * It's also a CPU-heavy operation, with non-negligible impact on latency. 1087 * Note 3 : Dictionary will be used for all future compression jobs. 1088 * To return to "no-dictionary" situation, load a NULL dictionary 1089 * Note 5 : Use ZSTD_CCtx_loadDictionary_advanced() to select how dictionary 1090 * content will be interpreted. 1091 */ 1092 ZSTDLIB_API size_t ZSTD_CCtx_loadDictionary(ZSTD_CCtx* cctx, const void* dict, size_t dictSize); 1093 ZSTDLIB_API size_t ZSTD_CCtx_loadDictionary_byReference(ZSTD_CCtx* cctx, const void* dict, size_t dictSize); 1094 ZSTDLIB_API size_t ZSTD_CCtx_loadDictionary_advanced(ZSTD_CCtx* cctx, const void* dict, size_t dictSize, ZSTD_dictLoadMethod_e dictLoadMethod, ZSTD_dictMode_e dictMode); 1095 1096 1097 /*! ZSTD_CCtx_refCDict() : 1098 * Reference a prepared dictionary, to be used for all next compression jobs. 1099 * Note that compression parameters are enforced from within CDict, 1100 * and supercede any compression parameter previously set within CCtx. 1101 * The dictionary will remain valid for future compression jobs using same CCtx. 1102 * @result : 0, or an error code (which can be tested with ZSTD_isError()). 1103 * Special : adding a NULL CDict means "return to no-dictionary mode". 1104 * Note 1 : Currently, only one dictionary can be managed. 1105 * Adding a new dictionary effectively "discards" any previous one. 1106 * Note 2 : CDict is just referenced, its lifetime must outlive CCtx. 1107 */ 1108 ZSTDLIB_API size_t ZSTD_CCtx_refCDict(ZSTD_CCtx* cctx, const ZSTD_CDict* cdict); 1109 1110 /*! ZSTD_CCtx_refPrefix() : 1111 * Reference a prefix (single-usage dictionary) for next compression job. 1112 * Decompression need same prefix to properly regenerate data. 1113 * Prefix is **only used once**. Tables are discarded at end of compression job. 1114 * Subsequent compression jobs will be done without prefix (if none is explicitly referenced). 1115 * If there is a need to use same prefix multiple times, consider embedding it into a ZSTD_CDict instead. 1116 * @result : 0, or an error code (which can be tested with ZSTD_isError()). 1117 * Special : Adding any prefix (including NULL) invalidates any previous prefix or dictionary 1118 * Note 1 : Prefix buffer is referenced. It must outlive compression job. 1119 * Note 2 : Referencing a prefix involves building tables, which are dependent on compression parameters. 1120 * It's a CPU-heavy operation, with non-negligible impact on latency. 1121 * Note 3 : By default, the prefix is treated as raw content 1122 * (ZSTD_dm_rawContent). Use ZSTD_CCtx_refPrefix_advanced() to alter 1123 * dictMode. */ 1124 ZSTDLIB_API size_t ZSTD_CCtx_refPrefix(ZSTD_CCtx* cctx, const void* prefix, size_t prefixSize); 1125 ZSTDLIB_API size_t ZSTD_CCtx_refPrefix_advanced(ZSTD_CCtx* cctx, const void* prefix, size_t prefixSize, ZSTD_dictMode_e dictMode); 1126 1127 1128 1129 typedef enum { 1130 ZSTD_e_continue=0, /* collect more data, encoder transparently decides when to output result, for optimal conditions */ 1131 ZSTD_e_flush, /* flush any data provided so far - frame will continue, future data can still reference previous data for better compression */ 1132 ZSTD_e_end /* flush any remaining data and close current frame. Any additional data starts a new frame. */ 1133 } ZSTD_EndDirective; 1134 1135 /*! ZSTD_compress_generic() : 1136 * Behave about the same as ZSTD_compressStream. To note : 1137 * - Compression parameters are pushed into CCtx before starting compression, using ZSTD_CCtx_setParameter() 1138 * - Compression parameters cannot be changed once compression is started. 1139 * - outpot->pos must be <= dstCapacity, input->pos must be <= srcSize 1140 * - outpot->pos and input->pos will be updated. They are guaranteed to remain below their respective limit. 1141 * - @return provides the minimum amount of data still to flush from internal buffers 1142 * or an error code, which can be tested using ZSTD_isError(). 1143 * if @return != 0, flush is not fully completed, there is some data left within internal buffers. 1144 * - after a ZSTD_e_end directive, if internal buffer is not fully flushed, 1145 * only ZSTD_e_end or ZSTD_e_flush operations are allowed. 1146 * It is necessary to fully flush internal buffers 1147 * before starting a new compression job, or changing compression parameters. 1148 */ 1149 ZSTDLIB_API size_t ZSTD_compress_generic (ZSTD_CCtx* cctx, 1150 ZSTD_outBuffer* output, 1151 ZSTD_inBuffer* input, 1152 ZSTD_EndDirective endOp); 1153 1154 /*! ZSTD_CCtx_reset() : 1155 * Return a CCtx to clean state. 1156 * Useful after an error, or to interrupt an ongoing compression job and start a new one. 1157 * Any internal data not yet flushed is cancelled. 1158 * Dictionary (if any) is dropped. 1159 * All parameters are back to default values. 1160 * It's possible to modify compression parameters after a reset. 1161 */ 1162 ZSTDLIB_API void ZSTD_CCtx_reset(ZSTD_CCtx* cctx); /* Not ready yet ! */ 1163 1164 1165 /*! ZSTD_compress_generic_simpleArgs() : 1166 * Same as ZSTD_compress_generic(), 1167 * but using only integral types as arguments. 1168 * Argument list is larger than ZSTD_{in,out}Buffer, 1169 * but can be helpful for binders from dynamic languages 1170 * which have troubles handling structures containing memory pointers. 1171 */ 1172 ZSTDLIB_API size_t ZSTD_compress_generic_simpleArgs ( 1173 ZSTD_CCtx* cctx, 1174 void* dst, size_t dstCapacity, size_t* dstPos, 1175 const void* src, size_t srcSize, size_t* srcPos, 1176 ZSTD_EndDirective endOp); 1177 1178 1179 /*! ZSTD_CCtx_params : 1180 * Quick howto : 1181 * - ZSTD_createCCtxParams() : Create a ZSTD_CCtx_params structure 1182 * - ZSTD_CCtxParam_setParameter() : Push parameters one by one into 1183 * an existing ZSTD_CCtx_params structure. 1184 * This is similar to 1185 * ZSTD_CCtx_setParameter(). 1186 * - ZSTD_CCtx_setParametersUsingCCtxParams() : Apply parameters to 1187 * an existing CCtx. 1188 * These parameters will be applied to 1189 * all subsequent compression jobs. 1190 * - ZSTD_compress_generic() : Do compression using the CCtx. 1191 * - ZSTD_freeCCtxParams() : Free the memory. 1192 * 1193 * This can be used with ZSTD_estimateCCtxSize_advanced_usingCCtxParams() 1194 * for static allocation for single-threaded compression. 1195 */ 1196 ZSTDLIB_API ZSTD_CCtx_params* ZSTD_createCCtxParams(void); 1197 1198 /*! ZSTD_resetCCtxParams() : 1199 * Reset params to default, with the default compression level. 1200 */ 1201 ZSTDLIB_API size_t ZSTD_resetCCtxParams(ZSTD_CCtx_params* params); 1202 1203 /*! ZSTD_initCCtxParams() : 1204 * Initializes the compression parameters of cctxParams according to 1205 * compression level. All other parameters are reset to their default values. 1206 */ 1207 ZSTDLIB_API size_t ZSTD_initCCtxParams(ZSTD_CCtx_params* cctxParams, int compressionLevel); 1208 1209 /*! ZSTD_initCCtxParams_advanced() : 1210 * Initializes the compression and frame parameters of cctxParams according to 1211 * params. All other parameters are reset to their default values. 1212 */ 1213 ZSTDLIB_API size_t ZSTD_initCCtxParams_advanced(ZSTD_CCtx_params* cctxParams, ZSTD_parameters params); 1214 1215 ZSTDLIB_API size_t ZSTD_freeCCtxParams(ZSTD_CCtx_params* params); 1216 1217 /*! ZSTD_CCtxParam_setParameter() : 1218 * Similar to ZSTD_CCtx_setParameter. 1219 * Set one compression parameter, selected by enum ZSTD_cParameter. 1220 * Parameters must be applied to a ZSTD_CCtx using ZSTD_CCtx_setParametersUsingCCtxParams(). 1221 * Note : when `value` is an enum, cast it to unsigned for proper type checking. 1222 * @result : 0, or an error code (which can be tested with ZSTD_isError()). 1223 */ 1224 ZSTDLIB_API size_t ZSTD_CCtxParam_setParameter(ZSTD_CCtx_params* params, ZSTD_cParameter param, unsigned value); 1225 1226 /*! ZSTD_CCtx_setParametersUsingCCtxParams() : 1227 * Apply a set of ZSTD_CCtx_params to the compression context. 1228 * This must be done before the dictionary is loaded. 1229 * The pledgedSrcSize is treated as unknown. 1230 * Multithreading parameters are applied only if nbThreads > 1. 1231 */ 1232 ZSTDLIB_API size_t ZSTD_CCtx_setParametersUsingCCtxParams( 1233 ZSTD_CCtx* cctx, const ZSTD_CCtx_params* params); 1234 1235 1236 /*=== Advanced parameters for decompression API ===*/ 1237 1238 /* The following parameters must be set after creating a ZSTD_DCtx* (or ZSTD_DStream*) object, 1239 * but before starting decompression of a frame. 1240 */ 1241 1242 /*! ZSTD_DCtx_loadDictionary() : 1243 * Create an internal DDict from dict buffer, 1244 * to be used to decompress next frames. 1245 * @result : 0, or an error code (which can be tested with ZSTD_isError()). 1246 * Special : Adding a NULL (or 0-size) dictionary invalidates any previous dictionary, 1247 * meaning "return to no-dictionary mode". 1248 * Note 1 : `dict` content will be copied internally. 1249 * Use ZSTD_DCtx_loadDictionary_byReference() 1250 * to reference dictionary content instead. 1251 * In which case, the dictionary buffer must outlive its users. 1252 * Note 2 : Loading a dictionary involves building tables, 1253 * which has a non-negligible impact on CPU usage and latency. 1254 * Note 3 : Use ZSTD_DCtx_loadDictionary_advanced() to select 1255 * how dictionary content will be interpreted and loaded. 1256 */ 1257 ZSTDLIB_API size_t ZSTD_DCtx_loadDictionary(ZSTD_DCtx* dctx, const void* dict, size_t dictSize); /* not implemented */ 1258 ZSTDLIB_API size_t ZSTD_DCtx_loadDictionary_byReference(ZSTD_DCtx* dctx, const void* dict, size_t dictSize); /* not implemented */ 1259 ZSTDLIB_API size_t ZSTD_DCtx_loadDictionary_advanced(ZSTD_DCtx* dctx, const void* dict, size_t dictSize, ZSTD_dictLoadMethod_e dictLoadMethod, ZSTD_dictMode_e dictMode); /* not implemented */ 1260 1261 1262 /*! ZSTD_DCtx_refDDict() : 1263 * Reference a prepared dictionary, to be used to decompress next frames. 1264 * The dictionary remains active for decompression of future frames using same DCtx. 1265 * @result : 0, or an error code (which can be tested with ZSTD_isError()). 1266 * Note 1 : Currently, only one dictionary can be managed. 1267 * Referencing a new dictionary effectively "discards" any previous one. 1268 * Special : adding a NULL DDict means "return to no-dictionary mode". 1269 * Note 2 : DDict is just referenced, its lifetime must outlive its usage from DCtx. 1270 */ 1271 ZSTDLIB_API size_t ZSTD_DCtx_refDDict(ZSTD_DCtx* dctx, const ZSTD_DDict* ddict); /* not implemented */ 1272 1273 1274 /*! ZSTD_DCtx_refPrefix() : 1275 * Reference a prefix (single-usage dictionary) for next compression job. 1276 * Prefix is **only used once**. It must be explicitly referenced before each frame. 1277 * If there is a need to use same prefix multiple times, consider embedding it into a ZSTD_DDict instead. 1278 * @result : 0, or an error code (which can be tested with ZSTD_isError()). 1279 * Note 1 : Adding any prefix (including NULL) invalidates any previously set prefix or dictionary 1280 * Note 2 : Prefix buffer is referenced. It must outlive compression job. 1281 * Note 3 : By default, the prefix is treated as raw content (ZSTD_dm_rawContent). 1282 * Use ZSTD_CCtx_refPrefix_advanced() to alter dictMode. 1283 * Note 4 : Referencing a raw content prefix has almost no cpu nor memory cost. 1284 */ 1285 ZSTDLIB_API size_t ZSTD_DCtx_refPrefix(ZSTD_DCtx* dctx, const void* prefix, size_t prefixSize); /* not implemented */ 1286 ZSTDLIB_API size_t ZSTD_DCtx_refPrefix_advanced(ZSTD_DCtx* dctx, const void* prefix, size_t prefixSize, ZSTD_dictMode_e dictMode); /* not implemented */ 1287 1288 1289 /*! ZSTD_DCtx_setMaxWindowSize() : 1290 * Refuses allocating internal buffers for frames requiring a window size larger than provided limit. 1291 * This is useful to prevent a decoder context from reserving too much memory for itself (potential attack scenario). 1292 * This parameter is only useful in streaming mode, since no internal buffer is allocated in direct mode. 1293 * By default, a decompression context accepts all window sizes <= (1 << ZSTD_WINDOWLOG_MAX) 1294 * @return : 0, or an error code (which can be tested using ZSTD_isError()). 1295 */ 1296 ZSTDLIB_API size_t ZSTD_DCtx_setMaxWindowSize(ZSTD_DCtx* dctx, size_t maxWindowSize); 1297 1298 1299 /*! ZSTD_DCtx_setFormat() : 1300 * Instruct the decoder context about what kind of data to decode next. 1301 * This instruction is mandatory to decode data without a fully-formed header, 1302 * such ZSTD_f_zstd1_magicless for example. 1303 * @return : 0, or an error code (which can be tested using ZSTD_isError()). 1304 */ 1305 ZSTDLIB_API size_t ZSTD_DCtx_setFormat(ZSTD_DCtx* dctx, ZSTD_format_e format); 1306 1307 1308 /*! ZSTD_decompress_generic() : 1309 * Behave the same as ZSTD_decompressStream. 1310 * Decompression parameters cannot be changed once decompression is started. 1311 * @return : an error code, which can be tested using ZSTD_isError() 1312 * if >0, a hint, nb of expected input bytes for next invocation. 1313 * `0` means : a frame has just been fully decoded and flushed. 1314 */ 1315 ZSTDLIB_API size_t ZSTD_decompress_generic(ZSTD_DCtx* dctx, 1316 ZSTD_outBuffer* output, 1317 ZSTD_inBuffer* input); 1318 1319 1320 /*! ZSTD_decompress_generic_simpleArgs() : 1321 * Same as ZSTD_decompress_generic(), 1322 * but using only integral types as arguments. 1323 * Argument list is larger than ZSTD_{in,out}Buffer, 1324 * but can be helpful for binders from dynamic languages 1325 * which have troubles handling structures containing memory pointers. 1326 */ 1327 ZSTDLIB_API size_t ZSTD_decompress_generic_simpleArgs ( 1328 ZSTD_DCtx* dctx, 1329 void* dst, size_t dstCapacity, size_t* dstPos, 1330 const void* src, size_t srcSize, size_t* srcPos); 1331 1332 1333 /*! ZSTD_DCtx_reset() : 1334 * Return a DCtx to clean state. 1335 * If a decompression was ongoing, any internal data not yet flushed is cancelled. 1336 * All parameters are back to default values, including sticky ones. 1337 * Dictionary (if any) is dropped. 1338 * Parameters can be modified again after a reset. 1339 */ 1340 ZSTDLIB_API void ZSTD_DCtx_reset(ZSTD_DCtx* dctx); 1341 1342 1343 1344 /* ============================ */ 1345 /** Block level API */ 1346 /* ============================ */ 1347 1348 /*! 1349 Block functions produce and decode raw zstd blocks, without frame metadata. 1350 Frame metadata cost is typically ~18 bytes, which can be non-negligible for very small blocks (< 100 bytes). 1351 User will have to take in charge required information to regenerate data, such as compressed and content sizes. 1352 1353 A few rules to respect : 1354 - Compressing and decompressing require a context structure 1355 + Use ZSTD_createCCtx() and ZSTD_createDCtx() 1356 - It is necessary to init context before starting 1357 + compression : any ZSTD_compressBegin*() variant, including with dictionary 1358 + decompression : any ZSTD_decompressBegin*() variant, including with dictionary 1359 + copyCCtx() and copyDCtx() can be used too 1360 - Block size is limited, it must be <= ZSTD_getBlockSize() <= ZSTD_BLOCKSIZE_MAX == 128 KB 1361 + If input is larger than a block size, it's necessary to split input data into multiple blocks 1362 + For inputs larger than a single block size, consider using the regular ZSTD_compress() instead. 1363 Frame metadata is not that costly, and quickly becomes negligible as source size grows larger. 1364 - When a block is considered not compressible enough, ZSTD_compressBlock() result will be zero. 1365 In which case, nothing is produced into `dst`. 1366 + User must test for such outcome and deal directly with uncompressed data 1367 + ZSTD_decompressBlock() doesn't accept uncompressed data as input !!! 1368 + In case of multiple successive blocks, should some of them be uncompressed, 1369 decoder must be informed of their existence in order to follow proper history. 1370 Use ZSTD_insertBlock() for such a case. 1371 */ 1372 1373 #define ZSTD_BLOCKSIZELOG_MAX 17 1374 #define ZSTD_BLOCKSIZE_MAX (1<<ZSTD_BLOCKSIZELOG_MAX) /* define, for static allocation */ 1375 /*===== Raw zstd block functions =====*/ 1376 ZSTDLIB_API size_t ZSTD_getBlockSize (const ZSTD_CCtx* cctx); 1377 ZSTDLIB_API size_t ZSTD_compressBlock (ZSTD_CCtx* cctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize); 1378 ZSTDLIB_API size_t ZSTD_decompressBlock(ZSTD_DCtx* dctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize); 1379 ZSTDLIB_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 */ 1380 1381 1382 #endif /* ZSTD_H_ZSTD_STATIC_LINKING_ONLY */ 1383 1384 #if defined (__cplusplus) 1385 } 1386 #endif 1387