zstd.h 82 KB

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