Coverage Report

Created: 2025-11-11 07:02

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/zstd/lib/compress/zstd_opt.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 "hist.h"
13
#include "zstd_opt.h"
14
15
#if !defined(ZSTD_EXCLUDE_BTLAZY2_BLOCK_COMPRESSOR) \
16
 || !defined(ZSTD_EXCLUDE_BTOPT_BLOCK_COMPRESSOR) \
17
 || !defined(ZSTD_EXCLUDE_BTULTRA_BLOCK_COMPRESSOR)
18
19
353M
#define ZSTD_LITFREQ_ADD    2   /* scaling factor for litFreq, so that frequencies adapt faster to new stats */
20
728M
#define ZSTD_MAX_PRICE     (1<<30)
21
22
103k
#define ZSTD_PREDEF_THRESHOLD 8   /* if srcSize < ZSTD_PREDEF_THRESHOLD, symbols' cost is assumed static, directly determined by pre-defined distributions */
23
24
25
/*-*************************************
26
*  Price functions for optimal parser
27
***************************************/
28
29
#if 0    /* approximation at bit level (for tests) */
30
#  define BITCOST_ACCURACY 0
31
#  define BITCOST_MULTIPLIER (1 << BITCOST_ACCURACY)
32
#  define WEIGHT(stat, opt) ((void)(opt), ZSTD_bitWeight(stat))
33
#elif 0  /* fractional bit accuracy (for tests) */
34
#  define BITCOST_ACCURACY 8
35
#  define BITCOST_MULTIPLIER (1 << BITCOST_ACCURACY)
36
#  define WEIGHT(stat,opt) ((void)(opt), ZSTD_fracWeight(stat))
37
#else    /* opt==approx, ultra==accurate */
38
40.4G
#  define BITCOST_ACCURACY 8
39
29.2G
#  define BITCOST_MULTIPLIER (1 << BITCOST_ACCURACY)
40
12.1G
#  define WEIGHT(stat,opt) ((opt) ? ZSTD_fracWeight(stat) : ZSTD_bitWeight(stat))
41
#endif
42
43
/* ZSTD_bitWeight() :
44
 * provide estimated "cost" of a stat in full bits only */
45
MEM_STATIC U32 ZSTD_bitWeight(U32 stat)
46
908M
{
47
908M
    return (ZSTD_highbit32(stat+1) * BITCOST_MULTIPLIER);
48
908M
}
49
50
/* ZSTD_fracWeight() :
51
 * provide fractional-bit "cost" of a stat,
52
 * using linear interpolation approximation */
53
MEM_STATIC U32 ZSTD_fracWeight(U32 rawStat)
54
11.2G
{
55
11.2G
    U32 const stat = rawStat + 1;
56
11.2G
    U32 const hb = ZSTD_highbit32(stat);
57
11.2G
    U32 const BWeight = hb * BITCOST_MULTIPLIER;
58
    /* Fweight was meant for "Fractional weight"
59
     * but it's effectively a value between 1 and 2
60
     * using fixed point arithmetic */
61
11.2G
    U32 const FWeight = (stat << BITCOST_ACCURACY) >> hb;
62
11.2G
    U32 const weight = BWeight + FWeight;
63
11.2G
    assert(hb + BITCOST_ACCURACY < 31);
64
11.2G
    return weight;
65
11.2G
}
66
67
#if (DEBUGLEVEL>=2)
68
/* debugging function,
69
 * @return price in bytes as fractional value
70
 * for debug messages only */
71
MEM_STATIC double ZSTD_fCost(int price)
72
{
73
    return (double)price / (BITCOST_MULTIPLIER*8);
74
}
75
#endif
76
77
static int ZSTD_compressedLiterals(optState_t const* const optPtr)
78
666M
{
79
666M
    return optPtr->literalCompressionMode != ZSTD_ps_disable;
80
666M
}
81
82
static void ZSTD_setBasePrices(optState_t* optPtr, int optLevel)
83
28.5M
{
84
28.5M
    if (ZSTD_compressedLiterals(optPtr))
85
24.1M
        optPtr->litSumBasePrice = WEIGHT(optPtr->litSum, optLevel);
86
28.5M
    optPtr->litLengthSumBasePrice = WEIGHT(optPtr->litLengthSum, optLevel);
87
28.5M
    optPtr->matchLengthSumBasePrice = WEIGHT(optPtr->matchLengthSum, optLevel);
88
28.5M
    optPtr->offCodeSumBasePrice = WEIGHT(optPtr->offCodeSum, optLevel);
89
28.5M
}
90
91
92
static U32 sum_u32(const unsigned table[], size_t nbElts)
93
2.05M
{
94
2.05M
    size_t n;
95
2.05M
    U32 total = 0;
96
172M
    for (n=0; n<nbElts; n++) {
97
170M
        total += table[n];
98
170M
    }
99
2.05M
    return total;
100
2.05M
}
101
102
typedef enum { base_0possible=0, base_1guaranteed=1 } base_directive_e;
103
104
static U32
105
ZSTD_downscaleStats(unsigned* table, U32 lastEltIndex, U32 shift, base_directive_e base1)
106
144k
{
107
144k
    U32 s, sum=0;
108
144k
    DEBUGLOG(5, "ZSTD_downscaleStats (nbElts=%u, shift=%u)",
109
144k
            (unsigned)lastEltIndex+1, (unsigned)shift );
110
144k
    assert(shift < 30);
111
28.2M
    for (s=0; s<lastEltIndex+1; s++) {
112
28.0M
        unsigned const base = base1 ? 1 : (table[s]>0);
113
28.0M
        unsigned const newStat = base + (table[s] >> shift);
114
28.0M
        sum += newStat;
115
28.0M
        table[s] = newStat;
116
28.0M
    }
117
144k
    return sum;
118
144k
}
119
120
/* ZSTD_scaleStats() :
121
 * reduce all elt frequencies in table if sum too large
122
 * return the resulting sum of elements */
123
static U32 ZSTD_scaleStats(unsigned* table, U32 lastEltIndex, U32 logTarget)
124
1.92M
{
125
1.92M
    U32 const prevsum = sum_u32(table, lastEltIndex+1);
126
1.92M
    U32 const factor = prevsum >> logTarget;
127
1.92M
    DEBUGLOG(5, "ZSTD_scaleStats (nbElts=%u, target=%u)", (unsigned)lastEltIndex+1, (unsigned)logTarget);
128
1.92M
    assert(logTarget < 30);
129
1.92M
    if (factor <= 1) return prevsum;
130
86.6k
    return ZSTD_downscaleStats(table, lastEltIndex, ZSTD_highbit32(factor), base_1guaranteed);
131
1.92M
}
132
133
/* ZSTD_rescaleFreqs() :
134
 * if first block (detected by optPtr->litLengthSum == 0) : init statistics
135
 *    take hints from dictionary if there is one
136
 *    and init from zero if there is none,
137
 *    using src for literals stats, and baseline stats for sequence symbols
138
 * otherwise downscale existing stats, to be used as seed for next block.
139
 */
140
static void
141
ZSTD_rescaleFreqs(optState_t* const optPtr,
142
            const BYTE* const src, size_t const srcSize,
143
                  int const optLevel)
144
586k
{
145
586k
    int const compressedLiterals = ZSTD_compressedLiterals(optPtr);
146
586k
    DEBUGLOG(5, "ZSTD_rescaleFreqs (srcSize=%u)", (unsigned)srcSize);
147
586k
    optPtr->priceType = zop_dynamic;
148
149
586k
    if (optPtr->litLengthSum == 0) {  /* no literals stats collected -> first block assumed -> init */
150
151
        /* heuristic: use pre-defined stats for too small inputs */
152
82.0k
        if (srcSize <= ZSTD_PREDEF_THRESHOLD) {
153
1.46k
            DEBUGLOG(5, "srcSize <= %i : use predefined stats", ZSTD_PREDEF_THRESHOLD);
154
1.46k
            optPtr->priceType = zop_predef;
155
1.46k
        }
156
157
82.0k
        assert(optPtr->symbolCosts != NULL);
158
82.0k
        if (optPtr->symbolCosts->huf.repeatMode == HUF_repeat_valid) {
159
160
            /* huffman stats covering the full value set : table presumed generated by dictionary */
161
17.8k
            optPtr->priceType = zop_dynamic;
162
163
17.8k
            if (compressedLiterals) {
164
                /* generate literals statistics from huffman table */
165
16.2k
                unsigned lit;
166
16.2k
                assert(optPtr->litFreq != NULL);
167
16.2k
                optPtr->litSum = 0;
168
4.18M
                for (lit=0; lit<=MaxLit; lit++) {
169
4.17M
                    U32 const scaleLog = 11;   /* scale to 2K */
170
4.17M
                    U32 const bitCost = HUF_getNbBitsFromCTable(optPtr->symbolCosts->huf.CTable, lit);
171
4.17M
                    assert(bitCost <= scaleLog);
172
4.17M
                    optPtr->litFreq[lit] = bitCost ? 1 << (scaleLog-bitCost) : 1 /*minimum to calculate cost*/;
173
4.17M
                    optPtr->litSum += optPtr->litFreq[lit];
174
4.17M
            }   }
175
176
17.8k
            {   unsigned ll;
177
17.8k
                FSE_CState_t llstate;
178
17.8k
                FSE_initCState(&llstate, optPtr->symbolCosts->fse.litlengthCTable);
179
17.8k
                optPtr->litLengthSum = 0;
180
660k
                for (ll=0; ll<=MaxLL; ll++) {
181
642k
                    U32 const scaleLog = 10;   /* scale to 1K */
182
642k
                    U32 const bitCost = FSE_getMaxNbBits(llstate.symbolTT, ll);
183
642k
                    assert(bitCost < scaleLog);
184
642k
                    optPtr->litLengthFreq[ll] = bitCost ? 1 << (scaleLog-bitCost) : 1 /*minimum to calculate cost*/;
185
642k
                    optPtr->litLengthSum += optPtr->litLengthFreq[ll];
186
642k
            }   }
187
188
17.8k
            {   unsigned ml;
189
17.8k
                FSE_CState_t mlstate;
190
17.8k
                FSE_initCState(&mlstate, optPtr->symbolCosts->fse.matchlengthCTable);
191
17.8k
                optPtr->matchLengthSum = 0;
192
963k
                for (ml=0; ml<=MaxML; ml++) {
193
946k
                    U32 const scaleLog = 10;
194
946k
                    U32 const bitCost = FSE_getMaxNbBits(mlstate.symbolTT, ml);
195
946k
                    assert(bitCost < scaleLog);
196
946k
                    optPtr->matchLengthFreq[ml] = bitCost ? 1 << (scaleLog-bitCost) : 1 /*minimum to calculate cost*/;
197
946k
                    optPtr->matchLengthSum += optPtr->matchLengthFreq[ml];
198
946k
            }   }
199
200
17.8k
            {   unsigned of;
201
17.8k
                FSE_CState_t ofstate;
202
17.8k
                FSE_initCState(&ofstate, optPtr->symbolCosts->fse.offcodeCTable);
203
17.8k
                optPtr->offCodeSum = 0;
204
589k
                for (of=0; of<=MaxOff; of++) {
205
571k
                    U32 const scaleLog = 10;
206
571k
                    U32 const bitCost = FSE_getMaxNbBits(ofstate.symbolTT, of);
207
571k
                    assert(bitCost < scaleLog);
208
571k
                    optPtr->offCodeFreq[of] = bitCost ? 1 << (scaleLog-bitCost) : 1 /*minimum to calculate cost*/;
209
571k
                    optPtr->offCodeSum += optPtr->offCodeFreq[of];
210
571k
            }   }
211
212
64.1k
        } else {  /* first block, no dictionary */
213
214
64.1k
            assert(optPtr->litFreq != NULL);
215
64.1k
            if (compressedLiterals) {
216
                /* base initial cost of literals on direct frequency within src */
217
57.5k
                unsigned lit = MaxLit;
218
57.5k
                HIST_count_simple(optPtr->litFreq, &lit, src, srcSize);   /* use raw first block to init statistics */
219
57.5k
                optPtr->litSum = ZSTD_downscaleStats(optPtr->litFreq, MaxLit, 8, base_0possible);
220
57.5k
            }
221
222
64.1k
            {   unsigned const baseLLfreqs[MaxLL+1] = {
223
64.1k
                    4, 2, 1, 1, 1, 1, 1, 1,
224
64.1k
                    1, 1, 1, 1, 1, 1, 1, 1,
225
64.1k
                    1, 1, 1, 1, 1, 1, 1, 1,
226
64.1k
                    1, 1, 1, 1, 1, 1, 1, 1,
227
64.1k
                    1, 1, 1, 1
228
64.1k
                };
229
64.1k
                ZSTD_memcpy(optPtr->litLengthFreq, baseLLfreqs, sizeof(baseLLfreqs));
230
64.1k
                optPtr->litLengthSum = sum_u32(baseLLfreqs, MaxLL+1);
231
64.1k
            }
232
233
64.1k
            {   unsigned ml;
234
3.46M
                for (ml=0; ml<=MaxML; ml++)
235
3.40M
                    optPtr->matchLengthFreq[ml] = 1;
236
64.1k
            }
237
64.1k
            optPtr->matchLengthSum = MaxML+1;
238
239
64.1k
            {   unsigned const baseOFCfreqs[MaxOff+1] = {
240
64.1k
                    6, 2, 1, 1, 2, 3, 4, 4,
241
64.1k
                    4, 3, 2, 1, 1, 1, 1, 1,
242
64.1k
                    1, 1, 1, 1, 1, 1, 1, 1,
243
64.1k
                    1, 1, 1, 1, 1, 1, 1, 1
244
64.1k
                };
245
64.1k
                ZSTD_memcpy(optPtr->offCodeFreq, baseOFCfreqs, sizeof(baseOFCfreqs));
246
64.1k
                optPtr->offCodeSum = sum_u32(baseOFCfreqs, MaxOff+1);
247
64.1k
            }
248
249
64.1k
        }
250
251
504k
    } else {   /* new block : scale down accumulated statistics */
252
253
504k
        if (compressedLiterals)
254
412k
            optPtr->litSum = ZSTD_scaleStats(optPtr->litFreq, MaxLit, 12);
255
504k
        optPtr->litLengthSum = ZSTD_scaleStats(optPtr->litLengthFreq, MaxLL, 11);
256
504k
        optPtr->matchLengthSum = ZSTD_scaleStats(optPtr->matchLengthFreq, MaxML, 11);
257
504k
        optPtr->offCodeSum = ZSTD_scaleStats(optPtr->offCodeFreq, MaxOff, 11);
258
504k
    }
259
260
586k
    ZSTD_setBasePrices(optPtr, optLevel);
261
586k
}
262
263
/* ZSTD_rawLiteralsCost() :
264
 * price of literals (only) in specified segment (which length can be 0).
265
 * does not include price of literalLength symbol */
266
static U32 ZSTD_rawLiteralsCost(const BYTE* const literals, U32 const litLength,
267
                                const optState_t* const optPtr,
268
                                int optLevel)
269
572M
{
270
572M
    DEBUGLOG(8, "ZSTD_rawLiteralsCost (%u literals)", litLength);
271
572M
    if (litLength == 0) return 0;
272
273
572M
    if (!ZSTD_compressedLiterals(optPtr))
274
70.4M
        return (litLength << 3) * BITCOST_MULTIPLIER;  /* Uncompressed - 8 bytes per literal. */
275
276
502M
    if (optPtr->priceType == zop_predef)
277
0
        return (litLength*6) * BITCOST_MULTIPLIER;  /* 6 bit per literal - no statistic used */
278
279
    /* dynamic statistics */
280
502M
    {   U32 price = optPtr->litSumBasePrice * litLength;
281
502M
        U32 const litPriceMax = optPtr->litSumBasePrice - BITCOST_MULTIPLIER;
282
502M
        U32 u;
283
502M
        assert(optPtr->litSumBasePrice >= BITCOST_MULTIPLIER);
284
1.00G
        for (u=0; u < litLength; u++) {
285
502M
            U32 litPrice = WEIGHT(optPtr->litFreq[literals[u]], optLevel);
286
502M
            if (UNLIKELY(litPrice > litPriceMax)) litPrice = litPriceMax;
287
502M
            price -= litPrice;
288
502M
        }
289
502M
        return price;
290
502M
    }
291
502M
}
292
293
/* ZSTD_litLengthPrice() :
294
 * cost of literalLength symbol */
295
static U32 ZSTD_litLengthPrice(U32 const litLength, const optState_t* const optPtr, int optLevel)
296
1.86G
{
297
1.86G
    assert(litLength <= ZSTD_BLOCKSIZE_MAX);
298
1.86G
    if (optPtr->priceType == zop_predef)
299
0
        return WEIGHT(litLength, optLevel);
300
301
    /* ZSTD_LLcode() can't compute litLength price for sizes >= ZSTD_BLOCKSIZE_MAX
302
     * because it isn't representable in the zstd format.
303
     * So instead just pretend it would cost 1 bit more than ZSTD_BLOCKSIZE_MAX - 1.
304
     * In such a case, the block would be all literals.
305
     */
306
1.86G
    if (litLength == ZSTD_BLOCKSIZE_MAX)
307
0
        return BITCOST_MULTIPLIER + ZSTD_litLengthPrice(ZSTD_BLOCKSIZE_MAX - 1, optPtr, optLevel);
308
309
    /* dynamic statistics */
310
1.86G
    {   U32 const llCode = ZSTD_LLcode(litLength);
311
1.86G
        return (LL_bits[llCode] * BITCOST_MULTIPLIER)
312
1.86G
             + optPtr->litLengthSumBasePrice
313
1.86G
             - WEIGHT(optPtr->litLengthFreq[llCode], optLevel);
314
1.86G
    }
315
1.86G
}
316
317
/* ZSTD_getMatchPrice() :
318
 * Provides the cost of the match part (offset + matchLength) of a sequence.
319
 * Must be combined with ZSTD_fullLiteralsCost() to get the full cost of a sequence.
320
 * @offBase : sumtype, representing an offset or a repcode, and using numeric representation of ZSTD_storeSeq()
321
 * @optLevel: when <2, favors small offset for decompression speed (improved cache efficiency)
322
 */
323
FORCE_INLINE_TEMPLATE U32
324
ZSTD_getMatchPrice(U32 const offBase,
325
                   U32 const matchLength,
326
             const optState_t* const optPtr,
327
                   int const optLevel)
328
4.84G
{
329
4.84G
    U32 price;
330
4.84G
    U32 const offCode = ZSTD_highbit32(offBase);
331
4.84G
    U32 const mlBase = matchLength - MINMATCH;
332
4.84G
    assert(matchLength >= MINMATCH);
333
334
4.84G
    if (optPtr->priceType == zop_predef)  /* fixed scheme, does not use statistics */
335
0
        return WEIGHT(mlBase, optLevel)
336
0
             + ((16 + offCode) * BITCOST_MULTIPLIER); /* emulated offset cost */
337
338
    /* dynamic statistics */
339
4.84G
    price = (offCode * BITCOST_MULTIPLIER) + (optPtr->offCodeSumBasePrice - WEIGHT(optPtr->offCodeFreq[offCode], optLevel));
340
4.84G
    if ((optLevel<2) /*static*/ && offCode >= 20)
341
16
        price += (offCode-19)*2 * BITCOST_MULTIPLIER; /* handicap for long distance offsets, favor decompression speed */
342
343
    /* match Length */
344
4.84G
    {   U32 const mlCode = ZSTD_MLcode(mlBase);
345
4.84G
        price += (ML_bits[mlCode] * BITCOST_MULTIPLIER) + (optPtr->matchLengthSumBasePrice - WEIGHT(optPtr->matchLengthFreq[mlCode], optLevel));
346
4.84G
    }
347
348
4.84G
    price += BITCOST_MULTIPLIER / 5;   /* heuristic : make matches a bit more costly to favor less sequences -> faster decompression speed */
349
350
4.84G
    DEBUGLOG(8, "ZSTD_getMatchPrice(ml:%u) = %u", matchLength, price);
351
4.84G
    return price;
352
4.84G
}
353
354
/* ZSTD_updateStats() :
355
 * assumption : literals + litLength <= iend */
356
static void ZSTD_updateStats(optState_t* const optPtr,
357
                             U32 litLength, const BYTE* literals,
358
                             U32 offBase, U32 matchLength)
359
64.7M
{
360
    /* literals */
361
64.7M
    if (ZSTD_compressedLiterals(optPtr)) {
362
56.0M
        U32 u;
363
353M
        for (u=0; u < litLength; u++)
364
297M
            optPtr->litFreq[literals[u]] += ZSTD_LITFREQ_ADD;
365
56.0M
        optPtr->litSum += litLength*ZSTD_LITFREQ_ADD;
366
56.0M
    }
367
368
    /* literal Length */
369
64.7M
    {   U32 const llCode = ZSTD_LLcode(litLength);
370
64.7M
        optPtr->litLengthFreq[llCode]++;
371
64.7M
        optPtr->litLengthSum++;
372
64.7M
    }
373
374
    /* offset code : follows storeSeq() numeric representation */
375
64.7M
    {   U32 const offCode = ZSTD_highbit32(offBase);
376
64.7M
        assert(offCode <= MaxOff);
377
64.7M
        optPtr->offCodeFreq[offCode]++;
378
64.7M
        optPtr->offCodeSum++;
379
64.7M
    }
380
381
    /* match Length */
382
64.7M
    {   U32 const mlBase = matchLength - MINMATCH;
383
64.7M
        U32 const mlCode = ZSTD_MLcode(mlBase);
384
64.7M
        optPtr->matchLengthFreq[mlCode]++;
385
64.7M
        optPtr->matchLengthSum++;
386
64.7M
    }
387
64.7M
}
388
389
390
/* ZSTD_readMINMATCH() :
391
 * function safe only for comparisons
392
 * assumption : memPtr must be at least 4 bytes before end of buffer */
393
MEM_STATIC U32 ZSTD_readMINMATCH(const void* memPtr, U32 length)
394
4.67G
{
395
4.67G
    switch (length)
396
4.67G
    {
397
0
    default :
398
2.26G
    case 4 : return MEM_read32(memPtr);
399
2.41G
    case 3 : if (MEM_isLittleEndian())
400
2.41G
                return MEM_read32(memPtr)<<8;
401
18.4E
             else
402
18.4E
                return MEM_read32(memPtr)>>8;
403
4.67G
    }
404
4.67G
}
405
406
407
/* Update hashTable3 up to ip (excluded)
408
   Assumption : always within prefix (i.e. not within extDict) */
409
static
410
ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
411
U32 ZSTD_insertAndFindFirstIndexHash3 (const ZSTD_MatchState_t* ms,
412
                                       U32* nextToUpdate3,
413
                                       const BYTE* const ip)
414
313M
{
415
313M
    U32* const hashTable3 = ms->hashTable3;
416
313M
    U32 const hashLog3 = ms->hashLog3;
417
313M
    const BYTE* const base = ms->window.base;
418
313M
    U32 idx = *nextToUpdate3;
419
313M
    U32 const target = (U32)(ip - base);
420
313M
    size_t const hash3 = ZSTD_hash3Ptr(ip, hashLog3);
421
313M
    assert(hashLog3 > 0);
422
423
1.01G
    while(idx < target) {
424
702M
        hashTable3[ZSTD_hash3Ptr(base+idx, hashLog3)] = idx;
425
702M
        idx++;
426
702M
    }
427
428
313M
    *nextToUpdate3 = target;
429
313M
    return hashTable3[hash3];
430
313M
}
431
432
433
/*-*************************************
434
*  Binary Tree search
435
***************************************/
436
/** ZSTD_insertBt1() : add one or multiple positions to tree.
437
 * @param ip assumed <= iend-8 .
438
 * @param target The target of ZSTD_updateTree_internal() - we are filling to this position
439
 * @return : nb of positions added */
440
static
441
ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
442
U32 ZSTD_insertBt1(
443
                const ZSTD_MatchState_t* ms,
444
                const BYTE* const ip, const BYTE* const iend,
445
                U32 const target,
446
                U32 const mls, const int extDict)
447
215M
{
448
215M
    const ZSTD_compressionParameters* const cParams = &ms->cParams;
449
215M
    U32*   const hashTable = ms->hashTable;
450
215M
    U32    const hashLog = cParams->hashLog;
451
215M
    size_t const h  = ZSTD_hashPtr(ip, hashLog, mls);
452
215M
    U32*   const bt = ms->chainTable;
453
215M
    U32    const btLog  = cParams->chainLog - 1;
454
215M
    U32    const btMask = (1 << btLog) - 1;
455
215M
    U32 matchIndex = hashTable[h];
456
215M
    size_t commonLengthSmaller=0, commonLengthLarger=0;
457
215M
    const BYTE* const base = ms->window.base;
458
215M
    const BYTE* const dictBase = ms->window.dictBase;
459
215M
    const U32 dictLimit = ms->window.dictLimit;
460
215M
    const BYTE* const dictEnd = dictBase + dictLimit;
461
215M
    const BYTE* const prefixStart = base + dictLimit;
462
215M
    const BYTE* match;
463
215M
    const U32 curr = (U32)(ip-base);
464
215M
    const U32 btLow = btMask >= curr ? 0 : curr - btMask;
465
215M
    U32* smallerPtr = bt + 2*(curr&btMask);
466
215M
    U32* largerPtr  = smallerPtr + 1;
467
215M
    U32 dummy32;   /* to be nullified at the end */
468
    /* windowLow is based on target because
469
     * we only need positions that will be in the window at the end of the tree update.
470
     */
471
215M
    U32 const windowLow = ZSTD_getLowestMatchIndex(ms, target, cParams->windowLog);
472
215M
    U32 matchEndIdx = curr+8+1;
473
215M
    size_t bestLength = 8;
474
215M
    U32 nbCompares = 1U << cParams->searchLog;
475
#ifdef ZSTD_C_PREDICT
476
    U32 predictedSmall = *(bt + 2*((curr-1)&btMask) + 0);
477
    U32 predictedLarge = *(bt + 2*((curr-1)&btMask) + 1);
478
    predictedSmall += (predictedSmall>0);
479
    predictedLarge += (predictedLarge>0);
480
#endif /* ZSTD_C_PREDICT */
481
482
215M
    DEBUGLOG(8, "ZSTD_insertBt1 (%u)", curr);
483
484
215M
    assert(curr <= target);
485
215M
    assert(ip <= iend-8);   /* required for h calculation */
486
215M
    hashTable[h] = curr;   /* Update Hash Table */
487
488
215M
    assert(windowLow > 0);
489
1.21G
    for (; nbCompares && (matchIndex >= windowLow); --nbCompares) {
490
1.05G
        U32* const nextPtr = bt + 2*(matchIndex & btMask);
491
1.05G
        size_t matchLength = MIN(commonLengthSmaller, commonLengthLarger);   /* guaranteed minimum nb of common bytes */
492
1.05G
        assert(matchIndex < curr);
493
494
#ifdef ZSTD_C_PREDICT   /* note : can create issues when hlog small <= 11 */
495
        const U32* predictPtr = bt + 2*((matchIndex-1) & btMask);   /* written this way, as bt is a roll buffer */
496
        if (matchIndex == predictedSmall) {
497
            /* no need to check length, result known */
498
            *smallerPtr = matchIndex;
499
            if (matchIndex <= btLow) { smallerPtr=&dummy32; break; }   /* beyond tree size, stop the search */
500
            smallerPtr = nextPtr+1;               /* new "smaller" => larger of match */
501
            matchIndex = nextPtr[1];              /* new matchIndex larger than previous (closer to current) */
502
            predictedSmall = predictPtr[1] + (predictPtr[1]>0);
503
            continue;
504
        }
505
        if (matchIndex == predictedLarge) {
506
            *largerPtr = matchIndex;
507
            if (matchIndex <= btLow) { largerPtr=&dummy32; break; }   /* beyond tree size, stop the search */
508
            largerPtr = nextPtr;
509
            matchIndex = nextPtr[0];
510
            predictedLarge = predictPtr[0] + (predictPtr[0]>0);
511
            continue;
512
        }
513
#endif
514
515
1.05G
        if (!extDict || (matchIndex+matchLength >= dictLimit)) {
516
1.01G
            assert(matchIndex+matchLength >= dictLimit);   /* might be wrong if actually extDict */
517
1.01G
            match = base + matchIndex;
518
1.01G
            matchLength += ZSTD_count(ip+matchLength, match+matchLength, iend);
519
1.01G
        } else {
520
39.5M
            match = dictBase + matchIndex;
521
39.5M
            matchLength += ZSTD_count_2segments(ip+matchLength, match+matchLength, iend, dictEnd, prefixStart);
522
39.5M
            if (matchIndex+matchLength >= dictLimit)
523
88.0k
                match = base + matchIndex;   /* to prepare for next usage of match[matchLength] */
524
39.5M
        }
525
526
1.05G
        if (matchLength > bestLength) {
527
177M
            bestLength = matchLength;
528
177M
            if (matchLength > matchEndIdx - matchIndex)
529
4.11M
                matchEndIdx = matchIndex + (U32)matchLength;
530
177M
        }
531
532
1.05G
        if (ip+matchLength == iend) {   /* equal : no way to know if inf or sup */
533
681k
            break;   /* drop , to guarantee consistency ; miss a bit of compression, but other solutions can corrupt tree */
534
681k
        }
535
536
1.05G
        if (match[matchLength] < ip[matchLength]) {  /* necessarily within buffer */
537
            /* match is smaller than current */
538
341M
            *smallerPtr = matchIndex;             /* update smaller idx */
539
341M
            commonLengthSmaller = matchLength;    /* all smaller will now have at least this guaranteed common length */
540
341M
            if (matchIndex <= btLow) { smallerPtr=&dummy32; break; }   /* beyond tree size, stop searching */
541
314M
            smallerPtr = nextPtr+1;               /* new "candidate" => larger than match, which was smaller than target */
542
314M
            matchIndex = nextPtr[1];              /* new matchIndex, larger than previous and closer to current */
543
709M
        } else {
544
            /* match is larger than current */
545
709M
            *largerPtr = matchIndex;
546
709M
            commonLengthLarger = matchLength;
547
709M
            if (matchIndex <= btLow) { largerPtr=&dummy32; break; }   /* beyond tree size, stop searching */
548
680M
            largerPtr = nextPtr;
549
680M
            matchIndex = nextPtr[0];
550
680M
    }   }
551
552
215M
    *smallerPtr = *largerPtr = 0;
553
215M
    {   U32 positions = 0;
554
215M
        if (bestLength > 384) positions = MIN(192, (U32)(bestLength - 384));   /* speed optimization */
555
215M
        assert(matchEndIdx > curr + 8);
556
215M
        return MAX(positions, matchEndIdx - (curr + 8));
557
215M
    }
558
215M
}
559
560
FORCE_INLINE_TEMPLATE
561
ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
562
void ZSTD_updateTree_internal(
563
                ZSTD_MatchState_t* ms,
564
                const BYTE* const ip, const BYTE* const iend,
565
                const U32 mls, const ZSTD_dictMode_e dictMode)
566
796M
{
567
796M
    const BYTE* const base = ms->window.base;
568
796M
    U32 const target = (U32)(ip - base);
569
796M
    U32 idx = ms->nextToUpdate;
570
796M
    DEBUGLOG(7, "ZSTD_updateTree_internal, from %u to %u  (dictMode:%u)",
571
796M
                idx, target, dictMode);
572
573
1.01G
    while(idx < target) {
574
215M
        U32 const forward = ZSTD_insertBt1(ms, base+idx, iend, target, mls, dictMode == ZSTD_extDict);
575
215M
        assert(idx < (U32)(idx + forward));
576
215M
        idx += forward;
577
215M
    }
578
796M
    assert((size_t)(ip - base) <= (size_t)(U32)(-1));
579
796M
    assert((size_t)(iend - base) <= (size_t)(U32)(-1));
580
796M
    ms->nextToUpdate = target;
581
796M
}
582
583
36.5k
void ZSTD_updateTree(ZSTD_MatchState_t* ms, const BYTE* ip, const BYTE* iend) {
584
36.5k
    ZSTD_updateTree_internal(ms, ip, iend, ms->cParams.minMatch, ZSTD_noDict);
585
36.5k
}
586
587
FORCE_INLINE_TEMPLATE
588
ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
589
U32
590
ZSTD_insertBtAndGetAllMatches (
591
                ZSTD_match_t* matches,  /* store result (found matches) in this table (presumed large enough) */
592
                ZSTD_MatchState_t* ms,
593
                U32* nextToUpdate3,
594
                const BYTE* const ip, const BYTE* const iLimit,
595
                const ZSTD_dictMode_e dictMode,
596
                const U32 rep[ZSTD_REP_NUM],
597
                const U32 ll0,  /* tells if associated literal length is 0 or not. This value must be 0 or 1 */
598
                const U32 lengthToBeat,
599
                const U32 mls /* template */)
600
796M
{
601
796M
    const ZSTD_compressionParameters* const cParams = &ms->cParams;
602
796M
    U32 const sufficient_len = MIN(cParams->targetLength, ZSTD_OPT_NUM -1);
603
796M
    const BYTE* const base = ms->window.base;
604
796M
    U32 const curr = (U32)(ip-base);
605
796M
    U32 const hashLog = cParams->hashLog;
606
796M
    U32 const minMatch = (mls==3) ? 3 : 4;
607
796M
    U32* const hashTable = ms->hashTable;
608
796M
    size_t const h  = ZSTD_hashPtr(ip, hashLog, mls);
609
796M
    U32 matchIndex  = hashTable[h];
610
796M
    U32* const bt   = ms->chainTable;
611
796M
    U32 const btLog = cParams->chainLog - 1;
612
796M
    U32 const btMask= (1U << btLog) - 1;
613
796M
    size_t commonLengthSmaller=0, commonLengthLarger=0;
614
796M
    const BYTE* const dictBase = ms->window.dictBase;
615
796M
    U32 const dictLimit = ms->window.dictLimit;
616
796M
    const BYTE* const dictEnd = dictBase + dictLimit;
617
796M
    const BYTE* const prefixStart = base + dictLimit;
618
796M
    U32 const btLow = (btMask >= curr) ? 0 : curr - btMask;
619
796M
    U32 const windowLow = ZSTD_getLowestMatchIndex(ms, curr, cParams->windowLog);
620
18.4E
    U32 const matchLow = windowLow ? windowLow : 1;
621
796M
    U32* smallerPtr = bt + 2*(curr&btMask);
622
796M
    U32* largerPtr  = bt + 2*(curr&btMask) + 1;
623
796M
    U32 matchEndIdx = curr+8+1;   /* farthest referenced position of any match => detects repetitive patterns */
624
796M
    U32 dummy32;   /* to be nullified at the end */
625
796M
    U32 mnum = 0;
626
796M
    U32 nbCompares = 1U << cParams->searchLog;
627
628
796M
    const ZSTD_MatchState_t* dms    = dictMode == ZSTD_dictMatchState ? ms->dictMatchState : NULL;
629
796M
    const ZSTD_compressionParameters* const dmsCParams =
630
796M
                                      dictMode == ZSTD_dictMatchState ? &dms->cParams : NULL;
631
796M
    const BYTE* const dmsBase       = dictMode == ZSTD_dictMatchState ? dms->window.base : NULL;
632
796M
    const BYTE* const dmsEnd        = dictMode == ZSTD_dictMatchState ? dms->window.nextSrc : NULL;
633
796M
    U32         const dmsHighLimit  = dictMode == ZSTD_dictMatchState ? (U32)(dmsEnd - dmsBase) : 0;
634
796M
    U32         const dmsLowLimit   = dictMode == ZSTD_dictMatchState ? dms->window.lowLimit : 0;
635
796M
    U32         const dmsIndexDelta = dictMode == ZSTD_dictMatchState ? windowLow - dmsHighLimit : 0;
636
796M
    U32         const dmsHashLog    = dictMode == ZSTD_dictMatchState ? dmsCParams->hashLog : hashLog;
637
796M
    U32         const dmsBtLog      = dictMode == ZSTD_dictMatchState ? dmsCParams->chainLog - 1 : btLog;
638
796M
    U32         const dmsBtMask     = dictMode == ZSTD_dictMatchState ? (1U << dmsBtLog) - 1 : 0;
639
796M
    U32         const dmsBtLow      = dictMode == ZSTD_dictMatchState && dmsBtMask < dmsHighLimit - dmsLowLimit ? dmsHighLimit - dmsBtMask : dmsLowLimit;
640
641
796M
    size_t bestLength = lengthToBeat-1;
642
796M
    DEBUGLOG(8, "ZSTD_insertBtAndGetAllMatches: current=%u", curr);
643
644
    /* check repCode */
645
796M
    assert(ll0 <= 1);   /* necessarily 1 or 0 */
646
797M
    {   U32 const lastR = ZSTD_REP_NUM + ll0;
647
797M
        U32 repCode;
648
3.17G
        for (repCode = ll0; repCode < lastR; repCode++) {
649
2.38G
            U32 const repOffset = (repCode==ZSTD_REP_NUM) ? (rep[0] - 1) : rep[repCode];
650
2.38G
            U32 const repIndex = curr - repOffset;
651
2.38G
            U32 repLen = 0;
652
2.38G
            assert(curr >= dictLimit);
653
2.38G
            if (repOffset-1 /* intentional overflow, discards 0 and -1 */ < curr-dictLimit) {  /* equivalent to `curr > repIndex >= dictLimit` */
654
                /* We must validate the repcode offset because when we're using a dictionary the
655
                 * valid offset range shrinks when the dictionary goes out of bounds.
656
                 */
657
2.29G
                if ((repIndex >= windowLow) & (ZSTD_readMINMATCH(ip, minMatch) == ZSTD_readMINMATCH(ip - repOffset, minMatch))) {
658
228M
                    repLen = (U32)ZSTD_count(ip+minMatch, ip+minMatch-repOffset, iLimit) + minMatch;
659
228M
                }
660
2.29G
            } else {  /* repIndex < dictLimit || repIndex >= curr */
661
88.9M
                const BYTE* const repMatch = dictMode == ZSTD_dictMatchState ?
662
2.16M
                                             dmsBase + repIndex - dmsIndexDelta :
663
88.9M
                                             dictBase + repIndex;
664
88.9M
                assert(curr >= windowLow);
665
90.1M
                if ( dictMode == ZSTD_extDict
666
49.4M
                  && ( ((repOffset-1) /*intentional overflow*/ < curr - windowLow)  /* equivalent to `curr > repIndex >= windowLow` */
667
49.4M
                     & (ZSTD_index_overlap_check(dictLimit, repIndex)) )
668
47.5M
                  && (ZSTD_readMINMATCH(ip, minMatch) == ZSTD_readMINMATCH(repMatch, minMatch)) ) {
669
1.29M
                    repLen = (U32)ZSTD_count_2segments(ip+minMatch, repMatch+minMatch, iLimit, dictEnd, prefixStart) + minMatch;
670
1.29M
                }
671
90.1M
                if (dictMode == ZSTD_dictMatchState
672
2.16M
                  && ( ((repOffset-1) /*intentional overflow*/ < curr - (dmsLowLimit + dmsIndexDelta))  /* equivalent to `curr > repIndex >= dmsLowLimit` */
673
2.16M
                     & (ZSTD_index_overlap_check(dictLimit, repIndex)) )
674
1.88M
                  && (ZSTD_readMINMATCH(ip, minMatch) == ZSTD_readMINMATCH(repMatch, minMatch)) ) {
675
105k
                    repLen = (U32)ZSTD_count_2segments(ip+minMatch, repMatch+minMatch, iLimit, dmsEnd, prefixStart) + minMatch;
676
105k
            }   }
677
            /* save longer solution */
678
2.38G
            if (repLen > bestLength) {
679
165M
                DEBUGLOG(8, "found repCode %u (ll0:%u, offset:%u) of length %u",
680
165M
                            repCode, ll0, repOffset, repLen);
681
165M
                bestLength = repLen;
682
331M
                matches[mnum].off = REPCODE_TO_OFFBASE(repCode - ll0 + 1);  /* expect value between 1 and 3 */
683
331M
                matches[mnum].len = (U32)repLen;
684
331M
                mnum++;
685
331M
                if ( (repLen > sufficient_len)
686
165M
                   | (ip+repLen == iLimit) ) {  /* best possible */
687
2.17M
                    return mnum;
688
2.17M
    }   }   }   }
689
690
    /* HC3 match finder */
691
796M
    if ((mls == 3) /*static*/ && (bestLength < mls)) {
692
313M
        U32 const matchIndex3 = ZSTD_insertAndFindFirstIndexHash3(ms, nextToUpdate3, ip);
693
313M
        if ((matchIndex3 >= matchLow)
694
313M
          & (curr - matchIndex3 < (1<<18)) /*heuristic : longer distance likely too expensive*/ ) {
695
197M
            size_t mlen;
696
197M
            if ((dictMode == ZSTD_noDict) /*static*/ || (dictMode == ZSTD_dictMatchState) /*static*/ || (matchIndex3 >= dictLimit)) {
697
196M
                const BYTE* const match = base + matchIndex3;
698
196M
                mlen = ZSTD_count(ip, match, iLimit);
699
196M
            } else {
700
1.02M
                const BYTE* const match = dictBase + matchIndex3;
701
1.02M
                mlen = ZSTD_count_2segments(ip, match, iLimit, dictEnd, prefixStart);
702
1.02M
            }
703
704
            /* save best solution */
705
197M
            if (mlen >= mls /* == 3 > bestLength */) {
706
129M
                DEBUGLOG(8, "found small match with hlog3, of length %u",
707
129M
                            (U32)mlen);
708
129M
                bestLength = mlen;
709
129M
                assert(curr > matchIndex3);
710
129M
                assert(mnum==0);  /* no prior solution */
711
129M
                matches[0].off = OFFSET_TO_OFFBASE(curr - matchIndex3);
712
129M
                matches[0].len = (U32)mlen;
713
129M
                mnum = 1;
714
129M
                if ( (mlen > sufficient_len) |
715
129M
                     (ip+mlen == iLimit) ) {  /* best possible length */
716
2.89M
                    ms->nextToUpdate = curr+1;  /* skip insertion */
717
2.89M
                    return 1;
718
2.89M
        }   }   }
719
        /* no dictMatchState lookup: dicts don't have a populated HC3 table */
720
313M
    }  /* if (mls == 3) */
721
722
793M
    hashTable[h] = curr;   /* Update Hash Table */
723
724
2.77G
    for (; nbCompares && (matchIndex >= matchLow); --nbCompares) {
725
2.19G
        U32* const nextPtr = bt + 2*(matchIndex & btMask);
726
2.19G
        const BYTE* match;
727
2.19G
        size_t matchLength = MIN(commonLengthSmaller, commonLengthLarger);   /* guaranteed minimum nb of common bytes */
728
2.19G
        assert(curr > matchIndex);
729
730
2.19G
        if ((dictMode == ZSTD_noDict) || (dictMode == ZSTD_dictMatchState) || (matchIndex+matchLength >= dictLimit)) {
731
2.17G
            assert(matchIndex+matchLength >= dictLimit);  /* ensure the condition is correct when !extDict */
732
2.17G
            match = base + matchIndex;
733
2.17G
            if (matchIndex >= dictLimit) assert(memcmp(match, ip, matchLength) == 0);  /* ensure early section of match is equal as expected */
734
2.17G
            matchLength += ZSTD_count(ip+matchLength, match+matchLength, iLimit);
735
2.17G
        } else {
736
19.4M
            match = dictBase + matchIndex;
737
19.4M
            assert(memcmp(match, ip, matchLength) == 0);  /* ensure early section of match is equal as expected */
738
19.4M
            matchLength += ZSTD_count_2segments(ip+matchLength, match+matchLength, iLimit, dictEnd, prefixStart);
739
19.4M
            if (matchIndex+matchLength >= dictLimit)
740
102k
                match = base + matchIndex;   /* prepare for match[matchLength] read */
741
19.4M
        }
742
743
2.19G
        if (matchLength > bestLength) {
744
243M
            DEBUGLOG(8, "found match of length %u at distance %u (offBase=%u)",
745
243M
                    (U32)matchLength, curr - matchIndex, OFFSET_TO_OFFBASE(curr - matchIndex));
746
243M
            assert(matchEndIdx > matchIndex);
747
243M
            if (matchLength > matchEndIdx - matchIndex)
748
1.53M
                matchEndIdx = matchIndex + (U32)matchLength;
749
243M
            bestLength = matchLength;
750
243M
            matches[mnum].off = OFFSET_TO_OFFBASE(curr - matchIndex);
751
243M
            matches[mnum].len = (U32)matchLength;
752
243M
            mnum++;
753
243M
            if ( (matchLength > ZSTD_OPT_NUM)
754
243M
               | (ip+matchLength == iLimit) /* equal : no way to know if inf or sup */) {
755
155k
                if (dictMode == ZSTD_dictMatchState) nbCompares = 0; /* break should also skip searching dms */
756
155k
                break; /* drop, to preserve bt consistency (miss a little bit of compression) */
757
155k
        }   }
758
759
2.19G
        if (match[matchLength] < ip[matchLength]) {
760
            /* match smaller than current */
761
795M
            *smallerPtr = matchIndex;             /* update smaller idx */
762
795M
            commonLengthSmaller = matchLength;    /* all smaller will now have at least this guaranteed common length */
763
795M
            if (matchIndex <= btLow) { smallerPtr=&dummy32; break; }   /* beyond tree size, stop the search */
764
692M
            smallerPtr = nextPtr+1;               /* new candidate => larger than match, which was smaller than current */
765
692M
            matchIndex = nextPtr[1];              /* new matchIndex, larger than previous, closer to current */
766
1.39G
        } else {
767
1.39G
            *largerPtr = matchIndex;
768
1.39G
            commonLengthLarger = matchLength;
769
1.39G
            if (matchIndex <= btLow) { largerPtr=&dummy32; break; }   /* beyond tree size, stop the search */
770
1.29G
            largerPtr = nextPtr;
771
1.29G
            matchIndex = nextPtr[0];
772
1.29G
    }   }
773
774
793M
    *smallerPtr = *largerPtr = 0;
775
776
793M
    assert(nbCompares <= (1U << ZSTD_SEARCHLOG_MAX)); /* Check we haven't underflowed. */
777
793M
    if (dictMode == ZSTD_dictMatchState && nbCompares) {
778
2.64M
        size_t const dmsH = ZSTD_hashPtr(ip, dmsHashLog, mls);
779
2.64M
        U32 dictMatchIndex = dms->hashTable[dmsH];
780
2.64M
        const U32* const dmsBt = dms->chainTable;
781
2.64M
        commonLengthSmaller = commonLengthLarger = 0;
782
7.05M
        for (; nbCompares && (dictMatchIndex > dmsLowLimit); --nbCompares) {
783
5.51M
            const U32* const nextPtr = dmsBt + 2*(dictMatchIndex & dmsBtMask);
784
5.51M
            size_t matchLength = MIN(commonLengthSmaller, commonLengthLarger);   /* guaranteed minimum nb of common bytes */
785
5.51M
            const BYTE* match = dmsBase + dictMatchIndex;
786
5.51M
            matchLength += ZSTD_count_2segments(ip+matchLength, match+matchLength, iLimit, dmsEnd, prefixStart);
787
5.51M
            if (dictMatchIndex+matchLength >= dmsHighLimit)
788
64.8k
                match = base + dictMatchIndex + dmsIndexDelta;   /* to prepare for next usage of match[matchLength] */
789
790
5.51M
            if (matchLength > bestLength) {
791
530k
                matchIndex = dictMatchIndex + dmsIndexDelta;
792
530k
                DEBUGLOG(8, "found dms match of length %u at distance %u (offBase=%u)",
793
530k
                        (U32)matchLength, curr - matchIndex, OFFSET_TO_OFFBASE(curr - matchIndex));
794
530k
                if (matchLength > matchEndIdx - matchIndex)
795
208
                    matchEndIdx = matchIndex + (U32)matchLength;
796
530k
                bestLength = matchLength;
797
530k
                matches[mnum].off = OFFSET_TO_OFFBASE(curr - matchIndex);
798
530k
                matches[mnum].len = (U32)matchLength;
799
530k
                mnum++;
800
530k
                if ( (matchLength > ZSTD_OPT_NUM)
801
530k
                   | (ip+matchLength == iLimit) /* equal : no way to know if inf or sup */) {
802
5.24k
                    break;   /* drop, to guarantee consistency (miss a little bit of compression) */
803
5.24k
            }   }
804
805
5.51M
            if (dictMatchIndex <= dmsBtLow) { break; }   /* beyond tree size, stop the search */
806
4.41M
            if (match[matchLength] < ip[matchLength]) {
807
2.16M
                commonLengthSmaller = matchLength;    /* all smaller will now have at least this guaranteed common length */
808
2.16M
                dictMatchIndex = nextPtr[1];              /* new matchIndex larger than previous (closer to current) */
809
2.24M
            } else {
810
                /* match is larger than current */
811
2.24M
                commonLengthLarger = matchLength;
812
2.24M
                dictMatchIndex = nextPtr[0];
813
2.24M
    }   }   }  /* if (dictMode == ZSTD_dictMatchState) */
814
815
791M
    assert(matchEndIdx > curr+8);
816
791M
    ms->nextToUpdate = matchEndIdx - 8;  /* skip repetitive patterns */
817
791M
    return mnum;
818
791M
}
819
820
typedef U32 (*ZSTD_getAllMatchesFn)(
821
    ZSTD_match_t*,
822
    ZSTD_MatchState_t*,
823
    U32*,
824
    const BYTE*,
825
    const BYTE*,
826
    const U32 rep[ZSTD_REP_NUM],
827
    U32 const ll0,
828
    U32 const lengthToBeat);
829
830
FORCE_INLINE_TEMPLATE
831
ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
832
U32 ZSTD_btGetAllMatches_internal(
833
        ZSTD_match_t* matches,
834
        ZSTD_MatchState_t* ms,
835
        U32* nextToUpdate3,
836
        const BYTE* ip,
837
        const BYTE* const iHighLimit,
838
        const U32 rep[ZSTD_REP_NUM],
839
        U32 const ll0,
840
        U32 const lengthToBeat,
841
        const ZSTD_dictMode_e dictMode,
842
        const U32 mls)
843
828M
{
844
828M
    assert(BOUNDED(3, ms->cParams.minMatch, 6) == mls);
845
828M
    DEBUGLOG(8, "ZSTD_BtGetAllMatches(dictMode=%d, mls=%u)", (int)dictMode, mls);
846
828M
    if (ip < ms->window.base + ms->nextToUpdate)
847
31.9M
        return 0;   /* skipped area */
848
796M
    ZSTD_updateTree_internal(ms, ip, iHighLimit, mls, dictMode);
849
796M
    return ZSTD_insertBtAndGetAllMatches(matches, ms, nextToUpdate3, ip, iHighLimit, dictMode, rep, ll0, lengthToBeat, mls);
850
828M
}
851
852
7.04M
#define ZSTD_BT_GET_ALL_MATCHES_FN(dictMode, mls) ZSTD_btGetAllMatches_##dictMode##_##mls
853
854
#define GEN_ZSTD_BT_GET_ALL_MATCHES_(dictMode, mls)            \
855
    static U32 ZSTD_BT_GET_ALL_MATCHES_FN(dictMode, mls)(      \
856
            ZSTD_match_t* matches,                             \
857
            ZSTD_MatchState_t* ms,                             \
858
            U32* nextToUpdate3,                                \
859
            const BYTE* ip,                                    \
860
            const BYTE* const iHighLimit,                      \
861
            const U32 rep[ZSTD_REP_NUM],                       \
862
            U32 const ll0,                                     \
863
            U32 const lengthToBeat)                            \
864
828M
    {                                                          \
865
828M
        return ZSTD_btGetAllMatches_internal(                  \
866
828M
                matches, ms, nextToUpdate3, ip, iHighLimit,    \
867
828M
                rep, ll0, lengthToBeat, ZSTD_##dictMode, mls); \
868
828M
    }
zstd_opt.c:ZSTD_btGetAllMatches_noDict_3
Line
Count
Source
864
398M
    {                                                          \
865
398M
        return ZSTD_btGetAllMatches_internal(                  \
866
398M
                matches, ms, nextToUpdate3, ip, iHighLimit,    \
867
398M
                rep, ll0, lengthToBeat, ZSTD_##dictMode, mls); \
868
398M
    }
zstd_opt.c:ZSTD_btGetAllMatches_noDict_4
Line
Count
Source
864
91.5M
    {                                                          \
865
91.5M
        return ZSTD_btGetAllMatches_internal(                  \
866
91.5M
                matches, ms, nextToUpdate3, ip, iHighLimit,    \
867
91.5M
                rep, ll0, lengthToBeat, ZSTD_##dictMode, mls); \
868
91.5M
    }
zstd_opt.c:ZSTD_btGetAllMatches_noDict_5
Line
Count
Source
864
112M
    {                                                          \
865
112M
        return ZSTD_btGetAllMatches_internal(                  \
866
112M
                matches, ms, nextToUpdate3, ip, iHighLimit,    \
867
112M
                rep, ll0, lengthToBeat, ZSTD_##dictMode, mls); \
868
112M
    }
zstd_opt.c:ZSTD_btGetAllMatches_noDict_6
Line
Count
Source
864
155M
    {                                                          \
865
155M
        return ZSTD_btGetAllMatches_internal(                  \
866
155M
                matches, ms, nextToUpdate3, ip, iHighLimit,    \
867
155M
                rep, ll0, lengthToBeat, ZSTD_##dictMode, mls); \
868
155M
    }
zstd_opt.c:ZSTD_btGetAllMatches_extDict_3
Line
Count
Source
864
22.0M
    {                                                          \
865
22.0M
        return ZSTD_btGetAllMatches_internal(                  \
866
22.0M
                matches, ms, nextToUpdate3, ip, iHighLimit,    \
867
22.0M
                rep, ll0, lengthToBeat, ZSTD_##dictMode, mls); \
868
22.0M
    }
zstd_opt.c:ZSTD_btGetAllMatches_extDict_4
Line
Count
Source
864
24.2M
    {                                                          \
865
24.2M
        return ZSTD_btGetAllMatches_internal(                  \
866
24.2M
                matches, ms, nextToUpdate3, ip, iHighLimit,    \
867
24.2M
                rep, ll0, lengthToBeat, ZSTD_##dictMode, mls); \
868
24.2M
    }
zstd_opt.c:ZSTD_btGetAllMatches_extDict_5
Line
Count
Source
864
9.91M
    {                                                          \
865
9.91M
        return ZSTD_btGetAllMatches_internal(                  \
866
9.91M
                matches, ms, nextToUpdate3, ip, iHighLimit,    \
867
9.91M
                rep, ll0, lengthToBeat, ZSTD_##dictMode, mls); \
868
9.91M
    }
zstd_opt.c:ZSTD_btGetAllMatches_extDict_6
Line
Count
Source
864
11.0M
    {                                                          \
865
11.0M
        return ZSTD_btGetAllMatches_internal(                  \
866
11.0M
                matches, ms, nextToUpdate3, ip, iHighLimit,    \
867
11.0M
                rep, ll0, lengthToBeat, ZSTD_##dictMode, mls); \
868
11.0M
    }
zstd_opt.c:ZSTD_btGetAllMatches_dictMatchState_3
Line
Count
Source
864
1.09M
    {                                                          \
865
1.09M
        return ZSTD_btGetAllMatches_internal(                  \
866
1.09M
                matches, ms, nextToUpdate3, ip, iHighLimit,    \
867
1.09M
                rep, ll0, lengthToBeat, ZSTD_##dictMode, mls); \
868
1.09M
    }
zstd_opt.c:ZSTD_btGetAllMatches_dictMatchState_4
Line
Count
Source
864
579k
    {                                                          \
865
579k
        return ZSTD_btGetAllMatches_internal(                  \
866
579k
                matches, ms, nextToUpdate3, ip, iHighLimit,    \
867
579k
                rep, ll0, lengthToBeat, ZSTD_##dictMode, mls); \
868
579k
    }
zstd_opt.c:ZSTD_btGetAllMatches_dictMatchState_5
Line
Count
Source
864
670k
    {                                                          \
865
670k
        return ZSTD_btGetAllMatches_internal(                  \
866
670k
                matches, ms, nextToUpdate3, ip, iHighLimit,    \
867
670k
                rep, ll0, lengthToBeat, ZSTD_##dictMode, mls); \
868
670k
    }
zstd_opt.c:ZSTD_btGetAllMatches_dictMatchState_6
Line
Count
Source
864
735k
    {                                                          \
865
735k
        return ZSTD_btGetAllMatches_internal(                  \
866
735k
                matches, ms, nextToUpdate3, ip, iHighLimit,    \
867
735k
                rep, ll0, lengthToBeat, ZSTD_##dictMode, mls); \
868
735k
    }
869
870
#define GEN_ZSTD_BT_GET_ALL_MATCHES(dictMode)  \
871
    GEN_ZSTD_BT_GET_ALL_MATCHES_(dictMode, 3)  \
872
    GEN_ZSTD_BT_GET_ALL_MATCHES_(dictMode, 4)  \
873
    GEN_ZSTD_BT_GET_ALL_MATCHES_(dictMode, 5)  \
874
    GEN_ZSTD_BT_GET_ALL_MATCHES_(dictMode, 6)
875
876
GEN_ZSTD_BT_GET_ALL_MATCHES(noDict)
877
GEN_ZSTD_BT_GET_ALL_MATCHES(extDict)
878
GEN_ZSTD_BT_GET_ALL_MATCHES(dictMatchState)
879
880
#define ZSTD_BT_GET_ALL_MATCHES_ARRAY(dictMode)  \
881
1.76M
    {                                            \
882
1.76M
        ZSTD_BT_GET_ALL_MATCHES_FN(dictMode, 3), \
883
1.76M
        ZSTD_BT_GET_ALL_MATCHES_FN(dictMode, 4), \
884
1.76M
        ZSTD_BT_GET_ALL_MATCHES_FN(dictMode, 5), \
885
1.76M
        ZSTD_BT_GET_ALL_MATCHES_FN(dictMode, 6)  \
886
1.76M
    }
887
888
static ZSTD_getAllMatchesFn
889
ZSTD_selectBtGetAllMatches(ZSTD_MatchState_t const* ms, ZSTD_dictMode_e const dictMode)
890
586k
{
891
586k
    ZSTD_getAllMatchesFn const getAllMatchesFns[3][4] = {
892
586k
        ZSTD_BT_GET_ALL_MATCHES_ARRAY(noDict),
893
586k
        ZSTD_BT_GET_ALL_MATCHES_ARRAY(extDict),
894
586k
        ZSTD_BT_GET_ALL_MATCHES_ARRAY(dictMatchState)
895
586k
    };
896
586k
    U32 const mls = BOUNDED(3, ms->cParams.minMatch, 6);
897
586k
    assert((U32)dictMode < 3);
898
586k
    assert(mls - 3 < 4);
899
586k
    return getAllMatchesFns[(int)dictMode][mls - 3];
900
586k
}
901
902
/*************************
903
*  LDM helper functions  *
904
*************************/
905
906
/* Struct containing info needed to make decision about ldm inclusion */
907
typedef struct {
908
    RawSeqStore_t seqStore;   /* External match candidates store for this block */
909
    U32 startPosInBlock;      /* Start position of the current match candidate */
910
    U32 endPosInBlock;        /* End position of the current match candidate */
911
    U32 offset;               /* Offset of the match candidate */
912
} ZSTD_optLdm_t;
913
914
/* ZSTD_optLdm_skipRawSeqStoreBytes():
915
 * Moves forward in @rawSeqStore by @nbBytes,
916
 * which will update the fields 'pos' and 'posInSequence'.
917
 */
918
static void ZSTD_optLdm_skipRawSeqStoreBytes(RawSeqStore_t* rawSeqStore, size_t nbBytes)
919
606k
{
920
606k
    U32 currPos = (U32)(rawSeqStore->posInSequence + nbBytes);
921
1.19M
    while (currPos && rawSeqStore->pos < rawSeqStore->size) {
922
633k
        rawSeq currSeq = rawSeqStore->seq[rawSeqStore->pos];
923
633k
        if (currPos >= currSeq.litLength + currSeq.matchLength) {
924
583k
            currPos -= currSeq.litLength + currSeq.matchLength;
925
583k
            rawSeqStore->pos++;
926
583k
        } else {
927
49.3k
            rawSeqStore->posInSequence = currPos;
928
49.3k
            break;
929
49.3k
        }
930
633k
    }
931
606k
    if (currPos == 0 || rawSeqStore->pos == rawSeqStore->size) {
932
557k
        rawSeqStore->posInSequence = 0;
933
557k
    }
934
606k
}
935
936
/* ZSTD_opt_getNextMatchAndUpdateSeqStore():
937
 * Calculates the beginning and end of the next match in the current block.
938
 * Updates 'pos' and 'posInSequence' of the ldmSeqStore.
939
 */
940
static void
941
ZSTD_opt_getNextMatchAndUpdateSeqStore(ZSTD_optLdm_t* optLdm, U32 currPosInBlock,
942
                                       U32 blockBytesRemaining)
943
1.09M
{
944
1.09M
    rawSeq currSeq;
945
1.09M
    U32 currBlockEndPos;
946
1.09M
    U32 literalsBytesRemaining;
947
1.09M
    U32 matchBytesRemaining;
948
949
    /* Setting match end position to MAX to ensure we never use an LDM during this block */
950
1.09M
    if (optLdm->seqStore.size == 0 || optLdm->seqStore.pos >= optLdm->seqStore.size) {
951
538k
        optLdm->startPosInBlock = UINT_MAX;
952
538k
        optLdm->endPosInBlock = UINT_MAX;
953
538k
        return;
954
538k
    }
955
    /* Calculate appropriate bytes left in matchLength and litLength
956
     * after adjusting based on ldmSeqStore->posInSequence */
957
558k
    currSeq = optLdm->seqStore.seq[optLdm->seqStore.pos];
958
558k
    assert(optLdm->seqStore.posInSequence <= currSeq.litLength + currSeq.matchLength);
959
558k
    currBlockEndPos = currPosInBlock + blockBytesRemaining;
960
558k
    literalsBytesRemaining = (optLdm->seqStore.posInSequence < currSeq.litLength) ?
961
425k
            currSeq.litLength - (U32)optLdm->seqStore.posInSequence :
962
558k
            0;
963
558k
    matchBytesRemaining = (literalsBytesRemaining == 0) ?
964
133k
            currSeq.matchLength - ((U32)optLdm->seqStore.posInSequence - currSeq.litLength) :
965
558k
            currSeq.matchLength;
966
967
    /* If there are more literal bytes than bytes remaining in block, no ldm is possible */
968
558k
    if (literalsBytesRemaining >= blockBytesRemaining) {
969
19.6k
        optLdm->startPosInBlock = UINT_MAX;
970
19.6k
        optLdm->endPosInBlock = UINT_MAX;
971
19.6k
        ZSTD_optLdm_skipRawSeqStoreBytes(&optLdm->seqStore, blockBytesRemaining);
972
19.6k
        return;
973
19.6k
    }
974
975
    /* Matches may be < minMatch by this process. In that case, we will reject them
976
       when we are deciding whether or not to add the ldm */
977
539k
    optLdm->startPosInBlock = currPosInBlock + literalsBytesRemaining;
978
539k
    optLdm->endPosInBlock = optLdm->startPosInBlock + matchBytesRemaining;
979
539k
    optLdm->offset = currSeq.offset;
980
981
539k
    if (optLdm->endPosInBlock > currBlockEndPos) {
982
        /* Match ends after the block ends, we can't use the whole match */
983
368
        optLdm->endPosInBlock = currBlockEndPos;
984
368
        ZSTD_optLdm_skipRawSeqStoreBytes(&optLdm->seqStore, currBlockEndPos - currPosInBlock);
985
538k
    } else {
986
        /* Consume nb of bytes equal to size of sequence left */
987
538k
        ZSTD_optLdm_skipRawSeqStoreBytes(&optLdm->seqStore, literalsBytesRemaining + matchBytesRemaining);
988
538k
    }
989
539k
}
990
991
/* ZSTD_optLdm_maybeAddMatch():
992
 * Adds a match if it's long enough,
993
 * based on it's 'matchStartPosInBlock' and 'matchEndPosInBlock',
994
 * into 'matches'. Maintains the correct ordering of 'matches'.
995
 */
996
static void ZSTD_optLdm_maybeAddMatch(ZSTD_match_t* matches, U32* nbMatches,
997
                                      const ZSTD_optLdm_t* optLdm, U32 currPosInBlock,
998
                                      U32 minMatch)
999
28.2M
{
1000
28.2M
    U32 const posDiff = currPosInBlock - optLdm->startPosInBlock;
1001
    /* Note: ZSTD_match_t actually contains offBase and matchLength (before subtracting MINMATCH) */
1002
28.2M
    U32 const candidateMatchLength = optLdm->endPosInBlock - optLdm->startPosInBlock - posDiff;
1003
1004
    /* Ensure that current block position is not outside of the match */
1005
28.2M
    if (currPosInBlock < optLdm->startPosInBlock
1006
4.42M
      || currPosInBlock >= optLdm->endPosInBlock
1007
24.8M
      || candidateMatchLength < minMatch) {
1008
24.8M
        return;
1009
24.8M
    }
1010
1011
3.38M
    if (*nbMatches == 0 || ((candidateMatchLength > matches[*nbMatches-1].len) && *nbMatches < ZSTD_OPT_NUM)) {
1012
867k
        U32 const candidateOffBase = OFFSET_TO_OFFBASE(optLdm->offset);
1013
867k
        DEBUGLOG(6, "ZSTD_optLdm_maybeAddMatch(): Adding ldm candidate match (offBase: %u matchLength %u) at block position=%u",
1014
867k
                 candidateOffBase, candidateMatchLength, currPosInBlock);
1015
867k
        matches[*nbMatches].len = candidateMatchLength;
1016
867k
        matches[*nbMatches].off = candidateOffBase;
1017
867k
        (*nbMatches)++;
1018
867k
    }
1019
3.38M
}
1020
1021
/* ZSTD_optLdm_processMatchCandidate():
1022
 * Wrapper function to update ldm seq store and call ldm functions as necessary.
1023
 */
1024
static void
1025
ZSTD_optLdm_processMatchCandidate(ZSTD_optLdm_t* optLdm,
1026
                                  ZSTD_match_t* matches, U32* nbMatches,
1027
                                  U32 currPosInBlock, U32 remainingBytes,
1028
                                  U32 minMatch)
1029
828M
{
1030
828M
    if (optLdm->seqStore.size == 0 || optLdm->seqStore.pos >= optLdm->seqStore.size) {
1031
799M
        return;
1032
799M
    }
1033
1034
28.2M
    if (currPosInBlock >= optLdm->endPosInBlock) {
1035
510k
        if (currPosInBlock > optLdm->endPosInBlock) {
1036
            /* The position at which ZSTD_optLdm_processMatchCandidate() is called is not necessarily
1037
             * at the end of a match from the ldm seq store, and will often be some bytes
1038
             * over beyond matchEndPosInBlock. As such, we need to correct for these "overshoots"
1039
             */
1040
48.0k
            U32 const posOvershoot = currPosInBlock - optLdm->endPosInBlock;
1041
48.0k
            ZSTD_optLdm_skipRawSeqStoreBytes(&optLdm->seqStore, posOvershoot);
1042
48.0k
        }
1043
510k
        ZSTD_opt_getNextMatchAndUpdateSeqStore(optLdm, currPosInBlock, remainingBytes);
1044
510k
    }
1045
28.2M
    ZSTD_optLdm_maybeAddMatch(matches, nbMatches, optLdm, currPosInBlock, minMatch);
1046
28.2M
}
1047
1048
1049
/*-*******************************
1050
*  Optimal parser
1051
*********************************/
1052
1053
#if 0 /* debug */
1054
1055
static void
1056
listStats(const U32* table, int lastEltID)
1057
{
1058
    int const nbElts = lastEltID + 1;
1059
    int enb;
1060
    for (enb=0; enb < nbElts; enb++) {
1061
        (void)table;
1062
        /* RAWLOG(2, "%3i:%3i,  ", enb, table[enb]); */
1063
        RAWLOG(2, "%4i,", table[enb]);
1064
    }
1065
    RAWLOG(2, " \n");
1066
}
1067
1068
#endif
1069
1070
572M
#define LIT_PRICE(_p) (int)ZSTD_rawLiteralsCost(_p, 1, optStatePtr, optLevel)
1071
1.86G
#define LL_PRICE(_l) (int)ZSTD_litLengthPrice(_l, optStatePtr, optLevel)
1072
635M
#define LL_INCPRICE(_l) (LL_PRICE(_l) - LL_PRICE(_l-1))
1073
1074
FORCE_INLINE_TEMPLATE
1075
ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
1076
size_t
1077
ZSTD_compressBlock_opt_generic(ZSTD_MatchState_t* ms,
1078
                               SeqStore_t* seqStore,
1079
                               U32 rep[ZSTD_REP_NUM],
1080
                         const void* src, size_t srcSize,
1081
                         const int optLevel,
1082
                         const ZSTD_dictMode_e dictMode)
1083
586k
{
1084
586k
    optState_t* const optStatePtr = &ms->opt;
1085
586k
    const BYTE* const istart = (const BYTE*)src;
1086
586k
    const BYTE* ip = istart;
1087
586k
    const BYTE* anchor = istart;
1088
586k
    const BYTE* const iend = istart + srcSize;
1089
586k
    const BYTE* const ilimit = iend - 8;
1090
586k
    const BYTE* const base = ms->window.base;
1091
586k
    const BYTE* const prefixStart = base + ms->window.dictLimit;
1092
586k
    const ZSTD_compressionParameters* const cParams = &ms->cParams;
1093
1094
586k
    ZSTD_getAllMatchesFn getAllMatches = ZSTD_selectBtGetAllMatches(ms, dictMode);
1095
1096
586k
    U32 const sufficient_len = MIN(cParams->targetLength, ZSTD_OPT_NUM -1);
1097
586k
    U32 const minMatch = (cParams->minMatch == 3) ? 3 : 4;
1098
586k
    U32 nextToUpdate3 = ms->nextToUpdate;
1099
1100
586k
    ZSTD_optimal_t* const opt = optStatePtr->priceTable;
1101
586k
    ZSTD_match_t* const matches = optStatePtr->matchTable;
1102
586k
    ZSTD_optimal_t lastStretch;
1103
586k
    ZSTD_optLdm_t optLdm;
1104
1105
586k
    ZSTD_memset(&lastStretch, 0, sizeof(ZSTD_optimal_t));
1106
1107
586k
    optLdm.seqStore = ms->ldmSeqStore ? *ms->ldmSeqStore : kNullRawSeqStore;
1108
586k
    optLdm.endPosInBlock = optLdm.startPosInBlock = optLdm.offset = 0;
1109
586k
    ZSTD_opt_getNextMatchAndUpdateSeqStore(&optLdm, (U32)(ip-istart), (U32)(iend-ip));
1110
1111
    /* init */
1112
586k
    DEBUGLOG(5, "ZSTD_compressBlock_opt_generic: current=%u, prefix=%u, nextToUpdate=%u",
1113
586k
                (U32)(ip - base), ms->window.dictLimit, ms->nextToUpdate);
1114
586k
    assert(optLevel <= 2);
1115
586k
    ZSTD_rescaleFreqs(optStatePtr, (const BYTE*)src, srcSize, optLevel);
1116
586k
    ip += (ip==prefixStart);
1117
1118
    /* Match Loop */
1119
405M
    while (ip < ilimit) {
1120
404M
        U32 cur, last_pos = 0;
1121
1122
        /* find first match */
1123
404M
        {   U32 const litlen = (U32)(ip - anchor);
1124
404M
            U32 const ll0 = !litlen;
1125
404M
            U32 nbMatches = getAllMatches(matches, ms, &nextToUpdate3, ip, iend, rep, ll0, minMatch);
1126
404M
            ZSTD_optLdm_processMatchCandidate(&optLdm, matches, &nbMatches,
1127
404M
                                              (U32)(ip-istart), (U32)(iend-ip),
1128
404M
                                              minMatch);
1129
404M
            if (!nbMatches) {
1130
374M
                DEBUGLOG(8, "no match found at cPos %u", (unsigned)(ip-istart));
1131
374M
                ip++;
1132
374M
                continue;
1133
374M
            }
1134
1135
            /* Match found: let's store this solution, and eventually find more candidates.
1136
             * During this forward pass, @opt is used to store stretches,
1137
             * defined as "a match followed by N literals".
1138
             * Note how this is different from a Sequence, which is "N literals followed by a match".
1139
             * Storing stretches allows us to store different match predecessors
1140
             * for each literal position part of a literals run. */
1141
1142
            /* initialize opt[0] */
1143
29.9M
            opt[0].mlen = 0;  /* there are only literals so far */
1144
29.9M
            opt[0].litlen = litlen;
1145
            /* No need to include the actual price of the literals before the first match
1146
             * because it is static for the duration of the forward pass, and is included
1147
             * in every subsequent price. But, we include the literal length because
1148
             * the cost variation of litlen depends on the value of litlen.
1149
             */
1150
29.9M
            opt[0].price = LL_PRICE(litlen);
1151
29.9M
            ZSTD_STATIC_ASSERT(sizeof(opt[0].rep[0]) == sizeof(rep[0]));
1152
29.9M
            ZSTD_memcpy(&opt[0].rep, rep, sizeof(opt[0].rep));
1153
1154
            /* large match -> immediate encoding */
1155
29.9M
            {   U32 const maxML = matches[nbMatches-1].len;
1156
29.9M
                U32 const maxOffBase = matches[nbMatches-1].off;
1157
29.9M
                DEBUGLOG(6, "found %u matches of maxLength=%u and maxOffBase=%u at cPos=%u => start new series",
1158
29.9M
                            nbMatches, maxML, maxOffBase, (U32)(ip-prefixStart));
1159
1160
29.9M
                if (maxML > sufficient_len) {
1161
6.00M
                    lastStretch.litlen = 0;
1162
6.00M
                    lastStretch.mlen = maxML;
1163
6.00M
                    lastStretch.off = maxOffBase;
1164
6.00M
                    DEBUGLOG(6, "large match (%u>%u) => immediate encoding",
1165
6.00M
                                maxML, sufficient_len);
1166
6.00M
                    cur = 0;
1167
6.00M
                    last_pos = maxML;
1168
6.00M
                    goto _shortestPath;
1169
6.00M
            }   }
1170
1171
            /* set prices for first matches starting position == 0 */
1172
29.9M
            assert(opt[0].price >= 0);
1173
23.9M
            {   U32 pos;
1174
23.9M
                U32 matchNb;
1175
81.0M
                for (pos = 1; pos < minMatch; pos++) {
1176
57.1M
                    opt[pos].price = ZSTD_MAX_PRICE;
1177
57.1M
                    opt[pos].mlen = 0;
1178
57.1M
                    opt[pos].litlen = litlen + pos;
1179
57.1M
                }
1180
55.8M
                for (matchNb = 0; matchNb < nbMatches; matchNb++) {
1181
31.9M
                    U32 const offBase = matches[matchNb].off;
1182
31.9M
                    U32 const end = matches[matchNb].len;
1183
168M
                    for ( ; pos <= end ; pos++ ) {
1184
137M
                        int const matchPrice = (int)ZSTD_getMatchPrice(offBase, pos, optStatePtr, optLevel);
1185
137M
                        int const sequencePrice = opt[0].price + matchPrice;
1186
137M
                        DEBUGLOG(7, "rPos:%u => set initial price : %.2f",
1187
137M
                                    pos, ZSTD_fCost(sequencePrice));
1188
137M
                        opt[pos].mlen = pos;
1189
137M
                        opt[pos].off = offBase;
1190
137M
                        opt[pos].litlen = 0; /* end of match */
1191
137M
                        opt[pos].price = sequencePrice + LL_PRICE(0);
1192
137M
                    }
1193
31.9M
                }
1194
23.9M
                last_pos = pos-1;
1195
23.9M
                opt[pos].price = ZSTD_MAX_PRICE;
1196
23.9M
            }
1197
23.9M
        }
1198
1199
        /* check further positions */
1200
505M
        for (cur = 1; cur <= last_pos; cur++) {
1201
505M
            const BYTE* const inr = ip + cur;
1202
505M
            assert(cur <= ZSTD_OPT_NUM);
1203
505M
            DEBUGLOG(7, "cPos:%i==rPos:%u", (int)(inr-istart), cur);
1204
1205
            /* Fix current position with one literal if cheaper */
1206
505M
            {   U32 const litlen = opt[cur-1].litlen + 1;
1207
505M
                int const price = opt[cur-1].price
1208
505M
                                + LIT_PRICE(ip+cur-1)
1209
505M
                                + LL_INCPRICE(litlen);
1210
505M
                assert(price < 1000000000); /* overflow check */
1211
505M
                if (price <= opt[cur].price) {
1212
160M
                    ZSTD_optimal_t const prevMatch = opt[cur];
1213
160M
                    DEBUGLOG(7, "cPos:%i==rPos:%u : better price (%.2f<=%.2f) using literal (ll==%u) (hist:%u,%u,%u)",
1214
160M
                                (int)(inr-istart), cur, ZSTD_fCost(price), ZSTD_fCost(opt[cur].price), litlen,
1215
160M
                                opt[cur-1].rep[0], opt[cur-1].rep[1], opt[cur-1].rep[2]);
1216
160M
                    opt[cur] = opt[cur-1];
1217
160M
                    opt[cur].litlen = litlen;
1218
160M
                    opt[cur].price = price;
1219
160M
                    if ( (optLevel >= 1) /* additional check only for higher modes */
1220
114M
                      && (prevMatch.litlen == 0) /* replace a match */
1221
63.3M
                      && (LL_INCPRICE(1) < 0) /* ll1 is cheaper than ll0 */
1222
33.5M
                      && LIKELY(ip + cur < iend)
1223
160M
                    ) {
1224
                        /* check next position, in case it would be cheaper */
1225
33.5M
                        int with1literal = prevMatch.price + LIT_PRICE(ip+cur) + LL_INCPRICE(1);
1226
33.5M
                        int withMoreLiterals = price + LIT_PRICE(ip+cur) + LL_INCPRICE(litlen+1);
1227
33.5M
                        DEBUGLOG(7, "then at next rPos %u : match+1lit %.2f vs %ulits %.2f",
1228
33.5M
                                cur+1, ZSTD_fCost(with1literal), litlen+1, ZSTD_fCost(withMoreLiterals));
1229
33.5M
                        if ( (with1literal < withMoreLiterals)
1230
9.32M
                          && (with1literal < opt[cur+1].price) ) {
1231
                            /* update offset history - before it disappears */
1232
4.54M
                            U32 const prev = cur - prevMatch.mlen;
1233
4.54M
                            Repcodes_t const newReps = ZSTD_newRep(opt[prev].rep, prevMatch.off, opt[prev].litlen==0);
1234
4.54M
                            assert(cur >= prevMatch.mlen);
1235
4.54M
                            DEBUGLOG(7, "==> match+1lit is cheaper (%.2f < %.2f) (hist:%u,%u,%u) !",
1236
4.54M
                                        ZSTD_fCost(with1literal), ZSTD_fCost(withMoreLiterals),
1237
4.54M
                                        newReps.rep[0], newReps.rep[1], newReps.rep[2] );
1238
4.54M
                            opt[cur+1] = prevMatch;  /* mlen & offbase */
1239
4.54M
                            ZSTD_memcpy(opt[cur+1].rep, &newReps, sizeof(Repcodes_t));
1240
4.54M
                            opt[cur+1].litlen = 1;
1241
4.54M
                            opt[cur+1].price = with1literal;
1242
4.54M
                            if (last_pos < cur+1) last_pos = cur+1;
1243
4.54M
                        }
1244
33.5M
                    }
1245
344M
                } else {
1246
344M
                    DEBUGLOG(7, "cPos:%i==rPos:%u : literal would cost more (%.2f>%.2f)",
1247
344M
                                (int)(inr-istart), cur, ZSTD_fCost(price), ZSTD_fCost(opt[cur].price));
1248
344M
                }
1249
505M
            }
1250
1251
            /* Offset history is not updated during match comparison.
1252
             * Do it here, now that the match is selected and confirmed.
1253
             */
1254
505M
            ZSTD_STATIC_ASSERT(sizeof(opt[cur].rep) == sizeof(Repcodes_t));
1255
505M
            assert(cur >= opt[cur].mlen);
1256
505M
            if (opt[cur].litlen == 0) {
1257
                /* just finished a match => alter offset history */
1258
340M
                U32 const prev = cur - opt[cur].mlen;
1259
340M
                Repcodes_t const newReps = ZSTD_newRep(opt[prev].rep, opt[cur].off, opt[prev].litlen==0);
1260
340M
                ZSTD_memcpy(opt[cur].rep, &newReps, sizeof(Repcodes_t));
1261
340M
            }
1262
1263
            /* last match must start at a minimum distance of 8 from oend */
1264
505M
            if (inr > ilimit) continue;
1265
1266
505M
            if (cur == last_pos) break;
1267
1268
482M
            if ( (optLevel==0) /*static_test*/
1269
122M
              && (opt[cur+1].price <= opt[cur].price + (BITCOST_MULTIPLIER/2)) ) {
1270
57.4M
                DEBUGLOG(7, "skip current position : next rPos(%u) price is cheaper", cur+1);
1271
57.4M
                continue;  /* skip unpromising positions; about ~+6% speed, -0.01 ratio */
1272
57.4M
            }
1273
1274
482M
            assert(opt[cur].price >= 0);
1275
424M
            {   U32 const ll0 = (opt[cur].litlen == 0);
1276
424M
                int const previousPrice = opt[cur].price;
1277
424M
                int const basePrice = previousPrice + LL_PRICE(0);
1278
424M
                U32 nbMatches = getAllMatches(matches, ms, &nextToUpdate3, inr, iend, opt[cur].rep, ll0, minMatch);
1279
424M
                U32 matchNb;
1280
1281
424M
                ZSTD_optLdm_processMatchCandidate(&optLdm, matches, &nbMatches,
1282
424M
                                                  (U32)(inr-istart), (U32)(iend-inr),
1283
424M
                                                  minMatch);
1284
1285
424M
                if (!nbMatches) {
1286
100M
                    DEBUGLOG(7, "rPos:%u : no match found", cur);
1287
100M
                    continue;
1288
100M
                }
1289
1290
324M
                {   U32 const longestML = matches[nbMatches-1].len;
1291
324M
                    DEBUGLOG(7, "cPos:%i==rPos:%u, found %u matches, of longest ML=%u",
1292
324M
                                (int)(inr-istart), cur, nbMatches, longestML);
1293
1294
324M
                    if ( (longestML > sufficient_len)
1295
323M
                      || (cur + longestML >= ZSTD_OPT_NUM)
1296
323M
                      || (ip + cur + longestML >= iend) ) {
1297
800k
                        lastStretch.mlen = longestML;
1298
800k
                        lastStretch.off = matches[nbMatches-1].off;
1299
800k
                        lastStretch.litlen = 0;
1300
800k
                        last_pos = cur + longestML;
1301
800k
                        goto _shortestPath;
1302
800k
                }   }
1303
1304
                /* set prices using matches found at position == cur */
1305
822M
                for (matchNb = 0; matchNb < nbMatches; matchNb++) {
1306
499M
                    U32 const offset = matches[matchNb].off;
1307
499M
                    U32 const lastML = matches[matchNb].len;
1308
499M
                    U32 const startML = (matchNb>0) ? matches[matchNb-1].len+1 : minMatch;
1309
499M
                    U32 mlen;
1310
1311
499M
                    DEBUGLOG(7, "testing match %u => offBase=%4u, mlen=%2u, llen=%2u",
1312
499M
                                matchNb, matches[matchNb].off, lastML, opt[cur].litlen);
1313
1314
5.15G
                    for (mlen = lastML; mlen >= startML; mlen--) {  /* scan downward */
1315
4.70G
                        U32 const pos = cur + mlen;
1316
4.70G
                        int const price = basePrice + (int)ZSTD_getMatchPrice(offset, mlen, optStatePtr, optLevel);
1317
1318
4.70G
                        if ((pos > last_pos) || (price < opt[pos].price)) {
1319
516M
                            DEBUGLOG(7, "rPos:%u (ml=%2u) => new better price (%.2f<%.2f)",
1320
516M
                                        pos, mlen, ZSTD_fCost(price), ZSTD_fCost(opt[pos].price));
1321
840M
                            while (last_pos < pos) {
1322
                                /* fill empty positions, for future comparisons */
1323
324M
                                last_pos++;
1324
324M
                                opt[last_pos].price = ZSTD_MAX_PRICE;
1325
324M
                                opt[last_pos].litlen = !0;  /* just needs to be != 0, to mean "not an end of match" */
1326
324M
                            }
1327
516M
                            opt[pos].mlen = mlen;
1328
516M
                            opt[pos].off = offset;
1329
516M
                            opt[pos].litlen = 0;
1330
516M
                            opt[pos].price = price;
1331
4.18G
                        } else {
1332
4.18G
                            DEBUGLOG(7, "rPos:%u (ml=%2u) => new price is worse (%.2f>=%.2f)",
1333
4.18G
                                        pos, mlen, ZSTD_fCost(price), ZSTD_fCost(opt[pos].price));
1334
4.18G
                            if (optLevel==0) break;  /* early update abort; gets ~+10% speed for about -0.01 ratio loss */
1335
4.18G
                        }
1336
4.70G
            }   }   }
1337
323M
            opt[last_pos+1].price = ZSTD_MAX_PRICE;
1338
323M
        }  /* for (cur = 1; cur <= last_pos; cur++) */
1339
1340
23.2M
        lastStretch = opt[last_pos];
1341
23.2M
        assert(cur >= lastStretch.mlen);
1342
23.2M
        cur = last_pos - lastStretch.mlen;
1343
1344
29.9M
_shortestPath:   /* cur, last_pos, best_mlen, best_off have to be set */
1345
29.9M
        assert(opt[0].mlen == 0);
1346
29.9M
        assert(last_pos >= lastStretch.mlen);
1347
29.9M
        assert(cur == last_pos - lastStretch.mlen);
1348
1349
29.9M
        if (lastStretch.mlen==0) {
1350
            /* no solution : all matches have been converted into literals */
1351
1.94M
            assert(lastStretch.litlen == (ip - anchor) + last_pos);
1352
1.94M
            ip += last_pos;
1353
1.94M
            continue;
1354
1.94M
        }
1355
29.9M
        assert(lastStretch.off > 0);
1356
1357
        /* Update offset history */
1358
27.9M
        if (lastStretch.litlen == 0) {
1359
            /* finishing on a match : update offset history */
1360
24.3M
            Repcodes_t const reps = ZSTD_newRep(opt[cur].rep, lastStretch.off, opt[cur].litlen==0);
1361
24.3M
            ZSTD_memcpy(rep, &reps, sizeof(Repcodes_t));
1362
24.3M
        } else {
1363
3.58M
            ZSTD_memcpy(rep, lastStretch.rep, sizeof(Repcodes_t));
1364
3.58M
            assert(cur >= lastStretch.litlen);
1365
3.58M
            cur -= lastStretch.litlen;
1366
3.58M
        }
1367
1368
        /* Let's write the shortest path solution.
1369
         * It is stored in @opt in reverse order,
1370
         * starting from @storeEnd (==cur+2),
1371
         * effectively partially @opt overwriting.
1372
         * Content is changed too:
1373
         * - So far, @opt stored stretches, aka a match followed by literals
1374
         * - Now, it will store sequences, aka literals followed by a match
1375
         */
1376
27.9M
        {   U32 const storeEnd = cur + 2;
1377
27.9M
            U32 storeStart = storeEnd;
1378
27.9M
            U32 stretchPos = cur;
1379
1380
27.9M
            DEBUGLOG(6, "start reverse traversal (last_pos:%u, cur:%u)",
1381
27.9M
                        last_pos, cur); (void)last_pos;
1382
27.9M
            assert(storeEnd < ZSTD_OPT_SIZE);
1383
27.9M
            DEBUGLOG(6, "last stretch copied into pos=%u (llen=%u,mlen=%u,ofc=%u)",
1384
27.9M
                        storeEnd, lastStretch.litlen, lastStretch.mlen, lastStretch.off);
1385
27.9M
            opt[storeEnd] = lastStretch;  /* note: litlen will be fixed */
1386
27.9M
            storeStart = storeEnd;
1387
64.7M
            while (1) {
1388
64.7M
                ZSTD_optimal_t nextStretch = opt[stretchPos];
1389
64.7M
                opt[storeStart].litlen = nextStretch.litlen;
1390
64.7M
                DEBUGLOG(6, "selected sequence (llen=%u,mlen=%u,ofc=%u)",
1391
64.7M
                            opt[storeStart].litlen, opt[storeStart].mlen, opt[storeStart].off);
1392
64.7M
                if (nextStretch.mlen == 0) {
1393
                    /* reaching beginning of segment */
1394
27.9M
                    break;
1395
27.9M
                }
1396
36.8M
                storeStart--;
1397
36.8M
                opt[storeStart] = nextStretch; /* note: litlen will be fixed */
1398
36.8M
                assert(nextStretch.litlen + nextStretch.mlen <= stretchPos);
1399
36.8M
                stretchPos -= nextStretch.litlen + nextStretch.mlen;
1400
36.8M
            }
1401
1402
            /* save sequences */
1403
27.9M
            DEBUGLOG(6, "sending selected sequences into seqStore");
1404
27.9M
            {   U32 storePos;
1405
92.7M
                for (storePos=storeStart; storePos <= storeEnd; storePos++) {
1406
64.7M
                    U32 const llen = opt[storePos].litlen;
1407
64.7M
                    U32 const mlen = opt[storePos].mlen;
1408
64.7M
                    U32 const offBase = opt[storePos].off;
1409
64.7M
                    U32 const advance = llen + mlen;
1410
64.7M
                    DEBUGLOG(6, "considering seq starting at %i, llen=%u, mlen=%u",
1411
64.7M
                                (int)(anchor - istart), (unsigned)llen, (unsigned)mlen);
1412
1413
64.7M
                    if (mlen==0) {  /* only literals => must be last "sequence", actually starting a new stream of sequences */
1414
0
                        assert(storePos == storeEnd);   /* must be last sequence */
1415
0
                        ip = anchor + llen;     /* last "sequence" is a bunch of literals => don't progress anchor */
1416
0
                        continue;   /* will finish */
1417
0
                    }
1418
1419
64.7M
                    assert(anchor + llen <= iend);
1420
64.7M
                    ZSTD_updateStats(optStatePtr, llen, anchor, offBase, mlen);
1421
64.7M
                    ZSTD_storeSeq(seqStore, llen, anchor, iend, offBase, mlen);
1422
64.7M
                    anchor += advance;
1423
64.7M
                    ip = anchor;
1424
64.7M
            }   }
1425
27.9M
            DEBUGLOG(7, "new offset history : %u, %u, %u", rep[0], rep[1], rep[2]);
1426
1427
            /* update all costs */
1428
27.9M
            ZSTD_setBasePrices(optStatePtr, optLevel);
1429
27.9M
        }
1430
27.9M
    }   /* while (ip < ilimit) */
1431
1432
    /* Return the last literals size */
1433
574k
    return (size_t)(iend - anchor);
1434
586k
}
1435
#endif /* build exclusions */
1436
1437
#ifndef ZSTD_EXCLUDE_BTOPT_BLOCK_COMPRESSOR
1438
static size_t ZSTD_compressBlock_opt0(
1439
        ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
1440
        const void* src, size_t srcSize, const ZSTD_dictMode_e dictMode)
1441
160k
{
1442
160k
    return ZSTD_compressBlock_opt_generic(ms, seqStore, rep, src, srcSize, 0 /* optLevel */, dictMode);
1443
160k
}
1444
#endif
1445
1446
#ifndef ZSTD_EXCLUDE_BTULTRA_BLOCK_COMPRESSOR
1447
static size_t ZSTD_compressBlock_opt2(
1448
        ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
1449
        const void* src, size_t srcSize, const ZSTD_dictMode_e dictMode)
1450
426k
{
1451
426k
    return ZSTD_compressBlock_opt_generic(ms, seqStore, rep, src, srcSize, 2 /* optLevel */, dictMode);
1452
426k
}
1453
#endif
1454
1455
#ifndef ZSTD_EXCLUDE_BTOPT_BLOCK_COMPRESSOR
1456
size_t ZSTD_compressBlock_btopt(
1457
        ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
1458
        const void* src, size_t srcSize)
1459
127k
{
1460
127k
    DEBUGLOG(5, "ZSTD_compressBlock_btopt");
1461
127k
    return ZSTD_compressBlock_opt0(ms, seqStore, rep, src, srcSize, ZSTD_noDict);
1462
127k
}
1463
#endif
1464
1465
1466
1467
1468
#ifndef ZSTD_EXCLUDE_BTULTRA_BLOCK_COMPRESSOR
1469
/* ZSTD_initStats_ultra():
1470
 * make a first compression pass, just to seed stats with more accurate starting values.
1471
 * only works on first block, with no dictionary and no ldm.
1472
 * this function cannot error out, its narrow contract must be respected.
1473
 */
1474
static
1475
ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
1476
void ZSTD_initStats_ultra(ZSTD_MatchState_t* ms,
1477
                          SeqStore_t* seqStore,
1478
                          U32 rep[ZSTD_REP_NUM],
1479
                    const void* src, size_t srcSize)
1480
21.3k
{
1481
21.3k
    U32 tmpRep[ZSTD_REP_NUM];  /* updated rep codes will sink here */
1482
21.3k
    ZSTD_memcpy(tmpRep, rep, sizeof(tmpRep));
1483
1484
21.3k
    DEBUGLOG(4, "ZSTD_initStats_ultra (srcSize=%zu)", srcSize);
1485
21.3k
    assert(ms->opt.litLengthSum == 0);    /* first block */
1486
21.3k
    assert(seqStore->sequences == seqStore->sequencesStart);   /* no ldm */
1487
21.3k
    assert(ms->window.dictLimit == ms->window.lowLimit);   /* no dictionary */
1488
21.3k
    assert(ms->window.dictLimit - ms->nextToUpdate <= 1);  /* no prefix (note: intentional overflow, defined as 2-complement) */
1489
1490
21.3k
    ZSTD_compressBlock_opt2(ms, seqStore, tmpRep, src, srcSize, ZSTD_noDict);   /* generate stats into ms->opt*/
1491
1492
    /* invalidate first scan from history, only keep entropy stats */
1493
21.3k
    ZSTD_resetSeqStore(seqStore);
1494
21.3k
    ms->window.base -= srcSize;
1495
21.3k
    ms->window.dictLimit += (U32)srcSize;
1496
21.3k
    ms->window.lowLimit = ms->window.dictLimit;
1497
21.3k
    ms->nextToUpdate = ms->window.dictLimit;
1498
1499
21.3k
}
1500
1501
size_t ZSTD_compressBlock_btultra(
1502
        ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
1503
        const void* src, size_t srcSize)
1504
151k
{
1505
151k
    DEBUGLOG(5, "ZSTD_compressBlock_btultra (srcSize=%zu)", srcSize);
1506
151k
    return ZSTD_compressBlock_opt2(ms, seqStore, rep, src, srcSize, ZSTD_noDict);
1507
151k
}
1508
1509
size_t ZSTD_compressBlock_btultra2(
1510
        ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
1511
        const void* src, size_t srcSize)
1512
205k
{
1513
205k
    U32 const curr = (U32)((const BYTE*)src - ms->window.base);
1514
205k
    DEBUGLOG(5, "ZSTD_compressBlock_btultra2 (srcSize=%zu)", srcSize);
1515
1516
    /* 2-passes strategy:
1517
     * this strategy makes a first pass over first block to collect statistics
1518
     * in order to seed next round's statistics with it.
1519
     * After 1st pass, function forgets history, and starts a new block.
1520
     * Consequently, this can only work if no data has been previously loaded in tables,
1521
     * aka, no dictionary, no prefix, no ldm preprocessing.
1522
     * The compression ratio gain is generally small (~0.5% on first block),
1523
     * the cost is 2x cpu time on first block. */
1524
205k
    assert(srcSize <= ZSTD_BLOCKSIZE_MAX);
1525
205k
    if ( (ms->opt.litLengthSum==0)   /* first block */
1526
26.0k
      && (seqStore->sequences == seqStore->sequencesStart)  /* no ldm */
1527
26.0k
      && (ms->window.dictLimit == ms->window.lowLimit)   /* no dictionary */
1528
26.0k
      && (curr == ms->window.dictLimit)    /* start of frame, nothing already loaded nor skipped */
1529
21.8k
      && (srcSize > ZSTD_PREDEF_THRESHOLD) /* input large enough to not employ default stats */
1530
205k
      ) {
1531
21.3k
        ZSTD_initStats_ultra(ms, seqStore, rep, src, srcSize);
1532
21.3k
    }
1533
1534
205k
    return ZSTD_compressBlock_opt2(ms, seqStore, rep, src, srcSize, ZSTD_noDict);
1535
205k
}
1536
#endif
1537
1538
#ifndef ZSTD_EXCLUDE_BTOPT_BLOCK_COMPRESSOR
1539
size_t ZSTD_compressBlock_btopt_dictMatchState(
1540
        ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
1541
        const void* src, size_t srcSize)
1542
9.04k
{
1543
9.04k
    return ZSTD_compressBlock_opt0(ms, seqStore, rep, src, srcSize, ZSTD_dictMatchState);
1544
9.04k
}
1545
1546
size_t ZSTD_compressBlock_btopt_extDict(
1547
        ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
1548
        const void* src, size_t srcSize)
1549
23.7k
{
1550
23.7k
    return ZSTD_compressBlock_opt0(ms, seqStore, rep, src, srcSize, ZSTD_extDict);
1551
23.7k
}
1552
#endif
1553
1554
#ifndef ZSTD_EXCLUDE_BTULTRA_BLOCK_COMPRESSOR
1555
size_t ZSTD_compressBlock_btultra_dictMatchState(
1556
        ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
1557
        const void* src, size_t srcSize)
1558
8.48k
{
1559
8.48k
    return ZSTD_compressBlock_opt2(ms, seqStore, rep, src, srcSize, ZSTD_dictMatchState);
1560
8.48k
}
1561
1562
size_t ZSTD_compressBlock_btultra_extDict(
1563
        ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
1564
        const void* src, size_t srcSize)
1565
39.6k
{
1566
39.6k
    return ZSTD_compressBlock_opt2(ms, seqStore, rep, src, srcSize, ZSTD_extDict);
1567
39.6k
}
1568
#endif
1569
1570
/* note : no btultra2 variant for extDict nor dictMatchState,
1571
 * because btultra2 is not meant to work with dictionaries
1572
 * and is only specific for the first block (no prefix) */