Coverage Report

Created: 2025-07-18 06:59

/src/zstd/lib/compress/zstd_ldm.c
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_ldm.h"
12
13
#include "../common/debug.h"
14
#include "../common/xxhash.h"
15
#include "zstd_fast.h"          /* ZSTD_fillHashTable() */
16
#include "zstd_double_fast.h"   /* ZSTD_fillDoubleHashTable() */
17
#include "zstd_ldm_geartab.h"
18
19
#define LDM_BUCKET_SIZE_LOG 4
20
0
#define LDM_MIN_MATCH_LENGTH 64
21
#define LDM_HASH_RLOG 7
22
23
typedef struct {
24
    U64 rolling;
25
    U64 stopMask;
26
} ldmRollingHashState_t;
27
28
/** ZSTD_ldm_gear_init():
29
 *
30
 * Initializes the rolling hash state such that it will honor the
31
 * settings in params. */
32
static void ZSTD_ldm_gear_init(ldmRollingHashState_t* state, ldmParams_t const* params)
33
473k
{
34
473k
    unsigned maxBitsInMask = MIN(params->minMatchLength, 64);
35
473k
    unsigned hashRateLog = params->hashRateLog;
36
37
473k
    state->rolling = ~(U32)0;
38
39
    /* The choice of the splitting criterion is subject to two conditions:
40
     *   1. it has to trigger on average every 2^(hashRateLog) bytes;
41
     *   2. ideally, it has to depend on a window of minMatchLength bytes.
42
     *
43
     * In the gear hash algorithm, bit n depends on the last n bytes;
44
     * so in order to obtain a good quality splitting criterion it is
45
     * preferable to use bits with high weight.
46
     *
47
     * To match condition 1 we use a mask with hashRateLog bits set
48
     * and, because of the previous remark, we make sure these bits
49
     * have the highest possible weight while still respecting
50
     * condition 2.
51
     */
52
473k
    if (hashRateLog > 0 && hashRateLog <= maxBitsInMask) {
53
373k
        state->stopMask = (((U64)1 << hashRateLog) - 1) << (maxBitsInMask - hashRateLog);
54
373k
    } else {
55
        /* In this degenerate case we simply honor the hash rate. */
56
100k
        state->stopMask = ((U64)1 << hashRateLog) - 1;
57
100k
    }
58
473k
}
59
60
/** ZSTD_ldm_gear_reset()
61
 * Feeds [data, data + minMatchLength) into the hash without registering any
62
 * splits. This effectively resets the hash state. This is used when skipping
63
 * over data, either at the beginning of a block, or skipping sections.
64
 */
65
static void ZSTD_ldm_gear_reset(ldmRollingHashState_t* state,
66
                                BYTE const* data, size_t minMatchLength)
67
860k
{
68
860k
    U64 hash = state->rolling;
69
860k
    size_t n = 0;
70
71
109M
#define GEAR_ITER_ONCE() do {                                  \
72
109M
        hash = (hash << 1) + ZSTD_ldm_gearTab[data[n] & 0xff]; \
73
109M
        n += 1;                                                \
74
109M
    } while (0)
75
28.2M
    while (n + 3 < minMatchLength) {
76
27.3M
        GEAR_ITER_ONCE();
77
27.3M
        GEAR_ITER_ONCE();
78
27.3M
        GEAR_ITER_ONCE();
79
27.3M
        GEAR_ITER_ONCE();
80
27.3M
    }
81
1.27M
    while (n < minMatchLength) {
82
411k
        GEAR_ITER_ONCE();
83
411k
    }
84
860k
#undef GEAR_ITER_ONCE
85
860k
}
86
87
/** ZSTD_ldm_gear_feed():
88
 *
89
 * Registers in the splits array all the split points found in the first
90
 * size bytes following the data pointer. This function terminates when
91
 * either all the data has been processed or LDM_BATCH_SIZE splits are
92
 * present in the splits array.
93
 *
94
 * Precondition: The splits array must not be full.
95
 * Returns: The number of bytes processed. */
96
static size_t ZSTD_ldm_gear_feed(ldmRollingHashState_t* state,
97
                                 BYTE const* data, size_t size,
98
                                 size_t* splits, unsigned* numSplits)
99
2.51M
{
100
2.51M
    size_t n;
101
2.51M
    U64 hash, mask;
102
103
2.51M
    hash = state->rolling;
104
2.51M
    mask = state->stopMask;
105
2.51M
    n = 0;
106
107
980M
#define GEAR_ITER_ONCE() do { \
108
980M
        hash = (hash << 1) + ZSTD_ldm_gearTab[data[n] & 0xff]; \
109
980M
        n += 1; \
110
980M
        if (UNLIKELY((hash & mask) == 0)) { \
111
142M
            splits[*numSplits] = n; \
112
142M
            *numSplits += 1; \
113
142M
            if (*numSplits == LDM_BATCH_SIZE) \
114
142M
                goto done; \
115
142M
        } \
116
980M
    } while (0)
117
118
245M
    while (n + 3 < size) {
119
245M
        GEAR_ITER_ONCE();
120
245M
        GEAR_ITER_ONCE();
121
244M
        GEAR_ITER_ONCE();
122
244M
        GEAR_ITER_ONCE();
123
244M
    }
124
980k
    while (n < size) {
125
534k
        GEAR_ITER_ONCE();
126
534k
    }
127
128
445k
#undef GEAR_ITER_ONCE
129
130
2.51M
done:
131
2.51M
    state->rolling = hash;
132
2.51M
    return n;
133
446k
}
134
135
void ZSTD_ldm_adjustParameters(ldmParams_t* params,
136
                        const ZSTD_compressionParameters* cParams)
137
126k
{
138
126k
    params->windowLog = cParams->windowLog;
139
126k
    ZSTD_STATIC_ASSERT(LDM_BUCKET_SIZE_LOG <= ZSTD_LDM_BUCKETSIZELOG_MAX);
140
126k
    DEBUGLOG(4, "ZSTD_ldm_adjustParameters");
141
126k
    if (params->hashRateLog == 0) {
142
44.4k
        if (params->hashLog > 0) {
143
            /* if params->hashLog is set, derive hashRateLog from it */
144
44.4k
            assert(params->hashLog <= ZSTD_HASHLOG_MAX);
145
44.4k
            if (params->windowLog > params->hashLog) {
146
29.5k
                params->hashRateLog = params->windowLog - params->hashLog;
147
29.5k
            }
148
44.4k
        } else {
149
0
            assert(1 <= (int)cParams->strategy && (int)cParams->strategy <= 9);
150
            /* mapping from [fast, rate7] to [btultra2, rate4] */
151
0
            params->hashRateLog = 7 - (cParams->strategy/3);
152
0
        }
153
44.4k
    }
154
126k
    if (params->hashLog == 0) {
155
0
        params->hashLog = BOUNDED(ZSTD_HASHLOG_MIN, params->windowLog - params->hashRateLog, ZSTD_HASHLOG_MAX);
156
0
    }
157
126k
    if (params->minMatchLength == 0) {
158
0
        params->minMatchLength = LDM_MIN_MATCH_LENGTH;
159
0
        if (cParams->strategy >= ZSTD_btultra)
160
0
            params->minMatchLength /= 2;
161
0
    }
162
126k
    if (params->bucketSizeLog==0) {
163
44.8k
        assert(1 <= (int)cParams->strategy && (int)cParams->strategy <= 9);
164
44.8k
        params->bucketSizeLog = BOUNDED(LDM_BUCKET_SIZE_LOG, (U32)cParams->strategy, ZSTD_LDM_BUCKETSIZELOG_MAX);
165
44.8k
    }
166
126k
    params->bucketSizeLog = MIN(params->bucketSizeLog, params->hashLog);
167
126k
}
168
169
size_t ZSTD_ldm_getTableSize(ldmParams_t params)
170
3.78M
{
171
3.78M
    size_t const ldmHSize = ((size_t)1) << params.hashLog;
172
3.78M
    size_t const ldmBucketSizeLog = MIN(params.bucketSizeLog, params.hashLog);
173
3.78M
    size_t const ldmBucketSize = ((size_t)1) << (params.hashLog - ldmBucketSizeLog);
174
3.78M
    size_t const totalSize = ZSTD_cwksp_alloc_size(ldmBucketSize)
175
3.78M
                           + ZSTD_cwksp_alloc_size(ldmHSize * sizeof(ldmEntry_t));
176
3.78M
    return params.enableLdm == ZSTD_ps_enable ? totalSize : 0;
177
3.78M
}
178
179
size_t ZSTD_ldm_getMaxNbSeq(ldmParams_t params, size_t maxChunkSize)
180
7.57M
{
181
7.57M
    return params.enableLdm == ZSTD_ps_enable ? (maxChunkSize / params.minMatchLength) : 0;
182
7.57M
}
183
184
/** ZSTD_ldm_getBucket() :
185
 *  Returns a pointer to the start of the bucket associated with hash. */
186
static ldmEntry_t* ZSTD_ldm_getBucket(
187
        const ldmState_t* ldmState, size_t hash, U32 const bucketSizeLog)
188
276M
{
189
276M
    return ldmState->hashTable + (hash << bucketSizeLog);
190
276M
}
191
192
/** ZSTD_ldm_insertEntry() :
193
 *  Insert the entry with corresponding hash into the hash table */
194
static void ZSTD_ldm_insertEntry(ldmState_t* ldmState,
195
                                 size_t const hash, const ldmEntry_t entry,
196
                                 U32 const bucketSizeLog)
197
136M
{
198
136M
    BYTE* const pOffset = ldmState->bucketOffsets + hash;
199
136M
    unsigned const offset = *pOffset;
200
201
136M
    *(ZSTD_ldm_getBucket(ldmState, hash, bucketSizeLog) + offset) = entry;
202
136M
    *pOffset = (BYTE)((offset + 1) & ((1u << bucketSizeLog) - 1));
203
204
136M
}
205
206
/** ZSTD_ldm_countBackwardsMatch() :
207
 *  Returns the number of bytes that match backwards before pIn and pMatch.
208
 *
209
 *  We count only bytes where pMatch >= pBase and pIn >= pAnchor. */
210
static size_t ZSTD_ldm_countBackwardsMatch(
211
            const BYTE* pIn, const BYTE* pAnchor,
212
            const BYTE* pMatch, const BYTE* pMatchBase)
213
39.0M
{
214
39.0M
    size_t matchLength = 0;
215
92.3M
    while (pIn > pAnchor && pMatch > pMatchBase && pIn[-1] == pMatch[-1]) {
216
53.3M
        pIn--;
217
53.3M
        pMatch--;
218
53.3M
        matchLength++;
219
53.3M
    }
220
39.0M
    return matchLength;
221
39.0M
}
222
223
/** ZSTD_ldm_countBackwardsMatch_2segments() :
224
 *  Returns the number of bytes that match backwards from pMatch,
225
 *  even with the backwards match spanning 2 different segments.
226
 *
227
 *  On reaching `pMatchBase`, start counting from mEnd */
228
static size_t ZSTD_ldm_countBackwardsMatch_2segments(
229
                    const BYTE* pIn, const BYTE* pAnchor,
230
                    const BYTE* pMatch, const BYTE* pMatchBase,
231
                    const BYTE* pExtDictStart, const BYTE* pExtDictEnd)
232
1.48M
{
233
1.48M
    size_t matchLength = ZSTD_ldm_countBackwardsMatch(pIn, pAnchor, pMatch, pMatchBase);
234
1.48M
    if (pMatch - matchLength != pMatchBase || pMatchBase == pExtDictStart) {
235
        /* If backwards match is entirely in the extDict or prefix, immediately return */
236
1.48M
        return matchLength;
237
1.48M
    }
238
1.36k
    DEBUGLOG(7, "ZSTD_ldm_countBackwardsMatch_2segments: found 2-parts backwards match (length in prefix==%zu)", matchLength);
239
1.36k
    matchLength += ZSTD_ldm_countBackwardsMatch(pIn - matchLength, pAnchor, pExtDictEnd, pExtDictStart);
240
1.36k
    DEBUGLOG(7, "final backwards match length = %zu", matchLength);
241
1.36k
    return matchLength;
242
1.48M
}
243
244
/** ZSTD_ldm_fillFastTables() :
245
 *
246
 *  Fills the relevant tables for the ZSTD_fast and ZSTD_dfast strategies.
247
 *  This is similar to ZSTD_loadDictionaryContent.
248
 *
249
 *  The tables for the other strategies are filled within their
250
 *  block compressors. */
251
static size_t ZSTD_ldm_fillFastTables(ZSTD_MatchState_t* ms,
252
                                      void const* end)
253
7.98M
{
254
7.98M
    const BYTE* const iend = (const BYTE*)end;
255
256
7.98M
    switch(ms->cParams.strategy)
257
7.98M
    {
258
1.41M
    case ZSTD_fast:
259
1.41M
        ZSTD_fillHashTable(ms, iend, ZSTD_dtlm_fast, ZSTD_tfp_forCCtx);
260
1.41M
        break;
261
262
2.38M
    case ZSTD_dfast:
263
2.38M
#ifndef ZSTD_EXCLUDE_DFAST_BLOCK_COMPRESSOR
264
2.38M
        ZSTD_fillDoubleHashTable(ms, iend, ZSTD_dtlm_fast, ZSTD_tfp_forCCtx);
265
#else
266
        assert(0); /* shouldn't be called: cparams should've been adjusted. */
267
#endif
268
2.38M
        break;
269
270
855k
    case ZSTD_greedy:
271
1.92M
    case ZSTD_lazy:
272
3.78M
    case ZSTD_lazy2:
273
4.19M
    case ZSTD_btlazy2:
274
4.19M
    case ZSTD_btopt:
275
4.19M
    case ZSTD_btultra:
276
4.19M
    case ZSTD_btultra2:
277
4.19M
        break;
278
0
    default:
279
0
        assert(0);  /* not possible : not a valid strategy id */
280
7.98M
    }
281
282
7.98M
    return 0;
283
7.98M
}
284
285
void ZSTD_ldm_fillHashTable(
286
            ldmState_t* ldmState, const BYTE* ip,
287
            const BYTE* iend, ldmParams_t const* params)
288
5.68k
{
289
5.68k
    U32 const minMatchLength = params->minMatchLength;
290
5.68k
    U32 const bucketSizeLog = params->bucketSizeLog;
291
5.68k
    U32 const hBits = params->hashLog - bucketSizeLog;
292
5.68k
    BYTE const* const base = ldmState->window.base;
293
5.68k
    BYTE const* const istart = ip;
294
5.68k
    ldmRollingHashState_t hashState;
295
5.68k
    size_t* const splits = ldmState->splitIndices;
296
5.68k
    unsigned numSplits;
297
298
5.68k
    DEBUGLOG(5, "ZSTD_ldm_fillHashTable");
299
300
5.68k
    ZSTD_ldm_gear_init(&hashState, params);
301
52.0k
    while (ip < iend) {
302
46.3k
        size_t hashed;
303
46.3k
        unsigned n;
304
305
46.3k
        numSplits = 0;
306
46.3k
        hashed = ZSTD_ldm_gear_feed(&hashState, ip, (size_t)(iend - ip), splits, &numSplits);
307
308
2.72M
        for (n = 0; n < numSplits; n++) {
309
2.68M
            if (ip + splits[n] >= istart + minMatchLength) {
310
2.50M
                BYTE const* const split = ip + splits[n] - minMatchLength;
311
2.50M
                U64 const xxhash = XXH64(split, minMatchLength, 0);
312
2.50M
                U32 const hash = (U32)(xxhash & (((U32)1 << hBits) - 1));
313
2.50M
                ldmEntry_t entry;
314
315
2.50M
                entry.offset = (U32)(split - base);
316
2.50M
                entry.checksum = (U32)(xxhash >> 32);
317
2.50M
                ZSTD_ldm_insertEntry(ldmState, hash, entry, params->bucketSizeLog);
318
2.50M
            }
319
2.68M
        }
320
321
46.3k
        ip += hashed;
322
46.3k
    }
323
5.68k
}
324
325
326
/** ZSTD_ldm_limitTableUpdate() :
327
 *
328
 *  Sets cctx->nextToUpdate to a position corresponding closer to anchor
329
 *  if it is far way
330
 *  (after a long match, only update tables a limited amount). */
331
static void ZSTD_ldm_limitTableUpdate(ZSTD_MatchState_t* ms, const BYTE* anchor)
332
7.98M
{
333
7.98M
    U32 const curr = (U32)(anchor - ms->window.base);
334
7.98M
    if (curr > ms->nextToUpdate + 1024) {
335
143k
        ms->nextToUpdate =
336
143k
            curr - MIN(512, curr - ms->nextToUpdate - 1024);
337
143k
    }
338
7.98M
}
339
340
static
341
ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
342
size_t ZSTD_ldm_generateSequences_internal(
343
        ldmState_t* ldmState, RawSeqStore_t* rawSeqStore,
344
        ldmParams_t const* params, void const* src, size_t srcSize)
345
1.70M
{
346
    /* LDM parameters */
347
1.70M
    int const extDict = ZSTD_window_hasExtDict(ldmState->window);
348
1.70M
    U32 const minMatchLength = params->minMatchLength;
349
1.70M
    U32 const entsPerBucket = 1U << params->bucketSizeLog;
350
1.70M
    U32 const hBits = params->hashLog - params->bucketSizeLog;
351
    /* Prefix and extDict parameters */
352
1.70M
    U32 const dictLimit = ldmState->window.dictLimit;
353
1.70M
    U32 const lowestIndex = extDict ? ldmState->window.lowLimit : dictLimit;
354
1.70M
    BYTE const* const base = ldmState->window.base;
355
1.70M
    BYTE const* const dictBase = extDict ? ldmState->window.dictBase : NULL;
356
1.70M
    BYTE const* const dictStart = extDict ? dictBase + lowestIndex : NULL;
357
1.70M
    BYTE const* const dictEnd = extDict ? dictBase + dictLimit : NULL;
358
1.70M
    BYTE const* const lowPrefixPtr = base + dictLimit;
359
    /* Input bounds */
360
1.70M
    BYTE const* const istart = (BYTE const*)src;
361
1.70M
    BYTE const* const iend = istart + srcSize;
362
1.70M
    BYTE const* const ilimit = iend - HASH_READ_SIZE;
363
    /* Input positions */
364
1.70M
    BYTE const* anchor = istart;
365
1.70M
    BYTE const* ip = istart;
366
    /* Rolling hash state */
367
1.70M
    ldmRollingHashState_t hashState;
368
    /* Arrays for staged-processing */
369
1.70M
    size_t* const splits = ldmState->splitIndices;
370
1.70M
    ldmMatchCandidate_t* const candidates = ldmState->matchCandidates;
371
1.70M
    unsigned numSplits;
372
373
1.70M
    if (srcSize < minMatchLength)
374
1.24M
        return iend - anchor;
375
376
    /* Initialize the rolling hash state with the first minMatchLength bytes */
377
467k
    ZSTD_ldm_gear_init(&hashState, params);
378
467k
    ZSTD_ldm_gear_reset(&hashState, ip, minMatchLength);
379
467k
    ip += minMatchLength;
380
381
2.93M
    while (ip < ilimit) {
382
2.46M
        size_t hashed;
383
2.46M
        unsigned n;
384
385
2.46M
        numSplits = 0;
386
2.46M
        hashed = ZSTD_ldm_gear_feed(&hashState, ip, ilimit - ip,
387
2.46M
                                    splits, &numSplits);
388
389
141M
        for (n = 0; n < numSplits; n++) {
390
139M
            BYTE const* const split = ip + splits[n] - minMatchLength;
391
139M
            U64 const xxhash = XXH64(split, minMatchLength, 0);
392
139M
            U32 const hash = (U32)(xxhash & (((U32)1 << hBits) - 1));
393
394
139M
            candidates[n].split = split;
395
139M
            candidates[n].hash = hash;
396
139M
            candidates[n].checksum = (U32)(xxhash >> 32);
397
139M
            candidates[n].bucket = ZSTD_ldm_getBucket(ldmState, hash, params->bucketSizeLog);
398
139M
            PREFETCH_L1(candidates[n].bucket);
399
139M
        }
400
401
136M
        for (n = 0; n < numSplits; n++) {
402
134M
            size_t forwardMatchLength = 0, backwardMatchLength = 0,
403
134M
                   bestMatchLength = 0, mLength;
404
134M
            U32 offset;
405
134M
            BYTE const* const split = candidates[n].split;
406
134M
            U32 const checksum = candidates[n].checksum;
407
134M
            U32 const hash = candidates[n].hash;
408
134M
            ldmEntry_t* const bucket = candidates[n].bucket;
409
134M
            ldmEntry_t const* cur;
410
134M
            ldmEntry_t const* bestEntry = NULL;
411
134M
            ldmEntry_t newEntry;
412
413
134M
            newEntry.offset = (U32)(split - base);
414
134M
            newEntry.checksum = checksum;
415
416
            /* If a split point would generate a sequence overlapping with
417
             * the previous one, we merely register it in the hash table and
418
             * move on */
419
134M
            if (split < anchor) {
420
28.6M
                ZSTD_ldm_insertEntry(ldmState, hash, newEntry, params->bucketSizeLog);
421
28.6M
                continue;
422
28.6M
            }
423
424
5.94G
            for (cur = bucket; cur < bucket + entsPerBucket; cur++) {
425
5.84G
                size_t curForwardMatchLength, curBackwardMatchLength,
426
5.84G
                       curTotalMatchLength;
427
5.84G
                if (cur->checksum != checksum || cur->offset <= lowestIndex) {
428
5.80G
                    continue;
429
5.80G
                }
430
39.0M
                if (extDict) {
431
1.48M
                    BYTE const* const curMatchBase =
432
1.48M
                        cur->offset < dictLimit ? dictBase : base;
433
1.48M
                    BYTE const* const pMatch = curMatchBase + cur->offset;
434
1.48M
                    BYTE const* const matchEnd =
435
1.48M
                        cur->offset < dictLimit ? dictEnd : iend;
436
1.48M
                    BYTE const* const lowMatchPtr =
437
1.48M
                        cur->offset < dictLimit ? dictStart : lowPrefixPtr;
438
1.48M
                    curForwardMatchLength =
439
1.48M
                        ZSTD_count_2segments(split, pMatch, iend, matchEnd, lowPrefixPtr);
440
1.48M
                    if (curForwardMatchLength < minMatchLength) {
441
59
                        continue;
442
59
                    }
443
1.48M
                    curBackwardMatchLength = ZSTD_ldm_countBackwardsMatch_2segments(
444
1.48M
                            split, anchor, pMatch, lowMatchPtr, dictStart, dictEnd);
445
37.5M
                } else { /* !extDict */
446
37.5M
                    BYTE const* const pMatch = base + cur->offset;
447
37.5M
                    curForwardMatchLength = ZSTD_count(split, pMatch, iend);
448
37.5M
                    if (curForwardMatchLength < minMatchLength) {
449
879
                        continue;
450
879
                    }
451
37.5M
                    curBackwardMatchLength =
452
37.5M
                        ZSTD_ldm_countBackwardsMatch(split, anchor, pMatch, lowPrefixPtr);
453
37.5M
                }
454
39.0M
                curTotalMatchLength = curForwardMatchLength + curBackwardMatchLength;
455
456
39.0M
                if (curTotalMatchLength > bestMatchLength) {
457
10.6M
                    bestMatchLength = curTotalMatchLength;
458
10.6M
                    forwardMatchLength = curForwardMatchLength;
459
10.6M
                    backwardMatchLength = curBackwardMatchLength;
460
10.6M
                    bestEntry = cur;
461
10.6M
                }
462
39.0M
            }
463
464
            /* No match found -- insert an entry into the hash table
465
             * and process the next candidate match */
466
105M
            if (bestEntry == NULL) {
467
97.8M
                ZSTD_ldm_insertEntry(ldmState, hash, newEntry, params->bucketSizeLog);
468
97.8M
                continue;
469
97.8M
            }
470
471
            /* Match found */
472
7.93M
            offset = (U32)(split - base) - bestEntry->offset;
473
7.93M
            mLength = forwardMatchLength + backwardMatchLength;
474
7.93M
            {
475
7.93M
                rawSeq* const seq = rawSeqStore->seq + rawSeqStore->size;
476
477
                /* Out of sequence storage */
478
7.93M
                if (rawSeqStore->size == rawSeqStore->capacity)
479
0
                    return ERROR(dstSize_tooSmall);
480
7.93M
                seq->litLength = (U32)(split - backwardMatchLength - anchor);
481
7.93M
                seq->matchLength = (U32)mLength;
482
7.93M
                seq->offset = offset;
483
7.93M
                rawSeqStore->size++;
484
7.93M
            }
485
486
            /* Insert the current entry into the hash table --- it must be
487
             * done after the previous block to avoid clobbering bestEntry */
488
0
            ZSTD_ldm_insertEntry(ldmState, hash, newEntry, params->bucketSizeLog);
489
490
7.93M
            anchor = split + forwardMatchLength;
491
492
            /* If we find a match that ends after the data that we've hashed
493
             * then we have a repeating, overlapping, pattern. E.g. all zeros.
494
             * If one repetition of the pattern matches our `stopMask` then all
495
             * repetitions will. We don't need to insert them all into out table,
496
             * only the first one. So skip over overlapping matches.
497
             * This is a major speed boost (20x) for compressing a single byte
498
             * repeated, when that byte ends up in the table.
499
             */
500
7.93M
            if (anchor > ip + hashed) {
501
393k
                ZSTD_ldm_gear_reset(&hashState, anchor - minMatchLength, minMatchLength);
502
                /* Continue the outer loop at anchor (ip + hashed == anchor). */
503
393k
                ip = anchor - hashed;
504
393k
                break;
505
393k
            }
506
7.93M
        }
507
508
2.46M
        ip += hashed;
509
2.46M
    }
510
511
467k
    return iend - anchor;
512
467k
}
513
514
/*! ZSTD_ldm_reduceTable() :
515
 *  reduce table indexes by `reducerValue` */
516
static void ZSTD_ldm_reduceTable(ldmEntry_t* const table, U32 const size,
517
                                 U32 const reducerValue)
518
47.4k
{
519
47.4k
    U32 u;
520
273M
    for (u = 0; u < size; u++) {
521
273M
        if (table[u].offset < reducerValue) table[u].offset = 0;
522
9.17M
        else table[u].offset -= reducerValue;
523
273M
    }
524
47.4k
}
525
526
size_t ZSTD_ldm_generateSequences(
527
        ldmState_t* ldmState, RawSeqStore_t* sequences,
528
        ldmParams_t const* params, void const* src, size_t srcSize)
529
1.89M
{
530
1.89M
    U32 const maxDist = 1U << params->windowLog;
531
1.89M
    BYTE const* const istart = (BYTE const*)src;
532
1.89M
    BYTE const* const iend = istart + srcSize;
533
1.89M
    size_t const kMaxChunkSize = 1 << 20;
534
1.89M
    size_t const nbChunks = (srcSize / kMaxChunkSize) + ((srcSize % kMaxChunkSize) != 0);
535
1.89M
    size_t chunk;
536
1.89M
    size_t leftoverSize = 0;
537
538
1.89M
    assert(ZSTD_CHUNKSIZE_MAX >= kMaxChunkSize);
539
    /* Check that ZSTD_window_update() has been called for this chunk prior
540
     * to passing it to this function.
541
     */
542
1.89M
    assert(ldmState->window.nextSrc >= (BYTE const*)src + srcSize);
543
    /* The input could be very large (in zstdmt), so it must be broken up into
544
     * chunks to enforce the maximum distance and handle overflow correction.
545
     */
546
1.89M
    assert(sequences->pos <= sequences->size);
547
1.89M
    assert(sequences->size <= sequences->capacity);
548
3.60M
    for (chunk = 0; chunk < nbChunks && sequences->size < sequences->capacity; ++chunk) {
549
1.70M
        BYTE const* const chunkStart = istart + chunk * kMaxChunkSize;
550
1.70M
        size_t const remaining = (size_t)(iend - chunkStart);
551
1.70M
        BYTE const *const chunkEnd =
552
1.70M
            (remaining < kMaxChunkSize) ? iend : chunkStart + kMaxChunkSize;
553
1.70M
        size_t const chunkSize = chunkEnd - chunkStart;
554
1.70M
        size_t newLeftoverSize;
555
1.70M
        size_t const prevSize = sequences->size;
556
557
1.70M
        assert(chunkStart < iend);
558
        /* 1. Perform overflow correction if necessary. */
559
1.70M
        if (ZSTD_window_needOverflowCorrection(ldmState->window, 0, maxDist, ldmState->loadedDictEnd, chunkStart, chunkEnd)) {
560
47.4k
            U32 const ldmHSize = 1U << params->hashLog;
561
47.4k
            U32 const correction = ZSTD_window_correctOverflow(
562
47.4k
                &ldmState->window, /* cycleLog */ 0, maxDist, chunkStart);
563
47.4k
            ZSTD_ldm_reduceTable(ldmState->hashTable, ldmHSize, correction);
564
            /* invalidate dictionaries on overflow correction */
565
47.4k
            ldmState->loadedDictEnd = 0;
566
47.4k
        }
567
        /* 2. We enforce the maximum offset allowed.
568
         *
569
         * kMaxChunkSize should be small enough that we don't lose too much of
570
         * the window through early invalidation.
571
         * TODO: * Test the chunk size.
572
         *       * Try invalidation after the sequence generation and test the
573
         *         offset against maxDist directly.
574
         *
575
         * NOTE: Because of dictionaries + sequence splitting we MUST make sure
576
         * that any offset used is valid at the END of the sequence, since it may
577
         * be split into two sequences. This condition holds when using
578
         * ZSTD_window_enforceMaxDist(), but if we move to checking offsets
579
         * against maxDist directly, we'll have to carefully handle that case.
580
         */
581
1.70M
        ZSTD_window_enforceMaxDist(&ldmState->window, chunkEnd, maxDist, &ldmState->loadedDictEnd, NULL);
582
        /* 3. Generate the sequences for the chunk, and get newLeftoverSize. */
583
1.70M
        newLeftoverSize = ZSTD_ldm_generateSequences_internal(
584
1.70M
            ldmState, sequences, params, chunkStart, chunkSize);
585
1.70M
        if (ZSTD_isError(newLeftoverSize))
586
0
            return newLeftoverSize;
587
        /* 4. We add the leftover literals from previous iterations to the first
588
         *    newly generated sequence, or add the `newLeftoverSize` if none are
589
         *    generated.
590
         */
591
        /* Prepend the leftover literals from the last call */
592
1.70M
        if (prevSize < sequences->size) {
593
303k
            sequences->seq[prevSize].litLength += (U32)leftoverSize;
594
303k
            leftoverSize = newLeftoverSize;
595
1.40M
        } else {
596
1.40M
            assert(newLeftoverSize == chunkSize);
597
1.40M
            leftoverSize += chunkSize;
598
1.40M
        }
599
1.70M
    }
600
1.89M
    return 0;
601
1.89M
}
602
603
void
604
ZSTD_ldm_skipSequences(RawSeqStore_t* rawSeqStore, size_t srcSize, U32 const minMatch)
605
37.2M
{
606
37.2M
    while (srcSize > 0 && rawSeqStore->pos < rawSeqStore->size) {
607
40.0k
        rawSeq* seq = rawSeqStore->seq + rawSeqStore->pos;
608
40.0k
        if (srcSize <= seq->litLength) {
609
            /* Skip past srcSize literals */
610
38.6k
            seq->litLength -= (U32)srcSize;
611
38.6k
            return;
612
38.6k
        }
613
1.38k
        srcSize -= seq->litLength;
614
1.38k
        seq->litLength = 0;
615
1.38k
        if (srcSize < seq->matchLength) {
616
            /* Skip past the first srcSize of the match */
617
1.37k
            seq->matchLength -= (U32)srcSize;
618
1.37k
            if (seq->matchLength < minMatch) {
619
                /* The match is too short, omit it */
620
296
                if (rawSeqStore->pos + 1 < rawSeqStore->size) {
621
266
                    seq[1].litLength += seq[0].matchLength;
622
266
                }
623
296
                rawSeqStore->pos++;
624
296
            }
625
1.37k
            return;
626
1.37k
        }
627
9
        srcSize -= seq->matchLength;
628
9
        seq->matchLength = 0;
629
9
        rawSeqStore->pos++;
630
9
    }
631
37.2M
}
632
633
/**
634
 * If the sequence length is longer than remaining then the sequence is split
635
 * between this block and the next.
636
 *
637
 * Returns the current sequence to handle, or if the rest of the block should
638
 * be literals, it returns a sequence with offset == 0.
639
 */
640
static rawSeq maybeSplitSequence(RawSeqStore_t* rawSeqStore,
641
                                 U32 const remaining, U32 const minMatch)
642
7.42M
{
643
7.42M
    rawSeq sequence = rawSeqStore->seq[rawSeqStore->pos];
644
7.42M
    assert(sequence.offset > 0);
645
    /* Likely: No partial sequence */
646
7.42M
    if (remaining >= sequence.litLength + sequence.matchLength) {
647
7.38M
        rawSeqStore->pos++;
648
7.38M
        return sequence;
649
7.38M
    }
650
    /* Cut the sequence short (offset == 0 ==> rest is literals). */
651
40.0k
    if (remaining <= sequence.litLength) {
652
38.6k
        sequence.offset = 0;
653
38.6k
    } else if (remaining < sequence.litLength + sequence.matchLength) {
654
1.37k
        sequence.matchLength = remaining - sequence.litLength;
655
1.37k
        if (sequence.matchLength < minMatch) {
656
277
            sequence.offset = 0;
657
277
        }
658
1.37k
    }
659
    /* Skip past `remaining` bytes for the future sequences. */
660
40.0k
    ZSTD_ldm_skipSequences(rawSeqStore, remaining, minMatch);
661
40.0k
    return sequence;
662
7.42M
}
663
664
1.62M
void ZSTD_ldm_skipRawSeqStoreBytes(RawSeqStore_t* rawSeqStore, size_t nbBytes) {
665
1.62M
    U32 currPos = (U32)(rawSeqStore->posInSequence + nbBytes);
666
2.17M
    while (currPos && rawSeqStore->pos < rawSeqStore->size) {
667
566k
        rawSeq currSeq = rawSeqStore->seq[rawSeqStore->pos];
668
566k
        if (currPos >= currSeq.litLength + currSeq.matchLength) {
669
550k
            currPos -= currSeq.litLength + currSeq.matchLength;
670
550k
            rawSeqStore->pos++;
671
550k
        } else {
672
16.2k
            rawSeqStore->posInSequence = currPos;
673
16.2k
            break;
674
16.2k
        }
675
566k
    }
676
1.62M
    if (currPos == 0 || rawSeqStore->pos == rawSeqStore->size) {
677
1.60M
        rawSeqStore->posInSequence = 0;
678
1.60M
    }
679
1.62M
}
680
681
size_t ZSTD_ldm_blockCompress(RawSeqStore_t* rawSeqStore,
682
    ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
683
    ZSTD_ParamSwitch_e useRowMatchFinder,
684
    void const* src, size_t srcSize)
685
721k
{
686
721k
    const ZSTD_compressionParameters* const cParams = &ms->cParams;
687
721k
    unsigned const minMatch = cParams->minMatch;
688
721k
    ZSTD_BlockCompressor_f const blockCompressor =
689
721k
        ZSTD_selectBlockCompressor(cParams->strategy, useRowMatchFinder, ZSTD_matchState_dictMode(ms));
690
    /* Input bounds */
691
721k
    BYTE const* const istart = (BYTE const*)src;
692
721k
    BYTE const* const iend = istart + srcSize;
693
    /* Input positions */
694
721k
    BYTE const* ip = istart;
695
696
721k
    DEBUGLOG(5, "ZSTD_ldm_blockCompress: srcSize=%zu", srcSize);
697
    /* If using opt parser, use LDMs only as candidates rather than always accepting them */
698
721k
    if (cParams->strategy >= ZSTD_btopt) {
699
117k
        size_t lastLLSize;
700
117k
        ms->ldmSeqStore = rawSeqStore;
701
117k
        lastLLSize = blockCompressor(ms, seqStore, rep, src, srcSize);
702
117k
        ZSTD_ldm_skipRawSeqStoreBytes(rawSeqStore, srcSize);
703
117k
        return lastLLSize;
704
117k
    }
705
706
604k
    assert(rawSeqStore->pos <= rawSeqStore->size);
707
604k
    assert(rawSeqStore->size <= rawSeqStore->capacity);
708
    /* Loop through each sequence and apply the block compressor to the literals */
709
7.98M
    while (rawSeqStore->pos < rawSeqStore->size && ip < iend) {
710
        /* maybeSplitSequence updates rawSeqStore->pos */
711
7.42M
        rawSeq const sequence = maybeSplitSequence(rawSeqStore,
712
7.42M
                                                   (U32)(iend - ip), minMatch);
713
        /* End signal */
714
7.42M
        if (sequence.offset == 0)
715
38.9k
            break;
716
717
7.38M
        assert(ip + sequence.litLength + sequence.matchLength <= iend);
718
719
        /* Fill tables for block compressor */
720
7.38M
        ZSTD_ldm_limitTableUpdate(ms, ip);
721
7.38M
        ZSTD_ldm_fillFastTables(ms, ip);
722
        /* Run the block compressor */
723
7.38M
        DEBUGLOG(5, "pos %u : calling block compressor on segment of size %u", (unsigned)(ip-istart), sequence.litLength);
724
7.38M
        {
725
7.38M
            int i;
726
7.38M
            size_t const newLitLength =
727
7.38M
                blockCompressor(ms, seqStore, rep, ip, sequence.litLength);
728
7.38M
            ip += sequence.litLength;
729
            /* Update the repcodes */
730
22.1M
            for (i = ZSTD_REP_NUM - 1; i > 0; i--)
731
14.7M
                rep[i] = rep[i-1];
732
7.38M
            rep[0] = sequence.offset;
733
            /* Store the sequence */
734
7.38M
            ZSTD_storeSeq(seqStore, newLitLength, ip - newLitLength, iend,
735
7.38M
                          OFFSET_TO_OFFBASE(sequence.offset),
736
0
                          sequence.matchLength);
737
0
            ip += sequence.matchLength;
738
7.38M
        }
739
7.38M
    }
740
    /* Fill the tables for the block compressor */
741
604k
    ZSTD_ldm_limitTableUpdate(ms, ip);
742
604k
    ZSTD_ldm_fillFastTables(ms, ip);
743
    /* Compress the last literals */
744
604k
    return blockCompressor(ms, seqStore, rep, ip, iend - ip);
745
604k
}