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