zstd_opt.c 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346
  1. /*
  2. * Copyright (c) 2016-2020, Przemyslaw Skibinski, Yann Collet, Facebook, Inc.
  3. * All rights reserved.
  4. *
  5. * This source code is licensed under both the BSD-style license (found in the
  6. * LICENSE file in the root directory of this source tree) and the GPLv2 (found
  7. * in the COPYING file in the root directory of this source tree).
  8. * You may select, at your option, one of the above-listed licenses.
  9. */
  10. #include "zstd_compress_internal.h"
  11. #include "hist.h"
  12. #include "zstd_opt.h"
  13. #define ZSTD_LITFREQ_ADD 2 /* scaling factor for litFreq, so that frequencies adapt faster to new stats */
  14. #define ZSTD_FREQ_DIV 4 /* log factor when using previous stats to init next stats */
  15. #define ZSTD_MAX_PRICE (1<<30)
  16. #define ZSTD_PREDEF_THRESHOLD 1024 /* if srcSize < ZSTD_PREDEF_THRESHOLD, symbols' cost is assumed static, directly determined by pre-defined distributions */
  17. /*-*************************************
  18. * Price functions for optimal parser
  19. ***************************************/
  20. #if 0 /* approximation at bit level */
  21. # define BITCOST_ACCURACY 0
  22. # define BITCOST_MULTIPLIER (1 << BITCOST_ACCURACY)
  23. # define WEIGHT(stat) ((void)opt, ZSTD_bitWeight(stat))
  24. #elif 0 /* fractional bit accuracy */
  25. # define BITCOST_ACCURACY 8
  26. # define BITCOST_MULTIPLIER (1 << BITCOST_ACCURACY)
  27. # define WEIGHT(stat,opt) ((void)opt, ZSTD_fracWeight(stat))
  28. #else /* opt==approx, ultra==accurate */
  29. # define BITCOST_ACCURACY 8
  30. # define BITCOST_MULTIPLIER (1 << BITCOST_ACCURACY)
  31. # define WEIGHT(stat,opt) (opt ? ZSTD_fracWeight(stat) : ZSTD_bitWeight(stat))
  32. #endif
  33. MEM_STATIC U32 ZSTD_bitWeight(U32 stat)
  34. {
  35. return (ZSTD_highbit32(stat+1) * BITCOST_MULTIPLIER);
  36. }
  37. MEM_STATIC U32 ZSTD_fracWeight(U32 rawStat)
  38. {
  39. U32 const stat = rawStat + 1;
  40. U32 const hb = ZSTD_highbit32(stat);
  41. U32 const BWeight = hb * BITCOST_MULTIPLIER;
  42. U32 const FWeight = (stat << BITCOST_ACCURACY) >> hb;
  43. U32 const weight = BWeight + FWeight;
  44. assert(hb + BITCOST_ACCURACY < 31);
  45. return weight;
  46. }
  47. #if (DEBUGLEVEL>=2)
  48. /* debugging function,
  49. * @return price in bytes as fractional value
  50. * for debug messages only */
  51. MEM_STATIC double ZSTD_fCost(U32 price)
  52. {
  53. return (double)price / (BITCOST_MULTIPLIER*8);
  54. }
  55. #endif
  56. static int ZSTD_compressedLiterals(optState_t const* const optPtr)
  57. {
  58. return optPtr->literalCompressionMode != ZSTD_lcm_uncompressed;
  59. }
  60. static void ZSTD_setBasePrices(optState_t* optPtr, int optLevel)
  61. {
  62. if (ZSTD_compressedLiterals(optPtr))
  63. optPtr->litSumBasePrice = WEIGHT(optPtr->litSum, optLevel);
  64. optPtr->litLengthSumBasePrice = WEIGHT(optPtr->litLengthSum, optLevel);
  65. optPtr->matchLengthSumBasePrice = WEIGHT(optPtr->matchLengthSum, optLevel);
  66. optPtr->offCodeSumBasePrice = WEIGHT(optPtr->offCodeSum, optLevel);
  67. }
  68. /* ZSTD_downscaleStat() :
  69. * reduce all elements in table by a factor 2^(ZSTD_FREQ_DIV+malus)
  70. * return the resulting sum of elements */
  71. static U32 ZSTD_downscaleStat(unsigned* table, U32 lastEltIndex, int malus)
  72. {
  73. U32 s, sum=0;
  74. DEBUGLOG(5, "ZSTD_downscaleStat (nbElts=%u)", (unsigned)lastEltIndex+1);
  75. assert(ZSTD_FREQ_DIV+malus > 0 && ZSTD_FREQ_DIV+malus < 31);
  76. for (s=0; s<lastEltIndex+1; s++) {
  77. table[s] = 1 + (table[s] >> (ZSTD_FREQ_DIV+malus));
  78. sum += table[s];
  79. }
  80. return sum;
  81. }
  82. /* ZSTD_rescaleFreqs() :
  83. * if first block (detected by optPtr->litLengthSum == 0) : init statistics
  84. * take hints from dictionary if there is one
  85. * or init from zero, using src for literals stats, or flat 1 for match symbols
  86. * otherwise downscale existing stats, to be used as seed for next block.
  87. */
  88. static void
  89. ZSTD_rescaleFreqs(optState_t* const optPtr,
  90. const BYTE* const src, size_t const srcSize,
  91. int const optLevel)
  92. {
  93. int const compressedLiterals = ZSTD_compressedLiterals(optPtr);
  94. DEBUGLOG(5, "ZSTD_rescaleFreqs (srcSize=%u)", (unsigned)srcSize);
  95. optPtr->priceType = zop_dynamic;
  96. if (optPtr->litLengthSum == 0) { /* first block : init */
  97. if (srcSize <= ZSTD_PREDEF_THRESHOLD) { /* heuristic */
  98. DEBUGLOG(5, "(srcSize <= ZSTD_PREDEF_THRESHOLD) => zop_predef");
  99. optPtr->priceType = zop_predef;
  100. }
  101. assert(optPtr->symbolCosts != NULL);
  102. if (optPtr->symbolCosts->huf.repeatMode == HUF_repeat_valid) {
  103. /* huffman table presumed generated by dictionary */
  104. optPtr->priceType = zop_dynamic;
  105. if (compressedLiterals) {
  106. unsigned lit;
  107. assert(optPtr->litFreq != NULL);
  108. optPtr->litSum = 0;
  109. for (lit=0; lit<=MaxLit; lit++) {
  110. U32 const scaleLog = 11; /* scale to 2K */
  111. U32 const bitCost = HUF_getNbBits(optPtr->symbolCosts->huf.CTable, lit);
  112. assert(bitCost <= scaleLog);
  113. optPtr->litFreq[lit] = bitCost ? 1 << (scaleLog-bitCost) : 1 /*minimum to calculate cost*/;
  114. optPtr->litSum += optPtr->litFreq[lit];
  115. } }
  116. { unsigned ll;
  117. FSE_CState_t llstate;
  118. FSE_initCState(&llstate, optPtr->symbolCosts->fse.litlengthCTable);
  119. optPtr->litLengthSum = 0;
  120. for (ll=0; ll<=MaxLL; ll++) {
  121. U32 const scaleLog = 10; /* scale to 1K */
  122. U32 const bitCost = FSE_getMaxNbBits(llstate.symbolTT, ll);
  123. assert(bitCost < scaleLog);
  124. optPtr->litLengthFreq[ll] = bitCost ? 1 << (scaleLog-bitCost) : 1 /*minimum to calculate cost*/;
  125. optPtr->litLengthSum += optPtr->litLengthFreq[ll];
  126. } }
  127. { unsigned ml;
  128. FSE_CState_t mlstate;
  129. FSE_initCState(&mlstate, optPtr->symbolCosts->fse.matchlengthCTable);
  130. optPtr->matchLengthSum = 0;
  131. for (ml=0; ml<=MaxML; ml++) {
  132. U32 const scaleLog = 10;
  133. U32 const bitCost = FSE_getMaxNbBits(mlstate.symbolTT, ml);
  134. assert(bitCost < scaleLog);
  135. optPtr->matchLengthFreq[ml] = bitCost ? 1 << (scaleLog-bitCost) : 1 /*minimum to calculate cost*/;
  136. optPtr->matchLengthSum += optPtr->matchLengthFreq[ml];
  137. } }
  138. { unsigned of;
  139. FSE_CState_t ofstate;
  140. FSE_initCState(&ofstate, optPtr->symbolCosts->fse.offcodeCTable);
  141. optPtr->offCodeSum = 0;
  142. for (of=0; of<=MaxOff; of++) {
  143. U32 const scaleLog = 10;
  144. U32 const bitCost = FSE_getMaxNbBits(ofstate.symbolTT, of);
  145. assert(bitCost < scaleLog);
  146. optPtr->offCodeFreq[of] = bitCost ? 1 << (scaleLog-bitCost) : 1 /*minimum to calculate cost*/;
  147. optPtr->offCodeSum += optPtr->offCodeFreq[of];
  148. } }
  149. } else { /* not a dictionary */
  150. assert(optPtr->litFreq != NULL);
  151. if (compressedLiterals) {
  152. unsigned lit = MaxLit;
  153. HIST_count_simple(optPtr->litFreq, &lit, src, srcSize); /* use raw first block to init statistics */
  154. optPtr->litSum = ZSTD_downscaleStat(optPtr->litFreq, MaxLit, 1);
  155. }
  156. { unsigned ll;
  157. for (ll=0; ll<=MaxLL; ll++)
  158. optPtr->litLengthFreq[ll] = 1;
  159. }
  160. optPtr->litLengthSum = MaxLL+1;
  161. { unsigned ml;
  162. for (ml=0; ml<=MaxML; ml++)
  163. optPtr->matchLengthFreq[ml] = 1;
  164. }
  165. optPtr->matchLengthSum = MaxML+1;
  166. { unsigned of;
  167. for (of=0; of<=MaxOff; of++)
  168. optPtr->offCodeFreq[of] = 1;
  169. }
  170. optPtr->offCodeSum = MaxOff+1;
  171. }
  172. } else { /* new block : re-use previous statistics, scaled down */
  173. if (compressedLiterals)
  174. optPtr->litSum = ZSTD_downscaleStat(optPtr->litFreq, MaxLit, 1);
  175. optPtr->litLengthSum = ZSTD_downscaleStat(optPtr->litLengthFreq, MaxLL, 0);
  176. optPtr->matchLengthSum = ZSTD_downscaleStat(optPtr->matchLengthFreq, MaxML, 0);
  177. optPtr->offCodeSum = ZSTD_downscaleStat(optPtr->offCodeFreq, MaxOff, 0);
  178. }
  179. ZSTD_setBasePrices(optPtr, optLevel);
  180. }
  181. /* ZSTD_rawLiteralsCost() :
  182. * price of literals (only) in specified segment (which length can be 0).
  183. * does not include price of literalLength symbol */
  184. static U32 ZSTD_rawLiteralsCost(const BYTE* const literals, U32 const litLength,
  185. const optState_t* const optPtr,
  186. int optLevel)
  187. {
  188. if (litLength == 0) return 0;
  189. if (!ZSTD_compressedLiterals(optPtr))
  190. return (litLength << 3) * BITCOST_MULTIPLIER; /* Uncompressed - 8 bytes per literal. */
  191. if (optPtr->priceType == zop_predef)
  192. return (litLength*6) * BITCOST_MULTIPLIER; /* 6 bit per literal - no statistic used */
  193. /* dynamic statistics */
  194. { U32 price = litLength * optPtr->litSumBasePrice;
  195. U32 u;
  196. for (u=0; u < litLength; u++) {
  197. assert(WEIGHT(optPtr->litFreq[literals[u]], optLevel) <= optPtr->litSumBasePrice); /* literal cost should never be negative */
  198. price -= WEIGHT(optPtr->litFreq[literals[u]], optLevel);
  199. }
  200. return price;
  201. }
  202. }
  203. /* ZSTD_litLengthPrice() :
  204. * cost of literalLength symbol */
  205. static U32 ZSTD_litLengthPrice(U32 const litLength, const optState_t* const optPtr, int optLevel)
  206. {
  207. if (optPtr->priceType == zop_predef) return WEIGHT(litLength, optLevel);
  208. /* dynamic statistics */
  209. { U32 const llCode = ZSTD_LLcode(litLength);
  210. return (LL_bits[llCode] * BITCOST_MULTIPLIER)
  211. + optPtr->litLengthSumBasePrice
  212. - WEIGHT(optPtr->litLengthFreq[llCode], optLevel);
  213. }
  214. }
  215. /* ZSTD_getMatchPrice() :
  216. * Provides the cost of the match part (offset + matchLength) of a sequence
  217. * Must be combined with ZSTD_fullLiteralsCost() to get the full cost of a sequence.
  218. * optLevel: when <2, favors small offset for decompression speed (improved cache efficiency) */
  219. FORCE_INLINE_TEMPLATE U32
  220. ZSTD_getMatchPrice(U32 const offset,
  221. U32 const matchLength,
  222. const optState_t* const optPtr,
  223. int const optLevel)
  224. {
  225. U32 price;
  226. U32 const offCode = ZSTD_highbit32(offset+1);
  227. U32 const mlBase = matchLength - MINMATCH;
  228. assert(matchLength >= MINMATCH);
  229. if (optPtr->priceType == zop_predef) /* fixed scheme, do not use statistics */
  230. return WEIGHT(mlBase, optLevel) + ((16 + offCode) * BITCOST_MULTIPLIER);
  231. /* dynamic statistics */
  232. price = (offCode * BITCOST_MULTIPLIER) + (optPtr->offCodeSumBasePrice - WEIGHT(optPtr->offCodeFreq[offCode], optLevel));
  233. if ((optLevel<2) /*static*/ && offCode >= 20)
  234. price += (offCode-19)*2 * BITCOST_MULTIPLIER; /* handicap for long distance offsets, favor decompression speed */
  235. /* match Length */
  236. { U32 const mlCode = ZSTD_MLcode(mlBase);
  237. price += (ML_bits[mlCode] * BITCOST_MULTIPLIER) + (optPtr->matchLengthSumBasePrice - WEIGHT(optPtr->matchLengthFreq[mlCode], optLevel));
  238. }
  239. price += BITCOST_MULTIPLIER / 5; /* heuristic : make matches a bit more costly to favor less sequences -> faster decompression speed */
  240. DEBUGLOG(8, "ZSTD_getMatchPrice(ml:%u) = %u", matchLength, price);
  241. return price;
  242. }
  243. /* ZSTD_updateStats() :
  244. * assumption : literals + litLengtn <= iend */
  245. static void ZSTD_updateStats(optState_t* const optPtr,
  246. U32 litLength, const BYTE* literals,
  247. U32 offsetCode, U32 matchLength)
  248. {
  249. /* literals */
  250. if (ZSTD_compressedLiterals(optPtr)) {
  251. U32 u;
  252. for (u=0; u < litLength; u++)
  253. optPtr->litFreq[literals[u]] += ZSTD_LITFREQ_ADD;
  254. optPtr->litSum += litLength*ZSTD_LITFREQ_ADD;
  255. }
  256. /* literal Length */
  257. { U32 const llCode = ZSTD_LLcode(litLength);
  258. optPtr->litLengthFreq[llCode]++;
  259. optPtr->litLengthSum++;
  260. }
  261. /* match offset code (0-2=>repCode; 3+=>offset+2) */
  262. { U32 const offCode = ZSTD_highbit32(offsetCode+1);
  263. assert(offCode <= MaxOff);
  264. optPtr->offCodeFreq[offCode]++;
  265. optPtr->offCodeSum++;
  266. }
  267. /* match Length */
  268. { U32 const mlBase = matchLength - MINMATCH;
  269. U32 const mlCode = ZSTD_MLcode(mlBase);
  270. optPtr->matchLengthFreq[mlCode]++;
  271. optPtr->matchLengthSum++;
  272. }
  273. }
  274. /* ZSTD_readMINMATCH() :
  275. * function safe only for comparisons
  276. * assumption : memPtr must be at least 4 bytes before end of buffer */
  277. MEM_STATIC U32 ZSTD_readMINMATCH(const void* memPtr, U32 length)
  278. {
  279. switch (length)
  280. {
  281. default :
  282. case 4 : return MEM_read32(memPtr);
  283. case 3 : if (MEM_isLittleEndian())
  284. return MEM_read32(memPtr)<<8;
  285. else
  286. return MEM_read32(memPtr)>>8;
  287. }
  288. }
  289. /* Update hashTable3 up to ip (excluded)
  290. Assumption : always within prefix (i.e. not within extDict) */
  291. static U32 ZSTD_insertAndFindFirstIndexHash3 (ZSTD_matchState_t* ms,
  292. U32* nextToUpdate3,
  293. const BYTE* const ip)
  294. {
  295. U32* const hashTable3 = ms->hashTable3;
  296. U32 const hashLog3 = ms->hashLog3;
  297. const BYTE* const base = ms->window.base;
  298. U32 idx = *nextToUpdate3;
  299. U32 const target = (U32)(ip - base);
  300. size_t const hash3 = ZSTD_hash3Ptr(ip, hashLog3);
  301. assert(hashLog3 > 0);
  302. while(idx < target) {
  303. hashTable3[ZSTD_hash3Ptr(base+idx, hashLog3)] = idx;
  304. idx++;
  305. }
  306. *nextToUpdate3 = target;
  307. return hashTable3[hash3];
  308. }
  309. /*-*************************************
  310. * Binary Tree search
  311. ***************************************/
  312. /** ZSTD_insertBt1() : add one or multiple positions to tree.
  313. * ip : assumed <= iend-8 .
  314. * @return : nb of positions added */
  315. static U32 ZSTD_insertBt1(
  316. ZSTD_matchState_t* ms,
  317. const BYTE* const ip, const BYTE* const iend,
  318. U32 const mls, const int extDict)
  319. {
  320. const ZSTD_compressionParameters* const cParams = &ms->cParams;
  321. U32* const hashTable = ms->hashTable;
  322. U32 const hashLog = cParams->hashLog;
  323. size_t const h = ZSTD_hashPtr(ip, hashLog, mls);
  324. U32* const bt = ms->chainTable;
  325. U32 const btLog = cParams->chainLog - 1;
  326. U32 const btMask = (1 << btLog) - 1;
  327. U32 matchIndex = hashTable[h];
  328. size_t commonLengthSmaller=0, commonLengthLarger=0;
  329. const BYTE* const base = ms->window.base;
  330. const BYTE* const dictBase = ms->window.dictBase;
  331. const U32 dictLimit = ms->window.dictLimit;
  332. const BYTE* const dictEnd = dictBase + dictLimit;
  333. const BYTE* const prefixStart = base + dictLimit;
  334. const BYTE* match;
  335. const U32 curr = (U32)(ip-base);
  336. const U32 btLow = btMask >= curr ? 0 : curr - btMask;
  337. U32* smallerPtr = bt + 2*(curr&btMask);
  338. U32* largerPtr = smallerPtr + 1;
  339. U32 dummy32; /* to be nullified at the end */
  340. U32 const windowLow = ms->window.lowLimit;
  341. U32 matchEndIdx = curr+8+1;
  342. size_t bestLength = 8;
  343. U32 nbCompares = 1U << cParams->searchLog;
  344. #ifdef ZSTD_C_PREDICT
  345. U32 predictedSmall = *(bt + 2*((curr-1)&btMask) + 0);
  346. U32 predictedLarge = *(bt + 2*((curr-1)&btMask) + 1);
  347. predictedSmall += (predictedSmall>0);
  348. predictedLarge += (predictedLarge>0);
  349. #endif /* ZSTD_C_PREDICT */
  350. DEBUGLOG(8, "ZSTD_insertBt1 (%u)", curr);
  351. assert(ip <= iend-8); /* required for h calculation */
  352. hashTable[h] = curr; /* Update Hash Table */
  353. assert(windowLow > 0);
  354. while (nbCompares-- && (matchIndex >= windowLow)) {
  355. U32* const nextPtr = bt + 2*(matchIndex & btMask);
  356. size_t matchLength = MIN(commonLengthSmaller, commonLengthLarger); /* guaranteed minimum nb of common bytes */
  357. assert(matchIndex < curr);
  358. #ifdef ZSTD_C_PREDICT /* note : can create issues when hlog small <= 11 */
  359. const U32* predictPtr = bt + 2*((matchIndex-1) & btMask); /* written this way, as bt is a roll buffer */
  360. if (matchIndex == predictedSmall) {
  361. /* no need to check length, result known */
  362. *smallerPtr = matchIndex;
  363. if (matchIndex <= btLow) { smallerPtr=&dummy32; break; } /* beyond tree size, stop the search */
  364. smallerPtr = nextPtr+1; /* new "smaller" => larger of match */
  365. matchIndex = nextPtr[1]; /* new matchIndex larger than previous (closer to current) */
  366. predictedSmall = predictPtr[1] + (predictPtr[1]>0);
  367. continue;
  368. }
  369. if (matchIndex == predictedLarge) {
  370. *largerPtr = matchIndex;
  371. if (matchIndex <= btLow) { largerPtr=&dummy32; break; } /* beyond tree size, stop the search */
  372. largerPtr = nextPtr;
  373. matchIndex = nextPtr[0];
  374. predictedLarge = predictPtr[0] + (predictPtr[0]>0);
  375. continue;
  376. }
  377. #endif
  378. if (!extDict || (matchIndex+matchLength >= dictLimit)) {
  379. assert(matchIndex+matchLength >= dictLimit); /* might be wrong if actually extDict */
  380. match = base + matchIndex;
  381. matchLength += ZSTD_count(ip+matchLength, match+matchLength, iend);
  382. } else {
  383. match = dictBase + matchIndex;
  384. matchLength += ZSTD_count_2segments(ip+matchLength, match+matchLength, iend, dictEnd, prefixStart);
  385. if (matchIndex+matchLength >= dictLimit)
  386. match = base + matchIndex; /* to prepare for next usage of match[matchLength] */
  387. }
  388. if (matchLength > bestLength) {
  389. bestLength = matchLength;
  390. if (matchLength > matchEndIdx - matchIndex)
  391. matchEndIdx = matchIndex + (U32)matchLength;
  392. }
  393. if (ip+matchLength == iend) { /* equal : no way to know if inf or sup */
  394. break; /* drop , to guarantee consistency ; miss a bit of compression, but other solutions can corrupt tree */
  395. }
  396. if (match[matchLength] < ip[matchLength]) { /* necessarily within buffer */
  397. /* match is smaller than current */
  398. *smallerPtr = matchIndex; /* update smaller idx */
  399. commonLengthSmaller = matchLength; /* all smaller will now have at least this guaranteed common length */
  400. if (matchIndex <= btLow) { smallerPtr=&dummy32; break; } /* beyond tree size, stop searching */
  401. smallerPtr = nextPtr+1; /* new "candidate" => larger than match, which was smaller than target */
  402. matchIndex = nextPtr[1]; /* new matchIndex, larger than previous and closer to current */
  403. } else {
  404. /* match is larger than current */
  405. *largerPtr = matchIndex;
  406. commonLengthLarger = matchLength;
  407. if (matchIndex <= btLow) { largerPtr=&dummy32; break; } /* beyond tree size, stop searching */
  408. largerPtr = nextPtr;
  409. matchIndex = nextPtr[0];
  410. } }
  411. *smallerPtr = *largerPtr = 0;
  412. { U32 positions = 0;
  413. if (bestLength > 384) positions = MIN(192, (U32)(bestLength - 384)); /* speed optimization */
  414. assert(matchEndIdx > curr + 8);
  415. return MAX(positions, matchEndIdx - (curr + 8));
  416. }
  417. }
  418. FORCE_INLINE_TEMPLATE
  419. void ZSTD_updateTree_internal(
  420. ZSTD_matchState_t* ms,
  421. const BYTE* const ip, const BYTE* const iend,
  422. const U32 mls, const ZSTD_dictMode_e dictMode)
  423. {
  424. const BYTE* const base = ms->window.base;
  425. U32 const target = (U32)(ip - base);
  426. U32 idx = ms->nextToUpdate;
  427. DEBUGLOG(6, "ZSTD_updateTree_internal, from %u to %u (dictMode:%u)",
  428. idx, target, dictMode);
  429. while(idx < target) {
  430. U32 const forward = ZSTD_insertBt1(ms, base+idx, iend, mls, dictMode == ZSTD_extDict);
  431. assert(idx < (U32)(idx + forward));
  432. idx += forward;
  433. }
  434. assert((size_t)(ip - base) <= (size_t)(U32)(-1));
  435. assert((size_t)(iend - base) <= (size_t)(U32)(-1));
  436. ms->nextToUpdate = target;
  437. }
  438. void ZSTD_updateTree(ZSTD_matchState_t* ms, const BYTE* ip, const BYTE* iend) {
  439. ZSTD_updateTree_internal(ms, ip, iend, ms->cParams.minMatch, ZSTD_noDict);
  440. }
  441. FORCE_INLINE_TEMPLATE
  442. U32 ZSTD_insertBtAndGetAllMatches (
  443. ZSTD_match_t* matches, /* store result (found matches) in this table (presumed large enough) */
  444. ZSTD_matchState_t* ms,
  445. U32* nextToUpdate3,
  446. const BYTE* const ip, const BYTE* const iLimit, const ZSTD_dictMode_e dictMode,
  447. const U32 rep[ZSTD_REP_NUM],
  448. U32 const ll0, /* tells if associated literal length is 0 or not. This value must be 0 or 1 */
  449. const U32 lengthToBeat,
  450. U32 const mls /* template */)
  451. {
  452. const ZSTD_compressionParameters* const cParams = &ms->cParams;
  453. U32 const sufficient_len = MIN(cParams->targetLength, ZSTD_OPT_NUM -1);
  454. const BYTE* const base = ms->window.base;
  455. U32 const curr = (U32)(ip-base);
  456. U32 const hashLog = cParams->hashLog;
  457. U32 const minMatch = (mls==3) ? 3 : 4;
  458. U32* const hashTable = ms->hashTable;
  459. size_t const h = ZSTD_hashPtr(ip, hashLog, mls);
  460. U32 matchIndex = hashTable[h];
  461. U32* const bt = ms->chainTable;
  462. U32 const btLog = cParams->chainLog - 1;
  463. U32 const btMask= (1U << btLog) - 1;
  464. size_t commonLengthSmaller=0, commonLengthLarger=0;
  465. const BYTE* const dictBase = ms->window.dictBase;
  466. U32 const dictLimit = ms->window.dictLimit;
  467. const BYTE* const dictEnd = dictBase + dictLimit;
  468. const BYTE* const prefixStart = base + dictLimit;
  469. U32 const btLow = (btMask >= curr) ? 0 : curr - btMask;
  470. U32 const windowLow = ZSTD_getLowestMatchIndex(ms, curr, cParams->windowLog);
  471. U32 const matchLow = windowLow ? windowLow : 1;
  472. U32* smallerPtr = bt + 2*(curr&btMask);
  473. U32* largerPtr = bt + 2*(curr&btMask) + 1;
  474. U32 matchEndIdx = curr+8+1; /* farthest referenced position of any match => detects repetitive patterns */
  475. U32 dummy32; /* to be nullified at the end */
  476. U32 mnum = 0;
  477. U32 nbCompares = 1U << cParams->searchLog;
  478. const ZSTD_matchState_t* dms = dictMode == ZSTD_dictMatchState ? ms->dictMatchState : NULL;
  479. const ZSTD_compressionParameters* const dmsCParams =
  480. dictMode == ZSTD_dictMatchState ? &dms->cParams : NULL;
  481. const BYTE* const dmsBase = dictMode == ZSTD_dictMatchState ? dms->window.base : NULL;
  482. const BYTE* const dmsEnd = dictMode == ZSTD_dictMatchState ? dms->window.nextSrc : NULL;
  483. U32 const dmsHighLimit = dictMode == ZSTD_dictMatchState ? (U32)(dmsEnd - dmsBase) : 0;
  484. U32 const dmsLowLimit = dictMode == ZSTD_dictMatchState ? dms->window.lowLimit : 0;
  485. U32 const dmsIndexDelta = dictMode == ZSTD_dictMatchState ? windowLow - dmsHighLimit : 0;
  486. U32 const dmsHashLog = dictMode == ZSTD_dictMatchState ? dmsCParams->hashLog : hashLog;
  487. U32 const dmsBtLog = dictMode == ZSTD_dictMatchState ? dmsCParams->chainLog - 1 : btLog;
  488. U32 const dmsBtMask = dictMode == ZSTD_dictMatchState ? (1U << dmsBtLog) - 1 : 0;
  489. U32 const dmsBtLow = dictMode == ZSTD_dictMatchState && dmsBtMask < dmsHighLimit - dmsLowLimit ? dmsHighLimit - dmsBtMask : dmsLowLimit;
  490. size_t bestLength = lengthToBeat-1;
  491. DEBUGLOG(8, "ZSTD_insertBtAndGetAllMatches: current=%u", curr);
  492. /* check repCode */
  493. assert(ll0 <= 1); /* necessarily 1 or 0 */
  494. { U32 const lastR = ZSTD_REP_NUM + ll0;
  495. U32 repCode;
  496. for (repCode = ll0; repCode < lastR; repCode++) {
  497. U32 const repOffset = (repCode==ZSTD_REP_NUM) ? (rep[0] - 1) : rep[repCode];
  498. U32 const repIndex = curr - repOffset;
  499. U32 repLen = 0;
  500. assert(curr >= dictLimit);
  501. if (repOffset-1 /* intentional overflow, discards 0 and -1 */ < curr-dictLimit) { /* equivalent to `curr > repIndex >= dictLimit` */
  502. /* We must validate the repcode offset because when we're using a dictionary the
  503. * valid offset range shrinks when the dictionary goes out of bounds.
  504. */
  505. if ((repIndex >= windowLow) & (ZSTD_readMINMATCH(ip, minMatch) == ZSTD_readMINMATCH(ip - repOffset, minMatch))) {
  506. repLen = (U32)ZSTD_count(ip+minMatch, ip+minMatch-repOffset, iLimit) + minMatch;
  507. }
  508. } else { /* repIndex < dictLimit || repIndex >= curr */
  509. const BYTE* const repMatch = dictMode == ZSTD_dictMatchState ?
  510. dmsBase + repIndex - dmsIndexDelta :
  511. dictBase + repIndex;
  512. assert(curr >= windowLow);
  513. if ( dictMode == ZSTD_extDict
  514. && ( ((repOffset-1) /*intentional overflow*/ < curr - windowLow) /* equivalent to `curr > repIndex >= windowLow` */
  515. & (((U32)((dictLimit-1) - repIndex) >= 3) ) /* intentional overflow : do not test positions overlapping 2 memory segments */)
  516. && (ZSTD_readMINMATCH(ip, minMatch) == ZSTD_readMINMATCH(repMatch, minMatch)) ) {
  517. repLen = (U32)ZSTD_count_2segments(ip+minMatch, repMatch+minMatch, iLimit, dictEnd, prefixStart) + minMatch;
  518. }
  519. if (dictMode == ZSTD_dictMatchState
  520. && ( ((repOffset-1) /*intentional overflow*/ < curr - (dmsLowLimit + dmsIndexDelta)) /* equivalent to `curr > repIndex >= dmsLowLimit` */
  521. & ((U32)((dictLimit-1) - repIndex) >= 3) ) /* intentional overflow : do not test positions overlapping 2 memory segments */
  522. && (ZSTD_readMINMATCH(ip, minMatch) == ZSTD_readMINMATCH(repMatch, minMatch)) ) {
  523. repLen = (U32)ZSTD_count_2segments(ip+minMatch, repMatch+minMatch, iLimit, dmsEnd, prefixStart) + minMatch;
  524. } }
  525. /* save longer solution */
  526. if (repLen > bestLength) {
  527. DEBUGLOG(8, "found repCode %u (ll0:%u, offset:%u) of length %u",
  528. repCode, ll0, repOffset, repLen);
  529. bestLength = repLen;
  530. matches[mnum].off = repCode - ll0;
  531. matches[mnum].len = (U32)repLen;
  532. mnum++;
  533. if ( (repLen > sufficient_len)
  534. | (ip+repLen == iLimit) ) { /* best possible */
  535. return mnum;
  536. } } } }
  537. /* HC3 match finder */
  538. if ((mls == 3) /*static*/ && (bestLength < mls)) {
  539. U32 const matchIndex3 = ZSTD_insertAndFindFirstIndexHash3(ms, nextToUpdate3, ip);
  540. if ((matchIndex3 >= matchLow)
  541. & (curr - matchIndex3 < (1<<18)) /*heuristic : longer distance likely too expensive*/ ) {
  542. size_t mlen;
  543. if ((dictMode == ZSTD_noDict) /*static*/ || (dictMode == ZSTD_dictMatchState) /*static*/ || (matchIndex3 >= dictLimit)) {
  544. const BYTE* const match = base + matchIndex3;
  545. mlen = ZSTD_count(ip, match, iLimit);
  546. } else {
  547. const BYTE* const match = dictBase + matchIndex3;
  548. mlen = ZSTD_count_2segments(ip, match, iLimit, dictEnd, prefixStart);
  549. }
  550. /* save best solution */
  551. if (mlen >= mls /* == 3 > bestLength */) {
  552. DEBUGLOG(8, "found small match with hlog3, of length %u",
  553. (U32)mlen);
  554. bestLength = mlen;
  555. assert(curr > matchIndex3);
  556. assert(mnum==0); /* no prior solution */
  557. matches[0].off = (curr - matchIndex3) + ZSTD_REP_MOVE;
  558. matches[0].len = (U32)mlen;
  559. mnum = 1;
  560. if ( (mlen > sufficient_len) |
  561. (ip+mlen == iLimit) ) { /* best possible length */
  562. ms->nextToUpdate = curr+1; /* skip insertion */
  563. return 1;
  564. } } }
  565. /* no dictMatchState lookup: dicts don't have a populated HC3 table */
  566. }
  567. hashTable[h] = curr; /* Update Hash Table */
  568. while (nbCompares-- && (matchIndex >= matchLow)) {
  569. U32* const nextPtr = bt + 2*(matchIndex & btMask);
  570. const BYTE* match;
  571. size_t matchLength = MIN(commonLengthSmaller, commonLengthLarger); /* guaranteed minimum nb of common bytes */
  572. assert(curr > matchIndex);
  573. if ((dictMode == ZSTD_noDict) || (dictMode == ZSTD_dictMatchState) || (matchIndex+matchLength >= dictLimit)) {
  574. assert(matchIndex+matchLength >= dictLimit); /* ensure the condition is correct when !extDict */
  575. match = base + matchIndex;
  576. if (matchIndex >= dictLimit) assert(memcmp(match, ip, matchLength) == 0); /* ensure early section of match is equal as expected */
  577. matchLength += ZSTD_count(ip+matchLength, match+matchLength, iLimit);
  578. } else {
  579. match = dictBase + matchIndex;
  580. assert(memcmp(match, ip, matchLength) == 0); /* ensure early section of match is equal as expected */
  581. matchLength += ZSTD_count_2segments(ip+matchLength, match+matchLength, iLimit, dictEnd, prefixStart);
  582. if (matchIndex+matchLength >= dictLimit)
  583. match = base + matchIndex; /* prepare for match[matchLength] read */
  584. }
  585. if (matchLength > bestLength) {
  586. DEBUGLOG(8, "found match of length %u at distance %u (offCode=%u)",
  587. (U32)matchLength, curr - matchIndex, curr - matchIndex + ZSTD_REP_MOVE);
  588. assert(matchEndIdx > matchIndex);
  589. if (matchLength > matchEndIdx - matchIndex)
  590. matchEndIdx = matchIndex + (U32)matchLength;
  591. bestLength = matchLength;
  592. matches[mnum].off = (curr - matchIndex) + ZSTD_REP_MOVE;
  593. matches[mnum].len = (U32)matchLength;
  594. mnum++;
  595. if ( (matchLength > ZSTD_OPT_NUM)
  596. | (ip+matchLength == iLimit) /* equal : no way to know if inf or sup */) {
  597. if (dictMode == ZSTD_dictMatchState) nbCompares = 0; /* break should also skip searching dms */
  598. break; /* drop, to preserve bt consistency (miss a little bit of compression) */
  599. }
  600. }
  601. if (match[matchLength] < ip[matchLength]) {
  602. /* match smaller than current */
  603. *smallerPtr = matchIndex; /* update smaller idx */
  604. commonLengthSmaller = matchLength; /* all smaller will now have at least this guaranteed common length */
  605. if (matchIndex <= btLow) { smallerPtr=&dummy32; break; } /* beyond tree size, stop the search */
  606. smallerPtr = nextPtr+1; /* new candidate => larger than match, which was smaller than current */
  607. matchIndex = nextPtr[1]; /* new matchIndex, larger than previous, closer to current */
  608. } else {
  609. *largerPtr = matchIndex;
  610. commonLengthLarger = matchLength;
  611. if (matchIndex <= btLow) { largerPtr=&dummy32; break; } /* beyond tree size, stop the search */
  612. largerPtr = nextPtr;
  613. matchIndex = nextPtr[0];
  614. } }
  615. *smallerPtr = *largerPtr = 0;
  616. if (dictMode == ZSTD_dictMatchState && nbCompares) {
  617. size_t const dmsH = ZSTD_hashPtr(ip, dmsHashLog, mls);
  618. U32 dictMatchIndex = dms->hashTable[dmsH];
  619. const U32* const dmsBt = dms->chainTable;
  620. commonLengthSmaller = commonLengthLarger = 0;
  621. while (nbCompares-- && (dictMatchIndex > dmsLowLimit)) {
  622. const U32* const nextPtr = dmsBt + 2*(dictMatchIndex & dmsBtMask);
  623. size_t matchLength = MIN(commonLengthSmaller, commonLengthLarger); /* guaranteed minimum nb of common bytes */
  624. const BYTE* match = dmsBase + dictMatchIndex;
  625. matchLength += ZSTD_count_2segments(ip+matchLength, match+matchLength, iLimit, dmsEnd, prefixStart);
  626. if (dictMatchIndex+matchLength >= dmsHighLimit)
  627. match = base + dictMatchIndex + dmsIndexDelta; /* to prepare for next usage of match[matchLength] */
  628. if (matchLength > bestLength) {
  629. matchIndex = dictMatchIndex + dmsIndexDelta;
  630. DEBUGLOG(8, "found dms match of length %u at distance %u (offCode=%u)",
  631. (U32)matchLength, curr - matchIndex, curr - matchIndex + ZSTD_REP_MOVE);
  632. if (matchLength > matchEndIdx - matchIndex)
  633. matchEndIdx = matchIndex + (U32)matchLength;
  634. bestLength = matchLength;
  635. matches[mnum].off = (curr - matchIndex) + ZSTD_REP_MOVE;
  636. matches[mnum].len = (U32)matchLength;
  637. mnum++;
  638. if ( (matchLength > ZSTD_OPT_NUM)
  639. | (ip+matchLength == iLimit) /* equal : no way to know if inf or sup */) {
  640. break; /* drop, to guarantee consistency (miss a little bit of compression) */
  641. }
  642. }
  643. if (dictMatchIndex <= dmsBtLow) { break; } /* beyond tree size, stop the search */
  644. if (match[matchLength] < ip[matchLength]) {
  645. commonLengthSmaller = matchLength; /* all smaller will now have at least this guaranteed common length */
  646. dictMatchIndex = nextPtr[1]; /* new matchIndex larger than previous (closer to current) */
  647. } else {
  648. /* match is larger than current */
  649. commonLengthLarger = matchLength;
  650. dictMatchIndex = nextPtr[0];
  651. }
  652. }
  653. }
  654. assert(matchEndIdx > curr+8);
  655. ms->nextToUpdate = matchEndIdx - 8; /* skip repetitive patterns */
  656. return mnum;
  657. }
  658. FORCE_INLINE_TEMPLATE U32 ZSTD_BtGetAllMatches (
  659. ZSTD_match_t* matches, /* store result (match found, increasing size) in this table */
  660. ZSTD_matchState_t* ms,
  661. U32* nextToUpdate3,
  662. const BYTE* ip, const BYTE* const iHighLimit, const ZSTD_dictMode_e dictMode,
  663. const U32 rep[ZSTD_REP_NUM],
  664. U32 const ll0,
  665. U32 const lengthToBeat)
  666. {
  667. const ZSTD_compressionParameters* const cParams = &ms->cParams;
  668. U32 const matchLengthSearch = cParams->minMatch;
  669. DEBUGLOG(8, "ZSTD_BtGetAllMatches");
  670. if (ip < ms->window.base + ms->nextToUpdate) return 0; /* skipped area */
  671. ZSTD_updateTree_internal(ms, ip, iHighLimit, matchLengthSearch, dictMode);
  672. switch(matchLengthSearch)
  673. {
  674. case 3 : return ZSTD_insertBtAndGetAllMatches(matches, ms, nextToUpdate3, ip, iHighLimit, dictMode, rep, ll0, lengthToBeat, 3);
  675. default :
  676. case 4 : return ZSTD_insertBtAndGetAllMatches(matches, ms, nextToUpdate3, ip, iHighLimit, dictMode, rep, ll0, lengthToBeat, 4);
  677. case 5 : return ZSTD_insertBtAndGetAllMatches(matches, ms, nextToUpdate3, ip, iHighLimit, dictMode, rep, ll0, lengthToBeat, 5);
  678. case 7 :
  679. case 6 : return ZSTD_insertBtAndGetAllMatches(matches, ms, nextToUpdate3, ip, iHighLimit, dictMode, rep, ll0, lengthToBeat, 6);
  680. }
  681. }
  682. /*************************
  683. * LDM helper functions *
  684. *************************/
  685. /* Struct containing info needed to make decision about ldm inclusion */
  686. typedef struct {
  687. rawSeqStore_t seqStore; /* External match candidates store for this block */
  688. U32 startPosInBlock; /* Start position of the current match candidate */
  689. U32 endPosInBlock; /* End position of the current match candidate */
  690. U32 offset; /* Offset of the match candidate */
  691. } ZSTD_optLdm_t;
  692. /* ZSTD_optLdm_skipRawSeqStoreBytes():
  693. * Moves forward in rawSeqStore by nbBytes, which will update the fields 'pos' and 'posInSequence'.
  694. */
  695. static void ZSTD_optLdm_skipRawSeqStoreBytes(rawSeqStore_t* rawSeqStore, size_t nbBytes) {
  696. U32 currPos = (U32)(rawSeqStore->posInSequence + nbBytes);
  697. while (currPos && rawSeqStore->pos < rawSeqStore->size) {
  698. rawSeq currSeq = rawSeqStore->seq[rawSeqStore->pos];
  699. if (currPos >= currSeq.litLength + currSeq.matchLength) {
  700. currPos -= currSeq.litLength + currSeq.matchLength;
  701. rawSeqStore->pos++;
  702. } else {
  703. rawSeqStore->posInSequence = currPos;
  704. break;
  705. }
  706. }
  707. if (currPos == 0 || rawSeqStore->pos == rawSeqStore->size) {
  708. rawSeqStore->posInSequence = 0;
  709. }
  710. }
  711. /* ZSTD_opt_getNextMatchAndUpdateSeqStore():
  712. * Calculates the beginning and end of the next match in the current block.
  713. * Updates 'pos' and 'posInSequence' of the ldmSeqStore.
  714. */
  715. static void ZSTD_opt_getNextMatchAndUpdateSeqStore(ZSTD_optLdm_t* optLdm, U32 currPosInBlock,
  716. U32 blockBytesRemaining) {
  717. rawSeq currSeq;
  718. U32 currBlockEndPos;
  719. U32 literalsBytesRemaining;
  720. U32 matchBytesRemaining;
  721. /* Setting match end position to MAX to ensure we never use an LDM during this block */
  722. if (optLdm->seqStore.size == 0 || optLdm->seqStore.pos >= optLdm->seqStore.size) {
  723. optLdm->startPosInBlock = UINT_MAX;
  724. optLdm->endPosInBlock = UINT_MAX;
  725. return;
  726. }
  727. /* Calculate appropriate bytes left in matchLength and litLength after adjusting
  728. based on ldmSeqStore->posInSequence */
  729. currSeq = optLdm->seqStore.seq[optLdm->seqStore.pos];
  730. assert(optLdm->seqStore.posInSequence <= currSeq.litLength + currSeq.matchLength);
  731. currBlockEndPos = currPosInBlock + blockBytesRemaining;
  732. literalsBytesRemaining = (optLdm->seqStore.posInSequence < currSeq.litLength) ?
  733. currSeq.litLength - (U32)optLdm->seqStore.posInSequence :
  734. 0;
  735. matchBytesRemaining = (literalsBytesRemaining == 0) ?
  736. currSeq.matchLength - ((U32)optLdm->seqStore.posInSequence - currSeq.litLength) :
  737. currSeq.matchLength;
  738. /* If there are more literal bytes than bytes remaining in block, no ldm is possible */
  739. if (literalsBytesRemaining >= blockBytesRemaining) {
  740. optLdm->startPosInBlock = UINT_MAX;
  741. optLdm->endPosInBlock = UINT_MAX;
  742. ZSTD_optLdm_skipRawSeqStoreBytes(&optLdm->seqStore, blockBytesRemaining);
  743. return;
  744. }
  745. /* Matches may be < MINMATCH by this process. In that case, we will reject them
  746. when we are deciding whether or not to add the ldm */
  747. optLdm->startPosInBlock = currPosInBlock + literalsBytesRemaining;
  748. optLdm->endPosInBlock = optLdm->startPosInBlock + matchBytesRemaining;
  749. optLdm->offset = currSeq.offset;
  750. if (optLdm->endPosInBlock > currBlockEndPos) {
  751. /* Match ends after the block ends, we can't use the whole match */
  752. optLdm->endPosInBlock = currBlockEndPos;
  753. ZSTD_optLdm_skipRawSeqStoreBytes(&optLdm->seqStore, currBlockEndPos - currPosInBlock);
  754. } else {
  755. /* Consume nb of bytes equal to size of sequence left */
  756. ZSTD_optLdm_skipRawSeqStoreBytes(&optLdm->seqStore, literalsBytesRemaining + matchBytesRemaining);
  757. }
  758. }
  759. /* ZSTD_optLdm_maybeAddMatch():
  760. * Adds a match if it's long enough, based on it's 'matchStartPosInBlock'
  761. * and 'matchEndPosInBlock', into 'matches'. Maintains the correct ordering of 'matches'
  762. */
  763. static void ZSTD_optLdm_maybeAddMatch(ZSTD_match_t* matches, U32* nbMatches,
  764. ZSTD_optLdm_t* optLdm, U32 currPosInBlock) {
  765. U32 posDiff = currPosInBlock - optLdm->startPosInBlock;
  766. /* Note: ZSTD_match_t actually contains offCode and matchLength (before subtracting MINMATCH) */
  767. U32 candidateMatchLength = optLdm->endPosInBlock - optLdm->startPosInBlock - posDiff;
  768. U32 candidateOffCode = optLdm->offset + ZSTD_REP_MOVE;
  769. /* Ensure that current block position is not outside of the match */
  770. if (currPosInBlock < optLdm->startPosInBlock
  771. || currPosInBlock >= optLdm->endPosInBlock
  772. || candidateMatchLength < MINMATCH) {
  773. return;
  774. }
  775. if (*nbMatches == 0 || ((candidateMatchLength > matches[*nbMatches-1].len) && *nbMatches < ZSTD_OPT_NUM)) {
  776. DEBUGLOG(6, "ZSTD_optLdm_maybeAddMatch(): Adding ldm candidate match (offCode: %u matchLength %u) at block position=%u",
  777. candidateOffCode, candidateMatchLength, currPosInBlock);
  778. matches[*nbMatches].len = candidateMatchLength;
  779. matches[*nbMatches].off = candidateOffCode;
  780. (*nbMatches)++;
  781. }
  782. }
  783. /* ZSTD_optLdm_processMatchCandidate():
  784. * Wrapper function to update ldm seq store and call ldm functions as necessary.
  785. */
  786. static void ZSTD_optLdm_processMatchCandidate(ZSTD_optLdm_t* optLdm, ZSTD_match_t* matches, U32* nbMatches,
  787. U32 currPosInBlock, U32 remainingBytes) {
  788. if (optLdm->seqStore.size == 0 || optLdm->seqStore.pos >= optLdm->seqStore.size) {
  789. return;
  790. }
  791. if (currPosInBlock >= optLdm->endPosInBlock) {
  792. if (currPosInBlock > optLdm->endPosInBlock) {
  793. /* The position at which ZSTD_optLdm_processMatchCandidate() is called is not necessarily
  794. * at the end of a match from the ldm seq store, and will often be some bytes
  795. * over beyond matchEndPosInBlock. As such, we need to correct for these "overshoots"
  796. */
  797. U32 posOvershoot = currPosInBlock - optLdm->endPosInBlock;
  798. ZSTD_optLdm_skipRawSeqStoreBytes(&optLdm->seqStore, posOvershoot);
  799. }
  800. ZSTD_opt_getNextMatchAndUpdateSeqStore(optLdm, currPosInBlock, remainingBytes);
  801. }
  802. ZSTD_optLdm_maybeAddMatch(matches, nbMatches, optLdm, currPosInBlock);
  803. }
  804. /*-*******************************
  805. * Optimal parser
  806. *********************************/
  807. static U32 ZSTD_totalLen(ZSTD_optimal_t sol)
  808. {
  809. return sol.litlen + sol.mlen;
  810. }
  811. #if 0 /* debug */
  812. static void
  813. listStats(const U32* table, int lastEltID)
  814. {
  815. int const nbElts = lastEltID + 1;
  816. int enb;
  817. for (enb=0; enb < nbElts; enb++) {
  818. (void)table;
  819. /* RAWLOG(2, "%3i:%3i, ", enb, table[enb]); */
  820. RAWLOG(2, "%4i,", table[enb]);
  821. }
  822. RAWLOG(2, " \n");
  823. }
  824. #endif
  825. FORCE_INLINE_TEMPLATE size_t
  826. ZSTD_compressBlock_opt_generic(ZSTD_matchState_t* ms,
  827. seqStore_t* seqStore,
  828. U32 rep[ZSTD_REP_NUM],
  829. const void* src, size_t srcSize,
  830. const int optLevel,
  831. const ZSTD_dictMode_e dictMode)
  832. {
  833. optState_t* const optStatePtr = &ms->opt;
  834. const BYTE* const istart = (const BYTE*)src;
  835. const BYTE* ip = istart;
  836. const BYTE* anchor = istart;
  837. const BYTE* const iend = istart + srcSize;
  838. const BYTE* const ilimit = iend - 8;
  839. const BYTE* const base = ms->window.base;
  840. const BYTE* const prefixStart = base + ms->window.dictLimit;
  841. const ZSTD_compressionParameters* const cParams = &ms->cParams;
  842. U32 const sufficient_len = MIN(cParams->targetLength, ZSTD_OPT_NUM -1);
  843. U32 const minMatch = (cParams->minMatch == 3) ? 3 : 4;
  844. U32 nextToUpdate3 = ms->nextToUpdate;
  845. ZSTD_optimal_t* const opt = optStatePtr->priceTable;
  846. ZSTD_match_t* const matches = optStatePtr->matchTable;
  847. ZSTD_optimal_t lastSequence;
  848. ZSTD_optLdm_t optLdm;
  849. optLdm.seqStore = ms->ldmSeqStore ? *ms->ldmSeqStore : kNullRawSeqStore;
  850. optLdm.endPosInBlock = optLdm.startPosInBlock = optLdm.offset = 0;
  851. ZSTD_opt_getNextMatchAndUpdateSeqStore(&optLdm, (U32)(ip-istart), (U32)(iend-ip));
  852. /* init */
  853. DEBUGLOG(5, "ZSTD_compressBlock_opt_generic: current=%u, prefix=%u, nextToUpdate=%u",
  854. (U32)(ip - base), ms->window.dictLimit, ms->nextToUpdate);
  855. assert(optLevel <= 2);
  856. ZSTD_rescaleFreqs(optStatePtr, (const BYTE*)src, srcSize, optLevel);
  857. ip += (ip==prefixStart);
  858. /* Match Loop */
  859. while (ip < ilimit) {
  860. U32 cur, last_pos = 0;
  861. /* find first match */
  862. { U32 const litlen = (U32)(ip - anchor);
  863. U32 const ll0 = !litlen;
  864. U32 nbMatches = ZSTD_BtGetAllMatches(matches, ms, &nextToUpdate3, ip, iend, dictMode, rep, ll0, minMatch);
  865. ZSTD_optLdm_processMatchCandidate(&optLdm, matches, &nbMatches,
  866. (U32)(ip-istart), (U32)(iend - ip));
  867. if (!nbMatches) { ip++; continue; }
  868. /* initialize opt[0] */
  869. { U32 i ; for (i=0; i<ZSTD_REP_NUM; i++) opt[0].rep[i] = rep[i]; }
  870. opt[0].mlen = 0; /* means is_a_literal */
  871. opt[0].litlen = litlen;
  872. /* We don't need to include the actual price of the literals because
  873. * it is static for the duration of the forward pass, and is included
  874. * in every price. We include the literal length to avoid negative
  875. * prices when we subtract the previous literal length.
  876. */
  877. opt[0].price = ZSTD_litLengthPrice(litlen, optStatePtr, optLevel);
  878. /* large match -> immediate encoding */
  879. { U32 const maxML = matches[nbMatches-1].len;
  880. U32 const maxOffset = matches[nbMatches-1].off;
  881. DEBUGLOG(6, "found %u matches of maxLength=%u and maxOffCode=%u at cPos=%u => start new series",
  882. nbMatches, maxML, maxOffset, (U32)(ip-prefixStart));
  883. if (maxML > sufficient_len) {
  884. lastSequence.litlen = litlen;
  885. lastSequence.mlen = maxML;
  886. lastSequence.off = maxOffset;
  887. DEBUGLOG(6, "large match (%u>%u), immediate encoding",
  888. maxML, sufficient_len);
  889. cur = 0;
  890. last_pos = ZSTD_totalLen(lastSequence);
  891. goto _shortestPath;
  892. } }
  893. /* set prices for first matches starting position == 0 */
  894. { U32 const literalsPrice = opt[0].price + ZSTD_litLengthPrice(0, optStatePtr, optLevel);
  895. U32 pos;
  896. U32 matchNb;
  897. for (pos = 1; pos < minMatch; pos++) {
  898. opt[pos].price = ZSTD_MAX_PRICE; /* mlen, litlen and price will be fixed during forward scanning */
  899. }
  900. for (matchNb = 0; matchNb < nbMatches; matchNb++) {
  901. U32 const offset = matches[matchNb].off;
  902. U32 const end = matches[matchNb].len;
  903. for ( ; pos <= end ; pos++ ) {
  904. U32 const matchPrice = ZSTD_getMatchPrice(offset, pos, optStatePtr, optLevel);
  905. U32 const sequencePrice = literalsPrice + matchPrice;
  906. DEBUGLOG(7, "rPos:%u => set initial price : %.2f",
  907. pos, ZSTD_fCost(sequencePrice));
  908. opt[pos].mlen = pos;
  909. opt[pos].off = offset;
  910. opt[pos].litlen = litlen;
  911. opt[pos].price = sequencePrice;
  912. } }
  913. last_pos = pos-1;
  914. }
  915. }
  916. /* check further positions */
  917. for (cur = 1; cur <= last_pos; cur++) {
  918. const BYTE* const inr = ip + cur;
  919. assert(cur < ZSTD_OPT_NUM);
  920. DEBUGLOG(7, "cPos:%zi==rPos:%u", inr-istart, cur)
  921. /* Fix current position with one literal if cheaper */
  922. { U32 const litlen = (opt[cur-1].mlen == 0) ? opt[cur-1].litlen + 1 : 1;
  923. int const price = opt[cur-1].price
  924. + ZSTD_rawLiteralsCost(ip+cur-1, 1, optStatePtr, optLevel)
  925. + ZSTD_litLengthPrice(litlen, optStatePtr, optLevel)
  926. - ZSTD_litLengthPrice(litlen-1, optStatePtr, optLevel);
  927. assert(price < 1000000000); /* overflow check */
  928. if (price <= opt[cur].price) {
  929. DEBUGLOG(7, "cPos:%zi==rPos:%u : better price (%.2f<=%.2f) using literal (ll==%u) (hist:%u,%u,%u)",
  930. inr-istart, cur, ZSTD_fCost(price), ZSTD_fCost(opt[cur].price), litlen,
  931. opt[cur-1].rep[0], opt[cur-1].rep[1], opt[cur-1].rep[2]);
  932. opt[cur].mlen = 0;
  933. opt[cur].off = 0;
  934. opt[cur].litlen = litlen;
  935. opt[cur].price = price;
  936. } else {
  937. DEBUGLOG(7, "cPos:%zi==rPos:%u : literal would cost more (%.2f>%.2f) (hist:%u,%u,%u)",
  938. inr-istart, cur, ZSTD_fCost(price), ZSTD_fCost(opt[cur].price),
  939. opt[cur].rep[0], opt[cur].rep[1], opt[cur].rep[2]);
  940. }
  941. }
  942. /* Set the repcodes of the current position. We must do it here
  943. * because we rely on the repcodes of the 2nd to last sequence being
  944. * correct to set the next chunks repcodes during the backward
  945. * traversal.
  946. */
  947. ZSTD_STATIC_ASSERT(sizeof(opt[cur].rep) == sizeof(repcodes_t));
  948. assert(cur >= opt[cur].mlen);
  949. if (opt[cur].mlen != 0) {
  950. U32 const prev = cur - opt[cur].mlen;
  951. repcodes_t newReps = ZSTD_updateRep(opt[prev].rep, opt[cur].off, opt[cur].litlen==0);
  952. ZSTD_memcpy(opt[cur].rep, &newReps, sizeof(repcodes_t));
  953. } else {
  954. ZSTD_memcpy(opt[cur].rep, opt[cur - 1].rep, sizeof(repcodes_t));
  955. }
  956. /* last match must start at a minimum distance of 8 from oend */
  957. if (inr > ilimit) continue;
  958. if (cur == last_pos) break;
  959. if ( (optLevel==0) /*static_test*/
  960. && (opt[cur+1].price <= opt[cur].price + (BITCOST_MULTIPLIER/2)) ) {
  961. DEBUGLOG(7, "move to next rPos:%u : price is <=", cur+1);
  962. continue; /* skip unpromising positions; about ~+6% speed, -0.01 ratio */
  963. }
  964. { U32 const ll0 = (opt[cur].mlen != 0);
  965. U32 const litlen = (opt[cur].mlen == 0) ? opt[cur].litlen : 0;
  966. U32 const previousPrice = opt[cur].price;
  967. U32 const basePrice = previousPrice + ZSTD_litLengthPrice(0, optStatePtr, optLevel);
  968. U32 nbMatches = ZSTD_BtGetAllMatches(matches, ms, &nextToUpdate3, inr, iend, dictMode, opt[cur].rep, ll0, minMatch);
  969. U32 matchNb;
  970. ZSTD_optLdm_processMatchCandidate(&optLdm, matches, &nbMatches,
  971. (U32)(inr-istart), (U32)(iend-inr));
  972. if (!nbMatches) {
  973. DEBUGLOG(7, "rPos:%u : no match found", cur);
  974. continue;
  975. }
  976. { U32 const maxML = matches[nbMatches-1].len;
  977. DEBUGLOG(7, "cPos:%zi==rPos:%u, found %u matches, of maxLength=%u",
  978. inr-istart, cur, nbMatches, maxML);
  979. if ( (maxML > sufficient_len)
  980. || (cur + maxML >= ZSTD_OPT_NUM) ) {
  981. lastSequence.mlen = maxML;
  982. lastSequence.off = matches[nbMatches-1].off;
  983. lastSequence.litlen = litlen;
  984. cur -= (opt[cur].mlen==0) ? opt[cur].litlen : 0; /* last sequence is actually only literals, fix cur to last match - note : may underflow, in which case, it's first sequence, and it's okay */
  985. last_pos = cur + ZSTD_totalLen(lastSequence);
  986. if (cur > ZSTD_OPT_NUM) cur = 0; /* underflow => first match */
  987. goto _shortestPath;
  988. } }
  989. /* set prices using matches found at position == cur */
  990. for (matchNb = 0; matchNb < nbMatches; matchNb++) {
  991. U32 const offset = matches[matchNb].off;
  992. U32 const lastML = matches[matchNb].len;
  993. U32 const startML = (matchNb>0) ? matches[matchNb-1].len+1 : minMatch;
  994. U32 mlen;
  995. DEBUGLOG(7, "testing match %u => offCode=%4u, mlen=%2u, llen=%2u",
  996. matchNb, matches[matchNb].off, lastML, litlen);
  997. for (mlen = lastML; mlen >= startML; mlen--) { /* scan downward */
  998. U32 const pos = cur + mlen;
  999. int const price = basePrice + ZSTD_getMatchPrice(offset, mlen, optStatePtr, optLevel);
  1000. if ((pos > last_pos) || (price < opt[pos].price)) {
  1001. DEBUGLOG(7, "rPos:%u (ml=%2u) => new better price (%.2f<%.2f)",
  1002. pos, mlen, ZSTD_fCost(price), ZSTD_fCost(opt[pos].price));
  1003. while (last_pos < pos) { opt[last_pos+1].price = ZSTD_MAX_PRICE; last_pos++; } /* fill empty positions */
  1004. opt[pos].mlen = mlen;
  1005. opt[pos].off = offset;
  1006. opt[pos].litlen = litlen;
  1007. opt[pos].price = price;
  1008. } else {
  1009. DEBUGLOG(7, "rPos:%u (ml=%2u) => new price is worse (%.2f>=%.2f)",
  1010. pos, mlen, ZSTD_fCost(price), ZSTD_fCost(opt[pos].price));
  1011. if (optLevel==0) break; /* early update abort; gets ~+10% speed for about -0.01 ratio loss */
  1012. }
  1013. } } }
  1014. } /* for (cur = 1; cur <= last_pos; cur++) */
  1015. lastSequence = opt[last_pos];
  1016. cur = last_pos > ZSTD_totalLen(lastSequence) ? last_pos - ZSTD_totalLen(lastSequence) : 0; /* single sequence, and it starts before `ip` */
  1017. assert(cur < ZSTD_OPT_NUM); /* control overflow*/
  1018. _shortestPath: /* cur, last_pos, best_mlen, best_off have to be set */
  1019. assert(opt[0].mlen == 0);
  1020. /* Set the next chunk's repcodes based on the repcodes of the beginning
  1021. * of the last match, and the last sequence. This avoids us having to
  1022. * update them while traversing the sequences.
  1023. */
  1024. if (lastSequence.mlen != 0) {
  1025. repcodes_t reps = ZSTD_updateRep(opt[cur].rep, lastSequence.off, lastSequence.litlen==0);
  1026. ZSTD_memcpy(rep, &reps, sizeof(reps));
  1027. } else {
  1028. ZSTD_memcpy(rep, opt[cur].rep, sizeof(repcodes_t));
  1029. }
  1030. { U32 const storeEnd = cur + 1;
  1031. U32 storeStart = storeEnd;
  1032. U32 seqPos = cur;
  1033. DEBUGLOG(6, "start reverse traversal (last_pos:%u, cur:%u)",
  1034. last_pos, cur); (void)last_pos;
  1035. assert(storeEnd < ZSTD_OPT_NUM);
  1036. DEBUGLOG(6, "last sequence copied into pos=%u (llen=%u,mlen=%u,ofc=%u)",
  1037. storeEnd, lastSequence.litlen, lastSequence.mlen, lastSequence.off);
  1038. opt[storeEnd] = lastSequence;
  1039. while (seqPos > 0) {
  1040. U32 const backDist = ZSTD_totalLen(opt[seqPos]);
  1041. storeStart--;
  1042. DEBUGLOG(6, "sequence from rPos=%u copied into pos=%u (llen=%u,mlen=%u,ofc=%u)",
  1043. seqPos, storeStart, opt[seqPos].litlen, opt[seqPos].mlen, opt[seqPos].off);
  1044. opt[storeStart] = opt[seqPos];
  1045. seqPos = (seqPos > backDist) ? seqPos - backDist : 0;
  1046. }
  1047. /* save sequences */
  1048. DEBUGLOG(6, "sending selected sequences into seqStore")
  1049. { U32 storePos;
  1050. for (storePos=storeStart; storePos <= storeEnd; storePos++) {
  1051. U32 const llen = opt[storePos].litlen;
  1052. U32 const mlen = opt[storePos].mlen;
  1053. U32 const offCode = opt[storePos].off;
  1054. U32 const advance = llen + mlen;
  1055. DEBUGLOG(6, "considering seq starting at %zi, llen=%u, mlen=%u",
  1056. anchor - istart, (unsigned)llen, (unsigned)mlen);
  1057. if (mlen==0) { /* only literals => must be last "sequence", actually starting a new stream of sequences */
  1058. assert(storePos == storeEnd); /* must be last sequence */
  1059. ip = anchor + llen; /* last "sequence" is a bunch of literals => don't progress anchor */
  1060. continue; /* will finish */
  1061. }
  1062. assert(anchor + llen <= iend);
  1063. ZSTD_updateStats(optStatePtr, llen, anchor, offCode, mlen);
  1064. ZSTD_storeSeq(seqStore, llen, anchor, iend, offCode, mlen-MINMATCH);
  1065. anchor += advance;
  1066. ip = anchor;
  1067. } }
  1068. ZSTD_setBasePrices(optStatePtr, optLevel);
  1069. }
  1070. } /* while (ip < ilimit) */
  1071. /* Return the last literals size */
  1072. return (size_t)(iend - anchor);
  1073. }
  1074. size_t ZSTD_compressBlock_btopt(
  1075. ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
  1076. const void* src, size_t srcSize)
  1077. {
  1078. DEBUGLOG(5, "ZSTD_compressBlock_btopt");
  1079. return ZSTD_compressBlock_opt_generic(ms, seqStore, rep, src, srcSize, 0 /*optLevel*/, ZSTD_noDict);
  1080. }
  1081. /* used in 2-pass strategy */
  1082. static U32 ZSTD_upscaleStat(unsigned* table, U32 lastEltIndex, int bonus)
  1083. {
  1084. U32 s, sum=0;
  1085. assert(ZSTD_FREQ_DIV+bonus >= 0);
  1086. for (s=0; s<lastEltIndex+1; s++) {
  1087. table[s] <<= ZSTD_FREQ_DIV+bonus;
  1088. table[s]--;
  1089. sum += table[s];
  1090. }
  1091. return sum;
  1092. }
  1093. /* used in 2-pass strategy */
  1094. MEM_STATIC void ZSTD_upscaleStats(optState_t* optPtr)
  1095. {
  1096. if (ZSTD_compressedLiterals(optPtr))
  1097. optPtr->litSum = ZSTD_upscaleStat(optPtr->litFreq, MaxLit, 0);
  1098. optPtr->litLengthSum = ZSTD_upscaleStat(optPtr->litLengthFreq, MaxLL, 0);
  1099. optPtr->matchLengthSum = ZSTD_upscaleStat(optPtr->matchLengthFreq, MaxML, 0);
  1100. optPtr->offCodeSum = ZSTD_upscaleStat(optPtr->offCodeFreq, MaxOff, 0);
  1101. }
  1102. /* ZSTD_initStats_ultra():
  1103. * make a first compression pass, just to seed stats with more accurate starting values.
  1104. * only works on first block, with no dictionary and no ldm.
  1105. * this function cannot error, hence its contract must be respected.
  1106. */
  1107. static void
  1108. ZSTD_initStats_ultra(ZSTD_matchState_t* ms,
  1109. seqStore_t* seqStore,
  1110. U32 rep[ZSTD_REP_NUM],
  1111. const void* src, size_t srcSize)
  1112. {
  1113. U32 tmpRep[ZSTD_REP_NUM]; /* updated rep codes will sink here */
  1114. ZSTD_memcpy(tmpRep, rep, sizeof(tmpRep));
  1115. DEBUGLOG(4, "ZSTD_initStats_ultra (srcSize=%zu)", srcSize);
  1116. assert(ms->opt.litLengthSum == 0); /* first block */
  1117. assert(seqStore->sequences == seqStore->sequencesStart); /* no ldm */
  1118. assert(ms->window.dictLimit == ms->window.lowLimit); /* no dictionary */
  1119. assert(ms->window.dictLimit - ms->nextToUpdate <= 1); /* no prefix (note: intentional overflow, defined as 2-complement) */
  1120. ZSTD_compressBlock_opt_generic(ms, seqStore, tmpRep, src, srcSize, 2 /*optLevel*/, ZSTD_noDict); /* generate stats into ms->opt*/
  1121. /* invalidate first scan from history */
  1122. ZSTD_resetSeqStore(seqStore);
  1123. ms->window.base -= srcSize;
  1124. ms->window.dictLimit += (U32)srcSize;
  1125. ms->window.lowLimit = ms->window.dictLimit;
  1126. ms->nextToUpdate = ms->window.dictLimit;
  1127. /* re-inforce weight of collected statistics */
  1128. ZSTD_upscaleStats(&ms->opt);
  1129. }
  1130. size_t ZSTD_compressBlock_btultra(
  1131. ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
  1132. const void* src, size_t srcSize)
  1133. {
  1134. DEBUGLOG(5, "ZSTD_compressBlock_btultra (srcSize=%zu)", srcSize);
  1135. return ZSTD_compressBlock_opt_generic(ms, seqStore, rep, src, srcSize, 2 /*optLevel*/, ZSTD_noDict);
  1136. }
  1137. size_t ZSTD_compressBlock_btultra2(
  1138. ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
  1139. const void* src, size_t srcSize)
  1140. {
  1141. U32 const curr = (U32)((const BYTE*)src - ms->window.base);
  1142. DEBUGLOG(5, "ZSTD_compressBlock_btultra2 (srcSize=%zu)", srcSize);
  1143. /* 2-pass strategy:
  1144. * this strategy makes a first pass over first block to collect statistics
  1145. * and seed next round's statistics with it.
  1146. * After 1st pass, function forgets everything, and starts a new block.
  1147. * Consequently, this can only work if no data has been previously loaded in tables,
  1148. * aka, no dictionary, no prefix, no ldm preprocessing.
  1149. * The compression ratio gain is generally small (~0.5% on first block),
  1150. * the cost is 2x cpu time on first block. */
  1151. assert(srcSize <= ZSTD_BLOCKSIZE_MAX);
  1152. if ( (ms->opt.litLengthSum==0) /* first block */
  1153. && (seqStore->sequences == seqStore->sequencesStart) /* no ldm */
  1154. && (ms->window.dictLimit == ms->window.lowLimit) /* no dictionary */
  1155. && (curr == ms->window.dictLimit) /* start of frame, nothing already loaded nor skipped */
  1156. && (srcSize > ZSTD_PREDEF_THRESHOLD)
  1157. ) {
  1158. ZSTD_initStats_ultra(ms, seqStore, rep, src, srcSize);
  1159. }
  1160. return ZSTD_compressBlock_opt_generic(ms, seqStore, rep, src, srcSize, 2 /*optLevel*/, ZSTD_noDict);
  1161. }
  1162. size_t ZSTD_compressBlock_btopt_dictMatchState(
  1163. ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
  1164. const void* src, size_t srcSize)
  1165. {
  1166. return ZSTD_compressBlock_opt_generic(ms, seqStore, rep, src, srcSize, 0 /*optLevel*/, ZSTD_dictMatchState);
  1167. }
  1168. size_t ZSTD_compressBlock_btultra_dictMatchState(
  1169. ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
  1170. const void* src, size_t srcSize)
  1171. {
  1172. return ZSTD_compressBlock_opt_generic(ms, seqStore, rep, src, srcSize, 2 /*optLevel*/, ZSTD_dictMatchState);
  1173. }
  1174. size_t ZSTD_compressBlock_btopt_extDict(
  1175. ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
  1176. const void* src, size_t srcSize)
  1177. {
  1178. return ZSTD_compressBlock_opt_generic(ms, seqStore, rep, src, srcSize, 0 /*optLevel*/, ZSTD_extDict);
  1179. }
  1180. size_t ZSTD_compressBlock_btultra_extDict(
  1181. ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
  1182. const void* src, size_t srcSize)
  1183. {
  1184. return ZSTD_compressBlock_opt_generic(ms, seqStore, rep, src, srcSize, 2 /*optLevel*/, ZSTD_extDict);
  1185. }
  1186. /* note : no btultra2 variant for extDict nor dictMatchState,
  1187. * because btultra2 is not meant to work with dictionaries
  1188. * and is only specific for the first block (no prefix) */