Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

zstd.h 74KB

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