Coverage Report

Created: 2026-04-01 06:50

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