zstd_lazy.c 100 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157
  1. /*
  2. * Copyright (c) Meta Platforms, Inc. and affiliates.
  3. * All rights reserved.
  4. *
  5. * This source code is licensed under both the BSD-style license (found in the
  6. * LICENSE file in the root directory of this source tree) and the GPLv2 (found
  7. * in the COPYING file in the root directory of this source tree).
  8. * You may select, at your option, one of the above-listed licenses.
  9. */
  10. #include "zstd_compress_internal.h"
  11. #include "zstd_lazy.h"
  12. #include "../common/bits.h" /* ZSTD_countTrailingZeros64 */
  13. #define kLazySkippingStep 8
  14. /*-*************************************
  15. * Binary Tree search
  16. ***************************************/
  17. static void
  18. ZSTD_updateDUBT(ZSTD_matchState_t* ms,
  19. const BYTE* ip, const BYTE* iend,
  20. U32 mls)
  21. {
  22. const ZSTD_compressionParameters* const cParams = &ms->cParams;
  23. U32* const hashTable = ms->hashTable;
  24. U32 const hashLog = cParams->hashLog;
  25. U32* const bt = ms->chainTable;
  26. U32 const btLog = cParams->chainLog - 1;
  27. U32 const btMask = (1 << btLog) - 1;
  28. const BYTE* const base = ms->window.base;
  29. U32 const target = (U32)(ip - base);
  30. U32 idx = ms->nextToUpdate;
  31. if (idx != target)
  32. DEBUGLOG(7, "ZSTD_updateDUBT, from %u to %u (dictLimit:%u)",
  33. idx, target, ms->window.dictLimit);
  34. assert(ip + 8 <= iend); /* condition for ZSTD_hashPtr */
  35. (void)iend;
  36. assert(idx >= ms->window.dictLimit); /* condition for valid base+idx */
  37. for ( ; idx < target ; idx++) {
  38. size_t const h = ZSTD_hashPtr(base + idx, hashLog, mls); /* assumption : ip + 8 <= iend */
  39. U32 const matchIndex = hashTable[h];
  40. U32* const nextCandidatePtr = bt + 2*(idx&btMask);
  41. U32* const sortMarkPtr = nextCandidatePtr + 1;
  42. DEBUGLOG(8, "ZSTD_updateDUBT: insert %u", idx);
  43. hashTable[h] = idx; /* Update Hash Table */
  44. *nextCandidatePtr = matchIndex; /* update BT like a chain */
  45. *sortMarkPtr = ZSTD_DUBT_UNSORTED_MARK;
  46. }
  47. ms->nextToUpdate = target;
  48. }
  49. /** ZSTD_insertDUBT1() :
  50. * sort one already inserted but unsorted position
  51. * assumption : curr >= btlow == (curr - btmask)
  52. * doesn't fail */
  53. static void
  54. ZSTD_insertDUBT1(const ZSTD_matchState_t* ms,
  55. U32 curr, const BYTE* inputEnd,
  56. U32 nbCompares, U32 btLow,
  57. const ZSTD_dictMode_e dictMode)
  58. {
  59. const ZSTD_compressionParameters* const cParams = &ms->cParams;
  60. U32* const bt = ms->chainTable;
  61. U32 const btLog = cParams->chainLog - 1;
  62. U32 const btMask = (1 << btLog) - 1;
  63. size_t commonLengthSmaller=0, commonLengthLarger=0;
  64. const BYTE* const base = ms->window.base;
  65. const BYTE* const dictBase = ms->window.dictBase;
  66. const U32 dictLimit = ms->window.dictLimit;
  67. const BYTE* const ip = (curr>=dictLimit) ? base + curr : dictBase + curr;
  68. const BYTE* const iend = (curr>=dictLimit) ? inputEnd : dictBase + dictLimit;
  69. const BYTE* const dictEnd = dictBase + dictLimit;
  70. const BYTE* const prefixStart = base + dictLimit;
  71. const BYTE* match;
  72. U32* smallerPtr = bt + 2*(curr&btMask);
  73. U32* largerPtr = smallerPtr + 1;
  74. U32 matchIndex = *smallerPtr; /* this candidate is unsorted : next sorted candidate is reached through *smallerPtr, while *largerPtr contains previous unsorted candidate (which is already saved and can be overwritten) */
  75. U32 dummy32; /* to be nullified at the end */
  76. U32 const windowValid = ms->window.lowLimit;
  77. U32 const maxDistance = 1U << cParams->windowLog;
  78. U32 const windowLow = (curr - windowValid > maxDistance) ? curr - maxDistance : windowValid;
  79. DEBUGLOG(8, "ZSTD_insertDUBT1(%u) (dictLimit=%u, lowLimit=%u)",
  80. curr, dictLimit, windowLow);
  81. assert(curr >= btLow);
  82. assert(ip < iend); /* condition for ZSTD_count */
  83. for (; nbCompares && (matchIndex > windowLow); --nbCompares) {
  84. U32* const nextPtr = bt + 2*(matchIndex & btMask);
  85. size_t matchLength = MIN(commonLengthSmaller, commonLengthLarger); /* guaranteed minimum nb of common bytes */
  86. assert(matchIndex < curr);
  87. /* note : all candidates are now supposed sorted,
  88. * but it's still possible to have nextPtr[1] == ZSTD_DUBT_UNSORTED_MARK
  89. * when a real index has the same value as ZSTD_DUBT_UNSORTED_MARK */
  90. if ( (dictMode != ZSTD_extDict)
  91. || (matchIndex+matchLength >= dictLimit) /* both in current segment*/
  92. || (curr < dictLimit) /* both in extDict */) {
  93. const BYTE* const mBase = ( (dictMode != ZSTD_extDict)
  94. || (matchIndex+matchLength >= dictLimit)) ?
  95. base : dictBase;
  96. assert( (matchIndex+matchLength >= dictLimit) /* might be wrong if extDict is incorrectly set to 0 */
  97. || (curr < dictLimit) );
  98. match = mBase + matchIndex;
  99. matchLength += ZSTD_count(ip+matchLength, match+matchLength, iend);
  100. } else {
  101. match = dictBase + matchIndex;
  102. matchLength += ZSTD_count_2segments(ip+matchLength, match+matchLength, iend, dictEnd, prefixStart);
  103. if (matchIndex+matchLength >= dictLimit)
  104. match = base + matchIndex; /* preparation for next read of match[matchLength] */
  105. }
  106. DEBUGLOG(8, "ZSTD_insertDUBT1: comparing %u with %u : found %u common bytes ",
  107. curr, matchIndex, (U32)matchLength);
  108. if (ip+matchLength == iend) { /* equal : no way to know if inf or sup */
  109. break; /* drop , to guarantee consistency ; miss a bit of compression, but other solutions can corrupt tree */
  110. }
  111. if (match[matchLength] < ip[matchLength]) { /* necessarily within buffer */
  112. /* match is smaller than current */
  113. *smallerPtr = matchIndex; /* update smaller idx */
  114. commonLengthSmaller = matchLength; /* all smaller will now have at least this guaranteed common length */
  115. if (matchIndex <= btLow) { smallerPtr=&dummy32; break; } /* beyond tree size, stop searching */
  116. DEBUGLOG(8, "ZSTD_insertDUBT1: %u (>btLow=%u) is smaller : next => %u",
  117. matchIndex, btLow, nextPtr[1]);
  118. smallerPtr = nextPtr+1; /* new "candidate" => larger than match, which was smaller than target */
  119. matchIndex = nextPtr[1]; /* new matchIndex, larger than previous and closer to current */
  120. } else {
  121. /* match is larger than current */
  122. *largerPtr = matchIndex;
  123. commonLengthLarger = matchLength;
  124. if (matchIndex <= btLow) { largerPtr=&dummy32; break; } /* beyond tree size, stop searching */
  125. DEBUGLOG(8, "ZSTD_insertDUBT1: %u (>btLow=%u) is larger => %u",
  126. matchIndex, btLow, nextPtr[0]);
  127. largerPtr = nextPtr;
  128. matchIndex = nextPtr[0];
  129. } }
  130. *smallerPtr = *largerPtr = 0;
  131. }
  132. static size_t
  133. ZSTD_DUBT_findBetterDictMatch (
  134. const ZSTD_matchState_t* ms,
  135. const BYTE* const ip, const BYTE* const iend,
  136. size_t* offsetPtr,
  137. size_t bestLength,
  138. U32 nbCompares,
  139. U32 const mls,
  140. const ZSTD_dictMode_e dictMode)
  141. {
  142. const ZSTD_matchState_t * const dms = ms->dictMatchState;
  143. const ZSTD_compressionParameters* const dmsCParams = &dms->cParams;
  144. const U32 * const dictHashTable = dms->hashTable;
  145. U32 const hashLog = dmsCParams->hashLog;
  146. size_t const h = ZSTD_hashPtr(ip, hashLog, mls);
  147. U32 dictMatchIndex = dictHashTable[h];
  148. const BYTE* const base = ms->window.base;
  149. const BYTE* const prefixStart = base + ms->window.dictLimit;
  150. U32 const curr = (U32)(ip-base);
  151. const BYTE* const dictBase = dms->window.base;
  152. const BYTE* const dictEnd = dms->window.nextSrc;
  153. U32 const dictHighLimit = (U32)(dms->window.nextSrc - dms->window.base);
  154. U32 const dictLowLimit = dms->window.lowLimit;
  155. U32 const dictIndexDelta = ms->window.lowLimit - dictHighLimit;
  156. U32* const dictBt = dms->chainTable;
  157. U32 const btLog = dmsCParams->chainLog - 1;
  158. U32 const btMask = (1 << btLog) - 1;
  159. U32 const btLow = (btMask >= dictHighLimit - dictLowLimit) ? dictLowLimit : dictHighLimit - btMask;
  160. size_t commonLengthSmaller=0, commonLengthLarger=0;
  161. (void)dictMode;
  162. assert(dictMode == ZSTD_dictMatchState);
  163. for (; nbCompares && (dictMatchIndex > dictLowLimit); --nbCompares) {
  164. U32* const nextPtr = dictBt + 2*(dictMatchIndex & btMask);
  165. size_t matchLength = MIN(commonLengthSmaller, commonLengthLarger); /* guaranteed minimum nb of common bytes */
  166. const BYTE* match = dictBase + dictMatchIndex;
  167. matchLength += ZSTD_count_2segments(ip+matchLength, match+matchLength, iend, dictEnd, prefixStart);
  168. if (dictMatchIndex+matchLength >= dictHighLimit)
  169. match = base + dictMatchIndex + dictIndexDelta; /* to prepare for next usage of match[matchLength] */
  170. if (matchLength > bestLength) {
  171. U32 matchIndex = dictMatchIndex + dictIndexDelta;
  172. if ( (4*(int)(matchLength-bestLength)) > (int)(ZSTD_highbit32(curr-matchIndex+1) - ZSTD_highbit32((U32)offsetPtr[0]+1)) ) {
  173. DEBUGLOG(9, "ZSTD_DUBT_findBetterDictMatch(%u) : found better match length %u -> %u and offsetCode %u -> %u (dictMatchIndex %u, matchIndex %u)",
  174. curr, (U32)bestLength, (U32)matchLength, (U32)*offsetPtr, OFFSET_TO_OFFBASE(curr - matchIndex), dictMatchIndex, matchIndex);
  175. bestLength = matchLength, *offsetPtr = OFFSET_TO_OFFBASE(curr - matchIndex);
  176. }
  177. if (ip+matchLength == iend) { /* reached end of input : ip[matchLength] is not valid, no way to know if it's larger or smaller than match */
  178. break; /* drop, to guarantee consistency (miss a little bit of compression) */
  179. }
  180. }
  181. if (match[matchLength] < ip[matchLength]) {
  182. if (dictMatchIndex <= btLow) { break; } /* beyond tree size, stop the search */
  183. commonLengthSmaller = matchLength; /* all smaller will now have at least this guaranteed common length */
  184. dictMatchIndex = nextPtr[1]; /* new matchIndex larger than previous (closer to current) */
  185. } else {
  186. /* match is larger than current */
  187. if (dictMatchIndex <= btLow) { break; } /* beyond tree size, stop the search */
  188. commonLengthLarger = matchLength;
  189. dictMatchIndex = nextPtr[0];
  190. }
  191. }
  192. if (bestLength >= MINMATCH) {
  193. U32 const mIndex = curr - (U32)OFFBASE_TO_OFFSET(*offsetPtr); (void)mIndex;
  194. DEBUGLOG(8, "ZSTD_DUBT_findBetterDictMatch(%u) : found match of length %u and offsetCode %u (pos %u)",
  195. curr, (U32)bestLength, (U32)*offsetPtr, mIndex);
  196. }
  197. return bestLength;
  198. }
  199. static size_t
  200. ZSTD_DUBT_findBestMatch(ZSTD_matchState_t* ms,
  201. const BYTE* const ip, const BYTE* const iend,
  202. size_t* offBasePtr,
  203. U32 const mls,
  204. const ZSTD_dictMode_e dictMode)
  205. {
  206. const ZSTD_compressionParameters* const cParams = &ms->cParams;
  207. U32* const hashTable = ms->hashTable;
  208. U32 const hashLog = cParams->hashLog;
  209. size_t const h = ZSTD_hashPtr(ip, hashLog, mls);
  210. U32 matchIndex = hashTable[h];
  211. const BYTE* const base = ms->window.base;
  212. U32 const curr = (U32)(ip-base);
  213. U32 const windowLow = ZSTD_getLowestMatchIndex(ms, curr, cParams->windowLog);
  214. U32* const bt = ms->chainTable;
  215. U32 const btLog = cParams->chainLog - 1;
  216. U32 const btMask = (1 << btLog) - 1;
  217. U32 const btLow = (btMask >= curr) ? 0 : curr - btMask;
  218. U32 const unsortLimit = MAX(btLow, windowLow);
  219. U32* nextCandidate = bt + 2*(matchIndex&btMask);
  220. U32* unsortedMark = bt + 2*(matchIndex&btMask) + 1;
  221. U32 nbCompares = 1U << cParams->searchLog;
  222. U32 nbCandidates = nbCompares;
  223. U32 previousCandidate = 0;
  224. DEBUGLOG(7, "ZSTD_DUBT_findBestMatch (%u) ", curr);
  225. assert(ip <= iend-8); /* required for h calculation */
  226. assert(dictMode != ZSTD_dedicatedDictSearch);
  227. /* reach end of unsorted candidates list */
  228. while ( (matchIndex > unsortLimit)
  229. && (*unsortedMark == ZSTD_DUBT_UNSORTED_MARK)
  230. && (nbCandidates > 1) ) {
  231. DEBUGLOG(8, "ZSTD_DUBT_findBestMatch: candidate %u is unsorted",
  232. matchIndex);
  233. *unsortedMark = previousCandidate; /* the unsortedMark becomes a reversed chain, to move up back to original position */
  234. previousCandidate = matchIndex;
  235. matchIndex = *nextCandidate;
  236. nextCandidate = bt + 2*(matchIndex&btMask);
  237. unsortedMark = bt + 2*(matchIndex&btMask) + 1;
  238. nbCandidates --;
  239. }
  240. /* nullify last candidate if it's still unsorted
  241. * simplification, detrimental to compression ratio, beneficial for speed */
  242. if ( (matchIndex > unsortLimit)
  243. && (*unsortedMark==ZSTD_DUBT_UNSORTED_MARK) ) {
  244. DEBUGLOG(7, "ZSTD_DUBT_findBestMatch: nullify last unsorted candidate %u",
  245. matchIndex);
  246. *nextCandidate = *unsortedMark = 0;
  247. }
  248. /* batch sort stacked candidates */
  249. matchIndex = previousCandidate;
  250. while (matchIndex) { /* will end on matchIndex == 0 */
  251. U32* const nextCandidateIdxPtr = bt + 2*(matchIndex&btMask) + 1;
  252. U32 const nextCandidateIdx = *nextCandidateIdxPtr;
  253. ZSTD_insertDUBT1(ms, matchIndex, iend,
  254. nbCandidates, unsortLimit, dictMode);
  255. matchIndex = nextCandidateIdx;
  256. nbCandidates++;
  257. }
  258. /* find longest match */
  259. { size_t commonLengthSmaller = 0, commonLengthLarger = 0;
  260. const BYTE* const dictBase = ms->window.dictBase;
  261. const U32 dictLimit = ms->window.dictLimit;
  262. const BYTE* const dictEnd = dictBase + dictLimit;
  263. const BYTE* const prefixStart = base + dictLimit;
  264. U32* smallerPtr = bt + 2*(curr&btMask);
  265. U32* largerPtr = bt + 2*(curr&btMask) + 1;
  266. U32 matchEndIdx = curr + 8 + 1;
  267. U32 dummy32; /* to be nullified at the end */
  268. size_t bestLength = 0;
  269. matchIndex = hashTable[h];
  270. hashTable[h] = curr; /* Update Hash Table */
  271. for (; nbCompares && (matchIndex > windowLow); --nbCompares) {
  272. U32* const nextPtr = bt + 2*(matchIndex & btMask);
  273. size_t matchLength = MIN(commonLengthSmaller, commonLengthLarger); /* guaranteed minimum nb of common bytes */
  274. const BYTE* match;
  275. if ((dictMode != ZSTD_extDict) || (matchIndex+matchLength >= dictLimit)) {
  276. match = base + matchIndex;
  277. matchLength += ZSTD_count(ip+matchLength, match+matchLength, iend);
  278. } else {
  279. match = dictBase + matchIndex;
  280. matchLength += ZSTD_count_2segments(ip+matchLength, match+matchLength, iend, dictEnd, prefixStart);
  281. if (matchIndex+matchLength >= dictLimit)
  282. match = base + matchIndex; /* to prepare for next usage of match[matchLength] */
  283. }
  284. if (matchLength > bestLength) {
  285. if (matchLength > matchEndIdx - matchIndex)
  286. matchEndIdx = matchIndex + (U32)matchLength;
  287. if ( (4*(int)(matchLength-bestLength)) > (int)(ZSTD_highbit32(curr - matchIndex + 1) - ZSTD_highbit32((U32)*offBasePtr)) )
  288. bestLength = matchLength, *offBasePtr = OFFSET_TO_OFFBASE(curr - matchIndex);
  289. if (ip+matchLength == iend) { /* equal : no way to know if inf or sup */
  290. if (dictMode == ZSTD_dictMatchState) {
  291. nbCompares = 0; /* in addition to avoiding checking any
  292. * further in this loop, make sure we
  293. * skip checking in the dictionary. */
  294. }
  295. break; /* drop, to guarantee consistency (miss a little bit of compression) */
  296. }
  297. }
  298. if (match[matchLength] < ip[matchLength]) {
  299. /* match is smaller than current */
  300. *smallerPtr = matchIndex; /* update smaller idx */
  301. commonLengthSmaller = matchLength; /* all smaller will now have at least this guaranteed common length */
  302. if (matchIndex <= btLow) { smallerPtr=&dummy32; break; } /* beyond tree size, stop the search */
  303. smallerPtr = nextPtr+1; /* new "smaller" => larger of match */
  304. matchIndex = nextPtr[1]; /* new matchIndex larger than previous (closer to current) */
  305. } else {
  306. /* match is larger than current */
  307. *largerPtr = matchIndex;
  308. commonLengthLarger = matchLength;
  309. if (matchIndex <= btLow) { largerPtr=&dummy32; break; } /* beyond tree size, stop the search */
  310. largerPtr = nextPtr;
  311. matchIndex = nextPtr[0];
  312. } }
  313. *smallerPtr = *largerPtr = 0;
  314. assert(nbCompares <= (1U << ZSTD_SEARCHLOG_MAX)); /* Check we haven't underflowed. */
  315. if (dictMode == ZSTD_dictMatchState && nbCompares) {
  316. bestLength = ZSTD_DUBT_findBetterDictMatch(
  317. ms, ip, iend,
  318. offBasePtr, bestLength, nbCompares,
  319. mls, dictMode);
  320. }
  321. assert(matchEndIdx > curr+8); /* ensure nextToUpdate is increased */
  322. ms->nextToUpdate = matchEndIdx - 8; /* skip repetitive patterns */
  323. if (bestLength >= MINMATCH) {
  324. U32 const mIndex = curr - (U32)OFFBASE_TO_OFFSET(*offBasePtr); (void)mIndex;
  325. DEBUGLOG(8, "ZSTD_DUBT_findBestMatch(%u) : found match of length %u and offsetCode %u (pos %u)",
  326. curr, (U32)bestLength, (U32)*offBasePtr, mIndex);
  327. }
  328. return bestLength;
  329. }
  330. }
  331. /** ZSTD_BtFindBestMatch() : Tree updater, providing best match */
  332. FORCE_INLINE_TEMPLATE size_t
  333. ZSTD_BtFindBestMatch( ZSTD_matchState_t* ms,
  334. const BYTE* const ip, const BYTE* const iLimit,
  335. size_t* offBasePtr,
  336. const U32 mls /* template */,
  337. const ZSTD_dictMode_e dictMode)
  338. {
  339. DEBUGLOG(7, "ZSTD_BtFindBestMatch");
  340. if (ip < ms->window.base + ms->nextToUpdate) return 0; /* skipped area */
  341. ZSTD_updateDUBT(ms, ip, iLimit, mls);
  342. return ZSTD_DUBT_findBestMatch(ms, ip, iLimit, offBasePtr, mls, dictMode);
  343. }
  344. /***********************************
  345. * Dedicated dict search
  346. ***********************************/
  347. void ZSTD_dedicatedDictSearch_lazy_loadDictionary(ZSTD_matchState_t* ms, const BYTE* const ip)
  348. {
  349. const BYTE* const base = ms->window.base;
  350. U32 const target = (U32)(ip - base);
  351. U32* const hashTable = ms->hashTable;
  352. U32* const chainTable = ms->chainTable;
  353. U32 const chainSize = 1 << ms->cParams.chainLog;
  354. U32 idx = ms->nextToUpdate;
  355. U32 const minChain = chainSize < target - idx ? target - chainSize : idx;
  356. U32 const bucketSize = 1 << ZSTD_LAZY_DDSS_BUCKET_LOG;
  357. U32 const cacheSize = bucketSize - 1;
  358. U32 const chainAttempts = (1 << ms->cParams.searchLog) - cacheSize;
  359. U32 const chainLimit = chainAttempts > 255 ? 255 : chainAttempts;
  360. /* We know the hashtable is oversized by a factor of `bucketSize`.
  361. * We are going to temporarily pretend `bucketSize == 1`, keeping only a
  362. * single entry. We will use the rest of the space to construct a temporary
  363. * chaintable.
  364. */
  365. U32 const hashLog = ms->cParams.hashLog - ZSTD_LAZY_DDSS_BUCKET_LOG;
  366. U32* const tmpHashTable = hashTable;
  367. U32* const tmpChainTable = hashTable + ((size_t)1 << hashLog);
  368. U32 const tmpChainSize = (U32)((1 << ZSTD_LAZY_DDSS_BUCKET_LOG) - 1) << hashLog;
  369. U32 const tmpMinChain = tmpChainSize < target ? target - tmpChainSize : idx;
  370. U32 hashIdx;
  371. assert(ms->cParams.chainLog <= 24);
  372. assert(ms->cParams.hashLog > ms->cParams.chainLog);
  373. assert(idx != 0);
  374. assert(tmpMinChain <= minChain);
  375. /* fill conventional hash table and conventional chain table */
  376. for ( ; idx < target; idx++) {
  377. U32 const h = (U32)ZSTD_hashPtr(base + idx, hashLog, ms->cParams.minMatch);
  378. if (idx >= tmpMinChain) {
  379. tmpChainTable[idx - tmpMinChain] = hashTable[h];
  380. }
  381. tmpHashTable[h] = idx;
  382. }
  383. /* sort chains into ddss chain table */
  384. {
  385. U32 chainPos = 0;
  386. for (hashIdx = 0; hashIdx < (1U << hashLog); hashIdx++) {
  387. U32 count;
  388. U32 countBeyondMinChain = 0;
  389. U32 i = tmpHashTable[hashIdx];
  390. for (count = 0; i >= tmpMinChain && count < cacheSize; count++) {
  391. /* skip through the chain to the first position that won't be
  392. * in the hash cache bucket */
  393. if (i < minChain) {
  394. countBeyondMinChain++;
  395. }
  396. i = tmpChainTable[i - tmpMinChain];
  397. }
  398. if (count == cacheSize) {
  399. for (count = 0; count < chainLimit;) {
  400. if (i < minChain) {
  401. if (!i || ++countBeyondMinChain > cacheSize) {
  402. /* only allow pulling `cacheSize` number of entries
  403. * into the cache or chainTable beyond `minChain`,
  404. * to replace the entries pulled out of the
  405. * chainTable into the cache. This lets us reach
  406. * back further without increasing the total number
  407. * of entries in the chainTable, guaranteeing the
  408. * DDSS chain table will fit into the space
  409. * allocated for the regular one. */
  410. break;
  411. }
  412. }
  413. chainTable[chainPos++] = i;
  414. count++;
  415. if (i < tmpMinChain) {
  416. break;
  417. }
  418. i = tmpChainTable[i - tmpMinChain];
  419. }
  420. } else {
  421. count = 0;
  422. }
  423. if (count) {
  424. tmpHashTable[hashIdx] = ((chainPos - count) << 8) + count;
  425. } else {
  426. tmpHashTable[hashIdx] = 0;
  427. }
  428. }
  429. assert(chainPos <= chainSize); /* I believe this is guaranteed... */
  430. }
  431. /* move chain pointers into the last entry of each hash bucket */
  432. for (hashIdx = (1 << hashLog); hashIdx; ) {
  433. U32 const bucketIdx = --hashIdx << ZSTD_LAZY_DDSS_BUCKET_LOG;
  434. U32 const chainPackedPointer = tmpHashTable[hashIdx];
  435. U32 i;
  436. for (i = 0; i < cacheSize; i++) {
  437. hashTable[bucketIdx + i] = 0;
  438. }
  439. hashTable[bucketIdx + bucketSize - 1] = chainPackedPointer;
  440. }
  441. /* fill the buckets of the hash table */
  442. for (idx = ms->nextToUpdate; idx < target; idx++) {
  443. U32 const h = (U32)ZSTD_hashPtr(base + idx, hashLog, ms->cParams.minMatch)
  444. << ZSTD_LAZY_DDSS_BUCKET_LOG;
  445. U32 i;
  446. /* Shift hash cache down 1. */
  447. for (i = cacheSize - 1; i; i--)
  448. hashTable[h + i] = hashTable[h + i - 1];
  449. hashTable[h] = idx;
  450. }
  451. ms->nextToUpdate = target;
  452. }
  453. /* Returns the longest match length found in the dedicated dict search structure.
  454. * If none are longer than the argument ml, then ml will be returned.
  455. */
  456. FORCE_INLINE_TEMPLATE
  457. size_t ZSTD_dedicatedDictSearch_lazy_search(size_t* offsetPtr, size_t ml, U32 nbAttempts,
  458. const ZSTD_matchState_t* const dms,
  459. const BYTE* const ip, const BYTE* const iLimit,
  460. const BYTE* const prefixStart, const U32 curr,
  461. const U32 dictLimit, const size_t ddsIdx) {
  462. const U32 ddsLowestIndex = dms->window.dictLimit;
  463. const BYTE* const ddsBase = dms->window.base;
  464. const BYTE* const ddsEnd = dms->window.nextSrc;
  465. const U32 ddsSize = (U32)(ddsEnd - ddsBase);
  466. const U32 ddsIndexDelta = dictLimit - ddsSize;
  467. const U32 bucketSize = (1 << ZSTD_LAZY_DDSS_BUCKET_LOG);
  468. const U32 bucketLimit = nbAttempts < bucketSize - 1 ? nbAttempts : bucketSize - 1;
  469. U32 ddsAttempt;
  470. U32 matchIndex;
  471. for (ddsAttempt = 0; ddsAttempt < bucketSize - 1; ddsAttempt++) {
  472. PREFETCH_L1(ddsBase + dms->hashTable[ddsIdx + ddsAttempt]);
  473. }
  474. {
  475. U32 const chainPackedPointer = dms->hashTable[ddsIdx + bucketSize - 1];
  476. U32 const chainIndex = chainPackedPointer >> 8;
  477. PREFETCH_L1(&dms->chainTable[chainIndex]);
  478. }
  479. for (ddsAttempt = 0; ddsAttempt < bucketLimit; ddsAttempt++) {
  480. size_t currentMl=0;
  481. const BYTE* match;
  482. matchIndex = dms->hashTable[ddsIdx + ddsAttempt];
  483. match = ddsBase + matchIndex;
  484. if (!matchIndex) {
  485. return ml;
  486. }
  487. /* guaranteed by table construction */
  488. (void)ddsLowestIndex;
  489. assert(matchIndex >= ddsLowestIndex);
  490. assert(match+4 <= ddsEnd);
  491. if (MEM_read32(match) == MEM_read32(ip)) {
  492. /* assumption : matchIndex <= dictLimit-4 (by table construction) */
  493. currentMl = ZSTD_count_2segments(ip+4, match+4, iLimit, ddsEnd, prefixStart) + 4;
  494. }
  495. /* save best solution */
  496. if (currentMl > ml) {
  497. ml = currentMl;
  498. *offsetPtr = OFFSET_TO_OFFBASE(curr - (matchIndex + ddsIndexDelta));
  499. if (ip+currentMl == iLimit) {
  500. /* best possible, avoids read overflow on next attempt */
  501. return ml;
  502. }
  503. }
  504. }
  505. {
  506. U32 const chainPackedPointer = dms->hashTable[ddsIdx + bucketSize - 1];
  507. U32 chainIndex = chainPackedPointer >> 8;
  508. U32 const chainLength = chainPackedPointer & 0xFF;
  509. U32 const chainAttempts = nbAttempts - ddsAttempt;
  510. U32 const chainLimit = chainAttempts > chainLength ? chainLength : chainAttempts;
  511. U32 chainAttempt;
  512. for (chainAttempt = 0 ; chainAttempt < chainLimit; chainAttempt++) {
  513. PREFETCH_L1(ddsBase + dms->chainTable[chainIndex + chainAttempt]);
  514. }
  515. for (chainAttempt = 0 ; chainAttempt < chainLimit; chainAttempt++, chainIndex++) {
  516. size_t currentMl=0;
  517. const BYTE* match;
  518. matchIndex = dms->chainTable[chainIndex];
  519. match = ddsBase + matchIndex;
  520. /* guaranteed by table construction */
  521. assert(matchIndex >= ddsLowestIndex);
  522. assert(match+4 <= ddsEnd);
  523. if (MEM_read32(match) == MEM_read32(ip)) {
  524. /* assumption : matchIndex <= dictLimit-4 (by table construction) */
  525. currentMl = ZSTD_count_2segments(ip+4, match+4, iLimit, ddsEnd, prefixStart) + 4;
  526. }
  527. /* save best solution */
  528. if (currentMl > ml) {
  529. ml = currentMl;
  530. *offsetPtr = OFFSET_TO_OFFBASE(curr - (matchIndex + ddsIndexDelta));
  531. if (ip+currentMl == iLimit) break; /* best possible, avoids read overflow on next attempt */
  532. }
  533. }
  534. }
  535. return ml;
  536. }
  537. /* *********************************
  538. * Hash Chain
  539. ***********************************/
  540. #define NEXT_IN_CHAIN(d, mask) chainTable[(d) & (mask)]
  541. /* Update chains up to ip (excluded)
  542. Assumption : always within prefix (i.e. not within extDict) */
  543. FORCE_INLINE_TEMPLATE U32 ZSTD_insertAndFindFirstIndex_internal(
  544. ZSTD_matchState_t* ms,
  545. const ZSTD_compressionParameters* const cParams,
  546. const BYTE* ip, U32 const mls, U32 const lazySkipping)
  547. {
  548. U32* const hashTable = ms->hashTable;
  549. const U32 hashLog = cParams->hashLog;
  550. U32* const chainTable = ms->chainTable;
  551. const U32 chainMask = (1 << cParams->chainLog) - 1;
  552. const BYTE* const base = ms->window.base;
  553. const U32 target = (U32)(ip - base);
  554. U32 idx = ms->nextToUpdate;
  555. while(idx < target) { /* catch up */
  556. size_t const h = ZSTD_hashPtr(base+idx, hashLog, mls);
  557. NEXT_IN_CHAIN(idx, chainMask) = hashTable[h];
  558. hashTable[h] = idx;
  559. idx++;
  560. /* Stop inserting every position when in the lazy skipping mode. */
  561. if (lazySkipping)
  562. break;
  563. }
  564. ms->nextToUpdate = target;
  565. return hashTable[ZSTD_hashPtr(ip, hashLog, mls)];
  566. }
  567. U32 ZSTD_insertAndFindFirstIndex(ZSTD_matchState_t* ms, const BYTE* ip) {
  568. const ZSTD_compressionParameters* const cParams = &ms->cParams;
  569. return ZSTD_insertAndFindFirstIndex_internal(ms, cParams, ip, ms->cParams.minMatch, /* lazySkipping*/ 0);
  570. }
  571. /* inlining is important to hardwire a hot branch (template emulation) */
  572. FORCE_INLINE_TEMPLATE
  573. size_t ZSTD_HcFindBestMatch(
  574. ZSTD_matchState_t* ms,
  575. const BYTE* const ip, const BYTE* const iLimit,
  576. size_t* offsetPtr,
  577. const U32 mls, const ZSTD_dictMode_e dictMode)
  578. {
  579. const ZSTD_compressionParameters* const cParams = &ms->cParams;
  580. U32* const chainTable = ms->chainTable;
  581. const U32 chainSize = (1 << cParams->chainLog);
  582. const U32 chainMask = chainSize-1;
  583. const BYTE* const base = ms->window.base;
  584. const BYTE* const dictBase = ms->window.dictBase;
  585. const U32 dictLimit = ms->window.dictLimit;
  586. const BYTE* const prefixStart = base + dictLimit;
  587. const BYTE* const dictEnd = dictBase + dictLimit;
  588. const U32 curr = (U32)(ip-base);
  589. const U32 maxDistance = 1U << cParams->windowLog;
  590. const U32 lowestValid = ms->window.lowLimit;
  591. const U32 withinMaxDistance = (curr - lowestValid > maxDistance) ? curr - maxDistance : lowestValid;
  592. const U32 isDictionary = (ms->loadedDictEnd != 0);
  593. const U32 lowLimit = isDictionary ? lowestValid : withinMaxDistance;
  594. const U32 minChain = curr > chainSize ? curr - chainSize : 0;
  595. U32 nbAttempts = 1U << cParams->searchLog;
  596. size_t ml=4-1;
  597. const ZSTD_matchState_t* const dms = ms->dictMatchState;
  598. const U32 ddsHashLog = dictMode == ZSTD_dedicatedDictSearch
  599. ? dms->cParams.hashLog - ZSTD_LAZY_DDSS_BUCKET_LOG : 0;
  600. const size_t ddsIdx = dictMode == ZSTD_dedicatedDictSearch
  601. ? ZSTD_hashPtr(ip, ddsHashLog, mls) << ZSTD_LAZY_DDSS_BUCKET_LOG : 0;
  602. U32 matchIndex;
  603. if (dictMode == ZSTD_dedicatedDictSearch) {
  604. const U32* entry = &dms->hashTable[ddsIdx];
  605. PREFETCH_L1(entry);
  606. }
  607. /* HC4 match finder */
  608. matchIndex = ZSTD_insertAndFindFirstIndex_internal(ms, cParams, ip, mls, ms->lazySkipping);
  609. for ( ; (matchIndex>=lowLimit) & (nbAttempts>0) ; nbAttempts--) {
  610. size_t currentMl=0;
  611. if ((dictMode != ZSTD_extDict) || matchIndex >= dictLimit) {
  612. const BYTE* const match = base + matchIndex;
  613. assert(matchIndex >= dictLimit); /* ensures this is true if dictMode != ZSTD_extDict */
  614. /* read 4B starting from (match + ml + 1 - sizeof(U32)) */
  615. if (MEM_read32(match + ml - 3) == MEM_read32(ip + ml - 3)) /* potentially better */
  616. currentMl = ZSTD_count(ip, match, iLimit);
  617. } else {
  618. const BYTE* const match = dictBase + matchIndex;
  619. assert(match+4 <= dictEnd);
  620. if (MEM_read32(match) == MEM_read32(ip)) /* assumption : matchIndex <= dictLimit-4 (by table construction) */
  621. currentMl = ZSTD_count_2segments(ip+4, match+4, iLimit, dictEnd, prefixStart) + 4;
  622. }
  623. /* save best solution */
  624. if (currentMl > ml) {
  625. ml = currentMl;
  626. *offsetPtr = OFFSET_TO_OFFBASE(curr - matchIndex);
  627. if (ip+currentMl == iLimit) break; /* best possible, avoids read overflow on next attempt */
  628. }
  629. if (matchIndex <= minChain) break;
  630. matchIndex = NEXT_IN_CHAIN(matchIndex, chainMask);
  631. }
  632. assert(nbAttempts <= (1U << ZSTD_SEARCHLOG_MAX)); /* Check we haven't underflowed. */
  633. if (dictMode == ZSTD_dedicatedDictSearch) {
  634. ml = ZSTD_dedicatedDictSearch_lazy_search(offsetPtr, ml, nbAttempts, dms,
  635. ip, iLimit, prefixStart, curr, dictLimit, ddsIdx);
  636. } else if (dictMode == ZSTD_dictMatchState) {
  637. const U32* const dmsChainTable = dms->chainTable;
  638. const U32 dmsChainSize = (1 << dms->cParams.chainLog);
  639. const U32 dmsChainMask = dmsChainSize - 1;
  640. const U32 dmsLowestIndex = dms->window.dictLimit;
  641. const BYTE* const dmsBase = dms->window.base;
  642. const BYTE* const dmsEnd = dms->window.nextSrc;
  643. const U32 dmsSize = (U32)(dmsEnd - dmsBase);
  644. const U32 dmsIndexDelta = dictLimit - dmsSize;
  645. const U32 dmsMinChain = dmsSize > dmsChainSize ? dmsSize - dmsChainSize : 0;
  646. matchIndex = dms->hashTable[ZSTD_hashPtr(ip, dms->cParams.hashLog, mls)];
  647. for ( ; (matchIndex>=dmsLowestIndex) & (nbAttempts>0) ; nbAttempts--) {
  648. size_t currentMl=0;
  649. const BYTE* const match = dmsBase + matchIndex;
  650. assert(match+4 <= dmsEnd);
  651. if (MEM_read32(match) == MEM_read32(ip)) /* assumption : matchIndex <= dictLimit-4 (by table construction) */
  652. currentMl = ZSTD_count_2segments(ip+4, match+4, iLimit, dmsEnd, prefixStart) + 4;
  653. /* save best solution */
  654. if (currentMl > ml) {
  655. ml = currentMl;
  656. assert(curr > matchIndex + dmsIndexDelta);
  657. *offsetPtr = OFFSET_TO_OFFBASE(curr - (matchIndex + dmsIndexDelta));
  658. if (ip+currentMl == iLimit) break; /* best possible, avoids read overflow on next attempt */
  659. }
  660. if (matchIndex <= dmsMinChain) break;
  661. matchIndex = dmsChainTable[matchIndex & dmsChainMask];
  662. }
  663. }
  664. return ml;
  665. }
  666. /* *********************************
  667. * (SIMD) Row-based matchfinder
  668. ***********************************/
  669. /* Constants for row-based hash */
  670. #define ZSTD_ROW_HASH_TAG_MASK ((1u << ZSTD_ROW_HASH_TAG_BITS) - 1)
  671. #define ZSTD_ROW_HASH_MAX_ENTRIES 64 /* absolute maximum number of entries per row, for all configurations */
  672. #define ZSTD_ROW_HASH_CACHE_MASK (ZSTD_ROW_HASH_CACHE_SIZE - 1)
  673. typedef U64 ZSTD_VecMask; /* Clarifies when we are interacting with a U64 representing a mask of matches */
  674. /* ZSTD_VecMask_next():
  675. * Starting from the LSB, returns the idx of the next non-zero bit.
  676. * Basically counting the nb of trailing zeroes.
  677. */
  678. MEM_STATIC U32 ZSTD_VecMask_next(ZSTD_VecMask val) {
  679. return ZSTD_countTrailingZeros64(val);
  680. }
  681. /* ZSTD_row_nextIndex():
  682. * Returns the next index to insert at within a tagTable row, and updates the "head"
  683. * value to reflect the update. Essentially cycles backwards from [1, {entries per row})
  684. */
  685. FORCE_INLINE_TEMPLATE U32 ZSTD_row_nextIndex(BYTE* const tagRow, U32 const rowMask) {
  686. U32 next = (*tagRow-1) & rowMask;
  687. next += (next == 0) ? rowMask : 0; /* skip first position */
  688. *tagRow = (BYTE)next;
  689. return next;
  690. }
  691. /* ZSTD_isAligned():
  692. * Checks that a pointer is aligned to "align" bytes which must be a power of 2.
  693. */
  694. MEM_STATIC int ZSTD_isAligned(void const* ptr, size_t align) {
  695. assert((align & (align - 1)) == 0);
  696. return (((size_t)ptr) & (align - 1)) == 0;
  697. }
  698. /* ZSTD_row_prefetch():
  699. * Performs prefetching for the hashTable and tagTable at a given row.
  700. */
  701. FORCE_INLINE_TEMPLATE void ZSTD_row_prefetch(U32 const* hashTable, BYTE const* tagTable, U32 const relRow, U32 const rowLog) {
  702. PREFETCH_L1(hashTable + relRow);
  703. if (rowLog >= 5) {
  704. PREFETCH_L1(hashTable + relRow + 16);
  705. /* Note: prefetching more of the hash table does not appear to be beneficial for 128-entry rows */
  706. }
  707. PREFETCH_L1(tagTable + relRow);
  708. if (rowLog == 6) {
  709. PREFETCH_L1(tagTable + relRow + 32);
  710. }
  711. assert(rowLog == 4 || rowLog == 5 || rowLog == 6);
  712. assert(ZSTD_isAligned(hashTable + relRow, 64)); /* prefetched hash row always 64-byte aligned */
  713. assert(ZSTD_isAligned(tagTable + relRow, (size_t)1 << rowLog)); /* prefetched tagRow sits on correct multiple of bytes (32,64,128) */
  714. }
  715. /* ZSTD_row_fillHashCache():
  716. * Fill up the hash cache starting at idx, prefetching up to ZSTD_ROW_HASH_CACHE_SIZE entries,
  717. * but not beyond iLimit.
  718. */
  719. FORCE_INLINE_TEMPLATE void ZSTD_row_fillHashCache(ZSTD_matchState_t* ms, const BYTE* base,
  720. U32 const rowLog, U32 const mls,
  721. U32 idx, const BYTE* const iLimit)
  722. {
  723. U32 const* const hashTable = ms->hashTable;
  724. BYTE const* const tagTable = ms->tagTable;
  725. U32 const hashLog = ms->rowHashLog;
  726. U32 const maxElemsToPrefetch = (base + idx) > iLimit ? 0 : (U32)(iLimit - (base + idx) + 1);
  727. U32 const lim = idx + MIN(ZSTD_ROW_HASH_CACHE_SIZE, maxElemsToPrefetch);
  728. for (; idx < lim; ++idx) {
  729. U32 const hash = (U32)ZSTD_hashPtrSalted(base + idx, hashLog + ZSTD_ROW_HASH_TAG_BITS, mls, ms->hashSalt);
  730. U32 const row = (hash >> ZSTD_ROW_HASH_TAG_BITS) << rowLog;
  731. ZSTD_row_prefetch(hashTable, tagTable, row, rowLog);
  732. ms->hashCache[idx & ZSTD_ROW_HASH_CACHE_MASK] = hash;
  733. }
  734. DEBUGLOG(6, "ZSTD_row_fillHashCache(): [%u %u %u %u %u %u %u %u]", ms->hashCache[0], ms->hashCache[1],
  735. ms->hashCache[2], ms->hashCache[3], ms->hashCache[4],
  736. ms->hashCache[5], ms->hashCache[6], ms->hashCache[7]);
  737. }
  738. /* ZSTD_row_nextCachedHash():
  739. * Returns the hash of base + idx, and replaces the hash in the hash cache with the byte at
  740. * base + idx + ZSTD_ROW_HASH_CACHE_SIZE. Also prefetches the appropriate rows from hashTable and tagTable.
  741. */
  742. FORCE_INLINE_TEMPLATE U32 ZSTD_row_nextCachedHash(U32* cache, U32 const* hashTable,
  743. BYTE const* tagTable, BYTE const* base,
  744. U32 idx, U32 const hashLog,
  745. U32 const rowLog, U32 const mls,
  746. U64 const hashSalt)
  747. {
  748. U32 const newHash = (U32)ZSTD_hashPtrSalted(base+idx+ZSTD_ROW_HASH_CACHE_SIZE, hashLog + ZSTD_ROW_HASH_TAG_BITS, mls, hashSalt);
  749. U32 const row = (newHash >> ZSTD_ROW_HASH_TAG_BITS) << rowLog;
  750. ZSTD_row_prefetch(hashTable, tagTable, row, rowLog);
  751. { U32 const hash = cache[idx & ZSTD_ROW_HASH_CACHE_MASK];
  752. cache[idx & ZSTD_ROW_HASH_CACHE_MASK] = newHash;
  753. return hash;
  754. }
  755. }
  756. /* ZSTD_row_update_internalImpl():
  757. * Updates the hash table with positions starting from updateStartIdx until updateEndIdx.
  758. */
  759. FORCE_INLINE_TEMPLATE void ZSTD_row_update_internalImpl(ZSTD_matchState_t* ms,
  760. U32 updateStartIdx, U32 const updateEndIdx,
  761. U32 const mls, U32 const rowLog,
  762. U32 const rowMask, U32 const useCache)
  763. {
  764. U32* const hashTable = ms->hashTable;
  765. BYTE* const tagTable = ms->tagTable;
  766. U32 const hashLog = ms->rowHashLog;
  767. const BYTE* const base = ms->window.base;
  768. DEBUGLOG(6, "ZSTD_row_update_internalImpl(): updateStartIdx=%u, updateEndIdx=%u", updateStartIdx, updateEndIdx);
  769. for (; updateStartIdx < updateEndIdx; ++updateStartIdx) {
  770. U32 const hash = useCache ? ZSTD_row_nextCachedHash(ms->hashCache, hashTable, tagTable, base, updateStartIdx, hashLog, rowLog, mls, ms->hashSalt)
  771. : (U32)ZSTD_hashPtrSalted(base + updateStartIdx, hashLog + ZSTD_ROW_HASH_TAG_BITS, mls, ms->hashSalt);
  772. U32 const relRow = (hash >> ZSTD_ROW_HASH_TAG_BITS) << rowLog;
  773. U32* const row = hashTable + relRow;
  774. BYTE* tagRow = tagTable + relRow;
  775. U32 const pos = ZSTD_row_nextIndex(tagRow, rowMask);
  776. assert(hash == ZSTD_hashPtrSalted(base + updateStartIdx, hashLog + ZSTD_ROW_HASH_TAG_BITS, mls, ms->hashSalt));
  777. tagRow[pos] = hash & ZSTD_ROW_HASH_TAG_MASK;
  778. row[pos] = updateStartIdx;
  779. }
  780. }
  781. /* ZSTD_row_update_internal():
  782. * Inserts the byte at ip into the appropriate position in the hash table, and updates ms->nextToUpdate.
  783. * Skips sections of long matches as is necessary.
  784. */
  785. FORCE_INLINE_TEMPLATE void ZSTD_row_update_internal(ZSTD_matchState_t* ms, const BYTE* ip,
  786. U32 const mls, U32 const rowLog,
  787. U32 const rowMask, U32 const useCache)
  788. {
  789. U32 idx = ms->nextToUpdate;
  790. const BYTE* const base = ms->window.base;
  791. const U32 target = (U32)(ip - base);
  792. const U32 kSkipThreshold = 384;
  793. const U32 kMaxMatchStartPositionsToUpdate = 96;
  794. const U32 kMaxMatchEndPositionsToUpdate = 32;
  795. if (useCache) {
  796. /* Only skip positions when using hash cache, i.e.
  797. * if we are loading a dict, don't skip anything.
  798. * If we decide to skip, then we only update a set number
  799. * of positions at the beginning and end of the match.
  800. */
  801. if (UNLIKELY(target - idx > kSkipThreshold)) {
  802. U32 const bound = idx + kMaxMatchStartPositionsToUpdate;
  803. ZSTD_row_update_internalImpl(ms, idx, bound, mls, rowLog, rowMask, useCache);
  804. idx = target - kMaxMatchEndPositionsToUpdate;
  805. ZSTD_row_fillHashCache(ms, base, rowLog, mls, idx, ip+1);
  806. }
  807. }
  808. assert(target >= idx);
  809. ZSTD_row_update_internalImpl(ms, idx, target, mls, rowLog, rowMask, useCache);
  810. ms->nextToUpdate = target;
  811. }
  812. /* ZSTD_row_update():
  813. * External wrapper for ZSTD_row_update_internal(). Used for filling the hashtable during dictionary
  814. * processing.
  815. */
  816. void ZSTD_row_update(ZSTD_matchState_t* const ms, const BYTE* ip) {
  817. const U32 rowLog = BOUNDED(4, ms->cParams.searchLog, 6);
  818. const U32 rowMask = (1u << rowLog) - 1;
  819. const U32 mls = MIN(ms->cParams.minMatch, 6 /* mls caps out at 6 */);
  820. DEBUGLOG(5, "ZSTD_row_update(), rowLog=%u", rowLog);
  821. ZSTD_row_update_internal(ms, ip, mls, rowLog, rowMask, 0 /* don't use cache */);
  822. }
  823. /* Returns the mask width of bits group of which will be set to 1. Given not all
  824. * architectures have easy movemask instruction, this helps to iterate over
  825. * groups of bits easier and faster.
  826. */
  827. FORCE_INLINE_TEMPLATE U32
  828. ZSTD_row_matchMaskGroupWidth(const U32 rowEntries)
  829. {
  830. assert((rowEntries == 16) || (rowEntries == 32) || rowEntries == 64);
  831. assert(rowEntries <= ZSTD_ROW_HASH_MAX_ENTRIES);
  832. (void)rowEntries;
  833. #if defined(ZSTD_ARCH_ARM_NEON)
  834. /* NEON path only works for little endian */
  835. if (!MEM_isLittleEndian()) {
  836. return 1;
  837. }
  838. if (rowEntries == 16) {
  839. return 4;
  840. }
  841. if (rowEntries == 32) {
  842. return 2;
  843. }
  844. if (rowEntries == 64) {
  845. return 1;
  846. }
  847. #endif
  848. return 1;
  849. }
  850. #if defined(ZSTD_ARCH_X86_SSE2)
  851. FORCE_INLINE_TEMPLATE ZSTD_VecMask
  852. ZSTD_row_getSSEMask(int nbChunks, const BYTE* const src, const BYTE tag, const U32 head)
  853. {
  854. const __m128i comparisonMask = _mm_set1_epi8((char)tag);
  855. int matches[4] = {0};
  856. int i;
  857. assert(nbChunks == 1 || nbChunks == 2 || nbChunks == 4);
  858. for (i=0; i<nbChunks; i++) {
  859. const __m128i chunk = _mm_loadu_si128((const __m128i*)(const void*)(src + 16*i));
  860. const __m128i equalMask = _mm_cmpeq_epi8(chunk, comparisonMask);
  861. matches[i] = _mm_movemask_epi8(equalMask);
  862. }
  863. if (nbChunks == 1) return ZSTD_rotateRight_U16((U16)matches[0], head);
  864. if (nbChunks == 2) return ZSTD_rotateRight_U32((U32)matches[1] << 16 | (U32)matches[0], head);
  865. assert(nbChunks == 4);
  866. return ZSTD_rotateRight_U64((U64)matches[3] << 48 | (U64)matches[2] << 32 | (U64)matches[1] << 16 | (U64)matches[0], head);
  867. }
  868. #endif
  869. #if defined(ZSTD_ARCH_ARM_NEON)
  870. FORCE_INLINE_TEMPLATE ZSTD_VecMask
  871. ZSTD_row_getNEONMask(const U32 rowEntries, const BYTE* const src, const BYTE tag, const U32 headGrouped)
  872. {
  873. assert((rowEntries == 16) || (rowEntries == 32) || rowEntries == 64);
  874. if (rowEntries == 16) {
  875. /* vshrn_n_u16 shifts by 4 every u16 and narrows to 8 lower bits.
  876. * After that groups of 4 bits represent the equalMask. We lower
  877. * all bits except the highest in these groups by doing AND with
  878. * 0x88 = 0b10001000.
  879. */
  880. const uint8x16_t chunk = vld1q_u8(src);
  881. const uint16x8_t equalMask = vreinterpretq_u16_u8(vceqq_u8(chunk, vdupq_n_u8(tag)));
  882. const uint8x8_t res = vshrn_n_u16(equalMask, 4);
  883. const U64 matches = vget_lane_u64(vreinterpret_u64_u8(res), 0);
  884. return ZSTD_rotateRight_U64(matches, headGrouped) & 0x8888888888888888ull;
  885. } else if (rowEntries == 32) {
  886. /* Same idea as with rowEntries == 16 but doing AND with
  887. * 0x55 = 0b01010101.
  888. */
  889. const uint16x8x2_t chunk = vld2q_u16((const uint16_t*)(const void*)src);
  890. const uint8x16_t chunk0 = vreinterpretq_u8_u16(chunk.val[0]);
  891. const uint8x16_t chunk1 = vreinterpretq_u8_u16(chunk.val[1]);
  892. const uint8x16_t dup = vdupq_n_u8(tag);
  893. const uint8x8_t t0 = vshrn_n_u16(vreinterpretq_u16_u8(vceqq_u8(chunk0, dup)), 6);
  894. const uint8x8_t t1 = vshrn_n_u16(vreinterpretq_u16_u8(vceqq_u8(chunk1, dup)), 6);
  895. const uint8x8_t res = vsli_n_u8(t0, t1, 4);
  896. const U64 matches = vget_lane_u64(vreinterpret_u64_u8(res), 0) ;
  897. return ZSTD_rotateRight_U64(matches, headGrouped) & 0x5555555555555555ull;
  898. } else { /* rowEntries == 64 */
  899. const uint8x16x4_t chunk = vld4q_u8(src);
  900. const uint8x16_t dup = vdupq_n_u8(tag);
  901. const uint8x16_t cmp0 = vceqq_u8(chunk.val[0], dup);
  902. const uint8x16_t cmp1 = vceqq_u8(chunk.val[1], dup);
  903. const uint8x16_t cmp2 = vceqq_u8(chunk.val[2], dup);
  904. const uint8x16_t cmp3 = vceqq_u8(chunk.val[3], dup);
  905. const uint8x16_t t0 = vsriq_n_u8(cmp1, cmp0, 1);
  906. const uint8x16_t t1 = vsriq_n_u8(cmp3, cmp2, 1);
  907. const uint8x16_t t2 = vsriq_n_u8(t1, t0, 2);
  908. const uint8x16_t t3 = vsriq_n_u8(t2, t2, 4);
  909. const uint8x8_t t4 = vshrn_n_u16(vreinterpretq_u16_u8(t3), 4);
  910. const U64 matches = vget_lane_u64(vreinterpret_u64_u8(t4), 0);
  911. return ZSTD_rotateRight_U64(matches, headGrouped);
  912. }
  913. }
  914. #endif
  915. /* Returns a ZSTD_VecMask (U64) that has the nth group (determined by
  916. * ZSTD_row_matchMaskGroupWidth) of bits set to 1 if the newly-computed "tag"
  917. * matches the hash at the nth position in a row of the tagTable.
  918. * Each row is a circular buffer beginning at the value of "headGrouped". So we
  919. * must rotate the "matches" bitfield to match up with the actual layout of the
  920. * entries within the hashTable */
  921. FORCE_INLINE_TEMPLATE ZSTD_VecMask
  922. ZSTD_row_getMatchMask(const BYTE* const tagRow, const BYTE tag, const U32 headGrouped, const U32 rowEntries)
  923. {
  924. const BYTE* const src = tagRow;
  925. assert((rowEntries == 16) || (rowEntries == 32) || rowEntries == 64);
  926. assert(rowEntries <= ZSTD_ROW_HASH_MAX_ENTRIES);
  927. assert(ZSTD_row_matchMaskGroupWidth(rowEntries) * rowEntries <= sizeof(ZSTD_VecMask) * 8);
  928. #if defined(ZSTD_ARCH_X86_SSE2)
  929. return ZSTD_row_getSSEMask(rowEntries / 16, src, tag, headGrouped);
  930. #else /* SW or NEON-LE */
  931. # if defined(ZSTD_ARCH_ARM_NEON)
  932. /* This NEON path only works for little endian - otherwise use SWAR below */
  933. if (MEM_isLittleEndian()) {
  934. return ZSTD_row_getNEONMask(rowEntries, src, tag, headGrouped);
  935. }
  936. # endif /* ZSTD_ARCH_ARM_NEON */
  937. /* SWAR */
  938. { const int chunkSize = sizeof(size_t);
  939. const size_t shiftAmount = ((chunkSize * 8) - chunkSize);
  940. const size_t xFF = ~((size_t)0);
  941. const size_t x01 = xFF / 0xFF;
  942. const size_t x80 = x01 << 7;
  943. const size_t splatChar = tag * x01;
  944. ZSTD_VecMask matches = 0;
  945. int i = rowEntries - chunkSize;
  946. assert((sizeof(size_t) == 4) || (sizeof(size_t) == 8));
  947. if (MEM_isLittleEndian()) { /* runtime check so have two loops */
  948. const size_t extractMagic = (xFF / 0x7F) >> chunkSize;
  949. do {
  950. size_t chunk = MEM_readST(&src[i]);
  951. chunk ^= splatChar;
  952. chunk = (((chunk | x80) - x01) | chunk) & x80;
  953. matches <<= chunkSize;
  954. matches |= (chunk * extractMagic) >> shiftAmount;
  955. i -= chunkSize;
  956. } while (i >= 0);
  957. } else { /* big endian: reverse bits during extraction */
  958. const size_t msb = xFF ^ (xFF >> 1);
  959. const size_t extractMagic = (msb / 0x1FF) | msb;
  960. do {
  961. size_t chunk = MEM_readST(&src[i]);
  962. chunk ^= splatChar;
  963. chunk = (((chunk | x80) - x01) | chunk) & x80;
  964. matches <<= chunkSize;
  965. matches |= ((chunk >> 7) * extractMagic) >> shiftAmount;
  966. i -= chunkSize;
  967. } while (i >= 0);
  968. }
  969. matches = ~matches;
  970. if (rowEntries == 16) {
  971. return ZSTD_rotateRight_U16((U16)matches, headGrouped);
  972. } else if (rowEntries == 32) {
  973. return ZSTD_rotateRight_U32((U32)matches, headGrouped);
  974. } else {
  975. return ZSTD_rotateRight_U64((U64)matches, headGrouped);
  976. }
  977. }
  978. #endif
  979. }
  980. /* The high-level approach of the SIMD row based match finder is as follows:
  981. * - Figure out where to insert the new entry:
  982. * - Generate a hash from a byte along with an additional 1-byte "short hash". The additional byte is our "tag"
  983. * - The hashTable is effectively split into groups or "rows" of 16 or 32 entries of U32, and the hash determines
  984. * which row to insert into.
  985. * - Determine the correct position within the row to insert the entry into. Each row of 16 or 32 can
  986. * be considered as a circular buffer with a "head" index that resides in the tagTable.
  987. * - Also insert the "tag" into the equivalent row and position in the tagTable.
  988. * - Note: The tagTable has 17 or 33 1-byte entries per row, due to 16 or 32 tags, and 1 "head" entry.
  989. * The 17 or 33 entry rows are spaced out to occur every 32 or 64 bytes, respectively,
  990. * for alignment/performance reasons, leaving some bytes unused.
  991. * - Use SIMD to efficiently compare the tags in the tagTable to the 1-byte "short hash" and
  992. * generate a bitfield that we can cycle through to check the collisions in the hash table.
  993. * - Pick the longest match.
  994. */
  995. FORCE_INLINE_TEMPLATE
  996. size_t ZSTD_RowFindBestMatch(
  997. ZSTD_matchState_t* ms,
  998. const BYTE* const ip, const BYTE* const iLimit,
  999. size_t* offsetPtr,
  1000. const U32 mls, const ZSTD_dictMode_e dictMode,
  1001. const U32 rowLog)
  1002. {
  1003. U32* const hashTable = ms->hashTable;
  1004. BYTE* const tagTable = ms->tagTable;
  1005. U32* const hashCache = ms->hashCache;
  1006. const U32 hashLog = ms->rowHashLog;
  1007. const ZSTD_compressionParameters* const cParams = &ms->cParams;
  1008. const BYTE* const base = ms->window.base;
  1009. const BYTE* const dictBase = ms->window.dictBase;
  1010. const U32 dictLimit = ms->window.dictLimit;
  1011. const BYTE* const prefixStart = base + dictLimit;
  1012. const BYTE* const dictEnd = dictBase + dictLimit;
  1013. const U32 curr = (U32)(ip-base);
  1014. const U32 maxDistance = 1U << cParams->windowLog;
  1015. const U32 lowestValid = ms->window.lowLimit;
  1016. const U32 withinMaxDistance = (curr - lowestValid > maxDistance) ? curr - maxDistance : lowestValid;
  1017. const U32 isDictionary = (ms->loadedDictEnd != 0);
  1018. const U32 lowLimit = isDictionary ? lowestValid : withinMaxDistance;
  1019. const U32 rowEntries = (1U << rowLog);
  1020. const U32 rowMask = rowEntries - 1;
  1021. const U32 cappedSearchLog = MIN(cParams->searchLog, rowLog); /* nb of searches is capped at nb entries per row */
  1022. const U32 groupWidth = ZSTD_row_matchMaskGroupWidth(rowEntries);
  1023. const U64 hashSalt = ms->hashSalt;
  1024. U32 nbAttempts = 1U << cappedSearchLog;
  1025. size_t ml=4-1;
  1026. U32 hash;
  1027. /* DMS/DDS variables that may be referenced laster */
  1028. const ZSTD_matchState_t* const dms = ms->dictMatchState;
  1029. /* Initialize the following variables to satisfy static analyzer */
  1030. size_t ddsIdx = 0;
  1031. U32 ddsExtraAttempts = 0; /* cctx hash tables are limited in searches, but allow extra searches into DDS */
  1032. U32 dmsTag = 0;
  1033. U32* dmsRow = NULL;
  1034. BYTE* dmsTagRow = NULL;
  1035. if (dictMode == ZSTD_dedicatedDictSearch) {
  1036. const U32 ddsHashLog = dms->cParams.hashLog - ZSTD_LAZY_DDSS_BUCKET_LOG;
  1037. { /* Prefetch DDS hashtable entry */
  1038. ddsIdx = ZSTD_hashPtr(ip, ddsHashLog, mls) << ZSTD_LAZY_DDSS_BUCKET_LOG;
  1039. PREFETCH_L1(&dms->hashTable[ddsIdx]);
  1040. }
  1041. ddsExtraAttempts = cParams->searchLog > rowLog ? 1U << (cParams->searchLog - rowLog) : 0;
  1042. }
  1043. if (dictMode == ZSTD_dictMatchState) {
  1044. /* Prefetch DMS rows */
  1045. U32* const dmsHashTable = dms->hashTable;
  1046. BYTE* const dmsTagTable = dms->tagTable;
  1047. U32 const dmsHash = (U32)ZSTD_hashPtr(ip, dms->rowHashLog + ZSTD_ROW_HASH_TAG_BITS, mls);
  1048. U32 const dmsRelRow = (dmsHash >> ZSTD_ROW_HASH_TAG_BITS) << rowLog;
  1049. dmsTag = dmsHash & ZSTD_ROW_HASH_TAG_MASK;
  1050. dmsTagRow = (BYTE*)(dmsTagTable + dmsRelRow);
  1051. dmsRow = dmsHashTable + dmsRelRow;
  1052. ZSTD_row_prefetch(dmsHashTable, dmsTagTable, dmsRelRow, rowLog);
  1053. }
  1054. /* Update the hashTable and tagTable up to (but not including) ip */
  1055. if (!ms->lazySkipping) {
  1056. ZSTD_row_update_internal(ms, ip, mls, rowLog, rowMask, 1 /* useCache */);
  1057. hash = ZSTD_row_nextCachedHash(hashCache, hashTable, tagTable, base, curr, hashLog, rowLog, mls, hashSalt);
  1058. } else {
  1059. /* Stop inserting every position when in the lazy skipping mode.
  1060. * The hash cache is also not kept up to date in this mode.
  1061. */
  1062. hash = (U32)ZSTD_hashPtrSalted(ip, hashLog + ZSTD_ROW_HASH_TAG_BITS, mls, hashSalt);
  1063. ms->nextToUpdate = curr;
  1064. }
  1065. ms->hashSaltEntropy += hash; /* collect salt entropy */
  1066. { /* Get the hash for ip, compute the appropriate row */
  1067. U32 const relRow = (hash >> ZSTD_ROW_HASH_TAG_BITS) << rowLog;
  1068. U32 const tag = hash & ZSTD_ROW_HASH_TAG_MASK;
  1069. U32* const row = hashTable + relRow;
  1070. BYTE* tagRow = (BYTE*)(tagTable + relRow);
  1071. U32 const headGrouped = (*tagRow & rowMask) * groupWidth;
  1072. U32 matchBuffer[ZSTD_ROW_HASH_MAX_ENTRIES];
  1073. size_t numMatches = 0;
  1074. size_t currMatch = 0;
  1075. ZSTD_VecMask matches = ZSTD_row_getMatchMask(tagRow, (BYTE)tag, headGrouped, rowEntries);
  1076. /* Cycle through the matches and prefetch */
  1077. for (; (matches > 0) && (nbAttempts > 0); matches &= (matches - 1)) {
  1078. U32 const matchPos = ((headGrouped + ZSTD_VecMask_next(matches)) / groupWidth) & rowMask;
  1079. U32 const matchIndex = row[matchPos];
  1080. if(matchPos == 0) continue;
  1081. assert(numMatches < rowEntries);
  1082. if (matchIndex < lowLimit)
  1083. break;
  1084. if ((dictMode != ZSTD_extDict) || matchIndex >= dictLimit) {
  1085. PREFETCH_L1(base + matchIndex);
  1086. } else {
  1087. PREFETCH_L1(dictBase + matchIndex);
  1088. }
  1089. matchBuffer[numMatches++] = matchIndex;
  1090. --nbAttempts;
  1091. }
  1092. /* Speed opt: insert current byte into hashtable too. This allows us to avoid one iteration of the loop
  1093. in ZSTD_row_update_internal() at the next search. */
  1094. {
  1095. U32 const pos = ZSTD_row_nextIndex(tagRow, rowMask);
  1096. tagRow[pos] = (BYTE)tag;
  1097. row[pos] = ms->nextToUpdate++;
  1098. }
  1099. /* Return the longest match */
  1100. for (; currMatch < numMatches; ++currMatch) {
  1101. U32 const matchIndex = matchBuffer[currMatch];
  1102. size_t currentMl=0;
  1103. assert(matchIndex < curr);
  1104. assert(matchIndex >= lowLimit);
  1105. if ((dictMode != ZSTD_extDict) || matchIndex >= dictLimit) {
  1106. const BYTE* const match = base + matchIndex;
  1107. assert(matchIndex >= dictLimit); /* ensures this is true if dictMode != ZSTD_extDict */
  1108. /* read 4B starting from (match + ml + 1 - sizeof(U32)) */
  1109. if (MEM_read32(match + ml - 3) == MEM_read32(ip + ml - 3)) /* potentially better */
  1110. currentMl = ZSTD_count(ip, match, iLimit);
  1111. } else {
  1112. const BYTE* const match = dictBase + matchIndex;
  1113. assert(match+4 <= dictEnd);
  1114. if (MEM_read32(match) == MEM_read32(ip)) /* assumption : matchIndex <= dictLimit-4 (by table construction) */
  1115. currentMl = ZSTD_count_2segments(ip+4, match+4, iLimit, dictEnd, prefixStart) + 4;
  1116. }
  1117. /* Save best solution */
  1118. if (currentMl > ml) {
  1119. ml = currentMl;
  1120. *offsetPtr = OFFSET_TO_OFFBASE(curr - matchIndex);
  1121. if (ip+currentMl == iLimit) break; /* best possible, avoids read overflow on next attempt */
  1122. }
  1123. }
  1124. }
  1125. assert(nbAttempts <= (1U << ZSTD_SEARCHLOG_MAX)); /* Check we haven't underflowed. */
  1126. if (dictMode == ZSTD_dedicatedDictSearch) {
  1127. ml = ZSTD_dedicatedDictSearch_lazy_search(offsetPtr, ml, nbAttempts + ddsExtraAttempts, dms,
  1128. ip, iLimit, prefixStart, curr, dictLimit, ddsIdx);
  1129. } else if (dictMode == ZSTD_dictMatchState) {
  1130. /* TODO: Measure and potentially add prefetching to DMS */
  1131. const U32 dmsLowestIndex = dms->window.dictLimit;
  1132. const BYTE* const dmsBase = dms->window.base;
  1133. const BYTE* const dmsEnd = dms->window.nextSrc;
  1134. const U32 dmsSize = (U32)(dmsEnd - dmsBase);
  1135. const U32 dmsIndexDelta = dictLimit - dmsSize;
  1136. { U32 const headGrouped = (*dmsTagRow & rowMask) * groupWidth;
  1137. U32 matchBuffer[ZSTD_ROW_HASH_MAX_ENTRIES];
  1138. size_t numMatches = 0;
  1139. size_t currMatch = 0;
  1140. ZSTD_VecMask matches = ZSTD_row_getMatchMask(dmsTagRow, (BYTE)dmsTag, headGrouped, rowEntries);
  1141. for (; (matches > 0) && (nbAttempts > 0); matches &= (matches - 1)) {
  1142. U32 const matchPos = ((headGrouped + ZSTD_VecMask_next(matches)) / groupWidth) & rowMask;
  1143. U32 const matchIndex = dmsRow[matchPos];
  1144. if(matchPos == 0) continue;
  1145. if (matchIndex < dmsLowestIndex)
  1146. break;
  1147. PREFETCH_L1(dmsBase + matchIndex);
  1148. matchBuffer[numMatches++] = matchIndex;
  1149. --nbAttempts;
  1150. }
  1151. /* Return the longest match */
  1152. for (; currMatch < numMatches; ++currMatch) {
  1153. U32 const matchIndex = matchBuffer[currMatch];
  1154. size_t currentMl=0;
  1155. assert(matchIndex >= dmsLowestIndex);
  1156. assert(matchIndex < curr);
  1157. { const BYTE* const match = dmsBase + matchIndex;
  1158. assert(match+4 <= dmsEnd);
  1159. if (MEM_read32(match) == MEM_read32(ip))
  1160. currentMl = ZSTD_count_2segments(ip+4, match+4, iLimit, dmsEnd, prefixStart) + 4;
  1161. }
  1162. if (currentMl > ml) {
  1163. ml = currentMl;
  1164. assert(curr > matchIndex + dmsIndexDelta);
  1165. *offsetPtr = OFFSET_TO_OFFBASE(curr - (matchIndex + dmsIndexDelta));
  1166. if (ip+currentMl == iLimit) break;
  1167. }
  1168. }
  1169. }
  1170. }
  1171. return ml;
  1172. }
  1173. /**
  1174. * Generate search functions templated on (dictMode, mls, rowLog).
  1175. * These functions are outlined for code size & compilation time.
  1176. * ZSTD_searchMax() dispatches to the correct implementation function.
  1177. *
  1178. * TODO: The start of the search function involves loading and calculating a
  1179. * bunch of constants from the ZSTD_matchState_t. These computations could be
  1180. * done in an initialization function, and saved somewhere in the match state.
  1181. * Then we could pass a pointer to the saved state instead of the match state,
  1182. * and avoid duplicate computations.
  1183. *
  1184. * TODO: Move the match re-winding into searchMax. This improves compression
  1185. * ratio, and unlocks further simplifications with the next TODO.
  1186. *
  1187. * TODO: Try moving the repcode search into searchMax. After the re-winding
  1188. * and repcode search are in searchMax, there is no more logic in the match
  1189. * finder loop that requires knowledge about the dictMode. So we should be
  1190. * able to avoid force inlining it, and we can join the extDict loop with
  1191. * the single segment loop. It should go in searchMax instead of its own
  1192. * function to avoid having multiple virtual function calls per search.
  1193. */
  1194. #define ZSTD_BT_SEARCH_FN(dictMode, mls) ZSTD_BtFindBestMatch_##dictMode##_##mls
  1195. #define ZSTD_HC_SEARCH_FN(dictMode, mls) ZSTD_HcFindBestMatch_##dictMode##_##mls
  1196. #define ZSTD_ROW_SEARCH_FN(dictMode, mls, rowLog) ZSTD_RowFindBestMatch_##dictMode##_##mls##_##rowLog
  1197. #define ZSTD_SEARCH_FN_ATTRS FORCE_NOINLINE
  1198. #define GEN_ZSTD_BT_SEARCH_FN(dictMode, mls) \
  1199. ZSTD_SEARCH_FN_ATTRS size_t ZSTD_BT_SEARCH_FN(dictMode, mls)( \
  1200. ZSTD_matchState_t* ms, \
  1201. const BYTE* ip, const BYTE* const iLimit, \
  1202. size_t* offBasePtr) \
  1203. { \
  1204. assert(MAX(4, MIN(6, ms->cParams.minMatch)) == mls); \
  1205. return ZSTD_BtFindBestMatch(ms, ip, iLimit, offBasePtr, mls, ZSTD_##dictMode); \
  1206. } \
  1207. #define GEN_ZSTD_HC_SEARCH_FN(dictMode, mls) \
  1208. ZSTD_SEARCH_FN_ATTRS size_t ZSTD_HC_SEARCH_FN(dictMode, mls)( \
  1209. ZSTD_matchState_t* ms, \
  1210. const BYTE* ip, const BYTE* const iLimit, \
  1211. size_t* offsetPtr) \
  1212. { \
  1213. assert(MAX(4, MIN(6, ms->cParams.minMatch)) == mls); \
  1214. return ZSTD_HcFindBestMatch(ms, ip, iLimit, offsetPtr, mls, ZSTD_##dictMode); \
  1215. } \
  1216. #define GEN_ZSTD_ROW_SEARCH_FN(dictMode, mls, rowLog) \
  1217. ZSTD_SEARCH_FN_ATTRS size_t ZSTD_ROW_SEARCH_FN(dictMode, mls, rowLog)( \
  1218. ZSTD_matchState_t* ms, \
  1219. const BYTE* ip, const BYTE* const iLimit, \
  1220. size_t* offsetPtr) \
  1221. { \
  1222. assert(MAX(4, MIN(6, ms->cParams.minMatch)) == mls); \
  1223. assert(MAX(4, MIN(6, ms->cParams.searchLog)) == rowLog); \
  1224. return ZSTD_RowFindBestMatch(ms, ip, iLimit, offsetPtr, mls, ZSTD_##dictMode, rowLog); \
  1225. } \
  1226. #define ZSTD_FOR_EACH_ROWLOG(X, dictMode, mls) \
  1227. X(dictMode, mls, 4) \
  1228. X(dictMode, mls, 5) \
  1229. X(dictMode, mls, 6)
  1230. #define ZSTD_FOR_EACH_MLS_ROWLOG(X, dictMode) \
  1231. ZSTD_FOR_EACH_ROWLOG(X, dictMode, 4) \
  1232. ZSTD_FOR_EACH_ROWLOG(X, dictMode, 5) \
  1233. ZSTD_FOR_EACH_ROWLOG(X, dictMode, 6)
  1234. #define ZSTD_FOR_EACH_MLS(X, dictMode) \
  1235. X(dictMode, 4) \
  1236. X(dictMode, 5) \
  1237. X(dictMode, 6)
  1238. #define ZSTD_FOR_EACH_DICT_MODE(X, ...) \
  1239. X(__VA_ARGS__, noDict) \
  1240. X(__VA_ARGS__, extDict) \
  1241. X(__VA_ARGS__, dictMatchState) \
  1242. X(__VA_ARGS__, dedicatedDictSearch)
  1243. /* Generate row search fns for each combination of (dictMode, mls, rowLog) */
  1244. ZSTD_FOR_EACH_DICT_MODE(ZSTD_FOR_EACH_MLS_ROWLOG, GEN_ZSTD_ROW_SEARCH_FN)
  1245. /* Generate binary Tree search fns for each combination of (dictMode, mls) */
  1246. ZSTD_FOR_EACH_DICT_MODE(ZSTD_FOR_EACH_MLS, GEN_ZSTD_BT_SEARCH_FN)
  1247. /* Generate hash chain search fns for each combination of (dictMode, mls) */
  1248. ZSTD_FOR_EACH_DICT_MODE(ZSTD_FOR_EACH_MLS, GEN_ZSTD_HC_SEARCH_FN)
  1249. typedef enum { search_hashChain=0, search_binaryTree=1, search_rowHash=2 } searchMethod_e;
  1250. #define GEN_ZSTD_CALL_BT_SEARCH_FN(dictMode, mls) \
  1251. case mls: \
  1252. return ZSTD_BT_SEARCH_FN(dictMode, mls)(ms, ip, iend, offsetPtr);
  1253. #define GEN_ZSTD_CALL_HC_SEARCH_FN(dictMode, mls) \
  1254. case mls: \
  1255. return ZSTD_HC_SEARCH_FN(dictMode, mls)(ms, ip, iend, offsetPtr);
  1256. #define GEN_ZSTD_CALL_ROW_SEARCH_FN(dictMode, mls, rowLog) \
  1257. case rowLog: \
  1258. return ZSTD_ROW_SEARCH_FN(dictMode, mls, rowLog)(ms, ip, iend, offsetPtr);
  1259. #define ZSTD_SWITCH_MLS(X, dictMode) \
  1260. switch (mls) { \
  1261. ZSTD_FOR_EACH_MLS(X, dictMode) \
  1262. }
  1263. #define ZSTD_SWITCH_ROWLOG(dictMode, mls) \
  1264. case mls: \
  1265. switch (rowLog) { \
  1266. ZSTD_FOR_EACH_ROWLOG(GEN_ZSTD_CALL_ROW_SEARCH_FN, dictMode, mls) \
  1267. } \
  1268. ZSTD_UNREACHABLE; \
  1269. break;
  1270. #define ZSTD_SWITCH_SEARCH_METHOD(dictMode) \
  1271. switch (searchMethod) { \
  1272. case search_hashChain: \
  1273. ZSTD_SWITCH_MLS(GEN_ZSTD_CALL_HC_SEARCH_FN, dictMode) \
  1274. break; \
  1275. case search_binaryTree: \
  1276. ZSTD_SWITCH_MLS(GEN_ZSTD_CALL_BT_SEARCH_FN, dictMode) \
  1277. break; \
  1278. case search_rowHash: \
  1279. ZSTD_SWITCH_MLS(ZSTD_SWITCH_ROWLOG, dictMode) \
  1280. break; \
  1281. } \
  1282. ZSTD_UNREACHABLE;
  1283. /**
  1284. * Searches for the longest match at @p ip.
  1285. * Dispatches to the correct implementation function based on the
  1286. * (searchMethod, dictMode, mls, rowLog). We use switch statements
  1287. * here instead of using an indirect function call through a function
  1288. * pointer because after Spectre and Meltdown mitigations, indirect
  1289. * function calls can be very costly, especially in the kernel.
  1290. *
  1291. * NOTE: dictMode and searchMethod should be templated, so those switch
  1292. * statements should be optimized out. Only the mls & rowLog switches
  1293. * should be left.
  1294. *
  1295. * @param ms The match state.
  1296. * @param ip The position to search at.
  1297. * @param iend The end of the input data.
  1298. * @param[out] offsetPtr Stores the match offset into this pointer.
  1299. * @param mls The minimum search length, in the range [4, 6].
  1300. * @param rowLog The row log (if applicable), in the range [4, 6].
  1301. * @param searchMethod The search method to use (templated).
  1302. * @param dictMode The dictMode (templated).
  1303. *
  1304. * @returns The length of the longest match found, or < mls if no match is found.
  1305. * If a match is found its offset is stored in @p offsetPtr.
  1306. */
  1307. FORCE_INLINE_TEMPLATE size_t ZSTD_searchMax(
  1308. ZSTD_matchState_t* ms,
  1309. const BYTE* ip,
  1310. const BYTE* iend,
  1311. size_t* offsetPtr,
  1312. U32 const mls,
  1313. U32 const rowLog,
  1314. searchMethod_e const searchMethod,
  1315. ZSTD_dictMode_e const dictMode)
  1316. {
  1317. if (dictMode == ZSTD_noDict) {
  1318. ZSTD_SWITCH_SEARCH_METHOD(noDict)
  1319. } else if (dictMode == ZSTD_extDict) {
  1320. ZSTD_SWITCH_SEARCH_METHOD(extDict)
  1321. } else if (dictMode == ZSTD_dictMatchState) {
  1322. ZSTD_SWITCH_SEARCH_METHOD(dictMatchState)
  1323. } else if (dictMode == ZSTD_dedicatedDictSearch) {
  1324. ZSTD_SWITCH_SEARCH_METHOD(dedicatedDictSearch)
  1325. }
  1326. ZSTD_UNREACHABLE;
  1327. return 0;
  1328. }
  1329. /* *******************************
  1330. * Common parser - lazy strategy
  1331. *********************************/
  1332. FORCE_INLINE_TEMPLATE size_t
  1333. ZSTD_compressBlock_lazy_generic(
  1334. ZSTD_matchState_t* ms, seqStore_t* seqStore,
  1335. U32 rep[ZSTD_REP_NUM],
  1336. const void* src, size_t srcSize,
  1337. const searchMethod_e searchMethod, const U32 depth,
  1338. ZSTD_dictMode_e const dictMode)
  1339. {
  1340. const BYTE* const istart = (const BYTE*)src;
  1341. const BYTE* ip = istart;
  1342. const BYTE* anchor = istart;
  1343. const BYTE* const iend = istart + srcSize;
  1344. const BYTE* const ilimit = (searchMethod == search_rowHash) ? iend - 8 - ZSTD_ROW_HASH_CACHE_SIZE : iend - 8;
  1345. const BYTE* const base = ms->window.base;
  1346. const U32 prefixLowestIndex = ms->window.dictLimit;
  1347. const BYTE* const prefixLowest = base + prefixLowestIndex;
  1348. const U32 mls = BOUNDED(4, ms->cParams.minMatch, 6);
  1349. const U32 rowLog = BOUNDED(4, ms->cParams.searchLog, 6);
  1350. U32 offset_1 = rep[0], offset_2 = rep[1];
  1351. U32 offsetSaved1 = 0, offsetSaved2 = 0;
  1352. const int isDMS = dictMode == ZSTD_dictMatchState;
  1353. const int isDDS = dictMode == ZSTD_dedicatedDictSearch;
  1354. const int isDxS = isDMS || isDDS;
  1355. const ZSTD_matchState_t* const dms = ms->dictMatchState;
  1356. const U32 dictLowestIndex = isDxS ? dms->window.dictLimit : 0;
  1357. const BYTE* const dictBase = isDxS ? dms->window.base : NULL;
  1358. const BYTE* const dictLowest = isDxS ? dictBase + dictLowestIndex : NULL;
  1359. const BYTE* const dictEnd = isDxS ? dms->window.nextSrc : NULL;
  1360. const U32 dictIndexDelta = isDxS ?
  1361. prefixLowestIndex - (U32)(dictEnd - dictBase) :
  1362. 0;
  1363. const U32 dictAndPrefixLength = (U32)((ip - prefixLowest) + (dictEnd - dictLowest));
  1364. DEBUGLOG(5, "ZSTD_compressBlock_lazy_generic (dictMode=%u) (searchFunc=%u)", (U32)dictMode, (U32)searchMethod);
  1365. ip += (dictAndPrefixLength == 0);
  1366. if (dictMode == ZSTD_noDict) {
  1367. U32 const curr = (U32)(ip - base);
  1368. U32 const windowLow = ZSTD_getLowestPrefixIndex(ms, curr, ms->cParams.windowLog);
  1369. U32 const maxRep = curr - windowLow;
  1370. if (offset_2 > maxRep) offsetSaved2 = offset_2, offset_2 = 0;
  1371. if (offset_1 > maxRep) offsetSaved1 = offset_1, offset_1 = 0;
  1372. }
  1373. if (isDxS) {
  1374. /* dictMatchState repCode checks don't currently handle repCode == 0
  1375. * disabling. */
  1376. assert(offset_1 <= dictAndPrefixLength);
  1377. assert(offset_2 <= dictAndPrefixLength);
  1378. }
  1379. /* Reset the lazy skipping state */
  1380. ms->lazySkipping = 0;
  1381. if (searchMethod == search_rowHash) {
  1382. ZSTD_row_fillHashCache(ms, base, rowLog, mls, ms->nextToUpdate, ilimit);
  1383. }
  1384. /* Match Loop */
  1385. #if defined(__GNUC__) && defined(__x86_64__)
  1386. /* I've measured random a 5% speed loss on levels 5 & 6 (greedy) when the
  1387. * code alignment is perturbed. To fix the instability align the loop on 32-bytes.
  1388. */
  1389. __asm__(".p2align 5");
  1390. #endif
  1391. while (ip < ilimit) {
  1392. size_t matchLength=0;
  1393. size_t offBase = REPCODE1_TO_OFFBASE;
  1394. const BYTE* start=ip+1;
  1395. DEBUGLOG(7, "search baseline (depth 0)");
  1396. /* check repCode */
  1397. if (isDxS) {
  1398. const U32 repIndex = (U32)(ip - base) + 1 - offset_1;
  1399. const BYTE* repMatch = ((dictMode == ZSTD_dictMatchState || dictMode == ZSTD_dedicatedDictSearch)
  1400. && repIndex < prefixLowestIndex) ?
  1401. dictBase + (repIndex - dictIndexDelta) :
  1402. base + repIndex;
  1403. if (((U32)((prefixLowestIndex-1) - repIndex) >= 3 /* intentional underflow */)
  1404. && (MEM_read32(repMatch) == MEM_read32(ip+1)) ) {
  1405. const BYTE* repMatchEnd = repIndex < prefixLowestIndex ? dictEnd : iend;
  1406. matchLength = ZSTD_count_2segments(ip+1+4, repMatch+4, iend, repMatchEnd, prefixLowest) + 4;
  1407. if (depth==0) goto _storeSequence;
  1408. }
  1409. }
  1410. if ( dictMode == ZSTD_noDict
  1411. && ((offset_1 > 0) & (MEM_read32(ip+1-offset_1) == MEM_read32(ip+1)))) {
  1412. matchLength = ZSTD_count(ip+1+4, ip+1+4-offset_1, iend) + 4;
  1413. if (depth==0) goto _storeSequence;
  1414. }
  1415. /* first search (depth 0) */
  1416. { size_t offbaseFound = 999999999;
  1417. size_t const ml2 = ZSTD_searchMax(ms, ip, iend, &offbaseFound, mls, rowLog, searchMethod, dictMode);
  1418. if (ml2 > matchLength)
  1419. matchLength = ml2, start = ip, offBase = offbaseFound;
  1420. }
  1421. if (matchLength < 4) {
  1422. size_t const step = ((size_t)(ip-anchor) >> kSearchStrength) + 1; /* jump faster over incompressible sections */;
  1423. ip += step;
  1424. /* Enter the lazy skipping mode once we are skipping more than 8 bytes at a time.
  1425. * In this mode we stop inserting every position into our tables, and only insert
  1426. * positions that we search, which is one in step positions.
  1427. * The exact cutoff is flexible, I've just chosen a number that is reasonably high,
  1428. * so we minimize the compression ratio loss in "normal" scenarios. This mode gets
  1429. * triggered once we've gone 2KB without finding any matches.
  1430. */
  1431. ms->lazySkipping = step > kLazySkippingStep;
  1432. continue;
  1433. }
  1434. /* let's try to find a better solution */
  1435. if (depth>=1)
  1436. while (ip<ilimit) {
  1437. DEBUGLOG(7, "search depth 1");
  1438. ip ++;
  1439. if ( (dictMode == ZSTD_noDict)
  1440. && (offBase) && ((offset_1>0) & (MEM_read32(ip) == MEM_read32(ip - offset_1)))) {
  1441. size_t const mlRep = ZSTD_count(ip+4, ip+4-offset_1, iend) + 4;
  1442. int const gain2 = (int)(mlRep * 3);
  1443. int const gain1 = (int)(matchLength*3 - ZSTD_highbit32((U32)offBase) + 1);
  1444. if ((mlRep >= 4) && (gain2 > gain1))
  1445. matchLength = mlRep, offBase = REPCODE1_TO_OFFBASE, start = ip;
  1446. }
  1447. if (isDxS) {
  1448. const U32 repIndex = (U32)(ip - base) - offset_1;
  1449. const BYTE* repMatch = repIndex < prefixLowestIndex ?
  1450. dictBase + (repIndex - dictIndexDelta) :
  1451. base + repIndex;
  1452. if (((U32)((prefixLowestIndex-1) - repIndex) >= 3 /* intentional underflow */)
  1453. && (MEM_read32(repMatch) == MEM_read32(ip)) ) {
  1454. const BYTE* repMatchEnd = repIndex < prefixLowestIndex ? dictEnd : iend;
  1455. size_t const mlRep = ZSTD_count_2segments(ip+4, repMatch+4, iend, repMatchEnd, prefixLowest) + 4;
  1456. int const gain2 = (int)(mlRep * 3);
  1457. int const gain1 = (int)(matchLength*3 - ZSTD_highbit32((U32)offBase) + 1);
  1458. if ((mlRep >= 4) && (gain2 > gain1))
  1459. matchLength = mlRep, offBase = REPCODE1_TO_OFFBASE, start = ip;
  1460. }
  1461. }
  1462. { size_t ofbCandidate=999999999;
  1463. size_t const ml2 = ZSTD_searchMax(ms, ip, iend, &ofbCandidate, mls, rowLog, searchMethod, dictMode);
  1464. int const gain2 = (int)(ml2*4 - ZSTD_highbit32((U32)ofbCandidate)); /* raw approx */
  1465. int const gain1 = (int)(matchLength*4 - ZSTD_highbit32((U32)offBase) + 4);
  1466. if ((ml2 >= 4) && (gain2 > gain1)) {
  1467. matchLength = ml2, offBase = ofbCandidate, start = ip;
  1468. continue; /* search a better one */
  1469. } }
  1470. /* let's find an even better one */
  1471. if ((depth==2) && (ip<ilimit)) {
  1472. DEBUGLOG(7, "search depth 2");
  1473. ip ++;
  1474. if ( (dictMode == ZSTD_noDict)
  1475. && (offBase) && ((offset_1>0) & (MEM_read32(ip) == MEM_read32(ip - offset_1)))) {
  1476. size_t const mlRep = ZSTD_count(ip+4, ip+4-offset_1, iend) + 4;
  1477. int const gain2 = (int)(mlRep * 4);
  1478. int const gain1 = (int)(matchLength*4 - ZSTD_highbit32((U32)offBase) + 1);
  1479. if ((mlRep >= 4) && (gain2 > gain1))
  1480. matchLength = mlRep, offBase = REPCODE1_TO_OFFBASE, start = ip;
  1481. }
  1482. if (isDxS) {
  1483. const U32 repIndex = (U32)(ip - base) - offset_1;
  1484. const BYTE* repMatch = repIndex < prefixLowestIndex ?
  1485. dictBase + (repIndex - dictIndexDelta) :
  1486. base + repIndex;
  1487. if (((U32)((prefixLowestIndex-1) - repIndex) >= 3 /* intentional underflow */)
  1488. && (MEM_read32(repMatch) == MEM_read32(ip)) ) {
  1489. const BYTE* repMatchEnd = repIndex < prefixLowestIndex ? dictEnd : iend;
  1490. size_t const mlRep = ZSTD_count_2segments(ip+4, repMatch+4, iend, repMatchEnd, prefixLowest) + 4;
  1491. int const gain2 = (int)(mlRep * 4);
  1492. int const gain1 = (int)(matchLength*4 - ZSTD_highbit32((U32)offBase) + 1);
  1493. if ((mlRep >= 4) && (gain2 > gain1))
  1494. matchLength = mlRep, offBase = REPCODE1_TO_OFFBASE, start = ip;
  1495. }
  1496. }
  1497. { size_t ofbCandidate=999999999;
  1498. size_t const ml2 = ZSTD_searchMax(ms, ip, iend, &ofbCandidate, mls, rowLog, searchMethod, dictMode);
  1499. int const gain2 = (int)(ml2*4 - ZSTD_highbit32((U32)ofbCandidate)); /* raw approx */
  1500. int const gain1 = (int)(matchLength*4 - ZSTD_highbit32((U32)offBase) + 7);
  1501. if ((ml2 >= 4) && (gain2 > gain1)) {
  1502. matchLength = ml2, offBase = ofbCandidate, start = ip;
  1503. continue;
  1504. } } }
  1505. break; /* nothing found : store previous solution */
  1506. }
  1507. /* NOTE:
  1508. * Pay attention that `start[-value]` can lead to strange undefined behavior
  1509. * notably if `value` is unsigned, resulting in a large positive `-value`.
  1510. */
  1511. /* catch up */
  1512. if (OFFBASE_IS_OFFSET(offBase)) {
  1513. if (dictMode == ZSTD_noDict) {
  1514. while ( ((start > anchor) & (start - OFFBASE_TO_OFFSET(offBase) > prefixLowest))
  1515. && (start[-1] == (start-OFFBASE_TO_OFFSET(offBase))[-1]) ) /* only search for offset within prefix */
  1516. { start--; matchLength++; }
  1517. }
  1518. if (isDxS) {
  1519. U32 const matchIndex = (U32)((size_t)(start-base) - OFFBASE_TO_OFFSET(offBase));
  1520. const BYTE* match = (matchIndex < prefixLowestIndex) ? dictBase + matchIndex - dictIndexDelta : base + matchIndex;
  1521. const BYTE* const mStart = (matchIndex < prefixLowestIndex) ? dictLowest : prefixLowest;
  1522. while ((start>anchor) && (match>mStart) && (start[-1] == match[-1])) { start--; match--; matchLength++; } /* catch up */
  1523. }
  1524. offset_2 = offset_1; offset_1 = (U32)OFFBASE_TO_OFFSET(offBase);
  1525. }
  1526. /* store sequence */
  1527. _storeSequence:
  1528. { size_t const litLength = (size_t)(start - anchor);
  1529. ZSTD_storeSeq(seqStore, litLength, anchor, iend, (U32)offBase, matchLength);
  1530. anchor = ip = start + matchLength;
  1531. }
  1532. if (ms->lazySkipping) {
  1533. /* We've found a match, disable lazy skipping mode, and refill the hash cache. */
  1534. if (searchMethod == search_rowHash) {
  1535. ZSTD_row_fillHashCache(ms, base, rowLog, mls, ms->nextToUpdate, ilimit);
  1536. }
  1537. ms->lazySkipping = 0;
  1538. }
  1539. /* check immediate repcode */
  1540. if (isDxS) {
  1541. while (ip <= ilimit) {
  1542. U32 const current2 = (U32)(ip-base);
  1543. U32 const repIndex = current2 - offset_2;
  1544. const BYTE* repMatch = repIndex < prefixLowestIndex ?
  1545. dictBase - dictIndexDelta + repIndex :
  1546. base + repIndex;
  1547. if ( ((U32)((prefixLowestIndex-1) - (U32)repIndex) >= 3 /* intentional overflow */)
  1548. && (MEM_read32(repMatch) == MEM_read32(ip)) ) {
  1549. const BYTE* const repEnd2 = repIndex < prefixLowestIndex ? dictEnd : iend;
  1550. matchLength = ZSTD_count_2segments(ip+4, repMatch+4, iend, repEnd2, prefixLowest) + 4;
  1551. offBase = offset_2; offset_2 = offset_1; offset_1 = (U32)offBase; /* swap offset_2 <=> offset_1 */
  1552. ZSTD_storeSeq(seqStore, 0, anchor, iend, REPCODE1_TO_OFFBASE, matchLength);
  1553. ip += matchLength;
  1554. anchor = ip;
  1555. continue;
  1556. }
  1557. break;
  1558. }
  1559. }
  1560. if (dictMode == ZSTD_noDict) {
  1561. while ( ((ip <= ilimit) & (offset_2>0))
  1562. && (MEM_read32(ip) == MEM_read32(ip - offset_2)) ) {
  1563. /* store sequence */
  1564. matchLength = ZSTD_count(ip+4, ip+4-offset_2, iend) + 4;
  1565. offBase = offset_2; offset_2 = offset_1; offset_1 = (U32)offBase; /* swap repcodes */
  1566. ZSTD_storeSeq(seqStore, 0, anchor, iend, REPCODE1_TO_OFFBASE, matchLength);
  1567. ip += matchLength;
  1568. anchor = ip;
  1569. continue; /* faster when present ... (?) */
  1570. } } }
  1571. /* If offset_1 started invalid (offsetSaved1 != 0) and became valid (offset_1 != 0),
  1572. * rotate saved offsets. See comment in ZSTD_compressBlock_fast_noDict for more context. */
  1573. offsetSaved2 = ((offsetSaved1 != 0) && (offset_1 != 0)) ? offsetSaved1 : offsetSaved2;
  1574. /* save reps for next block */
  1575. rep[0] = offset_1 ? offset_1 : offsetSaved1;
  1576. rep[1] = offset_2 ? offset_2 : offsetSaved2;
  1577. /* Return the last literals size */
  1578. return (size_t)(iend - anchor);
  1579. }
  1580. size_t ZSTD_compressBlock_btlazy2(
  1581. ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
  1582. void const* src, size_t srcSize)
  1583. {
  1584. return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_binaryTree, 2, ZSTD_noDict);
  1585. }
  1586. size_t ZSTD_compressBlock_lazy2(
  1587. ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
  1588. void const* src, size_t srcSize)
  1589. {
  1590. return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 2, ZSTD_noDict);
  1591. }
  1592. size_t ZSTD_compressBlock_lazy(
  1593. ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
  1594. void const* src, size_t srcSize)
  1595. {
  1596. return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 1, ZSTD_noDict);
  1597. }
  1598. size_t ZSTD_compressBlock_greedy(
  1599. ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
  1600. void const* src, size_t srcSize)
  1601. {
  1602. return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 0, ZSTD_noDict);
  1603. }
  1604. size_t ZSTD_compressBlock_btlazy2_dictMatchState(
  1605. ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
  1606. void const* src, size_t srcSize)
  1607. {
  1608. return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_binaryTree, 2, ZSTD_dictMatchState);
  1609. }
  1610. size_t ZSTD_compressBlock_lazy2_dictMatchState(
  1611. ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
  1612. void const* src, size_t srcSize)
  1613. {
  1614. return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 2, ZSTD_dictMatchState);
  1615. }
  1616. size_t ZSTD_compressBlock_lazy_dictMatchState(
  1617. ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
  1618. void const* src, size_t srcSize)
  1619. {
  1620. return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 1, ZSTD_dictMatchState);
  1621. }
  1622. size_t ZSTD_compressBlock_greedy_dictMatchState(
  1623. ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
  1624. void const* src, size_t srcSize)
  1625. {
  1626. return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 0, ZSTD_dictMatchState);
  1627. }
  1628. size_t ZSTD_compressBlock_lazy2_dedicatedDictSearch(
  1629. ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
  1630. void const* src, size_t srcSize)
  1631. {
  1632. return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 2, ZSTD_dedicatedDictSearch);
  1633. }
  1634. size_t ZSTD_compressBlock_lazy_dedicatedDictSearch(
  1635. ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
  1636. void const* src, size_t srcSize)
  1637. {
  1638. return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 1, ZSTD_dedicatedDictSearch);
  1639. }
  1640. size_t ZSTD_compressBlock_greedy_dedicatedDictSearch(
  1641. ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
  1642. void const* src, size_t srcSize)
  1643. {
  1644. return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 0, ZSTD_dedicatedDictSearch);
  1645. }
  1646. /* Row-based matchfinder */
  1647. size_t ZSTD_compressBlock_lazy2_row(
  1648. ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
  1649. void const* src, size_t srcSize)
  1650. {
  1651. return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 2, ZSTD_noDict);
  1652. }
  1653. size_t ZSTD_compressBlock_lazy_row(
  1654. ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
  1655. void const* src, size_t srcSize)
  1656. {
  1657. return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 1, ZSTD_noDict);
  1658. }
  1659. size_t ZSTD_compressBlock_greedy_row(
  1660. ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
  1661. void const* src, size_t srcSize)
  1662. {
  1663. return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 0, ZSTD_noDict);
  1664. }
  1665. size_t ZSTD_compressBlock_lazy2_dictMatchState_row(
  1666. ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
  1667. void const* src, size_t srcSize)
  1668. {
  1669. return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 2, ZSTD_dictMatchState);
  1670. }
  1671. size_t ZSTD_compressBlock_lazy_dictMatchState_row(
  1672. ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
  1673. void const* src, size_t srcSize)
  1674. {
  1675. return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 1, ZSTD_dictMatchState);
  1676. }
  1677. size_t ZSTD_compressBlock_greedy_dictMatchState_row(
  1678. ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
  1679. void const* src, size_t srcSize)
  1680. {
  1681. return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 0, ZSTD_dictMatchState);
  1682. }
  1683. size_t ZSTD_compressBlock_lazy2_dedicatedDictSearch_row(
  1684. ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
  1685. void const* src, size_t srcSize)
  1686. {
  1687. return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 2, ZSTD_dedicatedDictSearch);
  1688. }
  1689. size_t ZSTD_compressBlock_lazy_dedicatedDictSearch_row(
  1690. ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
  1691. void const* src, size_t srcSize)
  1692. {
  1693. return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 1, ZSTD_dedicatedDictSearch);
  1694. }
  1695. size_t ZSTD_compressBlock_greedy_dedicatedDictSearch_row(
  1696. ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
  1697. void const* src, size_t srcSize)
  1698. {
  1699. return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 0, ZSTD_dedicatedDictSearch);
  1700. }
  1701. FORCE_INLINE_TEMPLATE
  1702. size_t ZSTD_compressBlock_lazy_extDict_generic(
  1703. ZSTD_matchState_t* ms, seqStore_t* seqStore,
  1704. U32 rep[ZSTD_REP_NUM],
  1705. const void* src, size_t srcSize,
  1706. const searchMethod_e searchMethod, const U32 depth)
  1707. {
  1708. const BYTE* const istart = (const BYTE*)src;
  1709. const BYTE* ip = istart;
  1710. const BYTE* anchor = istart;
  1711. const BYTE* const iend = istart + srcSize;
  1712. const BYTE* const ilimit = searchMethod == search_rowHash ? iend - 8 - ZSTD_ROW_HASH_CACHE_SIZE : iend - 8;
  1713. const BYTE* const base = ms->window.base;
  1714. const U32 dictLimit = ms->window.dictLimit;
  1715. const BYTE* const prefixStart = base + dictLimit;
  1716. const BYTE* const dictBase = ms->window.dictBase;
  1717. const BYTE* const dictEnd = dictBase + dictLimit;
  1718. const BYTE* const dictStart = dictBase + ms->window.lowLimit;
  1719. const U32 windowLog = ms->cParams.windowLog;
  1720. const U32 mls = BOUNDED(4, ms->cParams.minMatch, 6);
  1721. const U32 rowLog = BOUNDED(4, ms->cParams.searchLog, 6);
  1722. U32 offset_1 = rep[0], offset_2 = rep[1];
  1723. DEBUGLOG(5, "ZSTD_compressBlock_lazy_extDict_generic (searchFunc=%u)", (U32)searchMethod);
  1724. /* Reset the lazy skipping state */
  1725. ms->lazySkipping = 0;
  1726. /* init */
  1727. ip += (ip == prefixStart);
  1728. if (searchMethod == search_rowHash) {
  1729. ZSTD_row_fillHashCache(ms, base, rowLog, mls, ms->nextToUpdate, ilimit);
  1730. }
  1731. /* Match Loop */
  1732. #if defined(__GNUC__) && defined(__x86_64__)
  1733. /* I've measured random a 5% speed loss on levels 5 & 6 (greedy) when the
  1734. * code alignment is perturbed. To fix the instability align the loop on 32-bytes.
  1735. */
  1736. __asm__(".p2align 5");
  1737. #endif
  1738. while (ip < ilimit) {
  1739. size_t matchLength=0;
  1740. size_t offBase = REPCODE1_TO_OFFBASE;
  1741. const BYTE* start=ip+1;
  1742. U32 curr = (U32)(ip-base);
  1743. /* check repCode */
  1744. { const U32 windowLow = ZSTD_getLowestMatchIndex(ms, curr+1, windowLog);
  1745. const U32 repIndex = (U32)(curr+1 - offset_1);
  1746. const BYTE* const repBase = repIndex < dictLimit ? dictBase : base;
  1747. const BYTE* const repMatch = repBase + repIndex;
  1748. if ( ((U32)((dictLimit-1) - repIndex) >= 3) /* intentional overflow */
  1749. & (offset_1 <= curr+1 - windowLow) ) /* note: we are searching at curr+1 */
  1750. if (MEM_read32(ip+1) == MEM_read32(repMatch)) {
  1751. /* repcode detected we should take it */
  1752. const BYTE* const repEnd = repIndex < dictLimit ? dictEnd : iend;
  1753. matchLength = ZSTD_count_2segments(ip+1+4, repMatch+4, iend, repEnd, prefixStart) + 4;
  1754. if (depth==0) goto _storeSequence;
  1755. } }
  1756. /* first search (depth 0) */
  1757. { size_t ofbCandidate = 999999999;
  1758. size_t const ml2 = ZSTD_searchMax(ms, ip, iend, &ofbCandidate, mls, rowLog, searchMethod, ZSTD_extDict);
  1759. if (ml2 > matchLength)
  1760. matchLength = ml2, start = ip, offBase = ofbCandidate;
  1761. }
  1762. if (matchLength < 4) {
  1763. size_t const step = ((size_t)(ip-anchor) >> kSearchStrength);
  1764. ip += step + 1; /* jump faster over incompressible sections */
  1765. /* Enter the lazy skipping mode once we are skipping more than 8 bytes at a time.
  1766. * In this mode we stop inserting every position into our tables, and only insert
  1767. * positions that we search, which is one in step positions.
  1768. * The exact cutoff is flexible, I've just chosen a number that is reasonably high,
  1769. * so we minimize the compression ratio loss in "normal" scenarios. This mode gets
  1770. * triggered once we've gone 2KB without finding any matches.
  1771. */
  1772. ms->lazySkipping = step > kLazySkippingStep;
  1773. continue;
  1774. }
  1775. /* let's try to find a better solution */
  1776. if (depth>=1)
  1777. while (ip<ilimit) {
  1778. ip ++;
  1779. curr++;
  1780. /* check repCode */
  1781. if (offBase) {
  1782. const U32 windowLow = ZSTD_getLowestMatchIndex(ms, curr, windowLog);
  1783. const U32 repIndex = (U32)(curr - offset_1);
  1784. const BYTE* const repBase = repIndex < dictLimit ? dictBase : base;
  1785. const BYTE* const repMatch = repBase + repIndex;
  1786. if ( ((U32)((dictLimit-1) - repIndex) >= 3) /* intentional overflow : do not test positions overlapping 2 memory segments */
  1787. & (offset_1 <= curr - windowLow) ) /* equivalent to `curr > repIndex >= windowLow` */
  1788. if (MEM_read32(ip) == MEM_read32(repMatch)) {
  1789. /* repcode detected */
  1790. const BYTE* const repEnd = repIndex < dictLimit ? dictEnd : iend;
  1791. size_t const repLength = ZSTD_count_2segments(ip+4, repMatch+4, iend, repEnd, prefixStart) + 4;
  1792. int const gain2 = (int)(repLength * 3);
  1793. int const gain1 = (int)(matchLength*3 - ZSTD_highbit32((U32)offBase) + 1);
  1794. if ((repLength >= 4) && (gain2 > gain1))
  1795. matchLength = repLength, offBase = REPCODE1_TO_OFFBASE, start = ip;
  1796. } }
  1797. /* search match, depth 1 */
  1798. { size_t ofbCandidate = 999999999;
  1799. size_t const ml2 = ZSTD_searchMax(ms, ip, iend, &ofbCandidate, mls, rowLog, searchMethod, ZSTD_extDict);
  1800. int const gain2 = (int)(ml2*4 - ZSTD_highbit32((U32)ofbCandidate)); /* raw approx */
  1801. int const gain1 = (int)(matchLength*4 - ZSTD_highbit32((U32)offBase) + 4);
  1802. if ((ml2 >= 4) && (gain2 > gain1)) {
  1803. matchLength = ml2, offBase = ofbCandidate, start = ip;
  1804. continue; /* search a better one */
  1805. } }
  1806. /* let's find an even better one */
  1807. if ((depth==2) && (ip<ilimit)) {
  1808. ip ++;
  1809. curr++;
  1810. /* check repCode */
  1811. if (offBase) {
  1812. const U32 windowLow = ZSTD_getLowestMatchIndex(ms, curr, windowLog);
  1813. const U32 repIndex = (U32)(curr - offset_1);
  1814. const BYTE* const repBase = repIndex < dictLimit ? dictBase : base;
  1815. const BYTE* const repMatch = repBase + repIndex;
  1816. if ( ((U32)((dictLimit-1) - repIndex) >= 3) /* intentional overflow : do not test positions overlapping 2 memory segments */
  1817. & (offset_1 <= curr - windowLow) ) /* equivalent to `curr > repIndex >= windowLow` */
  1818. if (MEM_read32(ip) == MEM_read32(repMatch)) {
  1819. /* repcode detected */
  1820. const BYTE* const repEnd = repIndex < dictLimit ? dictEnd : iend;
  1821. size_t const repLength = ZSTD_count_2segments(ip+4, repMatch+4, iend, repEnd, prefixStart) + 4;
  1822. int const gain2 = (int)(repLength * 4);
  1823. int const gain1 = (int)(matchLength*4 - ZSTD_highbit32((U32)offBase) + 1);
  1824. if ((repLength >= 4) && (gain2 > gain1))
  1825. matchLength = repLength, offBase = REPCODE1_TO_OFFBASE, start = ip;
  1826. } }
  1827. /* search match, depth 2 */
  1828. { size_t ofbCandidate = 999999999;
  1829. size_t const ml2 = ZSTD_searchMax(ms, ip, iend, &ofbCandidate, mls, rowLog, searchMethod, ZSTD_extDict);
  1830. int const gain2 = (int)(ml2*4 - ZSTD_highbit32((U32)ofbCandidate)); /* raw approx */
  1831. int const gain1 = (int)(matchLength*4 - ZSTD_highbit32((U32)offBase) + 7);
  1832. if ((ml2 >= 4) && (gain2 > gain1)) {
  1833. matchLength = ml2, offBase = ofbCandidate, start = ip;
  1834. continue;
  1835. } } }
  1836. break; /* nothing found : store previous solution */
  1837. }
  1838. /* catch up */
  1839. if (OFFBASE_IS_OFFSET(offBase)) {
  1840. U32 const matchIndex = (U32)((size_t)(start-base) - OFFBASE_TO_OFFSET(offBase));
  1841. const BYTE* match = (matchIndex < dictLimit) ? dictBase + matchIndex : base + matchIndex;
  1842. const BYTE* const mStart = (matchIndex < dictLimit) ? dictStart : prefixStart;
  1843. while ((start>anchor) && (match>mStart) && (start[-1] == match[-1])) { start--; match--; matchLength++; } /* catch up */
  1844. offset_2 = offset_1; offset_1 = (U32)OFFBASE_TO_OFFSET(offBase);
  1845. }
  1846. /* store sequence */
  1847. _storeSequence:
  1848. { size_t const litLength = (size_t)(start - anchor);
  1849. ZSTD_storeSeq(seqStore, litLength, anchor, iend, (U32)offBase, matchLength);
  1850. anchor = ip = start + matchLength;
  1851. }
  1852. if (ms->lazySkipping) {
  1853. /* We've found a match, disable lazy skipping mode, and refill the hash cache. */
  1854. if (searchMethod == search_rowHash) {
  1855. ZSTD_row_fillHashCache(ms, base, rowLog, mls, ms->nextToUpdate, ilimit);
  1856. }
  1857. ms->lazySkipping = 0;
  1858. }
  1859. /* check immediate repcode */
  1860. while (ip <= ilimit) {
  1861. const U32 repCurrent = (U32)(ip-base);
  1862. const U32 windowLow = ZSTD_getLowestMatchIndex(ms, repCurrent, windowLog);
  1863. const U32 repIndex = repCurrent - offset_2;
  1864. const BYTE* const repBase = repIndex < dictLimit ? dictBase : base;
  1865. const BYTE* const repMatch = repBase + repIndex;
  1866. if ( ((U32)((dictLimit-1) - repIndex) >= 3) /* intentional overflow : do not test positions overlapping 2 memory segments */
  1867. & (offset_2 <= repCurrent - windowLow) ) /* equivalent to `curr > repIndex >= windowLow` */
  1868. if (MEM_read32(ip) == MEM_read32(repMatch)) {
  1869. /* repcode detected we should take it */
  1870. const BYTE* const repEnd = repIndex < dictLimit ? dictEnd : iend;
  1871. matchLength = ZSTD_count_2segments(ip+4, repMatch+4, iend, repEnd, prefixStart) + 4;
  1872. offBase = offset_2; offset_2 = offset_1; offset_1 = (U32)offBase; /* swap offset history */
  1873. ZSTD_storeSeq(seqStore, 0, anchor, iend, REPCODE1_TO_OFFBASE, matchLength);
  1874. ip += matchLength;
  1875. anchor = ip;
  1876. continue; /* faster when present ... (?) */
  1877. }
  1878. break;
  1879. } }
  1880. /* Save reps for next block */
  1881. rep[0] = offset_1;
  1882. rep[1] = offset_2;
  1883. /* Return the last literals size */
  1884. return (size_t)(iend - anchor);
  1885. }
  1886. size_t ZSTD_compressBlock_greedy_extDict(
  1887. ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
  1888. void const* src, size_t srcSize)
  1889. {
  1890. return ZSTD_compressBlock_lazy_extDict_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 0);
  1891. }
  1892. size_t ZSTD_compressBlock_lazy_extDict(
  1893. ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
  1894. void const* src, size_t srcSize)
  1895. {
  1896. return ZSTD_compressBlock_lazy_extDict_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 1);
  1897. }
  1898. size_t ZSTD_compressBlock_lazy2_extDict(
  1899. ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
  1900. void const* src, size_t srcSize)
  1901. {
  1902. return ZSTD_compressBlock_lazy_extDict_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 2);
  1903. }
  1904. size_t ZSTD_compressBlock_btlazy2_extDict(
  1905. ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
  1906. void const* src, size_t srcSize)
  1907. {
  1908. return ZSTD_compressBlock_lazy_extDict_generic(ms, seqStore, rep, src, srcSize, search_binaryTree, 2);
  1909. }
  1910. size_t ZSTD_compressBlock_greedy_extDict_row(
  1911. ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
  1912. void const* src, size_t srcSize)
  1913. {
  1914. return ZSTD_compressBlock_lazy_extDict_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 0);
  1915. }
  1916. size_t ZSTD_compressBlock_lazy_extDict_row(
  1917. ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
  1918. void const* src, size_t srcSize)
  1919. {
  1920. return ZSTD_compressBlock_lazy_extDict_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 1);
  1921. }
  1922. size_t ZSTD_compressBlock_lazy2_extDict_row(
  1923. ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
  1924. void const* src, size_t srcSize)
  1925. {
  1926. return ZSTD_compressBlock_lazy_extDict_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 2);
  1927. }