zstd_compress.c 108 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565
  1. /*
  2. ZSTD HC - High Compression Mode of Zstandard
  3. Copyright (C) 2015-2016, Yann Collet.
  4. BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
  5. Redistribution and use in source and binary forms, with or without
  6. modification, are permitted provided that the following conditions are
  7. met:
  8. * Redistributions of source code must retain the above copyright
  9. notice, this list of conditions and the following disclaimer.
  10. * Redistributions in binary form must reproduce the above
  11. copyright notice, this list of conditions and the following disclaimer
  12. in the documentation and/or other materials provided with the
  13. distribution.
  14. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  15. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  16. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  17. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  18. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  19. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  20. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  21. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  22. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  23. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. You can contact the author at :
  26. - Zstd source repository : https://www.zstd.net
  27. */
  28. /* *******************************************************
  29. * Compiler specifics
  30. *********************************************************/
  31. #ifdef _MSC_VER /* Visual Studio */
  32. # define FORCE_INLINE static __forceinline
  33. # include <intrin.h> /* For Visual 2005 */
  34. # pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */
  35. #else
  36. # ifdef __GNUC__
  37. # define FORCE_INLINE static inline __attribute__((always_inline))
  38. # else
  39. # define FORCE_INLINE static inline
  40. # endif
  41. #endif
  42. /*-*************************************
  43. * Dependencies
  44. ***************************************/
  45. #include <stdlib.h> /* malloc */
  46. #include <string.h> /* memset */
  47. #include "mem.h"
  48. #include "fse_static.h"
  49. #include "huf_static.h"
  50. #include "zstd_internal.h"
  51. /*-*************************************
  52. * Constants
  53. ***************************************/
  54. static const U32 g_searchStrength = 8; /* control skip over incompressible data */
  55. /*-*************************************
  56. * Helper functions
  57. ***************************************/
  58. size_t ZSTD_compressBound(size_t srcSize) { return FSE_compressBound(srcSize) + 12; }
  59. /*-*************************************
  60. * Sequence storage
  61. ***************************************/
  62. static void ZSTD_resetSeqStore(seqStore_t* ssPtr)
  63. {
  64. ssPtr->offset = ssPtr->offsetStart;
  65. ssPtr->lit = ssPtr->litStart;
  66. ssPtr->litLength = ssPtr->litLengthStart;
  67. ssPtr->matchLength = ssPtr->matchLengthStart;
  68. ssPtr->longLengthID = 0;
  69. }
  70. /*-*************************************
  71. * Context memory management
  72. ***************************************/
  73. struct ZSTD_CCtx_s
  74. {
  75. const BYTE* nextSrc; /* next block here to continue on current prefix */
  76. const BYTE* base; /* All regular indexes relative to this position */
  77. const BYTE* dictBase; /* extDict indexes relative to this position */
  78. U32 dictLimit; /* below that point, need extDict */
  79. U32 lowLimit; /* below that point, no more data */
  80. U32 nextToUpdate; /* index from which to continue dictionary update */
  81. U32 nextToUpdate3; /* index from which to continue dictionary update */
  82. U32 hashLog3; /* dispatch table : larger == faster, more memory */
  83. U32 loadedDictEnd;
  84. U32 stage; /* 0: created; 1: init,dictLoad; 2:started */
  85. ZSTD_parameters params;
  86. void* workSpace;
  87. size_t workSpaceSize;
  88. size_t blockSize;
  89. seqStore_t seqStore; /* sequences storage ptrs */
  90. U32* hashTable;
  91. U32* hashTable3;
  92. U32* chainTable;
  93. HUF_CElt* hufTable;
  94. U32 flagStaticTables;
  95. FSE_CTable offcodeCTable [FSE_CTABLE_SIZE_U32(OffFSELog, MaxOff)];
  96. FSE_CTable matchlengthCTable [FSE_CTABLE_SIZE_U32(MLFSELog, MaxML)];
  97. FSE_CTable litlengthCTable [FSE_CTABLE_SIZE_U32(LLFSELog, MaxLL)];
  98. };
  99. ZSTD_CCtx* ZSTD_createCCtx(void)
  100. {
  101. return (ZSTD_CCtx*) calloc(1, sizeof(ZSTD_CCtx));
  102. }
  103. size_t ZSTD_freeCCtx(ZSTD_CCtx* cctx)
  104. {
  105. free(cctx->workSpace);
  106. free(cctx);
  107. return 0; /* reserved as a potential error code in the future */
  108. }
  109. const seqStore_t* ZSTD_getSeqStore(const ZSTD_CCtx* ctx) /* hidden interface */
  110. {
  111. return &(ctx->seqStore);
  112. }
  113. #define CLAMP(val,min,max) { if (val<min) val=min; else if (val>max) val=max; }
  114. #define CLAMPCHECK(val,min,max) { if ((val<min) || (val>max)) return ERROR(compressionParameter_unsupported); }
  115. /** ZSTD_checkParams() :
  116. ensure param values remain within authorized range.
  117. @return : 0, or an error code if one value is beyond authorized range */
  118. size_t ZSTD_checkCParams(ZSTD_compressionParameters cParams)
  119. {
  120. CLAMPCHECK(cParams.windowLog, ZSTD_WINDOWLOG_MIN, ZSTD_WINDOWLOG_MAX);
  121. CLAMPCHECK(cParams.chainLog, ZSTD_CHAINLOG_MIN, ZSTD_CHAINLOG_MAX);
  122. CLAMPCHECK(cParams.hashLog, ZSTD_HASHLOG_MIN, ZSTD_HASHLOG_MAX);
  123. CLAMPCHECK(cParams.searchLog, ZSTD_SEARCHLOG_MIN, ZSTD_SEARCHLOG_MAX);
  124. { U32 const searchLengthMin = (cParams.strategy == ZSTD_fast || cParams.strategy == ZSTD_greedy) ? ZSTD_SEARCHLENGTH_MIN+1 : ZSTD_SEARCHLENGTH_MIN;
  125. U32 const searchLengthMax = (cParams.strategy == ZSTD_fast) ? ZSTD_SEARCHLENGTH_MAX : ZSTD_SEARCHLENGTH_MAX-1;
  126. CLAMPCHECK(cParams.searchLength, searchLengthMin, searchLengthMax); }
  127. CLAMPCHECK(cParams.targetLength, ZSTD_TARGETLENGTH_MIN, ZSTD_TARGETLENGTH_MAX);
  128. if ((U32)(cParams.strategy) > (U32)ZSTD_btopt) return ERROR(compressionParameter_unsupported);
  129. return 0;
  130. }
  131. static unsigned ZSTD_highbit(U32 val);
  132. /** ZSTD_checkCParams_advanced() :
  133. temporary work-around, while the compressor compatibility remains limited regarding windowLog < 18 */
  134. size_t ZSTD_checkCParams_advanced(ZSTD_compressionParameters cParams, U64 srcSize)
  135. {
  136. if (srcSize > (1ULL << ZSTD_WINDOWLOG_MIN)) return ZSTD_checkCParams(cParams);
  137. if (cParams.windowLog < ZSTD_WINDOWLOG_ABSOLUTEMIN) return ERROR(compressionParameter_unsupported);
  138. if (srcSize <= (1ULL << cParams.windowLog)) cParams.windowLog = ZSTD_WINDOWLOG_MIN; /* fake value - temporary work around */
  139. if (srcSize <= (1ULL << cParams.chainLog)) cParams.chainLog = ZSTD_CHAINLOG_MIN; /* fake value - temporary work around */
  140. if ((srcSize <= (1ULL << cParams.hashLog)) && ((U32)cParams.strategy < (U32)ZSTD_btlazy2)) cParams.hashLog = ZSTD_HASHLOG_MIN; /* fake value - temporary work around */
  141. return ZSTD_checkCParams(cParams);
  142. }
  143. /** ZSTD_adjustParams() :
  144. optimize params for q given input (`srcSize` and `dictSize`).
  145. mostly downsizing to reduce memory consumption and initialization.
  146. Both `srcSize` and `dictSize` are optional (use 0 if unknown),
  147. but if both are 0, no optimization can be done.
  148. Note : params is considered validated at this stage. Use ZSTD_checkParams() to ensure that. */
  149. void ZSTD_adjustCParams(ZSTD_compressionParameters* params, U64 srcSize, size_t dictSize)
  150. {
  151. if (srcSize+dictSize == 0) return; /* no size information available : no adjustment */
  152. /* resize params, to use less memory when necessary */
  153. { U32 const minSrcSize = (srcSize==0) ? 500 : 0;
  154. U64 const rSize = srcSize + dictSize + minSrcSize;
  155. if (rSize < ((U64)1<<ZSTD_WINDOWLOG_MAX)) {
  156. U32 const srcLog = ZSTD_highbit((U32)(rSize)-1) + 1;
  157. if (params->windowLog > srcLog) params->windowLog = srcLog;
  158. } }
  159. if (params->hashLog > params->windowLog) params->hashLog = params->windowLog;
  160. { U32 const btPlus = (params->strategy == ZSTD_btlazy2) || (params->strategy == ZSTD_btopt);
  161. U32 const maxChainLog = params->windowLog+btPlus;
  162. if (params->chainLog > maxChainLog) params->chainLog = maxChainLog; } /* <= ZSTD_CHAINLOG_MAX */
  163. if (params->windowLog < ZSTD_WINDOWLOG_ABSOLUTEMIN) params->windowLog = ZSTD_WINDOWLOG_ABSOLUTEMIN; /* required for frame header */
  164. if ((params->hashLog < ZSTD_HASHLOG_MIN) && ((U32)params->strategy >= (U32)ZSTD_btlazy2)) params->hashLog = ZSTD_HASHLOG_MIN; /* required to ensure collision resistance in bt */
  165. }
  166. size_t ZSTD_sizeofCCtx(ZSTD_compressionParameters cParams) /* hidden interface, for paramagrill */
  167. {
  168. ZSTD_CCtx* zc = ZSTD_createCCtx();
  169. ZSTD_parameters params;
  170. params.cParams = cParams;
  171. params.fParams.contentSizeFlag = 1;
  172. ZSTD_compressBegin_advanced(zc, NULL, 0, params, 0);
  173. { size_t const ccsize = sizeof(*zc) + zc->workSpaceSize;
  174. ZSTD_freeCCtx(zc);
  175. return ccsize; }
  176. }
  177. /*! ZSTD_resetCCtx_advanced() :
  178. note : 'params' is expected to be validated */
  179. static size_t ZSTD_resetCCtx_advanced (ZSTD_CCtx* zc,
  180. ZSTD_parameters params, U32 reset)
  181. { /* note : params considered validated here */
  182. const size_t blockSize = MIN(ZSTD_BLOCKSIZE_MAX, (size_t)1 << params.cParams.windowLog);
  183. const U32 divider = (params.cParams.searchLength==3) ? 3 : 4;
  184. const size_t maxNbSeq = blockSize / divider;
  185. const size_t tokenSpace = blockSize + 11*maxNbSeq;
  186. const size_t chainSize = (params.cParams.strategy == ZSTD_fast) ? 0 : (1 << params.cParams.chainLog);
  187. const size_t hSize = ((size_t)1) << params.cParams.hashLog;
  188. const size_t h3Size = (zc->hashLog3) ? 1 << zc->hashLog3 : 0;
  189. const size_t tableSpace = (chainSize + hSize + h3Size) * sizeof(U32);
  190. /* Check if workSpace is large enough, alloc a new one if needed */
  191. { size_t const optSpace = ((MaxML+1) + (MaxLL+1) + (MaxOff+1) + (1<<Litbits))*sizeof(U32)
  192. + (ZSTD_OPT_NUM+1)*(sizeof(ZSTD_match_t) + sizeof(ZSTD_optimal_t));
  193. size_t const neededSpace = tableSpace + (256*sizeof(U32)) /* huffTable */ + tokenSpace
  194. + ((params.cParams.strategy == ZSTD_btopt) ? optSpace : 0);
  195. if (zc->workSpaceSize < neededSpace) {
  196. free(zc->workSpace);
  197. zc->workSpace = malloc(neededSpace);
  198. if (zc->workSpace == NULL) return ERROR(memory_allocation);
  199. zc->workSpaceSize = neededSpace;
  200. } }
  201. if (reset) memset(zc->workSpace, 0, tableSpace ); /* reset only tables */
  202. zc->hashTable3 = (U32*)(zc->workSpace);
  203. zc->hashTable = zc->hashTable3 + h3Size;
  204. zc->chainTable = zc->hashTable + hSize;
  205. zc->seqStore.buffer = zc->chainTable + chainSize;
  206. zc->hufTable = (HUF_CElt*)zc->seqStore.buffer;
  207. zc->flagStaticTables = 0;
  208. zc->seqStore.buffer = ((U32*)(zc->seqStore.buffer)) + 256;
  209. zc->nextToUpdate = 1;
  210. zc->nextSrc = NULL;
  211. zc->base = NULL;
  212. zc->dictBase = NULL;
  213. zc->dictLimit = 0;
  214. zc->lowLimit = 0;
  215. zc->params = params;
  216. zc->blockSize = blockSize;
  217. if (params.cParams.strategy == ZSTD_btopt) {
  218. zc->seqStore.litFreq = (U32*)(zc->seqStore.buffer);
  219. zc->seqStore.litLengthFreq = zc->seqStore.litFreq + (1<<Litbits);
  220. zc->seqStore.matchLengthFreq = zc->seqStore.litLengthFreq + (MaxLL+1);
  221. zc->seqStore.offCodeFreq = zc->seqStore.matchLengthFreq + (MaxML+1);
  222. zc->seqStore.matchTable = (ZSTD_match_t*)((void*)(zc->seqStore.offCodeFreq + (MaxOff+1)));
  223. zc->seqStore.priceTable = (ZSTD_optimal_t*)((void*)(zc->seqStore.matchTable + ZSTD_OPT_NUM+1));
  224. zc->seqStore.buffer = zc->seqStore.priceTable + ZSTD_OPT_NUM+1;
  225. zc->seqStore.litLengthSum = 0;
  226. }
  227. zc->seqStore.offsetStart = (U32*) (zc->seqStore.buffer);
  228. zc->seqStore.litLengthStart = (U16*) (void*)(zc->seqStore.offsetStart + maxNbSeq);
  229. zc->seqStore.matchLengthStart = (U16*) (void*)(zc->seqStore.litLengthStart + maxNbSeq);
  230. zc->seqStore.llCodeStart = (BYTE*) (zc->seqStore.matchLengthStart + maxNbSeq);
  231. zc->seqStore.mlCodeStart = zc->seqStore.llCodeStart + maxNbSeq;
  232. zc->seqStore.offCodeStart = zc->seqStore.mlCodeStart + maxNbSeq;
  233. zc->seqStore.litStart = zc->seqStore.offCodeStart + maxNbSeq;
  234. zc->stage = 1;
  235. zc->loadedDictEnd = 0;
  236. return 0;
  237. }
  238. /*! ZSTD_copyCCtx() :
  239. * Duplicate an existing context `srcCCtx` into another one `dstCCtx`.
  240. * Only works during stage 1 (i.e. after creation, but before first call to ZSTD_compressContinue()).
  241. * @return : 0, or an error code */
  242. size_t ZSTD_copyCCtx(ZSTD_CCtx* dstCCtx, const ZSTD_CCtx* srcCCtx)
  243. {
  244. if (srcCCtx->stage!=1) return ERROR(stage_wrong);
  245. dstCCtx->hashLog3 = srcCCtx->hashLog3; /* must be before ZSTD_resetCCtx_advanced */
  246. ZSTD_resetCCtx_advanced(dstCCtx, srcCCtx->params, 0);
  247. dstCCtx->params.fParams.contentSizeFlag = 0; /* content size different from the one set during srcCCtx init */
  248. /* copy tables */
  249. { const size_t chainSize = (srcCCtx->params.cParams.strategy == ZSTD_fast) ? 0 : (1 << srcCCtx->params.cParams.chainLog);
  250. const size_t hSize = ((size_t)1) << srcCCtx->params.cParams.hashLog;
  251. const size_t h3Size = (srcCCtx->hashLog3) ? 1 << srcCCtx->hashLog3 : 0;
  252. const size_t tableSpace = (chainSize + hSize + h3Size) * sizeof(U32);
  253. memcpy(dstCCtx->workSpace, srcCCtx->workSpace, tableSpace);
  254. }
  255. /* copy dictionary pointers */
  256. dstCCtx->nextToUpdate = srcCCtx->nextToUpdate;
  257. dstCCtx->nextToUpdate3= srcCCtx->nextToUpdate3;
  258. dstCCtx->nextSrc = srcCCtx->nextSrc;
  259. dstCCtx->base = srcCCtx->base;
  260. dstCCtx->dictBase = srcCCtx->dictBase;
  261. dstCCtx->dictLimit = srcCCtx->dictLimit;
  262. dstCCtx->lowLimit = srcCCtx->lowLimit;
  263. dstCCtx->loadedDictEnd= srcCCtx->loadedDictEnd;
  264. /* copy entropy tables */
  265. dstCCtx->flagStaticTables = srcCCtx->flagStaticTables;
  266. if (srcCCtx->flagStaticTables) {
  267. memcpy(dstCCtx->hufTable, srcCCtx->hufTable, 256*4);
  268. memcpy(dstCCtx->litlengthCTable, srcCCtx->litlengthCTable, sizeof(dstCCtx->litlengthCTable));
  269. memcpy(dstCCtx->matchlengthCTable, srcCCtx->matchlengthCTable, sizeof(dstCCtx->matchlengthCTable));
  270. memcpy(dstCCtx->offcodeCTable, srcCCtx->offcodeCTable, sizeof(dstCCtx->offcodeCTable));
  271. }
  272. return 0;
  273. }
  274. /*! ZSTD_reduceTable() :
  275. * reduce table indexes by `reducerValue` */
  276. static void ZSTD_reduceTable (U32* const table, U32 const size, U32 const reducerValue)
  277. {
  278. U32 u;
  279. for (u=0 ; u < size ; u++) {
  280. if (table[u] < reducerValue) table[u] = 0;
  281. else table[u] -= reducerValue;
  282. }
  283. }
  284. /*! ZSTD_reduceIndex() :
  285. * rescale all indexes to avoid future overflow (indexes are U32) */
  286. static void ZSTD_reduceIndex (ZSTD_CCtx* zc, const U32 reducerValue)
  287. {
  288. { const U32 hSize = 1 << zc->params.cParams.hashLog;
  289. ZSTD_reduceTable(zc->hashTable, hSize, reducerValue); }
  290. { const U32 chainSize = (zc->params.cParams.strategy == ZSTD_fast) ? 0 : (1 << zc->params.cParams.chainLog);
  291. ZSTD_reduceTable(zc->chainTable, chainSize, reducerValue); }
  292. { const U32 h3Size = (zc->hashLog3) ? 1 << zc->hashLog3 : 0;
  293. ZSTD_reduceTable(zc->hashTable3, h3Size, reducerValue); }
  294. }
  295. /*-*******************************************************
  296. * Block entropic compression
  297. *********************************************************/
  298. /* Frame format description
  299. Frame Header - [ Block Header - Block ] - Frame End
  300. 1) Frame Header
  301. - 4 bytes - Magic Number : ZSTD_MAGICNUMBER (defined within zstd_static.h)
  302. - 1 byte - Frame Descriptor
  303. 2) Block Header
  304. - 3 bytes, starting with a 2-bits descriptor
  305. Uncompressed, Compressed, Frame End, unused
  306. 3) Block
  307. See Block Format Description
  308. 4) Frame End
  309. - 3 bytes, compatible with Block Header
  310. */
  311. /* Frame descriptor
  312. 1 byte, using :
  313. bit 0-3 : windowLog - ZSTD_WINDOWLOG_ABSOLUTEMIN (see zstd_internal.h)
  314. bit 4 : minmatch 4(0) or 3(1)
  315. bit 5 : reserved (must be zero)
  316. bit 6-7 : Frame content size : unknown, 1 byte, 2 bytes, 8 bytes
  317. Optional : content size (0, 1, 2 or 8 bytes)
  318. 0 : unknown
  319. 1 : 0-255 bytes
  320. 2 : 256 - 65535+256
  321. 8 : up to 16 exa
  322. */
  323. /* Block format description
  324. Block = Literal Section - Sequences Section
  325. Prerequisite : size of (compressed) block, maximum size of regenerated data
  326. 1) Literal Section
  327. 1.1) Header : 1-5 bytes
  328. flags: 2 bits
  329. 00 compressed by Huff0
  330. 01 unused
  331. 10 is Raw (uncompressed)
  332. 11 is Rle
  333. Note : using 01 => Huff0 with precomputed table ?
  334. Note : delta map ? => compressed ?
  335. 1.1.1) Huff0-compressed literal block : 3-5 bytes
  336. srcSize < 1 KB => 3 bytes (2-2-10-10) => single stream
  337. srcSize < 1 KB => 3 bytes (2-2-10-10)
  338. srcSize < 16KB => 4 bytes (2-2-14-14)
  339. else => 5 bytes (2-2-18-18)
  340. big endian convention
  341. 1.1.2) Raw (uncompressed) literal block header : 1-3 bytes
  342. size : 5 bits: (IS_RAW<<6) + (0<<4) + size
  343. 12 bits: (IS_RAW<<6) + (2<<4) + (size>>8)
  344. size&255
  345. 20 bits: (IS_RAW<<6) + (3<<4) + (size>>16)
  346. size>>8&255
  347. size&255
  348. 1.1.3) Rle (repeated single byte) literal block header : 1-3 bytes
  349. size : 5 bits: (IS_RLE<<6) + (0<<4) + size
  350. 12 bits: (IS_RLE<<6) + (2<<4) + (size>>8)
  351. size&255
  352. 20 bits: (IS_RLE<<6) + (3<<4) + (size>>16)
  353. size>>8&255
  354. size&255
  355. 1.1.4) Huff0-compressed literal block, using precomputed CTables : 3-5 bytes
  356. srcSize < 1 KB => 3 bytes (2-2-10-10) => single stream
  357. srcSize < 1 KB => 3 bytes (2-2-10-10)
  358. srcSize < 16KB => 4 bytes (2-2-14-14)
  359. else => 5 bytes (2-2-18-18)
  360. big endian convention
  361. 1- CTable available (stored into workspace ?)
  362. 2- Small input (fast heuristic ? Full comparison ? depend on clevel ?)
  363. 1.2) Literal block content
  364. 1.2.1) Huff0 block, using sizes from header
  365. See Huff0 format
  366. 1.2.2) Huff0 block, using prepared table
  367. 1.2.3) Raw content
  368. 1.2.4) single byte
  369. 2) Sequences section
  370. - Nb Sequences : 2 bytes, little endian
  371. - Control Token : 1 byte (see below)
  372. - Dumps Length : 1 or 2 bytes (depending on control token)
  373. - Dumps : as stated by dumps length
  374. - Literal Lengths FSE table (as needed depending on encoding method)
  375. - Offset Codes FSE table (as needed depending on encoding method)
  376. - Match Lengths FSE table (as needed depending on encoding method)
  377. 2.1) Control Token
  378. 8 bits, divided as :
  379. 0-1 : dumpsLength
  380. 2-3 : MatchLength, FSE encoding method
  381. 4-5 : Offset Codes, FSE encoding method
  382. 6-7 : Literal Lengths, FSE encoding method
  383. FSE encoding method :
  384. FSE_ENCODING_RAW : uncompressed; no header
  385. FSE_ENCODING_RLE : single repeated value; header 1 byte
  386. FSE_ENCODING_STATIC : use prepared table; no header
  387. FSE_ENCODING_DYNAMIC : read NCount
  388. */
  389. size_t ZSTD_noCompressBlock (void* dst, size_t dstCapacity, const void* src, size_t srcSize)
  390. {
  391. BYTE* const ostart = (BYTE* const)dst;
  392. if (srcSize + ZSTD_blockHeaderSize > dstCapacity) return ERROR(dstSize_tooSmall);
  393. memcpy(ostart + ZSTD_blockHeaderSize, src, srcSize);
  394. /* Build header */
  395. ostart[0] = (BYTE)(srcSize>>16);
  396. ostart[1] = (BYTE)(srcSize>>8);
  397. ostart[2] = (BYTE) srcSize;
  398. ostart[0] += (BYTE)(bt_raw<<6); /* is a raw (uncompressed) block */
  399. return ZSTD_blockHeaderSize+srcSize;
  400. }
  401. static size_t ZSTD_noCompressLiterals (void* dst, size_t dstCapacity, const void* src, size_t srcSize)
  402. {
  403. BYTE* const ostart = (BYTE* const)dst;
  404. U32 const flSize = 1 + (srcSize>31) + (srcSize>4095);
  405. if (srcSize + flSize > dstCapacity) return ERROR(dstSize_tooSmall);
  406. switch(flSize)
  407. {
  408. case 1: /* 2 - 1 - 5 */
  409. ostart[0] = (BYTE)((IS_RAW<<6) + (0<<5) + srcSize);
  410. break;
  411. case 2: /* 2 - 2 - 12 */
  412. ostart[0] = (BYTE)((IS_RAW<<6) + (2<<4) + (srcSize >> 8));
  413. ostart[1] = (BYTE)srcSize;
  414. break;
  415. default: /*note : should not be necessary : flSize is within {1,2,3} */
  416. case 3: /* 2 - 2 - 20 */
  417. ostart[0] = (BYTE)((IS_RAW<<6) + (3<<4) + (srcSize >> 16));
  418. ostart[1] = (BYTE)(srcSize>>8);
  419. ostart[2] = (BYTE)srcSize;
  420. break;
  421. }
  422. memcpy(ostart + flSize, src, srcSize);
  423. return srcSize + flSize;
  424. }
  425. static size_t ZSTD_compressRleLiteralsBlock (void* dst, size_t dstCapacity, const void* src, size_t srcSize)
  426. {
  427. BYTE* const ostart = (BYTE* const)dst;
  428. U32 const flSize = 1 + (srcSize>31) + (srcSize>4095);
  429. (void)dstCapacity; /* dstCapacity guaranteed to be >=4, hence large enough */
  430. switch(flSize)
  431. {
  432. case 1: /* 2 - 1 - 5 */
  433. ostart[0] = (BYTE)((IS_RLE<<6) + (0<<5) + srcSize);
  434. break;
  435. case 2: /* 2 - 2 - 12 */
  436. ostart[0] = (BYTE)((IS_RLE<<6) + (2<<4) + (srcSize >> 8));
  437. ostart[1] = (BYTE)srcSize;
  438. break;
  439. default: /*note : should not be necessary : flSize is necessarily within {1,2,3} */
  440. case 3: /* 2 - 2 - 20 */
  441. ostart[0] = (BYTE)((IS_RLE<<6) + (3<<4) + (srcSize >> 16));
  442. ostart[1] = (BYTE)(srcSize>>8);
  443. ostart[2] = (BYTE)srcSize;
  444. break;
  445. }
  446. ostart[flSize] = *(const BYTE*)src;
  447. return flSize+1;
  448. }
  449. static size_t ZSTD_minGain(size_t srcSize) { return (srcSize >> 6) + 2; }
  450. static size_t ZSTD_compressLiterals (ZSTD_CCtx* zc,
  451. void* dst, size_t dstCapacity,
  452. const void* src, size_t srcSize)
  453. {
  454. size_t const minGain = ZSTD_minGain(srcSize);
  455. size_t const lhSize = 3 + (srcSize >= 1 KB) + (srcSize >= 16 KB);
  456. BYTE* const ostart = (BYTE*)dst;
  457. U32 singleStream = srcSize < 256;
  458. U32 hType = IS_HUF;
  459. size_t cLitSize;
  460. /* small ? don't even attempt compression (speed opt) */
  461. # define LITERAL_NOENTROPY 63
  462. { size_t const minLitSize = zc->flagStaticTables ? 6 : LITERAL_NOENTROPY;
  463. if (srcSize <= minLitSize) return ZSTD_noCompressLiterals(dst, dstCapacity, src, srcSize);
  464. }
  465. if (dstCapacity < lhSize+1) return ERROR(dstSize_tooSmall); /* not enough space for compression */
  466. if (zc->flagStaticTables && (lhSize==3)) {
  467. hType = IS_PCH;
  468. singleStream = 1;
  469. cLitSize = HUF_compress1X_usingCTable(ostart+lhSize, dstCapacity-lhSize, src, srcSize, zc->hufTable);
  470. } else {
  471. cLitSize = singleStream ? HUF_compress1X(ostart+lhSize, dstCapacity-lhSize, src, srcSize, 255, 12)
  472. : HUF_compress2 (ostart+lhSize, dstCapacity-lhSize, src, srcSize, 255, 12);
  473. }
  474. if ((cLitSize==0) || (cLitSize >= srcSize - minGain))
  475. return ZSTD_noCompressLiterals(dst, dstCapacity, src, srcSize);
  476. if (cLitSize==1)
  477. return ZSTD_compressRleLiteralsBlock(dst, dstCapacity, src, srcSize);
  478. /* Build header */
  479. switch(lhSize)
  480. {
  481. case 3: /* 2 - 2 - 10 - 10 */
  482. ostart[0] = (BYTE)((srcSize>>6) + (singleStream << 4) + (hType<<6));
  483. ostart[1] = (BYTE)((srcSize<<2) + (cLitSize>>8));
  484. ostart[2] = (BYTE)(cLitSize);
  485. break;
  486. case 4: /* 2 - 2 - 14 - 14 */
  487. ostart[0] = (BYTE)((srcSize>>10) + (2<<4) + (hType<<6));
  488. ostart[1] = (BYTE)(srcSize>> 2);
  489. ostart[2] = (BYTE)((srcSize<<6) + (cLitSize>>8));
  490. ostart[3] = (BYTE)(cLitSize);
  491. break;
  492. default: /* should not be necessary, lhSize is only {3,4,5} */
  493. case 5: /* 2 - 2 - 18 - 18 */
  494. ostart[0] = (BYTE)((srcSize>>14) + (3<<4) + (hType<<6));
  495. ostart[1] = (BYTE)(srcSize>>6);
  496. ostart[2] = (BYTE)((srcSize<<2) + (cLitSize>>16));
  497. ostart[3] = (BYTE)(cLitSize>>8);
  498. ostart[4] = (BYTE)(cLitSize);
  499. break;
  500. }
  501. return lhSize+cLitSize;
  502. }
  503. void ZSTD_seqToCodes(const seqStore_t* seqStorePtr, size_t const nbSeq)
  504. {
  505. /* LL codes */
  506. { static const BYTE LL_Code[64] = { 0, 1, 2, 3, 4, 5, 6, 7,
  507. 8, 9, 10, 11, 12, 13, 14, 15,
  508. 16, 16, 17, 17, 18, 18, 19, 19,
  509. 20, 20, 20, 20, 21, 21, 21, 21,
  510. 22, 22, 22, 22, 22, 22, 22, 22,
  511. 23, 23, 23, 23, 23, 23, 23, 23,
  512. 24, 24, 24, 24, 24, 24, 24, 24,
  513. 24, 24, 24, 24, 24, 24, 24, 24 };
  514. const BYTE LL_deltaCode = 19;
  515. const U16* const llTable = seqStorePtr->litLengthStart;
  516. BYTE* const llCodeTable = seqStorePtr->llCodeStart;
  517. size_t u;
  518. for (u=0; u<nbSeq; u++) {
  519. U32 const ll = llTable[u];
  520. llCodeTable[u] = (ll>63) ? (BYTE)ZSTD_highbit(ll) + LL_deltaCode : LL_Code[ll];
  521. }
  522. if (seqStorePtr->longLengthID==1)
  523. llCodeTable[seqStorePtr->longLengthPos] = MaxLL;
  524. }
  525. /* Offset codes */
  526. { const U32* const offsetTable = seqStorePtr->offsetStart;
  527. BYTE* const ofCodeTable = seqStorePtr->offCodeStart;
  528. size_t u;
  529. for (u=0; u<nbSeq; u++) ofCodeTable[u] = (BYTE)ZSTD_highbit(offsetTable[u]);
  530. }
  531. /* ML codes */
  532. { static const BYTE ML_Code[128] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
  533. 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
  534. 32, 32, 33, 33, 34, 34, 35, 35, 36, 36, 36, 36, 37, 37, 37, 37,
  535. 38, 38, 38, 38, 38, 38, 38, 38, 39, 39, 39, 39, 39, 39, 39, 39,
  536. 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40,
  537. 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41,
  538. 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42,
  539. 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42 };
  540. const BYTE ML_deltaCode = 36;
  541. const U16* const mlTable = seqStorePtr->matchLengthStart;
  542. BYTE* const mlCodeTable = seqStorePtr->mlCodeStart;
  543. size_t u;
  544. for (u=0; u<nbSeq; u++) {
  545. U32 const ml = mlTable[u];
  546. mlCodeTable[u] = (ml>127) ? (BYTE)ZSTD_highbit(ml) + ML_deltaCode : ML_Code[ml];
  547. }
  548. if (seqStorePtr->longLengthID==2)
  549. mlCodeTable[seqStorePtr->longLengthPos] = MaxML;
  550. }
  551. }
  552. size_t ZSTD_compressSequences(ZSTD_CCtx* zc,
  553. void* dst, size_t dstCapacity,
  554. size_t srcSize)
  555. {
  556. const seqStore_t* seqStorePtr = &(zc->seqStore);
  557. U32 count[MaxSeq+1];
  558. S16 norm[MaxSeq+1];
  559. FSE_CTable* CTable_LitLength = zc->litlengthCTable;
  560. FSE_CTable* CTable_OffsetBits = zc->offcodeCTable;
  561. FSE_CTable* CTable_MatchLength = zc->matchlengthCTable;
  562. U32 LLtype, Offtype, MLtype; /* compressed, raw or rle */
  563. U16* const llTable = seqStorePtr->litLengthStart;
  564. U16* const mlTable = seqStorePtr->matchLengthStart;
  565. const U32* const offsetTable = seqStorePtr->offsetStart;
  566. const U32* const offsetTableEnd = seqStorePtr->offset;
  567. BYTE* const ofCodeTable = seqStorePtr->offCodeStart;
  568. BYTE* const llCodeTable = seqStorePtr->llCodeStart;
  569. BYTE* const mlCodeTable = seqStorePtr->mlCodeStart;
  570. BYTE* const ostart = (BYTE*)dst;
  571. BYTE* const oend = ostart + dstCapacity;
  572. BYTE* op = ostart;
  573. size_t const nbSeq = offsetTableEnd - offsetTable;
  574. BYTE* seqHead;
  575. /* Compress literals */
  576. { const BYTE* const literals = seqStorePtr->litStart;
  577. size_t const litSize = seqStorePtr->lit - literals;
  578. size_t const cSize = ZSTD_compressLiterals(zc, op, dstCapacity, literals, litSize);
  579. if (ZSTD_isError(cSize)) return cSize;
  580. op += cSize;
  581. }
  582. /* Sequences Header */
  583. if ((oend-op) < 3 /*max nbSeq Size*/ + 1 /*seqHead */) return ERROR(dstSize_tooSmall);
  584. if (nbSeq < 0x7F) *op++ = (BYTE)nbSeq;
  585. else if (nbSeq < LONGNBSEQ) op[0] = (BYTE)((nbSeq>>8) + 0x80), op[1] = (BYTE)nbSeq, op+=2;
  586. else op[0]=0xFF, MEM_writeLE16(op+1, (U16)(nbSeq - LONGNBSEQ)), op+=3;
  587. if (nbSeq==0) goto _check_compressibility;
  588. /* seqHead : flags for FSE encoding type */
  589. seqHead = op++;
  590. #define MIN_SEQ_FOR_DYNAMIC_FSE 64
  591. #define MAX_SEQ_FOR_STATIC_FSE 1000
  592. /* convert length/distances into codes */
  593. ZSTD_seqToCodes(seqStorePtr, nbSeq);
  594. /* CTable for Literal Lengths */
  595. { U32 max = MaxLL;
  596. size_t const mostFrequent = FSE_countFast(count, &max, llCodeTable, nbSeq);
  597. if ((mostFrequent == nbSeq) && (nbSeq > 2)) {
  598. *op++ = llCodeTable[0];
  599. FSE_buildCTable_rle(CTable_LitLength, (BYTE)max);
  600. LLtype = FSE_ENCODING_RLE;
  601. } else if ((zc->flagStaticTables) && (nbSeq < MAX_SEQ_FOR_STATIC_FSE)) {
  602. LLtype = FSE_ENCODING_STATIC;
  603. } else if ((nbSeq < MIN_SEQ_FOR_DYNAMIC_FSE) || (mostFrequent < (nbSeq >> (LL_defaultNormLog-1)))) {
  604. FSE_buildCTable(CTable_LitLength, LL_defaultNorm, MaxLL, LL_defaultNormLog);
  605. LLtype = FSE_ENCODING_RAW;
  606. } else {
  607. size_t nbSeq_1 = nbSeq;
  608. const U32 tableLog = FSE_optimalTableLog(LLFSELog, nbSeq, max);
  609. if (count[llCodeTable[nbSeq-1]]>1) { count[llCodeTable[nbSeq-1]]--; nbSeq_1--; }
  610. FSE_normalizeCount(norm, tableLog, count, nbSeq_1, max);
  611. { size_t const NCountSize = FSE_writeNCount(op, oend-op, norm, max, tableLog); /* overflow protected */
  612. if (FSE_isError(NCountSize)) return ERROR(GENERIC);
  613. op += NCountSize; }
  614. FSE_buildCTable(CTable_LitLength, norm, max, tableLog);
  615. LLtype = FSE_ENCODING_DYNAMIC;
  616. } }
  617. /* CTable for Offsets */
  618. { U32 max = MaxOff;
  619. size_t const mostFrequent = FSE_countFast(count, &max, ofCodeTable, nbSeq);
  620. if ((mostFrequent == nbSeq) && (nbSeq > 2)) {
  621. *op++ = ofCodeTable[0];
  622. FSE_buildCTable_rle(CTable_OffsetBits, (BYTE)max);
  623. Offtype = FSE_ENCODING_RLE;
  624. } else if ((zc->flagStaticTables) && (nbSeq < MAX_SEQ_FOR_STATIC_FSE)) {
  625. Offtype = FSE_ENCODING_STATIC;
  626. } else if ((nbSeq < MIN_SEQ_FOR_DYNAMIC_FSE) || (mostFrequent < (nbSeq >> (OF_defaultNormLog-1)))) {
  627. FSE_buildCTable(CTable_OffsetBits, OF_defaultNorm, MaxOff, OF_defaultNormLog);
  628. Offtype = FSE_ENCODING_RAW;
  629. } else {
  630. size_t nbSeq_1 = nbSeq;
  631. const U32 tableLog = FSE_optimalTableLog(OffFSELog, nbSeq, max);
  632. if (count[ofCodeTable[nbSeq-1]]>1) { count[ofCodeTable[nbSeq-1]]--; nbSeq_1--; }
  633. FSE_normalizeCount(norm, tableLog, count, nbSeq_1, max);
  634. { size_t const NCountSize = FSE_writeNCount(op, oend-op, norm, max, tableLog); /* overflow protected */
  635. if (FSE_isError(NCountSize)) return ERROR(GENERIC);
  636. op += NCountSize; }
  637. FSE_buildCTable(CTable_OffsetBits, norm, max, tableLog);
  638. Offtype = FSE_ENCODING_DYNAMIC;
  639. } }
  640. /* CTable for MatchLengths */
  641. { U32 max = MaxML;
  642. size_t const mostFrequent = FSE_countFast(count, &max, mlCodeTable, nbSeq);
  643. if ((mostFrequent == nbSeq) && (nbSeq > 2)) {
  644. *op++ = *mlCodeTable;
  645. FSE_buildCTable_rle(CTable_MatchLength, (BYTE)max);
  646. MLtype = FSE_ENCODING_RLE;
  647. } else if ((zc->flagStaticTables) && (nbSeq < MAX_SEQ_FOR_STATIC_FSE)) {
  648. MLtype = FSE_ENCODING_STATIC;
  649. } else if ((nbSeq < MIN_SEQ_FOR_DYNAMIC_FSE) || (mostFrequent < (nbSeq >> (ML_defaultNormLog-1)))) {
  650. FSE_buildCTable(CTable_MatchLength, ML_defaultNorm, MaxML, ML_defaultNormLog);
  651. MLtype = FSE_ENCODING_RAW;
  652. } else {
  653. size_t nbSeq_1 = nbSeq;
  654. const U32 tableLog = FSE_optimalTableLog(MLFSELog, nbSeq, max);
  655. if (count[mlCodeTable[nbSeq-1]]>1) { count[mlCodeTable[nbSeq-1]]--; nbSeq_1--; }
  656. FSE_normalizeCount(norm, tableLog, count, nbSeq_1, max);
  657. { size_t const NCountSize = FSE_writeNCount(op, oend-op, norm, max, tableLog); /* overflow protected */
  658. if (FSE_isError(NCountSize)) return ERROR(GENERIC);
  659. op += NCountSize; }
  660. FSE_buildCTable(CTable_MatchLength, norm, max, tableLog);
  661. MLtype = FSE_ENCODING_DYNAMIC;
  662. } }
  663. *seqHead = (BYTE)((LLtype<<6) + (Offtype<<4) + (MLtype<<2));
  664. zc->flagStaticTables = 0;
  665. /* Encoding Sequences */
  666. { BIT_CStream_t blockStream;
  667. FSE_CState_t stateMatchLength;
  668. FSE_CState_t stateOffsetBits;
  669. FSE_CState_t stateLitLength;
  670. { size_t const errorCode = BIT_initCStream(&blockStream, op, oend-op);
  671. if (ERR_isError(errorCode)) return ERROR(dstSize_tooSmall); } /* not enough space remaining */
  672. /* first symbols */
  673. FSE_initCState2(&stateMatchLength, CTable_MatchLength, mlCodeTable[nbSeq-1]);
  674. FSE_initCState2(&stateOffsetBits, CTable_OffsetBits, ofCodeTable[nbSeq-1]);
  675. FSE_initCState2(&stateLitLength, CTable_LitLength, llCodeTable[nbSeq-1]);
  676. BIT_addBits(&blockStream, llTable[nbSeq-1], LL_bits[llCodeTable[nbSeq-1]]);
  677. if (MEM_32bits()) BIT_flushBits(&blockStream);
  678. BIT_addBits(&blockStream, mlTable[nbSeq-1], ML_bits[mlCodeTable[nbSeq-1]]);
  679. if (MEM_32bits()) BIT_flushBits(&blockStream);
  680. BIT_addBits(&blockStream, offsetTable[nbSeq-1], ofCodeTable[nbSeq-1]);
  681. BIT_flushBits(&blockStream);
  682. { size_t n;
  683. for (n=nbSeq-2 ; n<nbSeq ; n--) { /* intentional underflow */
  684. const BYTE ofCode = ofCodeTable[n];
  685. const BYTE mlCode = mlCodeTable[n];
  686. const BYTE llCode = llCodeTable[n];
  687. const U32 llBits = LL_bits[llCode];
  688. const U32 mlBits = ML_bits[mlCode];
  689. const U32 ofBits = ofCode; /* 32b*/ /* 64b*/
  690. /* (7)*/ /* (7)*/
  691. FSE_encodeSymbol(&blockStream, &stateOffsetBits, ofCode); /* 15 */ /* 15 */
  692. FSE_encodeSymbol(&blockStream, &stateMatchLength, mlCode); /* 24 */ /* 24 */
  693. if (MEM_32bits()) BIT_flushBits(&blockStream); /* (7)*/
  694. FSE_encodeSymbol(&blockStream, &stateLitLength, llCode); /* 16 */ /* 33 */
  695. if (MEM_32bits() || (ofBits+mlBits+llBits >= 64-7-(LLFSELog+MLFSELog+OffFSELog)))
  696. BIT_flushBits(&blockStream); /* (7)*/
  697. BIT_addBits(&blockStream, llTable[n], llBits);
  698. if (MEM_32bits() && ((llBits+mlBits)>24)) BIT_flushBits(&blockStream);
  699. BIT_addBits(&blockStream, mlTable[n], mlBits);
  700. if (MEM_32bits()) BIT_flushBits(&blockStream); /* (7)*/
  701. BIT_addBits(&blockStream, offsetTable[n], ofBits); /* 31 */
  702. BIT_flushBits(&blockStream); /* (7)*/
  703. } }
  704. FSE_flushCState(&blockStream, &stateMatchLength);
  705. FSE_flushCState(&blockStream, &stateOffsetBits);
  706. FSE_flushCState(&blockStream, &stateLitLength);
  707. { size_t const streamSize = BIT_closeCStream(&blockStream);
  708. if (streamSize==0) return ERROR(dstSize_tooSmall); /* not enough space */
  709. op += streamSize;
  710. } }
  711. /* check compressibility */
  712. _check_compressibility:
  713. { size_t const minGain = ZSTD_minGain(srcSize);
  714. size_t const maxCSize = srcSize - minGain;
  715. if ((size_t)(op-ostart) >= maxCSize) return 0; }
  716. return op - ostart;
  717. }
  718. /*! ZSTD_storeSeq() :
  719. Store a sequence (literal length, literals, offset code and match length code) into seqStore_t.
  720. `offsetCode` : distance to match, or 0 == repCode.
  721. `matchCode` : matchLength - MINMATCH
  722. */
  723. MEM_STATIC void ZSTD_storeSeq(seqStore_t* seqStorePtr, size_t litLength, const BYTE* literals, size_t offsetCode, size_t matchCode)
  724. {
  725. #if 0 /* for debug */
  726. static const BYTE* g_start = NULL;
  727. const U32 pos = (U32)(literals - g_start);
  728. if (g_start==NULL) g_start = literals;
  729. if ((pos > 2587900) && (pos < 2588050))
  730. printf("Cpos %6u :%5u literals & match %3u bytes at distance %6u \n",
  731. pos, (U32)litLength, (U32)matchCode+MINMATCH, (U32)offsetCode);
  732. #endif
  733. ZSTD_statsUpdatePrices(&seqStorePtr->stats, litLength, literals, offsetCode, matchCode);
  734. /* copy Literals */
  735. ZSTD_wildcopy(seqStorePtr->lit, literals, litLength);
  736. seqStorePtr->lit += litLength;
  737. /* literal Length */
  738. if (litLength>0xFFFF) { seqStorePtr->longLengthID = 1; seqStorePtr->longLengthPos = (U32)(seqStorePtr->litLength - seqStorePtr->litLengthStart); }
  739. *seqStorePtr->litLength++ = (U16)litLength;
  740. /* match offset */
  741. *(seqStorePtr->offset++) = (U32)offsetCode + 1;
  742. /* match Length */
  743. if (matchCode>0xFFFF) { seqStorePtr->longLengthID = 2; seqStorePtr->longLengthPos = (U32)(seqStorePtr->matchLength - seqStorePtr->matchLengthStart); }
  744. *seqStorePtr->matchLength++ = (U16)matchCode;
  745. }
  746. /*-*************************************
  747. * Match length counter
  748. ***************************************/
  749. static unsigned ZSTD_NbCommonBytes (register size_t val)
  750. {
  751. if (MEM_isLittleEndian()) {
  752. if (MEM_64bits()) {
  753. # if defined(_MSC_VER) && defined(_WIN64)
  754. unsigned long r = 0;
  755. _BitScanForward64( &r, (U64)val );
  756. return (unsigned)(r>>3);
  757. # elif defined(__GNUC__) && (__GNUC__ >= 3)
  758. return (__builtin_ctzll((U64)val) >> 3);
  759. # else
  760. static const int DeBruijnBytePos[64] = { 0, 0, 0, 0, 0, 1, 1, 2, 0, 3, 1, 3, 1, 4, 2, 7, 0, 2, 3, 6, 1, 5, 3, 5, 1, 3, 4, 4, 2, 5, 6, 7, 7, 0, 1, 2, 3, 3, 4, 6, 2, 6, 5, 5, 3, 4, 5, 6, 7, 1, 2, 4, 6, 4, 4, 5, 7, 2, 6, 5, 7, 6, 7, 7 };
  761. return DeBruijnBytePos[((U64)((val & -(long long)val) * 0x0218A392CDABBD3FULL)) >> 58];
  762. # endif
  763. } else { /* 32 bits */
  764. # if defined(_MSC_VER)
  765. unsigned long r=0;
  766. _BitScanForward( &r, (U32)val );
  767. return (unsigned)(r>>3);
  768. # elif defined(__GNUC__) && (__GNUC__ >= 3)
  769. return (__builtin_ctz((U32)val) >> 3);
  770. # else
  771. static const int DeBruijnBytePos[32] = { 0, 0, 3, 0, 3, 1, 3, 0, 3, 2, 2, 1, 3, 2, 0, 1, 3, 3, 1, 2, 2, 2, 2, 0, 3, 1, 2, 0, 1, 0, 1, 1 };
  772. return DeBruijnBytePos[((U32)((val & -(S32)val) * 0x077CB531U)) >> 27];
  773. # endif
  774. }
  775. } else { /* Big Endian CPU */
  776. if (MEM_64bits()) {
  777. # if defined(_MSC_VER) && defined(_WIN64)
  778. unsigned long r = 0;
  779. _BitScanReverse64( &r, val );
  780. return (unsigned)(r>>3);
  781. # elif defined(__GNUC__) && (__GNUC__ >= 3)
  782. return (__builtin_clzll(val) >> 3);
  783. # else
  784. unsigned r;
  785. const unsigned n32 = sizeof(size_t)*4; /* calculate this way due to compiler complaining in 32-bits mode */
  786. if (!(val>>n32)) { r=4; } else { r=0; val>>=n32; }
  787. if (!(val>>16)) { r+=2; val>>=8; } else { val>>=24; }
  788. r += (!val);
  789. return r;
  790. # endif
  791. } else { /* 32 bits */
  792. # if defined(_MSC_VER)
  793. unsigned long r = 0;
  794. _BitScanReverse( &r, (unsigned long)val );
  795. return (unsigned)(r>>3);
  796. # elif defined(__GNUC__) && (__GNUC__ >= 3)
  797. return (__builtin_clz((U32)val) >> 3);
  798. # else
  799. unsigned r;
  800. if (!(val>>16)) { r=2; val>>=8; } else { r=0; val>>=24; }
  801. r += (!val);
  802. return r;
  803. # endif
  804. } }
  805. }
  806. static size_t ZSTD_count(const BYTE* pIn, const BYTE* pMatch, const BYTE* pInLimit)
  807. {
  808. const BYTE* const pStart = pIn;
  809. while ((pIn<pInLimit-(sizeof(size_t)-1))) {
  810. size_t diff = MEM_readST(pMatch) ^ MEM_readST(pIn);
  811. if (!diff) { pIn+=sizeof(size_t); pMatch+=sizeof(size_t); continue; }
  812. pIn += ZSTD_NbCommonBytes(diff);
  813. return (size_t)(pIn - pStart);
  814. }
  815. if (MEM_64bits()) if ((pIn<(pInLimit-3)) && (MEM_read32(pMatch) == MEM_read32(pIn))) { pIn+=4; pMatch+=4; }
  816. if ((pIn<(pInLimit-1)) && (MEM_read16(pMatch) == MEM_read16(pIn))) { pIn+=2; pMatch+=2; }
  817. if ((pIn<pInLimit) && (*pMatch == *pIn)) pIn++;
  818. return (size_t)(pIn - pStart);
  819. }
  820. /** ZSTD_count_2segments() :
  821. * can count match length with `ip` & `match` in 2 different segments.
  822. * convention : on reaching mEnd, match count continue starting from iStart
  823. */
  824. static size_t ZSTD_count_2segments(const BYTE* ip, const BYTE* match, const BYTE* iEnd, const BYTE* mEnd, const BYTE* iStart)
  825. {
  826. size_t matchLength;
  827. const BYTE* vEnd = ip + (mEnd - match);
  828. if (vEnd > iEnd) vEnd = iEnd;
  829. matchLength = ZSTD_count(ip, match, vEnd);
  830. if (match + matchLength == mEnd)
  831. matchLength += ZSTD_count(ip+matchLength, iStart, iEnd);
  832. return matchLength;
  833. }
  834. /*-*************************************
  835. * Hashes
  836. ***************************************/
  837. static const U32 prime3bytes = 506832829U;
  838. static U32 ZSTD_hash3(U32 u, U32 h) { return ((u << (32-24)) * prime3bytes) >> (32-h) ; }
  839. static size_t ZSTD_hash3Ptr(const void* ptr, U32 h) { return ZSTD_hash3(MEM_readLE32(ptr), h); }
  840. static const U32 prime4bytes = 2654435761U;
  841. static U32 ZSTD_hash4(U32 u, U32 h) { return (u * prime4bytes) >> (32-h) ; }
  842. static size_t ZSTD_hash4Ptr(const void* ptr, U32 h) { return ZSTD_hash4(MEM_read32(ptr), h); }
  843. static const U64 prime5bytes = 889523592379ULL;
  844. static size_t ZSTD_hash5(U64 u, U32 h) { return (size_t)(((u << (64-40)) * prime5bytes) >> (64-h)) ; }
  845. static size_t ZSTD_hash5Ptr(const void* p, U32 h) { return ZSTD_hash5(MEM_readLE64(p), h); }
  846. static const U64 prime6bytes = 227718039650203ULL;
  847. static size_t ZSTD_hash6(U64 u, U32 h) { return (size_t)(((u << (64-48)) * prime6bytes) >> (64-h)) ; }
  848. static size_t ZSTD_hash6Ptr(const void* p, U32 h) { return ZSTD_hash6(MEM_readLE64(p), h); }
  849. static const U64 prime7bytes = 58295818150454627ULL;
  850. static size_t ZSTD_hash7(U64 u, U32 h) { return (size_t)(((u << (64-56)) * prime7bytes) >> (64-h)) ; }
  851. static size_t ZSTD_hash7Ptr(const void* p, U32 h) { return ZSTD_hash7(MEM_readLE64(p), h); }
  852. static size_t ZSTD_hashPtr(const void* p, U32 hBits, U32 mls)
  853. {
  854. switch(mls)
  855. {
  856. default:
  857. case 4: return ZSTD_hash4Ptr(p, hBits);
  858. case 5: return ZSTD_hash5Ptr(p, hBits);
  859. case 6: return ZSTD_hash6Ptr(p, hBits);
  860. case 7: return ZSTD_hash7Ptr(p, hBits);
  861. }
  862. }
  863. /*-*************************************
  864. * Fast Scan
  865. ***************************************/
  866. static void ZSTD_fillHashTable (ZSTD_CCtx* zc, const void* end, const U32 mls)
  867. {
  868. U32* const hashTable = zc->hashTable;
  869. const U32 hBits = zc->params.cParams.hashLog;
  870. const BYTE* const base = zc->base;
  871. const BYTE* ip = base + zc->nextToUpdate;
  872. const BYTE* const iend = ((const BYTE*)end) - 8;
  873. const size_t fastHashFillStep = 3;
  874. while(ip <= iend) {
  875. hashTable[ZSTD_hashPtr(ip, hBits, mls)] = (U32)(ip - base);
  876. ip += fastHashFillStep;
  877. }
  878. }
  879. FORCE_INLINE
  880. void ZSTD_compressBlock_fast_generic(ZSTD_CCtx* zc,
  881. const void* src, size_t srcSize,
  882. const U32 mls)
  883. {
  884. U32* const hashTable = zc->hashTable;
  885. const U32 hBits = zc->params.cParams.hashLog;
  886. seqStore_t* seqStorePtr = &(zc->seqStore);
  887. const BYTE* const base = zc->base;
  888. const BYTE* const istart = (const BYTE*)src;
  889. const BYTE* ip = istart;
  890. const BYTE* anchor = istart;
  891. const U32 lowIndex = zc->dictLimit;
  892. const BYTE* const lowest = base + lowIndex;
  893. const BYTE* const iend = istart + srcSize;
  894. const BYTE* const ilimit = iend - 8;
  895. size_t offset_2=REPCODE_STARTVALUE, offset_1=REPCODE_STARTVALUE;
  896. /* init */
  897. ZSTD_resetSeqStore(seqStorePtr);
  898. if (ip < lowest+REPCODE_STARTVALUE) ip = lowest+REPCODE_STARTVALUE;
  899. /* Main Search Loop */
  900. while (ip < ilimit) { /* < instead of <=, because repcode check at (ip+1) */
  901. size_t mlCode;
  902. size_t offset;
  903. const size_t h = ZSTD_hashPtr(ip, hBits, mls);
  904. const U32 matchIndex = hashTable[h];
  905. const BYTE* match = base + matchIndex;
  906. const U32 current = (U32)(ip-base);
  907. hashTable[h] = current; /* update hash table */
  908. if (MEM_read32(ip+1-offset_1) == MEM_read32(ip+1)) { /* note : by construction, offset_1 <= current */
  909. mlCode = ZSTD_count(ip+1+EQUAL_READ32, ip+1+EQUAL_READ32-offset_1, iend) + EQUAL_READ32;
  910. ip++;
  911. ZSTD_storeSeq(seqStorePtr, ip-anchor, anchor, 0, mlCode-MINMATCH);
  912. } else {
  913. if ( (matchIndex <= lowIndex) ||
  914. (MEM_read32(match) != MEM_read32(ip)) ) {
  915. ip += ((ip-anchor) >> g_searchStrength) + 1;
  916. continue;
  917. }
  918. mlCode = ZSTD_count(ip+EQUAL_READ32, match+EQUAL_READ32, iend) + EQUAL_READ32;
  919. offset = ip-match;
  920. while ((ip>anchor) && (match>lowest) && (ip[-1] == match[-1])) { ip--; match--; mlCode++; } /* catch up */
  921. offset_2 = offset_1;
  922. offset_1 = offset;
  923. ZSTD_storeSeq(seqStorePtr, ip-anchor, anchor, offset + ZSTD_REP_MOVE, mlCode-MINMATCH);
  924. }
  925. /* match found */
  926. ip += mlCode;
  927. anchor = ip;
  928. if (ip <= ilimit) {
  929. /* Fill Table */
  930. hashTable[ZSTD_hashPtr(base+current+2, hBits, mls)] = current+2; /* here because current+2 could be > iend-8 */
  931. hashTable[ZSTD_hashPtr(ip-2, hBits, mls)] = (U32)(ip-2-base);
  932. /* check immediate repcode */
  933. while ( (ip <= ilimit)
  934. && (MEM_read32(ip) == MEM_read32(ip - offset_2)) ) {
  935. /* store sequence */
  936. size_t const rlCode = ZSTD_count(ip+EQUAL_READ32, ip+EQUAL_READ32-offset_2, iend) + EQUAL_READ32;
  937. { size_t const tmpOff = offset_2; offset_2 = offset_1; offset_1 = tmpOff; } /* swap offset_2 <=> offset_1 */
  938. hashTable[ZSTD_hashPtr(ip, hBits, mls)] = (U32)(ip-base);
  939. ZSTD_storeSeq(seqStorePtr, 0, anchor, 0, rlCode-MINMATCH);
  940. ip += rlCode;
  941. anchor = ip;
  942. continue; /* faster when present ... (?) */
  943. } } }
  944. /* Last Literals */
  945. { size_t const lastLLSize = iend - anchor;
  946. memcpy(seqStorePtr->lit, anchor, lastLLSize);
  947. seqStorePtr->lit += lastLLSize;
  948. }
  949. }
  950. static void ZSTD_compressBlock_fast(ZSTD_CCtx* ctx,
  951. const void* src, size_t srcSize)
  952. {
  953. const U32 mls = ctx->params.cParams.searchLength;
  954. switch(mls)
  955. {
  956. default:
  957. case 4 :
  958. ZSTD_compressBlock_fast_generic(ctx, src, srcSize, 4); return;
  959. case 5 :
  960. ZSTD_compressBlock_fast_generic(ctx, src, srcSize, 5); return;
  961. case 6 :
  962. ZSTD_compressBlock_fast_generic(ctx, src, srcSize, 6); return;
  963. case 7 :
  964. ZSTD_compressBlock_fast_generic(ctx, src, srcSize, 7); return;
  965. }
  966. }
  967. static void ZSTD_compressBlock_fast_extDict_generic(ZSTD_CCtx* ctx,
  968. const void* src, size_t srcSize,
  969. const U32 mls)
  970. {
  971. U32* hashTable = ctx->hashTable;
  972. const U32 hBits = ctx->params.cParams.hashLog;
  973. seqStore_t* seqStorePtr = &(ctx->seqStore);
  974. const BYTE* const base = ctx->base;
  975. const BYTE* const dictBase = ctx->dictBase;
  976. const BYTE* const istart = (const BYTE*)src;
  977. const BYTE* ip = istart;
  978. const BYTE* anchor = istart;
  979. const U32 lowLimit = ctx->lowLimit;
  980. const BYTE* const dictStart = dictBase + lowLimit;
  981. const U32 dictLimit = ctx->dictLimit;
  982. const BYTE* const lowPrefixPtr = base + dictLimit;
  983. const BYTE* const dictEnd = dictBase + dictLimit;
  984. const BYTE* const iend = istart + srcSize;
  985. const BYTE* const ilimit = iend - 8;
  986. U32 offset_2=REPCODE_STARTVALUE, offset_1=REPCODE_STARTVALUE;
  987. /* init */
  988. ZSTD_resetSeqStore(seqStorePtr);
  989. /* skip first position to avoid read overflow during repcode match check */
  990. hashTable[ZSTD_hashPtr(ip+0, hBits, mls)] = (U32)(ip-base+0);
  991. ip += REPCODE_STARTVALUE;
  992. /* Main Search Loop */
  993. while (ip < ilimit) { /* < instead of <=, because (ip+1) */
  994. const size_t h = ZSTD_hashPtr(ip, hBits, mls);
  995. const U32 matchIndex = hashTable[h];
  996. const BYTE* matchBase = matchIndex < dictLimit ? dictBase : base;
  997. const BYTE* match = matchBase + matchIndex;
  998. const U32 current = (U32)(ip-base);
  999. const U32 repIndex = current + 1 - offset_1;
  1000. const BYTE* repBase = repIndex < dictLimit ? dictBase : base;
  1001. const BYTE* repMatch = repBase + repIndex;
  1002. size_t mlCode;
  1003. U32 offset;
  1004. hashTable[h] = current; /* update hash table */
  1005. if ( ((repIndex >= dictLimit) || (repIndex <= dictLimit-4))
  1006. && (MEM_read32(repMatch) == MEM_read32(ip+1)) ) {
  1007. const BYTE* repMatchEnd = repIndex < dictLimit ? dictEnd : iend;
  1008. mlCode = ZSTD_count_2segments(ip+1+EQUAL_READ32, repMatch+EQUAL_READ32, iend, repMatchEnd, lowPrefixPtr) + EQUAL_READ32;
  1009. ip++;
  1010. ZSTD_storeSeq(seqStorePtr, ip-anchor, anchor, 0, mlCode-MINMATCH);
  1011. } else {
  1012. if ( (matchIndex < lowLimit) ||
  1013. (MEM_read32(match) != MEM_read32(ip)) ) {
  1014. ip += ((ip-anchor) >> g_searchStrength) + 1;
  1015. continue;
  1016. }
  1017. { const BYTE* matchEnd = matchIndex < dictLimit ? dictEnd : iend;
  1018. const BYTE* lowMatchPtr = matchIndex < dictLimit ? dictStart : lowPrefixPtr;
  1019. mlCode = ZSTD_count_2segments(ip+EQUAL_READ32, match+EQUAL_READ32, iend, matchEnd, lowPrefixPtr) + EQUAL_READ32;
  1020. while ((ip>anchor) && (match>lowMatchPtr) && (ip[-1] == match[-1])) { ip--; match--; mlCode++; } /* catch up */
  1021. offset = current - matchIndex;
  1022. offset_2 = offset_1;
  1023. offset_1 = offset;
  1024. ZSTD_storeSeq(seqStorePtr, ip-anchor, anchor, offset + ZSTD_REP_MOVE, mlCode-MINMATCH);
  1025. } }
  1026. /* found a match : store it */
  1027. ip += mlCode;
  1028. anchor = ip;
  1029. if (ip <= ilimit) {
  1030. /* Fill Table */
  1031. hashTable[ZSTD_hashPtr(base+current+2, hBits, mls)] = current+2;
  1032. hashTable[ZSTD_hashPtr(ip-2, hBits, mls)] = (U32)(ip-2-base);
  1033. /* check immediate repcode */
  1034. while (ip <= ilimit) {
  1035. U32 const current2 = (U32)(ip-base);
  1036. U32 const repIndex2 = current2 - offset_2;
  1037. const BYTE* repMatch2 = repIndex2 < dictLimit ? dictBase + repIndex2 : base + repIndex2;
  1038. if ( ((repIndex2 <= dictLimit-4) || (repIndex2 >= dictLimit))
  1039. && (MEM_read32(repMatch2) == MEM_read32(ip)) ) {
  1040. const BYTE* const repEnd2 = repIndex2 < dictLimit ? dictEnd : iend;
  1041. size_t repLength2 = ZSTD_count_2segments(ip+EQUAL_READ32, repMatch2+EQUAL_READ32, iend, repEnd2, lowPrefixPtr) + EQUAL_READ32;
  1042. U32 tmpOffset = offset_2; offset_2 = offset_1; offset_1 = tmpOffset; /* swap offset_2 <=> offset_1 */
  1043. ZSTD_storeSeq(seqStorePtr, 0, anchor, 0, repLength2-MINMATCH);
  1044. hashTable[ZSTD_hashPtr(ip, hBits, mls)] = current2;
  1045. ip += repLength2;
  1046. anchor = ip;
  1047. continue;
  1048. }
  1049. break;
  1050. } } }
  1051. /* Last Literals */
  1052. { size_t const lastLLSize = iend - anchor;
  1053. memcpy(seqStorePtr->lit, anchor, lastLLSize);
  1054. seqStorePtr->lit += lastLLSize;
  1055. }
  1056. }
  1057. static void ZSTD_compressBlock_fast_extDict(ZSTD_CCtx* ctx,
  1058. const void* src, size_t srcSize)
  1059. {
  1060. const U32 mls = ctx->params.cParams.searchLength;
  1061. switch(mls)
  1062. {
  1063. default:
  1064. case 4 :
  1065. ZSTD_compressBlock_fast_extDict_generic(ctx, src, srcSize, 4); return;
  1066. case 5 :
  1067. ZSTD_compressBlock_fast_extDict_generic(ctx, src, srcSize, 5); return;
  1068. case 6 :
  1069. ZSTD_compressBlock_fast_extDict_generic(ctx, src, srcSize, 6); return;
  1070. case 7 :
  1071. ZSTD_compressBlock_fast_extDict_generic(ctx, src, srcSize, 7); return;
  1072. }
  1073. }
  1074. /*-*************************************
  1075. * Binary Tree search
  1076. ***************************************/
  1077. /** ZSTD_insertBt1() : add one or multiple positions to tree.
  1078. * ip : assumed <= iend-8 .
  1079. * @return : nb of positions added */
  1080. static U32 ZSTD_insertBt1(ZSTD_CCtx* zc, const BYTE* const ip, const U32 mls, const BYTE* const iend, U32 nbCompares,
  1081. U32 extDict)
  1082. {
  1083. U32* const hashTable = zc->hashTable;
  1084. const U32 hashLog = zc->params.cParams.hashLog;
  1085. const size_t h = ZSTD_hashPtr(ip, hashLog, mls);
  1086. U32* const bt = zc->chainTable;
  1087. const U32 btLog = zc->params.cParams.chainLog - 1;
  1088. const U32 btMask= (1 << btLog) - 1;
  1089. U32 matchIndex = hashTable[h];
  1090. size_t commonLengthSmaller=0, commonLengthLarger=0;
  1091. const BYTE* const base = zc->base;
  1092. const BYTE* const dictBase = zc->dictBase;
  1093. const U32 dictLimit = zc->dictLimit;
  1094. const BYTE* const dictEnd = dictBase + dictLimit;
  1095. const BYTE* const prefixStart = base + dictLimit;
  1096. const BYTE* match = base + matchIndex;
  1097. const U32 current = (U32)(ip-base);
  1098. const U32 btLow = btMask >= current ? 0 : current - btMask;
  1099. U32* smallerPtr = bt + 2*(current&btMask);
  1100. U32* largerPtr = smallerPtr + 1;
  1101. U32 dummy32; /* to be nullified at the end */
  1102. const U32 windowLow = zc->lowLimit;
  1103. U32 matchEndIdx = current+8;
  1104. size_t bestLength = 8;
  1105. U32 predictedSmall = *(bt + 2*((current-1)&btMask) + 0);
  1106. U32 predictedLarge = *(bt + 2*((current-1)&btMask) + 1);
  1107. predictedSmall += (predictedSmall>0);
  1108. predictedLarge += (predictedLarge>0);
  1109. hashTable[h] = current; /* Update Hash Table */
  1110. while (nbCompares-- && (matchIndex > windowLow)) {
  1111. U32* nextPtr = bt + 2*(matchIndex & btMask);
  1112. size_t matchLength = MIN(commonLengthSmaller, commonLengthLarger); /* guaranteed minimum nb of common bytes */
  1113. #if 0 /* note : can create issues when hlog small <= 11 */
  1114. const U32* predictPtr = bt + 2*((matchIndex-1) & btMask); /* written this way, as bt is a roll buffer */
  1115. if (matchIndex == predictedSmall) {
  1116. /* no need to check length, result known */
  1117. *smallerPtr = matchIndex;
  1118. if (matchIndex <= btLow) { smallerPtr=&dummy32; break; } /* beyond tree size, stop the search */
  1119. smallerPtr = nextPtr+1; /* new "smaller" => larger of match */
  1120. matchIndex = nextPtr[1]; /* new matchIndex larger than previous (closer to current) */
  1121. predictedSmall = predictPtr[1] + (predictPtr[1]>0);
  1122. continue;
  1123. }
  1124. if (matchIndex == predictedLarge) {
  1125. *largerPtr = matchIndex;
  1126. if (matchIndex <= btLow) { largerPtr=&dummy32; break; } /* beyond tree size, stop the search */
  1127. largerPtr = nextPtr;
  1128. matchIndex = nextPtr[0];
  1129. predictedLarge = predictPtr[0] + (predictPtr[0]>0);
  1130. continue;
  1131. }
  1132. #endif
  1133. if ((!extDict) || (matchIndex+matchLength >= dictLimit)) {
  1134. match = base + matchIndex;
  1135. if (match[matchLength] == ip[matchLength])
  1136. matchLength += ZSTD_count(ip+matchLength+1, match+matchLength+1, iend) +1;
  1137. } else {
  1138. match = dictBase + matchIndex;
  1139. matchLength += ZSTD_count_2segments(ip+matchLength, match+matchLength, iend, dictEnd, prefixStart);
  1140. if (matchIndex+matchLength >= dictLimit)
  1141. match = base + matchIndex; /* to prepare for next usage of match[matchLength] */
  1142. }
  1143. if (matchLength > bestLength) {
  1144. bestLength = matchLength;
  1145. if (matchLength > matchEndIdx - matchIndex)
  1146. matchEndIdx = matchIndex + (U32)matchLength;
  1147. }
  1148. if (ip+matchLength == iend) /* equal : no way to know if inf or sup */
  1149. break; /* drop , to guarantee consistency ; miss a bit of compression, but other solutions can corrupt the tree */
  1150. if (match[matchLength] < ip[matchLength]) { /* necessarily within correct buffer */
  1151. /* match is smaller than current */
  1152. *smallerPtr = matchIndex; /* update smaller idx */
  1153. commonLengthSmaller = matchLength; /* all smaller will now have at least this guaranteed common length */
  1154. if (matchIndex <= btLow) { smallerPtr=&dummy32; break; } /* beyond tree size, stop the search */
  1155. smallerPtr = nextPtr+1; /* new "smaller" => larger of match */
  1156. matchIndex = nextPtr[1]; /* new matchIndex larger than previous (closer to current) */
  1157. } else {
  1158. /* match is larger than current */
  1159. *largerPtr = matchIndex;
  1160. commonLengthLarger = matchLength;
  1161. if (matchIndex <= btLow) { largerPtr=&dummy32; break; } /* beyond tree size, stop the search */
  1162. largerPtr = nextPtr;
  1163. matchIndex = nextPtr[0];
  1164. } }
  1165. *smallerPtr = *largerPtr = 0;
  1166. if (bestLength > 384) return MIN(192, (U32)(bestLength - 384));
  1167. if (matchEndIdx > current + 8) return matchEndIdx - current - 8;
  1168. return 1;
  1169. }
  1170. static size_t ZSTD_insertBtAndFindBestMatch (
  1171. ZSTD_CCtx* zc,
  1172. const BYTE* const ip, const BYTE* const iend,
  1173. size_t* offsetPtr,
  1174. U32 nbCompares, const U32 mls,
  1175. U32 extDict)
  1176. {
  1177. U32* const hashTable = zc->hashTable;
  1178. const U32 hashLog = zc->params.cParams.hashLog;
  1179. const size_t h = ZSTD_hashPtr(ip, hashLog, mls);
  1180. U32* const bt = zc->chainTable;
  1181. const U32 btLog = zc->params.cParams.chainLog - 1;
  1182. const U32 btMask= (1 << btLog) - 1;
  1183. U32 matchIndex = hashTable[h];
  1184. size_t commonLengthSmaller=0, commonLengthLarger=0;
  1185. const BYTE* const base = zc->base;
  1186. const BYTE* const dictBase = zc->dictBase;
  1187. const U32 dictLimit = zc->dictLimit;
  1188. const BYTE* const dictEnd = dictBase + dictLimit;
  1189. const BYTE* const prefixStart = base + dictLimit;
  1190. const U32 current = (U32)(ip-base);
  1191. const U32 btLow = btMask >= current ? 0 : current - btMask;
  1192. const U32 windowLow = zc->lowLimit;
  1193. U32* smallerPtr = bt + 2*(current&btMask);
  1194. U32* largerPtr = bt + 2*(current&btMask) + 1;
  1195. U32 matchEndIdx = current+8;
  1196. U32 dummy32; /* to be nullified at the end */
  1197. size_t bestLength = 0;
  1198. hashTable[h] = current; /* Update Hash Table */
  1199. while (nbCompares-- && (matchIndex > windowLow)) {
  1200. U32* nextPtr = bt + 2*(matchIndex & btMask);
  1201. size_t matchLength = MIN(commonLengthSmaller, commonLengthLarger); /* guaranteed minimum nb of common bytes */
  1202. const BYTE* match;
  1203. if ((!extDict) || (matchIndex+matchLength >= dictLimit)) {
  1204. match = base + matchIndex;
  1205. if (match[matchLength] == ip[matchLength])
  1206. matchLength += ZSTD_count(ip+matchLength+1, match+matchLength+1, iend) +1;
  1207. } else {
  1208. match = dictBase + matchIndex;
  1209. matchLength += ZSTD_count_2segments(ip+matchLength, match+matchLength, iend, dictEnd, prefixStart);
  1210. if (matchIndex+matchLength >= dictLimit)
  1211. match = base + matchIndex; /* to prepare for next usage of match[matchLength] */
  1212. }
  1213. if (matchLength > bestLength) {
  1214. if (matchLength > matchEndIdx - matchIndex)
  1215. matchEndIdx = matchIndex + (U32)matchLength;
  1216. if ( (4*(int)(matchLength-bestLength)) > (int)(ZSTD_highbit(current-matchIndex+1) - ZSTD_highbit((U32)offsetPtr[0]+1)) )
  1217. bestLength = matchLength, *offsetPtr = ZSTD_REP_MOVE + current - matchIndex;
  1218. if (ip+matchLength == iend) /* equal : no way to know if inf or sup */
  1219. break; /* drop, to guarantee consistency (miss a little bit of compression) */
  1220. }
  1221. if (match[matchLength] < ip[matchLength]) {
  1222. /* match is smaller than current */
  1223. *smallerPtr = matchIndex; /* update smaller idx */
  1224. commonLengthSmaller = matchLength; /* all smaller will now have at least this guaranteed common length */
  1225. if (matchIndex <= btLow) { smallerPtr=&dummy32; break; } /* beyond tree size, stop the search */
  1226. smallerPtr = nextPtr+1; /* new "smaller" => larger of match */
  1227. matchIndex = nextPtr[1]; /* new matchIndex larger than previous (closer to current) */
  1228. } else {
  1229. /* match is larger than current */
  1230. *largerPtr = matchIndex;
  1231. commonLengthLarger = matchLength;
  1232. if (matchIndex <= btLow) { largerPtr=&dummy32; break; } /* beyond tree size, stop the search */
  1233. largerPtr = nextPtr;
  1234. matchIndex = nextPtr[0];
  1235. } }
  1236. *smallerPtr = *largerPtr = 0;
  1237. zc->nextToUpdate = (matchEndIdx > current + 8) ? matchEndIdx - 8 : current+1;
  1238. return bestLength;
  1239. }
  1240. static void ZSTD_updateTree(ZSTD_CCtx* zc, const BYTE* const ip, const BYTE* const iend, const U32 nbCompares, const U32 mls)
  1241. {
  1242. const BYTE* const base = zc->base;
  1243. const U32 target = (U32)(ip - base);
  1244. U32 idx = zc->nextToUpdate;
  1245. while(idx < target)
  1246. idx += ZSTD_insertBt1(zc, base+idx, mls, iend, nbCompares, 0);
  1247. }
  1248. /** ZSTD_BtFindBestMatch() : Tree updater, providing best match */
  1249. static size_t ZSTD_BtFindBestMatch (
  1250. ZSTD_CCtx* zc,
  1251. const BYTE* const ip, const BYTE* const iLimit,
  1252. size_t* offsetPtr,
  1253. const U32 maxNbAttempts, const U32 mls)
  1254. {
  1255. if (ip < zc->base + zc->nextToUpdate) return 0; /* skipped area */
  1256. ZSTD_updateTree(zc, ip, iLimit, maxNbAttempts, mls);
  1257. return ZSTD_insertBtAndFindBestMatch(zc, ip, iLimit, offsetPtr, maxNbAttempts, mls, 0);
  1258. }
  1259. static size_t ZSTD_BtFindBestMatch_selectMLS (
  1260. ZSTD_CCtx* zc, /* Index table will be updated */
  1261. const BYTE* ip, const BYTE* const iLimit,
  1262. size_t* offsetPtr,
  1263. const U32 maxNbAttempts, const U32 matchLengthSearch)
  1264. {
  1265. switch(matchLengthSearch)
  1266. {
  1267. default :
  1268. case 4 : return ZSTD_BtFindBestMatch(zc, ip, iLimit, offsetPtr, maxNbAttempts, 4);
  1269. case 5 : return ZSTD_BtFindBestMatch(zc, ip, iLimit, offsetPtr, maxNbAttempts, 5);
  1270. case 6 : return ZSTD_BtFindBestMatch(zc, ip, iLimit, offsetPtr, maxNbAttempts, 6);
  1271. }
  1272. }
  1273. static void ZSTD_updateTree_extDict(ZSTD_CCtx* zc, const BYTE* const ip, const BYTE* const iend, const U32 nbCompares, const U32 mls)
  1274. {
  1275. const BYTE* const base = zc->base;
  1276. const U32 target = (U32)(ip - base);
  1277. U32 idx = zc->nextToUpdate;
  1278. while (idx < target) idx += ZSTD_insertBt1(zc, base+idx, mls, iend, nbCompares, 1);
  1279. }
  1280. /** Tree updater, providing best match */
  1281. static size_t ZSTD_BtFindBestMatch_extDict (
  1282. ZSTD_CCtx* zc,
  1283. const BYTE* const ip, const BYTE* const iLimit,
  1284. size_t* offsetPtr,
  1285. const U32 maxNbAttempts, const U32 mls)
  1286. {
  1287. if (ip < zc->base + zc->nextToUpdate) return 0; /* skipped area */
  1288. ZSTD_updateTree_extDict(zc, ip, iLimit, maxNbAttempts, mls);
  1289. return ZSTD_insertBtAndFindBestMatch(zc, ip, iLimit, offsetPtr, maxNbAttempts, mls, 1);
  1290. }
  1291. static size_t ZSTD_BtFindBestMatch_selectMLS_extDict (
  1292. ZSTD_CCtx* zc, /* Index table will be updated */
  1293. const BYTE* ip, const BYTE* const iLimit,
  1294. size_t* offsetPtr,
  1295. const U32 maxNbAttempts, const U32 matchLengthSearch)
  1296. {
  1297. switch(matchLengthSearch)
  1298. {
  1299. default :
  1300. case 4 : return ZSTD_BtFindBestMatch_extDict(zc, ip, iLimit, offsetPtr, maxNbAttempts, 4);
  1301. case 5 : return ZSTD_BtFindBestMatch_extDict(zc, ip, iLimit, offsetPtr, maxNbAttempts, 5);
  1302. case 6 : return ZSTD_BtFindBestMatch_extDict(zc, ip, iLimit, offsetPtr, maxNbAttempts, 6);
  1303. }
  1304. }
  1305. /* ***********************
  1306. * Hash Chain
  1307. *************************/
  1308. #define NEXT_IN_CHAIN(d, mask) chainTable[(d) & mask]
  1309. /* Update chains up to ip (excluded)
  1310. Assumption : always within prefix (ie. not within extDict) */
  1311. FORCE_INLINE
  1312. U32 ZSTD_insertAndFindFirstIndex (ZSTD_CCtx* zc, const BYTE* ip, U32 mls)
  1313. {
  1314. U32* const hashTable = zc->hashTable;
  1315. const U32 hashLog = zc->params.cParams.hashLog;
  1316. U32* const chainTable = zc->chainTable;
  1317. const U32 chainMask = (1 << zc->params.cParams.chainLog) - 1;
  1318. const BYTE* const base = zc->base;
  1319. const U32 target = (U32)(ip - base);
  1320. U32 idx = zc->nextToUpdate;
  1321. while(idx < target) {
  1322. size_t const h = ZSTD_hashPtr(base+idx, hashLog, mls);
  1323. NEXT_IN_CHAIN(idx, chainMask) = hashTable[h];
  1324. hashTable[h] = idx;
  1325. idx++;
  1326. }
  1327. zc->nextToUpdate = target;
  1328. return hashTable[ZSTD_hashPtr(ip, hashLog, mls)];
  1329. }
  1330. FORCE_INLINE /* inlining is important to hardwire a hot branch (template emulation) */
  1331. size_t ZSTD_HcFindBestMatch_generic (
  1332. ZSTD_CCtx* zc, /* Index table will be updated */
  1333. const BYTE* const ip, const BYTE* const iLimit,
  1334. size_t* offsetPtr,
  1335. const U32 maxNbAttempts, const U32 mls, const U32 extDict)
  1336. {
  1337. U32* const chainTable = zc->chainTable;
  1338. const U32 chainSize = (1 << zc->params.cParams.chainLog);
  1339. const U32 chainMask = chainSize-1;
  1340. const BYTE* const base = zc->base;
  1341. const BYTE* const dictBase = zc->dictBase;
  1342. const U32 dictLimit = zc->dictLimit;
  1343. const BYTE* const prefixStart = base + dictLimit;
  1344. const BYTE* const dictEnd = dictBase + dictLimit;
  1345. const U32 lowLimit = zc->lowLimit;
  1346. const U32 current = (U32)(ip-base);
  1347. const U32 minChain = current > chainSize ? current - chainSize : 0;
  1348. int nbAttempts=maxNbAttempts;
  1349. size_t ml=EQUAL_READ32-1;
  1350. /* HC4 match finder */
  1351. U32 matchIndex = ZSTD_insertAndFindFirstIndex (zc, ip, mls);
  1352. for ( ; (matchIndex>lowLimit) && (nbAttempts) ; nbAttempts--) {
  1353. const BYTE* match;
  1354. size_t currentMl=0;
  1355. if ((!extDict) || matchIndex >= dictLimit) {
  1356. match = base + matchIndex;
  1357. if (match[ml] == ip[ml]) /* potentially better */
  1358. currentMl = ZSTD_count(ip, match, iLimit);
  1359. } else {
  1360. match = dictBase + matchIndex;
  1361. if (MEM_read32(match) == MEM_read32(ip)) /* assumption : matchIndex <= dictLimit-4 (by table construction) */
  1362. currentMl = ZSTD_count_2segments(ip+EQUAL_READ32, match+EQUAL_READ32, iLimit, dictEnd, prefixStart) + EQUAL_READ32;
  1363. }
  1364. /* save best solution */
  1365. if (currentMl > ml) { ml = currentMl; *offsetPtr = ZSTD_REP_MOVE + current - matchIndex; if (ip+currentMl == iLimit) break; /* best possible, and avoid read overflow*/ }
  1366. if (matchIndex <= minChain) break;
  1367. matchIndex = NEXT_IN_CHAIN(matchIndex, chainMask);
  1368. }
  1369. return ml;
  1370. }
  1371. FORCE_INLINE size_t ZSTD_HcFindBestMatch_selectMLS (
  1372. ZSTD_CCtx* zc,
  1373. const BYTE* ip, const BYTE* const iLimit,
  1374. size_t* offsetPtr,
  1375. const U32 maxNbAttempts, const U32 matchLengthSearch)
  1376. {
  1377. switch(matchLengthSearch)
  1378. {
  1379. default :
  1380. case 4 : return ZSTD_HcFindBestMatch_generic(zc, ip, iLimit, offsetPtr, maxNbAttempts, 4, 0);
  1381. case 5 : return ZSTD_HcFindBestMatch_generic(zc, ip, iLimit, offsetPtr, maxNbAttempts, 5, 0);
  1382. case 6 : return ZSTD_HcFindBestMatch_generic(zc, ip, iLimit, offsetPtr, maxNbAttempts, 6, 0);
  1383. }
  1384. }
  1385. FORCE_INLINE size_t ZSTD_HcFindBestMatch_extDict_selectMLS (
  1386. ZSTD_CCtx* zc,
  1387. const BYTE* ip, const BYTE* const iLimit,
  1388. size_t* offsetPtr,
  1389. const U32 maxNbAttempts, const U32 matchLengthSearch)
  1390. {
  1391. switch(matchLengthSearch)
  1392. {
  1393. default :
  1394. case 4 : return ZSTD_HcFindBestMatch_generic(zc, ip, iLimit, offsetPtr, maxNbAttempts, 4, 1);
  1395. case 5 : return ZSTD_HcFindBestMatch_generic(zc, ip, iLimit, offsetPtr, maxNbAttempts, 5, 1);
  1396. case 6 : return ZSTD_HcFindBestMatch_generic(zc, ip, iLimit, offsetPtr, maxNbAttempts, 6, 1);
  1397. }
  1398. }
  1399. /* *******************************
  1400. * Common parser - lazy strategy
  1401. *********************************/
  1402. FORCE_INLINE
  1403. void ZSTD_compressBlock_lazy_generic(ZSTD_CCtx* ctx,
  1404. const void* src, size_t srcSize,
  1405. const U32 searchMethod, const U32 depth)
  1406. {
  1407. seqStore_t* seqStorePtr = &(ctx->seqStore);
  1408. const BYTE* const istart = (const BYTE*)src;
  1409. const BYTE* ip = istart;
  1410. const BYTE* anchor = istart;
  1411. const BYTE* const iend = istart + srcSize;
  1412. const BYTE* const ilimit = iend - 8;
  1413. const BYTE* const base = ctx->base + ctx->dictLimit;
  1414. U32 const maxSearches = 1 << ctx->params.cParams.searchLog;
  1415. U32 const mls = ctx->params.cParams.searchLength;
  1416. typedef size_t (*searchMax_f)(ZSTD_CCtx* zc, const BYTE* ip, const BYTE* iLimit,
  1417. size_t* offsetPtr,
  1418. U32 maxNbAttempts, U32 matchLengthSearch);
  1419. searchMax_f searchMax = searchMethod ? ZSTD_BtFindBestMatch_selectMLS : ZSTD_HcFindBestMatch_selectMLS;
  1420. /* init */
  1421. U32 rep[ZSTD_REP_INIT];
  1422. { U32 i ; for (i=0; i<ZSTD_REP_INIT; i++) rep[i]=REPCODE_STARTVALUE; }
  1423. ctx->nextToUpdate3 = ctx->nextToUpdate;
  1424. ZSTD_resetSeqStore(seqStorePtr);
  1425. if ((ip-base) < REPCODE_STARTVALUE) ip = base + REPCODE_STARTVALUE;
  1426. /* Match Loop */
  1427. while (ip < ilimit) {
  1428. size_t matchLength=0;
  1429. size_t offset=0;
  1430. const BYTE* start=ip+1;
  1431. /* check repCode */
  1432. if (MEM_read32(ip+1) == MEM_read32(ip+1 - rep[0])) {
  1433. /* repcode : we take it */
  1434. matchLength = ZSTD_count(ip+1+EQUAL_READ32, ip+1+EQUAL_READ32-rep[0], iend) + EQUAL_READ32;
  1435. if (depth==0) goto _storeSequence;
  1436. }
  1437. /* first search (depth 0) */
  1438. { size_t offsetFound = 99999999;
  1439. size_t const ml2 = searchMax(ctx, ip, iend, &offsetFound, maxSearches, mls);
  1440. if (ml2 > matchLength)
  1441. matchLength = ml2, start = ip, offset=offsetFound;
  1442. }
  1443. if (matchLength < EQUAL_READ32) {
  1444. ip += ((ip-anchor) >> g_searchStrength) + 1; /* jump faster over incompressible sections */
  1445. continue;
  1446. }
  1447. /* let's try to find a better solution */
  1448. if (depth>=1)
  1449. while (ip<ilimit) {
  1450. ip ++;
  1451. if ((offset) && (MEM_read32(ip) == MEM_read32(ip - rep[0]))) {
  1452. size_t const mlRep = ZSTD_count(ip+EQUAL_READ32, ip+EQUAL_READ32-rep[0], iend) + EQUAL_READ32;
  1453. int const gain2 = (int)(mlRep * 3);
  1454. int const gain1 = (int)(matchLength*3 - ZSTD_highbit((U32)offset+1) + 1);
  1455. if ((mlRep >= EQUAL_READ32) && (gain2 > gain1))
  1456. matchLength = mlRep, offset = 0, start = ip;
  1457. }
  1458. { size_t offset2=99999999;
  1459. size_t const ml2 = searchMax(ctx, ip, iend, &offset2, maxSearches, mls);
  1460. int const gain2 = (int)(ml2*4 - ZSTD_highbit((U32)offset2+1)); /* raw approx */
  1461. int const gain1 = (int)(matchLength*4 - ZSTD_highbit((U32)offset+1) + 4);
  1462. if ((ml2 >= EQUAL_READ32) && (gain2 > gain1)) {
  1463. matchLength = ml2, offset = offset2, start = ip;
  1464. continue; /* search a better one */
  1465. } }
  1466. /* let's find an even better one */
  1467. if ((depth==2) && (ip<ilimit)) {
  1468. ip ++;
  1469. if ((offset) && (MEM_read32(ip) == MEM_read32(ip - rep[0]))) {
  1470. size_t const ml2 = ZSTD_count(ip+EQUAL_READ32, ip+EQUAL_READ32-rep[0], iend) + EQUAL_READ32;
  1471. int const gain2 = (int)(ml2 * 4);
  1472. int const gain1 = (int)(matchLength*4 - ZSTD_highbit((U32)offset+1) + 1);
  1473. if ((ml2 >= EQUAL_READ32) && (gain2 > gain1))
  1474. matchLength = ml2, offset = 0, start = ip;
  1475. }
  1476. { size_t offset2=99999999;
  1477. size_t const ml2 = searchMax(ctx, ip, iend, &offset2, maxSearches, mls);
  1478. int const gain2 = (int)(ml2*4 - ZSTD_highbit((U32)offset2+1)); /* raw approx */
  1479. int const gain1 = (int)(matchLength*4 - ZSTD_highbit((U32)offset+1) + 7);
  1480. if ((ml2 >= EQUAL_READ32) && (gain2 > gain1)) {
  1481. matchLength = ml2, offset = offset2, start = ip;
  1482. continue;
  1483. } } }
  1484. break; /* nothing found : store previous solution */
  1485. }
  1486. /* catch up */
  1487. if (offset) {
  1488. while ((start>anchor) && (start>base+offset-ZSTD_REP_MOVE) && (start[-1] == start[-1-offset+ZSTD_REP_MOVE])) /* only search for offset within prefix */
  1489. { start--; matchLength++; }
  1490. rep[1] = rep[0]; rep[0] = (U32)(offset - ZSTD_REP_MOVE);
  1491. }
  1492. /* store sequence */
  1493. _storeSequence:
  1494. { size_t const litLength = start - anchor;
  1495. ZSTD_storeSeq(seqStorePtr, litLength, anchor, offset, matchLength-MINMATCH);
  1496. anchor = ip = start + matchLength;
  1497. }
  1498. /* check immediate repcode */
  1499. while ( (ip <= ilimit)
  1500. && (MEM_read32(ip) == MEM_read32(ip - rep[1])) ) {
  1501. /* store sequence */
  1502. matchLength = ZSTD_count(ip+EQUAL_READ32, ip+EQUAL_READ32-rep[1], iend) + EQUAL_READ32;
  1503. offset = rep[1]; rep[1] = rep[0]; rep[0] = (U32)offset; /* swap repcodes */
  1504. ZSTD_storeSeq(seqStorePtr, 0, anchor, 0, matchLength-MINMATCH);
  1505. ip += matchLength;
  1506. anchor = ip;
  1507. continue; /* faster when present ... (?) */
  1508. } }
  1509. /* Last Literals */
  1510. { size_t const lastLLSize = iend - anchor;
  1511. memcpy(seqStorePtr->lit, anchor, lastLLSize);
  1512. seqStorePtr->lit += lastLLSize;
  1513. ZSTD_statsUpdatePrices(&seqStorePtr->stats, lastLLSize, anchor, 0, 0);
  1514. }
  1515. }
  1516. static void ZSTD_compressBlock_btlazy2(ZSTD_CCtx* ctx, const void* src, size_t srcSize)
  1517. {
  1518. ZSTD_compressBlock_lazy_generic(ctx, src, srcSize, 1, 2);
  1519. }
  1520. static void ZSTD_compressBlock_lazy2(ZSTD_CCtx* ctx, const void* src, size_t srcSize)
  1521. {
  1522. ZSTD_compressBlock_lazy_generic(ctx, src, srcSize, 0, 2);
  1523. }
  1524. static void ZSTD_compressBlock_lazy(ZSTD_CCtx* ctx, const void* src, size_t srcSize)
  1525. {
  1526. ZSTD_compressBlock_lazy_generic(ctx, src, srcSize, 0, 1);
  1527. }
  1528. static void ZSTD_compressBlock_greedy(ZSTD_CCtx* ctx, const void* src, size_t srcSize)
  1529. {
  1530. ZSTD_compressBlock_lazy_generic(ctx, src, srcSize, 0, 0);
  1531. }
  1532. FORCE_INLINE
  1533. void ZSTD_compressBlock_lazy_extDict_generic(ZSTD_CCtx* ctx,
  1534. const void* src, size_t srcSize,
  1535. const U32 searchMethod, const U32 depth)
  1536. {
  1537. seqStore_t* seqStorePtr = &(ctx->seqStore);
  1538. const BYTE* const istart = (const BYTE*)src;
  1539. const BYTE* ip = istart;
  1540. const BYTE* anchor = istart;
  1541. const BYTE* const iend = istart + srcSize;
  1542. const BYTE* const ilimit = iend - 8;
  1543. const BYTE* const base = ctx->base;
  1544. const U32 dictLimit = ctx->dictLimit;
  1545. const BYTE* const prefixStart = base + dictLimit;
  1546. const BYTE* const dictBase = ctx->dictBase;
  1547. const BYTE* const dictEnd = dictBase + dictLimit;
  1548. const BYTE* const dictStart = dictBase + ctx->lowLimit;
  1549. const U32 maxSearches = 1 << ctx->params.cParams.searchLog;
  1550. const U32 mls = ctx->params.cParams.searchLength;
  1551. typedef size_t (*searchMax_f)(ZSTD_CCtx* zc, const BYTE* ip, const BYTE* iLimit,
  1552. size_t* offsetPtr,
  1553. U32 maxNbAttempts, U32 matchLengthSearch);
  1554. searchMax_f searchMax = searchMethod ? ZSTD_BtFindBestMatch_selectMLS_extDict : ZSTD_HcFindBestMatch_extDict_selectMLS;
  1555. /* init */
  1556. U32 rep[ZSTD_REP_INIT];
  1557. { U32 i; for (i=0; i<ZSTD_REP_INIT; i++) rep[i]=REPCODE_STARTVALUE; }
  1558. ctx->nextToUpdate3 = ctx->nextToUpdate;
  1559. ZSTD_resetSeqStore(seqStorePtr);
  1560. if ((ip - prefixStart) < REPCODE_STARTVALUE) ip += REPCODE_STARTVALUE;
  1561. /* Match Loop */
  1562. while (ip < ilimit) {
  1563. size_t matchLength=0;
  1564. size_t offset=0;
  1565. const BYTE* start=ip+1;
  1566. U32 current = (U32)(ip-base);
  1567. /* check repCode */
  1568. {
  1569. const U32 repIndex = (U32)(current+1 - rep[0]);
  1570. const BYTE* const repBase = repIndex < dictLimit ? dictBase : base;
  1571. const BYTE* const repMatch = repBase + repIndex;
  1572. if ((U32)((dictLimit-1) - repIndex) >= 3) /* intentional overflow */
  1573. if (MEM_read32(ip+1) == MEM_read32(repMatch)) {
  1574. /* repcode detected we should take it */
  1575. const BYTE* const repEnd = repIndex < dictLimit ? dictEnd : iend;
  1576. matchLength = ZSTD_count_2segments(ip+1+EQUAL_READ32, repMatch+EQUAL_READ32, iend, repEnd, prefixStart) + EQUAL_READ32;
  1577. if (depth==0) goto _storeSequence;
  1578. } }
  1579. /* first search (depth 0) */
  1580. { size_t offsetFound = 99999999;
  1581. size_t const ml2 = searchMax(ctx, ip, iend, &offsetFound, maxSearches, mls);
  1582. if (ml2 > matchLength)
  1583. matchLength = ml2, start = ip, offset=offsetFound;
  1584. }
  1585. if (matchLength < EQUAL_READ32) {
  1586. ip += ((ip-anchor) >> g_searchStrength) + 1; /* jump faster over incompressible sections */
  1587. continue;
  1588. }
  1589. /* let's try to find a better solution */
  1590. if (depth>=1)
  1591. while (ip<ilimit) {
  1592. ip ++;
  1593. current++;
  1594. /* check repCode */
  1595. if (offset) {
  1596. const U32 repIndex = (U32)(current - rep[0]);
  1597. const BYTE* const repBase = repIndex < dictLimit ? dictBase : base;
  1598. const BYTE* const repMatch = repBase + repIndex;
  1599. if ((U32)((dictLimit-1) - repIndex) >= 3) /* intentional overflow */
  1600. if (MEM_read32(ip) == MEM_read32(repMatch)) {
  1601. /* repcode detected */
  1602. const BYTE* const repEnd = repIndex < dictLimit ? dictEnd : iend;
  1603. size_t const repLength = ZSTD_count_2segments(ip+EQUAL_READ32, repMatch+EQUAL_READ32, iend, repEnd, prefixStart) + EQUAL_READ32;
  1604. int const gain2 = (int)(repLength * 3);
  1605. int const gain1 = (int)(matchLength*3 - ZSTD_highbit((U32)offset+1) + 1);
  1606. if ((repLength >= EQUAL_READ32) && (gain2 > gain1))
  1607. matchLength = repLength, offset = 0, start = ip;
  1608. } }
  1609. /* search match, depth 1 */
  1610. { size_t offset2=99999999;
  1611. size_t const ml2 = searchMax(ctx, ip, iend, &offset2, maxSearches, mls);
  1612. int const gain2 = (int)(ml2*4 - ZSTD_highbit((U32)offset2+1)); /* raw approx */
  1613. int const gain1 = (int)(matchLength*4 - ZSTD_highbit((U32)offset+1) + 4);
  1614. if ((ml2 >= EQUAL_READ32) && (gain2 > gain1)) {
  1615. matchLength = ml2, offset = offset2, start = ip;
  1616. continue; /* search a better one */
  1617. } }
  1618. /* let's find an even better one */
  1619. if ((depth==2) && (ip<ilimit)) {
  1620. ip ++;
  1621. current++;
  1622. /* check repCode */
  1623. if (offset) {
  1624. const U32 repIndex = (U32)(current - rep[0]);
  1625. const BYTE* const repBase = repIndex < dictLimit ? dictBase : base;
  1626. const BYTE* const repMatch = repBase + repIndex;
  1627. if ((U32)((dictLimit-1) - repIndex) >= 3) /* intentional overflow */
  1628. if (MEM_read32(ip) == MEM_read32(repMatch)) {
  1629. /* repcode detected */
  1630. const BYTE* const repEnd = repIndex < dictLimit ? dictEnd : iend;
  1631. size_t repLength = ZSTD_count_2segments(ip+EQUAL_READ32, repMatch+EQUAL_READ32, iend, repEnd, prefixStart) + EQUAL_READ32;
  1632. int gain2 = (int)(repLength * 4);
  1633. int gain1 = (int)(matchLength*4 - ZSTD_highbit((U32)offset+1) + 1);
  1634. if ((repLength >= EQUAL_READ32) && (gain2 > gain1))
  1635. matchLength = repLength, offset = 0, start = ip;
  1636. } }
  1637. /* search match, depth 2 */
  1638. { size_t offset2=99999999;
  1639. size_t const ml2 = searchMax(ctx, ip, iend, &offset2, maxSearches, mls);
  1640. int const gain2 = (int)(ml2*4 - ZSTD_highbit((U32)offset2+1)); /* raw approx */
  1641. int const gain1 = (int)(matchLength*4 - ZSTD_highbit((U32)offset+1) + 7);
  1642. if ((ml2 >= EQUAL_READ32) && (gain2 > gain1)) {
  1643. matchLength = ml2, offset = offset2, start = ip;
  1644. continue;
  1645. } } }
  1646. break; /* nothing found : store previous solution */
  1647. }
  1648. /* catch up */
  1649. if (offset) {
  1650. U32 matchIndex = (U32)((start-base) - (offset - ZSTD_REP_MOVE));
  1651. const BYTE* match = (matchIndex < dictLimit) ? dictBase + matchIndex : base + matchIndex;
  1652. const BYTE* const mStart = (matchIndex < dictLimit) ? dictStart : prefixStart;
  1653. while ((start>anchor) && (match>mStart) && (start[-1] == match[-1])) { start--; match--; matchLength++; } /* catch up */
  1654. rep[1] = rep[0]; rep[0] = (U32)(offset - ZSTD_REP_MOVE);
  1655. }
  1656. /* store sequence */
  1657. _storeSequence:
  1658. { size_t const litLength = start - anchor;
  1659. ZSTD_storeSeq(seqStorePtr, litLength, anchor, offset, matchLength-MINMATCH);
  1660. anchor = ip = start + matchLength;
  1661. }
  1662. /* check immediate repcode */
  1663. while (ip <= ilimit) {
  1664. const U32 repIndex = (U32)((ip-base) - rep[1]);
  1665. const BYTE* const repBase = repIndex < dictLimit ? dictBase : base;
  1666. const BYTE* const repMatch = repBase + repIndex;
  1667. if ((U32)((dictLimit-1) - repIndex) >= 3) /* intentional overflow */
  1668. if (MEM_read32(ip) == MEM_read32(repMatch)) {
  1669. /* repcode detected we should take it */
  1670. const BYTE* const repEnd = repIndex < dictLimit ? dictEnd : iend;
  1671. matchLength = ZSTD_count_2segments(ip+EQUAL_READ32, repMatch+EQUAL_READ32, iend, repEnd, prefixStart) + EQUAL_READ32;
  1672. offset = rep[1]; rep[1] = rep[0]; rep[0] = (U32)offset; /* swap offset history */
  1673. ZSTD_storeSeq(seqStorePtr, 0, anchor, 0, matchLength-MINMATCH);
  1674. ip += matchLength;
  1675. anchor = ip;
  1676. continue; /* faster when present ... (?) */
  1677. }
  1678. break;
  1679. } }
  1680. /* Last Literals */
  1681. { size_t const lastLLSize = iend - anchor;
  1682. memcpy(seqStorePtr->lit, anchor, lastLLSize);
  1683. seqStorePtr->lit += lastLLSize;
  1684. }
  1685. }
  1686. void ZSTD_compressBlock_greedy_extDict(ZSTD_CCtx* ctx, const void* src, size_t srcSize)
  1687. {
  1688. ZSTD_compressBlock_lazy_extDict_generic(ctx, src, srcSize, 0, 0);
  1689. }
  1690. static void ZSTD_compressBlock_lazy_extDict(ZSTD_CCtx* ctx, const void* src, size_t srcSize)
  1691. {
  1692. ZSTD_compressBlock_lazy_extDict_generic(ctx, src, srcSize, 0, 1);
  1693. }
  1694. static void ZSTD_compressBlock_lazy2_extDict(ZSTD_CCtx* ctx, const void* src, size_t srcSize)
  1695. {
  1696. ZSTD_compressBlock_lazy_extDict_generic(ctx, src, srcSize, 0, 2);
  1697. }
  1698. static void ZSTD_compressBlock_btlazy2_extDict(ZSTD_CCtx* ctx, const void* src, size_t srcSize)
  1699. {
  1700. ZSTD_compressBlock_lazy_extDict_generic(ctx, src, srcSize, 1, 2);
  1701. }
  1702. /* The optimal parser */
  1703. #include "zstd_opt.h"
  1704. static void ZSTD_compressBlock_btopt(ZSTD_CCtx* ctx, const void* src, size_t srcSize)
  1705. {
  1706. ZSTD_compressBlock_opt_generic(ctx, src, srcSize);
  1707. }
  1708. static void ZSTD_compressBlock_btopt_extDict(ZSTD_CCtx* ctx, const void* src, size_t srcSize)
  1709. {
  1710. ZSTD_compressBlock_opt_extDict_generic(ctx, src, srcSize);
  1711. }
  1712. typedef void (*ZSTD_blockCompressor) (ZSTD_CCtx* ctx, const void* src, size_t srcSize);
  1713. static ZSTD_blockCompressor ZSTD_selectBlockCompressor(ZSTD_strategy strat, int extDict)
  1714. {
  1715. static const ZSTD_blockCompressor blockCompressor[2][6] = {
  1716. #if 1
  1717. { ZSTD_compressBlock_fast, ZSTD_compressBlock_greedy, ZSTD_compressBlock_lazy, ZSTD_compressBlock_lazy2, ZSTD_compressBlock_btlazy2, ZSTD_compressBlock_btopt },
  1718. #else
  1719. { ZSTD_compressBlock_fast_extDict, ZSTD_compressBlock_greedy_extDict, ZSTD_compressBlock_lazy_extDict,ZSTD_compressBlock_lazy2_extDict, ZSTD_compressBlock_btlazy2_extDict, ZSTD_compressBlock_btopt_extDict },
  1720. #endif
  1721. { ZSTD_compressBlock_fast_extDict, ZSTD_compressBlock_greedy_extDict, ZSTD_compressBlock_lazy_extDict,ZSTD_compressBlock_lazy2_extDict, ZSTD_compressBlock_btlazy2_extDict, ZSTD_compressBlock_btopt_extDict }
  1722. };
  1723. return blockCompressor[extDict][(U32)strat];
  1724. }
  1725. static size_t ZSTD_compressBlock_internal(ZSTD_CCtx* zc, void* dst, size_t dstCapacity, const void* src, size_t srcSize)
  1726. {
  1727. ZSTD_blockCompressor blockCompressor = ZSTD_selectBlockCompressor(zc->params.cParams.strategy, zc->lowLimit < zc->dictLimit);
  1728. if (srcSize < MIN_CBLOCK_SIZE+ZSTD_blockHeaderSize+1) return 0; /* don't even attempt compression below a certain srcSize */
  1729. blockCompressor(zc, src, srcSize);
  1730. return ZSTD_compressSequences(zc, dst, dstCapacity, srcSize);
  1731. }
  1732. static size_t ZSTD_compress_generic (ZSTD_CCtx* zc,
  1733. void* dst, size_t dstCapacity,
  1734. const void* src, size_t srcSize)
  1735. {
  1736. size_t blockSize = zc->blockSize;
  1737. size_t remaining = srcSize;
  1738. const BYTE* ip = (const BYTE*)src;
  1739. BYTE* const ostart = (BYTE*)dst;
  1740. BYTE* op = ostart;
  1741. const U32 maxDist = 1 << zc->params.cParams.windowLog;
  1742. ZSTD_stats_t* stats = &zc->seqStore.stats;
  1743. ZSTD_statsInit(stats);
  1744. while (remaining) {
  1745. size_t cSize;
  1746. ZSTD_statsResetFreqs(stats);
  1747. if (dstCapacity < ZSTD_blockHeaderSize + MIN_CBLOCK_SIZE) return ERROR(dstSize_tooSmall); /* not enough space to store compressed block */
  1748. if (remaining < blockSize) blockSize = remaining;
  1749. if ((U32)(ip+blockSize - zc->base) > zc->loadedDictEnd + maxDist) {
  1750. /* enforce maxDist */
  1751. U32 const newLowLimit = (U32)(ip+blockSize - zc->base) - maxDist;
  1752. if (zc->lowLimit < newLowLimit) zc->lowLimit = newLowLimit;
  1753. if (zc->dictLimit < zc->lowLimit) zc->dictLimit = zc->lowLimit;
  1754. }
  1755. cSize = ZSTD_compressBlock_internal(zc, op+ZSTD_blockHeaderSize, dstCapacity-ZSTD_blockHeaderSize, ip, blockSize);
  1756. if (ZSTD_isError(cSize)) return cSize;
  1757. if (cSize == 0) { /* block is not compressible */
  1758. cSize = ZSTD_noCompressBlock(op, dstCapacity, ip, blockSize);
  1759. if (ZSTD_isError(cSize)) return cSize;
  1760. } else {
  1761. op[0] = (BYTE)(cSize>>16);
  1762. op[1] = (BYTE)(cSize>>8);
  1763. op[2] = (BYTE)cSize;
  1764. op[0] += (BYTE)(bt_compressed << 6); /* is a compressed block */
  1765. cSize += 3;
  1766. }
  1767. remaining -= blockSize;
  1768. dstCapacity -= cSize;
  1769. ip += blockSize;
  1770. op += cSize;
  1771. }
  1772. ZSTD_statsPrint(stats, zc->params.cParams.searchLength);
  1773. return op-ostart;
  1774. }
  1775. static size_t ZSTD_writeFrameHeader(void* dst, size_t dstCapacity,
  1776. ZSTD_parameters params, U64 pledgedSrcSize)
  1777. { BYTE* const op = (BYTE*)dst;
  1778. U32 const fcsId = params.fParams.contentSizeFlag ?
  1779. (pledgedSrcSize>0) + (pledgedSrcSize>=256) + (pledgedSrcSize>=65536+256) : /* 0-3 */
  1780. 0;
  1781. BYTE const fdescriptor = (BYTE)((params.cParams.windowLog - ZSTD_WINDOWLOG_ABSOLUTEMIN) /* windowLog : 4 KB - 128 MB */
  1782. | (fcsId << 6) );
  1783. size_t const hSize = ZSTD_frameHeaderSize_min + ZSTD_fcs_fieldSize[fcsId];
  1784. if (hSize > dstCapacity) return ERROR(dstSize_tooSmall);
  1785. MEM_writeLE32(dst, ZSTD_MAGICNUMBER);
  1786. op[4] = fdescriptor;
  1787. switch(fcsId)
  1788. {
  1789. default: /* impossible */
  1790. case 0 : break;
  1791. case 1 : op[5] = (BYTE)(pledgedSrcSize); break;
  1792. case 2 : MEM_writeLE16(op+5, (U16)(pledgedSrcSize-256)); break;
  1793. case 3 : MEM_writeLE64(op+5, (U64)(pledgedSrcSize)); break;
  1794. }
  1795. return hSize;
  1796. }
  1797. static size_t ZSTD_compressContinue_internal (ZSTD_CCtx* zc,
  1798. void* dst, size_t dstCapacity,
  1799. const void* src, size_t srcSize,
  1800. U32 frame)
  1801. {
  1802. const BYTE* const ip = (const BYTE*) src;
  1803. size_t fhSize = 0;
  1804. if (zc->stage==0) return ERROR(stage_wrong);
  1805. if (frame && (zc->stage==1)) { /* copy saved header */
  1806. fhSize = ZSTD_writeFrameHeader(dst, dstCapacity, zc->params, srcSize);
  1807. if (ZSTD_isError(fhSize)) return fhSize;
  1808. dstCapacity -= fhSize;
  1809. dst = (char*)dst + fhSize;
  1810. zc->stage = 2;
  1811. }
  1812. /* Check if blocks follow each other */
  1813. if (src != zc->nextSrc) {
  1814. /* not contiguous */
  1815. size_t const delta = zc->nextSrc - ip;
  1816. zc->lowLimit = zc->dictLimit;
  1817. zc->dictLimit = (U32)(zc->nextSrc - zc->base);
  1818. zc->dictBase = zc->base;
  1819. zc->base -= delta;
  1820. zc->nextToUpdate = zc->dictLimit;
  1821. if (zc->dictLimit - zc->lowLimit < 8) zc->lowLimit = zc->dictLimit; /* too small extDict */
  1822. }
  1823. /* preemptive overflow correction */
  1824. if (zc->lowLimit > (1<<30)) {
  1825. U32 const btplus = (zc->params.cParams.strategy == ZSTD_btlazy2) || (zc->params.cParams.strategy == ZSTD_btopt);
  1826. U32 const chainMask = (1 << (zc->params.cParams.chainLog - btplus)) - 1;
  1827. U32 const newLowLimit = zc->lowLimit & chainMask; /* preserve position % chainSize */
  1828. U32 const correction = zc->lowLimit - newLowLimit;
  1829. ZSTD_reduceIndex(zc, correction);
  1830. zc->base += correction;
  1831. zc->dictBase += correction;
  1832. zc->lowLimit = newLowLimit;
  1833. zc->dictLimit -= correction;
  1834. if (zc->nextToUpdate < correction) zc->nextToUpdate = 0;
  1835. else zc->nextToUpdate -= correction;
  1836. }
  1837. /* if input and dictionary overlap : reduce dictionary (presumed modified by input) */
  1838. if ((ip+srcSize > zc->dictBase + zc->lowLimit) && (ip < zc->dictBase + zc->dictLimit)) {
  1839. zc->lowLimit = (U32)(ip + srcSize - zc->dictBase);
  1840. if (zc->lowLimit > zc->dictLimit) zc->lowLimit = zc->dictLimit;
  1841. }
  1842. zc->nextSrc = ip + srcSize;
  1843. { size_t const cSize = frame ?
  1844. ZSTD_compress_generic (zc, dst, dstCapacity, src, srcSize) :
  1845. ZSTD_compressBlock_internal (zc, dst, dstCapacity, src, srcSize);
  1846. if (ZSTD_isError(cSize)) return cSize;
  1847. return cSize + fhSize;
  1848. }
  1849. }
  1850. size_t ZSTD_compressContinue (ZSTD_CCtx* zc,
  1851. void* dst, size_t dstCapacity,
  1852. const void* src, size_t srcSize)
  1853. {
  1854. return ZSTD_compressContinue_internal(zc, dst, dstCapacity, src, srcSize, 1);
  1855. }
  1856. size_t ZSTD_compressBlock(ZSTD_CCtx* zc, void* dst, size_t dstCapacity, const void* src, size_t srcSize)
  1857. {
  1858. if (srcSize > ZSTD_BLOCKSIZE_MAX) return ERROR(srcSize_wrong);
  1859. ZSTD_LOG_BLOCK("%p: ZSTD_compressBlock searchLength=%d\n", zc->base, zc->params.cParams.searchLength);
  1860. return ZSTD_compressContinue_internal(zc, dst, dstCapacity, src, srcSize, 0);
  1861. }
  1862. static size_t ZSTD_loadDictionaryContent(ZSTD_CCtx* zc, const void* src, size_t srcSize)
  1863. {
  1864. const BYTE* const ip = (const BYTE*) src;
  1865. const BYTE* const iend = ip + srcSize;
  1866. /* input becomes current prefix */
  1867. zc->lowLimit = zc->dictLimit;
  1868. zc->dictLimit = (U32)(zc->nextSrc - zc->base);
  1869. zc->dictBase = zc->base;
  1870. zc->base += ip - zc->nextSrc;
  1871. zc->nextToUpdate = zc->dictLimit;
  1872. zc->loadedDictEnd = (U32)(iend - zc->base);
  1873. zc->nextSrc = iend;
  1874. if (srcSize <= 8) return 0;
  1875. switch(zc->params.cParams.strategy)
  1876. {
  1877. case ZSTD_fast:
  1878. ZSTD_fillHashTable (zc, iend, zc->params.cParams.searchLength);
  1879. break;
  1880. case ZSTD_greedy:
  1881. case ZSTD_lazy:
  1882. case ZSTD_lazy2:
  1883. ZSTD_insertAndFindFirstIndex (zc, iend-8, zc->params.cParams.searchLength);
  1884. break;
  1885. case ZSTD_btlazy2:
  1886. case ZSTD_btopt:
  1887. ZSTD_updateTree(zc, iend-8, iend, 1 << zc->params.cParams.searchLog, zc->params.cParams.searchLength);
  1888. break;
  1889. default:
  1890. return ERROR(GENERIC); /* strategy doesn't exist; impossible */
  1891. }
  1892. zc->nextToUpdate = zc->loadedDictEnd;
  1893. return 0;
  1894. }
  1895. /* Dictionary format :
  1896. Magic == ZSTD_DICT_MAGIC (4 bytes)
  1897. HUF_writeCTable(256)
  1898. Dictionary content
  1899. */
  1900. /*! ZSTD_loadDictEntropyStats() :
  1901. @return : size read from dictionary */
  1902. static size_t ZSTD_loadDictEntropyStats(ZSTD_CCtx* zc, const void* dict, size_t dictSize)
  1903. {
  1904. /* note : magic number already checked */
  1905. size_t offcodeHeaderSize, matchlengthHeaderSize, litlengthHeaderSize, errorCode;
  1906. short offcodeNCount[MaxOff+1];
  1907. unsigned offcodeMaxValue = MaxOff, offcodeLog = OffFSELog;
  1908. short matchlengthNCount[MaxML+1];
  1909. unsigned matchlengthMaxValue = MaxML, matchlengthLog = MLFSELog;
  1910. short litlengthNCount[MaxLL+1];
  1911. unsigned litlengthMaxValue = MaxLL, litlengthLog = LLFSELog;
  1912. size_t const hufHeaderSize = HUF_readCTable(zc->hufTable, 255, dict, dictSize);
  1913. if (HUF_isError(hufHeaderSize)) return ERROR(dictionary_corrupted);
  1914. zc->flagStaticTables = 1;
  1915. dict = (const char*)dict + hufHeaderSize;
  1916. dictSize -= hufHeaderSize;
  1917. offcodeHeaderSize = FSE_readNCount(offcodeNCount, &offcodeMaxValue, &offcodeLog, dict, dictSize);
  1918. if (FSE_isError(offcodeHeaderSize)) return ERROR(dictionary_corrupted);
  1919. errorCode = FSE_buildCTable(zc->offcodeCTable, offcodeNCount, offcodeMaxValue, offcodeLog);
  1920. if (FSE_isError(errorCode)) return ERROR(dictionary_corrupted);
  1921. dict = (const char*)dict + offcodeHeaderSize;
  1922. dictSize -= offcodeHeaderSize;
  1923. matchlengthHeaderSize = FSE_readNCount(matchlengthNCount, &matchlengthMaxValue, &matchlengthLog, dict, dictSize);
  1924. if (FSE_isError(matchlengthHeaderSize)) return ERROR(dictionary_corrupted);
  1925. errorCode = FSE_buildCTable(zc->matchlengthCTable, matchlengthNCount, matchlengthMaxValue, matchlengthLog);
  1926. if (FSE_isError(errorCode)) return ERROR(dictionary_corrupted);
  1927. dict = (const char*)dict + matchlengthHeaderSize;
  1928. dictSize -= matchlengthHeaderSize;
  1929. litlengthHeaderSize = FSE_readNCount(litlengthNCount, &litlengthMaxValue, &litlengthLog, dict, dictSize);
  1930. if (FSE_isError(litlengthHeaderSize)) return ERROR(dictionary_corrupted);
  1931. errorCode = FSE_buildCTable(zc->litlengthCTable, litlengthNCount, litlengthMaxValue, litlengthLog);
  1932. if (FSE_isError(errorCode)) return ERROR(dictionary_corrupted);
  1933. return hufHeaderSize + offcodeHeaderSize + matchlengthHeaderSize + litlengthHeaderSize;
  1934. }
  1935. /** ZSTD_compress_insertDictionary() :
  1936. * @return : 0, or an error code */
  1937. static size_t ZSTD_compress_insertDictionary(ZSTD_CCtx* zc, const void* dict, size_t dictSize)
  1938. {
  1939. if ((dict==NULL) || (dictSize<=4)) return 0;
  1940. /* default : dict is pure content */
  1941. if (MEM_readLE32(dict) != ZSTD_DICT_MAGIC) return ZSTD_loadDictionaryContent(zc, dict, dictSize);
  1942. /* known magic number : dict is parsed for entropy stats and content */
  1943. { size_t const eSize = ZSTD_loadDictEntropyStats(zc, (const char*)dict+4 /* skip magic */, dictSize-4) + 4;
  1944. if (ZSTD_isError(eSize)) return eSize;
  1945. return ZSTD_loadDictionaryContent(zc, (const char*)dict+eSize, dictSize-eSize);
  1946. }
  1947. }
  1948. /*! ZSTD_compressBegin_internal() :
  1949. * @return : 0, or an error code */
  1950. static size_t ZSTD_compressBegin_internal(ZSTD_CCtx* zc,
  1951. const void* dict, size_t dictSize,
  1952. ZSTD_parameters params, U64 pledgedSrcSize)
  1953. {
  1954. { U32 const hashLog3 = (pledgedSrcSize || pledgedSrcSize >= 8192) ? ZSTD_HASHLOG3_MAX : ((pledgedSrcSize >= 2048) ? ZSTD_HASHLOG3_MIN + 1 : ZSTD_HASHLOG3_MIN);
  1955. zc->hashLog3 = (params.cParams.searchLength==3) ? hashLog3 : 0; }
  1956. { size_t const resetError = ZSTD_resetCCtx_advanced(zc, params, 1);
  1957. if (ZSTD_isError(resetError)) return resetError; }
  1958. return ZSTD_compress_insertDictionary(zc, dict, dictSize);
  1959. }
  1960. /*! ZSTD_compressBegin_advanced() :
  1961. * @return : 0, or an error code */
  1962. size_t ZSTD_compressBegin_advanced(ZSTD_CCtx* zc,
  1963. const void* dict, size_t dictSize,
  1964. ZSTD_parameters params, U64 pledgedSrcSize)
  1965. {
  1966. /* compression parameters verification and optimization */
  1967. { size_t const errorCode = ZSTD_checkCParams_advanced(params.cParams, pledgedSrcSize);
  1968. if (ZSTD_isError(errorCode)) return errorCode; }
  1969. return ZSTD_compressBegin_internal(zc, dict, dictSize, params, pledgedSrcSize);
  1970. }
  1971. size_t ZSTD_compressBegin_usingDict(ZSTD_CCtx* zc, const void* dict, size_t dictSize, int compressionLevel)
  1972. {
  1973. ZSTD_parameters params;
  1974. params.cParams = ZSTD_getCParams(compressionLevel, 0, dictSize);
  1975. params.fParams.contentSizeFlag = 0;
  1976. ZSTD_adjustCParams(&params.cParams, 0, dictSize);
  1977. ZSTD_LOG_BLOCK("%p: ZSTD_compressBegin_usingDict compressionLevel=%d\n", zc->base, compressionLevel);
  1978. return ZSTD_compressBegin_internal(zc, dict, dictSize, params, 0);
  1979. }
  1980. size_t ZSTD_compressBegin(ZSTD_CCtx* zc, int compressionLevel)
  1981. {
  1982. ZSTD_LOG_BLOCK("%p: ZSTD_compressBegin compressionLevel=%d\n", zc->base, compressionLevel);
  1983. return ZSTD_compressBegin_usingDict(zc, NULL, 0, compressionLevel);
  1984. }
  1985. /*! ZSTD_compressEnd() :
  1986. * Write frame epilogue.
  1987. * @return : nb of bytes written into dst (or an error code) */
  1988. size_t ZSTD_compressEnd(ZSTD_CCtx* zc, void* dst, size_t dstCapacity)
  1989. {
  1990. BYTE* op = (BYTE*)dst;
  1991. size_t fhSize = 0;
  1992. /* not even init ! */
  1993. if (zc->stage==0) return ERROR(stage_wrong);
  1994. /* special case : empty frame */
  1995. if (zc->stage==1) {
  1996. fhSize = ZSTD_writeFrameHeader(dst, dstCapacity, zc->params, 0);
  1997. if (ZSTD_isError(fhSize)) return fhSize;
  1998. dstCapacity -= fhSize;
  1999. op += fhSize;
  2000. zc->stage = 2;
  2001. }
  2002. /* frame epilogue */
  2003. if (dstCapacity < 3) return ERROR(dstSize_tooSmall);
  2004. op[0] = (BYTE)(bt_end << 6);
  2005. op[1] = 0;
  2006. op[2] = 0;
  2007. zc->stage = 0; /* return to "created by not init" status */
  2008. return 3+fhSize;
  2009. }
  2010. size_t ZSTD_compress_usingPreparedCCtx(ZSTD_CCtx* cctx, const ZSTD_CCtx* preparedCCtx,
  2011. void* dst, size_t dstCapacity,
  2012. const void* src, size_t srcSize)
  2013. {
  2014. { size_t const errorCode = ZSTD_copyCCtx(cctx, preparedCCtx);
  2015. if (ZSTD_isError(errorCode)) return errorCode;
  2016. }
  2017. { size_t const cSize = ZSTD_compressContinue(cctx, dst, dstCapacity, src, srcSize);
  2018. if (ZSTD_isError(cSize)) return cSize;
  2019. { size_t const endSize = ZSTD_compressEnd(cctx, (char*)dst+cSize, dstCapacity-cSize);
  2020. if (ZSTD_isError(endSize)) return endSize;
  2021. return cSize + endSize;
  2022. } }
  2023. }
  2024. static size_t ZSTD_compress_internal (ZSTD_CCtx* ctx,
  2025. void* dst, size_t dstCapacity,
  2026. const void* src, size_t srcSize,
  2027. const void* dict,size_t dictSize,
  2028. ZSTD_parameters params)
  2029. {
  2030. BYTE* const ostart = (BYTE*)dst;
  2031. BYTE* op = ostart;
  2032. /* Init */
  2033. { size_t const errorCode = ZSTD_compressBegin_internal(ctx, dict, dictSize, params, srcSize);
  2034. if(ZSTD_isError(errorCode)) return errorCode; }
  2035. /* body (compression) */
  2036. { size_t const oSize = ZSTD_compressContinue (ctx, op, dstCapacity, src, srcSize);
  2037. if(ZSTD_isError(oSize)) return oSize;
  2038. op += oSize;
  2039. dstCapacity -= oSize; }
  2040. /* Close frame */
  2041. { size_t const oSize = ZSTD_compressEnd(ctx, op, dstCapacity);
  2042. if(ZSTD_isError(oSize)) return oSize;
  2043. op += oSize; }
  2044. return (op - ostart);
  2045. }
  2046. size_t ZSTD_compress_advanced (ZSTD_CCtx* ctx,
  2047. void* dst, size_t dstCapacity,
  2048. const void* src, size_t srcSize,
  2049. const void* dict,size_t dictSize,
  2050. ZSTD_parameters params)
  2051. {
  2052. size_t const errorCode = ZSTD_checkCParams_advanced(params.cParams, srcSize);
  2053. if (ZSTD_isError(errorCode)) return errorCode;
  2054. return ZSTD_compress_internal(ctx, dst, dstCapacity, src, srcSize, dict, dictSize, params);
  2055. }
  2056. size_t ZSTD_compress_usingDict(ZSTD_CCtx* ctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize, const void* dict, size_t dictSize, int compressionLevel)
  2057. {
  2058. ZSTD_parameters params;
  2059. ZSTD_LOG_BLOCK("%p: ZSTD_compress_usingDict srcSize=%d dictSize=%d compressionLevel=%d\n", ctx->base, (int)srcSize, (int)dictSize, compressionLevel);
  2060. params.cParams = ZSTD_getCParams(compressionLevel, srcSize, dictSize);
  2061. params.fParams.contentSizeFlag = 1;
  2062. ZSTD_adjustCParams(&params.cParams, srcSize, dictSize);
  2063. return ZSTD_compress_internal(ctx, dst, dstCapacity, src, srcSize, dict, dictSize, params);
  2064. }
  2065. size_t ZSTD_compressCCtx (ZSTD_CCtx* ctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize, int compressionLevel)
  2066. {
  2067. ZSTD_LOG_BLOCK("%p: ZSTD_compressCCtx srcSize=%d compressionLevel=%d\n", ctx->base, (int)srcSize, compressionLevel);
  2068. return ZSTD_compress_usingDict(ctx, dst, dstCapacity, src, srcSize, NULL, 0, compressionLevel);
  2069. }
  2070. size_t ZSTD_compress(void* dst, size_t dstCapacity, const void* src, size_t srcSize, int compressionLevel)
  2071. {
  2072. size_t result;
  2073. ZSTD_CCtx ctxBody;
  2074. memset(&ctxBody, 0, sizeof(ctxBody));
  2075. result = ZSTD_compressCCtx(&ctxBody, dst, dstCapacity, src, srcSize, compressionLevel);
  2076. free(ctxBody.workSpace); /* can't free ctxBody, since it's on stack; just free heap content */
  2077. return result;
  2078. }
  2079. /*-===== Pre-defined compression levels =====-*/
  2080. #define ZSTD_DEFAULT_CLEVEL 5
  2081. #define ZSTD_MAX_CLEVEL 22
  2082. unsigned ZSTD_maxCLevel(void) { return ZSTD_MAX_CLEVEL; }
  2083. static const ZSTD_compressionParameters ZSTD_defaultCParameters[4][ZSTD_MAX_CLEVEL+1] = {
  2084. { /* "default" */
  2085. /* W, C, H, S, L, TL, strat */
  2086. { 0, 0, 0, 0, 0, 0, ZSTD_fast }, /* level 0 - never used */
  2087. { 19, 13, 14, 1, 7, 4, ZSTD_fast }, /* level 1 */
  2088. { 19, 15, 16, 1, 6, 4, ZSTD_fast }, /* level 2 */
  2089. { 20, 18, 20, 1, 6, 4, ZSTD_fast }, /* level 3 */
  2090. { 20, 13, 17, 2, 5, 4, ZSTD_greedy }, /* level 4.*/
  2091. { 20, 15, 18, 3, 5, 4, ZSTD_greedy }, /* level 5 */
  2092. { 21, 16, 19, 2, 5, 4, ZSTD_lazy }, /* level 6 */
  2093. { 21, 17, 20, 3, 5, 4, ZSTD_lazy }, /* level 7 */
  2094. { 21, 18, 20, 3, 5, 4, ZSTD_lazy2 }, /* level 8.*/
  2095. { 21, 20, 20, 3, 5, 4, ZSTD_lazy2 }, /* level 9 */
  2096. { 21, 19, 21, 4, 5, 4, ZSTD_lazy2 }, /* level 10 */
  2097. { 22, 20, 22, 4, 5, 4, ZSTD_lazy2 }, /* level 11 */
  2098. { 22, 20, 22, 5, 5, 4, ZSTD_lazy2 }, /* level 12 */
  2099. { 22, 21, 22, 5, 5, 4, ZSTD_lazy2 }, /* level 13 */
  2100. { 22, 21, 22, 6, 5, 4, ZSTD_lazy2 }, /* level 14 */
  2101. { 22, 21, 21, 5, 5, 4, ZSTD_btlazy2 }, /* level 15 */
  2102. { 23, 22, 22, 5, 5, 4, ZSTD_btlazy2 }, /* level 16 */
  2103. { 23, 23, 22, 5, 5, 4, ZSTD_btlazy2 }, /* level 17.*/
  2104. { 23, 23, 22, 6, 5, 24, ZSTD_btopt }, /* level 18.*/
  2105. { 23, 23, 22, 6, 3, 48, ZSTD_btopt }, /* level 19.*/
  2106. { 25, 26, 23, 7, 3, 64, ZSTD_btopt }, /* level 20.*/
  2107. { 26, 26, 23, 7, 3,256, ZSTD_btopt }, /* level 21.*/
  2108. { 27, 27, 25, 9, 3,512, ZSTD_btopt }, /* level 22.*/
  2109. },
  2110. { /* for srcSize <= 256 KB */
  2111. /* W, C, H, S, L, T, strat */
  2112. { 0, 0, 0, 0, 0, 0, ZSTD_fast }, /* level 0 */
  2113. { 18, 13, 14, 1, 6, 4, ZSTD_fast }, /* level 1 */
  2114. { 18, 15, 17, 1, 5, 4, ZSTD_fast }, /* level 2 */
  2115. { 18, 13, 15, 1, 5, 4, ZSTD_greedy }, /* level 3.*/
  2116. { 18, 15, 17, 1, 5, 4, ZSTD_greedy }, /* level 4.*/
  2117. { 18, 16, 17, 4, 5, 4, ZSTD_greedy }, /* level 5 */
  2118. { 18, 17, 17, 5, 5, 4, ZSTD_greedy }, /* level 6 */
  2119. { 18, 17, 17, 4, 4, 4, ZSTD_lazy }, /* level 7 */
  2120. { 18, 17, 17, 4, 4, 4, ZSTD_lazy2 }, /* level 8 */
  2121. { 18, 17, 17, 5, 4, 4, ZSTD_lazy2 }, /* level 9 */
  2122. { 18, 17, 17, 6, 4, 4, ZSTD_lazy2 }, /* level 10 */
  2123. { 18, 18, 17, 6, 4, 4, ZSTD_lazy2 }, /* level 11.*/
  2124. { 18, 18, 17, 7, 4, 4, ZSTD_lazy2 }, /* level 12.*/
  2125. { 18, 19, 17, 7, 4, 4, ZSTD_btlazy2 }, /* level 13 */
  2126. { 18, 18, 18, 4, 4, 16, ZSTD_btopt }, /* level 14.*/
  2127. { 18, 18, 18, 8, 4, 24, ZSTD_btopt }, /* level 15.*/
  2128. { 18, 19, 18, 8, 3, 48, ZSTD_btopt }, /* level 16.*/
  2129. { 18, 19, 18, 8, 3, 96, ZSTD_btopt }, /* level 17.*/
  2130. { 18, 19, 18, 9, 3,128, ZSTD_btopt }, /* level 18.*/
  2131. { 18, 19, 18, 10, 3,256, ZSTD_btopt }, /* level 19.*/
  2132. { 18, 19, 18, 11, 3,512, ZSTD_btopt }, /* level 20.*/
  2133. { 18, 19, 18, 12, 3,512, ZSTD_btopt }, /* level 21.*/
  2134. { 18, 19, 18, 13, 3,512, ZSTD_btopt }, /* level 22.*/
  2135. },
  2136. { /* for srcSize <= 128 KB */
  2137. /* W, C, H, S, L, T, strat */
  2138. { 0, 0, 0, 0, 0, 0, ZSTD_fast }, /* level 0 - never used */
  2139. { 17, 12, 13, 1, 6, 4, ZSTD_fast }, /* level 1 */
  2140. { 17, 13, 16, 1, 5, 4, ZSTD_fast }, /* level 2 */
  2141. { 17, 13, 14, 2, 5, 4, ZSTD_greedy }, /* level 3 */
  2142. { 17, 13, 15, 3, 4, 4, ZSTD_greedy }, /* level 4 */
  2143. { 17, 15, 17, 4, 4, 4, ZSTD_greedy }, /* level 5 */
  2144. { 17, 16, 17, 3, 4, 4, ZSTD_lazy }, /* level 6 */
  2145. { 17, 15, 17, 4, 4, 4, ZSTD_lazy2 }, /* level 7 */
  2146. { 17, 17, 17, 4, 4, 4, ZSTD_lazy2 }, /* level 8 */
  2147. { 17, 17, 17, 5, 4, 4, ZSTD_lazy2 }, /* level 9 */
  2148. { 17, 17, 17, 6, 4, 4, ZSTD_lazy2 }, /* level 10 */
  2149. { 17, 17, 17, 7, 4, 4, ZSTD_lazy2 }, /* level 11 */
  2150. { 17, 17, 17, 8, 4, 4, ZSTD_lazy2 }, /* level 12 */
  2151. { 17, 18, 17, 6, 4, 4, ZSTD_btlazy2 }, /* level 13.*/
  2152. { 17, 17, 17, 7, 3, 8, ZSTD_btopt }, /* level 14.*/
  2153. { 17, 17, 17, 7, 3, 16, ZSTD_btopt }, /* level 15.*/
  2154. { 17, 18, 17, 7, 3, 32, ZSTD_btopt }, /* level 16.*/
  2155. { 17, 18, 17, 7, 3, 64, ZSTD_btopt }, /* level 17.*/
  2156. { 17, 18, 17, 7, 3,256, ZSTD_btopt }, /* level 18.*/
  2157. { 17, 18, 17, 8, 3,256, ZSTD_btopt }, /* level 19.*/
  2158. { 17, 18, 17, 9, 3,256, ZSTD_btopt }, /* level 20.*/
  2159. { 17, 18, 17, 10, 3,256, ZSTD_btopt }, /* level 21.*/
  2160. { 17, 18, 17, 11, 3,256, ZSTD_btopt }, /* level 22.*/
  2161. },
  2162. { /* for srcSize <= 16 KB */
  2163. /* W, C, H, S, L, T, strat */
  2164. { 0, 0, 0, 0, 0, 0, ZSTD_fast }, /* level 0 -- never used */
  2165. { 14, 14, 14, 1, 4, 4, ZSTD_fast }, /* level 1 */
  2166. { 14, 14, 15, 1, 4, 4, ZSTD_fast }, /* level 2 */
  2167. { 14, 14, 14, 4, 4, 4, ZSTD_greedy }, /* level 3.*/
  2168. { 14, 14, 14, 3, 4, 4, ZSTD_lazy }, /* level 4.*/
  2169. { 14, 14, 14, 4, 4, 4, ZSTD_lazy2 }, /* level 5 */
  2170. { 14, 14, 14, 5, 4, 4, ZSTD_lazy2 }, /* level 6 */
  2171. { 14, 14, 14, 6, 4, 4, ZSTD_lazy2 }, /* level 7.*/
  2172. { 14, 14, 14, 7, 4, 4, ZSTD_lazy2 }, /* level 8.*/
  2173. { 14, 15, 14, 6, 4, 4, ZSTD_btlazy2 }, /* level 9.*/
  2174. { 14, 15, 14, 3, 3, 6, ZSTD_btopt }, /* level 10.*/
  2175. { 14, 15, 14, 6, 3, 8, ZSTD_btopt }, /* level 11.*/
  2176. { 14, 15, 14, 6, 3, 16, ZSTD_btopt }, /* level 12.*/
  2177. { 14, 15, 14, 6, 3, 24, ZSTD_btopt }, /* level 13.*/
  2178. { 14, 15, 15, 6, 3, 48, ZSTD_btopt }, /* level 14.*/
  2179. { 14, 15, 15, 6, 3, 64, ZSTD_btopt }, /* level 15.*/
  2180. { 14, 15, 15, 6, 3, 96, ZSTD_btopt }, /* level 16.*/
  2181. { 14, 15, 15, 6, 3,128, ZSTD_btopt }, /* level 17.*/
  2182. { 14, 15, 15, 6, 3,256, ZSTD_btopt }, /* level 18.*/
  2183. { 14, 15, 15, 7, 3,256, ZSTD_btopt }, /* level 19.*/
  2184. { 14, 15, 15, 8, 3,256, ZSTD_btopt }, /* level 20.*/
  2185. { 14, 15, 15, 9, 3,256, ZSTD_btopt }, /* level 21.*/
  2186. { 14, 15, 15, 10, 3,256, ZSTD_btopt }, /* level 22.*/
  2187. },
  2188. };
  2189. /*! ZSTD_getParams() :
  2190. * @return ZSTD_parameters structure for a selected compression level and srcSize.
  2191. * `srcSize` value is optional, select 0 if not known */
  2192. ZSTD_compressionParameters ZSTD_getCParams(int compressionLevel, U64 srcSize, size_t dictSize)
  2193. {
  2194. ZSTD_compressionParameters cp;
  2195. size_t const addedSize = srcSize ? 0 : 500;
  2196. U64 const rSize = srcSize+dictSize ? srcSize+dictSize+addedSize : (U64)-1;
  2197. U32 const tableID = (rSize <= 256 KB) + (rSize <= 128 KB) + (rSize <= 16 KB); /* intentional underflow for srcSizeHint == 0 */
  2198. if (compressionLevel < 0) compressionLevel = ZSTD_DEFAULT_CLEVEL;
  2199. if (compressionLevel==0) compressionLevel = 1;
  2200. if (compressionLevel > ZSTD_MAX_CLEVEL) compressionLevel = ZSTD_MAX_CLEVEL;
  2201. cp = ZSTD_defaultCParameters[tableID][compressionLevel];
  2202. if (MEM_32bits()) { /* auto-correction, for 32-bits mode */
  2203. if (cp.windowLog > ZSTD_WINDOWLOG_MAX) cp.windowLog = ZSTD_WINDOWLOG_MAX;
  2204. if (cp.chainLog > ZSTD_CHAINLOG_MAX) cp.chainLog = ZSTD_CHAINLOG_MAX;
  2205. if (cp.hashLog > ZSTD_HASHLOG_MAX) cp.hashLog = ZSTD_HASHLOG_MAX;
  2206. }
  2207. return cp;
  2208. }