Coverage Report

Created: 2025-03-15 06:58

/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
0
{
34
0
    unsigned maxBitsInMask = MIN(params->minMatchLength, 64);
35
0
    unsigned hashRateLog = params->hashRateLog;
36
37
0
    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
0
    if (hashRateLog > 0 && hashRateLog <= maxBitsInMask) {
53
0
        state->stopMask = (((U64)1 << hashRateLog) - 1) << (maxBitsInMask - hashRateLog);
54
0
    } else {
55
        /* In this degenerate case we simply honor the hash rate. */
56
0
        state->stopMask = ((U64)1 << hashRateLog) - 1;
57
0
    }
58
0
}
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
0
{
68
0
    U64 hash = state->rolling;
69
0
    size_t n = 0;
70
71
0
#define GEAR_ITER_ONCE() do {                                  \
72
0
        hash = (hash << 1) + ZSTD_ldm_gearTab[data[n] & 0xff]; \
73
0
        n += 1;                                                \
74
0
    } while (0)
75
0
    while (n + 3 < minMatchLength) {
76
0
        GEAR_ITER_ONCE();
77
0
        GEAR_ITER_ONCE();
78
0
        GEAR_ITER_ONCE();
79
0
        GEAR_ITER_ONCE();
80
0
    }
81
0
    while (n < minMatchLength) {
82
0
        GEAR_ITER_ONCE();
83
0
    }
84
0
#undef GEAR_ITER_ONCE
85
0
}
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
0
{
100
0
    size_t n;
101
0
    U64 hash, mask;
102
103
0
    hash = state->rolling;
104
0
    mask = state->stopMask;
105
0
    n = 0;
106
107
0
#define GEAR_ITER_ONCE() do { \
108
0
        hash = (hash << 1) + ZSTD_ldm_gearTab[data[n] & 0xff]; \
109
0
        n += 1; \
110
0
        if (UNLIKELY((hash & mask) == 0)) { \
111
0
            splits[*numSplits] = n; \
112
0
            *numSplits += 1; \
113
0
            if (*numSplits == LDM_BATCH_SIZE) \
114
0
                goto done; \
115
0
        } \
116
0
    } while (0)
117
118
0
    while (n + 3 < size) {
119
0
        GEAR_ITER_ONCE();
120
0
        GEAR_ITER_ONCE();
121
0
        GEAR_ITER_ONCE();
122
0
        GEAR_ITER_ONCE();
123
0
    }
124
0
    while (n < size) {
125
0
        GEAR_ITER_ONCE();
126
0
    }
127
128
0
#undef GEAR_ITER_ONCE
129
130
0
done:
131
0
    state->rolling = hash;
132
0
    return n;
133
0
}
134
135
void ZSTD_ldm_adjustParameters(ldmParams_t* params,
136
                        const ZSTD_compressionParameters* cParams)
137
0
{
138
0
    params->windowLog = cParams->windowLog;
139
0
    ZSTD_STATIC_ASSERT(LDM_BUCKET_SIZE_LOG <= ZSTD_LDM_BUCKETSIZELOG_MAX);
140
0
    DEBUGLOG(4, "ZSTD_ldm_adjustParameters");
141
0
    if (params->hashRateLog == 0) {
142
0
        if (params->hashLog > 0) {
143
            /* if params->hashLog is set, derive hashRateLog from it */
144
0
            assert(params->hashLog <= ZSTD_HASHLOG_MAX);
145
0
            if (params->windowLog > params->hashLog) {
146
0
                params->hashRateLog = params->windowLog - params->hashLog;
147
0
            }
148
0
        } 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
0
    }
154
0
    if (params->hashLog == 0) {
155
0
        params->hashLog = BOUNDED(ZSTD_HASHLOG_MIN, params->windowLog - params->hashRateLog, ZSTD_HASHLOG_MAX);
156
0
    }
157
0
    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
0
    if (params->bucketSizeLog==0) {
163
0
        assert(1 <= (int)cParams->strategy && (int)cParams->strategy <= 9);
164
0
        params->bucketSizeLog = BOUNDED(LDM_BUCKET_SIZE_LOG, (U32)cParams->strategy, ZSTD_LDM_BUCKETSIZELOG_MAX);
165
0
    }
166
0
    params->bucketSizeLog = MIN(params->bucketSizeLog, params->hashLog);
167
0
}
168
169
size_t ZSTD_ldm_getTableSize(ldmParams_t params)
170
0
{
171
0
    size_t const ldmHSize = ((size_t)1) << params.hashLog;
172
0
    size_t const ldmBucketSizeLog = MIN(params.bucketSizeLog, params.hashLog);
173
0
    size_t const ldmBucketSize = ((size_t)1) << (params.hashLog - ldmBucketSizeLog);
174
0
    size_t const totalSize = ZSTD_cwksp_alloc_size(ldmBucketSize)
175
0
                           + ZSTD_cwksp_alloc_size(ldmHSize * sizeof(ldmEntry_t));
176
0
    return params.enableLdm == ZSTD_ps_enable ? totalSize : 0;
177
0
}
178
179
size_t ZSTD_ldm_getMaxNbSeq(ldmParams_t params, size_t maxChunkSize)
180
0
{
181
0
    return params.enableLdm == ZSTD_ps_enable ? (maxChunkSize / params.minMatchLength) : 0;
182
0
}
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
0
{
189
0
    return ldmState->hashTable + (hash << bucketSizeLog);
190
0
}
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
0
{
198
0
    BYTE* const pOffset = ldmState->bucketOffsets + hash;
199
0
    unsigned const offset = *pOffset;
200
201
0
    *(ZSTD_ldm_getBucket(ldmState, hash, bucketSizeLog) + offset) = entry;
202
0
    *pOffset = (BYTE)((offset + 1) & ((1u << bucketSizeLog) - 1));
203
204
0
}
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
0
{
214
0
    size_t matchLength = 0;
215
0
    while (pIn > pAnchor && pMatch > pMatchBase && pIn[-1] == pMatch[-1]) {
216
0
        pIn--;
217
0
        pMatch--;
218
0
        matchLength++;
219
0
    }
220
0
    return matchLength;
221
0
}
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
0
{
233
0
    size_t matchLength = ZSTD_ldm_countBackwardsMatch(pIn, pAnchor, pMatch, pMatchBase);
234
0
    if (pMatch - matchLength != pMatchBase || pMatchBase == pExtDictStart) {
235
        /* If backwards match is entirely in the extDict or prefix, immediately return */
236
0
        return matchLength;
237
0
    }
238
0
    DEBUGLOG(7, "ZSTD_ldm_countBackwardsMatch_2segments: found 2-parts backwards match (length in prefix==%zu)", matchLength);
239
0
    matchLength += ZSTD_ldm_countBackwardsMatch(pIn - matchLength, pAnchor, pExtDictEnd, pExtDictStart);
240
0
    DEBUGLOG(7, "final backwards match length = %zu", matchLength);
241
0
    return matchLength;
242
0
}
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
0
{
254
0
    const BYTE* const iend = (const BYTE*)end;
255
256
0
    switch(ms->cParams.strategy)
257
0
    {
258
0
    case ZSTD_fast:
259
0
        ZSTD_fillHashTable(ms, iend, ZSTD_dtlm_fast, ZSTD_tfp_forCCtx);
260
0
        break;
261
262
0
    case ZSTD_dfast:
263
0
#ifndef ZSTD_EXCLUDE_DFAST_BLOCK_COMPRESSOR
264
0
        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
0
        break;
269
270
0
    case ZSTD_greedy:
271
0
    case ZSTD_lazy:
272
0
    case ZSTD_lazy2:
273
0
    case ZSTD_btlazy2:
274
0
    case ZSTD_btopt:
275
0
    case ZSTD_btultra:
276
0
    case ZSTD_btultra2:
277
0
        break;
278
0
    default:
279
0
        assert(0);  /* not possible : not a valid strategy id */
280
0
    }
281
282
0
    return 0;
283
0
}
284
285
void ZSTD_ldm_fillHashTable(
286
            ldmState_t* ldmState, const BYTE* ip,
287
            const BYTE* iend, ldmParams_t const* params)
288
0
{
289
0
    U32 const minMatchLength = params->minMatchLength;
290
0
    U32 const bucketSizeLog = params->bucketSizeLog;
291
0
    U32 const hBits = params->hashLog - bucketSizeLog;
292
0
    BYTE const* const base = ldmState->window.base;
293
0
    BYTE const* const istart = ip;
294
0
    ldmRollingHashState_t hashState;
295
0
    size_t* const splits = ldmState->splitIndices;
296
0
    unsigned numSplits;
297
298
0
    DEBUGLOG(5, "ZSTD_ldm_fillHashTable");
299
300
0
    ZSTD_ldm_gear_init(&hashState, params);
301
0
    while (ip < iend) {
302
0
        size_t hashed;
303
0
        unsigned n;
304
305
0
        numSplits = 0;
306
0
        hashed = ZSTD_ldm_gear_feed(&hashState, ip, (size_t)(iend - ip), splits, &numSplits);
307
308
0
        for (n = 0; n < numSplits; n++) {
309
0
            if (ip + splits[n] >= istart + minMatchLength) {
310
0
                BYTE const* const split = ip + splits[n] - minMatchLength;
311
0
                U64 const xxhash = XXH64(split, minMatchLength, 0);
312
0
                U32 const hash = (U32)(xxhash & (((U32)1 << hBits) - 1));
313
0
                ldmEntry_t entry;
314
315
0
                entry.offset = (U32)(split - base);
316
0
                entry.checksum = (U32)(xxhash >> 32);
317
0
                ZSTD_ldm_insertEntry(ldmState, hash, entry, params->bucketSizeLog);
318
0
            }
319
0
        }
320
321
0
        ip += hashed;
322
0
    }
323
0
}
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
0
{
333
0
    U32 const curr = (U32)(anchor - ms->window.base);
334
0
    if (curr > ms->nextToUpdate + 1024) {
335
0
        ms->nextToUpdate =
336
0
            curr - MIN(512, curr - ms->nextToUpdate - 1024);
337
0
    }
338
0
}
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
0
{
346
    /* LDM parameters */
347
0
    int const extDict = ZSTD_window_hasExtDict(ldmState->window);
348
0
    U32 const minMatchLength = params->minMatchLength;
349
0
    U32 const entsPerBucket = 1U << params->bucketSizeLog;
350
0
    U32 const hBits = params->hashLog - params->bucketSizeLog;
351
    /* Prefix and extDict parameters */
352
0
    U32 const dictLimit = ldmState->window.dictLimit;
353
0
    U32 const lowestIndex = extDict ? ldmState->window.lowLimit : dictLimit;
354
0
    BYTE const* const base = ldmState->window.base;
355
0
    BYTE const* const dictBase = extDict ? ldmState->window.dictBase : NULL;
356
0
    BYTE const* const dictStart = extDict ? dictBase + lowestIndex : NULL;
357
0
    BYTE const* const dictEnd = extDict ? dictBase + dictLimit : NULL;
358
0
    BYTE const* const lowPrefixPtr = base + dictLimit;
359
    /* Input bounds */
360
0
    BYTE const* const istart = (BYTE const*)src;
361
0
    BYTE const* const iend = istart + srcSize;
362
0
    BYTE const* const ilimit = iend - HASH_READ_SIZE;
363
    /* Input positions */
364
0
    BYTE const* anchor = istart;
365
0
    BYTE const* ip = istart;
366
    /* Rolling hash state */
367
0
    ldmRollingHashState_t hashState;
368
    /* Arrays for staged-processing */
369
0
    size_t* const splits = ldmState->splitIndices;
370
0
    ldmMatchCandidate_t* const candidates = ldmState->matchCandidates;
371
0
    unsigned numSplits;
372
373
0
    if (srcSize < minMatchLength)
374
0
        return iend - anchor;
375
376
    /* Initialize the rolling hash state with the first minMatchLength bytes */
377
0
    ZSTD_ldm_gear_init(&hashState, params);
378
0
    ZSTD_ldm_gear_reset(&hashState, ip, minMatchLength);
379
0
    ip += minMatchLength;
380
381
0
    while (ip < ilimit) {
382
0
        size_t hashed;
383
0
        unsigned n;
384
385
0
        numSplits = 0;
386
0
        hashed = ZSTD_ldm_gear_feed(&hashState, ip, ilimit - ip,
387
0
                                    splits, &numSplits);
388
389
0
        for (n = 0; n < numSplits; n++) {
390
0
            BYTE const* const split = ip + splits[n] - minMatchLength;
391
0
            U64 const xxhash = XXH64(split, minMatchLength, 0);
392
0
            U32 const hash = (U32)(xxhash & (((U32)1 << hBits) - 1));
393
394
0
            candidates[n].split = split;
395
0
            candidates[n].hash = hash;
396
0
            candidates[n].checksum = (U32)(xxhash >> 32);
397
0
            candidates[n].bucket = ZSTD_ldm_getBucket(ldmState, hash, params->bucketSizeLog);
398
0
            PREFETCH_L1(candidates[n].bucket);
399
0
        }
400
401
0
        for (n = 0; n < numSplits; n++) {
402
0
            size_t forwardMatchLength = 0, backwardMatchLength = 0,
403
0
                   bestMatchLength = 0, mLength;
404
0
            U32 offset;
405
0
            BYTE const* const split = candidates[n].split;
406
0
            U32 const checksum = candidates[n].checksum;
407
0
            U32 const hash = candidates[n].hash;
408
0
            ldmEntry_t* const bucket = candidates[n].bucket;
409
0
            ldmEntry_t const* cur;
410
0
            ldmEntry_t const* bestEntry = NULL;
411
0
            ldmEntry_t newEntry;
412
413
0
            newEntry.offset = (U32)(split - base);
414
0
            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
0
            if (split < anchor) {
420
0
                ZSTD_ldm_insertEntry(ldmState, hash, newEntry, params->bucketSizeLog);
421
0
                continue;
422
0
            }
423
424
0
            for (cur = bucket; cur < bucket + entsPerBucket; cur++) {
425
0
                size_t curForwardMatchLength, curBackwardMatchLength,
426
0
                       curTotalMatchLength;
427
0
                if (cur->checksum != checksum || cur->offset <= lowestIndex) {
428
0
                    continue;
429
0
                }
430
0
                if (extDict) {
431
0
                    BYTE const* const curMatchBase =
432
0
                        cur->offset < dictLimit ? dictBase : base;
433
0
                    BYTE const* const pMatch = curMatchBase + cur->offset;
434
0
                    BYTE const* const matchEnd =
435
0
                        cur->offset < dictLimit ? dictEnd : iend;
436
0
                    BYTE const* const lowMatchPtr =
437
0
                        cur->offset < dictLimit ? dictStart : lowPrefixPtr;
438
0
                    curForwardMatchLength =
439
0
                        ZSTD_count_2segments(split, pMatch, iend, matchEnd, lowPrefixPtr);
440
0
                    if (curForwardMatchLength < minMatchLength) {
441
0
                        continue;
442
0
                    }
443
0
                    curBackwardMatchLength = ZSTD_ldm_countBackwardsMatch_2segments(
444
0
                            split, anchor, pMatch, lowMatchPtr, dictStart, dictEnd);
445
0
                } else { /* !extDict */
446
0
                    BYTE const* const pMatch = base + cur->offset;
447
0
                    curForwardMatchLength = ZSTD_count(split, pMatch, iend);
448
0
                    if (curForwardMatchLength < minMatchLength) {
449
0
                        continue;
450
0
                    }
451
0
                    curBackwardMatchLength =
452
0
                        ZSTD_ldm_countBackwardsMatch(split, anchor, pMatch, lowPrefixPtr);
453
0
                }
454
0
                curTotalMatchLength = curForwardMatchLength + curBackwardMatchLength;
455
456
0
                if (curTotalMatchLength > bestMatchLength) {
457
0
                    bestMatchLength = curTotalMatchLength;
458
0
                    forwardMatchLength = curForwardMatchLength;
459
0
                    backwardMatchLength = curBackwardMatchLength;
460
0
                    bestEntry = cur;
461
0
                }
462
0
            }
463
464
            /* No match found -- insert an entry into the hash table
465
             * and process the next candidate match */
466
0
            if (bestEntry == NULL) {
467
0
                ZSTD_ldm_insertEntry(ldmState, hash, newEntry, params->bucketSizeLog);
468
0
                continue;
469
0
            }
470
471
            /* Match found */
472
0
            offset = (U32)(split - base) - bestEntry->offset;
473
0
            mLength = forwardMatchLength + backwardMatchLength;
474
0
            {
475
0
                rawSeq* const seq = rawSeqStore->seq + rawSeqStore->size;
476
477
                /* Out of sequence storage */
478
0
                if (rawSeqStore->size == rawSeqStore->capacity)
479
0
                    return ERROR(dstSize_tooSmall);
480
0
                seq->litLength = (U32)(split - backwardMatchLength - anchor);
481
0
                seq->matchLength = (U32)mLength;
482
0
                seq->offset = offset;
483
0
                rawSeqStore->size++;
484
0
            }
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
0
            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
0
            if (anchor > ip + hashed) {
501
0
                ZSTD_ldm_gear_reset(&hashState, anchor - minMatchLength, minMatchLength);
502
                /* Continue the outer loop at anchor (ip + hashed == anchor). */
503
0
                ip = anchor - hashed;
504
0
                break;
505
0
            }
506
0
        }
507
508
0
        ip += hashed;
509
0
    }
510
511
0
    return iend - anchor;
512
0
}
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
0
{
519
0
    U32 u;
520
0
    for (u = 0; u < size; u++) {
521
0
        if (table[u].offset < reducerValue) table[u].offset = 0;
522
0
        else table[u].offset -= reducerValue;
523
0
    }
524
0
}
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
0
{
530
0
    U32 const maxDist = 1U << params->windowLog;
531
0
    BYTE const* const istart = (BYTE const*)src;
532
0
    BYTE const* const iend = istart + srcSize;
533
0
    size_t const kMaxChunkSize = 1 << 20;
534
0
    size_t const nbChunks = (srcSize / kMaxChunkSize) + ((srcSize % kMaxChunkSize) != 0);
535
0
    size_t chunk;
536
0
    size_t leftoverSize = 0;
537
538
0
    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
0
    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
0
    assert(sequences->pos <= sequences->size);
547
0
    assert(sequences->size <= sequences->capacity);
548
0
    for (chunk = 0; chunk < nbChunks && sequences->size < sequences->capacity; ++chunk) {
549
0
        BYTE const* const chunkStart = istart + chunk * kMaxChunkSize;
550
0
        size_t const remaining = (size_t)(iend - chunkStart);
551
0
        BYTE const *const chunkEnd =
552
0
            (remaining < kMaxChunkSize) ? iend : chunkStart + kMaxChunkSize;
553
0
        size_t const chunkSize = chunkEnd - chunkStart;
554
0
        size_t newLeftoverSize;
555
0
        size_t const prevSize = sequences->size;
556
557
0
        assert(chunkStart < iend);
558
        /* 1. Perform overflow correction if necessary. */
559
0
        if (ZSTD_window_needOverflowCorrection(ldmState->window, 0, maxDist, ldmState->loadedDictEnd, chunkStart, chunkEnd)) {
560
0
            U32 const ldmHSize = 1U << params->hashLog;
561
0
            U32 const correction = ZSTD_window_correctOverflow(
562
0
                &ldmState->window, /* cycleLog */ 0, maxDist, chunkStart);
563
0
            ZSTD_ldm_reduceTable(ldmState->hashTable, ldmHSize, correction);
564
            /* invalidate dictionaries on overflow correction */
565
0
            ldmState->loadedDictEnd = 0;
566
0
        }
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
0
        ZSTD_window_enforceMaxDist(&ldmState->window, chunkEnd, maxDist, &ldmState->loadedDictEnd, NULL);
582
        /* 3. Generate the sequences for the chunk, and get newLeftoverSize. */
583
0
        newLeftoverSize = ZSTD_ldm_generateSequences_internal(
584
0
            ldmState, sequences, params, chunkStart, chunkSize);
585
0
        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
0
        if (prevSize < sequences->size) {
593
0
            sequences->seq[prevSize].litLength += (U32)leftoverSize;
594
0
            leftoverSize = newLeftoverSize;
595
0
        } else {
596
0
            assert(newLeftoverSize == chunkSize);
597
0
            leftoverSize += chunkSize;
598
0
        }
599
0
    }
600
0
    return 0;
601
0
}
602
603
void
604
ZSTD_ldm_skipSequences(RawSeqStore_t* rawSeqStore, size_t srcSize, U32 const minMatch)
605
0
{
606
0
    while (srcSize > 0 && rawSeqStore->pos < rawSeqStore->size) {
607
0
        rawSeq* seq = rawSeqStore->seq + rawSeqStore->pos;
608
0
        if (srcSize <= seq->litLength) {
609
            /* Skip past srcSize literals */
610
0
            seq->litLength -= (U32)srcSize;
611
0
            return;
612
0
        }
613
0
        srcSize -= seq->litLength;
614
0
        seq->litLength = 0;
615
0
        if (srcSize < seq->matchLength) {
616
            /* Skip past the first srcSize of the match */
617
0
            seq->matchLength -= (U32)srcSize;
618
0
            if (seq->matchLength < minMatch) {
619
                /* The match is too short, omit it */
620
0
                if (rawSeqStore->pos + 1 < rawSeqStore->size) {
621
0
                    seq[1].litLength += seq[0].matchLength;
622
0
                }
623
0
                rawSeqStore->pos++;
624
0
            }
625
0
            return;
626
0
        }
627
0
        srcSize -= seq->matchLength;
628
0
        seq->matchLength = 0;
629
0
        rawSeqStore->pos++;
630
0
    }
631
0
}
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
0
{
643
0
    rawSeq sequence = rawSeqStore->seq[rawSeqStore->pos];
644
0
    assert(sequence.offset > 0);
645
    /* Likely: No partial sequence */
646
0
    if (remaining >= sequence.litLength + sequence.matchLength) {
647
0
        rawSeqStore->pos++;
648
0
        return sequence;
649
0
    }
650
    /* Cut the sequence short (offset == 0 ==> rest is literals). */
651
0
    if (remaining <= sequence.litLength) {
652
0
        sequence.offset = 0;
653
0
    } else if (remaining < sequence.litLength + sequence.matchLength) {
654
0
        sequence.matchLength = remaining - sequence.litLength;
655
0
        if (sequence.matchLength < minMatch) {
656
0
            sequence.offset = 0;
657
0
        }
658
0
    }
659
    /* Skip past `remaining` bytes for the future sequences. */
660
0
    ZSTD_ldm_skipSequences(rawSeqStore, remaining, minMatch);
661
0
    return sequence;
662
0
}
663
664
0
void ZSTD_ldm_skipRawSeqStoreBytes(RawSeqStore_t* rawSeqStore, size_t nbBytes) {
665
0
    U32 currPos = (U32)(rawSeqStore->posInSequence + nbBytes);
666
0
    while (currPos && rawSeqStore->pos < rawSeqStore->size) {
667
0
        rawSeq currSeq = rawSeqStore->seq[rawSeqStore->pos];
668
0
        if (currPos >= currSeq.litLength + currSeq.matchLength) {
669
0
            currPos -= currSeq.litLength + currSeq.matchLength;
670
0
            rawSeqStore->pos++;
671
0
        } else {
672
0
            rawSeqStore->posInSequence = currPos;
673
0
            break;
674
0
        }
675
0
    }
676
0
    if (currPos == 0 || rawSeqStore->pos == rawSeqStore->size) {
677
0
        rawSeqStore->posInSequence = 0;
678
0
    }
679
0
}
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
0
{
686
0
    const ZSTD_compressionParameters* const cParams = &ms->cParams;
687
0
    unsigned const minMatch = cParams->minMatch;
688
0
    ZSTD_BlockCompressor_f const blockCompressor =
689
0
        ZSTD_selectBlockCompressor(cParams->strategy, useRowMatchFinder, ZSTD_matchState_dictMode(ms));
690
    /* Input bounds */
691
0
    BYTE const* const istart = (BYTE const*)src;
692
0
    BYTE const* const iend = istart + srcSize;
693
    /* Input positions */
694
0
    BYTE const* ip = istart;
695
696
0
    DEBUGLOG(5, "ZSTD_ldm_blockCompress: srcSize=%zu", srcSize);
697
    /* If using opt parser, use LDMs only as candidates rather than always accepting them */
698
0
    if (cParams->strategy >= ZSTD_btopt) {
699
0
        size_t lastLLSize;
700
0
        ms->ldmSeqStore = rawSeqStore;
701
0
        lastLLSize = blockCompressor(ms, seqStore, rep, src, srcSize);
702
0
        ZSTD_ldm_skipRawSeqStoreBytes(rawSeqStore, srcSize);
703
0
        return lastLLSize;
704
0
    }
705
706
0
    assert(rawSeqStore->pos <= rawSeqStore->size);
707
0
    assert(rawSeqStore->size <= rawSeqStore->capacity);
708
    /* Loop through each sequence and apply the block compressor to the literals */
709
0
    while (rawSeqStore->pos < rawSeqStore->size && ip < iend) {
710
        /* maybeSplitSequence updates rawSeqStore->pos */
711
0
        rawSeq const sequence = maybeSplitSequence(rawSeqStore,
712
0
                                                   (U32)(iend - ip), minMatch);
713
        /* End signal */
714
0
        if (sequence.offset == 0)
715
0
            break;
716
717
0
        assert(ip + sequence.litLength + sequence.matchLength <= iend);
718
719
        /* Fill tables for block compressor */
720
0
        ZSTD_ldm_limitTableUpdate(ms, ip);
721
0
        ZSTD_ldm_fillFastTables(ms, ip);
722
        /* Run the block compressor */
723
0
        DEBUGLOG(5, "pos %u : calling block compressor on segment of size %u", (unsigned)(ip-istart), sequence.litLength);
724
0
        {
725
0
            int i;
726
0
            size_t const newLitLength =
727
0
                blockCompressor(ms, seqStore, rep, ip, sequence.litLength);
728
0
            ip += sequence.litLength;
729
            /* Update the repcodes */
730
0
            for (i = ZSTD_REP_NUM - 1; i > 0; i--)
731
0
                rep[i] = rep[i-1];
732
0
            rep[0] = sequence.offset;
733
            /* Store the sequence */
734
0
            ZSTD_storeSeq(seqStore, newLitLength, ip - newLitLength, iend,
735
0
                          OFFSET_TO_OFFBASE(sequence.offset),
736
0
                          sequence.matchLength);
737
0
            ip += sequence.matchLength;
738
0
        }
739
0
    }
740
    /* Fill the tables for the block compressor */
741
0
    ZSTD_ldm_limitTableUpdate(ms, ip);
742
0
    ZSTD_ldm_fillFastTables(ms, ip);
743
    /* Compress the last literals */
744
0
    return blockCompressor(ms, seqStore, rep, ip, iend - ip);
745
0
}