Coverage Report

Created: 2026-12-01 06:39

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