zstd.h 167 KB

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