zstd_opt.c 62 KB

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