Coverage Report

Created: 2025-08-28 07:58

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