zstd_compress.c 126 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024
  1. /*
  2. * Copyright (c) 2016-present, Yann Collet, Facebook, Inc.
  3. * All rights reserved.
  4. *
  5. * This source code is licensed under both the BSD-style license (found in the
  6. * LICENSE file in the root directory of this source tree) and the GPLv2 (found
  7. * in the COPYING file in the root directory of this source tree).
  8. * You may select, at your option, one of the above-listed licenses.
  9. */
  10. /*-*************************************
  11. * Tuning parameters
  12. ***************************************/
  13. #ifndef ZSTD_CLEVEL_DEFAULT
  14. # define ZSTD_CLEVEL_DEFAULT 3
  15. #endif
  16. /*-*************************************
  17. * Dependencies
  18. ***************************************/
  19. #include <string.h> /* memset */
  20. #include "mem.h"
  21. #define FSE_STATIC_LINKING_ONLY /* FSE_encodeSymbol */
  22. #include "fse.h"
  23. #define HUF_STATIC_LINKING_ONLY
  24. #include "huf.h"
  25. #include "zstd_compress.h"
  26. #include "zstd_fast.h"
  27. #include "zstd_double_fast.h"
  28. #include "zstd_lazy.h"
  29. #include "zstd_opt.h"
  30. #include "zstd_ldm.h"
  31. /*-*************************************
  32. * Helper functions
  33. ***************************************/
  34. size_t ZSTD_compressBound(size_t srcSize) {
  35. return ZSTD_COMPRESSBOUND(srcSize);
  36. }
  37. /*-*************************************
  38. * Sequence storage
  39. ***************************************/
  40. static void ZSTD_resetSeqStore(seqStore_t* ssPtr)
  41. {
  42. ssPtr->lit = ssPtr->litStart;
  43. ssPtr->sequences = ssPtr->sequencesStart;
  44. ssPtr->longLengthID = 0;
  45. }
  46. /*-*************************************
  47. * Context memory management
  48. ***************************************/
  49. struct ZSTD_CDict_s {
  50. void* dictBuffer;
  51. const void* dictContent;
  52. size_t dictContentSize;
  53. ZSTD_CCtx* refContext;
  54. }; /* typedef'd to ZSTD_CDict within "zstd.h" */
  55. ZSTD_CCtx* ZSTD_createCCtx(void)
  56. {
  57. return ZSTD_createCCtx_advanced(ZSTD_defaultCMem);
  58. }
  59. ZSTD_CCtx* ZSTD_createCCtx_advanced(ZSTD_customMem customMem)
  60. {
  61. ZSTD_CCtx* cctx;
  62. if (!customMem.customAlloc ^ !customMem.customFree) return NULL;
  63. cctx = (ZSTD_CCtx*) ZSTD_calloc(sizeof(ZSTD_CCtx), customMem);
  64. if (!cctx) return NULL;
  65. cctx->customMem = customMem;
  66. cctx->requestedParams.compressionLevel = ZSTD_CLEVEL_DEFAULT;
  67. ZSTD_STATIC_ASSERT(zcss_init==0);
  68. ZSTD_STATIC_ASSERT(ZSTD_CONTENTSIZE_UNKNOWN==(0ULL - 1));
  69. return cctx;
  70. }
  71. ZSTD_CCtx* ZSTD_initStaticCCtx(void *workspace, size_t workspaceSize)
  72. {
  73. ZSTD_CCtx* const cctx = (ZSTD_CCtx*) workspace;
  74. if (workspaceSize <= sizeof(ZSTD_CCtx)) return NULL; /* minimum size */
  75. if ((size_t)workspace & 7) return NULL; /* must be 8-aligned */
  76. memset(workspace, 0, workspaceSize); /* may be a bit generous, could memset be smaller ? */
  77. cctx->staticSize = workspaceSize;
  78. cctx->workSpace = (void*)(cctx+1);
  79. cctx->workSpaceSize = workspaceSize - sizeof(ZSTD_CCtx);
  80. /* entropy space (never moves) */
  81. if (cctx->workSpaceSize < sizeof(ZSTD_entropyCTables_t)) return NULL;
  82. assert(((size_t)cctx->workSpace & (sizeof(void*)-1)) == 0); /* ensure correct alignment */
  83. cctx->entropy = (ZSTD_entropyCTables_t*)cctx->workSpace;
  84. return cctx;
  85. }
  86. size_t ZSTD_freeCCtx(ZSTD_CCtx* cctx)
  87. {
  88. if (cctx==NULL) return 0; /* support free on NULL */
  89. if (cctx->staticSize) return ERROR(memory_allocation); /* not compatible with static CCtx */
  90. ZSTD_free(cctx->workSpace, cctx->customMem);
  91. cctx->workSpace = NULL;
  92. ZSTD_freeCDict(cctx->cdictLocal);
  93. cctx->cdictLocal = NULL;
  94. #ifdef ZSTD_MULTITHREAD
  95. ZSTDMT_freeCCtx(cctx->mtctx);
  96. cctx->mtctx = NULL;
  97. #endif
  98. ZSTD_free(cctx, cctx->customMem);
  99. return 0; /* reserved as a potential error code in the future */
  100. }
  101. static size_t ZSTD_sizeof_mtctx(const ZSTD_CCtx* cctx)
  102. {
  103. #ifdef ZSTD_MULTITHREAD
  104. return ZSTDMT_sizeof_CCtx(cctx->mtctx);
  105. #else
  106. (void) cctx;
  107. return 0;
  108. #endif
  109. }
  110. size_t ZSTD_sizeof_CCtx(const ZSTD_CCtx* cctx)
  111. {
  112. if (cctx==NULL) return 0; /* support sizeof on NULL */
  113. DEBUGLOG(3, "sizeof(*cctx) : %u", (U32)sizeof(*cctx));
  114. DEBUGLOG(3, "workSpaceSize (including streaming buffers): %u", (U32)cctx->workSpaceSize);
  115. DEBUGLOG(3, "inner cdict : %u", (U32)ZSTD_sizeof_CDict(cctx->cdictLocal));
  116. DEBUGLOG(3, "inner MTCTX : %u", (U32)ZSTD_sizeof_mtctx(cctx));
  117. return sizeof(*cctx) + cctx->workSpaceSize
  118. + ZSTD_sizeof_CDict(cctx->cdictLocal)
  119. + ZSTD_sizeof_mtctx(cctx);
  120. }
  121. size_t ZSTD_sizeof_CStream(const ZSTD_CStream* zcs)
  122. {
  123. return ZSTD_sizeof_CCtx(zcs); /* same object */
  124. }
  125. /* private API call, for dictBuilder only */
  126. const seqStore_t* ZSTD_getSeqStore(const ZSTD_CCtx* ctx) { return &(ctx->seqStore); }
  127. #define ZSTD_CLEVEL_CUSTOM 999
  128. static ZSTD_compressionParameters ZSTD_getCParamsFromCCtxParams(
  129. ZSTD_CCtx_params params, U64 srcSizeHint, size_t dictSize)
  130. {
  131. return (params.compressionLevel == ZSTD_CLEVEL_CUSTOM ?
  132. params.cParams :
  133. ZSTD_getCParams(params.compressionLevel, srcSizeHint, dictSize));
  134. }
  135. static void ZSTD_cLevelToCCtxParams_srcSize(ZSTD_CCtx_params* params, U64 srcSize)
  136. {
  137. params->cParams = ZSTD_getCParamsFromCCtxParams(*params, srcSize, 0);
  138. params->compressionLevel = ZSTD_CLEVEL_CUSTOM;
  139. }
  140. static void ZSTD_cLevelToCParams(ZSTD_CCtx* cctx)
  141. {
  142. ZSTD_cLevelToCCtxParams_srcSize(
  143. &cctx->requestedParams, cctx->pledgedSrcSizePlusOne-1);
  144. }
  145. static void ZSTD_cLevelToCCtxParams(ZSTD_CCtx_params* params)
  146. {
  147. ZSTD_cLevelToCCtxParams_srcSize(params, 0);
  148. }
  149. static ZSTD_CCtx_params ZSTD_makeCCtxParamsFromCParams(
  150. ZSTD_compressionParameters cParams)
  151. {
  152. ZSTD_CCtx_params cctxParams;
  153. memset(&cctxParams, 0, sizeof(cctxParams));
  154. cctxParams.cParams = cParams;
  155. cctxParams.compressionLevel = ZSTD_CLEVEL_CUSTOM;
  156. return cctxParams;
  157. }
  158. static ZSTD_CCtx_params* ZSTD_createCCtxParams_advanced(
  159. ZSTD_customMem customMem)
  160. {
  161. ZSTD_CCtx_params* params;
  162. if (!customMem.customAlloc ^ !customMem.customFree) return NULL;
  163. params = (ZSTD_CCtx_params*)ZSTD_calloc(
  164. sizeof(ZSTD_CCtx_params), customMem);
  165. if (!params) { return NULL; }
  166. params->customMem = customMem;
  167. params->compressionLevel = ZSTD_CLEVEL_DEFAULT;
  168. return params;
  169. }
  170. ZSTD_CCtx_params* ZSTD_createCCtxParams(void)
  171. {
  172. return ZSTD_createCCtxParams_advanced(ZSTD_defaultCMem);
  173. }
  174. size_t ZSTD_freeCCtxParams(ZSTD_CCtx_params* params)
  175. {
  176. if (params == NULL) { return 0; }
  177. ZSTD_free(params, params->customMem);
  178. return 0;
  179. }
  180. size_t ZSTD_resetCCtxParams(ZSTD_CCtx_params* params)
  181. {
  182. return ZSTD_initCCtxParams(params, ZSTD_CLEVEL_DEFAULT);
  183. }
  184. size_t ZSTD_initCCtxParams(ZSTD_CCtx_params* cctxParams, int compressionLevel) {
  185. if (!cctxParams) { return ERROR(GENERIC); }
  186. memset(cctxParams, 0, sizeof(*cctxParams));
  187. cctxParams->compressionLevel = compressionLevel;
  188. return 0;
  189. }
  190. size_t ZSTD_initCCtxParams_advanced(ZSTD_CCtx_params* cctxParams, ZSTD_parameters params)
  191. {
  192. if (!cctxParams) { return ERROR(GENERIC); }
  193. CHECK_F( ZSTD_checkCParams(params.cParams) );
  194. memset(cctxParams, 0, sizeof(*cctxParams));
  195. cctxParams->cParams = params.cParams;
  196. cctxParams->fParams = params.fParams;
  197. cctxParams->compressionLevel = ZSTD_CLEVEL_CUSTOM;
  198. return 0;
  199. }
  200. static ZSTD_CCtx_params ZSTD_assignParamsToCCtxParams(
  201. ZSTD_CCtx_params cctxParams, ZSTD_parameters params)
  202. {
  203. ZSTD_CCtx_params ret = cctxParams;
  204. ret.cParams = params.cParams;
  205. ret.fParams = params.fParams;
  206. ret.compressionLevel = ZSTD_CLEVEL_CUSTOM;
  207. return ret;
  208. }
  209. #define CLAMPCHECK(val,min,max) { \
  210. if (((val)<(min)) | ((val)>(max))) { \
  211. return ERROR(parameter_outOfBound); \
  212. } }
  213. size_t ZSTD_CCtx_setParameter(ZSTD_CCtx* cctx, ZSTD_cParameter param, unsigned value)
  214. {
  215. if (cctx->streamStage != zcss_init) return ERROR(stage_wrong);
  216. switch(param)
  217. {
  218. case ZSTD_p_format :
  219. return ZSTD_CCtxParam_setParameter(&cctx->requestedParams, param, value);
  220. case ZSTD_p_compressionLevel:
  221. if (value == 0) return 0; /* special value : 0 means "don't change anything" */
  222. if (cctx->cdict) return ERROR(stage_wrong);
  223. return ZSTD_CCtxParam_setParameter(&cctx->requestedParams, param, value);
  224. case ZSTD_p_windowLog:
  225. case ZSTD_p_hashLog:
  226. case ZSTD_p_chainLog:
  227. case ZSTD_p_searchLog:
  228. case ZSTD_p_minMatch:
  229. case ZSTD_p_targetLength:
  230. case ZSTD_p_compressionStrategy:
  231. if (value == 0) return 0; /* special value : 0 means "don't change anything" */
  232. if (cctx->cdict) return ERROR(stage_wrong);
  233. ZSTD_cLevelToCParams(cctx); /* Can optimize if srcSize is known */
  234. return ZSTD_CCtxParam_setParameter(&cctx->requestedParams, param, value);
  235. case ZSTD_p_contentSizeFlag:
  236. case ZSTD_p_checksumFlag:
  237. case ZSTD_p_dictIDFlag:
  238. return ZSTD_CCtxParam_setParameter(&cctx->requestedParams, param, value);
  239. case ZSTD_p_forceMaxWindow : /* Force back-references to remain < windowSize,
  240. * even when referencing into Dictionary content
  241. * default : 0 when using a CDict, 1 when using a Prefix */
  242. cctx->loadedDictEnd = 0;
  243. return ZSTD_CCtxParam_setParameter(&cctx->requestedParams, param, value);
  244. case ZSTD_p_nbThreads:
  245. if (value==0) return 0;
  246. DEBUGLOG(5, " setting nbThreads : %u", value);
  247. if (value > 1 && cctx->staticSize) {
  248. return ERROR(parameter_unsupported); /* MT not compatible with static alloc */
  249. }
  250. return ZSTD_CCtxParam_setParameter(&cctx->requestedParams, param, value);
  251. case ZSTD_p_jobSize:
  252. return ZSTD_CCtxParam_setParameter(&cctx->requestedParams, param, value);
  253. case ZSTD_p_overlapSizeLog:
  254. DEBUGLOG(5, " setting overlap with nbThreads == %u", cctx->requestedParams.nbThreads);
  255. return ZSTD_CCtxParam_setParameter(&cctx->requestedParams, param, value);
  256. case ZSTD_p_enableLongDistanceMatching:
  257. if (cctx->cdict) return ERROR(stage_wrong);
  258. if (value != 0) {
  259. ZSTD_cLevelToCParams(cctx);
  260. }
  261. return ZSTD_CCtxParam_setParameter(&cctx->requestedParams, param, value);
  262. case ZSTD_p_ldmHashLog:
  263. case ZSTD_p_ldmMinMatch:
  264. if (value == 0) return 0; /* special value : 0 means "don't change anything" */
  265. if (cctx->cdict) return ERROR(stage_wrong);
  266. return ZSTD_CCtxParam_setParameter(&cctx->requestedParams, param, value);
  267. case ZSTD_p_ldmBucketSizeLog:
  268. case ZSTD_p_ldmHashEveryLog:
  269. if (cctx->cdict) return ERROR(stage_wrong);
  270. return ZSTD_CCtxParam_setParameter(&cctx->requestedParams, param, value);
  271. default: return ERROR(parameter_unsupported);
  272. }
  273. }
  274. size_t ZSTD_CCtxParam_setParameter(
  275. ZSTD_CCtx_params* params, ZSTD_cParameter param, unsigned value)
  276. {
  277. switch(param)
  278. {
  279. case ZSTD_p_format :
  280. if (value > (unsigned)ZSTD_f_zstd1_magicless)
  281. return ERROR(parameter_unsupported);
  282. params->format = (ZSTD_format_e)value;
  283. return 0;
  284. case ZSTD_p_compressionLevel :
  285. if ((int)value > ZSTD_maxCLevel()) value = ZSTD_maxCLevel();
  286. if (value == 0) return 0;
  287. params->compressionLevel = value;
  288. return 0;
  289. case ZSTD_p_windowLog :
  290. if (value == 0) return 0;
  291. CLAMPCHECK(value, ZSTD_WINDOWLOG_MIN, ZSTD_WINDOWLOG_MAX);
  292. ZSTD_cLevelToCCtxParams(params);
  293. params->cParams.windowLog = value;
  294. return 0;
  295. case ZSTD_p_hashLog :
  296. if (value == 0) return 0;
  297. CLAMPCHECK(value, ZSTD_HASHLOG_MIN, ZSTD_HASHLOG_MAX);
  298. ZSTD_cLevelToCCtxParams(params);
  299. params->cParams.hashLog = value;
  300. return 0;
  301. case ZSTD_p_chainLog :
  302. if (value == 0) return 0;
  303. CLAMPCHECK(value, ZSTD_CHAINLOG_MIN, ZSTD_CHAINLOG_MAX);
  304. ZSTD_cLevelToCCtxParams(params);
  305. params->cParams.chainLog = value;
  306. return 0;
  307. case ZSTD_p_searchLog :
  308. if (value == 0) return 0;
  309. CLAMPCHECK(value, ZSTD_SEARCHLOG_MIN, ZSTD_SEARCHLOG_MAX);
  310. ZSTD_cLevelToCCtxParams(params);
  311. params->cParams.searchLog = value;
  312. return 0;
  313. case ZSTD_p_minMatch :
  314. if (value == 0) return 0;
  315. CLAMPCHECK(value, ZSTD_SEARCHLENGTH_MIN, ZSTD_SEARCHLENGTH_MAX);
  316. ZSTD_cLevelToCCtxParams(params);
  317. params->cParams.searchLength = value;
  318. return 0;
  319. case ZSTD_p_targetLength :
  320. if (value == 0) return 0;
  321. CLAMPCHECK(value, ZSTD_TARGETLENGTH_MIN, ZSTD_TARGETLENGTH_MAX);
  322. ZSTD_cLevelToCCtxParams(params);
  323. params->cParams.targetLength = value;
  324. return 0;
  325. case ZSTD_p_compressionStrategy :
  326. if (value == 0) return 0;
  327. CLAMPCHECK(value, (unsigned)ZSTD_fast, (unsigned)ZSTD_btultra);
  328. ZSTD_cLevelToCCtxParams(params);
  329. params->cParams.strategy = (ZSTD_strategy)value;
  330. return 0;
  331. case ZSTD_p_contentSizeFlag :
  332. /* Content size written in frame header _when known_ (default:1) */
  333. DEBUGLOG(5, "set content size flag = %u", (value>0));
  334. params->fParams.contentSizeFlag = value > 0;
  335. return 0;
  336. case ZSTD_p_checksumFlag :
  337. /* A 32-bits content checksum will be calculated and written at end of frame (default:0) */
  338. params->fParams.checksumFlag = value > 0;
  339. return 0;
  340. case ZSTD_p_dictIDFlag : /* When applicable, dictionary's dictID is provided in frame header (default:1) */
  341. DEBUGLOG(5, "set dictIDFlag = %u", (value>0));
  342. params->fParams.noDictIDFlag = (value == 0);
  343. return 0;
  344. case ZSTD_p_forceMaxWindow :
  345. params->forceWindow = value > 0;
  346. return 0;
  347. case ZSTD_p_nbThreads :
  348. if (value == 0) return 0;
  349. #ifndef ZSTD_MULTITHREAD
  350. if (value > 1) return ERROR(parameter_unsupported);
  351. return 0;
  352. #else
  353. return ZSTDMT_initializeCCtxParameters(params, value);
  354. #endif
  355. case ZSTD_p_jobSize :
  356. #ifndef ZSTD_MULTITHREAD
  357. return ERROR(parameter_unsupported);
  358. #else
  359. if (params->nbThreads <= 1) return ERROR(parameter_unsupported);
  360. return ZSTDMT_CCtxParam_setMTCtxParameter(params, ZSTDMT_p_sectionSize, value);
  361. #endif
  362. case ZSTD_p_overlapSizeLog :
  363. #ifndef ZSTD_MULTITHREAD
  364. return ERROR(parameter_unsupported);
  365. #else
  366. if (params->nbThreads <= 1) return ERROR(parameter_unsupported);
  367. return ZSTDMT_CCtxParam_setMTCtxParameter(params, ZSTDMT_p_overlapSectionLog, value);
  368. #endif
  369. case ZSTD_p_enableLongDistanceMatching :
  370. if (value != 0) {
  371. ZSTD_cLevelToCCtxParams(params);
  372. params->cParams.windowLog = ZSTD_LDM_DEFAULT_WINDOW_LOG;
  373. }
  374. return ZSTD_ldm_initializeParameters(&params->ldmParams, value);
  375. case ZSTD_p_ldmHashLog :
  376. if (value == 0) return 0;
  377. CLAMPCHECK(value, ZSTD_HASHLOG_MIN, ZSTD_HASHLOG_MAX);
  378. params->ldmParams.hashLog = value;
  379. return 0;
  380. case ZSTD_p_ldmMinMatch :
  381. if (value == 0) return 0;
  382. CLAMPCHECK(value, ZSTD_LDM_MINMATCH_MIN, ZSTD_LDM_MINMATCH_MAX);
  383. params->ldmParams.minMatchLength = value;
  384. return 0;
  385. case ZSTD_p_ldmBucketSizeLog :
  386. if (value > ZSTD_LDM_BUCKETSIZELOG_MAX) {
  387. return ERROR(parameter_outOfBound);
  388. }
  389. params->ldmParams.bucketSizeLog = value;
  390. return 0;
  391. case ZSTD_p_ldmHashEveryLog :
  392. if (value > ZSTD_WINDOWLOG_MAX - ZSTD_HASHLOG_MIN) {
  393. return ERROR(parameter_outOfBound);
  394. }
  395. params->ldmParams.hashEveryLog = value;
  396. return 0;
  397. default: return ERROR(parameter_unsupported);
  398. }
  399. }
  400. /**
  401. * This function should be updated whenever ZSTD_CCtx_params is updated.
  402. * Parameters are copied manually before the dictionary is loaded.
  403. * The multithreading parameters jobSize and overlapSizeLog are set only if
  404. * nbThreads > 1.
  405. *
  406. * Pledged srcSize is treated as unknown.
  407. */
  408. size_t ZSTD_CCtx_setParametersUsingCCtxParams(
  409. ZSTD_CCtx* cctx, const ZSTD_CCtx_params* params)
  410. {
  411. if (cctx->streamStage != zcss_init) return ERROR(stage_wrong);
  412. if (cctx->cdict) return ERROR(stage_wrong);
  413. /* Assume the compression and frame parameters are validated */
  414. cctx->requestedParams.cParams = params->cParams;
  415. cctx->requestedParams.fParams = params->fParams;
  416. cctx->requestedParams.compressionLevel = params->compressionLevel;
  417. /* Set force window explicitly since it sets cctx->loadedDictEnd */
  418. CHECK_F( ZSTD_CCtx_setParameter(
  419. cctx, ZSTD_p_forceMaxWindow, params->forceWindow) );
  420. /* Set multithreading parameters explicitly */
  421. CHECK_F( ZSTD_CCtx_setParameter(cctx, ZSTD_p_nbThreads, params->nbThreads) );
  422. if (params->nbThreads > 1) {
  423. CHECK_F( ZSTD_CCtx_setParameter(cctx, ZSTD_p_jobSize, params->jobSize) );
  424. CHECK_F( ZSTD_CCtx_setParameter(
  425. cctx, ZSTD_p_overlapSizeLog, params->overlapSizeLog) );
  426. }
  427. /* Copy long distance matching parameters */
  428. cctx->requestedParams.ldmParams = params->ldmParams;
  429. /* customMem is used only for create/free params and can be ignored */
  430. return 0;
  431. }
  432. ZSTDLIB_API size_t ZSTD_CCtx_setPledgedSrcSize(ZSTD_CCtx* cctx, unsigned long long pledgedSrcSize)
  433. {
  434. DEBUGLOG(4, " setting pledgedSrcSize to %u", (U32)pledgedSrcSize);
  435. if (cctx->streamStage != zcss_init) return ERROR(stage_wrong);
  436. cctx->pledgedSrcSizePlusOne = pledgedSrcSize+1;
  437. return 0;
  438. }
  439. size_t ZSTD_CCtx_loadDictionary_advanced(
  440. ZSTD_CCtx* cctx, const void* dict, size_t dictSize,
  441. ZSTD_dictLoadMethod_e dictLoadMethod, ZSTD_dictMode_e dictMode)
  442. {
  443. if (cctx->streamStage != zcss_init) return ERROR(stage_wrong);
  444. if (cctx->staticSize) return ERROR(memory_allocation); /* no malloc for static CCtx */
  445. DEBUGLOG(4, "load dictionary of size %u", (U32)dictSize);
  446. ZSTD_freeCDict(cctx->cdictLocal); /* in case one already exists */
  447. if (dict==NULL || dictSize==0) { /* no dictionary mode */
  448. cctx->cdictLocal = NULL;
  449. cctx->cdict = NULL;
  450. } else {
  451. ZSTD_compressionParameters const cParams =
  452. ZSTD_getCParamsFromCCtxParams(cctx->requestedParams, 0, dictSize);
  453. cctx->cdictLocal = ZSTD_createCDict_advanced(
  454. dict, dictSize,
  455. dictLoadMethod, dictMode,
  456. cParams, cctx->customMem);
  457. cctx->cdict = cctx->cdictLocal;
  458. if (cctx->cdictLocal == NULL)
  459. return ERROR(memory_allocation);
  460. }
  461. return 0;
  462. }
  463. ZSTDLIB_API size_t ZSTD_CCtx_loadDictionary_byReference(
  464. ZSTD_CCtx* cctx, const void* dict, size_t dictSize)
  465. {
  466. return ZSTD_CCtx_loadDictionary_advanced(
  467. cctx, dict, dictSize, ZSTD_dlm_byRef, ZSTD_dm_auto);
  468. }
  469. ZSTDLIB_API size_t ZSTD_CCtx_loadDictionary(ZSTD_CCtx* cctx, const void* dict, size_t dictSize)
  470. {
  471. return ZSTD_CCtx_loadDictionary_advanced(
  472. cctx, dict, dictSize, ZSTD_dlm_byCopy, ZSTD_dm_auto);
  473. }
  474. size_t ZSTD_CCtx_refCDict(ZSTD_CCtx* cctx, const ZSTD_CDict* cdict)
  475. {
  476. if (cctx->streamStage != zcss_init) return ERROR(stage_wrong);
  477. cctx->cdict = cdict;
  478. memset(&cctx->prefixDict, 0, sizeof(cctx->prefixDict)); /* exclusive */
  479. return 0;
  480. }
  481. size_t ZSTD_CCtx_refPrefix(ZSTD_CCtx* cctx, const void* prefix, size_t prefixSize)
  482. {
  483. return ZSTD_CCtx_refPrefix_advanced(cctx, prefix, prefixSize, ZSTD_dm_rawContent);
  484. }
  485. size_t ZSTD_CCtx_refPrefix_advanced(
  486. ZSTD_CCtx* cctx, const void* prefix, size_t prefixSize, ZSTD_dictMode_e dictMode)
  487. {
  488. if (cctx->streamStage != zcss_init) return ERROR(stage_wrong);
  489. cctx->cdict = NULL; /* prefix discards any prior cdict */
  490. cctx->prefixDict.dict = prefix;
  491. cctx->prefixDict.dictSize = prefixSize;
  492. cctx->prefixDict.dictMode = dictMode;
  493. return 0;
  494. }
  495. static void ZSTD_startNewCompression(ZSTD_CCtx* cctx)
  496. {
  497. cctx->streamStage = zcss_init;
  498. cctx->pledgedSrcSizePlusOne = 0;
  499. }
  500. /*! ZSTD_CCtx_reset() :
  501. * Also dumps dictionary */
  502. void ZSTD_CCtx_reset(ZSTD_CCtx* cctx)
  503. {
  504. ZSTD_startNewCompression(cctx);
  505. cctx->cdict = NULL;
  506. }
  507. /** ZSTD_checkCParams() :
  508. control CParam values remain within authorized range.
  509. @return : 0, or an error code if one value is beyond authorized range */
  510. size_t ZSTD_checkCParams(ZSTD_compressionParameters cParams)
  511. {
  512. CLAMPCHECK(cParams.windowLog, ZSTD_WINDOWLOG_MIN, ZSTD_WINDOWLOG_MAX);
  513. CLAMPCHECK(cParams.chainLog, ZSTD_CHAINLOG_MIN, ZSTD_CHAINLOG_MAX);
  514. CLAMPCHECK(cParams.hashLog, ZSTD_HASHLOG_MIN, ZSTD_HASHLOG_MAX);
  515. CLAMPCHECK(cParams.searchLog, ZSTD_SEARCHLOG_MIN, ZSTD_SEARCHLOG_MAX);
  516. CLAMPCHECK(cParams.searchLength, ZSTD_SEARCHLENGTH_MIN, ZSTD_SEARCHLENGTH_MAX);
  517. CLAMPCHECK(cParams.targetLength, ZSTD_TARGETLENGTH_MIN, ZSTD_TARGETLENGTH_MAX);
  518. if ((U32)(cParams.strategy) > (U32)ZSTD_btultra)
  519. return ERROR(parameter_unsupported);
  520. return 0;
  521. }
  522. /** ZSTD_clampCParams() :
  523. * make CParam values within valid range.
  524. * @return : valid CParams */
  525. static ZSTD_compressionParameters ZSTD_clampCParams(ZSTD_compressionParameters cParams)
  526. {
  527. # define CLAMP(val,min,max) { \
  528. if (val<min) val=min; \
  529. else if (val>max) val=max; \
  530. }
  531. CLAMP(cParams.windowLog, ZSTD_WINDOWLOG_MIN, ZSTD_WINDOWLOG_MAX);
  532. CLAMP(cParams.chainLog, ZSTD_CHAINLOG_MIN, ZSTD_CHAINLOG_MAX);
  533. CLAMP(cParams.hashLog, ZSTD_HASHLOG_MIN, ZSTD_HASHLOG_MAX);
  534. CLAMP(cParams.searchLog, ZSTD_SEARCHLOG_MIN, ZSTD_SEARCHLOG_MAX);
  535. CLAMP(cParams.searchLength, ZSTD_SEARCHLENGTH_MIN, ZSTD_SEARCHLENGTH_MAX);
  536. CLAMP(cParams.targetLength, ZSTD_TARGETLENGTH_MIN, ZSTD_TARGETLENGTH_MAX);
  537. if ((U32)(cParams.strategy) > (U32)ZSTD_btultra) cParams.strategy = ZSTD_btultra;
  538. return cParams;
  539. }
  540. /** ZSTD_cycleLog() :
  541. * condition for correct operation : hashLog > 1 */
  542. static U32 ZSTD_cycleLog(U32 hashLog, ZSTD_strategy strat)
  543. {
  544. U32 const btScale = ((U32)strat >= (U32)ZSTD_btlazy2);
  545. return hashLog - btScale;
  546. }
  547. /** ZSTD_adjustCParams_internal() :
  548. optimize `cPar` for a given input (`srcSize` and `dictSize`).
  549. mostly downsizing to reduce memory consumption and initialization latency.
  550. Both `srcSize` and `dictSize` are optional (use 0 if unknown).
  551. Note : cPar is considered validated at this stage. Use ZSTD_checkCParams() to ensure that condition. */
  552. ZSTD_compressionParameters ZSTD_adjustCParams_internal(ZSTD_compressionParameters cPar, unsigned long long srcSize, size_t dictSize)
  553. {
  554. static const U64 minSrcSize = 513; /* (1<<9) + 1 */
  555. static const U64 maxWindowResize = 1ULL << (ZSTD_WINDOWLOG_MAX-1);
  556. assert(ZSTD_checkCParams(cPar)==0);
  557. if (dictSize && (srcSize+1<2) /* srcSize unknown */ )
  558. srcSize = minSrcSize; /* presumed small when there is a dictionary */
  559. else if (srcSize == 0)
  560. srcSize = ZSTD_CONTENTSIZE_UNKNOWN; /* 0 == unknown : presumed large */
  561. /* resize windowLog if input is small enough, to use less memory */
  562. if ( (srcSize < maxWindowResize)
  563. && (dictSize < maxWindowResize) ) {
  564. U32 const tSize = (U32)(srcSize + dictSize);
  565. static U32 const hashSizeMin = 1 << ZSTD_HASHLOG_MIN;
  566. U32 const srcLog = (tSize < hashSizeMin) ? ZSTD_HASHLOG_MIN :
  567. ZSTD_highbit32(tSize-1) + 1;
  568. if (cPar.windowLog > srcLog) cPar.windowLog = srcLog;
  569. }
  570. if (cPar.hashLog > cPar.windowLog) cPar.hashLog = cPar.windowLog;
  571. { U32 const cycleLog = ZSTD_cycleLog(cPar.chainLog, cPar.strategy);
  572. if (cycleLog > cPar.windowLog)
  573. cPar.chainLog -= (cycleLog - cPar.windowLog);
  574. }
  575. if (cPar.windowLog < ZSTD_WINDOWLOG_ABSOLUTEMIN)
  576. cPar.windowLog = ZSTD_WINDOWLOG_ABSOLUTEMIN; /* required for frame header */
  577. return cPar;
  578. }
  579. ZSTD_compressionParameters ZSTD_adjustCParams(ZSTD_compressionParameters cPar, unsigned long long srcSize, size_t dictSize)
  580. {
  581. cPar = ZSTD_clampCParams(cPar);
  582. return ZSTD_adjustCParams_internal(cPar, srcSize, dictSize);
  583. }
  584. size_t ZSTD_estimateCCtxSize_usingCCtxParams(const ZSTD_CCtx_params* params)
  585. {
  586. /* Estimate CCtx size is supported for single-threaded compression only. */
  587. if (params->nbThreads > 1) { return ERROR(GENERIC); }
  588. { ZSTD_compressionParameters const cParams =
  589. ZSTD_getCParamsFromCCtxParams(*params, 0, 0);
  590. size_t const blockSize = MIN(ZSTD_BLOCKSIZE_MAX, (size_t)1 << cParams.windowLog);
  591. U32 const divider = (cParams.searchLength==3) ? 3 : 4;
  592. size_t const maxNbSeq = blockSize / divider;
  593. size_t const tokenSpace = blockSize + 11*maxNbSeq;
  594. size_t const chainSize =
  595. (cParams.strategy == ZSTD_fast) ? 0 : ((size_t)1 << cParams.chainLog);
  596. size_t const hSize = ((size_t)1) << cParams.hashLog;
  597. U32 const hashLog3 = (cParams.searchLength>3) ?
  598. 0 : MIN(ZSTD_HASHLOG3_MAX, cParams.windowLog);
  599. size_t const h3Size = ((size_t)1) << hashLog3;
  600. size_t const entropySpace = sizeof(ZSTD_entropyCTables_t);
  601. size_t const tableSpace = (chainSize + hSize + h3Size) * sizeof(U32);
  602. size_t const optBudget =
  603. ((MaxML+1) + (MaxLL+1) + (MaxOff+1) + (1<<Litbits))*sizeof(U32)
  604. + (ZSTD_OPT_NUM+1)*(sizeof(ZSTD_match_t) + sizeof(ZSTD_optimal_t));
  605. size_t const optSpace = ((cParams.strategy == ZSTD_btopt) || (cParams.strategy == ZSTD_btultra)) ? optBudget : 0;
  606. size_t const ldmSpace = params->ldmParams.enableLdm ?
  607. ZSTD_ldm_getTableSize(params->ldmParams.hashLog,
  608. params->ldmParams.bucketSizeLog) : 0;
  609. size_t const neededSpace = entropySpace + tableSpace + tokenSpace +
  610. optSpace + ldmSpace;
  611. DEBUGLOG(5, "sizeof(ZSTD_CCtx) : %u", (U32)sizeof(ZSTD_CCtx));
  612. DEBUGLOG(5, "estimate workSpace : %u", (U32)neededSpace);
  613. return sizeof(ZSTD_CCtx) + neededSpace;
  614. }
  615. }
  616. size_t ZSTD_estimateCCtxSize_usingCParams(ZSTD_compressionParameters cParams)
  617. {
  618. ZSTD_CCtx_params const params = ZSTD_makeCCtxParamsFromCParams(cParams);
  619. return ZSTD_estimateCCtxSize_usingCCtxParams(&params);
  620. }
  621. size_t ZSTD_estimateCCtxSize(int compressionLevel)
  622. {
  623. ZSTD_compressionParameters const cParams = ZSTD_getCParams(compressionLevel, 0, 0);
  624. return ZSTD_estimateCCtxSize_usingCParams(cParams);
  625. }
  626. size_t ZSTD_estimateCStreamSize_usingCCtxParams(const ZSTD_CCtx_params* params)
  627. {
  628. if (params->nbThreads > 1) { return ERROR(GENERIC); }
  629. { size_t const CCtxSize = ZSTD_estimateCCtxSize_usingCCtxParams(params);
  630. size_t const blockSize = MIN(ZSTD_BLOCKSIZE_MAX, (size_t)1 << params->cParams.windowLog);
  631. size_t const inBuffSize = ((size_t)1 << params->cParams.windowLog) + blockSize;
  632. size_t const outBuffSize = ZSTD_compressBound(blockSize) + 1;
  633. size_t const streamingSize = inBuffSize + outBuffSize;
  634. return CCtxSize + streamingSize;
  635. }
  636. }
  637. size_t ZSTD_estimateCStreamSize_usingCParams(ZSTD_compressionParameters cParams)
  638. {
  639. ZSTD_CCtx_params const params = ZSTD_makeCCtxParamsFromCParams(cParams);
  640. return ZSTD_estimateCStreamSize_usingCCtxParams(&params);
  641. }
  642. size_t ZSTD_estimateCStreamSize(int compressionLevel) {
  643. ZSTD_compressionParameters const cParams = ZSTD_getCParams(compressionLevel, 0, 0);
  644. return ZSTD_estimateCStreamSize_usingCParams(cParams);
  645. }
  646. static U32 ZSTD_equivalentCParams(ZSTD_compressionParameters cParams1,
  647. ZSTD_compressionParameters cParams2)
  648. {
  649. U32 bslog1 = MIN(cParams1.windowLog, ZSTD_BLOCKSIZELOG_MAX);
  650. U32 bslog2 = MIN(cParams2.windowLog, ZSTD_BLOCKSIZELOG_MAX);
  651. return (bslog1 == bslog2) /* same block size */
  652. & (cParams1.hashLog == cParams2.hashLog)
  653. & (cParams1.chainLog == cParams2.chainLog)
  654. & (cParams1.strategy == cParams2.strategy) /* opt parser space */
  655. & ((cParams1.searchLength==3) == (cParams2.searchLength==3)); /* hashlog3 space */
  656. }
  657. /** The parameters are equivalent if ldm is not enabled in both sets or
  658. * all the parameters are equivalent. */
  659. static U32 ZSTD_equivalentLdmParams(ldmParams_t ldmParams1,
  660. ldmParams_t ldmParams2)
  661. {
  662. return (!ldmParams1.enableLdm && !ldmParams2.enableLdm) ||
  663. (ldmParams1.enableLdm == ldmParams2.enableLdm &&
  664. ldmParams1.hashLog == ldmParams2.hashLog &&
  665. ldmParams1.bucketSizeLog == ldmParams2.bucketSizeLog &&
  666. ldmParams1.minMatchLength == ldmParams2.minMatchLength &&
  667. ldmParams1.hashEveryLog == ldmParams2.hashEveryLog);
  668. }
  669. /** Equivalence for resetCCtx purposes */
  670. static U32 ZSTD_equivalentParams(ZSTD_CCtx_params params1,
  671. ZSTD_CCtx_params params2)
  672. {
  673. return ZSTD_equivalentCParams(params1.cParams, params2.cParams) &&
  674. ZSTD_equivalentLdmParams(params1.ldmParams, params2.ldmParams);
  675. }
  676. /*! ZSTD_continueCCtx() :
  677. * reuse CCtx without reset (note : requires no dictionary) */
  678. static size_t ZSTD_continueCCtx(ZSTD_CCtx* cctx, ZSTD_CCtx_params params, U64 pledgedSrcSize)
  679. {
  680. U32 const end = (U32)(cctx->nextSrc - cctx->base);
  681. DEBUGLOG(4, "continue mode");
  682. cctx->appliedParams = params;
  683. cctx->pledgedSrcSizePlusOne = pledgedSrcSize+1;
  684. cctx->consumedSrcSize = 0;
  685. if (pledgedSrcSize == ZSTD_CONTENTSIZE_UNKNOWN)
  686. cctx->appliedParams.fParams.contentSizeFlag = 0;
  687. DEBUGLOG(4, "pledged content size : %u ; flag : %u",
  688. (U32)pledgedSrcSize, cctx->appliedParams.fParams.contentSizeFlag);
  689. cctx->lowLimit = end;
  690. cctx->dictLimit = end;
  691. cctx->nextToUpdate = end+1;
  692. cctx->stage = ZSTDcs_init;
  693. cctx->dictID = 0;
  694. cctx->loadedDictEnd = 0;
  695. { int i; for (i=0; i<ZSTD_REP_NUM; i++) cctx->seqStore.rep[i] = repStartValue[i]; }
  696. cctx->optState.litLengthSum = 0; /* force reset of btopt stats */
  697. XXH64_reset(&cctx->xxhState, 0);
  698. return 0;
  699. }
  700. typedef enum { ZSTDcrp_continue, ZSTDcrp_noMemset } ZSTD_compResetPolicy_e;
  701. typedef enum { ZSTDb_not_buffered, ZSTDb_buffered } ZSTD_buffered_policy_e;
  702. /*! ZSTD_resetCCtx_internal() :
  703. note : `params` are assumed fully validated at this stage */
  704. static size_t ZSTD_resetCCtx_internal(ZSTD_CCtx* zc,
  705. ZSTD_CCtx_params params, U64 pledgedSrcSize,
  706. ZSTD_compResetPolicy_e const crp,
  707. ZSTD_buffered_policy_e const zbuff)
  708. {
  709. DEBUGLOG(4, "ZSTD_resetCCtx_internal");
  710. assert(!ZSTD_isError(ZSTD_checkCParams(params.cParams)));
  711. DEBUGLOG(4, "pledgedSrcSize: %u", (U32)pledgedSrcSize);
  712. if (crp == ZSTDcrp_continue) {
  713. if (ZSTD_equivalentParams(params, zc->appliedParams)) {
  714. DEBUGLOG(4, "ZSTD_equivalentParams()==1");
  715. assert(!(params.ldmParams.enableLdm &&
  716. params.ldmParams.hashEveryLog == ZSTD_LDM_HASHEVERYLOG_NOTSET));
  717. zc->entropy->hufCTable_repeatMode = HUF_repeat_none;
  718. zc->entropy->offcode_repeatMode = FSE_repeat_none;
  719. zc->entropy->matchlength_repeatMode = FSE_repeat_none;
  720. zc->entropy->litlength_repeatMode = FSE_repeat_none;
  721. return ZSTD_continueCCtx(zc, params, pledgedSrcSize);
  722. } }
  723. if (params.ldmParams.enableLdm) {
  724. /* Adjust long distance matching parameters */
  725. ZSTD_ldm_adjustParameters(&params.ldmParams, params.cParams.windowLog);
  726. assert(params.ldmParams.hashLog >= params.ldmParams.bucketSizeLog);
  727. assert(params.ldmParams.hashEveryLog < 32);
  728. zc->ldmState.hashPower =
  729. ZSTD_ldm_getHashPower(params.ldmParams.minMatchLength);
  730. }
  731. { size_t const blockSize = MIN(ZSTD_BLOCKSIZE_MAX, (size_t)1 << params.cParams.windowLog);
  732. U32 const divider = (params.cParams.searchLength==3) ? 3 : 4;
  733. size_t const maxNbSeq = blockSize / divider;
  734. size_t const tokenSpace = blockSize + 11*maxNbSeq;
  735. size_t const chainSize = (params.cParams.strategy == ZSTD_fast) ?
  736. 0 : ((size_t)1 << params.cParams.chainLog);
  737. size_t const hSize = ((size_t)1) << params.cParams.hashLog;
  738. U32 const hashLog3 = (params.cParams.searchLength>3) ?
  739. 0 : MIN(ZSTD_HASHLOG3_MAX, params.cParams.windowLog);
  740. size_t const h3Size = ((size_t)1) << hashLog3;
  741. size_t const tableSpace = (chainSize + hSize + h3Size) * sizeof(U32);
  742. size_t const buffOutSize = (zbuff==ZSTDb_buffered) ? ZSTD_compressBound(blockSize)+1 : 0;
  743. size_t const buffInSize = (zbuff==ZSTDb_buffered) ? ((size_t)1 << params.cParams.windowLog) + blockSize : 0;
  744. void* ptr;
  745. /* Check if workSpace is large enough, alloc a new one if needed */
  746. { size_t const entropySpace = sizeof(ZSTD_entropyCTables_t);
  747. size_t const optPotentialSpace = ((MaxML+1) + (MaxLL+1) + (MaxOff+1) + (1<<Litbits)) * sizeof(U32)
  748. + (ZSTD_OPT_NUM+1) * (sizeof(ZSTD_match_t)+sizeof(ZSTD_optimal_t));
  749. size_t const optSpace = ( (params.cParams.strategy == ZSTD_btopt)
  750. || (params.cParams.strategy == ZSTD_btultra)) ?
  751. optPotentialSpace : 0;
  752. size_t const bufferSpace = buffInSize + buffOutSize;
  753. size_t const ldmSpace = params.ldmParams.enableLdm
  754. ? ZSTD_ldm_getTableSize(params.ldmParams.hashLog, params.ldmParams.bucketSizeLog)
  755. : 0;
  756. size_t const neededSpace = entropySpace + optSpace + ldmSpace +
  757. tableSpace + tokenSpace + bufferSpace;
  758. if (zc->workSpaceSize < neededSpace) { /* too small : resize */
  759. DEBUGLOG(5, "Need to update workSpaceSize from %uK to %uK \n",
  760. (unsigned)zc->workSpaceSize>>10,
  761. (unsigned)neededSpace>>10);
  762. /* static cctx : no resize, error out */
  763. if (zc->staticSize) return ERROR(memory_allocation);
  764. zc->workSpaceSize = 0;
  765. ZSTD_free(zc->workSpace, zc->customMem);
  766. zc->workSpace = ZSTD_malloc(neededSpace, zc->customMem);
  767. if (zc->workSpace == NULL) return ERROR(memory_allocation);
  768. zc->workSpaceSize = neededSpace;
  769. ptr = zc->workSpace;
  770. /* entropy space */
  771. assert(((size_t)zc->workSpace & 3) == 0); /* ensure correct alignment */
  772. assert(zc->workSpaceSize >= sizeof(ZSTD_entropyCTables_t));
  773. zc->entropy = (ZSTD_entropyCTables_t*)zc->workSpace;
  774. } }
  775. /* init params */
  776. zc->appliedParams = params;
  777. zc->pledgedSrcSizePlusOne = pledgedSrcSize+1;
  778. zc->consumedSrcSize = 0;
  779. if (pledgedSrcSize == ZSTD_CONTENTSIZE_UNKNOWN)
  780. zc->appliedParams.fParams.contentSizeFlag = 0;
  781. DEBUGLOG(5, "pledged content size : %u ; flag : %u",
  782. (U32)pledgedSrcSize, zc->appliedParams.fParams.contentSizeFlag);
  783. zc->blockSize = blockSize;
  784. XXH64_reset(&zc->xxhState, 0);
  785. zc->stage = ZSTDcs_init;
  786. zc->dictID = 0;
  787. zc->loadedDictEnd = 0;
  788. zc->entropy->hufCTable_repeatMode = HUF_repeat_none;
  789. zc->entropy->offcode_repeatMode = FSE_repeat_none;
  790. zc->entropy->matchlength_repeatMode = FSE_repeat_none;
  791. zc->entropy->litlength_repeatMode = FSE_repeat_none;
  792. zc->nextToUpdate = 1;
  793. zc->nextSrc = NULL;
  794. zc->base = NULL;
  795. zc->dictBase = NULL;
  796. zc->dictLimit = 0;
  797. zc->lowLimit = 0;
  798. { int i; for (i=0; i<ZSTD_REP_NUM; i++) zc->seqStore.rep[i] = repStartValue[i]; }
  799. zc->hashLog3 = hashLog3;
  800. zc->optState.litLengthSum = 0;
  801. ptr = zc->entropy + 1;
  802. /* opt parser space */
  803. if ((params.cParams.strategy == ZSTD_btopt) || (params.cParams.strategy == ZSTD_btultra)) {
  804. DEBUGLOG(5, "reserving optimal parser space");
  805. assert(((size_t)ptr & 3) == 0); /* ensure ptr is properly aligned */
  806. zc->optState.litFreq = (U32*)ptr;
  807. zc->optState.litLengthFreq = zc->optState.litFreq + (1<<Litbits);
  808. zc->optState.matchLengthFreq = zc->optState.litLengthFreq + (MaxLL+1);
  809. zc->optState.offCodeFreq = zc->optState.matchLengthFreq + (MaxML+1);
  810. ptr = zc->optState.offCodeFreq + (MaxOff+1);
  811. zc->optState.matchTable = (ZSTD_match_t*)ptr;
  812. ptr = zc->optState.matchTable + ZSTD_OPT_NUM+1;
  813. zc->optState.priceTable = (ZSTD_optimal_t*)ptr;
  814. ptr = zc->optState.priceTable + ZSTD_OPT_NUM+1;
  815. }
  816. /* ldm hash table */
  817. /* initialize bucketOffsets table later for pointer alignment */
  818. if (params.ldmParams.enableLdm) {
  819. size_t const ldmHSize = ((size_t)1) << params.ldmParams.hashLog;
  820. memset(ptr, 0, ldmHSize * sizeof(ldmEntry_t));
  821. assert(((size_t)ptr & 3) == 0); /* ensure ptr is properly aligned */
  822. zc->ldmState.hashTable = (ldmEntry_t*)ptr;
  823. ptr = zc->ldmState.hashTable + ldmHSize;
  824. }
  825. /* table Space */
  826. if (crp!=ZSTDcrp_noMemset) memset(ptr, 0, tableSpace); /* reset tables only */
  827. assert(((size_t)ptr & 3) == 0); /* ensure ptr is properly aligned */
  828. zc->hashTable = (U32*)(ptr);
  829. zc->chainTable = zc->hashTable + hSize;
  830. zc->hashTable3 = zc->chainTable + chainSize;
  831. ptr = zc->hashTable3 + h3Size;
  832. /* sequences storage */
  833. zc->seqStore.sequencesStart = (seqDef*)ptr;
  834. ptr = zc->seqStore.sequencesStart + maxNbSeq;
  835. zc->seqStore.llCode = (BYTE*) ptr;
  836. zc->seqStore.mlCode = zc->seqStore.llCode + maxNbSeq;
  837. zc->seqStore.ofCode = zc->seqStore.mlCode + maxNbSeq;
  838. zc->seqStore.litStart = zc->seqStore.ofCode + maxNbSeq;
  839. ptr = zc->seqStore.litStart + blockSize;
  840. /* ldm bucketOffsets table */
  841. if (params.ldmParams.enableLdm) {
  842. size_t const ldmBucketSize =
  843. ((size_t)1) << (params.ldmParams.hashLog -
  844. params.ldmParams.bucketSizeLog);
  845. memset(ptr, 0, ldmBucketSize);
  846. zc->ldmState.bucketOffsets = (BYTE*)ptr;
  847. ptr = zc->ldmState.bucketOffsets + ldmBucketSize;
  848. }
  849. /* buffers */
  850. zc->inBuffSize = buffInSize;
  851. zc->inBuff = (char*)ptr;
  852. zc->outBuffSize = buffOutSize;
  853. zc->outBuff = zc->inBuff + buffInSize;
  854. return 0;
  855. }
  856. }
  857. /* ZSTD_invalidateRepCodes() :
  858. * ensures next compression will not use repcodes from previous block.
  859. * Note : only works with regular variant;
  860. * do not use with extDict variant ! */
  861. void ZSTD_invalidateRepCodes(ZSTD_CCtx* cctx) {
  862. int i;
  863. for (i=0; i<ZSTD_REP_NUM; i++) cctx->seqStore.rep[i] = 0;
  864. }
  865. /*! ZSTD_copyCCtx_internal() :
  866. * Duplicate an existing context `srcCCtx` into another one `dstCCtx`.
  867. * The "context", in this case, refers to the hash and chain tables, entropy
  868. * tables, and dictionary offsets.
  869. * Only works during stage ZSTDcs_init (i.e. after creation, but before first call to ZSTD_compressContinue()).
  870. * pledgedSrcSize=0 means "empty" if fParams.contentSizeFlag=1
  871. * @return : 0, or an error code */
  872. static size_t ZSTD_copyCCtx_internal(ZSTD_CCtx* dstCCtx,
  873. const ZSTD_CCtx* srcCCtx,
  874. ZSTD_frameParameters fParams,
  875. unsigned long long pledgedSrcSize,
  876. ZSTD_buffered_policy_e zbuff)
  877. {
  878. DEBUGLOG(5, "ZSTD_copyCCtx_internal");
  879. if (srcCCtx->stage!=ZSTDcs_init) return ERROR(stage_wrong);
  880. memcpy(&dstCCtx->customMem, &srcCCtx->customMem, sizeof(ZSTD_customMem));
  881. { ZSTD_CCtx_params params = dstCCtx->requestedParams;
  882. /* Copy only compression parameters related to tables. */
  883. params.cParams = srcCCtx->appliedParams.cParams;
  884. params.fParams = fParams;
  885. ZSTD_resetCCtx_internal(dstCCtx, params, pledgedSrcSize,
  886. ZSTDcrp_noMemset, zbuff);
  887. }
  888. /* copy tables */
  889. { size_t const chainSize = (srcCCtx->appliedParams.cParams.strategy == ZSTD_fast) ? 0 : ((size_t)1 << srcCCtx->appliedParams.cParams.chainLog);
  890. size_t const hSize = (size_t)1 << srcCCtx->appliedParams.cParams.hashLog;
  891. size_t const h3Size = (size_t)1 << srcCCtx->hashLog3;
  892. size_t const tableSpace = (chainSize + hSize + h3Size) * sizeof(U32);
  893. assert((U32*)dstCCtx->chainTable == (U32*)dstCCtx->hashTable + hSize); /* chainTable must follow hashTable */
  894. assert((U32*)dstCCtx->hashTable3 == (U32*)dstCCtx->chainTable + chainSize);
  895. memcpy(dstCCtx->hashTable, srcCCtx->hashTable, tableSpace); /* presumes all tables follow each other */
  896. }
  897. /* copy dictionary offsets */
  898. dstCCtx->nextToUpdate = srcCCtx->nextToUpdate;
  899. dstCCtx->nextToUpdate3= srcCCtx->nextToUpdate3;
  900. dstCCtx->nextSrc = srcCCtx->nextSrc;
  901. dstCCtx->base = srcCCtx->base;
  902. dstCCtx->dictBase = srcCCtx->dictBase;
  903. dstCCtx->dictLimit = srcCCtx->dictLimit;
  904. dstCCtx->lowLimit = srcCCtx->lowLimit;
  905. dstCCtx->loadedDictEnd= srcCCtx->loadedDictEnd;
  906. dstCCtx->dictID = srcCCtx->dictID;
  907. /* copy entropy tables */
  908. memcpy(dstCCtx->entropy, srcCCtx->entropy, sizeof(ZSTD_entropyCTables_t));
  909. return 0;
  910. }
  911. /*! ZSTD_copyCCtx() :
  912. * Duplicate an existing context `srcCCtx` into another one `dstCCtx`.
  913. * Only works during stage ZSTDcs_init (i.e. after creation, but before first call to ZSTD_compressContinue()).
  914. * pledgedSrcSize==0 means "unknown".
  915. * @return : 0, or an error code */
  916. size_t ZSTD_copyCCtx(ZSTD_CCtx* dstCCtx, const ZSTD_CCtx* srcCCtx, unsigned long long pledgedSrcSize)
  917. {
  918. ZSTD_frameParameters fParams = { 1 /*content*/, 0 /*checksum*/, 0 /*noDictID*/ };
  919. ZSTD_buffered_policy_e const zbuff = (ZSTD_buffered_policy_e)(srcCCtx->inBuffSize>0);
  920. ZSTD_STATIC_ASSERT((U32)ZSTDb_buffered==1);
  921. fParams.contentSizeFlag = pledgedSrcSize>0;
  922. return ZSTD_copyCCtx_internal(dstCCtx, srcCCtx, fParams, pledgedSrcSize, zbuff);
  923. }
  924. /*! ZSTD_reduceTable() :
  925. * reduce table indexes by `reducerValue` */
  926. static void ZSTD_reduceTable (U32* const table, U32 const size, U32 const reducerValue)
  927. {
  928. U32 u;
  929. for (u=0 ; u < size ; u++) {
  930. if (table[u] < reducerValue) table[u] = 0;
  931. else table[u] -= reducerValue;
  932. }
  933. }
  934. /*! ZSTD_ldm_reduceTable() :
  935. * reduce table indexes by `reducerValue` */
  936. static void ZSTD_ldm_reduceTable(ldmEntry_t* const table, U32 const size,
  937. U32 const reducerValue)
  938. {
  939. U32 u;
  940. for (u = 0; u < size; u++) {
  941. if (table[u].offset < reducerValue) table[u].offset = 0;
  942. else table[u].offset -= reducerValue;
  943. }
  944. }
  945. /*! ZSTD_reduceIndex() :
  946. * rescale all indexes to avoid future overflow (indexes are U32) */
  947. static void ZSTD_reduceIndex (ZSTD_CCtx* zc, const U32 reducerValue)
  948. {
  949. { U32 const hSize = (U32)1 << zc->appliedParams.cParams.hashLog;
  950. ZSTD_reduceTable(zc->hashTable, hSize, reducerValue); }
  951. { U32 const chainSize = (zc->appliedParams.cParams.strategy == ZSTD_fast) ? 0 : ((U32)1 << zc->appliedParams.cParams.chainLog);
  952. ZSTD_reduceTable(zc->chainTable, chainSize, reducerValue); }
  953. { U32 const h3Size = (zc->hashLog3) ? (U32)1 << zc->hashLog3 : 0;
  954. ZSTD_reduceTable(zc->hashTable3, h3Size, reducerValue); }
  955. { if (zc->appliedParams.ldmParams.enableLdm) {
  956. U32 const ldmHSize = (U32)1 << zc->appliedParams.ldmParams.hashLog;
  957. ZSTD_ldm_reduceTable(zc->ldmState.hashTable, ldmHSize, reducerValue);
  958. }
  959. }
  960. }
  961. /*-*******************************************************
  962. * Block entropic compression
  963. *********************************************************/
  964. /* See doc/zstd_compression_format.md for detailed format description */
  965. size_t ZSTD_noCompressBlock (void* dst, size_t dstCapacity, const void* src, size_t srcSize)
  966. {
  967. if (srcSize + ZSTD_blockHeaderSize > dstCapacity) return ERROR(dstSize_tooSmall);
  968. memcpy((BYTE*)dst + ZSTD_blockHeaderSize, src, srcSize);
  969. MEM_writeLE24(dst, (U32)(srcSize << 2) + (U32)bt_raw);
  970. return ZSTD_blockHeaderSize+srcSize;
  971. }
  972. static size_t ZSTD_noCompressLiterals (void* dst, size_t dstCapacity, const void* src, size_t srcSize)
  973. {
  974. BYTE* const ostart = (BYTE* const)dst;
  975. U32 const flSize = 1 + (srcSize>31) + (srcSize>4095);
  976. if (srcSize + flSize > dstCapacity) return ERROR(dstSize_tooSmall);
  977. switch(flSize)
  978. {
  979. case 1: /* 2 - 1 - 5 */
  980. ostart[0] = (BYTE)((U32)set_basic + (srcSize<<3));
  981. break;
  982. case 2: /* 2 - 2 - 12 */
  983. MEM_writeLE16(ostart, (U16)((U32)set_basic + (1<<2) + (srcSize<<4)));
  984. break;
  985. case 3: /* 2 - 2 - 20 */
  986. MEM_writeLE32(ostart, (U32)((U32)set_basic + (3<<2) + (srcSize<<4)));
  987. break;
  988. default: /* not necessary : flSize is {1,2,3} */
  989. assert(0);
  990. }
  991. memcpy(ostart + flSize, src, srcSize);
  992. return srcSize + flSize;
  993. }
  994. static size_t ZSTD_compressRleLiteralsBlock (void* dst, size_t dstCapacity, const void* src, size_t srcSize)
  995. {
  996. BYTE* const ostart = (BYTE* const)dst;
  997. U32 const flSize = 1 + (srcSize>31) + (srcSize>4095);
  998. (void)dstCapacity; /* dstCapacity already guaranteed to be >=4, hence large enough */
  999. switch(flSize)
  1000. {
  1001. case 1: /* 2 - 1 - 5 */
  1002. ostart[0] = (BYTE)((U32)set_rle + (srcSize<<3));
  1003. break;
  1004. case 2: /* 2 - 2 - 12 */
  1005. MEM_writeLE16(ostart, (U16)((U32)set_rle + (1<<2) + (srcSize<<4)));
  1006. break;
  1007. case 3: /* 2 - 2 - 20 */
  1008. MEM_writeLE32(ostart, (U32)((U32)set_rle + (3<<2) + (srcSize<<4)));
  1009. break;
  1010. default: /* not necessary : flSize is {1,2,3} */
  1011. assert(0);
  1012. }
  1013. ostart[flSize] = *(const BYTE*)src;
  1014. return flSize+1;
  1015. }
  1016. static size_t ZSTD_minGain(size_t srcSize) { return (srcSize >> 6) + 2; }
  1017. static size_t ZSTD_compressLiterals (ZSTD_entropyCTables_t * entropy,
  1018. ZSTD_strategy strategy,
  1019. void* dst, size_t dstCapacity,
  1020. const void* src, size_t srcSize)
  1021. {
  1022. size_t const minGain = ZSTD_minGain(srcSize);
  1023. size_t const lhSize = 3 + (srcSize >= 1 KB) + (srcSize >= 16 KB);
  1024. BYTE* const ostart = (BYTE*)dst;
  1025. U32 singleStream = srcSize < 256;
  1026. symbolEncodingType_e hType = set_compressed;
  1027. size_t cLitSize;
  1028. /* small ? don't even attempt compression (speed opt) */
  1029. # define LITERAL_NOENTROPY 63
  1030. { size_t const minLitSize = entropy->hufCTable_repeatMode == HUF_repeat_valid ? 6 : LITERAL_NOENTROPY;
  1031. if (srcSize <= minLitSize) return ZSTD_noCompressLiterals(dst, dstCapacity, src, srcSize);
  1032. }
  1033. if (dstCapacity < lhSize+1) return ERROR(dstSize_tooSmall); /* not enough space for compression */
  1034. { HUF_repeat repeat = entropy->hufCTable_repeatMode;
  1035. int const preferRepeat = strategy < ZSTD_lazy ? srcSize <= 1024 : 0;
  1036. if (repeat == HUF_repeat_valid && lhSize == 3) singleStream = 1;
  1037. cLitSize = singleStream ? HUF_compress1X_repeat(ostart+lhSize, dstCapacity-lhSize, src, srcSize, 255, 11,
  1038. entropy->workspace, sizeof(entropy->workspace), (HUF_CElt*)entropy->hufCTable, &repeat, preferRepeat)
  1039. : HUF_compress4X_repeat(ostart+lhSize, dstCapacity-lhSize, src, srcSize, 255, 11,
  1040. entropy->workspace, sizeof(entropy->workspace), (HUF_CElt*)entropy->hufCTable, &repeat, preferRepeat);
  1041. if (repeat != HUF_repeat_none) { hType = set_repeat; } /* reused the existing table */
  1042. else { entropy->hufCTable_repeatMode = HUF_repeat_check; } /* now have a table to reuse */
  1043. }
  1044. if ((cLitSize==0) | (cLitSize >= srcSize - minGain) | ERR_isError(cLitSize)) {
  1045. entropy->hufCTable_repeatMode = HUF_repeat_none;
  1046. return ZSTD_noCompressLiterals(dst, dstCapacity, src, srcSize);
  1047. }
  1048. if (cLitSize==1) {
  1049. entropy->hufCTable_repeatMode = HUF_repeat_none;
  1050. return ZSTD_compressRleLiteralsBlock(dst, dstCapacity, src, srcSize);
  1051. }
  1052. /* Build header */
  1053. switch(lhSize)
  1054. {
  1055. case 3: /* 2 - 2 - 10 - 10 */
  1056. { U32 const lhc = hType + ((!singleStream) << 2) + ((U32)srcSize<<4) + ((U32)cLitSize<<14);
  1057. MEM_writeLE24(ostart, lhc);
  1058. break;
  1059. }
  1060. case 4: /* 2 - 2 - 14 - 14 */
  1061. { U32 const lhc = hType + (2 << 2) + ((U32)srcSize<<4) + ((U32)cLitSize<<18);
  1062. MEM_writeLE32(ostart, lhc);
  1063. break;
  1064. }
  1065. case 5: /* 2 - 2 - 18 - 18 */
  1066. { U32 const lhc = hType + (3 << 2) + ((U32)srcSize<<4) + ((U32)cLitSize<<22);
  1067. MEM_writeLE32(ostart, lhc);
  1068. ostart[4] = (BYTE)(cLitSize >> 10);
  1069. break;
  1070. }
  1071. default: /* not possible : lhSize is {3,4,5} */
  1072. assert(0);
  1073. }
  1074. return lhSize+cLitSize;
  1075. }
  1076. void ZSTD_seqToCodes(const seqStore_t* seqStorePtr)
  1077. {
  1078. BYTE const LL_deltaCode = 19;
  1079. BYTE const ML_deltaCode = 36;
  1080. const seqDef* const sequences = seqStorePtr->sequencesStart;
  1081. BYTE* const llCodeTable = seqStorePtr->llCode;
  1082. BYTE* const ofCodeTable = seqStorePtr->ofCode;
  1083. BYTE* const mlCodeTable = seqStorePtr->mlCode;
  1084. U32 const nbSeq = (U32)(seqStorePtr->sequences - seqStorePtr->sequencesStart);
  1085. U32 u;
  1086. for (u=0; u<nbSeq; u++) {
  1087. U32 const llv = sequences[u].litLength;
  1088. U32 const mlv = sequences[u].matchLength;
  1089. llCodeTable[u] = (llv> 63) ? (BYTE)ZSTD_highbit32(llv) + LL_deltaCode : LL_Code[llv];
  1090. ofCodeTable[u] = (BYTE)ZSTD_highbit32(sequences[u].offset);
  1091. mlCodeTable[u] = (mlv>127) ? (BYTE)ZSTD_highbit32(mlv) + ML_deltaCode : ML_Code[mlv];
  1092. }
  1093. if (seqStorePtr->longLengthID==1)
  1094. llCodeTable[seqStorePtr->longLengthPos] = MaxLL;
  1095. if (seqStorePtr->longLengthID==2)
  1096. mlCodeTable[seqStorePtr->longLengthPos] = MaxML;
  1097. }
  1098. typedef enum {
  1099. ZSTD_defaultDisallowed = 0,
  1100. ZSTD_defaultAllowed = 1
  1101. } ZSTD_defaultPolicy_e;
  1102. MEM_STATIC symbolEncodingType_e ZSTD_selectEncodingType(
  1103. FSE_repeat* repeatMode, size_t const mostFrequent, size_t nbSeq,
  1104. U32 defaultNormLog, ZSTD_defaultPolicy_e const isDefaultAllowed)
  1105. {
  1106. #define MIN_SEQ_FOR_DYNAMIC_FSE 64
  1107. #define MAX_SEQ_FOR_STATIC_FSE 1000
  1108. ZSTD_STATIC_ASSERT(ZSTD_defaultDisallowed == 0 && ZSTD_defaultAllowed != 0);
  1109. if ((mostFrequent == nbSeq) && (!isDefaultAllowed || nbSeq > 2)) {
  1110. /* Prefer set_basic over set_rle when there are 2 or less symbols,
  1111. * since RLE uses 1 byte, but set_basic uses 5-6 bits per symbol.
  1112. * If basic encoding isn't possible, always choose RLE.
  1113. */
  1114. *repeatMode = FSE_repeat_check;
  1115. return set_rle;
  1116. }
  1117. if (isDefaultAllowed && (*repeatMode == FSE_repeat_valid) && (nbSeq < MAX_SEQ_FOR_STATIC_FSE)) {
  1118. return set_repeat;
  1119. }
  1120. if (isDefaultAllowed && ((nbSeq < MIN_SEQ_FOR_DYNAMIC_FSE) || (mostFrequent < (nbSeq >> (defaultNormLog-1))))) {
  1121. *repeatMode = FSE_repeat_valid;
  1122. return set_basic;
  1123. }
  1124. *repeatMode = FSE_repeat_check;
  1125. return set_compressed;
  1126. }
  1127. MEM_STATIC size_t ZSTD_buildCTable(void* dst, size_t dstCapacity,
  1128. FSE_CTable* CTable, U32 FSELog, symbolEncodingType_e type,
  1129. U32* count, U32 max,
  1130. BYTE const* codeTable, size_t nbSeq,
  1131. S16 const* defaultNorm, U32 defaultNormLog, U32 defaultMax,
  1132. void* workspace, size_t workspaceSize)
  1133. {
  1134. BYTE* op = (BYTE*)dst;
  1135. BYTE const* const oend = op + dstCapacity;
  1136. switch (type) {
  1137. case set_rle:
  1138. *op = codeTable[0];
  1139. CHECK_F(FSE_buildCTable_rle(CTable, (BYTE)max));
  1140. return 1;
  1141. case set_repeat:
  1142. return 0;
  1143. case set_basic:
  1144. CHECK_F(FSE_buildCTable_wksp(CTable, defaultNorm, defaultMax, defaultNormLog, workspace, workspaceSize));
  1145. return 0;
  1146. case set_compressed: {
  1147. S16 norm[MaxSeq + 1];
  1148. size_t nbSeq_1 = nbSeq;
  1149. const U32 tableLog = FSE_optimalTableLog(FSELog, nbSeq, max);
  1150. if (count[codeTable[nbSeq-1]] > 1) {
  1151. count[codeTable[nbSeq-1]]--;
  1152. nbSeq_1--;
  1153. }
  1154. assert(nbSeq_1 > 1);
  1155. CHECK_F(FSE_normalizeCount(norm, tableLog, count, nbSeq_1, max));
  1156. { size_t const NCountSize = FSE_writeNCount(op, oend - op, norm, max, tableLog); /* overflow protected */
  1157. if (FSE_isError(NCountSize)) return NCountSize;
  1158. CHECK_F(FSE_buildCTable_wksp(CTable, norm, max, tableLog, workspace, workspaceSize));
  1159. return NCountSize;
  1160. }
  1161. }
  1162. default: return assert(0), ERROR(GENERIC);
  1163. }
  1164. }
  1165. MEM_STATIC size_t ZSTD_encodeSequences(void* dst, size_t dstCapacity,
  1166. FSE_CTable const* CTable_MatchLength, BYTE const* mlCodeTable,
  1167. FSE_CTable const* CTable_OffsetBits, BYTE const* ofCodeTable,
  1168. FSE_CTable const* CTable_LitLength, BYTE const* llCodeTable,
  1169. seqDef const* sequences, size_t nbSeq, int longOffsets)
  1170. {
  1171. BIT_CStream_t blockStream;
  1172. FSE_CState_t stateMatchLength;
  1173. FSE_CState_t stateOffsetBits;
  1174. FSE_CState_t stateLitLength;
  1175. CHECK_E(BIT_initCStream(&blockStream, dst, dstCapacity), dstSize_tooSmall); /* not enough space remaining */
  1176. /* first symbols */
  1177. FSE_initCState2(&stateMatchLength, CTable_MatchLength, mlCodeTable[nbSeq-1]);
  1178. FSE_initCState2(&stateOffsetBits, CTable_OffsetBits, ofCodeTable[nbSeq-1]);
  1179. FSE_initCState2(&stateLitLength, CTable_LitLength, llCodeTable[nbSeq-1]);
  1180. BIT_addBits(&blockStream, sequences[nbSeq-1].litLength, LL_bits[llCodeTable[nbSeq-1]]);
  1181. if (MEM_32bits()) BIT_flushBits(&blockStream);
  1182. BIT_addBits(&blockStream, sequences[nbSeq-1].matchLength, ML_bits[mlCodeTable[nbSeq-1]]);
  1183. if (MEM_32bits()) BIT_flushBits(&blockStream);
  1184. if (longOffsets) {
  1185. U32 const ofBits = ofCodeTable[nbSeq-1];
  1186. int const extraBits = ofBits - MIN(ofBits, STREAM_ACCUMULATOR_MIN-1);
  1187. if (extraBits) {
  1188. BIT_addBits(&blockStream, sequences[nbSeq-1].offset, extraBits);
  1189. BIT_flushBits(&blockStream);
  1190. }
  1191. BIT_addBits(&blockStream, sequences[nbSeq-1].offset >> extraBits,
  1192. ofBits - extraBits);
  1193. } else {
  1194. BIT_addBits(&blockStream, sequences[nbSeq-1].offset, ofCodeTable[nbSeq-1]);
  1195. }
  1196. BIT_flushBits(&blockStream);
  1197. { size_t n;
  1198. for (n=nbSeq-2 ; n<nbSeq ; n--) { /* intentional underflow */
  1199. BYTE const llCode = llCodeTable[n];
  1200. BYTE const ofCode = ofCodeTable[n];
  1201. BYTE const mlCode = mlCodeTable[n];
  1202. U32 const llBits = LL_bits[llCode];
  1203. U32 const ofBits = ofCode; /* 32b*/ /* 64b*/
  1204. U32 const mlBits = ML_bits[mlCode];
  1205. /* (7)*/ /* (7)*/
  1206. FSE_encodeSymbol(&blockStream, &stateOffsetBits, ofCode); /* 15 */ /* 15 */
  1207. FSE_encodeSymbol(&blockStream, &stateMatchLength, mlCode); /* 24 */ /* 24 */
  1208. if (MEM_32bits()) BIT_flushBits(&blockStream); /* (7)*/
  1209. FSE_encodeSymbol(&blockStream, &stateLitLength, llCode); /* 16 */ /* 33 */
  1210. if (MEM_32bits() || (ofBits+mlBits+llBits >= 64-7-(LLFSELog+MLFSELog+OffFSELog)))
  1211. BIT_flushBits(&blockStream); /* (7)*/
  1212. BIT_addBits(&blockStream, sequences[n].litLength, llBits);
  1213. if (MEM_32bits() && ((llBits+mlBits)>24)) BIT_flushBits(&blockStream);
  1214. BIT_addBits(&blockStream, sequences[n].matchLength, mlBits);
  1215. if (MEM_32bits() || (ofBits+mlBits+llBits > 56)) BIT_flushBits(&blockStream);
  1216. if (longOffsets) {
  1217. int const extraBits = ofBits - MIN(ofBits, STREAM_ACCUMULATOR_MIN-1);
  1218. if (extraBits) {
  1219. BIT_addBits(&blockStream, sequences[n].offset, extraBits);
  1220. BIT_flushBits(&blockStream); /* (7)*/
  1221. }
  1222. BIT_addBits(&blockStream, sequences[n].offset >> extraBits,
  1223. ofBits - extraBits); /* 31 */
  1224. } else {
  1225. BIT_addBits(&blockStream, sequences[n].offset, ofBits); /* 31 */
  1226. }
  1227. BIT_flushBits(&blockStream); /* (7)*/
  1228. } }
  1229. FSE_flushCState(&blockStream, &stateMatchLength);
  1230. FSE_flushCState(&blockStream, &stateOffsetBits);
  1231. FSE_flushCState(&blockStream, &stateLitLength);
  1232. { size_t const streamSize = BIT_closeCStream(&blockStream);
  1233. if (streamSize==0) return ERROR(dstSize_tooSmall); /* not enough space */
  1234. return streamSize;
  1235. }
  1236. }
  1237. MEM_STATIC size_t ZSTD_compressSequences_internal(seqStore_t* seqStorePtr,
  1238. ZSTD_entropyCTables_t* entropy,
  1239. ZSTD_compressionParameters const* cParams,
  1240. void* dst, size_t dstCapacity)
  1241. {
  1242. const int longOffsets = cParams->windowLog > STREAM_ACCUMULATOR_MIN;
  1243. U32 count[MaxSeq+1];
  1244. FSE_CTable* CTable_LitLength = entropy->litlengthCTable;
  1245. FSE_CTable* CTable_OffsetBits = entropy->offcodeCTable;
  1246. FSE_CTable* CTable_MatchLength = entropy->matchlengthCTable;
  1247. U32 LLtype, Offtype, MLtype; /* compressed, raw or rle */
  1248. const seqDef* const sequences = seqStorePtr->sequencesStart;
  1249. const BYTE* const ofCodeTable = seqStorePtr->ofCode;
  1250. const BYTE* const llCodeTable = seqStorePtr->llCode;
  1251. const BYTE* const mlCodeTable = seqStorePtr->mlCode;
  1252. BYTE* const ostart = (BYTE*)dst;
  1253. BYTE* const oend = ostart + dstCapacity;
  1254. BYTE* op = ostart;
  1255. size_t const nbSeq = seqStorePtr->sequences - seqStorePtr->sequencesStart;
  1256. BYTE* seqHead;
  1257. ZSTD_STATIC_ASSERT(sizeof(entropy->workspace) >= (1<<MAX(MLFSELog,LLFSELog)));
  1258. /* Compress literals */
  1259. { const BYTE* const literals = seqStorePtr->litStart;
  1260. size_t const litSize = seqStorePtr->lit - literals;
  1261. size_t const cSize = ZSTD_compressLiterals(
  1262. entropy, cParams->strategy, op, dstCapacity, literals, litSize);
  1263. if (ZSTD_isError(cSize))
  1264. return cSize;
  1265. op += cSize;
  1266. }
  1267. /* Sequences Header */
  1268. if ((oend-op) < 3 /*max nbSeq Size*/ + 1 /*seqHead */) return ERROR(dstSize_tooSmall);
  1269. if (nbSeq < 0x7F) *op++ = (BYTE)nbSeq;
  1270. else if (nbSeq < LONGNBSEQ) op[0] = (BYTE)((nbSeq>>8) + 0x80), op[1] = (BYTE)nbSeq, op+=2;
  1271. else op[0]=0xFF, MEM_writeLE16(op+1, (U16)(nbSeq - LONGNBSEQ)), op+=3;
  1272. if (nbSeq==0) return op - ostart;
  1273. /* seqHead : flags for FSE encoding type */
  1274. seqHead = op++;
  1275. /* convert length/distances into codes */
  1276. ZSTD_seqToCodes(seqStorePtr);
  1277. /* CTable for Literal Lengths */
  1278. { U32 max = MaxLL;
  1279. size_t const mostFrequent = FSE_countFast_wksp(count, &max, llCodeTable, nbSeq, entropy->workspace);
  1280. LLtype = ZSTD_selectEncodingType(&entropy->litlength_repeatMode, mostFrequent, nbSeq, LL_defaultNormLog, ZSTD_defaultAllowed);
  1281. { size_t const countSize = ZSTD_buildCTable(op, oend - op, CTable_LitLength, LLFSELog, (symbolEncodingType_e)LLtype,
  1282. count, max, llCodeTable, nbSeq, LL_defaultNorm, LL_defaultNormLog, MaxLL,
  1283. entropy->workspace, sizeof(entropy->workspace));
  1284. if (ZSTD_isError(countSize)) return countSize;
  1285. op += countSize;
  1286. } }
  1287. /* CTable for Offsets */
  1288. { U32 max = MaxOff;
  1289. size_t const mostFrequent = FSE_countFast_wksp(count, &max, ofCodeTable, nbSeq, entropy->workspace);
  1290. /* We can only use the basic table if max <= DefaultMaxOff, otherwise the offsets are too large */
  1291. ZSTD_defaultPolicy_e const defaultPolicy = max <= DefaultMaxOff ? ZSTD_defaultAllowed : ZSTD_defaultDisallowed;
  1292. Offtype = ZSTD_selectEncodingType(&entropy->offcode_repeatMode, mostFrequent, nbSeq, OF_defaultNormLog, defaultPolicy);
  1293. { size_t const countSize = ZSTD_buildCTable(op, oend - op, CTable_OffsetBits, OffFSELog, (symbolEncodingType_e)Offtype,
  1294. count, max, ofCodeTable, nbSeq, OF_defaultNorm, OF_defaultNormLog, DefaultMaxOff,
  1295. entropy->workspace, sizeof(entropy->workspace));
  1296. if (ZSTD_isError(countSize)) return countSize;
  1297. op += countSize;
  1298. } }
  1299. /* CTable for MatchLengths */
  1300. { U32 max = MaxML;
  1301. size_t const mostFrequent = FSE_countFast_wksp(count, &max, mlCodeTable, nbSeq, entropy->workspace);
  1302. MLtype = ZSTD_selectEncodingType(&entropy->matchlength_repeatMode, mostFrequent, nbSeq, ML_defaultNormLog, ZSTD_defaultAllowed);
  1303. { size_t const countSize = ZSTD_buildCTable(op, oend - op, CTable_MatchLength, MLFSELog, (symbolEncodingType_e)MLtype,
  1304. count, max, mlCodeTable, nbSeq, ML_defaultNorm, ML_defaultNormLog, MaxML,
  1305. entropy->workspace, sizeof(entropy->workspace));
  1306. if (ZSTD_isError(countSize)) return countSize;
  1307. op += countSize;
  1308. } }
  1309. *seqHead = (BYTE)((LLtype<<6) + (Offtype<<4) + (MLtype<<2));
  1310. { size_t const streamSize = ZSTD_encodeSequences(op, oend - op,
  1311. CTable_MatchLength, mlCodeTable,
  1312. CTable_OffsetBits, ofCodeTable,
  1313. CTable_LitLength, llCodeTable,
  1314. sequences, nbSeq, longOffsets);
  1315. if (ZSTD_isError(streamSize)) return streamSize;
  1316. op += streamSize;
  1317. }
  1318. return op - ostart;
  1319. }
  1320. MEM_STATIC size_t ZSTD_compressSequences(seqStore_t* seqStorePtr,
  1321. ZSTD_entropyCTables_t* entropy,
  1322. ZSTD_compressionParameters const* cParams,
  1323. void* dst, size_t dstCapacity,
  1324. size_t srcSize)
  1325. {
  1326. size_t const cSize = ZSTD_compressSequences_internal(seqStorePtr, entropy, cParams,
  1327. dst, dstCapacity);
  1328. size_t const minGain = ZSTD_minGain(srcSize);
  1329. size_t const maxCSize = srcSize - minGain;
  1330. /* If the srcSize <= dstCapacity, then there is enough space to write a
  1331. * raw uncompressed block. Since we ran out of space, the block must not
  1332. * be compressible, so fall back to a raw uncompressed block.
  1333. */
  1334. int const uncompressibleError = cSize == ERROR(dstSize_tooSmall) && srcSize <= dstCapacity;
  1335. if (ZSTD_isError(cSize) && !uncompressibleError)
  1336. return cSize;
  1337. /* Check compressibility */
  1338. if (cSize >= maxCSize || uncompressibleError) {
  1339. entropy->hufCTable_repeatMode = HUF_repeat_none;
  1340. entropy->offcode_repeatMode = FSE_repeat_none;
  1341. entropy->matchlength_repeatMode = FSE_repeat_none;
  1342. entropy->litlength_repeatMode = FSE_repeat_none;
  1343. return 0;
  1344. }
  1345. assert(!ZSTD_isError(cSize));
  1346. /* confirm repcodes */
  1347. { int i; for (i=0; i<ZSTD_REP_NUM; i++) seqStorePtr->rep[i] = seqStorePtr->repToConfirm[i]; }
  1348. return cSize;
  1349. }
  1350. /* ZSTD_selectBlockCompressor() :
  1351. * Not static, but internal use only (used by long distance matcher)
  1352. * assumption : strat is a valid strategy */
  1353. typedef size_t (*ZSTD_blockCompressor) (ZSTD_CCtx* ctx, const void* src, size_t srcSize);
  1354. ZSTD_blockCompressor ZSTD_selectBlockCompressor(ZSTD_strategy strat, int extDict)
  1355. {
  1356. static const ZSTD_blockCompressor blockCompressor[2][(unsigned)ZSTD_btultra+1] = {
  1357. { ZSTD_compressBlock_fast /* default for 0 */,
  1358. ZSTD_compressBlock_fast, ZSTD_compressBlock_doubleFast, ZSTD_compressBlock_greedy,
  1359. ZSTD_compressBlock_lazy, ZSTD_compressBlock_lazy2, ZSTD_compressBlock_btlazy2,
  1360. ZSTD_compressBlock_btopt, ZSTD_compressBlock_btultra },
  1361. { ZSTD_compressBlock_fast_extDict /* default for 0 */,
  1362. ZSTD_compressBlock_fast_extDict, ZSTD_compressBlock_doubleFast_extDict, ZSTD_compressBlock_greedy_extDict,
  1363. ZSTD_compressBlock_lazy_extDict,ZSTD_compressBlock_lazy2_extDict, ZSTD_compressBlock_btlazy2_extDict,
  1364. ZSTD_compressBlock_btopt_extDict, ZSTD_compressBlock_btultra_extDict }
  1365. };
  1366. ZSTD_STATIC_ASSERT((unsigned)ZSTD_fast == 1);
  1367. assert((U32)strat >= (U32)ZSTD_fast);
  1368. assert((U32)strat <= (U32)ZSTD_btultra);
  1369. return blockCompressor[extDict!=0][(U32)strat];
  1370. }
  1371. static void ZSTD_storeLastLiterals(seqStore_t* seqStorePtr,
  1372. const BYTE* anchor, size_t lastLLSize)
  1373. {
  1374. memcpy(seqStorePtr->lit, anchor, lastLLSize);
  1375. seqStorePtr->lit += lastLLSize;
  1376. }
  1377. static size_t ZSTD_compressBlock_internal(ZSTD_CCtx* zc, void* dst, size_t dstCapacity, const void* src, size_t srcSize)
  1378. {
  1379. const BYTE* const base = zc->base;
  1380. const BYTE* const istart = (const BYTE*)src;
  1381. const U32 current = (U32)(istart-base);
  1382. size_t lastLLSize;
  1383. const BYTE* anchor;
  1384. U32 const extDict = zc->lowLimit < zc->dictLimit;
  1385. const ZSTD_blockCompressor blockCompressor =
  1386. zc->appliedParams.ldmParams.enableLdm
  1387. ? (extDict ? ZSTD_compressBlock_ldm_extDict : ZSTD_compressBlock_ldm)
  1388. : ZSTD_selectBlockCompressor(zc->appliedParams.cParams.strategy, extDict);
  1389. if (srcSize < MIN_CBLOCK_SIZE+ZSTD_blockHeaderSize+1) return 0; /* don't even attempt compression below a certain srcSize */
  1390. ZSTD_resetSeqStore(&(zc->seqStore));
  1391. if (current > zc->nextToUpdate + 384)
  1392. zc->nextToUpdate = current - MIN(192, (U32)(current - zc->nextToUpdate - 384)); /* limited update after finding a very long match */
  1393. lastLLSize = blockCompressor(zc, src, srcSize);
  1394. /* Last literals */
  1395. anchor = (const BYTE*)src + srcSize - lastLLSize;
  1396. ZSTD_storeLastLiterals(&zc->seqStore, anchor, lastLLSize);
  1397. return ZSTD_compressSequences(&zc->seqStore, zc->entropy, &zc->appliedParams.cParams, dst, dstCapacity, srcSize);
  1398. }
  1399. /*! ZSTD_compress_frameChunk() :
  1400. * Compress a chunk of data into one or multiple blocks.
  1401. * All blocks will be terminated, all input will be consumed.
  1402. * Function will issue an error if there is not enough `dstCapacity` to hold the compressed content.
  1403. * Frame is supposed already started (header already produced)
  1404. * @return : compressed size, or an error code
  1405. */
  1406. static size_t ZSTD_compress_frameChunk (ZSTD_CCtx* cctx,
  1407. void* dst, size_t dstCapacity,
  1408. const void* src, size_t srcSize,
  1409. U32 lastFrameChunk)
  1410. {
  1411. size_t blockSize = cctx->blockSize;
  1412. size_t remaining = srcSize;
  1413. const BYTE* ip = (const BYTE*)src;
  1414. BYTE* const ostart = (BYTE*)dst;
  1415. BYTE* op = ostart;
  1416. U32 const maxDist = (U32)1 << cctx->appliedParams.cParams.windowLog;
  1417. if (cctx->appliedParams.fParams.checksumFlag && srcSize)
  1418. XXH64_update(&cctx->xxhState, src, srcSize);
  1419. while (remaining) {
  1420. U32 const lastBlock = lastFrameChunk & (blockSize >= remaining);
  1421. size_t cSize;
  1422. if (dstCapacity < ZSTD_blockHeaderSize + MIN_CBLOCK_SIZE)
  1423. return ERROR(dstSize_tooSmall); /* not enough space to store compressed block */
  1424. if (remaining < blockSize) blockSize = remaining;
  1425. /* preemptive overflow correction:
  1426. * 1. correction is large enough:
  1427. * lowLimit > (3<<29) ==> current > 3<<29 + 1<<windowLog - blockSize
  1428. * 1<<windowLog <= newCurrent < 1<<chainLog + 1<<windowLog
  1429. *
  1430. * current - newCurrent
  1431. * > (3<<29 + 1<<windowLog - blockSize) - (1<<windowLog + 1<<chainLog)
  1432. * > (3<<29 - blockSize) - (1<<chainLog)
  1433. * > (3<<29 - blockSize) - (1<<30) (NOTE: chainLog <= 30)
  1434. * > 1<<29 - 1<<17
  1435. *
  1436. * 2. (ip+blockSize - cctx->base) doesn't overflow:
  1437. * In 32 bit mode we limit windowLog to 30 so we don't get
  1438. * differences larger than 1<<31-1.
  1439. * 3. cctx->lowLimit < 1<<32:
  1440. * windowLog <= 31 ==> 3<<29 + 1<<windowLog < 7<<29 < 1<<32.
  1441. */
  1442. if (cctx->lowLimit > (3U<<29)) {
  1443. U32 const cycleMask = ((U32)1 << ZSTD_cycleLog(cctx->appliedParams.cParams.chainLog, cctx->appliedParams.cParams.strategy)) - 1;
  1444. U32 const current = (U32)(ip - cctx->base);
  1445. U32 const newCurrent = (current & cycleMask) + ((U32)1 << cctx->appliedParams.cParams.windowLog);
  1446. U32 const correction = current - newCurrent;
  1447. ZSTD_STATIC_ASSERT(ZSTD_CHAINLOG_MAX <= 30);
  1448. ZSTD_STATIC_ASSERT(ZSTD_WINDOWLOG_MAX_32 <= 30);
  1449. ZSTD_STATIC_ASSERT(ZSTD_WINDOWLOG_MAX <= 31);
  1450. assert(current > newCurrent);
  1451. assert(correction > 1<<28); /* Loose bound, should be about 1<<29 */
  1452. ZSTD_reduceIndex(cctx, correction);
  1453. cctx->base += correction;
  1454. cctx->dictBase += correction;
  1455. cctx->lowLimit -= correction;
  1456. cctx->dictLimit -= correction;
  1457. if (cctx->nextToUpdate < correction) cctx->nextToUpdate = 0;
  1458. else cctx->nextToUpdate -= correction;
  1459. DEBUGLOG(4, "Correction of 0x%x bytes to lowLimit=0x%x\n", correction, cctx->lowLimit);
  1460. }
  1461. if ((U32)(ip+blockSize - cctx->base) > cctx->loadedDictEnd + maxDist) {
  1462. /* enforce maxDist */
  1463. U32 const newLowLimit = (U32)(ip+blockSize - cctx->base) - maxDist;
  1464. if (cctx->lowLimit < newLowLimit) cctx->lowLimit = newLowLimit;
  1465. if (cctx->dictLimit < cctx->lowLimit) cctx->dictLimit = cctx->lowLimit;
  1466. }
  1467. cSize = ZSTD_compressBlock_internal(cctx, op+ZSTD_blockHeaderSize, dstCapacity-ZSTD_blockHeaderSize, ip, blockSize);
  1468. if (ZSTD_isError(cSize)) return cSize;
  1469. if (cSize == 0) { /* block is not compressible */
  1470. U32 const cBlockHeader24 = lastBlock + (((U32)bt_raw)<<1) + (U32)(blockSize << 3);
  1471. if (blockSize + ZSTD_blockHeaderSize > dstCapacity) return ERROR(dstSize_tooSmall);
  1472. MEM_writeLE32(op, cBlockHeader24); /* no pb, 4th byte will be overwritten */
  1473. memcpy(op + ZSTD_blockHeaderSize, ip, blockSize);
  1474. cSize = ZSTD_blockHeaderSize+blockSize;
  1475. } else {
  1476. U32 const cBlockHeader24 = lastBlock + (((U32)bt_compressed)<<1) + (U32)(cSize << 3);
  1477. MEM_writeLE24(op, cBlockHeader24);
  1478. cSize += ZSTD_blockHeaderSize;
  1479. }
  1480. remaining -= blockSize;
  1481. dstCapacity -= cSize;
  1482. ip += blockSize;
  1483. op += cSize;
  1484. }
  1485. if (lastFrameChunk && (op>ostart)) cctx->stage = ZSTDcs_ending;
  1486. return op-ostart;
  1487. }
  1488. static size_t ZSTD_writeFrameHeader(void* dst, size_t dstCapacity,
  1489. ZSTD_CCtx_params params, U64 pledgedSrcSize, U32 dictID)
  1490. { BYTE* const op = (BYTE*)dst;
  1491. U32 const dictIDSizeCodeLength = (dictID>0) + (dictID>=256) + (dictID>=65536); /* 0-3 */
  1492. U32 const dictIDSizeCode = params.fParams.noDictIDFlag ? 0 : dictIDSizeCodeLength; /* 0-3 */
  1493. U32 const checksumFlag = params.fParams.checksumFlag>0;
  1494. U32 const windowSize = (U32)1 << params.cParams.windowLog;
  1495. U32 const singleSegment = params.fParams.contentSizeFlag && (windowSize >= pledgedSrcSize);
  1496. BYTE const windowLogByte = (BYTE)((params.cParams.windowLog - ZSTD_WINDOWLOG_ABSOLUTEMIN) << 3);
  1497. U32 const fcsCode = params.fParams.contentSizeFlag ?
  1498. (pledgedSrcSize>=256) + (pledgedSrcSize>=65536+256) + (pledgedSrcSize>=0xFFFFFFFFU) : 0; /* 0-3 */
  1499. BYTE const frameHeaderDecriptionByte = (BYTE)(dictIDSizeCode + (checksumFlag<<2) + (singleSegment<<5) + (fcsCode<<6) );
  1500. size_t pos=0;
  1501. if (dstCapacity < ZSTD_frameHeaderSize_max) return ERROR(dstSize_tooSmall);
  1502. DEBUGLOG(4, "ZSTD_writeFrameHeader : dictIDFlag : %u ; dictID : %u ; dictIDSizeCode : %u",
  1503. !params.fParams.noDictIDFlag, dictID, dictIDSizeCode);
  1504. if (params.format == ZSTD_f_zstd1) {
  1505. DEBUGLOG(4, "writing zstd magic number");
  1506. MEM_writeLE32(dst, ZSTD_MAGICNUMBER);
  1507. pos = 4;
  1508. }
  1509. op[pos++] = frameHeaderDecriptionByte;
  1510. if (!singleSegment) op[pos++] = windowLogByte;
  1511. switch(dictIDSizeCode)
  1512. {
  1513. default: assert(0); /* impossible */
  1514. case 0 : break;
  1515. case 1 : op[pos] = (BYTE)(dictID); pos++; break;
  1516. case 2 : MEM_writeLE16(op+pos, (U16)dictID); pos+=2; break;
  1517. case 3 : MEM_writeLE32(op+pos, dictID); pos+=4; break;
  1518. }
  1519. switch(fcsCode)
  1520. {
  1521. default: assert(0); /* impossible */
  1522. case 0 : if (singleSegment) op[pos++] = (BYTE)(pledgedSrcSize); break;
  1523. case 1 : MEM_writeLE16(op+pos, (U16)(pledgedSrcSize-256)); pos+=2; break;
  1524. case 2 : MEM_writeLE32(op+pos, (U32)(pledgedSrcSize)); pos+=4; break;
  1525. case 3 : MEM_writeLE64(op+pos, (U64)(pledgedSrcSize)); pos+=8; break;
  1526. }
  1527. return pos;
  1528. }
  1529. static size_t ZSTD_compressContinue_internal (ZSTD_CCtx* cctx,
  1530. void* dst, size_t dstCapacity,
  1531. const void* src, size_t srcSize,
  1532. U32 frame, U32 lastFrameChunk)
  1533. {
  1534. const BYTE* const ip = (const BYTE*) src;
  1535. size_t fhSize = 0;
  1536. DEBUGLOG(5, "ZSTD_compressContinue_internal");
  1537. DEBUGLOG(5, "stage: %u", cctx->stage);
  1538. if (cctx->stage==ZSTDcs_created) return ERROR(stage_wrong); /* missing init (ZSTD_compressBegin) */
  1539. if (frame && (cctx->stage==ZSTDcs_init)) {
  1540. fhSize = ZSTD_writeFrameHeader(dst, dstCapacity, cctx->appliedParams,
  1541. cctx->pledgedSrcSizePlusOne-1, cctx->dictID);
  1542. if (ZSTD_isError(fhSize)) return fhSize;
  1543. dstCapacity -= fhSize;
  1544. dst = (char*)dst + fhSize;
  1545. cctx->stage = ZSTDcs_ongoing;
  1546. }
  1547. /* Check if blocks follow each other */
  1548. if (src != cctx->nextSrc) {
  1549. /* not contiguous */
  1550. ptrdiff_t const delta = cctx->nextSrc - ip;
  1551. cctx->lowLimit = cctx->dictLimit;
  1552. cctx->dictLimit = (U32)(cctx->nextSrc - cctx->base);
  1553. cctx->dictBase = cctx->base;
  1554. cctx->base -= delta;
  1555. cctx->nextToUpdate = cctx->dictLimit;
  1556. if (cctx->dictLimit - cctx->lowLimit < HASH_READ_SIZE) cctx->lowLimit = cctx->dictLimit; /* too small extDict */
  1557. }
  1558. /* if input and dictionary overlap : reduce dictionary (area presumed modified by input) */
  1559. if ((ip+srcSize > cctx->dictBase + cctx->lowLimit) & (ip < cctx->dictBase + cctx->dictLimit)) {
  1560. ptrdiff_t const highInputIdx = (ip + srcSize) - cctx->dictBase;
  1561. U32 const lowLimitMax = (highInputIdx > (ptrdiff_t)cctx->dictLimit) ? cctx->dictLimit : (U32)highInputIdx;
  1562. cctx->lowLimit = lowLimitMax;
  1563. }
  1564. cctx->nextSrc = ip + srcSize;
  1565. if (srcSize) {
  1566. size_t const cSize = frame ?
  1567. ZSTD_compress_frameChunk (cctx, dst, dstCapacity, src, srcSize, lastFrameChunk) :
  1568. ZSTD_compressBlock_internal (cctx, dst, dstCapacity, src, srcSize);
  1569. if (ZSTD_isError(cSize)) return cSize;
  1570. cctx->consumedSrcSize += srcSize;
  1571. return cSize + fhSize;
  1572. } else
  1573. return fhSize;
  1574. }
  1575. size_t ZSTD_compressContinue (ZSTD_CCtx* cctx,
  1576. void* dst, size_t dstCapacity,
  1577. const void* src, size_t srcSize)
  1578. {
  1579. return ZSTD_compressContinue_internal(cctx, dst, dstCapacity, src, srcSize, 1 /* frame mode */, 0 /* last chunk */);
  1580. }
  1581. size_t ZSTD_getBlockSize(const ZSTD_CCtx* cctx)
  1582. {
  1583. ZSTD_compressionParameters const cParams =
  1584. ZSTD_getCParamsFromCCtxParams(cctx->appliedParams, 0, 0);
  1585. return MIN (ZSTD_BLOCKSIZE_MAX, (U32)1 << cParams.windowLog);
  1586. }
  1587. size_t ZSTD_compressBlock(ZSTD_CCtx* cctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize)
  1588. {
  1589. size_t const blockSizeMax = ZSTD_getBlockSize(cctx);
  1590. if (srcSize > blockSizeMax) return ERROR(srcSize_wrong);
  1591. return ZSTD_compressContinue_internal(cctx, dst, dstCapacity, src, srcSize, 0 /* frame mode */, 0 /* last chunk */);
  1592. }
  1593. /*! ZSTD_loadDictionaryContent() :
  1594. * @return : 0, or an error code
  1595. */
  1596. static size_t ZSTD_loadDictionaryContent(ZSTD_CCtx* zc, const void* src, size_t srcSize)
  1597. {
  1598. const BYTE* const ip = (const BYTE*) src;
  1599. const BYTE* const iend = ip + srcSize;
  1600. /* input becomes current prefix */
  1601. zc->lowLimit = zc->dictLimit;
  1602. zc->dictLimit = (U32)(zc->nextSrc - zc->base);
  1603. zc->dictBase = zc->base;
  1604. zc->base += ip - zc->nextSrc;
  1605. zc->nextToUpdate = zc->dictLimit;
  1606. zc->loadedDictEnd = zc->appliedParams.forceWindow ? 0 : (U32)(iend - zc->base);
  1607. zc->nextSrc = iend;
  1608. if (srcSize <= HASH_READ_SIZE) return 0;
  1609. switch(zc->appliedParams.cParams.strategy)
  1610. {
  1611. case ZSTD_fast:
  1612. ZSTD_fillHashTable (zc, iend, zc->appliedParams.cParams.searchLength);
  1613. break;
  1614. case ZSTD_dfast:
  1615. ZSTD_fillDoubleHashTable (zc, iend, zc->appliedParams.cParams.searchLength);
  1616. break;
  1617. case ZSTD_greedy:
  1618. case ZSTD_lazy:
  1619. case ZSTD_lazy2:
  1620. if (srcSize >= HASH_READ_SIZE)
  1621. ZSTD_insertAndFindFirstIndex(zc, iend-HASH_READ_SIZE, zc->appliedParams.cParams.searchLength);
  1622. break;
  1623. case ZSTD_btlazy2:
  1624. case ZSTD_btopt:
  1625. case ZSTD_btultra:
  1626. if (srcSize >= HASH_READ_SIZE)
  1627. ZSTD_updateTree(zc, iend-HASH_READ_SIZE, iend, (U32)1 << zc->appliedParams.cParams.searchLog, zc->appliedParams.cParams.searchLength);
  1628. break;
  1629. default:
  1630. assert(0); /* not possible : not a valid strategy id */
  1631. }
  1632. zc->nextToUpdate = (U32)(iend - zc->base);
  1633. return 0;
  1634. }
  1635. /* Dictionaries that assign zero probability to symbols that show up causes problems
  1636. when FSE encoding. Refuse dictionaries that assign zero probability to symbols
  1637. that we may encounter during compression.
  1638. NOTE: This behavior is not standard and could be improved in the future. */
  1639. static size_t ZSTD_checkDictNCount(short* normalizedCounter, unsigned dictMaxSymbolValue, unsigned maxSymbolValue) {
  1640. U32 s;
  1641. if (dictMaxSymbolValue < maxSymbolValue) return ERROR(dictionary_corrupted);
  1642. for (s = 0; s <= maxSymbolValue; ++s) {
  1643. if (normalizedCounter[s] == 0) return ERROR(dictionary_corrupted);
  1644. }
  1645. return 0;
  1646. }
  1647. /* Dictionary format :
  1648. * See :
  1649. * https://github.com/facebook/zstd/blob/master/doc/zstd_compression_format.md#dictionary-format
  1650. */
  1651. /*! ZSTD_loadZstdDictionary() :
  1652. * @return : 0, or an error code
  1653. * assumptions : magic number supposed already checked
  1654. * dictSize supposed > 8
  1655. */
  1656. static size_t ZSTD_loadZstdDictionary(ZSTD_CCtx* cctx, const void* dict, size_t dictSize)
  1657. {
  1658. const BYTE* dictPtr = (const BYTE*)dict;
  1659. const BYTE* const dictEnd = dictPtr + dictSize;
  1660. short offcodeNCount[MaxOff+1];
  1661. unsigned offcodeMaxValue = MaxOff;
  1662. ZSTD_STATIC_ASSERT(sizeof(cctx->entropy->workspace) >= (1<<MAX(MLFSELog,LLFSELog)));
  1663. dictPtr += 4; /* skip magic number */
  1664. cctx->dictID = cctx->appliedParams.fParams.noDictIDFlag ? 0 : MEM_readLE32(dictPtr);
  1665. dictPtr += 4;
  1666. { unsigned maxSymbolValue = 255;
  1667. size_t const hufHeaderSize = HUF_readCTable((HUF_CElt*)cctx->entropy->hufCTable, &maxSymbolValue, dictPtr, dictEnd-dictPtr);
  1668. if (HUF_isError(hufHeaderSize)) return ERROR(dictionary_corrupted);
  1669. if (maxSymbolValue < 255) return ERROR(dictionary_corrupted);
  1670. dictPtr += hufHeaderSize;
  1671. }
  1672. { unsigned offcodeLog;
  1673. size_t const offcodeHeaderSize = FSE_readNCount(offcodeNCount, &offcodeMaxValue, &offcodeLog, dictPtr, dictEnd-dictPtr);
  1674. if (FSE_isError(offcodeHeaderSize)) return ERROR(dictionary_corrupted);
  1675. if (offcodeLog > OffFSELog) return ERROR(dictionary_corrupted);
  1676. /* Defer checking offcodeMaxValue because we need to know the size of the dictionary content */
  1677. CHECK_E( FSE_buildCTable_wksp(cctx->entropy->offcodeCTable, offcodeNCount, offcodeMaxValue, offcodeLog, cctx->entropy->workspace, sizeof(cctx->entropy->workspace)),
  1678. dictionary_corrupted);
  1679. dictPtr += offcodeHeaderSize;
  1680. }
  1681. { short matchlengthNCount[MaxML+1];
  1682. unsigned matchlengthMaxValue = MaxML, matchlengthLog;
  1683. size_t const matchlengthHeaderSize = FSE_readNCount(matchlengthNCount, &matchlengthMaxValue, &matchlengthLog, dictPtr, dictEnd-dictPtr);
  1684. if (FSE_isError(matchlengthHeaderSize)) return ERROR(dictionary_corrupted);
  1685. if (matchlengthLog > MLFSELog) return ERROR(dictionary_corrupted);
  1686. /* Every match length code must have non-zero probability */
  1687. CHECK_F( ZSTD_checkDictNCount(matchlengthNCount, matchlengthMaxValue, MaxML));
  1688. CHECK_E( FSE_buildCTable_wksp(cctx->entropy->matchlengthCTable, matchlengthNCount, matchlengthMaxValue, matchlengthLog, cctx->entropy->workspace, sizeof(cctx->entropy->workspace)),
  1689. dictionary_corrupted);
  1690. dictPtr += matchlengthHeaderSize;
  1691. }
  1692. { short litlengthNCount[MaxLL+1];
  1693. unsigned litlengthMaxValue = MaxLL, litlengthLog;
  1694. size_t const litlengthHeaderSize = FSE_readNCount(litlengthNCount, &litlengthMaxValue, &litlengthLog, dictPtr, dictEnd-dictPtr);
  1695. if (FSE_isError(litlengthHeaderSize)) return ERROR(dictionary_corrupted);
  1696. if (litlengthLog > LLFSELog) return ERROR(dictionary_corrupted);
  1697. /* Every literal length code must have non-zero probability */
  1698. CHECK_F( ZSTD_checkDictNCount(litlengthNCount, litlengthMaxValue, MaxLL));
  1699. CHECK_E( FSE_buildCTable_wksp(cctx->entropy->litlengthCTable, litlengthNCount, litlengthMaxValue, litlengthLog, cctx->entropy->workspace, sizeof(cctx->entropy->workspace)),
  1700. dictionary_corrupted);
  1701. dictPtr += litlengthHeaderSize;
  1702. }
  1703. if (dictPtr+12 > dictEnd) return ERROR(dictionary_corrupted);
  1704. cctx->seqStore.rep[0] = MEM_readLE32(dictPtr+0);
  1705. cctx->seqStore.rep[1] = MEM_readLE32(dictPtr+4);
  1706. cctx->seqStore.rep[2] = MEM_readLE32(dictPtr+8);
  1707. dictPtr += 12;
  1708. { size_t const dictContentSize = (size_t)(dictEnd - dictPtr);
  1709. U32 offcodeMax = MaxOff;
  1710. if (dictContentSize <= ((U32)-1) - 128 KB) {
  1711. U32 const maxOffset = (U32)dictContentSize + 128 KB; /* The maximum offset that must be supported */
  1712. offcodeMax = ZSTD_highbit32(maxOffset); /* Calculate minimum offset code required to represent maxOffset */
  1713. }
  1714. /* All offset values <= dictContentSize + 128 KB must be representable */
  1715. CHECK_F (ZSTD_checkDictNCount(offcodeNCount, offcodeMaxValue, MIN(offcodeMax, MaxOff)));
  1716. /* All repCodes must be <= dictContentSize and != 0*/
  1717. { U32 u;
  1718. for (u=0; u<3; u++) {
  1719. if (cctx->seqStore.rep[u] == 0) return ERROR(dictionary_corrupted);
  1720. if (cctx->seqStore.rep[u] > dictContentSize) return ERROR(dictionary_corrupted);
  1721. } }
  1722. cctx->entropy->hufCTable_repeatMode = HUF_repeat_valid;
  1723. cctx->entropy->offcode_repeatMode = FSE_repeat_valid;
  1724. cctx->entropy->matchlength_repeatMode = FSE_repeat_valid;
  1725. cctx->entropy->litlength_repeatMode = FSE_repeat_valid;
  1726. return ZSTD_loadDictionaryContent(cctx, dictPtr, dictContentSize);
  1727. }
  1728. }
  1729. /** ZSTD_compress_insertDictionary() :
  1730. * @return : 0, or an error code */
  1731. static size_t ZSTD_compress_insertDictionary(ZSTD_CCtx* cctx,
  1732. const void* dict, size_t dictSize,
  1733. ZSTD_dictMode_e dictMode)
  1734. {
  1735. DEBUGLOG(5, "ZSTD_compress_insertDictionary");
  1736. if ((dict==NULL) || (dictSize<=8)) return 0;
  1737. /* dict restricted modes */
  1738. if (dictMode==ZSTD_dm_rawContent)
  1739. return ZSTD_loadDictionaryContent(cctx, dict, dictSize);
  1740. if (MEM_readLE32(dict) != ZSTD_MAGIC_DICTIONARY) {
  1741. if (dictMode == ZSTD_dm_auto) {
  1742. DEBUGLOG(5, "raw content dictionary detected");
  1743. return ZSTD_loadDictionaryContent(cctx, dict, dictSize);
  1744. }
  1745. if (dictMode == ZSTD_dm_fullDict)
  1746. return ERROR(dictionary_wrong);
  1747. assert(0); /* impossible */
  1748. }
  1749. /* dict as full zstd dictionary */
  1750. return ZSTD_loadZstdDictionary(cctx, dict, dictSize);
  1751. }
  1752. /*! ZSTD_compressBegin_internal() :
  1753. * @return : 0, or an error code */
  1754. static size_t ZSTD_compressBegin_internal(ZSTD_CCtx* cctx,
  1755. const void* dict, size_t dictSize,
  1756. ZSTD_dictMode_e dictMode,
  1757. const ZSTD_CDict* cdict,
  1758. ZSTD_CCtx_params params, U64 pledgedSrcSize,
  1759. ZSTD_buffered_policy_e zbuff)
  1760. {
  1761. DEBUGLOG(4, "ZSTD_compressBegin_internal");
  1762. /* params are supposed to be fully validated at this point */
  1763. assert(!ZSTD_isError(ZSTD_checkCParams(params.cParams)));
  1764. assert(!((dict) && (cdict))); /* either dict or cdict, not both */
  1765. if (cdict && cdict->dictContentSize>0) {
  1766. return ZSTD_copyCCtx_internal(cctx, cdict->refContext,
  1767. params.fParams, pledgedSrcSize,
  1768. zbuff);
  1769. }
  1770. CHECK_F( ZSTD_resetCCtx_internal(cctx, params, pledgedSrcSize,
  1771. ZSTDcrp_continue, zbuff) );
  1772. return ZSTD_compress_insertDictionary(cctx, dict, dictSize, dictMode);
  1773. }
  1774. size_t ZSTD_compressBegin_advanced_internal(
  1775. ZSTD_CCtx* cctx,
  1776. const void* dict, size_t dictSize,
  1777. ZSTD_dictMode_e dictMode,
  1778. ZSTD_CCtx_params params,
  1779. unsigned long long pledgedSrcSize)
  1780. {
  1781. /* compression parameters verification and optimization */
  1782. CHECK_F( ZSTD_checkCParams(params.cParams) );
  1783. return ZSTD_compressBegin_internal(cctx, dict, dictSize, dictMode, NULL,
  1784. params, pledgedSrcSize,
  1785. ZSTDb_not_buffered);
  1786. }
  1787. /*! ZSTD_compressBegin_advanced() :
  1788. * @return : 0, or an error code */
  1789. size_t ZSTD_compressBegin_advanced(ZSTD_CCtx* cctx,
  1790. const void* dict, size_t dictSize,
  1791. ZSTD_parameters params, unsigned long long pledgedSrcSize)
  1792. {
  1793. ZSTD_CCtx_params const cctxParams =
  1794. ZSTD_assignParamsToCCtxParams(cctx->requestedParams, params);
  1795. return ZSTD_compressBegin_advanced_internal(cctx, dict, dictSize, ZSTD_dm_auto,
  1796. cctxParams,
  1797. pledgedSrcSize);
  1798. }
  1799. size_t ZSTD_compressBegin_usingDict(ZSTD_CCtx* cctx, const void* dict, size_t dictSize, int compressionLevel)
  1800. {
  1801. ZSTD_parameters const params = ZSTD_getParams(compressionLevel, 0, dictSize);
  1802. ZSTD_CCtx_params const cctxParams =
  1803. ZSTD_assignParamsToCCtxParams(cctx->requestedParams, params);
  1804. return ZSTD_compressBegin_internal(cctx, dict, dictSize, ZSTD_dm_auto, NULL,
  1805. cctxParams, 0, ZSTDb_not_buffered);
  1806. }
  1807. size_t ZSTD_compressBegin(ZSTD_CCtx* cctx, int compressionLevel)
  1808. {
  1809. return ZSTD_compressBegin_usingDict(cctx, NULL, 0, compressionLevel);
  1810. }
  1811. /*! ZSTD_writeEpilogue() :
  1812. * Ends a frame.
  1813. * @return : nb of bytes written into dst (or an error code) */
  1814. static size_t ZSTD_writeEpilogue(ZSTD_CCtx* cctx, void* dst, size_t dstCapacity)
  1815. {
  1816. BYTE* const ostart = (BYTE*)dst;
  1817. BYTE* op = ostart;
  1818. size_t fhSize = 0;
  1819. DEBUGLOG(5, "ZSTD_writeEpilogue");
  1820. if (cctx->stage == ZSTDcs_created) return ERROR(stage_wrong); /* init missing */
  1821. /* special case : empty frame */
  1822. if (cctx->stage == ZSTDcs_init) {
  1823. fhSize = ZSTD_writeFrameHeader(dst, dstCapacity, cctx->appliedParams, 0, 0);
  1824. if (ZSTD_isError(fhSize)) return fhSize;
  1825. dstCapacity -= fhSize;
  1826. op += fhSize;
  1827. cctx->stage = ZSTDcs_ongoing;
  1828. }
  1829. if (cctx->stage != ZSTDcs_ending) {
  1830. /* write one last empty block, make it the "last" block */
  1831. U32 const cBlockHeader24 = 1 /* last block */ + (((U32)bt_raw)<<1) + 0;
  1832. if (dstCapacity<4) return ERROR(dstSize_tooSmall);
  1833. MEM_writeLE32(op, cBlockHeader24);
  1834. op += ZSTD_blockHeaderSize;
  1835. dstCapacity -= ZSTD_blockHeaderSize;
  1836. }
  1837. if (cctx->appliedParams.fParams.checksumFlag) {
  1838. U32 const checksum = (U32) XXH64_digest(&cctx->xxhState);
  1839. if (dstCapacity<4) return ERROR(dstSize_tooSmall);
  1840. MEM_writeLE32(op, checksum);
  1841. op += 4;
  1842. }
  1843. cctx->stage = ZSTDcs_created; /* return to "created but no init" status */
  1844. return op-ostart;
  1845. }
  1846. size_t ZSTD_compressEnd (ZSTD_CCtx* cctx,
  1847. void* dst, size_t dstCapacity,
  1848. const void* src, size_t srcSize)
  1849. {
  1850. size_t endResult;
  1851. size_t const cSize = ZSTD_compressContinue_internal(cctx,
  1852. dst, dstCapacity, src, srcSize,
  1853. 1 /* frame mode */, 1 /* last chunk */);
  1854. if (ZSTD_isError(cSize)) return cSize;
  1855. endResult = ZSTD_writeEpilogue(cctx, (char*)dst + cSize, dstCapacity-cSize);
  1856. if (ZSTD_isError(endResult)) return endResult;
  1857. if (cctx->appliedParams.fParams.contentSizeFlag) { /* control src size */
  1858. DEBUGLOG(4, "end of frame : controlling src size");
  1859. if (cctx->pledgedSrcSizePlusOne != cctx->consumedSrcSize+1) {
  1860. DEBUGLOG(4, "error : pledgedSrcSize = %u, while realSrcSize = %u",
  1861. (U32)cctx->pledgedSrcSizePlusOne-1, (U32)cctx->consumedSrcSize);
  1862. return ERROR(srcSize_wrong);
  1863. } }
  1864. return cSize + endResult;
  1865. }
  1866. static size_t ZSTD_compress_internal (ZSTD_CCtx* cctx,
  1867. void* dst, size_t dstCapacity,
  1868. const void* src, size_t srcSize,
  1869. const void* dict,size_t dictSize,
  1870. ZSTD_parameters params)
  1871. {
  1872. ZSTD_CCtx_params const cctxParams =
  1873. ZSTD_assignParamsToCCtxParams(cctx->requestedParams, params);
  1874. return ZSTD_compress_advanced_internal(cctx,
  1875. dst, dstCapacity,
  1876. src, srcSize,
  1877. dict, dictSize,
  1878. cctxParams);
  1879. }
  1880. size_t ZSTD_compress_advanced (ZSTD_CCtx* ctx,
  1881. void* dst, size_t dstCapacity,
  1882. const void* src, size_t srcSize,
  1883. const void* dict,size_t dictSize,
  1884. ZSTD_parameters params)
  1885. {
  1886. CHECK_F(ZSTD_checkCParams(params.cParams));
  1887. return ZSTD_compress_internal(ctx, dst, dstCapacity, src, srcSize, dict, dictSize, params);
  1888. }
  1889. /* Internal */
  1890. size_t ZSTD_compress_advanced_internal(
  1891. ZSTD_CCtx* cctx,
  1892. void* dst, size_t dstCapacity,
  1893. const void* src, size_t srcSize,
  1894. const void* dict,size_t dictSize,
  1895. ZSTD_CCtx_params params)
  1896. {
  1897. CHECK_F( ZSTD_compressBegin_internal(cctx, dict, dictSize, ZSTD_dm_auto, NULL,
  1898. params, srcSize, ZSTDb_not_buffered) );
  1899. return ZSTD_compressEnd(cctx, dst, dstCapacity, src, srcSize);
  1900. }
  1901. size_t ZSTD_compress_usingDict(ZSTD_CCtx* ctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize,
  1902. const void* dict, size_t dictSize, int compressionLevel)
  1903. {
  1904. ZSTD_parameters params = ZSTD_getParams(compressionLevel, srcSize, dict ? dictSize : 0);
  1905. params.fParams.contentSizeFlag = 1;
  1906. return ZSTD_compress_internal(ctx, dst, dstCapacity, src, srcSize, dict, dictSize, params);
  1907. }
  1908. size_t ZSTD_compressCCtx (ZSTD_CCtx* ctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize, int compressionLevel)
  1909. {
  1910. return ZSTD_compress_usingDict(ctx, dst, dstCapacity, src, srcSize, NULL, 0, compressionLevel);
  1911. }
  1912. size_t ZSTD_compress(void* dst, size_t dstCapacity, const void* src, size_t srcSize, int compressionLevel)
  1913. {
  1914. size_t result;
  1915. ZSTD_CCtx ctxBody;
  1916. memset(&ctxBody, 0, sizeof(ctxBody));
  1917. ctxBody.customMem = ZSTD_defaultCMem;
  1918. result = ZSTD_compressCCtx(&ctxBody, dst, dstCapacity, src, srcSize, compressionLevel);
  1919. ZSTD_free(ctxBody.workSpace, ZSTD_defaultCMem); /* can't free ctxBody itself, as it's on stack; free only heap content */
  1920. return result;
  1921. }
  1922. /* ===== Dictionary API ===== */
  1923. /*! ZSTD_estimateCDictSize_advanced() :
  1924. * Estimate amount of memory that will be needed to create a dictionary with following arguments */
  1925. size_t ZSTD_estimateCDictSize_advanced(
  1926. size_t dictSize, ZSTD_compressionParameters cParams,
  1927. ZSTD_dictLoadMethod_e dictLoadMethod)
  1928. {
  1929. DEBUGLOG(5, "sizeof(ZSTD_CDict) : %u", (U32)sizeof(ZSTD_CDict));
  1930. DEBUGLOG(5, "CCtx estimate : %u",
  1931. (U32)ZSTD_estimateCCtxSize_usingCParams(cParams));
  1932. return sizeof(ZSTD_CDict) + ZSTD_estimateCCtxSize_usingCParams(cParams)
  1933. + (dictLoadMethod == ZSTD_dlm_byRef ? 0 : dictSize);
  1934. }
  1935. size_t ZSTD_estimateCDictSize(size_t dictSize, int compressionLevel)
  1936. {
  1937. ZSTD_compressionParameters const cParams = ZSTD_getCParams(compressionLevel, 0, dictSize);
  1938. return ZSTD_estimateCDictSize_advanced(dictSize, cParams, ZSTD_dlm_byCopy);
  1939. }
  1940. size_t ZSTD_sizeof_CDict(const ZSTD_CDict* cdict)
  1941. {
  1942. if (cdict==NULL) return 0; /* support sizeof on NULL */
  1943. DEBUGLOG(5, "sizeof(*cdict) : %u", (U32)sizeof(*cdict));
  1944. DEBUGLOG(5, "ZSTD_sizeof_CCtx : %u", (U32)ZSTD_sizeof_CCtx(cdict->refContext));
  1945. return ZSTD_sizeof_CCtx(cdict->refContext) + (cdict->dictBuffer ? cdict->dictContentSize : 0) + sizeof(*cdict);
  1946. }
  1947. static size_t ZSTD_initCDict_internal(
  1948. ZSTD_CDict* cdict,
  1949. const void* dictBuffer, size_t dictSize,
  1950. ZSTD_dictLoadMethod_e dictLoadMethod,
  1951. ZSTD_dictMode_e dictMode,
  1952. ZSTD_compressionParameters cParams)
  1953. {
  1954. DEBUGLOG(5, "ZSTD_initCDict_internal, mode %u", (U32)dictMode);
  1955. if ((dictLoadMethod == ZSTD_dlm_byRef) || (!dictBuffer) || (!dictSize)) {
  1956. cdict->dictBuffer = NULL;
  1957. cdict->dictContent = dictBuffer;
  1958. } else {
  1959. void* const internalBuffer = ZSTD_malloc(dictSize, cdict->refContext->customMem);
  1960. cdict->dictBuffer = internalBuffer;
  1961. cdict->dictContent = internalBuffer;
  1962. if (!internalBuffer) return ERROR(memory_allocation);
  1963. memcpy(internalBuffer, dictBuffer, dictSize);
  1964. }
  1965. cdict->dictContentSize = dictSize;
  1966. { ZSTD_CCtx_params cctxParams = cdict->refContext->requestedParams;
  1967. cctxParams.cParams = cParams;
  1968. CHECK_F( ZSTD_compressBegin_internal(cdict->refContext,
  1969. cdict->dictContent, dictSize, dictMode,
  1970. NULL,
  1971. cctxParams, ZSTD_CONTENTSIZE_UNKNOWN,
  1972. ZSTDb_not_buffered) );
  1973. }
  1974. return 0;
  1975. }
  1976. ZSTD_CDict* ZSTD_createCDict_advanced(const void* dictBuffer, size_t dictSize,
  1977. ZSTD_dictLoadMethod_e dictLoadMethod,
  1978. ZSTD_dictMode_e dictMode,
  1979. ZSTD_compressionParameters cParams, ZSTD_customMem customMem)
  1980. {
  1981. DEBUGLOG(5, "ZSTD_createCDict_advanced, mode %u", (U32)dictMode);
  1982. if (!customMem.customAlloc ^ !customMem.customFree) return NULL;
  1983. { ZSTD_CDict* const cdict = (ZSTD_CDict*)ZSTD_malloc(sizeof(ZSTD_CDict), customMem);
  1984. ZSTD_CCtx* const cctx = ZSTD_createCCtx_advanced(customMem);
  1985. if (!cdict || !cctx) {
  1986. ZSTD_free(cdict, customMem);
  1987. ZSTD_freeCCtx(cctx);
  1988. return NULL;
  1989. }
  1990. cdict->refContext = cctx;
  1991. if (ZSTD_isError( ZSTD_initCDict_internal(cdict,
  1992. dictBuffer, dictSize,
  1993. dictLoadMethod, dictMode,
  1994. cParams) )) {
  1995. ZSTD_freeCDict(cdict);
  1996. return NULL;
  1997. }
  1998. return cdict;
  1999. }
  2000. }
  2001. ZSTD_CDict* ZSTD_createCDict(const void* dict, size_t dictSize, int compressionLevel)
  2002. {
  2003. ZSTD_compressionParameters cParams = ZSTD_getCParams(compressionLevel, 0, dictSize);
  2004. return ZSTD_createCDict_advanced(dict, dictSize,
  2005. ZSTD_dlm_byCopy, ZSTD_dm_auto,
  2006. cParams, ZSTD_defaultCMem);
  2007. }
  2008. ZSTD_CDict* ZSTD_createCDict_byReference(const void* dict, size_t dictSize, int compressionLevel)
  2009. {
  2010. ZSTD_compressionParameters cParams = ZSTD_getCParams(compressionLevel, 0, dictSize);
  2011. return ZSTD_createCDict_advanced(dict, dictSize,
  2012. ZSTD_dlm_byRef, ZSTD_dm_auto,
  2013. cParams, ZSTD_defaultCMem);
  2014. }
  2015. size_t ZSTD_freeCDict(ZSTD_CDict* cdict)
  2016. {
  2017. if (cdict==NULL) return 0; /* support free on NULL */
  2018. { ZSTD_customMem const cMem = cdict->refContext->customMem;
  2019. ZSTD_freeCCtx(cdict->refContext);
  2020. ZSTD_free(cdict->dictBuffer, cMem);
  2021. ZSTD_free(cdict, cMem);
  2022. return 0;
  2023. }
  2024. }
  2025. /*! ZSTD_initStaticCDict_advanced() :
  2026. * Generate a digested dictionary in provided memory area.
  2027. * workspace: The memory area to emplace the dictionary into.
  2028. * Provided pointer must 8-bytes aligned.
  2029. * It must outlive dictionary usage.
  2030. * workspaceSize: Use ZSTD_estimateCDictSize()
  2031. * to determine how large workspace must be.
  2032. * cParams : use ZSTD_getCParams() to transform a compression level
  2033. * into its relevants cParams.
  2034. * @return : pointer to ZSTD_CDict*, or NULL if error (size too small)
  2035. * Note : there is no corresponding "free" function.
  2036. * Since workspace was allocated externally, it must be freed externally.
  2037. */
  2038. ZSTD_CDict* ZSTD_initStaticCDict(void* workspace, size_t workspaceSize,
  2039. const void* dict, size_t dictSize,
  2040. ZSTD_dictLoadMethod_e dictLoadMethod,
  2041. ZSTD_dictMode_e dictMode,
  2042. ZSTD_compressionParameters cParams)
  2043. {
  2044. size_t const cctxSize = ZSTD_estimateCCtxSize_usingCParams(cParams);
  2045. size_t const neededSize = sizeof(ZSTD_CDict) + (dictLoadMethod == ZSTD_dlm_byRef ? 0 : dictSize)
  2046. + cctxSize;
  2047. ZSTD_CDict* const cdict = (ZSTD_CDict*) workspace;
  2048. void* ptr;
  2049. DEBUGLOG(5, "(size_t)workspace & 7 : %u", (U32)(size_t)workspace & 7);
  2050. if ((size_t)workspace & 7) return NULL; /* 8-aligned */
  2051. DEBUGLOG(5, "(workspaceSize < neededSize) : (%u < %u) => %u",
  2052. (U32)workspaceSize, (U32)neededSize, (U32)(workspaceSize < neededSize));
  2053. if (workspaceSize < neededSize) return NULL;
  2054. if (dictLoadMethod == ZSTD_dlm_byCopy) {
  2055. memcpy(cdict+1, dict, dictSize);
  2056. dict = cdict+1;
  2057. ptr = (char*)workspace + sizeof(ZSTD_CDict) + dictSize;
  2058. } else {
  2059. ptr = cdict+1;
  2060. }
  2061. cdict->refContext = ZSTD_initStaticCCtx(ptr, cctxSize);
  2062. if (ZSTD_isError( ZSTD_initCDict_internal(cdict,
  2063. dict, dictSize,
  2064. ZSTD_dlm_byRef, dictMode,
  2065. cParams) ))
  2066. return NULL;
  2067. return cdict;
  2068. }
  2069. ZSTD_compressionParameters ZSTD_getCParamsFromCDict(const ZSTD_CDict* cdict) {
  2070. return cdict->refContext->appliedParams.cParams;
  2071. }
  2072. /* ZSTD_compressBegin_usingCDict_advanced() :
  2073. * cdict must be != NULL */
  2074. size_t ZSTD_compressBegin_usingCDict_advanced(
  2075. ZSTD_CCtx* const cctx, const ZSTD_CDict* const cdict,
  2076. ZSTD_frameParameters const fParams, unsigned long long const pledgedSrcSize)
  2077. {
  2078. if (cdict==NULL) return ERROR(dictionary_wrong);
  2079. { ZSTD_CCtx_params params = cctx->requestedParams;
  2080. params.cParams = ZSTD_getCParamsFromCDict(cdict);
  2081. params.fParams = fParams;
  2082. DEBUGLOG(5, "ZSTD_compressBegin_usingCDict_advanced");
  2083. return ZSTD_compressBegin_internal(cctx,
  2084. NULL, 0, ZSTD_dm_auto,
  2085. cdict,
  2086. params, pledgedSrcSize,
  2087. ZSTDb_not_buffered);
  2088. }
  2089. }
  2090. /* ZSTD_compressBegin_usingCDict() :
  2091. * pledgedSrcSize=0 means "unknown"
  2092. * if pledgedSrcSize>0, it will enable contentSizeFlag */
  2093. size_t ZSTD_compressBegin_usingCDict(ZSTD_CCtx* cctx, const ZSTD_CDict* cdict)
  2094. {
  2095. ZSTD_frameParameters const fParams = { 0 /*content*/, 0 /*checksum*/, 0 /*noDictID*/ };
  2096. DEBUGLOG(5, "ZSTD_compressBegin_usingCDict : dictIDFlag == %u", !fParams.noDictIDFlag);
  2097. return ZSTD_compressBegin_usingCDict_advanced(cctx, cdict, fParams, 0);
  2098. }
  2099. size_t ZSTD_compress_usingCDict_advanced(ZSTD_CCtx* cctx,
  2100. void* dst, size_t dstCapacity,
  2101. const void* src, size_t srcSize,
  2102. const ZSTD_CDict* cdict, ZSTD_frameParameters fParams)
  2103. {
  2104. CHECK_F (ZSTD_compressBegin_usingCDict_advanced(cctx, cdict, fParams, srcSize)); /* will check if cdict != NULL */
  2105. return ZSTD_compressEnd(cctx, dst, dstCapacity, src, srcSize);
  2106. }
  2107. /*! ZSTD_compress_usingCDict() :
  2108. * Compression using a digested Dictionary.
  2109. * Faster startup than ZSTD_compress_usingDict(), recommended when same dictionary is used multiple times.
  2110. * Note that compression parameters are decided at CDict creation time
  2111. * while frame parameters are hardcoded */
  2112. size_t ZSTD_compress_usingCDict(ZSTD_CCtx* cctx,
  2113. void* dst, size_t dstCapacity,
  2114. const void* src, size_t srcSize,
  2115. const ZSTD_CDict* cdict)
  2116. {
  2117. ZSTD_frameParameters const fParams = { 1 /*content*/, 0 /*checksum*/, 0 /*noDictID*/ };
  2118. return ZSTD_compress_usingCDict_advanced(cctx, dst, dstCapacity, src, srcSize, cdict, fParams);
  2119. }
  2120. /* ******************************************************************
  2121. * Streaming
  2122. ********************************************************************/
  2123. ZSTD_CStream* ZSTD_createCStream(void)
  2124. {
  2125. return ZSTD_createCStream_advanced(ZSTD_defaultCMem);
  2126. }
  2127. ZSTD_CStream* ZSTD_initStaticCStream(void *workspace, size_t workspaceSize)
  2128. {
  2129. return ZSTD_initStaticCCtx(workspace, workspaceSize);
  2130. }
  2131. ZSTD_CStream* ZSTD_createCStream_advanced(ZSTD_customMem customMem)
  2132. { /* CStream and CCtx are now same object */
  2133. return ZSTD_createCCtx_advanced(customMem);
  2134. }
  2135. size_t ZSTD_freeCStream(ZSTD_CStream* zcs)
  2136. {
  2137. return ZSTD_freeCCtx(zcs); /* same object */
  2138. }
  2139. /*====== Initialization ======*/
  2140. size_t ZSTD_CStreamInSize(void) { return ZSTD_BLOCKSIZE_MAX; }
  2141. size_t ZSTD_CStreamOutSize(void)
  2142. {
  2143. return ZSTD_compressBound(ZSTD_BLOCKSIZE_MAX) + ZSTD_blockHeaderSize + 4 /* 32-bits hash */ ;
  2144. }
  2145. static size_t ZSTD_resetCStream_internal(ZSTD_CStream* zcs,
  2146. const void* dict, size_t dictSize, ZSTD_dictMode_e dictMode,
  2147. const ZSTD_CDict* cdict,
  2148. const ZSTD_CCtx_params params, unsigned long long pledgedSrcSize)
  2149. {
  2150. DEBUGLOG(4, "ZSTD_resetCStream_internal");
  2151. /* params are supposed to be fully validated at this point */
  2152. assert(!ZSTD_isError(ZSTD_checkCParams(params.cParams)));
  2153. assert(!((dict) && (cdict))); /* either dict or cdict, not both */
  2154. CHECK_F( ZSTD_compressBegin_internal(zcs,
  2155. dict, dictSize, dictMode,
  2156. cdict,
  2157. params, pledgedSrcSize,
  2158. ZSTDb_buffered) );
  2159. zcs->inToCompress = 0;
  2160. zcs->inBuffPos = 0;
  2161. zcs->inBuffTarget = zcs->blockSize;
  2162. zcs->outBuffContentSize = zcs->outBuffFlushedSize = 0;
  2163. zcs->streamStage = zcss_load;
  2164. zcs->frameEnded = 0;
  2165. return 0; /* ready to go */
  2166. }
  2167. size_t ZSTD_resetCStream(ZSTD_CStream* zcs, unsigned long long pledgedSrcSize)
  2168. {
  2169. ZSTD_CCtx_params params = zcs->requestedParams;
  2170. params.fParams.contentSizeFlag = (pledgedSrcSize > 0);
  2171. params.cParams = ZSTD_getCParamsFromCCtxParams(params, pledgedSrcSize, 0);
  2172. DEBUGLOG(4, "ZSTD_resetCStream");
  2173. return ZSTD_resetCStream_internal(zcs, NULL, 0, ZSTD_dm_auto, zcs->cdict, params, pledgedSrcSize);
  2174. }
  2175. /*! ZSTD_initCStream_internal() :
  2176. * Note : not static, but hidden (not exposed). Used by zstdmt_compress.c
  2177. * Assumption 1 : params are valid
  2178. * Assumption 2 : either dict, or cdict, is defined, not both */
  2179. size_t ZSTD_initCStream_internal(ZSTD_CStream* zcs,
  2180. const void* dict, size_t dictSize, const ZSTD_CDict* cdict,
  2181. ZSTD_CCtx_params params, unsigned long long pledgedSrcSize)
  2182. {
  2183. DEBUGLOG(4, "ZSTD_initCStream_internal");
  2184. assert(!ZSTD_isError(ZSTD_checkCParams(params.cParams)));
  2185. assert(!((dict) && (cdict))); /* either dict or cdict, not both */
  2186. if (dict && dictSize >= 8) {
  2187. DEBUGLOG(5, "loading dictionary of size %u", (U32)dictSize);
  2188. if (zcs->staticSize) { /* static CCtx : never uses malloc */
  2189. /* incompatible with internal cdict creation */
  2190. return ERROR(memory_allocation);
  2191. }
  2192. ZSTD_freeCDict(zcs->cdictLocal);
  2193. zcs->cdictLocal = ZSTD_createCDict_advanced(dict, dictSize,
  2194. ZSTD_dlm_byCopy, ZSTD_dm_auto,
  2195. params.cParams, zcs->customMem);
  2196. zcs->cdict = zcs->cdictLocal;
  2197. if (zcs->cdictLocal == NULL) return ERROR(memory_allocation);
  2198. } else {
  2199. if (cdict) {
  2200. params.cParams = ZSTD_getCParamsFromCDict(cdict); /* cParams are enforced from cdict */
  2201. }
  2202. ZSTD_freeCDict(zcs->cdictLocal);
  2203. zcs->cdictLocal = NULL;
  2204. zcs->cdict = cdict;
  2205. }
  2206. params.compressionLevel = ZSTD_CLEVEL_CUSTOM;
  2207. zcs->requestedParams = params;
  2208. return ZSTD_resetCStream_internal(zcs, NULL, 0, ZSTD_dm_auto, zcs->cdict, params, pledgedSrcSize);
  2209. }
  2210. /* ZSTD_initCStream_usingCDict_advanced() :
  2211. * same as ZSTD_initCStream_usingCDict(), with control over frame parameters */
  2212. size_t ZSTD_initCStream_usingCDict_advanced(ZSTD_CStream* zcs,
  2213. const ZSTD_CDict* cdict,
  2214. ZSTD_frameParameters fParams,
  2215. unsigned long long pledgedSrcSize)
  2216. { /* cannot handle NULL cdict (does not know what to do) */
  2217. if (!cdict) return ERROR(dictionary_wrong);
  2218. { ZSTD_CCtx_params params = zcs->requestedParams;
  2219. params.cParams = ZSTD_getCParamsFromCDict(cdict);
  2220. params.fParams = fParams;
  2221. return ZSTD_initCStream_internal(zcs,
  2222. NULL, 0, cdict,
  2223. params, pledgedSrcSize);
  2224. }
  2225. }
  2226. /* note : cdict must outlive compression session */
  2227. size_t ZSTD_initCStream_usingCDict(ZSTD_CStream* zcs, const ZSTD_CDict* cdict)
  2228. {
  2229. ZSTD_frameParameters const fParams = { 0 /* contentSize */, 0 /* checksum */, 0 /* hideDictID */ };
  2230. return ZSTD_initCStream_usingCDict_advanced(zcs, cdict, fParams, 0); /* note : will check that cdict != NULL */
  2231. }
  2232. size_t ZSTD_initCStream_advanced(ZSTD_CStream* zcs,
  2233. const void* dict, size_t dictSize,
  2234. ZSTD_parameters params, unsigned long long pledgedSrcSize)
  2235. {
  2236. ZSTD_CCtx_params const cctxParams =
  2237. ZSTD_assignParamsToCCtxParams(zcs->requestedParams, params);
  2238. CHECK_F( ZSTD_checkCParams(params.cParams) );
  2239. return ZSTD_initCStream_internal(zcs, dict, dictSize, NULL, cctxParams, pledgedSrcSize);
  2240. }
  2241. size_t ZSTD_initCStream_usingDict(ZSTD_CStream* zcs, const void* dict, size_t dictSize, int compressionLevel)
  2242. {
  2243. ZSTD_parameters const params = ZSTD_getParams(compressionLevel, 0, dictSize);
  2244. ZSTD_CCtx_params const cctxParams =
  2245. ZSTD_assignParamsToCCtxParams(zcs->requestedParams, params);
  2246. return ZSTD_initCStream_internal(zcs, dict, dictSize, NULL, cctxParams, 0);
  2247. }
  2248. size_t ZSTD_initCStream_srcSize(ZSTD_CStream* zcs, int compressionLevel, unsigned long long pledgedSrcSize)
  2249. {
  2250. ZSTD_CCtx_params cctxParams;
  2251. ZSTD_parameters const params = ZSTD_getParams(compressionLevel, pledgedSrcSize, 0);
  2252. cctxParams = ZSTD_assignParamsToCCtxParams(zcs->requestedParams, params);
  2253. cctxParams.fParams.contentSizeFlag = (pledgedSrcSize>0);
  2254. return ZSTD_initCStream_internal(zcs, NULL, 0, NULL, cctxParams, pledgedSrcSize);
  2255. }
  2256. size_t ZSTD_initCStream(ZSTD_CStream* zcs, int compressionLevel)
  2257. {
  2258. return ZSTD_initCStream_srcSize(zcs, compressionLevel, 0);
  2259. }
  2260. /*====== Compression ======*/
  2261. MEM_STATIC size_t ZSTD_limitCopy(void* dst, size_t dstCapacity,
  2262. const void* src, size_t srcSize)
  2263. {
  2264. size_t const length = MIN(dstCapacity, srcSize);
  2265. if (length) memcpy(dst, src, length);
  2266. return length;
  2267. }
  2268. /** ZSTD_compressStream_generic():
  2269. * internal function for all *compressStream*() variants and *compress_generic()
  2270. * non-static, because can be called from zstdmt.c
  2271. * @return : hint size for next input */
  2272. size_t ZSTD_compressStream_generic(ZSTD_CStream* zcs,
  2273. ZSTD_outBuffer* output,
  2274. ZSTD_inBuffer* input,
  2275. ZSTD_EndDirective const flushMode)
  2276. {
  2277. const char* const istart = (const char*)input->src;
  2278. const char* const iend = istart + input->size;
  2279. const char* ip = istart + input->pos;
  2280. char* const ostart = (char*)output->dst;
  2281. char* const oend = ostart + output->size;
  2282. char* op = ostart + output->pos;
  2283. U32 someMoreWork = 1;
  2284. /* check expectations */
  2285. DEBUGLOG(5, "ZSTD_compressStream_generic, flush=%u", (U32)flushMode);
  2286. assert(zcs->inBuff != NULL);
  2287. assert(zcs->inBuffSize>0);
  2288. assert(zcs->outBuff!= NULL);
  2289. assert(zcs->outBuffSize>0);
  2290. assert(output->pos <= output->size);
  2291. assert(input->pos <= input->size);
  2292. while (someMoreWork) {
  2293. switch(zcs->streamStage)
  2294. {
  2295. case zcss_init:
  2296. /* call ZSTD_initCStream() first ! */
  2297. return ERROR(init_missing);
  2298. case zcss_load:
  2299. if ( (flushMode == ZSTD_e_end)
  2300. && ((size_t)(oend-op) >= ZSTD_compressBound(iend-ip)) /* enough dstCapacity */
  2301. && (zcs->inBuffPos == 0) ) {
  2302. /* shortcut to compression pass directly into output buffer */
  2303. size_t const cSize = ZSTD_compressEnd(zcs,
  2304. op, oend-op, ip, iend-ip);
  2305. DEBUGLOG(4, "ZSTD_compressEnd : %u", (U32)cSize);
  2306. if (ZSTD_isError(cSize)) return cSize;
  2307. ip = iend;
  2308. op += cSize;
  2309. zcs->frameEnded = 1;
  2310. ZSTD_startNewCompression(zcs);
  2311. someMoreWork = 0; break;
  2312. }
  2313. /* complete loading into inBuffer */
  2314. { size_t const toLoad = zcs->inBuffTarget - zcs->inBuffPos;
  2315. size_t const loaded = ZSTD_limitCopy(
  2316. zcs->inBuff + zcs->inBuffPos, toLoad,
  2317. ip, iend-ip);
  2318. zcs->inBuffPos += loaded;
  2319. ip += loaded;
  2320. if ( (flushMode == ZSTD_e_continue)
  2321. && (zcs->inBuffPos < zcs->inBuffTarget) ) {
  2322. /* not enough input to fill full block : stop here */
  2323. someMoreWork = 0; break;
  2324. }
  2325. if ( (flushMode == ZSTD_e_flush)
  2326. && (zcs->inBuffPos == zcs->inToCompress) ) {
  2327. /* empty */
  2328. someMoreWork = 0; break;
  2329. }
  2330. }
  2331. /* compress current block (note : this stage cannot be stopped in the middle) */
  2332. DEBUGLOG(5, "stream compression stage (flushMode==%u)", flushMode);
  2333. { void* cDst;
  2334. size_t cSize;
  2335. size_t const iSize = zcs->inBuffPos - zcs->inToCompress;
  2336. size_t oSize = oend-op;
  2337. unsigned const lastBlock = (flushMode == ZSTD_e_end) && (ip==iend);
  2338. if (oSize >= ZSTD_compressBound(iSize))
  2339. cDst = op; /* compress into output buffer, to skip flush stage */
  2340. else
  2341. cDst = zcs->outBuff, oSize = zcs->outBuffSize;
  2342. cSize = lastBlock ?
  2343. ZSTD_compressEnd(zcs, cDst, oSize,
  2344. zcs->inBuff + zcs->inToCompress, iSize) :
  2345. ZSTD_compressContinue(zcs, cDst, oSize,
  2346. zcs->inBuff + zcs->inToCompress, iSize);
  2347. if (ZSTD_isError(cSize)) return cSize;
  2348. zcs->frameEnded = lastBlock;
  2349. /* prepare next block */
  2350. zcs->inBuffTarget = zcs->inBuffPos + zcs->blockSize;
  2351. if (zcs->inBuffTarget > zcs->inBuffSize)
  2352. zcs->inBuffPos = 0, zcs->inBuffTarget = zcs->blockSize;
  2353. DEBUGLOG(5, "inBuffTarget:%u / inBuffSize:%u",
  2354. (U32)zcs->inBuffTarget, (U32)zcs->inBuffSize);
  2355. if (!lastBlock)
  2356. assert(zcs->inBuffTarget <= zcs->inBuffSize);
  2357. zcs->inToCompress = zcs->inBuffPos;
  2358. if (cDst == op) { /* no need to flush */
  2359. op += cSize;
  2360. if (zcs->frameEnded) {
  2361. DEBUGLOG(5, "Frame completed directly in outBuffer");
  2362. someMoreWork = 0;
  2363. ZSTD_startNewCompression(zcs);
  2364. }
  2365. break;
  2366. }
  2367. zcs->outBuffContentSize = cSize;
  2368. zcs->outBuffFlushedSize = 0;
  2369. zcs->streamStage = zcss_flush; /* pass-through to flush stage */
  2370. }
  2371. /* fall-through */
  2372. case zcss_flush:
  2373. DEBUGLOG(5, "flush stage");
  2374. { size_t const toFlush = zcs->outBuffContentSize - zcs->outBuffFlushedSize;
  2375. size_t const flushed = ZSTD_limitCopy(op, oend-op,
  2376. zcs->outBuff + zcs->outBuffFlushedSize, toFlush);
  2377. DEBUGLOG(5, "toFlush: %u into %u ==> flushed: %u",
  2378. (U32)toFlush, (U32)(oend-op), (U32)flushed);
  2379. op += flushed;
  2380. zcs->outBuffFlushedSize += flushed;
  2381. if (toFlush!=flushed) {
  2382. /* flush not fully completed, presumably because dst is too small */
  2383. assert(op==oend);
  2384. someMoreWork = 0;
  2385. break;
  2386. }
  2387. zcs->outBuffContentSize = zcs->outBuffFlushedSize = 0;
  2388. if (zcs->frameEnded) {
  2389. DEBUGLOG(5, "Frame completed on flush");
  2390. someMoreWork = 0;
  2391. ZSTD_startNewCompression(zcs);
  2392. break;
  2393. }
  2394. zcs->streamStage = zcss_load;
  2395. break;
  2396. }
  2397. default: /* impossible */
  2398. assert(0);
  2399. }
  2400. }
  2401. input->pos = ip - istart;
  2402. output->pos = op - ostart;
  2403. if (zcs->frameEnded) return 0;
  2404. { size_t hintInSize = zcs->inBuffTarget - zcs->inBuffPos;
  2405. if (hintInSize==0) hintInSize = zcs->blockSize;
  2406. return hintInSize;
  2407. }
  2408. }
  2409. size_t ZSTD_compressStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output, ZSTD_inBuffer* input)
  2410. {
  2411. /* check conditions */
  2412. if (output->pos > output->size) return ERROR(GENERIC);
  2413. if (input->pos > input->size) return ERROR(GENERIC);
  2414. return ZSTD_compressStream_generic(zcs, output, input, ZSTD_e_continue);
  2415. }
  2416. size_t ZSTD_compress_generic (ZSTD_CCtx* cctx,
  2417. ZSTD_outBuffer* output,
  2418. ZSTD_inBuffer* input,
  2419. ZSTD_EndDirective endOp)
  2420. {
  2421. DEBUGLOG(5, "ZSTD_compress_generic");
  2422. /* check conditions */
  2423. if (output->pos > output->size) return ERROR(GENERIC);
  2424. if (input->pos > input->size) return ERROR(GENERIC);
  2425. assert(cctx!=NULL);
  2426. /* transparent initialization stage */
  2427. if (cctx->streamStage == zcss_init) {
  2428. ZSTD_prefixDict const prefixDict = cctx->prefixDict;
  2429. ZSTD_CCtx_params params = cctx->requestedParams;
  2430. params.cParams = ZSTD_getCParamsFromCCtxParams(
  2431. cctx->requestedParams, cctx->pledgedSrcSizePlusOne-1, 0 /*dictSize*/);
  2432. memset(&cctx->prefixDict, 0, sizeof(cctx->prefixDict)); /* single usage */
  2433. assert(prefixDict.dict==NULL || cctx->cdict==NULL); /* only one can be set */
  2434. DEBUGLOG(4, "ZSTD_compress_generic : transparent init stage");
  2435. #ifdef ZSTD_MULTITHREAD
  2436. if (params.nbThreads > 1) {
  2437. if (cctx->mtctx == NULL || cctx->appliedParams.nbThreads != params.nbThreads) {
  2438. ZSTDMT_freeCCtx(cctx->mtctx);
  2439. cctx->mtctx = ZSTDMT_createCCtx_advanced(params.nbThreads, cctx->customMem);
  2440. if (cctx->mtctx == NULL) return ERROR(memory_allocation);
  2441. }
  2442. DEBUGLOG(4, "call ZSTDMT_initCStream_internal as nbThreads=%u", params.nbThreads);
  2443. CHECK_F( ZSTDMT_initCStream_internal(
  2444. cctx->mtctx,
  2445. prefixDict.dict, prefixDict.dictSize, ZSTD_dm_rawContent,
  2446. cctx->cdict, params, cctx->pledgedSrcSizePlusOne-1) );
  2447. cctx->streamStage = zcss_load;
  2448. cctx->appliedParams.nbThreads = params.nbThreads;
  2449. } else
  2450. #endif
  2451. {
  2452. CHECK_F( ZSTD_resetCStream_internal(
  2453. cctx, prefixDict.dict, prefixDict.dictSize,
  2454. prefixDict.dictMode, cctx->cdict, params,
  2455. cctx->pledgedSrcSizePlusOne-1) );
  2456. } }
  2457. /* compression stage */
  2458. #ifdef ZSTD_MULTITHREAD
  2459. if (cctx->appliedParams.nbThreads > 1) {
  2460. size_t const flushMin = ZSTDMT_compressStream_generic(cctx->mtctx, output, input, endOp);
  2461. DEBUGLOG(5, "ZSTDMT_compressStream_generic result : %u", (U32)flushMin);
  2462. if ( ZSTD_isError(flushMin)
  2463. || (endOp == ZSTD_e_end && flushMin == 0) ) { /* compression completed */
  2464. ZSTD_startNewCompression(cctx);
  2465. }
  2466. return flushMin;
  2467. }
  2468. #endif
  2469. CHECK_F( ZSTD_compressStream_generic(cctx, output, input, endOp) );
  2470. DEBUGLOG(5, "completed ZSTD_compress_generic");
  2471. return cctx->outBuffContentSize - cctx->outBuffFlushedSize; /* remaining to flush */
  2472. }
  2473. size_t ZSTD_compress_generic_simpleArgs (
  2474. ZSTD_CCtx* cctx,
  2475. void* dst, size_t dstCapacity, size_t* dstPos,
  2476. const void* src, size_t srcSize, size_t* srcPos,
  2477. ZSTD_EndDirective endOp)
  2478. {
  2479. ZSTD_outBuffer output = { dst, dstCapacity, *dstPos };
  2480. ZSTD_inBuffer input = { src, srcSize, *srcPos };
  2481. /* ZSTD_compress_generic() will check validity of dstPos and srcPos */
  2482. size_t const cErr = ZSTD_compress_generic(cctx, &output, &input, endOp);
  2483. *dstPos = output.pos;
  2484. *srcPos = input.pos;
  2485. return cErr;
  2486. }
  2487. /*====== Finalize ======*/
  2488. /*! ZSTD_flushStream() :
  2489. * @return : amount of data remaining to flush */
  2490. size_t ZSTD_flushStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output)
  2491. {
  2492. ZSTD_inBuffer input = { NULL, 0, 0 };
  2493. if (output->pos > output->size) return ERROR(GENERIC);
  2494. CHECK_F( ZSTD_compressStream_generic(zcs, output, &input, ZSTD_e_flush) );
  2495. return zcs->outBuffContentSize - zcs->outBuffFlushedSize; /* remaining to flush */
  2496. }
  2497. size_t ZSTD_endStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output)
  2498. {
  2499. ZSTD_inBuffer input = { NULL, 0, 0 };
  2500. if (output->pos > output->size) return ERROR(GENERIC);
  2501. CHECK_F( ZSTD_compressStream_generic(zcs, output, &input, ZSTD_e_end) );
  2502. { size_t const lastBlockSize = zcs->frameEnded ? 0 : ZSTD_BLOCKHEADERSIZE;
  2503. size_t const checksumSize = zcs->frameEnded ? 0 : zcs->appliedParams.fParams.checksumFlag * 4;
  2504. size_t const toFlush = zcs->outBuffContentSize - zcs->outBuffFlushedSize + lastBlockSize + checksumSize;
  2505. DEBUGLOG(5, "ZSTD_endStream : remaining to flush : %u",
  2506. (unsigned)toFlush);
  2507. return toFlush;
  2508. }
  2509. }
  2510. /*-===== Pre-defined compression levels =====-*/
  2511. #define ZSTD_MAX_CLEVEL 22
  2512. int ZSTD_maxCLevel(void) { return ZSTD_MAX_CLEVEL; }
  2513. static const ZSTD_compressionParameters ZSTD_defaultCParameters[4][ZSTD_MAX_CLEVEL+1] = {
  2514. { /* "default" - guarantees a monotonically increasing memory budget */
  2515. /* W, C, H, S, L, TL, strat */
  2516. { 18, 12, 12, 1, 7, 16, ZSTD_fast }, /* level 0 - never used */
  2517. { 19, 13, 14, 1, 7, 16, ZSTD_fast }, /* level 1 */
  2518. { 19, 15, 16, 1, 6, 16, ZSTD_fast }, /* level 2 */
  2519. { 20, 16, 17, 1, 5, 16, ZSTD_dfast }, /* level 3 */
  2520. { 20, 17, 18, 1, 5, 16, ZSTD_dfast }, /* level 4 */
  2521. { 20, 17, 18, 2, 5, 16, ZSTD_greedy }, /* level 5 */
  2522. { 21, 17, 19, 2, 5, 16, ZSTD_lazy }, /* level 6 */
  2523. { 21, 18, 19, 3, 5, 16, ZSTD_lazy }, /* level 7 */
  2524. { 21, 18, 20, 3, 5, 16, ZSTD_lazy2 }, /* level 8 */
  2525. { 21, 19, 20, 3, 5, 16, ZSTD_lazy2 }, /* level 9 */
  2526. { 21, 19, 21, 4, 5, 16, ZSTD_lazy2 }, /* level 10 */
  2527. { 22, 20, 22, 4, 5, 16, ZSTD_lazy2 }, /* level 11 */
  2528. { 22, 20, 22, 5, 5, 16, ZSTD_lazy2 }, /* level 12 */
  2529. { 22, 21, 22, 5, 5, 16, ZSTD_lazy2 }, /* level 13 */
  2530. { 22, 21, 22, 6, 5, 16, ZSTD_lazy2 }, /* level 14 */
  2531. { 22, 21, 22, 5, 5, 16, ZSTD_btlazy2 }, /* level 15 */
  2532. { 23, 22, 22, 5, 5, 16, ZSTD_btlazy2 }, /* level 16 */
  2533. { 23, 22, 22, 4, 5, 24, ZSTD_btopt }, /* level 17 */
  2534. { 23, 22, 22, 5, 4, 32, ZSTD_btopt }, /* level 18 */
  2535. { 23, 23, 22, 6, 3, 48, ZSTD_btopt }, /* level 19 */
  2536. { 25, 25, 23, 7, 3, 64, ZSTD_btultra }, /* level 20 */
  2537. { 26, 26, 24, 7, 3,256, ZSTD_btultra }, /* level 21 */
  2538. { 27, 27, 25, 9, 3,512, ZSTD_btultra }, /* level 22 */
  2539. },
  2540. { /* for srcSize <= 256 KB */
  2541. /* W, C, H, S, L, T, strat */
  2542. { 0, 0, 0, 0, 0, 0, ZSTD_fast }, /* level 0 - not used */
  2543. { 18, 13, 14, 1, 6, 8, ZSTD_fast }, /* level 1 */
  2544. { 18, 14, 13, 1, 5, 8, ZSTD_dfast }, /* level 2 */
  2545. { 18, 16, 15, 1, 5, 8, ZSTD_dfast }, /* level 3 */
  2546. { 18, 15, 17, 1, 5, 8, ZSTD_greedy }, /* level 4.*/
  2547. { 18, 16, 17, 4, 5, 8, ZSTD_greedy }, /* level 5.*/
  2548. { 18, 16, 17, 3, 5, 8, ZSTD_lazy }, /* level 6.*/
  2549. { 18, 17, 17, 4, 4, 8, ZSTD_lazy }, /* level 7 */
  2550. { 18, 17, 17, 4, 4, 8, ZSTD_lazy2 }, /* level 8 */
  2551. { 18, 17, 17, 5, 4, 8, ZSTD_lazy2 }, /* level 9 */
  2552. { 18, 17, 17, 6, 4, 8, ZSTD_lazy2 }, /* level 10 */
  2553. { 18, 18, 17, 6, 4, 8, ZSTD_lazy2 }, /* level 11.*/
  2554. { 18, 18, 17, 7, 4, 8, ZSTD_lazy2 }, /* level 12.*/
  2555. { 18, 19, 17, 6, 4, 8, ZSTD_btlazy2 }, /* level 13 */
  2556. { 18, 18, 18, 4, 4, 16, ZSTD_btopt }, /* level 14.*/
  2557. { 18, 18, 18, 4, 3, 16, ZSTD_btopt }, /* level 15.*/
  2558. { 18, 19, 18, 6, 3, 32, ZSTD_btopt }, /* level 16.*/
  2559. { 18, 19, 18, 8, 3, 64, ZSTD_btopt }, /* level 17.*/
  2560. { 18, 19, 18, 9, 3,128, ZSTD_btopt }, /* level 18.*/
  2561. { 18, 19, 18, 10, 3,256, ZSTD_btopt }, /* level 19.*/
  2562. { 18, 19, 18, 11, 3,512, ZSTD_btultra }, /* level 20.*/
  2563. { 18, 19, 18, 12, 3,512, ZSTD_btultra }, /* level 21.*/
  2564. { 18, 19, 18, 13, 3,512, ZSTD_btultra }, /* level 22.*/
  2565. },
  2566. { /* for srcSize <= 128 KB */
  2567. /* W, C, H, S, L, T, strat */
  2568. { 17, 12, 12, 1, 7, 8, ZSTD_fast }, /* level 0 - not used */
  2569. { 17, 12, 13, 1, 6, 8, ZSTD_fast }, /* level 1 */
  2570. { 17, 13, 16, 1, 5, 8, ZSTD_fast }, /* level 2 */
  2571. { 17, 16, 16, 2, 5, 8, ZSTD_dfast }, /* level 3 */
  2572. { 17, 13, 15, 3, 4, 8, ZSTD_greedy }, /* level 4 */
  2573. { 17, 15, 17, 4, 4, 8, ZSTD_greedy }, /* level 5 */
  2574. { 17, 16, 17, 3, 4, 8, ZSTD_lazy }, /* level 6 */
  2575. { 17, 15, 17, 4, 4, 8, ZSTD_lazy2 }, /* level 7 */
  2576. { 17, 17, 17, 4, 4, 8, ZSTD_lazy2 }, /* level 8 */
  2577. { 17, 17, 17, 5, 4, 8, ZSTD_lazy2 }, /* level 9 */
  2578. { 17, 17, 17, 6, 4, 8, ZSTD_lazy2 }, /* level 10 */
  2579. { 17, 17, 17, 7, 4, 8, ZSTD_lazy2 }, /* level 11 */
  2580. { 17, 17, 17, 8, 4, 8, ZSTD_lazy2 }, /* level 12 */
  2581. { 17, 18, 17, 6, 4, 8, ZSTD_btlazy2 }, /* level 13.*/
  2582. { 17, 17, 17, 7, 3, 8, ZSTD_btopt }, /* level 14.*/
  2583. { 17, 17, 17, 7, 3, 16, ZSTD_btopt }, /* level 15.*/
  2584. { 17, 18, 17, 7, 3, 32, ZSTD_btopt }, /* level 16.*/
  2585. { 17, 18, 17, 7, 3, 64, ZSTD_btopt }, /* level 17.*/
  2586. { 17, 18, 17, 7, 3,256, ZSTD_btopt }, /* level 18.*/
  2587. { 17, 18, 17, 8, 3,256, ZSTD_btopt }, /* level 19.*/
  2588. { 17, 18, 17, 9, 3,256, ZSTD_btultra }, /* level 20.*/
  2589. { 17, 18, 17, 10, 3,256, ZSTD_btultra }, /* level 21.*/
  2590. { 17, 18, 17, 11, 3,512, ZSTD_btultra }, /* level 22.*/
  2591. },
  2592. { /* for srcSize <= 16 KB */
  2593. /* W, C, H, S, L, T, strat */
  2594. { 14, 12, 12, 1, 7, 6, ZSTD_fast }, /* level 0 - not used */
  2595. { 14, 14, 14, 1, 6, 6, ZSTD_fast }, /* level 1 */
  2596. { 14, 14, 14, 1, 4, 6, ZSTD_fast }, /* level 2 */
  2597. { 14, 14, 14, 1, 4, 6, ZSTD_dfast }, /* level 3.*/
  2598. { 14, 14, 14, 4, 4, 6, ZSTD_greedy }, /* level 4.*/
  2599. { 14, 14, 14, 3, 4, 6, ZSTD_lazy }, /* level 5.*/
  2600. { 14, 14, 14, 4, 4, 6, ZSTD_lazy2 }, /* level 6 */
  2601. { 14, 14, 14, 5, 4, 6, ZSTD_lazy2 }, /* level 7 */
  2602. { 14, 14, 14, 6, 4, 6, ZSTD_lazy2 }, /* level 8.*/
  2603. { 14, 15, 14, 6, 4, 6, ZSTD_btlazy2 }, /* level 9.*/
  2604. { 14, 15, 14, 3, 3, 6, ZSTD_btopt }, /* level 10.*/
  2605. { 14, 15, 14, 6, 3, 8, ZSTD_btopt }, /* level 11.*/
  2606. { 14, 15, 14, 6, 3, 16, ZSTD_btopt }, /* level 12.*/
  2607. { 14, 15, 14, 6, 3, 24, ZSTD_btopt }, /* level 13.*/
  2608. { 14, 15, 15, 6, 3, 48, ZSTD_btopt }, /* level 14.*/
  2609. { 14, 15, 15, 6, 3, 64, ZSTD_btopt }, /* level 15.*/
  2610. { 14, 15, 15, 6, 3, 96, ZSTD_btopt }, /* level 16.*/
  2611. { 14, 15, 15, 6, 3,128, ZSTD_btopt }, /* level 17.*/
  2612. { 14, 15, 15, 6, 3,256, ZSTD_btopt }, /* level 18.*/
  2613. { 14, 15, 15, 7, 3,256, ZSTD_btopt }, /* level 19.*/
  2614. { 14, 15, 15, 8, 3,256, ZSTD_btultra }, /* level 20.*/
  2615. { 14, 15, 15, 9, 3,256, ZSTD_btultra }, /* level 21.*/
  2616. { 14, 15, 15, 10, 3,256, ZSTD_btultra }, /* level 22.*/
  2617. },
  2618. };
  2619. #if defined(ZSTD_DEBUG) && (ZSTD_DEBUG>=1)
  2620. /* This function just controls
  2621. * the monotonic memory budget increase of ZSTD_defaultCParameters[0].
  2622. * Run once, on first ZSTD_getCParams() usage, if ZSTD_DEBUG is enabled
  2623. */
  2624. MEM_STATIC void ZSTD_check_compressionLevel_monotonicIncrease_memoryBudget(void)
  2625. {
  2626. int level;
  2627. for (level=1; level<ZSTD_maxCLevel(); level++) {
  2628. ZSTD_compressionParameters const c1 = ZSTD_defaultCParameters[0][level];
  2629. ZSTD_compressionParameters const c2 = ZSTD_defaultCParameters[0][level+1];
  2630. assert(c1.windowLog <= c2.windowLog);
  2631. # define ZSTD_TABLECOST(h,c) ((1<<(h)) + (1<<(c)))
  2632. assert(ZSTD_TABLECOST(c1.hashLog, c1.chainLog) <= ZSTD_TABLECOST(c2.hashLog, c2.chainLog));
  2633. }
  2634. }
  2635. #endif
  2636. /*! ZSTD_getCParams() :
  2637. * @return ZSTD_compressionParameters structure for a selected compression level, `srcSize` and `dictSize`.
  2638. * Size values are optional, provide 0 if not known or unused */
  2639. ZSTD_compressionParameters ZSTD_getCParams(int compressionLevel, unsigned long long srcSizeHint, size_t dictSize)
  2640. {
  2641. size_t const addedSize = srcSizeHint ? 0 : 500;
  2642. U64 const rSize = srcSizeHint+dictSize ? srcSizeHint+dictSize+addedSize : (U64)-1;
  2643. U32 const tableID = (rSize <= 256 KB) + (rSize <= 128 KB) + (rSize <= 16 KB); /* intentional underflow for srcSizeHint == 0 */
  2644. #if defined(ZSTD_DEBUG) && (ZSTD_DEBUG>=1)
  2645. static int g_monotonicTest = 1;
  2646. if (g_monotonicTest) {
  2647. ZSTD_check_compressionLevel_monotonicIncrease_memoryBudget();
  2648. g_monotonicTest=0;
  2649. }
  2650. #endif
  2651. if (compressionLevel <= 0) compressionLevel = ZSTD_CLEVEL_DEFAULT; /* 0 == default; no negative compressionLevel yet */
  2652. if (compressionLevel > ZSTD_MAX_CLEVEL) compressionLevel = ZSTD_MAX_CLEVEL;
  2653. { ZSTD_compressionParameters const cp = ZSTD_defaultCParameters[tableID][compressionLevel];
  2654. return ZSTD_adjustCParams_internal(cp, srcSizeHint, dictSize); }
  2655. }
  2656. /*! ZSTD_getParams() :
  2657. * same as ZSTD_getCParams(), but @return a `ZSTD_parameters` object (instead of `ZSTD_compressionParameters`).
  2658. * All fields of `ZSTD_frameParameters` are set to default (0) */
  2659. ZSTD_parameters ZSTD_getParams(int compressionLevel, unsigned long long srcSizeHint, size_t dictSize) {
  2660. ZSTD_parameters params;
  2661. ZSTD_compressionParameters const cParams = ZSTD_getCParams(compressionLevel, srcSizeHint, dictSize);
  2662. memset(&params, 0, sizeof(params));
  2663. params.cParams = cParams;
  2664. return params;
  2665. }