1 /// Zstandard bindings module 2 module squiz_box.c.zstd; 3 4 version (HaveSquizZstandard) 5 { 6 } 7 else 8 { 9 static assert(false, "Zstandard support is disabled"); 10 } 11 12 import core.stdc.config; 13 import std.algorithm : min; 14 import std.format; 15 16 /* 17 * Copyright (c) 2016-2020, Yann Collet, Facebook, Inc. 18 * All rights reserved. 19 * 20 * This source code is licensed under both the BSD-style license (found in the 21 * LICENSE file in the root directory of this source tree) and the GPLv2 (found 22 * in the COPYING file in the root directory of this source tree). 23 * You may select, at your option, one of the above-listed licenses. 24 */ 25 26 extern (C): 27 nothrow: 28 29 /******************************************************************************* 30 Introduction 31 32 zstd, short for Zstandard, is a fast lossless compression algorithm, targeting 33 real-time compression scenarios at zlib-level and better compression ratios. 34 The zstd compression library provides in-memory compression and decompression 35 functions. 36 37 The library supports regular compression levels from 1 up to ZSTD_maxCLevel(), 38 which is currently 22. Levels >= 20, labeled `--ultra`, should be used with 39 caution, as they require more memory. The library also offers negative 40 compression levels, which extend the range of speed vs. ratio preferences. 41 The lower the level, the faster the speed (at the cost of compression). 42 43 Compression can be done in: 44 - a single step (described as Simple API) 45 - a single step, reusing a context (described as Explicit context) 46 - unbounded multiple steps (described as Streaming compression) 47 48 The compression ratio achievable on small data can be highly improved using 49 a dictionary. Dictionary compression can be performed in: 50 - a single step (described as Simple dictionary API) 51 - a single step, reusing a dictionary (described as Bulk-processing 52 dictionary API) 53 54 Advanced experimental functions can be accessed using 55 `#define ZSTD_STATIC_LINKING_ONLY` before including zstd.h. 56 57 Advanced experimental APIs should never be used with a dynamically-linked 58 library. They are not "stable"; their definitions or signatures may change in 59 the future. Only static linking is allowed. 60 *******************************************************************************/ 61 62 /*------ Version ------*/ 63 enum ZSTD_VERSION_MAJOR = 1; 64 enum ZSTD_VERSION_MINOR = 5; 65 enum ZSTD_VERSION_RELEASE = 2; 66 enum ZSTD_VERSION_NUMBER = ZSTD_VERSION_MAJOR * 100 * 100 + ZSTD_VERSION_MINOR * 100 + ZSTD_VERSION_RELEASE; 67 68 /*! ZSTD_versionNumber() : 69 * Return runtime library version, the value is (MAJOR*100*100 + MINOR*100 + RELEASE). */ 70 uint ZSTD_versionNumber(); 71 72 enum ZSTD_VERSION_STRING = format!"%d.%d.%d"(ZSTD_VERSION_MAJOR, ZSTD_VERSION_MINOR, ZSTD_VERSION_RELEASE); 73 74 /*! ZSTD_versionString() : 75 * Return runtime library version, like "1.4.5". Requires v1.3.0+. */ 76 const(char)* ZSTD_versionString(); 77 78 /* ************************************* 79 * Default constant 80 ***************************************/ 81 enum ZSTD_CLEVEL_DEFAULT = 3; 82 83 /* ************************************* 84 * Constants 85 ***************************************/ 86 87 /* All magic numbers are supposed read/written to/from files/memory using little-endian convention */ 88 enum ZSTD_MAGICNUMBER = 0xFD2FB528; /* valid since v0.8.0 */ 89 enum ZSTD_MAGIC_DICTIONARY = 0xEC30A437; /* valid since v0.7.0 */ 90 /* all 16 values, from 0x184D2A50 to 0x184D2A5F, signal the beginning of a skippable frame */ 91 enum ZSTD_MAGIC_SKIPPABLE_START = 0x184D2A50; 92 enum ZSTD_MAGIC_SKIPPABLE_MASK = 0xFFFFFFF0; 93 94 enum ZSTD_BLOCKSIZELOG_MAX = 17; 95 enum ZSTD_BLOCKSIZE_MAX = (1 << ZSTD_BLOCKSIZELOG_MAX); 96 97 /*************************************** 98 * Simple API 99 ***************************************/ 100 /*! ZSTD_compress() : 101 * Compresses `src` content as a single zstd compressed frame into already allocated `dst`. 102 * Hint : compression runs faster if `dstCapacity` >= `ZSTD_compressBound(srcSize)`. 103 * @return : compressed size written into `dst` (<= `dstCapacity), 104 * or an error code if it fails (which can be tested using ZSTD_isError()). */ 105 size_t ZSTD_compress(void* dst, size_t dstCapacity, 106 const(void)* src, size_t srcSize, 107 int compressionLevel); 108 109 /*! ZSTD_decompress() : 110 * `compressedSize` : must be the _exact_ size of some number of compressed and/or skippable frames. 111 * `dstCapacity` is an upper bound of originalSize to regenerate. 112 * If user cannot imply a maximum upper bound, it's better to use streaming mode to decompress data. 113 * @return : the number of bytes decompressed into `dst` (<= `dstCapacity`), 114 * or an errorCode if it fails (which can be tested using ZSTD_isError()). */ 115 size_t ZSTD_decompress(void* dst, size_t dstCapacity, 116 const(void)* src, size_t compressedSize); 117 118 /*! ZSTD_getFrameContentSize() : requires v1.3.0+ 119 * `src` should point to the start of a ZSTD encoded frame. 120 * `srcSize` must be at least as large as the frame header. 121 * hint : any size >= `ZSTD_frameHeaderSize_max` is large enough. 122 * @return : - decompressed size of `src` frame content, if known 123 * - ZSTD_CONTENTSIZE_UNKNOWN if the size cannot be determined 124 * - ZSTD_CONTENTSIZE_ERROR if an error occurred (e.g. invalid magic number, srcSize too small) 125 * note 1 : a 0 return value means the frame is valid but "empty". 126 * note 2 : decompressed size is an optional field, it may not be present, typically in streaming mode. 127 * When `return==ZSTD_CONTENTSIZE_UNKNOWN`, data to decompress could be any size. 128 * In which case, it's necessary to use streaming mode to decompress data. 129 * Optionally, application can rely on some implicit limit, 130 * as ZSTD_decompress() only needs an upper bound of decompressed size. 131 * (For example, data could be necessarily cut into blocks <= 16 KB). 132 * note 3 : decompressed size is always present when compression is completed using single-pass functions, 133 * such as ZSTD_compress(), ZSTD_compressCCtx() ZSTD_compress_usingDict() or ZSTD_compress_usingCDict(). 134 * note 4 : decompressed size can be very large (64-bits value), 135 * potentially larger than what local system can handle as a single memory segment. 136 * In which case, it's necessary to use streaming mode to decompress data. 137 * note 5 : If source is untrusted, decompressed size could be wrong or intentionally modified. 138 * Always ensure return value fits within application's authorized limits. 139 * Each application can set its own limits. 140 * note 6 : This function replaces ZSTD_getDecompressedSize() */ 141 enum ZSTD_CONTENTSIZE_UNKNOWN = cpp_ulonglong.max; 142 enum ZSTD_CONTENTSIZE_ERROR = cpp_ulonglong.max - 1; 143 cpp_ulonglong ZSTD_getFrameContentSize(const(void)* src, size_t srcSize); 144 145 /*! ZSTD_getDecompressedSize() : 146 * NOTE: This function is now obsolete, in favor of ZSTD_getFrameContentSize(). 147 * Both functions work the same way, but ZSTD_getDecompressedSize() blends 148 * "empty", "unknown" and "error" results to the same return value (0), 149 * while ZSTD_getFrameContentSize() gives them separate return values. 150 * @return : decompressed size of `src` frame content _if known and not empty_, 0 otherwise. */ 151 cpp_ulonglong ZSTD_getDecompressedSize(const(void)* src, size_t srcSize); 152 153 /*! ZSTD_findFrameCompressedSize() : Requires v1.4.0+ 154 * `src` should point to the start of a ZSTD frame or skippable frame. 155 * `srcSize` must be >= first frame size 156 * @return : the compressed size of the first frame starting at `src`, 157 * suitable to pass as `srcSize` to `ZSTD_decompress` or similar, 158 * or an error code if input is invalid */ 159 size_t ZSTD_findFrameCompressedSize(const(void)* src, size_t srcSize); 160 161 /*====== Helper functions ======*/ 162 extern (D) auto ZSTD_COMPRESSBOUND(S)(S srcSize) 163 { 164 /* this formula ensures that bound(A) + bound(B) <= bound(A+B) as long as A and B >= 128 KB */ 165 return ((srcSize) + ((srcSize) >> 8) + 166 (((srcSize) < (128 << 10)) ? (((128 << 10) - (srcSize)) >> 11) /* margin, from 64 to 0 */ 167 : 0)); 168 } 169 170 size_t ZSTD_compressBound(size_t srcSize); /*!< maximum compressed size in worst case single-pass scenario */ 171 uint ZSTD_isError(size_t code); /*!< tells if a `size_t` function result is an error code */ 172 const(char)* ZSTD_getErrorName(size_t code); /*!< provides readable string from an error code */ 173 int ZSTD_minCLevel(); /*!< minimum negative compression level allowed, requires v1.4.0+ */ 174 int ZSTD_maxCLevel(); /*!< maximum compression level available */ 175 int ZSTD_defaultCLevel(); /*!< default compression level, specified by ZSTD_CLEVEL_DEFAULT, requires v1.5.0+ */ 176 177 /*************************************** 178 * Explicit context 179 ***************************************/ 180 /*= Compression context 181 * When compressing many times, 182 * it is recommended to allocate a context just once, 183 * and re-use it for each successive compression operation. 184 * This will make workload friendlier for system's memory. 185 * Note : re-using context is just a speed / resource optimization. 186 * It doesn't change the compression ratio, which remains identical. 187 * Note 2 : In multi-threaded environments, 188 * use one different context per thread for parallel execution. 189 */ 190 struct ZSTD_CCtx; 191 ZSTD_CCtx* ZSTD_createCCtx(); 192 size_t ZSTD_freeCCtx(ZSTD_CCtx* cctx); /* accept NULL pointer */ 193 194 /*! ZSTD_compressCCtx() : 195 * Same as ZSTD_compress(), using an explicit ZSTD_CCtx. 196 * Important : in order to behave similarly to `ZSTD_compress()`, 197 * this function compresses at requested compression level, 198 * __ignoring any other parameter__ . 199 * If any advanced parameter was set using the advanced API, 200 * they will all be reset. Only `compressionLevel` remains. 201 */ 202 size_t ZSTD_compressCCtx(ZSTD_CCtx* cctx, 203 void* dst, size_t dstCapacity, 204 const(void)* src, size_t srcSize, 205 int compressionLevel); 206 207 /*= Decompression context 208 * When decompressing many times, 209 * it is recommended to allocate a context only once, 210 * and re-use it for each successive compression operation. 211 * This will make workload friendlier for system's memory. 212 * Use one context per thread for parallel execution. */ 213 struct ZSTD_DCtx; 214 ZSTD_DCtx* ZSTD_createDCtx(); 215 size_t ZSTD_freeDCtx(ZSTD_DCtx* dctx); /* accept NULL pointer */ 216 217 /*! ZSTD_decompressDCtx() : 218 * Same as ZSTD_decompress(), 219 * requires an allocated ZSTD_DCtx. 220 * Compatible with sticky parameters. 221 */ 222 size_t ZSTD_decompressDCtx(ZSTD_DCtx* dctx, 223 void* dst, size_t dstCapacity, 224 const(void)* src, size_t srcSize); 225 226 /********************************************* 227 * Advanced compression API (Requires v1.4.0+) 228 **********************************************/ 229 230 /* API design : 231 * Parameters are pushed one by one into an existing context, 232 * using ZSTD_CCtx_set*() functions. 233 * Pushed parameters are sticky : they are valid for next compressed frame, and any subsequent frame. 234 * "sticky" parameters are applicable to `ZSTD_compress2()` and `ZSTD_compressStream*()` ! 235 * __They do not apply to "simple" one-shot variants such as ZSTD_compressCCtx()__ . 236 * 237 * It's possible to reset all parameters to "default" using ZSTD_CCtx_reset(). 238 * 239 * This API supersedes all other "advanced" API entry points in the experimental section. 240 * In the future, we expect to remove from experimental API entry points which are redundant with this API. 241 */ 242 243 /* Compression strategies, listed from fastest to strongest */ 244 enum ZSTD_strategy 245 { 246 fast = 1, 247 dfast = 2, 248 greedy = 3, 249 _lazy = 4, 250 lazy2 = 5, 251 btlazy2 = 6, 252 btopt = 7, 253 btultra = 8, 254 btultra2 = 9 /* note : new strategies _might_ be added in the future. 255 Only the order (from fast to strong) is guaranteed */ 256 } 257 258 enum ZSTD_cParameter 259 { 260 261 /* compression parameters 262 * Note: When compressing with a ZSTD_CDict these parameters are superseded 263 * by the parameters used to construct the ZSTD_CDict. 264 * See ZSTD_CCtx_refCDict() for more info (superseded-by-cdict). */ 265 compressionLevel = 100, /* Set compression parameters according to pre-defined cLevel table. 266 * Note that exact compression parameters are dynamically determined, 267 * depending on both compression level and srcSize (when known). 268 * Default level is ZSTD_CLEVEL_DEFAULT==3. 269 * Special: value 0 means default, which is controlled by ZSTD_CLEVEL_DEFAULT. 270 * Note 1 : it's possible to pass a negative compression level. 271 * Note 2 : setting a level does not automatically set all other compression parameters 272 * to default. Setting this will however eventually dynamically impact the compression 273 * parameters which have not been manually set. The manually set 274 * ones will 'stick'. */ 275 /* Advanced compression parameters : 276 * It's possible to pin down compression parameters to some specific values. 277 * In which case, these values are no longer dynamically selected by the compressor */ 278 windowLog = 101, /* Maximum allowed back-reference distance, expressed as power of 2. 279 * This will set a memory budget for streaming decompression, 280 * with larger values requiring more memory 281 * and typically compressing more. 282 * Must be clamped between ZSTD_WINDOWLOG_MIN and ZSTD_WINDOWLOG_MAX. 283 * Special: value 0 means "use default windowLog". 284 * Note: Using a windowLog greater than ZSTD_WINDOWLOG_LIMIT_DEFAULT 285 * requires explicitly allowing such size at streaming decompression stage. */ 286 hashLog = 102, /* Size of the initial probe table, as a power of 2. 287 * Resulting memory usage is (1 << (hashLog+2)). 288 * Must be clamped between ZSTD_HASHLOG_MIN and ZSTD_HASHLOG_MAX. 289 * Larger tables improve compression ratio of strategies <= dFast, 290 * and improve speed of strategies > dFast. 291 * Special: value 0 means "use default hashLog". */ 292 chainLog = 103, /* Size of the multi-probe search table, as a power of 2. 293 * Resulting memory usage is (1 << (chainLog+2)). 294 * Must be clamped between ZSTD_CHAINLOG_MIN and ZSTD_CHAINLOG_MAX. 295 * Larger tables result in better and slower compression. 296 * This parameter is useless for "fast" strategy. 297 * It's still useful when using "dfast" strategy, 298 * in which case it defines a secondary probe table. 299 * Special: value 0 means "use default chainLog". */ 300 searchLog = 104, /* Number of search attempts, as a power of 2. 301 * More attempts result in better and slower compression. 302 * This parameter is useless for "fast" and "dFast" strategies. 303 * Special: value 0 means "use default searchLog". */ 304 minMatch = 105, /* Minimum size of searched matches. 305 * Note that Zstandard can still find matches of smaller size, 306 * it just tweaks its search algorithm to look for this size and larger. 307 * Larger values increase compression and decompression speed, but decrease ratio. 308 * Must be clamped between ZSTD_MINMATCH_MIN and ZSTD_MINMATCH_MAX. 309 * Note that currently, for all strategies < btopt, effective minimum is 4. 310 * , for all strategies > fast, effective maximum is 6. 311 * Special: value 0 means "use default minMatchLength". */ 312 targetLength = 106, /* Impact of this field depends on strategy. 313 * For strategies btopt, btultra & btultra2: 314 * Length of Match considered "good enough" to stop search. 315 * Larger values make compression stronger, and slower. 316 * For strategy fast: 317 * Distance between match sampling. 318 * Larger values make compression faster, and weaker. 319 * Special: value 0 means "use default targetLength". */ 320 strategy = 107, /* See ZSTD_strategy enum definition. 321 * The higher the value of selected strategy, the more complex it is, 322 * resulting in stronger and slower compression. 323 * Special: value 0 means "use default strategy". */ 324 /* LDM mode parameters */ 325 enableLongDistanceMatching = 160, /* Enable long distance matching. 326 * This parameter is designed to improve compression ratio 327 * for large inputs, by finding large matches at long distance. 328 * It increases memory usage and window size. 329 * Note: enabling this parameter increases default ZSTD_c_windowLog to 128 MB 330 * except when expressly set to a different value. 331 * Note: will be enabled by default if ZSTD_c_windowLog >= 128 MB and 332 * compression strategy >= ZSTD_btopt (== compression level 16+) */ 333 ldmHashLog = 161, /* Size of the table for long distance matching, as a power of 2. 334 * Larger values increase memory usage and compression ratio, 335 * but decrease compression speed. 336 * Must be clamped between ZSTD_HASHLOG_MIN and ZSTD_HASHLOG_MAX 337 * default: windowlog - 7. 338 * Special: value 0 means "automatically determine hashlog". */ 339 ldmMinMatch = 162, /* Minimum match size for long distance matcher. 340 * Larger/too small values usually decrease compression ratio. 341 * Must be clamped between ZSTD_LDM_MINMATCH_MIN and ZSTD_LDM_MINMATCH_MAX. 342 * Special: value 0 means "use default value" (default: 64). */ 343 ldmBucketSizeLog = 163, /* Log size of each bucket in the LDM hash table for collision resolution. 344 * Larger values improve collision resolution but decrease compression speed. 345 * The maximum value is ZSTD_LDM_BUCKETSIZELOG_MAX. 346 * Special: value 0 means "use default value" (default: 3). */ 347 ldmHashRateLog = 164, /* Frequency of inserting/looking up entries into the LDM hash table. 348 * Must be clamped between 0 and (ZSTD_WINDOWLOG_MAX - ZSTD_HASHLOG_MIN). 349 * Default is MAX(0, (windowLog - ldmHashLog)), optimizing hash table usage. 350 * Larger values improve compression speed. 351 * Deviating far from default value will likely result in a compression ratio decrease. 352 * Special: value 0 means "automatically determine hashRateLog". */ 353 354 /* frame parameters */ 355 contentSizeFlag = 200, /* Content size will be written into frame header _whenever known_ (default:1) 356 * Content size must be known at the beginning of compression. 357 * This is automatically the case when using ZSTD_compress2(), 358 * For streaming scenarios, content size must be provided with ZSTD_CCtx_setPledgedSrcSize() */ 359 checksumFlag = 201, /* A 32-bits checksum of content is written at end of frame (default:0) */ 360 dictIDFlag = 202, /* When applicable, dictionary's ID is written into frame header (default:1) */ 361 362 /* multi-threading parameters */ 363 /* These parameters are only active if multi-threading is enabled (compiled with build macro ZSTD_MULTITHREAD). 364 * Otherwise, trying to set any other value than default (0) will be a no-op and return an error. 365 * In a situation where it's unknown if the linked library supports multi-threading or not, 366 * setting ZSTD_c_nbWorkers to any value >= 1 and consulting the return value provides a quick way to check this property. 367 */ 368 nbWorkers = 400, /* Select how many threads will be spawned to compress in parallel. 369 * When nbWorkers >= 1, triggers asynchronous mode when invoking ZSTD_compressStream*() : 370 * ZSTD_compressStream*() consumes input and flush output if possible, but immediately gives back control to caller, 371 * while compression is performed in parallel, within worker thread(s). 372 * (note : a strong exception to this rule is when first invocation of ZSTD_compressStream2() sets ZSTD_e_end : 373 * in which case, ZSTD_compressStream2() delegates to ZSTD_compress2(), which is always a blocking call). 374 * More workers improve speed, but also increase memory usage. 375 * Default value is `0`, aka "single-threaded mode" : no worker is spawned, 376 * compression is performed inside Caller's thread, and all invocations are blocking */ 377 jobSize = 401, /* Size of a compression job. This value is enforced only when nbWorkers >= 1. 378 * Each compression job is completed in parallel, so this value can indirectly impact the nb of active threads. 379 * 0 means default, which is dynamically determined based on compression parameters. 380 * Job size must be a minimum of overlap size, or ZSTDMT_JOBSIZE_MIN (= 512 KB), whichever is largest. 381 * The minimum size is automatically and transparently enforced. */ 382 overlapLog = 402, /* Control the overlap size, as a fraction of window size. 383 * The overlap size is an amount of data reloaded from previous job at the beginning of a new job. 384 * It helps preserve compression ratio, while each job is compressed in parallel. 385 * This value is enforced only when nbWorkers >= 1. 386 * Larger values increase compression ratio, but decrease speed. 387 * Possible values range from 0 to 9 : 388 * - 0 means "default" : value will be determined by the library, depending on strategy 389 * - 1 means "no overlap" 390 * - 9 means "full overlap", using a full window size. 391 * Each intermediate rank increases/decreases load size by a factor 2 : 392 * 9: full window; 8: w/2; 7: w/4; 6: w/8; 5:w/16; 4: w/32; 3:w/64; 2:w/128; 1:no overlap; 0:default 393 * default value varies between 6 and 9, depending on strategy */ 394 395 /* note : additional experimental parameters are also available 396 * within the experimental section of the API. 397 * At the time of this writing, they include : 398 * ZSTD_c_rsyncable 399 * ZSTD_c_format 400 * ZSTD_c_forceMaxWindow 401 * ZSTD_c_forceAttachDict 402 * ZSTD_c_literalCompressionMode 403 * ZSTD_c_targetCBlockSize 404 * ZSTD_c_srcSizeHint 405 * ZSTD_c_enableDedicatedDictSearch 406 * ZSTD_c_stableInBuffer 407 * ZSTD_c_stableOutBuffer 408 * ZSTD_c_blockDelimiters 409 * ZSTD_c_validateSequences 410 * ZSTD_c_useBlockSplitter 411 * ZSTD_c_useRowMatchFinder 412 * Because they are not stable, it's necessary to define ZSTD_STATIC_LINKING_ONLY to access them. 413 * note : never ever use experimentalParam? names directly; 414 * also, the enums values themselves are unstable and can still change. 415 */ 416 experimentalParam1 = 500, 417 experimentalParam2 = 10, 418 experimentalParam3 = 1000, 419 experimentalParam4 = 1001, 420 experimentalParam5 = 1002, 421 experimentalParam6 = 1003, 422 experimentalParam7 = 1004, 423 experimentalParam8 = 1005, 424 experimentalParam9 = 1006, 425 experimentalParam10 = 1007, 426 experimentalParam11 = 1008, 427 experimentalParam12 = 1009, 428 experimentalParam13 = 1010, 429 experimentalParam14 = 1011, 430 experimentalParam15 = 1012 431 } 432 433 struct ZSTD_bounds 434 { 435 size_t error; 436 int lowerBound; 437 int upperBound; 438 } 439 440 /*! ZSTD_cParam_getBounds() : 441 * All parameters must belong to an interval with lower and upper bounds, 442 * otherwise they will either trigger an error or be automatically clamped. 443 * @return : a structure, ZSTD_bounds, which contains 444 * - an error status field, which must be tested using ZSTD_isError() 445 * - lower and upper bounds, both inclusive 446 */ 447 ZSTD_bounds ZSTD_cParam_getBounds(ZSTD_cParameter cParam); 448 449 /*! ZSTD_CCtx_setParameter() : 450 * Set one compression parameter, selected by enum ZSTD_cParameter. 451 * All parameters have valid bounds. Bounds can be queried using ZSTD_cParam_getBounds(). 452 * Providing a value beyond bound will either clamp it, or trigger an error (depending on parameter). 453 * Setting a parameter is generally only possible during frame initialization (before starting compression). 454 * Exception : when using multi-threading mode (nbWorkers >= 1), 455 * the following parameters can be updated _during_ compression (within same frame): 456 * => compressionLevel, hashLog, chainLog, searchLog, minMatch, targetLength and strategy. 457 * new parameters will be active for next job only (after a flush()). 458 * @return : an error code (which can be tested using ZSTD_isError()). 459 */ 460 size_t ZSTD_CCtx_setParameter(ZSTD_CCtx* cctx, ZSTD_cParameter param, int value); 461 462 /*! ZSTD_CCtx_setPledgedSrcSize() : 463 * Total input data size to be compressed as a single frame. 464 * Value will be written in frame header, unless if explicitly forbidden using ZSTD_c_contentSizeFlag. 465 * This value will also be controlled at end of frame, and trigger an error if not respected. 466 * @result : 0, or an error code (which can be tested with ZSTD_isError()). 467 * Note 1 : pledgedSrcSize==0 actually means zero, aka an empty frame. 468 * In order to mean "unknown content size", pass constant ZSTD_CONTENTSIZE_UNKNOWN. 469 * ZSTD_CONTENTSIZE_UNKNOWN is default value for any new frame. 470 * Note 2 : pledgedSrcSize is only valid once, for the next frame. 471 * It's discarded at the end of the frame, and replaced by ZSTD_CONTENTSIZE_UNKNOWN. 472 * Note 3 : Whenever all input data is provided and consumed in a single round, 473 * for example with ZSTD_compress2(), 474 * or invoking immediately ZSTD_compressStream2(,,,ZSTD_e_end), 475 * this value is automatically overridden by srcSize instead. 476 */ 477 size_t ZSTD_CCtx_setPledgedSrcSize(ZSTD_CCtx* cctx, cpp_ulonglong pledgedSrcSize); 478 479 enum ZSTD_ResetDirective 480 { 481 session_only = 1, 482 parameters = 2, 483 session_and_parameters = 3 484 } 485 486 /*! ZSTD_CCtx_reset() : 487 * There are 2 different things that can be reset, independently or jointly : 488 * - The session : will stop compressing current frame, and make CCtx ready to start a new one. 489 * Useful after an error, or to interrupt any ongoing compression. 490 * Any internal data not yet flushed is cancelled. 491 * Compression parameters and dictionary remain unchanged. 492 * They will be used to compress next frame. 493 * Resetting session never fails. 494 * - The parameters : changes all parameters back to "default". 495 * This removes any reference to any dictionary too. 496 * Parameters can only be changed between 2 sessions (i.e. no compression is currently ongoing) 497 * otherwise the reset fails, and function returns an error value (which can be tested using ZSTD_isError()) 498 * - Both : similar to resetting the session, followed by resetting parameters. 499 */ 500 size_t ZSTD_CCtx_reset(ZSTD_CCtx* cctx, ZSTD_ResetDirective reset); 501 502 /*! ZSTD_compress2() : 503 * Behave the same as ZSTD_compressCCtx(), but compression parameters are set using the advanced API. 504 * ZSTD_compress2() always starts a new frame. 505 * Should cctx hold data from a previously unfinished frame, everything about it is forgotten. 506 * - Compression parameters are pushed into CCtx before starting compression, using ZSTD_CCtx_set*() 507 * - The function is always blocking, returns when compression is completed. 508 * Hint : compression runs faster if `dstCapacity` >= `ZSTD_compressBound(srcSize)`. 509 * @return : compressed size written into `dst` (<= `dstCapacity), 510 * or an error code if it fails (which can be tested using ZSTD_isError()). 511 */ 512 size_t ZSTD_compress2(ZSTD_CCtx* cctx, 513 void* dst, size_t dstCapacity, 514 const(void)* src, size_t srcSize); 515 516 /*********************************************** 517 * Advanced decompression API (Requires v1.4.0+) 518 ************************************************/ 519 520 /* The advanced API pushes parameters one by one into an existing DCtx context. 521 * Parameters are sticky, and remain valid for all following frames 522 * using the same DCtx context. 523 * It's possible to reset parameters to default values using ZSTD_DCtx_reset(). 524 * Note : This API is compatible with existing ZSTD_decompressDCtx() and ZSTD_decompressStream(). 525 * Therefore, no new decompression function is necessary. 526 */ 527 528 enum ZSTD_dParameter 529 { 530 531 windowLogMax = 100, /* Select a size limit (in power of 2) beyond which 532 * the streaming API will refuse to allocate memory buffer 533 * in order to protect the host from unreasonable memory requirements. 534 * This parameter is only useful in streaming mode, since no internal buffer is allocated in single-pass mode. 535 * By default, a decompression context accepts window sizes <= (1 << ZSTD_WINDOWLOG_LIMIT_DEFAULT). 536 * Special: value 0 means "use default maximum windowLog". */ 537 538 /* note : additional experimental parameters are also available 539 * within the experimental section of the API. 540 * At the time of this writing, they include : 541 * ZSTD_d_format 542 * ZSTD_d_stableOutBuffer 543 * ZSTD_d_forceIgnoreChecksum 544 * ZSTD_d_refMultipleDDicts 545 * Because they are not stable, it's necessary to define ZSTD_STATIC_LINKING_ONLY to access them. 546 * note : never ever use experimentalParam? names directly 547 */ 548 experimentalParam1 = 1000, 549 experimentalParam2 = 1001, 550 experimentalParam3 = 1002, 551 experimentalParam4 = 1003 552 } 553 554 /*! ZSTD_dParam_getBounds() : 555 * All parameters must belong to an interval with lower and upper bounds, 556 * otherwise they will either trigger an error or be automatically clamped. 557 * @return : a structure, ZSTD_bounds, which contains 558 * - an error status field, which must be tested using ZSTD_isError() 559 * - both lower and upper bounds, inclusive 560 */ 561 ZSTD_bounds ZSTD_dParam_getBounds(ZSTD_dParameter dParam); 562 563 /*! ZSTD_DCtx_setParameter() : 564 * Set one compression parameter, selected by enum ZSTD_dParameter. 565 * All parameters have valid bounds. Bounds can be queried using ZSTD_dParam_getBounds(). 566 * Providing a value beyond bound will either clamp it, or trigger an error (depending on parameter). 567 * Setting a parameter is only possible during frame initialization (before starting decompression). 568 * @return : 0, or an error code (which can be tested using ZSTD_isError()). 569 */ 570 size_t ZSTD_DCtx_setParameter(ZSTD_DCtx* dctx, ZSTD_dParameter param, int value); 571 572 /*! ZSTD_DCtx_reset() : 573 * Return a DCtx to clean state. 574 * Session and parameters can be reset jointly or separately. 575 * Parameters can only be reset when no active frame is being decompressed. 576 * @return : 0, or an error code, which can be tested with ZSTD_isError() 577 */ 578 size_t ZSTD_DCtx_reset(ZSTD_DCtx* dctx, ZSTD_ResetDirective reset); 579 580 /**************************** 581 * Streaming 582 ****************************/ 583 584 struct ZSTD_inBuffer 585 { 586 const(void)* src; /**< start of input buffer */ 587 size_t size; /**< size of input buffer */ 588 size_t pos; /**< position where reading stopped. Will be updated. Necessarily 0 <= pos <= size */ 589 } 590 591 struct ZSTD_outBuffer 592 { 593 void* dst; /**< start of output buffer */ 594 size_t size; /**< size of output buffer */ 595 size_t pos; /**< position where writing stopped. Will be updated. Necessarily 0 <= pos <= size */ 596 } 597 598 /*-*********************************************************************** 599 * Streaming compression - HowTo 600 * 601 * A ZSTD_CStream object is required to track streaming operation. 602 * Use ZSTD_createCStream() and ZSTD_freeCStream() to create/release resources. 603 * ZSTD_CStream objects can be reused multiple times on consecutive compression operations. 604 * It is recommended to re-use ZSTD_CStream since it will play nicer with system's memory, by re-using already allocated memory. 605 * 606 * For parallel execution, use one separate ZSTD_CStream per thread. 607 * 608 * note : since v1.3.0, ZSTD_CStream and ZSTD_CCtx are the same thing. 609 * 610 * Parameters are sticky : when starting a new compression on the same context, 611 * it will re-use the same sticky parameters as previous compression session. 612 * When in doubt, it's recommended to fully initialize the context before usage. 613 * Use ZSTD_CCtx_reset() to reset the context and ZSTD_CCtx_setParameter(), 614 * ZSTD_CCtx_setPledgedSrcSize(), or ZSTD_CCtx_loadDictionary() and friends to 615 * set more specific parameters, the pledged source size, or load a dictionary. 616 * 617 * Use ZSTD_compressStream2() with ZSTD_e_continue as many times as necessary to 618 * consume input stream. The function will automatically update both `pos` 619 * fields within `input` and `output`. 620 * Note that the function may not consume the entire input, for example, because 621 * the output buffer is already full, in which case `input.pos < input.size`. 622 * The caller must check if input has been entirely consumed. 623 * If not, the caller must make some room to receive more compressed data, 624 * and then present again remaining input data. 625 * note: ZSTD_e_continue is guaranteed to make some forward progress when called, 626 * but doesn't guarantee maximal forward progress. This is especially relevant 627 * when compressing with multiple threads. The call won't block if it can 628 * consume some input, but if it can't it will wait for some, but not all, 629 * output to be flushed. 630 * @return : provides a minimum amount of data remaining to be flushed from internal buffers 631 * or an error code, which can be tested using ZSTD_isError(). 632 * 633 * At any moment, it's possible to flush whatever data might remain stuck within internal buffer, 634 * using ZSTD_compressStream2() with ZSTD_e_flush. `output->pos` will be updated. 635 * Note that, if `output->size` is too small, a single invocation with ZSTD_e_flush might not be enough (return code > 0). 636 * In which case, make some room to receive more compressed data, and call again ZSTD_compressStream2() with ZSTD_e_flush. 637 * You must continue calling ZSTD_compressStream2() with ZSTD_e_flush until it returns 0, at which point you can change the 638 * operation. 639 * note: ZSTD_e_flush will flush as much output as possible, meaning when compressing with multiple threads, it will 640 * block until the flush is complete or the output buffer is full. 641 * @return : 0 if internal buffers are entirely flushed, 642 * >0 if some data still present within internal buffer (the value is minimal estimation of remaining size), 643 * or an error code, which can be tested using ZSTD_isError(). 644 * 645 * Calling ZSTD_compressStream2() with ZSTD_e_end instructs to finish a frame. 646 * It will perform a flush and write frame epilogue. 647 * The epilogue is required for decoders to consider a frame completed. 648 * flush operation is the same, and follows same rules as calling ZSTD_compressStream2() with ZSTD_e_flush. 649 * You must continue calling ZSTD_compressStream2() with ZSTD_e_end until it returns 0, at which point you are free to 650 * start a new frame. 651 * note: ZSTD_e_end will flush as much output as possible, meaning when compressing with multiple threads, it will 652 * block until the flush is complete or the output buffer is full. 653 * @return : 0 if frame fully completed and fully flushed, 654 * >0 if some data still present within internal buffer (the value is minimal estimation of remaining size), 655 * or an error code, which can be tested using ZSTD_isError(). 656 * 657 * *******************************************************************/ 658 659 alias ZSTD_CStream = ZSTD_CCtx; /**< CCtx and CStream are now effectively same object (>= v1.3.0) */ 660 /* Continue to distinguish them for compatibility with older versions <= v1.2.0 */ 661 /*===== ZSTD_CStream management functions =====*/ 662 ZSTD_CStream* ZSTD_createCStream(); 663 size_t ZSTD_freeCStream(ZSTD_CStream* zcs); /* accept NULL pointer */ 664 665 /*===== Streaming compression functions =====*/ 666 enum ZSTD_EndDirective 667 { 668 _continue = 0, /* collect more data, encoder decides when to output compressed result, for optimal compression ratio */ 669 flush = 1, /* flush any data provided so far, 670 * it creates (at least) one new block, that can be decoded immediately on reception; 671 * frame will continue: any future data can still reference previously compressed data, improving compression. 672 * note : multithreaded compression will block to flush as much output as possible. */ 673 end = 2 /* flush any remaining data _and_ close current frame. 674 * note that frame is only closed after compressed data is fully flushed (return value == 0). 675 * After that point, any additional data starts a new frame. 676 * note : each frame is independent (does not reference any content from previous frame). 677 : note : multithreaded compression will block to flush as much output as possible. */ 678 } 679 680 /*! ZSTD_compressStream2() : Requires v1.4.0+ 681 * Behaves about the same as ZSTD_compressStream, with additional control on end directive. 682 * - Compression parameters are pushed into CCtx before starting compression, using ZSTD_CCtx_set*() 683 * - Compression parameters cannot be changed once compression is started (save a list of exceptions in multi-threading mode) 684 * - output->pos must be <= dstCapacity, input->pos must be <= srcSize 685 * - output->pos and input->pos will be updated. They are guaranteed to remain below their respective limit. 686 * - endOp must be a valid directive 687 * - When nbWorkers==0 (default), function is blocking : it completes its job before returning to caller. 688 * - When nbWorkers>=1, function is non-blocking : it copies a portion of input, distributes jobs to internal worker threads, flush to output whatever is available, 689 * and then immediately returns, just indicating that there is some data remaining to be flushed. 690 * The function nonetheless guarantees forward progress : it will return only after it reads or write at least 1+ byte. 691 * - 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. 692 * - @return provides a minimum amount of data remaining to be flushed from internal buffers 693 * or an error code, which can be tested using ZSTD_isError(). 694 * if @return != 0, flush is not fully completed, there is still some data left within internal buffers. 695 * This is useful for ZSTD_e_flush, since in this case more flushes are necessary to empty all buffers. 696 * For ZSTD_e_end, @return == 0 when internal buffers are fully flushed and frame is completed. 697 * - after a ZSTD_e_end directive, if internal buffer is not fully flushed (@return != 0), 698 * only ZSTD_e_end or ZSTD_e_flush operations are allowed. 699 * Before starting a new compression job, or changing compression parameters, 700 * it is required to fully flush internal buffers. 701 */ 702 size_t ZSTD_compressStream2(ZSTD_CCtx* cctx, 703 ZSTD_outBuffer* output, 704 ZSTD_inBuffer* input, 705 ZSTD_EndDirective endOp); 706 707 /* These buffer sizes are softly recommended. 708 * They are not required : ZSTD_compressStream*() happily accepts any buffer size, for both input and output. 709 * Respecting the recommended size just makes it a bit easier for ZSTD_compressStream*(), 710 * reducing the amount of memory shuffling and buffering, resulting in minor performance savings. 711 * 712 * However, note that these recommendations are from the perspective of a C caller program. 713 * If the streaming interface is invoked from some other language, 714 * especially managed ones such as Java or Go, through a foreign function interface such as jni or cgo, 715 * a major performance rule is to reduce crossing such interface to an absolute minimum. 716 * It's not rare that performance ends being spent more into the interface, rather than compression itself. 717 * In which cases, prefer using large buffers, as large as practical, 718 * for both input and output, to reduce the nb of roundtrips. 719 */ 720 size_t ZSTD_CStreamInSize(); /**< recommended size for input buffer */ 721 size_t ZSTD_CStreamOutSize(); /**< recommended size for output buffer. Guarantee to successfully flush at least one complete compressed block. */ 722 723 /* ***************************************************************************** 724 * This following is a legacy streaming API, available since v1.0+ . 725 * It can be replaced by ZSTD_CCtx_reset() and ZSTD_compressStream2(). 726 * It is redundant, but remains fully supported. 727 * Streaming in combination with advanced parameters and dictionary compression 728 * can only be used through the new API. 729 ******************************************************************************/ 730 731 /*! 732 * Equivalent to: 733 * 734 * ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only); 735 * ZSTD_CCtx_refCDict(zcs, NULL); // clear the dictionary (if any) 736 * ZSTD_CCtx_setParameter(zcs, ZSTD_c_compressionLevel, compressionLevel); 737 */ 738 size_t ZSTD_initCStream(ZSTD_CStream* zcs, int compressionLevel); 739 /*! 740 * Alternative for ZSTD_compressStream2(zcs, output, input, ZSTD_e_continue). 741 * NOTE: The return value is different. ZSTD_compressStream() returns a hint for 742 * the next read size (if non-zero and not an error). ZSTD_compressStream2() 743 * returns the minimum nb of bytes left to flush (if non-zero and not an error). 744 */ 745 size_t ZSTD_compressStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output, ZSTD_inBuffer* input); 746 /*! Equivalent to ZSTD_compressStream2(zcs, output, &emptyInput, ZSTD_e_flush). */ 747 size_t ZSTD_flushStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output); 748 /*! Equivalent to ZSTD_compressStream2(zcs, output, &emptyInput, ZSTD_e_end). */ 749 size_t ZSTD_endStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output); 750 751 /*-*************************************************************************** 752 * Streaming decompression - HowTo 753 * 754 * A ZSTD_DStream object is required to track streaming operations. 755 * Use ZSTD_createDStream() and ZSTD_freeDStream() to create/release resources. 756 * ZSTD_DStream objects can be re-used multiple times. 757 * 758 * Use ZSTD_initDStream() to start a new decompression operation. 759 * @return : recommended first input size 760 * Alternatively, use advanced API to set specific properties. 761 * 762 * Use ZSTD_decompressStream() repetitively to consume your input. 763 * The function will update both `pos` fields. 764 * If `input.pos < input.size`, some input has not been consumed. 765 * It's up to the caller to present again remaining data. 766 * The function tries to flush all data decoded immediately, respecting output buffer size. 767 * If `output.pos < output.size`, decoder has flushed everything it could. 768 * But if `output.pos == output.size`, there might be some data left within internal buffers., 769 * In which case, call ZSTD_decompressStream() again to flush whatever remains in the buffer. 770 * Note : with no additional input provided, amount of data flushed is necessarily <= ZSTD_BLOCKSIZE_MAX. 771 * @return : 0 when a frame is completely decoded and fully flushed, 772 * or an error code, which can be tested using ZSTD_isError(), 773 * or any other value > 0, which means there is still some decoding or flushing to do to complete current frame : 774 * the return value is a suggested next input size (just a hint for better latency) 775 * that will never request more than the remaining frame size. 776 * *******************************************************************************/ 777 778 alias ZSTD_DStream = ZSTD_DCtx; /**< DCtx and DStream are now effectively same object (>= v1.3.0) */ 779 /* For compatibility with versions <= v1.2.0, prefer differentiating them. */ 780 /*===== ZSTD_DStream management functions =====*/ 781 ZSTD_DStream* ZSTD_createDStream(); 782 size_t ZSTD_freeDStream(ZSTD_DStream* zds); /* accept NULL pointer */ 783 784 /*===== Streaming decompression functions =====*/ 785 786 /* This function is redundant with the advanced API and equivalent to: 787 * 788 * ZSTD_DCtx_reset(zds, ZSTD_reset_session_only); 789 * ZSTD_DCtx_refDDict(zds, NULL); 790 */ 791 size_t ZSTD_initDStream(ZSTD_DStream* zds); 792 793 size_t ZSTD_decompressStream(ZSTD_DStream* zds, ZSTD_outBuffer* output, ZSTD_inBuffer* input); 794 795 size_t ZSTD_DStreamInSize(); /*!< recommended size for input buffer */ 796 size_t ZSTD_DStreamOutSize(); /*!< recommended size for output buffer. Guarantee to successfully flush at least one complete block in all circumstances. */ 797 798 /************************** 799 * Simple dictionary API 800 ***************************/ 801 /*! ZSTD_compress_usingDict() : 802 * Compression at an explicit compression level using a Dictionary. 803 * A dictionary can be any arbitrary data segment (also called a prefix), 804 * or a buffer with specified information (see zdict.h). 805 * Note : This function loads the dictionary, resulting in significant startup delay. 806 * It's intended for a dictionary used only once. 807 * Note 2 : When `dict == NULL || dictSize < 8` no dictionary is used. */ 808 size_t ZSTD_compress_usingDict(ZSTD_CCtx* ctx, 809 void* dst, size_t dstCapacity, 810 const(void)* src, size_t srcSize, 811 const(void)* dict, size_t dictSize, 812 int compressionLevel); 813 814 /*! ZSTD_decompress_usingDict() : 815 * Decompression using a known Dictionary. 816 * Dictionary must be identical to the one used during compression. 817 * Note : This function loads the dictionary, resulting in significant startup delay. 818 * It's intended for a dictionary used only once. 819 * Note : When `dict == NULL || dictSize < 8` no dictionary is used. */ 820 size_t ZSTD_decompress_usingDict(ZSTD_DCtx* dctx, 821 void* dst, size_t dstCapacity, 822 const(void)* src, size_t srcSize, 823 const(void)* dict, size_t dictSize); 824 825 /*********************************** 826 * Bulk processing dictionary API 827 **********************************/ 828 struct ZSTD_CDict; 829 830 /*! ZSTD_createCDict() : 831 * When compressing multiple messages or blocks using the same dictionary, 832 * it's recommended to digest the dictionary only once, since it's a costly operation. 833 * ZSTD_createCDict() will create a state from digesting a dictionary. 834 * The resulting state can be used for future compression operations with very limited startup cost. 835 * ZSTD_CDict can be created once and shared by multiple threads concurrently, since its usage is read-only. 836 * @dictBuffer can be released after ZSTD_CDict creation, because its content is copied within CDict. 837 * Note 1 : Consider experimental function `ZSTD_createCDict_byReference()` if you prefer to not duplicate @dictBuffer content. 838 * Note 2 : A ZSTD_CDict can be created from an empty @dictBuffer, 839 * in which case the only thing that it transports is the @compressionLevel. 840 * This can be useful in a pipeline featuring ZSTD_compress_usingCDict() exclusively, 841 * expecting a ZSTD_CDict parameter with any data, including those without a known dictionary. */ 842 ZSTD_CDict* ZSTD_createCDict(const(void)* dictBuffer, size_t dictSize, 843 int compressionLevel); 844 845 /*! ZSTD_freeCDict() : 846 * Function frees memory allocated by ZSTD_createCDict(). 847 * If a NULL pointer is passed, no operation is performed. */ 848 size_t ZSTD_freeCDict(ZSTD_CDict* CDict); 849 850 /*! ZSTD_compress_usingCDict() : 851 * Compression using a digested Dictionary. 852 * Recommended when same dictionary is used multiple times. 853 * Note : compression level is _decided at dictionary creation time_, 854 * and frame parameters are hardcoded (dictID=yes, contentSize=yes, checksum=no) */ 855 size_t ZSTD_compress_usingCDict(ZSTD_CCtx* cctx, 856 void* dst, size_t dstCapacity, 857 const(void)* src, size_t srcSize, 858 const(ZSTD_CDict)* cdict); 859 860 struct ZSTD_DDict; 861 862 /*! ZSTD_createDDict() : 863 * Create a digested dictionary, ready to start decompression operation without startup delay. 864 * dictBuffer can be released after DDict creation, as its content is copied inside DDict. */ 865 ZSTD_DDict* ZSTD_createDDict(const(void)* dictBuffer, size_t dictSize); 866 867 /*! ZSTD_freeDDict() : 868 * Function frees memory allocated with ZSTD_createDDict() 869 * If a NULL pointer is passed, no operation is performed. */ 870 size_t ZSTD_freeDDict(ZSTD_DDict* ddict); 871 872 /*! ZSTD_decompress_usingDDict() : 873 * Decompression using a digested Dictionary. 874 * Recommended when same dictionary is used multiple times. */ 875 size_t ZSTD_decompress_usingDDict(ZSTD_DCtx* dctx, 876 void* dst, size_t dstCapacity, 877 const(void)* src, size_t srcSize, 878 const(ZSTD_DDict)* ddict); 879 880 /******************************** 881 * Dictionary helper functions 882 *******************************/ 883 884 /*! ZSTD_getDictID_fromDict() : Requires v1.4.0+ 885 * Provides the dictID stored within dictionary. 886 * if @return == 0, the dictionary is not conformant with Zstandard specification. 887 * It can still be loaded, but as a content-only dictionary. */ 888 uint ZSTD_getDictID_fromDict(const(void)* dict, size_t dictSize); 889 890 /*! ZSTD_getDictID_fromCDict() : Requires v1.5.0+ 891 * Provides the dictID of the dictionary loaded into `cdict`. 892 * If @return == 0, the dictionary is not conformant to Zstandard specification, or empty. 893 * Non-conformant dictionaries can still be loaded, but as content-only dictionaries. */ 894 uint ZSTD_getDictID_fromCDict(const(ZSTD_CDict)* cdict); 895 896 /*! ZSTD_getDictID_fromDDict() : Requires v1.4.0+ 897 * Provides the dictID of the dictionary loaded into `ddict`. 898 * If @return == 0, the dictionary is not conformant to Zstandard specification, or empty. 899 * Non-conformant dictionaries can still be loaded, but as content-only dictionaries. */ 900 uint ZSTD_getDictID_fromDDict(const(ZSTD_DDict)* ddict); 901 902 /*! ZSTD_getDictID_fromFrame() : Requires v1.4.0+ 903 * Provides the dictID required to decompressed the frame stored within `src`. 904 * If @return == 0, the dictID could not be decoded. 905 * This could for one of the following reasons : 906 * - The frame does not require a dictionary to be decoded (most common case). 907 * - The frame was built with dictID intentionally removed. Whatever dictionary is necessary is a hidden information. 908 * Note : this use case also happens when using a non-conformant dictionary. 909 * - `srcSize` is too small, and as a result, the frame header could not be decoded (only possible if `srcSize < ZSTD_FRAMEHEADERSIZE_MAX`). 910 * - This is not a Zstandard frame. 911 * When identifying the exact failure cause, it's possible to use ZSTD_getFrameHeader(), which will provide a more precise error code. */ 912 uint ZSTD_getDictID_fromFrame(const(void)* src, size_t srcSize); 913 914 /******************************************************************************* 915 * Advanced dictionary and prefix API (Requires v1.4.0+) 916 * 917 * This API allows dictionaries to be used with ZSTD_compress2(), 918 * ZSTD_compressStream2(), and ZSTD_decompressDCtx(). Dictionaries are sticky, and 919 * only reset with the context is reset with ZSTD_reset_parameters or 920 * ZSTD_reset_session_and_parameters. Prefixes are single-use. 921 ******************************************************************************/ 922 923 /*! ZSTD_CCtx_loadDictionary() : Requires v1.4.0+ 924 * Create an internal CDict from `dict` buffer. 925 * Decompression will have to use same dictionary. 926 * @result : 0, or an error code (which can be tested with ZSTD_isError()). 927 * Special: Loading a NULL (or 0-size) dictionary invalidates previous dictionary, 928 * meaning "return to no-dictionary mode". 929 * Note 1 : Dictionary is sticky, it will be used for all future compressed frames. 930 * To return to "no-dictionary" situation, load a NULL dictionary (or reset parameters). 931 * Note 2 : Loading a dictionary involves building tables. 932 * It's also a CPU consuming operation, with non-negligible impact on latency. 933 * Tables are dependent on compression parameters, and for this reason, 934 * compression parameters can no longer be changed after loading a dictionary. 935 * Note 3 :`dict` content will be copied internally. 936 * Use experimental ZSTD_CCtx_loadDictionary_byReference() to reference content instead. 937 * In such a case, dictionary buffer must outlive its users. 938 * Note 4 : Use ZSTD_CCtx_loadDictionary_advanced() 939 * to precisely select how dictionary content must be interpreted. */ 940 size_t ZSTD_CCtx_loadDictionary(ZSTD_CCtx* cctx, const(void)* dict, size_t dictSize); 941 942 /*! ZSTD_CCtx_refCDict() : Requires v1.4.0+ 943 * Reference a prepared dictionary, to be used for all next compressed frames. 944 * Note that compression parameters are enforced from within CDict, 945 * and supersede any compression parameter previously set within CCtx. 946 * The parameters ignored are labelled as "superseded-by-cdict" in the ZSTD_cParameter enum docs. 947 * The ignored parameters will be used again if the CCtx is returned to no-dictionary mode. 948 * The dictionary will remain valid for future compressed frames using same CCtx. 949 * @result : 0, or an error code (which can be tested with ZSTD_isError()). 950 * Special : Referencing a NULL CDict means "return to no-dictionary mode". 951 * Note 1 : Currently, only one dictionary can be managed. 952 * Referencing a new dictionary effectively "discards" any previous one. 953 * Note 2 : CDict is just referenced, its lifetime must outlive its usage within CCtx. */ 954 size_t ZSTD_CCtx_refCDict(ZSTD_CCtx* cctx, const(ZSTD_CDict)* cdict); 955 956 /*! ZSTD_CCtx_refPrefix() : Requires v1.4.0+ 957 * Reference a prefix (single-usage dictionary) for next compressed frame. 958 * A prefix is **only used once**. Tables are discarded at end of frame (ZSTD_e_end). 959 * Decompression will need same prefix to properly regenerate data. 960 * Compressing with a prefix is similar in outcome as performing a diff and compressing it, 961 * but performs much faster, especially during decompression (compression speed is tunable with compression level). 962 * @result : 0, or an error code (which can be tested with ZSTD_isError()). 963 * Special: Adding any prefix (including NULL) invalidates any previous prefix or dictionary 964 * Note 1 : Prefix buffer is referenced. It **must** outlive compression. 965 * Its content must remain unmodified during compression. 966 * Note 2 : If the intention is to diff some large src data blob with some prior version of itself, 967 * ensure that the window size is large enough to contain the entire source. 968 * See ZSTD_c_windowLog. 969 * Note 3 : Referencing a prefix involves building tables, which are dependent on compression parameters. 970 * It's a CPU consuming operation, with non-negligible impact on latency. 971 * If there is a need to use the same prefix multiple times, consider loadDictionary instead. 972 * Note 4 : By default, the prefix is interpreted as raw content (ZSTD_dct_rawContent). 973 * Use experimental ZSTD_CCtx_refPrefix_advanced() to alter dictionary interpretation. */ 974 size_t ZSTD_CCtx_refPrefix(ZSTD_CCtx* cctx, 975 const(void)* prefix, size_t prefixSize); 976 977 /*! ZSTD_DCtx_loadDictionary() : Requires v1.4.0+ 978 * Create an internal DDict from dict buffer, 979 * to be used to decompress next frames. 980 * The dictionary remains valid for all future frames, until explicitly invalidated. 981 * @result : 0, or an error code (which can be tested with ZSTD_isError()). 982 * Special : Adding a NULL (or 0-size) dictionary invalidates any previous dictionary, 983 * meaning "return to no-dictionary mode". 984 * Note 1 : Loading a dictionary involves building tables, 985 * which has a non-negligible impact on CPU usage and latency. 986 * It's recommended to "load once, use many times", to amortize the cost 987 * Note 2 :`dict` content will be copied internally, so `dict` can be released after loading. 988 * Use ZSTD_DCtx_loadDictionary_byReference() to reference dictionary content instead. 989 * Note 3 : Use ZSTD_DCtx_loadDictionary_advanced() to take control of 990 * how dictionary content is loaded and interpreted. 991 */ 992 size_t ZSTD_DCtx_loadDictionary(ZSTD_DCtx* dctx, const(void)* dict, size_t dictSize); 993 994 /*! ZSTD_DCtx_refDDict() : Requires v1.4.0+ 995 * Reference a prepared dictionary, to be used to decompress next frames. 996 * The dictionary remains active for decompression of future frames using same DCtx. 997 * 998 * If called with ZSTD_d_refMultipleDDicts enabled, repeated calls of this function 999 * will store the DDict references in a table, and the DDict used for decompression 1000 * will be determined at decompression time, as per the dict ID in the frame. 1001 * The memory for the table is allocated on the first call to refDDict, and can be 1002 * freed with ZSTD_freeDCtx(). 1003 * 1004 * @result : 0, or an error code (which can be tested with ZSTD_isError()). 1005 * Note 1 : Currently, only one dictionary can be managed. 1006 * Referencing a new dictionary effectively "discards" any previous one. 1007 * Special: referencing a NULL DDict means "return to no-dictionary mode". 1008 * Note 2 : DDict is just referenced, its lifetime must outlive its usage from DCtx. 1009 */ 1010 size_t ZSTD_DCtx_refDDict(ZSTD_DCtx* dctx, const(ZSTD_DDict)* ddict); 1011 1012 /*! ZSTD_DCtx_refPrefix() : Requires v1.4.0+ 1013 * Reference a prefix (single-usage dictionary) to decompress next frame. 1014 * This is the reverse operation of ZSTD_CCtx_refPrefix(), 1015 * and must use the same prefix as the one used during compression. 1016 * Prefix is **only used once**. Reference is discarded at end of frame. 1017 * End of frame is reached when ZSTD_decompressStream() returns 0. 1018 * @result : 0, or an error code (which can be tested with ZSTD_isError()). 1019 * Note 1 : Adding any prefix (including NULL) invalidates any previously set prefix or dictionary 1020 * Note 2 : Prefix buffer is referenced. It **must** outlive decompression. 1021 * Prefix buffer must remain unmodified up to the end of frame, 1022 * reached when ZSTD_decompressStream() returns 0. 1023 * Note 3 : By default, the prefix is treated as raw content (ZSTD_dct_rawContent). 1024 * Use ZSTD_CCtx_refPrefix_advanced() to alter dictMode (Experimental section) 1025 * Note 4 : Referencing a raw content prefix has almost no cpu nor memory cost. 1026 * A full dictionary is more costly, as it requires building tables. 1027 */ 1028 size_t ZSTD_DCtx_refPrefix(ZSTD_DCtx* dctx, 1029 const(void)* prefix, size_t prefixSize); 1030 1031 /* === Memory management === */ 1032 1033 /*! ZSTD_sizeof_*() : Requires v1.4.0+ 1034 * These functions give the _current_ memory usage of selected object. 1035 * Note that object memory usage can evolve (increase or decrease) over time. */ 1036 size_t ZSTD_sizeof_CCtx(const(ZSTD_CCtx)* cctx); 1037 size_t ZSTD_sizeof_DCtx(const(ZSTD_DCtx)* dctx); 1038 size_t ZSTD_sizeof_CStream(const(ZSTD_CStream)* zcs); 1039 size_t ZSTD_sizeof_DStream(const(ZSTD_DStream)* zds); 1040 size_t ZSTD_sizeof_CDict(const(ZSTD_CDict)* cdict); 1041 size_t ZSTD_sizeof_DDict(const(ZSTD_DDict)* ddict); 1042 1043 /* ************************************************************************************** 1044 * ADVANCED AND EXPERIMENTAL FUNCTIONS 1045 **************************************************************************************** 1046 * The definitions in the following section are considered experimental. 1047 * They are provided for advanced scenarios. 1048 * They should never be used with a dynamic library, as prototypes may change in the future. 1049 * Use them only in association with static linking. 1050 * ***************************************************************************************/ 1051 1052 /**************************************************************************************** 1053 * experimental API (static linking only) 1054 **************************************************************************************** 1055 * The following symbols and constants 1056 * are not planned to join "stable API" status in the near future. 1057 * They can still change in future versions. 1058 * Some of them are planned to remain in the static_only section indefinitely. 1059 * Some of them might be removed in the future (especially when redundant with existing stable functions) 1060 * ***************************************************************************************/ 1061 1062 extern (D) 1063 auto ZSTD_FRAMEHEADERSIZE_PREFIX(F)(F format) 1064 { 1065 return format == ZSTD_f_std1 ? 5 : 1; 1066 } 1067 1068 extern (D) 1069 auto ZSTD_FRAMEHEADERSIZE_MIN(F)(F format) 1070 { 1071 return format == ZSTD_f_std1 ? 6 : 2; 1072 } 1073 1074 enum ZSTD_FRAMEHEADERSIZE_MAX = 18 /* can be useful for static allocation */ ; 1075 enum ZSTD_SKIPPABLEHEADERSIZE = 8; 1076 1077 /* compression parameter bounds */ 1078 enum ZSTD_WINDOWLOG_MAX_32 = 30; 1079 enum ZSTD_WINDOWLOG_MAX_64 = 31; 1080 enum ZSTD_CHAINLOG_MAX_32 = 29; 1081 enum ZSTD_CHAINLOG_MAX_64 = 30; 1082 static if (size_t.sizeof == 4) 1083 { 1084 enum ZSTD_WINDOWLOG_MAX = ZSTD_WINDOWLOG_MAX_32; 1085 enum ZSTD_CHAINLOG_MAX = ZSTD_CHAINLOG_MAX_32; 1086 } 1087 else 1088 { 1089 enum ZSTD_WINDOWLOG_MAX = ZSTD_WINDOWLOG_MAX_64; 1090 enum ZSTD_CHAINLOG_MAX = ZSTD_CHAINLOG_MAX_64; 1091 } 1092 enum ZSTD_WINDOWLOG_MIN = 10; 1093 enum ZSTD_HASHLOG_MAX = ((ZSTD_WINDOWLOG_MAX < 30) ? ZSTD_WINDOWLOG_MAX : 30); 1094 enum ZSTD_HASHLOG_MIN = 6; 1095 enum ZSTD_CHAINLOG_MIN = ZSTD_HASHLOG_MIN; 1096 enum ZSTD_SEARCHLOG_MAX = (ZSTD_WINDOWLOG_MAX - 1); 1097 enum ZSTD_SEARCHLOG_MIN = 1; 1098 enum ZSTD_MINMATCH_MAX = 7 /* only for ZSTD_fast, other strategies are limited to 6 */ ; 1099 enum ZSTD_MINMATCH_MIN = 3 /* only for ZSTD_btopt+, faster strategies are limited to 4 */ ; 1100 enum ZSTD_TARGETLENGTH_MAX = ZSTD_BLOCKSIZE_MAX; 1101 enum ZSTD_TARGETLENGTH_MIN = 0 /* note : comparing this constant to an unsigned results in a tautological test */ ; 1102 enum ZSTD_STRATEGY_MIN = ZSTD_strategy.fast; 1103 enum ZSTD_STRATEGY_MAX = ZSTD_strategy.btultra2; 1104 1105 enum ZSTD_OVERLAPLOG_MIN = 0; 1106 enum ZSTD_OVERLAPLOG_MAX = 9; 1107 1108 enum ZSTD_WINDOWLOG_LIMIT_DEFAULT = 27; /* by default, the streaming decoder will refuse any frame 1109 * requiring larger than (1<<ZSTD_WINDOWLOG_LIMIT_DEFAULT) window size, 1110 * to preserve host's memory from unreasonable requirements. 1111 * This limit can be overridden using ZSTD_DCtx_setParameter(,ZSTD_d_windowLogMax,). 1112 * The limit does not apply for one-pass decoders (such as ZSTD_decompress()), since no additional memory is allocated */ 1113 1114 /* LDM parameter bounds */ 1115 enum ZSTD_LDM_HASHLOG_MIN = ZSTD_HASHLOG_MIN; 1116 enum ZSTD_LDM_HASHLOG_MAX = ZSTD_HASHLOG_MAX; 1117 enum ZSTD_LDM_MINMATCH_MIN = 4; 1118 enum ZSTD_LDM_MINMATCH_MAX = 4096; 1119 enum ZSTD_LDM_BUCKETSIZELOG_MIN = 1; 1120 enum ZSTD_LDM_BUCKETSIZELOG_MAX = 8; 1121 enum ZSTD_LDM_HASHRATELOG_MIN = 0; 1122 enum ZSTD_LDM_HASHRATELOG_MAX = (ZSTD_WINDOWLOG_MAX - ZSTD_HASHLOG_MIN); 1123 1124 /* Advanced parameter bounds */ 1125 enum ZSTD_TARGETCBLOCKSIZE_MIN = 64; 1126 enum ZSTD_TARGETCBLOCKSIZE_MAX = ZSTD_BLOCKSIZE_MAX; 1127 enum ZSTD_SRCSIZEHINT_MIN = 0; 1128 enum ZSTD_SRCSIZEHINT_MAX = int.max; 1129 1130 /* internal */ 1131 enum ZSTD_HASHLOG3_MAX = 17; 1132 1133 /* --- Advanced types --- */ 1134 1135 struct ZSTD_CCtx_params; 1136 1137 struct ZSTD_Sequence 1138 { 1139 uint offset; /* The offset of the match. (NOT the same as the offset code) 1140 * If offset == 0 and matchLength == 0, this sequence represents the last 1141 * literals in the block of litLength size. 1142 */ 1143 1144 uint litLength; /* Literal length of the sequence. */ 1145 uint matchLength; /* Match length of the sequence. */ 1146 1147 /* Note: Users of this API may provide a sequence with matchLength == litLength == offset == 0. 1148 * In this case, we will treat the sequence as a marker for a block boundary. 1149 */ 1150 1151 uint rep; /* Represents which repeat offset is represented by the field 'offset'. 1152 * Ranges from [0, 3]. 1153 * 1154 * Repeat offsets are essentially previous offsets from previous sequences sorted in 1155 * recency order. For more detail, see doc/zstd_compression_format.md 1156 * 1157 * If rep == 0, then 'offset' does not contain a repeat offset. 1158 * If rep > 0: 1159 * If litLength != 0: 1160 * rep == 1 --> offset == repeat_offset_1 1161 * rep == 2 --> offset == repeat_offset_2 1162 * rep == 3 --> offset == repeat_offset_3 1163 * If litLength == 0: 1164 * rep == 1 --> offset == repeat_offset_2 1165 * rep == 2 --> offset == repeat_offset_3 1166 * rep == 3 --> offset == repeat_offset_1 - 1 1167 * 1168 * Note: This field is optional. ZSTD_generateSequences() will calculate the value of 1169 * 'rep', but repeat offsets do not necessarily need to be calculated from an external 1170 * sequence provider's perspective. For example, ZSTD_compressSequences() does not 1171 * use this 'rep' field at all (as of now). 1172 */ 1173 } 1174 1175 struct ZSTD_compressionParameters 1176 { 1177 uint windowLog; /**< largest match distance : larger == more compression, more memory needed during decompression */ 1178 uint chainLog; /**< fully searched segment : larger == more compression, slower, more memory (useless for fast) */ 1179 uint hashLog; /**< dispatch table : larger == faster, more memory */ 1180 uint searchLog; /**< nb of searches : larger == more compression, slower */ 1181 uint minMatch; /**< match length searched : larger == faster decompression, sometimes less compression */ 1182 uint targetLength; /**< acceptable match size for optimal parser (only) : larger == more compression, slower */ 1183 ZSTD_strategy strategy; /**< see ZSTD_strategy definition above */ 1184 } 1185 1186 struct ZSTD_frameParameters 1187 { 1188 int contentSizeFlag; /**< 1: content size will be in frame header (when known) */ 1189 int checksumFlag; /**< 1: generate a 32-bits checksum using XXH64 algorithm at end of frame, for error detection */ 1190 int noDictIDFlag; /**< 1: no dictID will be saved into frame header (dictID is only useful for dictionary compression) */ 1191 } 1192 1193 struct ZSTD_parameters 1194 { 1195 ZSTD_compressionParameters cParams; 1196 ZSTD_frameParameters fParams; 1197 } 1198 1199 enum ZSTD_dictContentType_e 1200 { 1201 _auto = 0, /* dictionary is "full" when starting with ZSTD_MAGIC_DICTIONARY, otherwise it is "rawContent" */ 1202 rawContent = 1, /* ensures dictionary is always loaded as rawContent, even if it starts with ZSTD_MAGIC_DICTIONARY */ 1203 fullDict = 2 /* refuses to load a dictionary if it does not respect Zstandard's specification, starting with ZSTD_MAGIC_DICTIONARY */ 1204 } 1205 1206 enum ZSTD_dictLoadMethod_e 1207 { 1208 byCopy = 0, /**< Copy dictionary content internally */ 1209 byRef = 1 /**< Reference dictionary content -- the dictionary buffer must outlive its users. */ 1210 } 1211 1212 enum ZSTD_format_e 1213 { 1214 zstd1 = 0, /* zstd frame format, specified in zstd_compression_format.md (default) */ 1215 zstd1_magicless = 1 /* Variant of zstd frame format, without initial 4-bytes magic number. 1216 * Useful to save 4 bytes per generated frame. 1217 * Decoder cannot recognise automatically this format, requiring this instruction. */ 1218 } 1219 1220 enum ZSTD_forceIgnoreChecksum_e 1221 { 1222 /* Note: this enum controls ZSTD_d_forceIgnoreChecksum */ 1223 validateChecksum = 0, 1224 ignoreChecksum = 1 1225 } 1226 1227 enum ZSTD_refMultipleDDicts_e 1228 { 1229 /* Note: this enum controls ZSTD_d_refMultipleDDicts */ 1230 refSingleDDict = 0, 1231 refMultipleDDicts = 1 1232 } 1233 1234 enum ZSTD_dictAttachPref_e 1235 { 1236 /* Note: this enum and the behavior it controls are effectively internal 1237 * implementation details of the compressor. They are expected to continue 1238 * to evolve and should be considered only in the context of extremely 1239 * advanced performance tuning. 1240 * 1241 * Zstd currently supports the use of a CDict in three ways: 1242 * 1243 * - The contents of the CDict can be copied into the working context. This 1244 * means that the compression can search both the dictionary and input 1245 * while operating on a single set of internal tables. This makes 1246 * the compression faster per-byte of input. However, the initial copy of 1247 * the CDict's tables incurs a fixed cost at the beginning of the 1248 * compression. For small compressions (< 8 KB), that copy can dominate 1249 * the cost of the compression. 1250 * 1251 * - The CDict's tables can be used in-place. In this model, compression is 1252 * slower per input byte, because the compressor has to search two sets of 1253 * tables. However, this model incurs no start-up cost (as long as the 1254 * working context's tables can be reused). For small inputs, this can be 1255 * faster than copying the CDict's tables. 1256 * 1257 * - The CDict's tables are not used at all, and instead we use the working 1258 * context alone to reload the dictionary and use params based on the source 1259 * size. See ZSTD_compress_insertDictionary() and ZSTD_compress_usingDict(). 1260 * This method is effective when the dictionary sizes are very small relative 1261 * to the input size, and the input size is fairly large to begin with. 1262 * 1263 * Zstd has a simple internal heuristic that selects which strategy to use 1264 * at the beginning of a compression. However, if experimentation shows that 1265 * Zstd is making poor choices, it is possible to override that choice with 1266 * this enum. 1267 */ 1268 dictDefaultAttach = 0, /* Use the default heuristic. */ 1269 dictForceAttach = 1, /* Never copy the dictionary. */ 1270 dictForceCopy = 2, /* Always copy the dictionary. */ 1271 dictForceLoad = 3 /* Always reload the dictionary */ 1272 } 1273 1274 enum ZSTD_literalCompressionMode_e 1275 { 1276 _auto = 0, /**< Automatically determine the compression mode based on the compression level. 1277 * Negative compression levels will be uncompressed, and positive compression 1278 * levels will be compressed. */ 1279 huffman = 1, /**< Always attempt Huffman compression. Uncompressed literals will still be 1280 * emitted if Huffman compression is not profitable. */ 1281 uncompressed = 2 /**< Always emit uncompressed literals. */ 1282 } 1283 1284 enum ZSTD_paramSwitch_e 1285 { 1286 /* Note: This enum controls features which are conditionally beneficial. Zstd typically will make a final 1287 * decision on whether or not to enable the feature (ZSTD_ps_auto), but setting the switch to ZSTD_ps_enable 1288 * or ZSTD_ps_disable allow for a force enable/disable the feature. 1289 */ 1290 _auto = 0, /* Let the library automatically determine whether the feature shall be enabled */ 1291 enable = 1, /* Force-enable the feature */ 1292 disable = 2 /* Do not use the feature */ 1293 } 1294 1295 /*************************************** 1296 * Frame size functions 1297 ***************************************/ 1298 1299 /*! ZSTD_findDecompressedSize() : 1300 * `src` should point to the start of a series of ZSTD encoded and/or skippable frames 1301 * `srcSize` must be the _exact_ size of this series 1302 * (i.e. there should be a frame boundary at `src + srcSize`) 1303 * @return : - decompressed size of all data in all successive frames 1304 * - if the decompressed size cannot be determined: ZSTD_CONTENTSIZE_UNKNOWN 1305 * - if an error occurred: ZSTD_CONTENTSIZE_ERROR 1306 * 1307 * note 1 : decompressed size is an optional field, that may not be present, especially in streaming mode. 1308 * When `return==ZSTD_CONTENTSIZE_UNKNOWN`, data to decompress could be any size. 1309 * In which case, it's necessary to use streaming mode to decompress data. 1310 * note 2 : decompressed size is always present when compression is done with ZSTD_compress() 1311 * note 3 : decompressed size can be very large (64-bits value), 1312 * potentially larger than what local system can handle as a single memory segment. 1313 * In which case, it's necessary to use streaming mode to decompress data. 1314 * note 4 : If source is untrusted, decompressed size could be wrong or intentionally modified. 1315 * Always ensure result fits within application's authorized limits. 1316 * Each application can set its own limits. 1317 * note 5 : ZSTD_findDecompressedSize handles multiple frames, and so it must traverse the input to 1318 * read each contained frame header. This is fast as most of the data is skipped, 1319 * however it does mean that all frame data must be present and valid. */ 1320 cpp_ulonglong ZSTD_findDecompressedSize(const(void)* src, size_t srcSize); 1321 1322 /*! ZSTD_decompressBound() : 1323 * `src` should point to the start of a series of ZSTD encoded and/or skippable frames 1324 * `srcSize` must be the _exact_ size of this series 1325 * (i.e. there should be a frame boundary at `src + srcSize`) 1326 * @return : - upper-bound for the decompressed size of all data in all successive frames 1327 * - if an error occurred: ZSTD_CONTENTSIZE_ERROR 1328 * 1329 * note 1 : an error can occur if `src` contains an invalid or incorrectly formatted frame. 1330 * note 2 : the upper-bound is exact when the decompressed size field is available in every ZSTD encoded frame of `src`. 1331 * in this case, `ZSTD_findDecompressedSize` and `ZSTD_decompressBound` return the same value. 1332 * note 3 : when the decompressed size field isn't available, the upper-bound for that frame is calculated by: 1333 * upper-bound = # blocks * min(128 KB, Window_Size) 1334 */ 1335 cpp_ulonglong ZSTD_decompressBound(const(void)* src, size_t srcSize); 1336 1337 /*! ZSTD_frameHeaderSize() : 1338 * srcSize must be >= ZSTD_FRAMEHEADERSIZE_PREFIX. 1339 * @return : size of the Frame Header, 1340 * or an error code (if srcSize is too small) */ 1341 size_t ZSTD_frameHeaderSize(const(void)* src, size_t srcSize); 1342 1343 enum ZSTD_sequenceFormat_e 1344 { 1345 noBlockDelimiters = 0, /* Representation of ZSTD_Sequence has no block delimiters, sequences only */ 1346 explicitBlockDelimiters = 1 /* Representation of ZSTD_Sequence contains explicit block delimiters */ 1347 } 1348 1349 /*! ZSTD_generateSequences() : 1350 * Generate sequences using ZSTD_compress2, given a source buffer. 1351 * 1352 * Each block will end with a dummy sequence 1353 * with offset == 0, matchLength == 0, and litLength == length of last literals. 1354 * litLength may be == 0, and if so, then the sequence of (of: 0 ml: 0 ll: 0) 1355 * simply acts as a block delimiter. 1356 * 1357 * zc can be used to insert custom compression params. 1358 * This function invokes ZSTD_compress2 1359 * 1360 * The output of this function can be fed into ZSTD_compressSequences() with CCtx 1361 * setting of ZSTD_c_blockDelimiters as ZSTD_sf_explicitBlockDelimiters 1362 * @return : number of sequences generated 1363 */ 1364 1365 size_t ZSTD_generateSequences(ZSTD_CCtx* zc, ZSTD_Sequence* outSeqs, 1366 size_t outSeqsSize, const(void)* src, size_t srcSize); 1367 1368 /*! ZSTD_mergeBlockDelimiters() : 1369 * Given an array of ZSTD_Sequence, remove all sequences that represent block delimiters/last literals 1370 * by merging them into into the literals of the next sequence. 1371 * 1372 * As such, the final generated result has no explicit representation of block boundaries, 1373 * and the final last literals segment is not represented in the sequences. 1374 * 1375 * The output of this function can be fed into ZSTD_compressSequences() with CCtx 1376 * setting of ZSTD_c_blockDelimiters as ZSTD_sf_noBlockDelimiters 1377 * @return : number of sequences left after merging 1378 */ 1379 size_t ZSTD_mergeBlockDelimiters(ZSTD_Sequence* sequences, size_t seqsSize); 1380 1381 /*! ZSTD_compressSequences() : 1382 * Compress an array of ZSTD_Sequence, generated from the original source buffer, into dst. 1383 * If a dictionary is included, then the cctx should reference the dict. (see: ZSTD_CCtx_refCDict(), ZSTD_CCtx_loadDictionary(), etc.) 1384 * The entire source is compressed into a single frame. 1385 * 1386 * The compression behavior changes based on cctx params. In particular: 1387 * If ZSTD_c_blockDelimiters == ZSTD_sf_noBlockDelimiters, the array of ZSTD_Sequence is expected to contain 1388 * no block delimiters (defined in ZSTD_Sequence). Block boundaries are roughly determined based on 1389 * the block size derived from the cctx, and sequences may be split. This is the default setting. 1390 * 1391 * If ZSTD_c_blockDelimiters == ZSTD_sf_explicitBlockDelimiters, the array of ZSTD_Sequence is expected to contain 1392 * block delimiters (defined in ZSTD_Sequence). Behavior is undefined if no block delimiters are provided. 1393 * 1394 * If ZSTD_c_validateSequences == 0, this function will blindly accept the sequences provided. Invalid sequences cause undefined 1395 * behavior. If ZSTD_c_validateSequences == 1, then if sequence is invalid (see doc/zstd_compression_format.md for 1396 * specifics regarding offset/matchlength requirements) then the function will bail out and return an error. 1397 * 1398 * In addition to the two adjustable experimental params, there are other important cctx params. 1399 * - ZSTD_c_minMatch MUST be set as less than or equal to the smallest match generated by the match finder. It has a minimum value of ZSTD_MINMATCH_MIN. 1400 * - ZSTD_c_compressionLevel accordingly adjusts the strength of the entropy coder, as it would in typical compression. 1401 * - ZSTD_c_windowLog affects offset validation: this function will return an error at higher debug levels if a provided offset 1402 * is larger than what the spec allows for a given window log and dictionary (if present). See: doc/zstd_compression_format.md 1403 * 1404 * Note: Repcodes are, as of now, always re-calculated within this function, so ZSTD_Sequence::rep is unused. 1405 * Note 2: Once we integrate ability to ingest repcodes, the explicit block delims mode must respect those repcodes exactly, 1406 * and cannot emit an RLE block that disagrees with the repcode history 1407 * @return : final compressed size or a ZSTD error. 1408 */ 1409 size_t ZSTD_compressSequences(ZSTD_CCtx* cctx, void* dst, size_t dstSize, 1410 const(ZSTD_Sequence)* inSeqs, size_t inSeqsSize, 1411 const(void)* src, size_t srcSize); 1412 1413 /*! ZSTD_writeSkippableFrame() : 1414 * Generates a zstd skippable frame containing data given by src, and writes it to dst buffer. 1415 * 1416 * Skippable frames begin with a a 4-byte magic number. There are 16 possible choices of magic number, 1417 * ranging from ZSTD_MAGIC_SKIPPABLE_START to ZSTD_MAGIC_SKIPPABLE_START+15. 1418 * As such, the parameter magicVariant controls the exact skippable frame magic number variant used, so 1419 * the magic number used will be ZSTD_MAGIC_SKIPPABLE_START + magicVariant. 1420 * 1421 * Returns an error if destination buffer is not large enough, if the source size is not representable 1422 * with a 4-byte uint, or if the parameter magicVariant is greater than 15 (and therefore invalid). 1423 * 1424 * @return : number of bytes written or a ZSTD error. 1425 */ 1426 size_t ZSTD_writeSkippableFrame(void* dst, size_t dstCapacity, 1427 const(void)* src, size_t srcSize, uint magicVariant); 1428 1429 /*! ZSTD_readSkippableFrame() : 1430 * Retrieves a zstd skippable frame containing data given by src, and writes it to dst buffer. 1431 * 1432 * The parameter magicVariant will receive the magicVariant that was supplied when the frame was written, 1433 * i.e. magicNumber - ZSTD_MAGIC_SKIPPABLE_START. This can be NULL if the caller is not interested 1434 * in the magicVariant. 1435 * 1436 * Returns an error if destination buffer is not large enough, or if the frame is not skippable. 1437 * 1438 * @return : number of bytes written or a ZSTD error. 1439 */ 1440 size_t ZSTD_readSkippableFrame(void* dst, size_t dstCapacity, uint* magicVariant, 1441 const(void)* src, size_t srcSize); 1442 1443 /*! ZSTD_isSkippableFrame() : 1444 * Tells if the content of `buffer` starts with a valid Frame Identifier for a skippable frame. 1445 */ 1446 uint ZSTD_isSkippableFrame(const(void)* buffer, size_t size); 1447 1448 /*************************************** 1449 * Memory management 1450 ***************************************/ 1451 1452 /*! ZSTD_estimate*() : 1453 * These functions make it possible to estimate memory usage 1454 * of a future {D,C}Ctx, before its creation. 1455 * 1456 * ZSTD_estimateCCtxSize() will provide a memory budget large enough 1457 * for any compression level up to selected one. 1458 * Note : Unlike ZSTD_estimateCStreamSize*(), this estimate 1459 * does not include space for a window buffer. 1460 * Therefore, the estimation is only guaranteed for single-shot compressions, not streaming. 1461 * The estimate will assume the input may be arbitrarily large, 1462 * which is the worst case. 1463 * 1464 * When srcSize can be bound by a known and rather "small" value, 1465 * this fact can be used to provide a tighter estimation 1466 * because the CCtx compression context will need less memory. 1467 * This tighter estimation can be provided by more advanced functions 1468 * ZSTD_estimateCCtxSize_usingCParams(), which can be used in tandem with ZSTD_getCParams(), 1469 * and ZSTD_estimateCCtxSize_usingCCtxParams(), which can be used in tandem with ZSTD_CCtxParams_setParameter(). 1470 * Both can be used to estimate memory using custom compression parameters and arbitrary srcSize limits. 1471 * 1472 * Note 2 : only single-threaded compression is supported. 1473 * ZSTD_estimateCCtxSize_usingCCtxParams() will return an error code if ZSTD_c_nbWorkers is >= 1. 1474 */ 1475 size_t ZSTD_estimateCCtxSize(int compressionLevel); 1476 size_t ZSTD_estimateCCtxSize_usingCParams(ZSTD_compressionParameters cParams); 1477 size_t ZSTD_estimateCCtxSize_usingCCtxParams(const(ZSTD_CCtx_params)* params); 1478 size_t ZSTD_estimateDCtxSize(); 1479 1480 /*! ZSTD_estimateCStreamSize() : 1481 * ZSTD_estimateCStreamSize() will provide a budget large enough for any compression level up to selected one. 1482 * It will also consider src size to be arbitrarily "large", which is worst case. 1483 * If srcSize is known to always be small, ZSTD_estimateCStreamSize_usingCParams() can provide a tighter estimation. 1484 * ZSTD_estimateCStreamSize_usingCParams() can be used in tandem with ZSTD_getCParams() to create cParams from compressionLevel. 1485 * 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. 1486 * Note : CStream size estimation is only correct for single-threaded compression. 1487 * ZSTD_DStream memory budget depends on window Size. 1488 * This information can be passed manually, using ZSTD_estimateDStreamSize, 1489 * or deducted from a valid frame Header, using ZSTD_estimateDStreamSize_fromFrame(); 1490 * Note : if streaming is init with function ZSTD_init?Stream_usingDict(), 1491 * an internal ?Dict will be created, which additional size is not estimated here. 1492 * In this case, get total size by adding ZSTD_estimate?DictSize */ 1493 size_t ZSTD_estimateCStreamSize(int compressionLevel); 1494 size_t ZSTD_estimateCStreamSize_usingCParams(ZSTD_compressionParameters cParams); 1495 size_t ZSTD_estimateCStreamSize_usingCCtxParams(const(ZSTD_CCtx_params)* params); 1496 size_t ZSTD_estimateDStreamSize(size_t windowSize); 1497 size_t ZSTD_estimateDStreamSize_fromFrame(const(void)* src, size_t srcSize); 1498 1499 /*! ZSTD_estimate?DictSize() : 1500 * ZSTD_estimateCDictSize() will bet that src size is relatively "small", and content is copied, like ZSTD_createCDict(). 1501 * ZSTD_estimateCDictSize_advanced() makes it possible to control compression parameters precisely, like ZSTD_createCDict_advanced(). 1502 * Note : dictionaries created by reference (`ZSTD_dlm_byRef`) are logically smaller. 1503 */ 1504 size_t ZSTD_estimateCDictSize(size_t dictSize, int compressionLevel); 1505 size_t ZSTD_estimateCDictSize_advanced(size_t dictSize, ZSTD_compressionParameters cParams, 1506 ZSTD_dictLoadMethod_e dictLoadMethod); 1507 size_t ZSTD_estimateDDictSize(size_t dictSize, ZSTD_dictLoadMethod_e dictLoadMethod); 1508 1509 /*! ZSTD_initStatic*() : 1510 * Initialize an object using a pre-allocated fixed-size buffer. 1511 * workspace: The memory area to emplace the object into. 1512 * Provided pointer *must be 8-bytes aligned*. 1513 * Buffer must outlive object. 1514 * workspaceSize: Use ZSTD_estimate*Size() to determine 1515 * how large workspace must be to support target scenario. 1516 * @return : pointer to object (same address as workspace, just different type), 1517 * or NULL if error (size too small, incorrect alignment, etc.) 1518 * Note : zstd will never resize nor malloc() when using a static buffer. 1519 * If the object requires more memory than available, 1520 * zstd will just error out (typically ZSTD_error_memory_allocation). 1521 * Note 2 : there is no corresponding "free" function. 1522 * Since workspace is allocated externally, it must be freed externally too. 1523 * Note 3 : cParams : use ZSTD_getCParams() to convert a compression level 1524 * into its associated cParams. 1525 * Limitation 1 : currently not compatible with internal dictionary creation, triggered by 1526 * ZSTD_CCtx_loadDictionary(), ZSTD_initCStream_usingDict() or ZSTD_initDStream_usingDict(). 1527 * Limitation 2 : static cctx currently not compatible with multi-threading. 1528 * Limitation 3 : static dctx is incompatible with legacy support. 1529 */ 1530 ZSTD_CCtx* ZSTD_initStaticCCtx(void* workspace, size_t workspaceSize); 1531 ZSTD_CStream* ZSTD_initStaticCStream(void* workspace, size_t workspaceSize); /**< same as ZSTD_initStaticCCtx() */ 1532 1533 ZSTD_DCtx* ZSTD_initStaticDCtx(void* workspace, size_t workspaceSize); 1534 ZSTD_DStream* ZSTD_initStaticDStream(void* workspace, size_t workspaceSize); /**< same as ZSTD_initStaticDCtx() */ 1535 1536 const(ZSTD_CDict)* ZSTD_initStaticCDict( 1537 void* workspace, size_t workspaceSize, 1538 const(void)* dict, size_t dictSize, 1539 ZSTD_dictLoadMethod_e dictLoadMethod, 1540 ZSTD_dictContentType_e dictContentType, 1541 ZSTD_compressionParameters cParams); 1542 1543 const(ZSTD_DDict)* ZSTD_initStaticDDict( 1544 void* workspace, size_t workspaceSize, 1545 const(void)* dict, size_t dictSize, 1546 ZSTD_dictLoadMethod_e dictLoadMethod, 1547 ZSTD_dictContentType_e dictContentType); 1548 1549 /*! Custom memory allocation : 1550 * These prototypes make it possible to pass your own allocation/free functions. 1551 * ZSTD_customMem is provided at creation time, using ZSTD_create*_advanced() variants listed below. 1552 * All allocation/free operations will be completed using these custom variants instead of regular <stdlib.h> ones. 1553 */ 1554 alias ZSTD_allocFunction = void* function(void* opaque, size_t size); 1555 alias ZSTD_freeFunction = void function(void* opaque, void* address); 1556 1557 struct ZSTD_customMem 1558 { 1559 ZSTD_allocFunction customAlloc; 1560 ZSTD_freeFunction customFree; 1561 void* opaque; 1562 } 1563 1564 ZSTD_CCtx* ZSTD_createCCtx_advanced(ZSTD_customMem customMem); 1565 ZSTD_CStream* ZSTD_createCStream_advanced(ZSTD_customMem customMem); 1566 ZSTD_DCtx* ZSTD_createDCtx_advanced(ZSTD_customMem customMem); 1567 ZSTD_DStream* ZSTD_createDStream_advanced(ZSTD_customMem customMem); 1568 1569 ZSTD_CDict* ZSTD_createCDict_advanced(const(void)* dict, size_t dictSize, 1570 ZSTD_dictLoadMethod_e dictLoadMethod, 1571 ZSTD_dictContentType_e dictContentType, 1572 ZSTD_compressionParameters cParams, 1573 ZSTD_customMem customMem); 1574 1575 /*! Thread pool : 1576 * These prototypes make it possible to share a thread pool among multiple compression contexts. 1577 * This can limit resources for applications with multiple threads where each one uses 1578 * a threaded compression mode (via ZSTD_c_nbWorkers parameter). 1579 * ZSTD_createThreadPool creates a new thread pool with a given number of threads. 1580 * Note that the lifetime of such pool must exist while being used. 1581 * ZSTD_CCtx_refThreadPool assigns a thread pool to a context (use NULL argument value 1582 * to use an internal thread pool). 1583 * ZSTD_freeThreadPool frees a thread pool, accepts NULL pointer. 1584 */ 1585 struct ZSTD_threadPool; 1586 ZSTD_threadPool* ZSTD_createThreadPool(size_t numThreads); 1587 void ZSTD_freeThreadPool(ZSTD_threadPool* pool); /* accept NULL pointer */ 1588 size_t ZSTD_CCtx_refThreadPool(ZSTD_CCtx* cctx, ZSTD_threadPool* pool); 1589 1590 /* 1591 * This API is temporary and is expected to change or disappear in the future! 1592 */ 1593 ZSTD_CDict* ZSTD_createCDict_advanced2( 1594 const(void)* dict, size_t dictSize, 1595 ZSTD_dictLoadMethod_e dictLoadMethod, 1596 ZSTD_dictContentType_e dictContentType, 1597 const(ZSTD_CCtx_params)* cctxParams, 1598 ZSTD_customMem customMem); 1599 1600 ZSTD_DDict* ZSTD_createDDict_advanced( 1601 const(void)* dict, size_t dictSize, 1602 ZSTD_dictLoadMethod_e dictLoadMethod, 1603 ZSTD_dictContentType_e dictContentType, 1604 ZSTD_customMem customMem); 1605 1606 /*************************************** 1607 * Advanced compression functions 1608 ***************************************/ 1609 1610 /*! ZSTD_createCDict_byReference() : 1611 * Create a digested dictionary for compression 1612 * Dictionary content is just referenced, not duplicated. 1613 * As a consequence, `dictBuffer` **must** outlive CDict, 1614 * and its content must remain unmodified throughout the lifetime of CDict. 1615 * note: equivalent to ZSTD_createCDict_advanced(), with dictLoadMethod==ZSTD_dlm_byRef */ 1616 ZSTD_CDict* ZSTD_createCDict_byReference(const(void)* dictBuffer, size_t dictSize, int compressionLevel); 1617 1618 /*! ZSTD_getCParams() : 1619 * @return ZSTD_compressionParameters structure for a selected compression level and estimated srcSize. 1620 * `estimatedSrcSize` value is optional, select 0 if not known */ 1621 ZSTD_compressionParameters ZSTD_getCParams(int compressionLevel, cpp_ulonglong estimatedSrcSize, size_t dictSize); 1622 1623 /*! ZSTD_getParams() : 1624 * same as ZSTD_getCParams(), but @return a full `ZSTD_parameters` object instead of sub-component `ZSTD_compressionParameters`. 1625 * All fields of `ZSTD_frameParameters` are set to default : contentSize=1, checksum=0, noDictID=0 */ 1626 ZSTD_parameters ZSTD_getParams(int compressionLevel, cpp_ulonglong estimatedSrcSize, size_t dictSize); 1627 1628 /*! ZSTD_checkCParams() : 1629 * Ensure param values remain within authorized range. 1630 * @return 0 on success, or an error code (can be checked with ZSTD_isError()) */ 1631 size_t ZSTD_checkCParams(ZSTD_compressionParameters params); 1632 1633 /*! ZSTD_adjustCParams() : 1634 * optimize params for a given `srcSize` and `dictSize`. 1635 * `srcSize` can be unknown, in which case use ZSTD_CONTENTSIZE_UNKNOWN. 1636 * `dictSize` must be `0` when there is no dictionary. 1637 * cPar can be invalid : all parameters will be clamped within valid range in the @return struct. 1638 * This function never fails (wide contract) */ 1639 ZSTD_compressionParameters ZSTD_adjustCParams(ZSTD_compressionParameters cPar, cpp_ulonglong srcSize, size_t dictSize); 1640 1641 /*! ZSTD_compress_advanced() : 1642 * Note : this function is now DEPRECATED. 1643 * It can be replaced by ZSTD_compress2(), in combination with ZSTD_CCtx_setParameter() and other parameter setters. 1644 * This prototype will generate compilation warnings. */ 1645 deprecated("use ZSTD_compress2") 1646 size_t ZSTD_compress_advanced(ZSTD_CCtx* cctx, 1647 void* dst, size_t dstCapacity, 1648 const(void)* src, size_t srcSize, 1649 const(void)* dict, size_t dictSize, 1650 ZSTD_parameters params); 1651 1652 /*! ZSTD_compress_usingCDict_advanced() : 1653 * Note : this function is now DEPRECATED. 1654 * It can be replaced by ZSTD_compress2(), in combination with ZSTD_CCtx_loadDictionary() and other parameter setters. 1655 * This prototype will generate compilation warnings. */ 1656 deprecated("use ZSTD_compress2 with ZSTD_CCtx_loadDictionary") 1657 size_t ZSTD_compress_usingCDict_advanced(ZSTD_CCtx* cctx, 1658 void* dst, size_t dstCapacity, 1659 const(void)* src, size_t srcSize, 1660 const(ZSTD_CDict)* cdict, 1661 ZSTD_frameParameters fParams); 1662 1663 /*! ZSTD_CCtx_loadDictionary_byReference() : 1664 * Same as ZSTD_CCtx_loadDictionary(), but dictionary content is referenced, instead of being copied into CCtx. 1665 * It saves some memory, but also requires that `dict` outlives its usage within `cctx` */ 1666 size_t ZSTD_CCtx_loadDictionary_byReference(ZSTD_CCtx* cctx, const(void)* dict, size_t dictSize); 1667 1668 /*! ZSTD_CCtx_loadDictionary_advanced() : 1669 * Same as ZSTD_CCtx_loadDictionary(), but gives finer control over 1670 * how to load the dictionary (by copy ? by reference ?) 1671 * and how to interpret it (automatic ? force raw mode ? full mode only ?) */ 1672 size_t ZSTD_CCtx_loadDictionary_advanced(ZSTD_CCtx* cctx, const(void)* dict, size_t dictSize, 1673 ZSTD_dictLoadMethod_e dictLoadMethod, ZSTD_dictContentType_e dictContentType); 1674 1675 /*! ZSTD_CCtx_refPrefix_advanced() : 1676 * Same as ZSTD_CCtx_refPrefix(), but gives finer control over 1677 * how to interpret prefix content (automatic ? force raw mode (default) ? full mode only ?) */ 1678 size_t ZSTD_CCtx_refPrefix_advanced(ZSTD_CCtx* cctx, const(void)* prefix, size_t prefixSize, 1679 ZSTD_dictContentType_e dictContentType); 1680 1681 /* === experimental parameters === */ 1682 /* these parameters can be used with ZSTD_setParameter() 1683 * they are not guaranteed to remain supported in the future */ 1684 1685 /* Enables rsyncable mode, 1686 * which makes compressed files more rsync friendly 1687 * by adding periodic synchronization points to the compressed data. 1688 * The target average block size is ZSTD_c_jobSize / 2. 1689 * It's possible to modify the job size to increase or decrease 1690 * the granularity of the synchronization point. 1691 * Once the jobSize is smaller than the window size, 1692 * it will result in compression ratio degradation. 1693 * NOTE 1: rsyncable mode only works when multithreading is enabled. 1694 * NOTE 2: rsyncable performs poorly in combination with long range mode, 1695 * since it will decrease the effectiveness of synchronization points, 1696 * though mileage may vary. 1697 * NOTE 3: Rsyncable mode limits maximum compression speed to ~400 MB/s. 1698 * If the selected compression level is already running significantly slower, 1699 * the overall speed won't be significantly impacted. 1700 */ 1701 enum ZSTD_c_rsyncable = ZSTD_cParameter.experimentalParam1; 1702 1703 /* Select a compression format. 1704 * The value must be of type ZSTD_format_e. 1705 * See ZSTD_format_e enum definition for details */ 1706 enum ZSTD_c_format = ZSTD_cParameter.experimentalParam2; 1707 1708 /* Force back-reference distances to remain < windowSize, 1709 * even when referencing into Dictionary content (default:0) */ 1710 enum ZSTD_c_forceMaxWindow = ZSTD_cParameter.experimentalParam3; 1711 1712 /* Controls whether the contents of a CDict 1713 * are used in place, or copied into the working context. 1714 * Accepts values from the ZSTD_dictAttachPref_e enum. 1715 * See the comments on that enum for an explanation of the feature. */ 1716 enum ZSTD_c_forceAttachDict = ZSTD_cParameter.experimentalParam4; 1717 1718 /* Controlled with ZSTD_paramSwitch_e enum. 1719 * Default is ZSTD_ps_auto. 1720 * Set to ZSTD_ps_disable to never compress literals. 1721 * Set to ZSTD_ps_enable to always compress literals. (Note: uncompressed literals 1722 * may still be emitted if huffman is not beneficial to use.) 1723 * 1724 * By default, in ZSTD_ps_auto, the library will decide at runtime whether to use 1725 * literals compression based on the compression parameters - specifically, 1726 * negative compression levels do not use literal compression. 1727 */ 1728 enum ZSTD_c_literalCompressionMode = ZSTD_cParameter.experimentalParam5; 1729 1730 /* Tries to fit compressed block size to be around targetCBlockSize. 1731 * No target when targetCBlockSize == 0. 1732 * There is no guarantee on compressed block size (default:0) */ 1733 enum ZSTD_c_targetCBlockSize = ZSTD_cParameter.experimentalParam6; 1734 1735 /* User's best guess of source size. 1736 * Hint is not valid when srcSizeHint == 0. 1737 * There is no guarantee that hint is close to actual source size, 1738 * but compression ratio may regress significantly if guess considerably underestimates */ 1739 enum ZSTD_c_srcSizeHint = ZSTD_cParameter.experimentalParam7; 1740 1741 /* Controls whether the new and experimental "dedicated dictionary search 1742 * structure" can be used. This feature is still rough around the edges, be 1743 * prepared for surprising behavior! 1744 * 1745 * How to use it: 1746 * 1747 * When using a CDict, whether to use this feature or not is controlled at 1748 * CDict creation, and it must be set in a CCtxParams set passed into that 1749 * construction (via ZSTD_createCDict_advanced2()). A compression will then 1750 * use the feature or not based on how the CDict was constructed; the value of 1751 * this param, set in the CCtx, will have no effect. 1752 * 1753 * However, when a dictionary buffer is passed into a CCtx, such as via 1754 * ZSTD_CCtx_loadDictionary(), this param can be set on the CCtx to control 1755 * whether the CDict that is created internally can use the feature or not. 1756 * 1757 * What it does: 1758 * 1759 * Normally, the internal data structures of the CDict are analogous to what 1760 * would be stored in a CCtx after compressing the contents of a dictionary. 1761 * To an approximation, a compression using a dictionary can then use those 1762 * data structures to simply continue what is effectively a streaming 1763 * compression where the simulated compression of the dictionary left off. 1764 * Which is to say, the search structures in the CDict are normally the same 1765 * format as in the CCtx. 1766 * 1767 * It is possible to do better, since the CDict is not like a CCtx: the search 1768 * structures are written once during CDict creation, and then are only read 1769 * after that, while the search structures in the CCtx are both read and 1770 * written as the compression goes along. This means we can choose a search 1771 * structure for the dictionary that is read-optimized. 1772 * 1773 * This feature enables the use of that different structure. 1774 * 1775 * Note that some of the members of the ZSTD_compressionParameters struct have 1776 * different semantics and constraints in the dedicated search structure. It is 1777 * highly recommended that you simply set a compression level in the CCtxParams 1778 * you pass into the CDict creation call, and avoid messing with the cParams 1779 * directly. 1780 * 1781 * Effects: 1782 * 1783 * This will only have any effect when the selected ZSTD_strategy 1784 * implementation supports this feature. Currently, that's limited to 1785 * ZSTD_greedy, ZSTD_lazy, and ZSTD_lazy2. 1786 * 1787 * Note that this means that the CDict tables can no longer be copied into the 1788 * CCtx, so the dict attachment mode ZSTD_dictForceCopy will no longer be 1789 * usable. The dictionary can only be attached or reloaded. 1790 * 1791 * In general, you should expect compression to be faster--sometimes very much 1792 * so--and CDict creation to be slightly slower. Eventually, we will probably 1793 * make this mode the default. 1794 */ 1795 enum ZSTD_c_enableDedicatedDictSearch = ZSTD_cParameter.experimentalParam8; 1796 1797 /* ZSTD_c_stableInBuffer 1798 * Experimental parameter. 1799 * Default is 0 == disabled. Set to 1 to enable. 1800 * 1801 * Tells the compressor that the ZSTD_inBuffer will ALWAYS be the same 1802 * between calls, except for the modifications that zstd makes to pos (the 1803 * caller must not modify pos). This is checked by the compressor, and 1804 * compression will fail if it ever changes. This means the only flush 1805 * mode that makes sense is ZSTD_e_end, so zstd will error if ZSTD_e_end 1806 * is not used. The data in the ZSTD_inBuffer in the range [src, src + pos) 1807 * MUST not be modified during compression or you will get data corruption. 1808 * 1809 * When this flag is enabled zstd won't allocate an input window buffer, 1810 * because the user guarantees it can reference the ZSTD_inBuffer until 1811 * the frame is complete. But, it will still allocate an output buffer 1812 * large enough to fit a block (see ZSTD_c_stableOutBuffer). This will also 1813 * avoid the memcpy() from the input buffer to the input window buffer. 1814 * 1815 * NOTE: ZSTD_compressStream2() will error if ZSTD_e_end is not used. 1816 * That means this flag cannot be used with ZSTD_compressStream(). 1817 * 1818 * NOTE: So long as the ZSTD_inBuffer always points to valid memory, using 1819 * this flag is ALWAYS memory safe, and will never access out-of-bounds 1820 * memory. However, compression WILL fail if you violate the preconditions. 1821 * 1822 * WARNING: The data in the ZSTD_inBuffer in the range [dst, dst + pos) MUST 1823 * not be modified during compression or you will get data corruption. This 1824 * is because zstd needs to reference data in the ZSTD_inBuffer to find 1825 * matches. Normally zstd maintains its own window buffer for this purpose, 1826 * but passing this flag tells zstd to use the user provided buffer. 1827 */ 1828 enum ZSTD_c_stableInBuffer = ZSTD_cParameter.experimentalParam9; 1829 1830 /* ZSTD_c_stableOutBuffer 1831 * Experimental parameter. 1832 * Default is 0 == disabled. Set to 1 to enable. 1833 * 1834 * Tells he compressor that the ZSTD_outBuffer will not be resized between 1835 * calls. Specifically: (out.size - out.pos) will never grow. This gives the 1836 * compressor the freedom to say: If the compressed data doesn't fit in the 1837 * output buffer then return ZSTD_error_dstSizeTooSmall. This allows us to 1838 * always decompress directly into the output buffer, instead of decompressing 1839 * into an internal buffer and copying to the output buffer. 1840 * 1841 * When this flag is enabled zstd won't allocate an output buffer, because 1842 * it can write directly to the ZSTD_outBuffer. It will still allocate the 1843 * input window buffer (see ZSTD_c_stableInBuffer). 1844 * 1845 * Zstd will check that (out.size - out.pos) never grows and return an error 1846 * if it does. While not strictly necessary, this should prevent surprises. 1847 */ 1848 enum ZSTD_c_stableOutBuffer = ZSTD_cParameter.experimentalParam10; 1849 1850 /* ZSTD_c_blockDelimiters 1851 * Default is 0 == ZSTD_sf_noBlockDelimiters. 1852 * 1853 * For use with sequence compression API: ZSTD_compressSequences(). 1854 * 1855 * Designates whether or not the given array of ZSTD_Sequence contains block delimiters 1856 * and last literals, which are defined as sequences with offset == 0 and matchLength == 0. 1857 * See the definition of ZSTD_Sequence for more specifics. 1858 */ 1859 enum ZSTD_c_blockDelimiters = ZSTD_cParameter.experimentalParam11; 1860 1861 /* ZSTD_c_validateSequences 1862 * Default is 0 == disabled. Set to 1 to enable sequence validation. 1863 * 1864 * For use with sequence compression API: ZSTD_compressSequences(). 1865 * Designates whether or not we validate sequences provided to ZSTD_compressSequences() 1866 * during function execution. 1867 * 1868 * Without validation, providing a sequence that does not conform to the zstd spec will cause 1869 * undefined behavior, and may produce a corrupted block. 1870 * 1871 * With validation enabled, a if sequence is invalid (see doc/zstd_compression_format.md for 1872 * specifics regarding offset/matchlength requirements) then the function will bail out and 1873 * return an error. 1874 * 1875 */ 1876 enum ZSTD_c_validateSequences = ZSTD_cParameter.experimentalParam12; 1877 1878 /* ZSTD_c_useBlockSplitter 1879 * Controlled with ZSTD_paramSwitch_e enum. 1880 * Default is ZSTD_ps_auto. 1881 * Set to ZSTD_ps_disable to never use block splitter. 1882 * Set to ZSTD_ps_enable to always use block splitter. 1883 * 1884 * By default, in ZSTD_ps_auto, the library will decide at runtime whether to use 1885 * block splitting based on the compression parameters. 1886 */ 1887 enum ZSTD_c_useBlockSplitter = ZSTD_cParameter.experimentalParam13; 1888 1889 /* ZSTD_c_useRowMatchFinder 1890 * Controlled with ZSTD_paramSwitch_e enum. 1891 * Default is ZSTD_ps_auto. 1892 * Set to ZSTD_ps_disable to never use row-based matchfinder. 1893 * Set to ZSTD_ps_enable to force usage of row-based matchfinder. 1894 * 1895 * By default, in ZSTD_ps_auto, the library will decide at runtime whether to use 1896 * the row-based matchfinder based on support for SIMD instructions and the window log. 1897 * Note that this only pertains to compression strategies: greedy, lazy, and lazy2 1898 */ 1899 enum ZSTD_c_useRowMatchFinder = ZSTD_cParameter.experimentalParam14; 1900 1901 /* ZSTD_c_deterministicRefPrefix 1902 * Default is 0 == disabled. Set to 1 to enable. 1903 * 1904 * Zstd produces different results for prefix compression when the prefix is 1905 * directly adjacent to the data about to be compressed vs. when it isn't. 1906 * This is because zstd detects that the two buffers are contiguous and it can 1907 * use a more efficient match finding algorithm. However, this produces different 1908 * results than when the two buffers are non-contiguous. This flag forces zstd 1909 * to always load the prefix in non-contiguous mode, even if it happens to be 1910 * adjacent to the data, to guarantee determinism. 1911 * 1912 * If you really care about determinism when using a dictionary or prefix, 1913 * like when doing delta compression, you should select this option. It comes 1914 * at a speed penalty of about ~2.5% if the dictionary and data happened to be 1915 * contiguous, and is free if they weren't contiguous. We don't expect that 1916 * intentionally making the dictionary and data contiguous will be worth the 1917 * cost to memcpy() the data. 1918 */ 1919 enum ZSTD_c_deterministicRefPrefix = ZSTD_cParameter.experimentalParam15; 1920 1921 /*! ZSTD_CCtx_getParameter() : 1922 * Get the requested compression parameter value, selected by enum ZSTD_cParameter, 1923 * and store it into int* value. 1924 * @return : 0, or an error code (which can be tested with ZSTD_isError()). 1925 */ 1926 size_t ZSTD_CCtx_getParameter(const(ZSTD_CCtx)* cctx, ZSTD_cParameter param, int* value); 1927 1928 /*! ZSTD_CCtx_params : 1929 * Quick howto : 1930 * - ZSTD_createCCtxParams() : Create a ZSTD_CCtx_params structure 1931 * - ZSTD_CCtxParams_setParameter() : Push parameters one by one into 1932 * an existing ZSTD_CCtx_params structure. 1933 * This is similar to 1934 * ZSTD_CCtx_setParameter(). 1935 * - ZSTD_CCtx_setParametersUsingCCtxParams() : Apply parameters to 1936 * an existing CCtx. 1937 * These parameters will be applied to 1938 * all subsequent frames. 1939 * - ZSTD_compressStream2() : Do compression using the CCtx. 1940 * - ZSTD_freeCCtxParams() : Free the memory, accept NULL pointer. 1941 * 1942 * This can be used with ZSTD_estimateCCtxSize_advanced_usingCCtxParams() 1943 * for static allocation of CCtx for single-threaded compression. 1944 */ 1945 ZSTD_CCtx_params* ZSTD_createCCtxParams(); 1946 size_t ZSTD_freeCCtxParams(ZSTD_CCtx_params* params); /* accept NULL pointer */ 1947 1948 /*! ZSTD_CCtxParams_reset() : 1949 * Reset params to default values. 1950 */ 1951 size_t ZSTD_CCtxParams_reset(ZSTD_CCtx_params* params); 1952 1953 /*! ZSTD_CCtxParams_init() : 1954 * Initializes the compression parameters of cctxParams according to 1955 * compression level. All other parameters are reset to their default values. 1956 */ 1957 size_t ZSTD_CCtxParams_init(ZSTD_CCtx_params* cctxParams, int compressionLevel); 1958 1959 /*! ZSTD_CCtxParams_init_advanced() : 1960 * Initializes the compression and frame parameters of cctxParams according to 1961 * params. All other parameters are reset to their default values. 1962 */ 1963 size_t ZSTD_CCtxParams_init_advanced(ZSTD_CCtx_params* cctxParams, ZSTD_parameters params); 1964 1965 /*! ZSTD_CCtxParams_setParameter() : Requires v1.4.0+ 1966 * Similar to ZSTD_CCtx_setParameter. 1967 * Set one compression parameter, selected by enum ZSTD_cParameter. 1968 * Parameters must be applied to a ZSTD_CCtx using 1969 * ZSTD_CCtx_setParametersUsingCCtxParams(). 1970 * @result : a code representing success or failure (which can be tested with 1971 * ZSTD_isError()). 1972 */ 1973 size_t ZSTD_CCtxParams_setParameter(ZSTD_CCtx_params* params, ZSTD_cParameter param, int value); 1974 1975 /*! ZSTD_CCtxParams_getParameter() : 1976 * Similar to ZSTD_CCtx_getParameter. 1977 * Get the requested value of one compression parameter, selected by enum ZSTD_cParameter. 1978 * @result : 0, or an error code (which can be tested with ZSTD_isError()). 1979 */ 1980 size_t ZSTD_CCtxParams_getParameter(const(ZSTD_CCtx_params)* params, ZSTD_cParameter param, int* value); 1981 1982 /*! ZSTD_CCtx_setParametersUsingCCtxParams() : 1983 * Apply a set of ZSTD_CCtx_params to the compression context. 1984 * This can be done even after compression is started, 1985 * if nbWorkers==0, this will have no impact until a new compression is started. 1986 * if nbWorkers>=1, new parameters will be picked up at next job, 1987 * with a few restrictions (windowLog, pledgedSrcSize, nbWorkers, jobSize, and overlapLog are not updated). 1988 */ 1989 size_t ZSTD_CCtx_setParametersUsingCCtxParams( 1990 ZSTD_CCtx* cctx, const(ZSTD_CCtx_params)* params); 1991 1992 /*! ZSTD_compressStream2_simpleArgs() : 1993 * Same as ZSTD_compressStream2(), 1994 * but using only integral types as arguments. 1995 * This variant might be helpful for binders from dynamic languages 1996 * which have troubles handling structures containing memory pointers. 1997 */ 1998 size_t ZSTD_compressStream2_simpleArgs( 1999 ZSTD_CCtx* cctx, 2000 void* dst, size_t dstCapacity, size_t* dstPos, 2001 const(void)* src, size_t srcSize, size_t* srcPos, 2002 ZSTD_EndDirective endOp); 2003 2004 /*************************************** 2005 * Advanced decompression functions 2006 ***************************************/ 2007 2008 /*! ZSTD_isFrame() : 2009 * Tells if the content of `buffer` starts with a valid Frame Identifier. 2010 * Note : Frame Identifier is 4 bytes. If `size < 4`, @return will always be 0. 2011 * Note 2 : Legacy Frame Identifiers are considered valid only if Legacy Support is enabled. 2012 * Note 3 : Skippable Frame Identifiers are considered valid. */ 2013 uint ZSTD_isFrame(const(void)* buffer, size_t size); 2014 2015 /*! ZSTD_createDDict_byReference() : 2016 * Create a digested dictionary, ready to start decompression operation without startup delay. 2017 * Dictionary content is referenced, and therefore stays in dictBuffer. 2018 * It is important that dictBuffer outlives DDict, 2019 * it must remain read accessible throughout the lifetime of DDict */ 2020 ZSTD_DDict* ZSTD_createDDict_byReference(const(void)* dictBuffer, size_t dictSize); 2021 2022 /*! ZSTD_DCtx_loadDictionary_byReference() : 2023 * Same as ZSTD_DCtx_loadDictionary(), 2024 * but references `dict` content instead of copying it into `dctx`. 2025 * This saves memory if `dict` remains around., 2026 * However, it's imperative that `dict` remains accessible (and unmodified) while being used, so it must outlive decompression. */ 2027 size_t ZSTD_DCtx_loadDictionary_byReference(ZSTD_DCtx* dctx, const(void)* dict, size_t dictSize); 2028 2029 /*! ZSTD_DCtx_loadDictionary_advanced() : 2030 * Same as ZSTD_DCtx_loadDictionary(), 2031 * but gives direct control over 2032 * how to load the dictionary (by copy ? by reference ?) 2033 * and how to interpret it (automatic ? force raw mode ? full mode only ?). */ 2034 size_t ZSTD_DCtx_loadDictionary_advanced(ZSTD_DCtx* dctx, const(void)* dict, size_t dictSize, 2035 ZSTD_dictLoadMethod_e dictLoadMethod, ZSTD_dictContentType_e dictContentType); 2036 2037 /*! ZSTD_DCtx_refPrefix_advanced() : 2038 * Same as ZSTD_DCtx_refPrefix(), but gives finer control over 2039 * how to interpret prefix content (automatic ? force raw mode (default) ? full mode only ?) */ 2040 size_t ZSTD_DCtx_refPrefix_advanced(ZSTD_DCtx* dctx, const(void)* prefix, size_t prefixSize, 2041 ZSTD_dictContentType_e dictContentType); 2042 2043 /*! ZSTD_DCtx_setMaxWindowSize() : 2044 * Refuses allocating internal buffers for frames requiring a window size larger than provided limit. 2045 * This protects a decoder context from reserving too much memory for itself (potential attack scenario). 2046 * This parameter is only useful in streaming mode, since no internal buffer is allocated in single-pass mode. 2047 * By default, a decompression context accepts all window sizes <= (1 << ZSTD_WINDOWLOG_LIMIT_DEFAULT) 2048 * @return : 0, or an error code (which can be tested using ZSTD_isError()). 2049 */ 2050 size_t ZSTD_DCtx_setMaxWindowSize(ZSTD_DCtx* dctx, size_t maxWindowSize); 2051 2052 /*! ZSTD_DCtx_getParameter() : 2053 * Get the requested decompression parameter value, selected by enum ZSTD_dParameter, 2054 * and store it into int* value. 2055 * @return : 0, or an error code (which can be tested with ZSTD_isError()). 2056 */ 2057 size_t ZSTD_DCtx_getParameter(ZSTD_DCtx* dctx, ZSTD_dParameter param, int* value); 2058 2059 /* ZSTD_d_format 2060 * experimental parameter, 2061 * allowing selection between ZSTD_format_e input compression formats 2062 */ 2063 enum ZSTD_d_format = ZSTD_dParameter.experimentalParam1; 2064 /* ZSTD_d_stableOutBuffer 2065 * Experimental parameter. 2066 * Default is 0 == disabled. Set to 1 to enable. 2067 * 2068 * Tells the decompressor that the ZSTD_outBuffer will ALWAYS be the same 2069 * between calls, except for the modifications that zstd makes to pos (the 2070 * caller must not modify pos). This is checked by the decompressor, and 2071 * decompression will fail if it ever changes. Therefore the ZSTD_outBuffer 2072 * MUST be large enough to fit the entire decompressed frame. This will be 2073 * checked when the frame content size is known. The data in the ZSTD_outBuffer 2074 * in the range [dst, dst + pos) MUST not be modified during decompression 2075 * or you will get data corruption. 2076 * 2077 * When this flags is enabled zstd won't allocate an output buffer, because 2078 * it can write directly to the ZSTD_outBuffer, but it will still allocate 2079 * an input buffer large enough to fit any compressed block. This will also 2080 * avoid the memcpy() from the internal output buffer to the ZSTD_outBuffer. 2081 * If you need to avoid the input buffer allocation use the buffer-less 2082 * streaming API. 2083 * 2084 * NOTE: So long as the ZSTD_outBuffer always points to valid memory, using 2085 * this flag is ALWAYS memory safe, and will never access out-of-bounds 2086 * memory. However, decompression WILL fail if you violate the preconditions. 2087 * 2088 * WARNING: The data in the ZSTD_outBuffer in the range [dst, dst + pos) MUST 2089 * not be modified during decompression or you will get data corruption. This 2090 * is because zstd needs to reference data in the ZSTD_outBuffer to regenerate 2091 * matches. Normally zstd maintains its own buffer for this purpose, but passing 2092 * this flag tells zstd to use the user provided buffer. 2093 */ 2094 enum ZSTD_d_stableOutBuffer = ZSTD_dParameter.experimentalParam2; 2095 2096 /* ZSTD_d_forceIgnoreChecksum 2097 * Experimental parameter. 2098 * Default is 0 == disabled. Set to 1 to enable 2099 * 2100 * Tells the decompressor to skip checksum validation during decompression, regardless 2101 * of whether checksumming was specified during compression. This offers some 2102 * slight performance benefits, and may be useful for debugging. 2103 * Param has values of type ZSTD_forceIgnoreChecksum_e 2104 */ 2105 enum ZSTD_d_forceIgnoreChecksum = ZSTD_dParameter.experimentalParam3; 2106 2107 /* ZSTD_d_refMultipleDDicts 2108 * Experimental parameter. 2109 * Default is 0 == disabled. Set to 1 to enable 2110 * 2111 * If enabled and dctx is allocated on the heap, then additional memory will be allocated 2112 * to store references to multiple ZSTD_DDict. That is, multiple calls of ZSTD_refDDict() 2113 * using a given ZSTD_DCtx, rather than overwriting the previous DDict reference, will instead 2114 * store all references. At decompression time, the appropriate dictID is selected 2115 * from the set of DDicts based on the dictID in the frame. 2116 * 2117 * Usage is simply calling ZSTD_refDDict() on multiple dict buffers. 2118 * 2119 * Param has values of byte ZSTD_refMultipleDDicts_e 2120 * 2121 * WARNING: Enabling this parameter and calling ZSTD_DCtx_refDDict(), will trigger memory 2122 * allocation for the hash table. ZSTD_freeDCtx() also frees this memory. 2123 * Memory is allocated as per ZSTD_DCtx::customMem. 2124 * 2125 * Although this function allocates memory for the table, the user is still responsible for 2126 * memory management of the underlying ZSTD_DDict* themselves. 2127 */ 2128 enum ZSTD_d_refMultipleDDicts = ZSTD_dParameter.experimentalParam4; 2129 2130 /*! ZSTD_DCtx_setFormat() : 2131 * This function is REDUNDANT. Prefer ZSTD_DCtx_setParameter(). 2132 * Instruct the decoder context about what kind of data to decode next. 2133 * This instruction is mandatory to decode data without a fully-formed header, 2134 * such ZSTD_f_zstd1_magicless for example. 2135 * @return : 0, or an error code (which can be tested using ZSTD_isError()). */ 2136 deprecated("use ZSTD_DCtx_setParameter() instead") 2137 size_t ZSTD_DCtx_setFormat(ZSTD_DCtx* dctx, ZSTD_format_e format); 2138 2139 /*! ZSTD_decompressStream_simpleArgs() : 2140 * Same as ZSTD_decompressStream(), 2141 * but using only integral types as arguments. 2142 * This can be helpful for binders from dynamic languages 2143 * which have troubles handling structures containing memory pointers. 2144 */ 2145 size_t ZSTD_decompressStream_simpleArgs( 2146 ZSTD_DCtx* dctx, 2147 void* dst, size_t dstCapacity, size_t* dstPos, 2148 const(void)* src, size_t srcSize, size_t* srcPos); 2149 2150 /******************************************************************** 2151 * Advanced streaming functions 2152 * Warning : most of these functions are now redundant with the Advanced API. 2153 * Once Advanced API reaches "stable" status, 2154 * redundant functions will be deprecated, and then at some point removed. 2155 ********************************************************************/ 2156 2157 /*===== Advanced Streaming compression functions =====*/ 2158 2159 /*! ZSTD_initCStream_srcSize() : 2160 * This function is DEPRECATED, and equivalent to: 2161 * ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only); 2162 * ZSTD_CCtx_refCDict(zcs, NULL); // clear the dictionary (if any) 2163 * ZSTD_CCtx_setParameter(zcs, ZSTD_c_compressionLevel, compressionLevel); 2164 * ZSTD_CCtx_setPledgedSrcSize(zcs, pledgedSrcSize); 2165 * 2166 * pledgedSrcSize must be correct. If it is not known at init time, use 2167 * ZSTD_CONTENTSIZE_UNKNOWN. Note that, for compatibility with older programs, 2168 * "0" also disables frame content size field. It may be enabled in the future. 2169 * This prototype will generate compilation warnings. 2170 */ 2171 deprecated("use ZSTD_CCtx_reset, see zstd.h for detailed instructions") 2172 size_t ZSTD_initCStream_srcSize(ZSTD_CStream* zcs, 2173 int compressionLevel, 2174 cpp_ulonglong pledgedSrcSize); 2175 2176 /*! ZSTD_initCStream_usingDict() : 2177 * This function is DEPRECATED, and is equivalent to: 2178 * ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only); 2179 * ZSTD_CCtx_setParameter(zcs, ZSTD_c_compressionLevel, compressionLevel); 2180 * ZSTD_CCtx_loadDictionary(zcs, dict, dictSize); 2181 * 2182 * Creates of an internal CDict (incompatible with static CCtx), except if 2183 * dict == NULL or dictSize < 8, in which case no dict is used. 2184 * Note: dict is loaded with ZSTD_dct_auto (treated as a full zstd dictionary if 2185 * it begins with ZSTD_MAGIC_DICTIONARY, else as raw content) and ZSTD_dlm_byCopy. 2186 * This prototype will generate compilation warnings. 2187 */ 2188 deprecated("use ZSTD_CCtx_reset, see zstd.h for detailed instructions") 2189 size_t ZSTD_initCStream_usingDict(ZSTD_CStream* zcs, 2190 const(void)* dict, size_t dictSize, 2191 int compressionLevel); 2192 2193 /*! ZSTD_initCStream_advanced() : 2194 * This function is DEPRECATED, and is approximately equivalent to: 2195 * ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only); 2196 * // Pseudocode: Set each zstd parameter and leave the rest as-is. 2197 * for ((param, value) : params) { 2198 * ZSTD_CCtx_setParameter(zcs, param, value); 2199 * } 2200 * ZSTD_CCtx_setPledgedSrcSize(zcs, pledgedSrcSize); 2201 * ZSTD_CCtx_loadDictionary(zcs, dict, dictSize); 2202 * 2203 * dict is loaded with ZSTD_dct_auto and ZSTD_dlm_byCopy. 2204 * pledgedSrcSize must be correct. 2205 * If srcSize is not known at init time, use value ZSTD_CONTENTSIZE_UNKNOWN. 2206 * This prototype will generate compilation warnings. 2207 */ 2208 deprecated("use ZSTD_CCtx_reset, see zstd.h for detailed instructions") 2209 size_t ZSTD_initCStream_advanced(ZSTD_CStream* zcs, 2210 const(void)* dict, size_t dictSize, 2211 ZSTD_parameters params, 2212 cpp_ulonglong pledgedSrcSize); 2213 2214 /*! ZSTD_initCStream_usingCDict() : 2215 * This function is DEPRECATED, and equivalent to: 2216 * ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only); 2217 * ZSTD_CCtx_refCDict(zcs, cdict); 2218 * 2219 * note : cdict will just be referenced, and must outlive compression session 2220 * This prototype will generate compilation warnings. 2221 */ 2222 deprecated("use ZSTD_CCtx_reset and ZSTD_CCtx_refCDict, see zstd.h for detailed instructions") 2223 size_t ZSTD_initCStream_usingCDict(ZSTD_CStream* zcs, const(ZSTD_CDict)* cdict); 2224 2225 /*! ZSTD_initCStream_usingCDict_advanced() : 2226 * This function is DEPRECATED, and is approximately equivalent to: 2227 * ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only); 2228 * // Pseudocode: Set each zstd frame parameter and leave the rest as-is. 2229 * for ((fParam, value) : fParams) { 2230 * ZSTD_CCtx_setParameter(zcs, fParam, value); 2231 * } 2232 * ZSTD_CCtx_setPledgedSrcSize(zcs, pledgedSrcSize); 2233 * ZSTD_CCtx_refCDict(zcs, cdict); 2234 * 2235 * same as ZSTD_initCStream_usingCDict(), with control over frame parameters. 2236 * pledgedSrcSize must be correct. If srcSize is not known at init time, use 2237 * value ZSTD_CONTENTSIZE_UNKNOWN. 2238 * This prototype will generate compilation warnings. 2239 */ 2240 deprecated("use ZSTD_CCtx_reset and ZSTD_CCtx_refCDict, see zstd.h for detailed instructions") 2241 size_t ZSTD_initCStream_usingCDict_advanced(ZSTD_CStream* zcs, 2242 const(ZSTD_CDict)* cdict, 2243 ZSTD_frameParameters fParams, 2244 cpp_ulonglong pledgedSrcSize); 2245 2246 /*! ZSTD_resetCStream() : 2247 * This function is DEPRECATED, and is equivalent to: 2248 * ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only); 2249 * ZSTD_CCtx_setPledgedSrcSize(zcs, pledgedSrcSize); 2250 * Note: ZSTD_resetCStream() interprets pledgedSrcSize == 0 as ZSTD_CONTENTSIZE_UNKNOWN, but 2251 * ZSTD_CCtx_setPledgedSrcSize() does not do the same, so ZSTD_CONTENTSIZE_UNKNOWN must be 2252 * explicitly specified. 2253 * 2254 * start a new frame, using same parameters from previous frame. 2255 * This is typically useful to skip dictionary loading stage, since it will re-use it in-place. 2256 * Note that zcs must be init at least once before using ZSTD_resetCStream(). 2257 * If pledgedSrcSize is not known at reset time, use macro ZSTD_CONTENTSIZE_UNKNOWN. 2258 * If pledgedSrcSize > 0, its value must be correct, as it will be written in header, and controlled at the end. 2259 * For the time being, pledgedSrcSize==0 is interpreted as "srcSize unknown" for compatibility with older programs, 2260 * but it will change to mean "empty" in future version, so use macro ZSTD_CONTENTSIZE_UNKNOWN instead. 2261 * @return : 0, or an error code (which can be tested using ZSTD_isError()) 2262 * This prototype will generate compilation warnings. 2263 */ 2264 deprecated("use ZSTD_CCtx_reset, see zstd.h for detailed instructions") 2265 size_t ZSTD_resetCStream(ZSTD_CStream* zcs, cpp_ulonglong pledgedSrcSize); 2266 2267 struct ZSTD_frameProgression 2268 { 2269 cpp_ulonglong ingested; /* nb input bytes read and buffered */ 2270 cpp_ulonglong consumed; /* nb input bytes actually compressed */ 2271 cpp_ulonglong produced; /* nb of compressed bytes generated and buffered */ 2272 cpp_ulonglong flushed; /* nb of compressed bytes flushed : not provided; can be tracked from caller side */ 2273 uint currentJobID; /* MT only : latest started job nb */ 2274 uint nbActiveWorkers; /* MT only : nb of workers actively compressing at probe time */ 2275 } 2276 2277 /* ZSTD_getFrameProgression() : 2278 * tells how much data has been ingested (read from input) 2279 * consumed (input actually compressed) and produced (output) for current frame. 2280 * Note : (ingested - consumed) is amount of input data buffered internally, not yet compressed. 2281 * Aggregates progression inside active worker threads. 2282 */ 2283 ZSTD_frameProgression ZSTD_getFrameProgression(const(ZSTD_CCtx)* cctx); 2284 2285 /*! ZSTD_toFlushNow() : 2286 * Tell how many bytes are ready to be flushed immediately. 2287 * Useful for multithreading scenarios (nbWorkers >= 1). 2288 * Probe the oldest active job, defined as oldest job not yet entirely flushed, 2289 * and check its output buffer. 2290 * @return : amount of data stored in oldest job and ready to be flushed immediately. 2291 * if @return == 0, it means either : 2292 * + there is no active job (could be checked with ZSTD_frameProgression()), or 2293 * + oldest job is still actively compressing data, 2294 * but everything it has produced has also been flushed so far, 2295 * therefore flush speed is limited by production speed of oldest job 2296 * irrespective of the speed of concurrent (and newer) jobs. 2297 */ 2298 size_t ZSTD_toFlushNow(ZSTD_CCtx* cctx); 2299 2300 /*===== Advanced Streaming decompression functions =====*/ 2301 2302 /*! 2303 * This function is deprecated, and is equivalent to: 2304 * 2305 * ZSTD_DCtx_reset(zds, ZSTD_reset_session_only); 2306 * ZSTD_DCtx_loadDictionary(zds, dict, dictSize); 2307 * 2308 * note: no dictionary will be used if dict == NULL or dictSize < 8 2309 * Note : this prototype will be marked as deprecated and generate compilation warnings on reaching v1.5.x 2310 */ 2311 size_t ZSTD_initDStream_usingDict(ZSTD_DStream* zds, const(void)* dict, size_t dictSize); 2312 2313 /*! 2314 * This function is deprecated, and is equivalent to: 2315 * 2316 * ZSTD_DCtx_reset(zds, ZSTD_reset_session_only); 2317 * ZSTD_DCtx_refDDict(zds, ddict); 2318 * 2319 * note : ddict is referenced, it must outlive decompression session 2320 * Note : this prototype will be marked as deprecated and generate compilation warnings on reaching v1.5.x 2321 */ 2322 size_t ZSTD_initDStream_usingDDict(ZSTD_DStream* zds, const(ZSTD_DDict)* ddict); 2323 2324 /*! 2325 * This function is deprecated, and is equivalent to: 2326 * 2327 * ZSTD_DCtx_reset(zds, ZSTD_reset_session_only); 2328 * 2329 * re-use decompression parameters from previous init; saves dictionary loading 2330 * Note : this prototype will be marked as deprecated and generate compilation warnings on reaching v1.5.x 2331 */ 2332 size_t ZSTD_resetDStream(ZSTD_DStream* zds); 2333 2334 /********************************************************************* 2335 * Buffer-less and synchronous inner streaming functions 2336 * 2337 * This is an advanced API, giving full control over buffer management, for users which need direct control over memory. 2338 * But it's also a complex one, with several restrictions, documented below. 2339 * Prefer normal streaming API for an easier experience. 2340 ********************************************************************* */ 2341 2342 /** 2343 Buffer-less streaming compression (synchronous mode) 2344 2345 A ZSTD_CCtx object is required to track streaming operations. 2346 Use ZSTD_createCCtx() / ZSTD_freeCCtx() to manage resource. 2347 ZSTD_CCtx object can be re-used multiple times within successive compression operations. 2348 2349 Start by initializing a context. 2350 Use ZSTD_compressBegin(), or ZSTD_compressBegin_usingDict() for dictionary compression. 2351 It's also possible to duplicate a reference context which has already been initialized, using ZSTD_copyCCtx() 2352 2353 Then, consume your input using ZSTD_compressContinue(). 2354 There are some important considerations to keep in mind when using this advanced function : 2355 - ZSTD_compressContinue() has no internal buffer. It uses externally provided buffers only. 2356 - Interface is synchronous : input is consumed entirely and produces 1+ compressed blocks. 2357 - Caller must ensure there is enough space in `dst` to store compressed data under worst case scenario. 2358 Worst case evaluation is provided by ZSTD_compressBound(). 2359 ZSTD_compressContinue() doesn't guarantee recover after a failed compression. 2360 - ZSTD_compressContinue() presumes prior input ***is still accessible and unmodified*** (up to maximum distance size, see WindowLog). 2361 It remembers all previous contiguous blocks, plus one separated memory segment (which can itself consists of multiple contiguous blocks) 2362 - ZSTD_compressContinue() detects that prior input has been overwritten when `src` buffer overlaps. 2363 In which case, it will "discard" the relevant memory section from its history. 2364 2365 Finish a frame with ZSTD_compressEnd(), which will write the last block(s) and optional checksum. 2366 It's possible to use srcSize==0, in which case, it will write a final empty block to end the frame. 2367 Without last block mark, frames are considered unfinished (hence corrupted) by compliant decoders. 2368 2369 `ZSTD_CCtx` object can be re-used (ZSTD_compressBegin()) to compress again. 2370 */ 2371 2372 /*===== Buffer-less streaming compression functions =====*/ 2373 size_t ZSTD_compressBegin(ZSTD_CCtx* cctx, int compressionLevel); 2374 size_t ZSTD_compressBegin_usingDict(ZSTD_CCtx* cctx, const(void)* dict, size_t dictSize, int compressionLevel); 2375 size_t ZSTD_compressBegin_usingCDict(ZSTD_CCtx* cctx, const(ZSTD_CDict)* cdict); /**< note: fails if cdict==NULL */ 2376 size_t ZSTD_copyCCtx(ZSTD_CCtx* cctx, const(ZSTD_CCtx)* preparedCCtx, cpp_ulonglong pledgedSrcSize); /**< note: if pledgedSrcSize is not known, use ZSTD_CONTENTSIZE_UNKNOWN */ 2377 2378 size_t ZSTD_compressContinue(ZSTD_CCtx* cctx, void* dst, size_t dstCapacity, const(void)* src, size_t srcSize); 2379 size_t ZSTD_compressEnd(ZSTD_CCtx* cctx, void* dst, size_t dstCapacity, const(void)* src, size_t srcSize); 2380 2381 /* The ZSTD_compressBegin_advanced() and ZSTD_compressBegin_usingCDict_advanced() are now DEPRECATED and will generate a compiler warning */ 2382 deprecated("use advanced API to access custom parameters") 2383 size_t ZSTD_compressBegin_advanced(ZSTD_CCtx* cctx, const(void)* dict, size_t dictSize, ZSTD_parameters params, 2384 cpp_ulonglong pledgedSrcSize); /**< pledgedSrcSize : If srcSize is not known at init time, use ZSTD_CONTENTSIZE_UNKNOWN */ 2385 deprecated("use advanced API to access custom parameters") 2386 size_t ZSTD_compressBegin_usingCDict_advanced(ZSTD_CCtx* cctx, const(ZSTD_CDict)* cdict, ZSTD_frameParameters fParams, 2387 cpp_ulonglong pledgedSrcSize); /* compression parameters are already set within cdict. pledgedSrcSize must be correct. If srcSize is not known, use macro ZSTD_CONTENTSIZE_UNKNOWN */ 2388 /** 2389 Buffer-less streaming decompression (synchronous mode) 2390 2391 A ZSTD_DCtx object is required to track streaming operations. 2392 Use ZSTD_createDCtx() / ZSTD_freeDCtx() to manage it. 2393 A ZSTD_DCtx object can be re-used multiple times. 2394 2395 First typical operation is to retrieve frame parameters, using ZSTD_getFrameHeader(). 2396 Frame header is extracted from the beginning of compressed frame, so providing only the frame's beginning is enough. 2397 Data fragment must be large enough to ensure successful decoding. 2398 `ZSTD_frameHeaderSize_max` bytes is guaranteed to always be large enough. 2399 @result : 0 : successful decoding, the `ZSTD_frameHeader` structure is correctly filled. 2400 >0 : `srcSize` is too small, please provide at least @result bytes on next attempt. 2401 errorCode, which can be tested using ZSTD_isError(). 2402 2403 It fills a ZSTD_frameHeader structure with important information to correctly decode the frame, 2404 such as the dictionary ID, content size, or maximum back-reference distance (`windowSize`). 2405 Note that these values could be wrong, either because of data corruption, or because a 3rd party deliberately spoofs false information. 2406 As a consequence, check that values remain within valid application range. 2407 For example, do not allocate memory blindly, check that `windowSize` is within expectation. 2408 Each application can set its own limits, depending on local restrictions. 2409 For extended interoperability, it is recommended to support `windowSize` of at least 8 MB. 2410 2411 ZSTD_decompressContinue() needs previous data blocks during decompression, up to `windowSize` bytes. 2412 ZSTD_decompressContinue() is very sensitive to contiguity, 2413 if 2 blocks don't follow each other, make sure that either the compressor breaks contiguity at the same place, 2414 or that previous contiguous segment is large enough to properly handle maximum back-reference distance. 2415 There are multiple ways to guarantee this condition. 2416 2417 The most memory efficient way is to use a round buffer of sufficient size. 2418 Sufficient size is determined by invoking ZSTD_decodingBufferSize_min(), 2419 which can @return an error code if required value is too large for current system (in 32-bits mode). 2420 In a round buffer methodology, ZSTD_decompressContinue() decompresses each block next to previous one, 2421 up to the moment there is not enough room left in the buffer to guarantee decoding another full block, 2422 which maximum size is provided in `ZSTD_frameHeader` structure, field `blockSizeMax`. 2423 At which point, decoding can resume from the beginning of the buffer. 2424 Note that already decoded data stored in the buffer should be flushed before being overwritten. 2425 2426 There are alternatives possible, for example using two or more buffers of size `windowSize` each, though they consume more memory. 2427 2428 Finally, if you control the compression process, you can also ignore all buffer size rules, 2429 as long as the encoder and decoder progress in "lock-step", 2430 aka use exactly the same buffer sizes, break contiguity at the same place, etc. 2431 2432 Once buffers are setup, start decompression, with ZSTD_decompressBegin(). 2433 If decompression requires a dictionary, use ZSTD_decompressBegin_usingDict() or ZSTD_decompressBegin_usingDDict(). 2434 2435 Then use ZSTD_nextSrcSizeToDecompress() and ZSTD_decompressContinue() alternatively. 2436 ZSTD_nextSrcSizeToDecompress() tells how many bytes to provide as 'srcSize' to ZSTD_decompressContinue(). 2437 ZSTD_decompressContinue() requires this _exact_ amount of bytes, or it will fail. 2438 2439 @result of ZSTD_decompressContinue() is the number of bytes regenerated within 'dst' (necessarily <= dstCapacity). 2440 It can be zero : it just means ZSTD_decompressContinue() has decoded some metadata item. 2441 It can also be an error code, which can be tested with ZSTD_isError(). 2442 2443 A frame is fully decoded when ZSTD_nextSrcSizeToDecompress() returns zero. 2444 Context can then be reset to start a new decompression. 2445 2446 Note : it's possible to know if next input to present is a header or a block, using ZSTD_nextInputType(). 2447 This information is not required to properly decode a frame. 2448 2449 == Special case : skippable frames == 2450 2451 Skippable frames allow integration of user-defined data into a flow of concatenated frames. 2452 Skippable frames will be ignored (skipped) by decompressor. 2453 The format of skippable frames is as follows : 2454 a) Skippable frame ID - 4 Bytes, Little endian format, any value from 0x184D2A50 to 0x184D2A5F 2455 b) Frame Size - 4 Bytes, Little endian format, unsigned 32-bits 2456 c) Frame Content - any content (User Data) of length equal to Frame Size 2457 For skippable frames ZSTD_getFrameHeader() returns zfhPtr->frameType==ZSTD_skippableFrame. 2458 For skippable frames ZSTD_decompressContinue() always returns 0 : it only skips the content. 2459 */ 2460 2461 /*===== Buffer-less streaming decompression functions =====*/ 2462 enum ZSTD_frameType_e 2463 { 2464 ZSTD_frame, 2465 ZSTD_skippableFrame 2466 } 2467 2468 struct ZSTD_frameHeader 2469 { 2470 cpp_ulonglong frameContentSize; /* if == ZSTD_CONTENTSIZE_UNKNOWN, it means this field is not available. 0 means "empty" */ 2471 cpp_ulonglong windowSize; /* can be very large, up to <= frameContentSize */ 2472 uint blockSizeMax; 2473 ZSTD_frameType_e frameType; /* if == ZSTD_skippableFrame, frameContentSize is the size of skippable content */ 2474 uint headerSize; 2475 uint dictID; 2476 uint checksumFlag; 2477 } 2478 2479 /*! ZSTD_getFrameHeader() : 2480 * decode Frame Header, or requires larger `srcSize`. 2481 * @return : 0, `zfhPtr` is correctly filled, 2482 * >0, `srcSize` is too small, value is wanted `srcSize` amount, 2483 * or an error code, which can be tested using ZSTD_isError() */ 2484 size_t ZSTD_getFrameHeader(ZSTD_frameHeader* zfhPtr, const(void)* src, size_t srcSize); /**< doesn't consume input */ 2485 /*! ZSTD_getFrameHeader_advanced() : 2486 * same as ZSTD_getFrameHeader(), 2487 * with added capability to select a format (like ZSTD_f_zstd1_magicless) */ 2488 size_t ZSTD_getFrameHeader_advanced(ZSTD_frameHeader* zfhPtr, const(void)* src, size_t srcSize, ZSTD_format_e format); 2489 size_t ZSTD_decodingBufferSize_min(cpp_ulonglong windowSize, cpp_ulonglong frameContentSize); /**< when frame content size is not known, pass in frameContentSize == ZSTD_CONTENTSIZE_UNKNOWN */ 2490 2491 size_t ZSTD_decompressBegin(ZSTD_DCtx* dctx); 2492 size_t ZSTD_decompressBegin_usingDict(ZSTD_DCtx* dctx, const(void)* dict, size_t dictSize); 2493 size_t ZSTD_decompressBegin_usingDDict(ZSTD_DCtx* dctx, const(ZSTD_DDict)* ddict); 2494 2495 size_t ZSTD_nextSrcSizeToDecompress(ZSTD_DCtx* dctx); 2496 size_t ZSTD_decompressContinue(ZSTD_DCtx* dctx, void* dst, size_t dstCapacity, const(void)* src, size_t srcSize); 2497 2498 /* misc */ 2499 void ZSTD_copyDCtx(ZSTD_DCtx* dctx, const(ZSTD_DCtx)* preparedDCtx); 2500 enum ZSTD_nextInputType_e 2501 { 2502 ZSTDnit_frameHeader, 2503 ZSTDnit_blockHeader, 2504 ZSTDnit_block, 2505 ZSTDnit_lastBlock, 2506 ZSTDnit_checksum, 2507 ZSTDnit_skippableFrame 2508 } 2509 2510 ZSTD_nextInputType_e ZSTD_nextInputType(ZSTD_DCtx* dctx); 2511 2512 /* ============================ */ 2513 /** Block level API */ 2514 /* ============================ */ 2515 2516 /*! 2517 Block functions produce and decode raw zstd blocks, without frame metadata. 2518 Frame metadata cost is typically ~12 bytes, which can be non-negligible for very small blocks (< 100 bytes). 2519 But users will have to take in charge needed metadata to regenerate data, such as compressed and content sizes. 2520 2521 A few rules to respect : 2522 - Compressing and decompressing require a context structure 2523 + Use ZSTD_createCCtx() and ZSTD_createDCtx() 2524 - It is necessary to init context before starting 2525 + compression : any ZSTD_compressBegin*() variant, including with dictionary 2526 + decompression : any ZSTD_decompressBegin*() variant, including with dictionary 2527 + copyCCtx() and copyDCtx() can be used too 2528 - Block size is limited, it must be <= ZSTD_getBlockSize() <= ZSTD_BLOCKSIZE_MAX == 128 KB 2529 + If input is larger than a block size, it's necessary to split input data into multiple blocks 2530 + For inputs larger than a single block, consider using regular ZSTD_compress() instead. 2531 Frame metadata is not that costly, and quickly becomes negligible as source size grows larger than a block. 2532 - When a block is considered not compressible enough, ZSTD_compressBlock() result will be 0 (zero) ! 2533 ===> In which case, nothing is produced into `dst` ! 2534 + User __must__ test for such outcome and deal directly with uncompressed data 2535 + A block cannot be declared incompressible if ZSTD_compressBlock() return value was != 0. 2536 Doing so would mess up with statistics history, leading to potential data corruption. 2537 + ZSTD_decompressBlock() _doesn't accept uncompressed data as input_ !! 2538 + In case of multiple successive blocks, should some of them be uncompressed, 2539 decoder must be informed of their existence in order to follow proper history. 2540 Use ZSTD_insertBlock() for such a case. 2541 */ 2542 2543 /*===== Raw zstd block functions =====*/ 2544 size_t ZSTD_getBlockSize(const(ZSTD_CCtx)* cctx); 2545 size_t ZSTD_compressBlock(ZSTD_CCtx* cctx, void* dst, size_t dstCapacity, const(void)* src, size_t srcSize); 2546 size_t ZSTD_decompressBlock(ZSTD_DCtx* dctx, void* dst, size_t dstCapacity, const(void)* src, size_t srcSize); 2547 size_t ZSTD_insertBlock(ZSTD_DCtx* dctx, const(void)* blockStart, size_t blockSize); /**< insert uncompressed block into `dctx` history. Useful for multi-blocks decompression. */