Coverage Report

Created: 2026-04-01 07:49

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/zstd/lib/compress/zstd_ldm.c
Line
Count
Source
1
/*
2
 * Copyright (c) Meta Platforms, Inc. and affiliates.
3
 * All rights reserved.
4
 *
5
 * This source code is licensed under both the BSD-style license (found in the
6
 * LICENSE file in the root directory of this source tree) and the GPLv2 (found
7
 * in the COPYING file in the root directory of this source tree).
8
 * You may select, at your option, one of the above-listed licenses.
9
 */
10
11
#include "zstd_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
        if (params->windowLog <= params->hashRateLog) {
156
0
            params->hashLog = ZSTD_HASHLOG_MIN;
157
0
        } else {
158
0
            params->hashLog = BOUNDED(ZSTD_HASHLOG_MIN, params->windowLog - params->hashRateLog, ZSTD_HASHLOG_MAX);
159
0
        }
160
0
    }
161
0
    if (params->minMatchLength == 0) {
162
0
        params->minMatchLength = LDM_MIN_MATCH_LENGTH;
163
0
        if (cParams->strategy >= ZSTD_btultra)
164
0
            params->minMatchLength /= 2;
165
0
    }
166
0
    if (params->bucketSizeLog==0) {
167
0
        assert(1 <= (int)cParams->strategy && (int)cParams->strategy <= 9);
168
0
        params->bucketSizeLog = BOUNDED(LDM_BUCKET_SIZE_LOG, (U32)cParams->strategy, ZSTD_LDM_BUCKETSIZELOG_MAX);
169
0
    }
170
0
    params->bucketSizeLog = MIN(params->bucketSizeLog, params->hashLog);
171
0
}
172
173
size_t ZSTD_ldm_getTableSize(ldmParams_t params)
174
2.97k
{
175
2.97k
    size_t const ldmHSize = ((size_t)1) << params.hashLog;
176
2.97k
    size_t const ldmBucketSizeLog = MIN(params.bucketSizeLog, params.hashLog);
177
2.97k
    size_t const ldmBucketSize = ((size_t)1) << (params.hashLog - ldmBucketSizeLog);
178
2.97k
    size_t const totalSize = ZSTD_cwksp_alloc_size(ldmBucketSize)
179
2.97k
                           + ZSTD_cwksp_alloc_size(ldmHSize * sizeof(ldmEntry_t));
180
2.97k
    return params.enableLdm == ZSTD_ps_enable ? totalSize : 0;
181
2.97k
}
182
183
size_t ZSTD_ldm_getMaxNbSeq(ldmParams_t params, size_t maxChunkSize)
184
5.95k
{
185
5.95k
    return params.enableLdm == ZSTD_ps_enable ? (maxChunkSize / params.minMatchLength) : 0;
186
5.95k
}
187
188
/** ZSTD_ldm_getBucket() :
189
 *  Returns a pointer to the start of the bucket associated with hash. */
190
static ldmEntry_t* ZSTD_ldm_getBucket(
191
        const ldmState_t* ldmState, size_t hash, U32 const bucketSizeLog)
192
0
{
193
0
    return ldmState->hashTable + (hash << bucketSizeLog);
194
0
}
195
196
/** ZSTD_ldm_insertEntry() :
197
 *  Insert the entry with corresponding hash into the hash table */
198
static void ZSTD_ldm_insertEntry(ldmState_t* ldmState,
199
                                 size_t const hash, const ldmEntry_t entry,
200
                                 U32 const bucketSizeLog)
201
0
{
202
0
    BYTE* const pOffset = ldmState->bucketOffsets + hash;
203
0
    unsigned const offset = *pOffset;
204
205
0
    *(ZSTD_ldm_getBucket(ldmState, hash, bucketSizeLog) + offset) = entry;
206
0
    *pOffset = (BYTE)((offset + 1) & ((1u << bucketSizeLog) - 1));
207
208
0
}
209
210
/** ZSTD_ldm_countBackwardsMatch() :
211
 *  Returns the number of bytes that match backwards before pIn and pMatch.
212
 *
213
 *  We count only bytes where pMatch >= pBase and pIn >= pAnchor. */
214
static size_t ZSTD_ldm_countBackwardsMatch(
215
            const BYTE* pIn, const BYTE* pAnchor,
216
            const BYTE* pMatch, const BYTE* pMatchBase)
217
0
{
218
0
    size_t matchLength = 0;
219
0
    while (pIn > pAnchor && pMatch > pMatchBase && pIn[-1] == pMatch[-1]) {
220
0
        pIn--;
221
0
        pMatch--;
222
0
        matchLength++;
223
0
    }
224
0
    return matchLength;
225
0
}
226
227
/** ZSTD_ldm_countBackwardsMatch_2segments() :
228
 *  Returns the number of bytes that match backwards from pMatch,
229
 *  even with the backwards match spanning 2 different segments.
230
 *
231
 *  On reaching `pMatchBase`, start counting from mEnd */
232
static size_t ZSTD_ldm_countBackwardsMatch_2segments(
233
                    const BYTE* pIn, const BYTE* pAnchor,
234
                    const BYTE* pMatch, const BYTE* pMatchBase,
235
                    const BYTE* pExtDictStart, const BYTE* pExtDictEnd)
236
0
{
237
0
    size_t matchLength = ZSTD_ldm_countBackwardsMatch(pIn, pAnchor, pMatch, pMatchBase);
238
0
    if (pMatch - matchLength != pMatchBase || pMatchBase == pExtDictStart) {
239
        /* If backwards match is entirely in the extDict or prefix, immediately return */
240
0
        return matchLength;
241
0
    }
242
0
    DEBUGLOG(7, "ZSTD_ldm_countBackwardsMatch_2segments: found 2-parts backwards match (length in prefix==%zu)", matchLength);
243
0
    matchLength += ZSTD_ldm_countBackwardsMatch(pIn - matchLength, pAnchor, pExtDictEnd, pExtDictStart);
244
0
    DEBUGLOG(7, "final backwards match length = %zu", matchLength);
245
0
    return matchLength;
246
0
}
247
248
/** ZSTD_ldm_fillFastTables() :
249
 *
250
 *  Fills the relevant tables for the ZSTD_fast and ZSTD_dfast strategies.
251
 *  This is similar to ZSTD_loadDictionaryContent.
252
 *
253
 *  The tables for the other strategies are filled within their
254
 *  block compressors. */
255
static size_t ZSTD_ldm_fillFastTables(ZSTD_MatchState_t* ms,
256
                                      void const* end)
257
0
{
258
0
    const BYTE* const iend = (const BYTE*)end;
259
260
0
    switch(ms->cParams.strategy)
261
0
    {
262
0
    case ZSTD_fast:
263
0
        ZSTD_fillHashTable(ms, iend, ZSTD_dtlm_fast, ZSTD_tfp_forCCtx);
264
0
        break;
265
266
0
    case ZSTD_dfast:
267
0
#ifndef ZSTD_EXCLUDE_DFAST_BLOCK_COMPRESSOR
268
0
        ZSTD_fillDoubleHashTable(ms, iend, ZSTD_dtlm_fast, ZSTD_tfp_forCCtx);
269
#else
270
        assert(0); /* shouldn't be called: cparams should've been adjusted. */
271
#endif
272
0
        break;
273
274
0
    case ZSTD_greedy:
275
0
    case ZSTD_lazy:
276
0
    case ZSTD_lazy2:
277
0
    case ZSTD_btlazy2:
278
0
    case ZSTD_btopt:
279
0
    case ZSTD_btultra:
280
0
    case ZSTD_btultra2:
281
0
        break;
282
0
    default:
283
0
        assert(0);  /* not possible : not a valid strategy id */
284
0
    }
285
286
0
    return 0;
287
0
}
288
289
void ZSTD_ldm_fillHashTable(
290
            ldmState_t* ldmState, const BYTE* ip,
291
            const BYTE* iend, ldmParams_t const* params)
292
0
{
293
0
    U32 const minMatchLength = params->minMatchLength;
294
0
    U32 const bucketSizeLog = params->bucketSizeLog;
295
0
    U32 const hBits = params->hashLog - bucketSizeLog;
296
0
    BYTE const* const base = ldmState->window.base;
297
0
    BYTE const* const istart = ip;
298
0
    ldmRollingHashState_t hashState;
299
0
    size_t* const splits = ldmState->splitIndices;
300
0
    unsigned numSplits;
301
302
0
    DEBUGLOG(5, "ZSTD_ldm_fillHashTable");
303
304
0
    ZSTD_ldm_gear_init(&hashState, params);
305
0
    while (ip < iend) {
306
0
        size_t hashed;
307
0
        unsigned n;
308
309
0
        numSplits = 0;
310
0
        hashed = ZSTD_ldm_gear_feed(&hashState, ip, (size_t)(iend - ip), splits, &numSplits);
311
312
0
        for (n = 0; n < numSplits; n++) {
313
0
            if (ip + splits[n] >= istart + minMatchLength) {
314
0
                BYTE const* const split = ip + splits[n] - minMatchLength;
315
0
                U64 const xxhash = XXH64(split, minMatchLength, 0);
316
0
                U32 const hash = (U32)(xxhash & (((U32)1 << hBits) - 1));
317
0
                ldmEntry_t entry;
318
319
0
                entry.offset = (U32)(split - base);
320
0
                entry.checksum = (U32)(xxhash >> 32);
321
0
                ZSTD_ldm_insertEntry(ldmState, hash, entry, params->bucketSizeLog);
322
0
            }
323
0
        }
324
325
0
        ip += hashed;
326
0
    }
327
0
}
328
329
330
/** ZSTD_ldm_limitTableUpdate() :
331
 *
332
 *  Sets cctx->nextToUpdate to a position corresponding closer to anchor
333
 *  if it is far way
334
 *  (after a long match, only update tables a limited amount). */
335
static void ZSTD_ldm_limitTableUpdate(ZSTD_MatchState_t* ms, const BYTE* anchor)
336
0
{
337
0
    U32 const curr = (U32)(anchor - ms->window.base);
338
0
    if (curr > ms->nextToUpdate + 1024) {
339
0
        ms->nextToUpdate =
340
0
            curr - MIN(512, curr - ms->nextToUpdate - 1024);
341
0
    }
342
0
}
343
344
static
345
ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
346
size_t ZSTD_ldm_generateSequences_internal(
347
        ldmState_t* ldmState, RawSeqStore_t* rawSeqStore,
348
        ldmParams_t const* params, void const* src, size_t srcSize)
349
0
{
350
    /* LDM parameters */
351
0
    int const extDict = ZSTD_window_hasExtDict(ldmState->window);
352
0
    U32 const minMatchLength = params->minMatchLength;
353
0
    U32 const entsPerBucket = 1U << params->bucketSizeLog;
354
0
    U32 const hBits = params->hashLog - params->bucketSizeLog;
355
    /* Prefix and extDict parameters */
356
0
    U32 const dictLimit = ldmState->window.dictLimit;
357
0
    U32 const lowestIndex = extDict ? ldmState->window.lowLimit : dictLimit;
358
0
    BYTE const* const base = ldmState->window.base;
359
0
    BYTE const* const dictBase = extDict ? ldmState->window.dictBase : NULL;
360
0
    BYTE const* const dictStart = extDict ? dictBase + lowestIndex : NULL;
361
0
    BYTE const* const dictEnd = extDict ? dictBase + dictLimit : NULL;
362
0
    BYTE const* const lowPrefixPtr = base + dictLimit;
363
    /* Input bounds */
364
0
    BYTE const* const istart = (BYTE const*)src;
365
0
    BYTE const* const iend = istart + srcSize;
366
0
    BYTE const* const ilimit = iend - HASH_READ_SIZE;
367
    /* Input positions */
368
0
    BYTE const* anchor = istart;
369
0
    BYTE const* ip = istart;
370
    /* Rolling hash state */
371
0
    ldmRollingHashState_t hashState;
372
    /* Arrays for staged-processing */
373
0
    size_t* const splits = ldmState->splitIndices;
374
0
    ldmMatchCandidate_t* const candidates = ldmState->matchCandidates;
375
0
    unsigned numSplits;
376
377
0
    if (srcSize < minMatchLength)
378
0
        return iend - anchor;
379
380
    /* Initialize the rolling hash state with the first minMatchLength bytes */
381
0
    ZSTD_ldm_gear_init(&hashState, params);
382
0
    ZSTD_ldm_gear_reset(&hashState, ip, minMatchLength);
383
0
    ip += minMatchLength;
384
385
0
    while (ip < ilimit) {
386
0
        size_t hashed;
387
0
        unsigned n;
388
389
0
        numSplits = 0;
390
0
        hashed = ZSTD_ldm_gear_feed(&hashState, ip, ilimit - ip,
391
0
                                    splits, &numSplits);
392
393
0
        for (n = 0; n < numSplits; n++) {
394
0
            BYTE const* const split = ip + splits[n] - minMatchLength;
395
0
            U64 const xxhash = XXH64(split, minMatchLength, 0);
396
0
            U32 const hash = (U32)(xxhash & (((U32)1 << hBits) - 1));
397
398
0
            candidates[n].split = split;
399
0
            candidates[n].hash = hash;
400
0
            candidates[n].checksum = (U32)(xxhash >> 32);
401
0
            candidates[n].bucket = ZSTD_ldm_getBucket(ldmState, hash, params->bucketSizeLog);
402
0
            PREFETCH_L1(candidates[n].bucket);
403
0
        }
404
405
0
        for (n = 0; n < numSplits; n++) {
406
0
            size_t forwardMatchLength = 0, backwardMatchLength = 0,
407
0
                   bestMatchLength = 0, mLength;
408
0
            U32 offset;
409
0
            BYTE const* const split = candidates[n].split;
410
0
            U32 const checksum = candidates[n].checksum;
411
0
            U32 const hash = candidates[n].hash;
412
0
            ldmEntry_t* const bucket = candidates[n].bucket;
413
0
            ldmEntry_t const* cur;
414
0
            ldmEntry_t const* bestEntry = NULL;
415
0
            ldmEntry_t newEntry;
416
417
0
            newEntry.offset = (U32)(split - base);
418
0
            newEntry.checksum = checksum;
419
420
            /* If a split point would generate a sequence overlapping with
421
             * the previous one, we merely register it in the hash table and
422
             * move on */
423
0
            if (split < anchor) {
424
0
                ZSTD_ldm_insertEntry(ldmState, hash, newEntry, params->bucketSizeLog);
425
0
                continue;
426
0
            }
427
428
0
            for (cur = bucket; cur < bucket + entsPerBucket; cur++) {
429
0
                size_t curForwardMatchLength, curBackwardMatchLength,
430
0
                       curTotalMatchLength;
431
0
                if (cur->checksum != checksum || cur->offset <= lowestIndex) {
432
0
                    continue;
433
0
                }
434
0
                if (extDict) {
435
0
                    BYTE const* const curMatchBase =
436
0
                        cur->offset < dictLimit ? dictBase : base;
437
0
                    BYTE const* const pMatch = curMatchBase + cur->offset;
438
0
                    BYTE const* const matchEnd =
439
0
                        cur->offset < dictLimit ? dictEnd : iend;
440
0
                    BYTE const* const lowMatchPtr =
441
0
                        cur->offset < dictLimit ? dictStart : lowPrefixPtr;
442
0
                    curForwardMatchLength =
443
0
                        ZSTD_count_2segments(split, pMatch, iend, matchEnd, lowPrefixPtr);
444
0
                    if (curForwardMatchLength < minMatchLength) {
445
0
                        continue;
446
0
                    }
447
0
                    curBackwardMatchLength = ZSTD_ldm_countBackwardsMatch_2segments(
448
0
                            split, anchor, pMatch, lowMatchPtr, dictStart, dictEnd);
449
0
                } else { /* !extDict */
450
0
                    BYTE const* const pMatch = base + cur->offset;
451
0
                    curForwardMatchLength = ZSTD_count(split, pMatch, iend);
452
0
                    if (curForwardMatchLength < minMatchLength) {
453
0
                        continue;
454
0
                    }
455
0
                    curBackwardMatchLength =
456
0
                        ZSTD_ldm_countBackwardsMatch(split, anchor, pMatch, lowPrefixPtr);
457
0
                }
458
0
                curTotalMatchLength = curForwardMatchLength + curBackwardMatchLength;
459
460
0
                if (curTotalMatchLength > bestMatchLength) {
461
0
                    bestMatchLength = curTotalMatchLength;
462
0
                    forwardMatchLength = curForwardMatchLength;
463
0
                    backwardMatchLength = curBackwardMatchLength;
464
0
                    bestEntry = cur;
465
0
                }
466
0
            }
467
468
            /* No match found -- insert an entry into the hash table
469
             * and process the next candidate match */
470
0
            if (bestEntry == NULL) {
471
0
                ZSTD_ldm_insertEntry(ldmState, hash, newEntry, params->bucketSizeLog);
472
0
                continue;
473
0
            }
474
475
            /* Match found */
476
0
            offset = (U32)(split - base) - bestEntry->offset;
477
0
            mLength = forwardMatchLength + backwardMatchLength;
478
0
            {
479
0
                rawSeq* const seq = rawSeqStore->seq + rawSeqStore->size;
480
481
                /* Out of sequence storage */
482
0
                if (rawSeqStore->size == rawSeqStore->capacity)
483
0
                    return ERROR(dstSize_tooSmall);
484
0
                seq->litLength = (U32)(split - backwardMatchLength - anchor);
485
0
                seq->matchLength = (U32)mLength;
486
0
                seq->offset = offset;
487
0
                rawSeqStore->size++;
488
0
            }
489
490
            /* Insert the current entry into the hash table --- it must be
491
             * done after the previous block to avoid clobbering bestEntry */
492
0
            ZSTD_ldm_insertEntry(ldmState, hash, newEntry, params->bucketSizeLog);
493
494
0
            anchor = split + forwardMatchLength;
495
496
            /* If we find a match that ends after the data that we've hashed
497
             * then we have a repeating, overlapping, pattern. E.g. all zeros.
498
             * If one repetition of the pattern matches our `stopMask` then all
499
             * repetitions will. We don't need to insert them all into out table,
500
             * only the first one. So skip over overlapping matches.
501
             * This is a major speed boost (20x) for compressing a single byte
502
             * repeated, when that byte ends up in the table.
503
             */
504
0
            if (anchor > ip + hashed) {
505
0
                ZSTD_ldm_gear_reset(&hashState, anchor - minMatchLength, minMatchLength);
506
                /* Continue the outer loop at anchor (ip + hashed == anchor). */
507
0
                ip = anchor - hashed;
508
0
                break;
509
0
            }
510
0
        }
511
512
0
        ip += hashed;
513
0
    }
514
515
0
    return iend - anchor;
516
0
}
517
518
/*! ZSTD_ldm_reduceTable() :
519
 *  reduce table indexes by `reducerValue` */
520
static void ZSTD_ldm_reduceTable(ldmEntry_t* const table, U32 const size,
521
                                 U32 const reducerValue)
522
0
{
523
0
    U32 u;
524
0
    for (u = 0; u < size; u++) {
525
0
        if (table[u].offset < reducerValue) table[u].offset = 0;
526
0
        else table[u].offset -= reducerValue;
527
0
    }
528
0
}
529
530
size_t ZSTD_ldm_generateSequences(
531
        ldmState_t* ldmState, RawSeqStore_t* sequences,
532
        ldmParams_t const* params, void const* src, size_t srcSize)
533
0
{
534
0
    U32 const maxDist = 1U << params->windowLog;
535
0
    BYTE const* const istart = (BYTE const*)src;
536
0
    BYTE const* const iend = istart + srcSize;
537
0
    size_t const kMaxChunkSize = 1 << 20;
538
0
    size_t const nbChunks = (srcSize / kMaxChunkSize) + ((srcSize % kMaxChunkSize) != 0);
539
0
    size_t chunk;
540
0
    size_t leftoverSize = 0;
541
542
0
    assert(ZSTD_CHUNKSIZE_MAX >= kMaxChunkSize);
543
    /* Check that ZSTD_window_update() has been called for this chunk prior
544
     * to passing it to this function.
545
     */
546
0
    assert(ldmState->window.nextSrc >= (BYTE const*)src + srcSize);
547
    /* The input could be very large (in zstdmt), so it must be broken up into
548
     * chunks to enforce the maximum distance and handle overflow correction.
549
     */
550
0
    assert(sequences->pos <= sequences->size);
551
0
    assert(sequences->size <= sequences->capacity);
552
0
    for (chunk = 0; chunk < nbChunks && sequences->size < sequences->capacity; ++chunk) {
553
0
        BYTE const* const chunkStart = istart + chunk * kMaxChunkSize;
554
0
        size_t const remaining = (size_t)(iend - chunkStart);
555
0
        BYTE const *const chunkEnd =
556
0
            (remaining < kMaxChunkSize) ? iend : chunkStart + kMaxChunkSize;
557
0
        size_t const chunkSize = chunkEnd - chunkStart;
558
0
        size_t newLeftoverSize;
559
0
        size_t const prevSize = sequences->size;
560
561
0
        assert(chunkStart < iend);
562
        /* 1. Perform overflow correction if necessary. */
563
0
        if (ZSTD_window_needOverflowCorrection(ldmState->window, 0, maxDist, ldmState->loadedDictEnd, chunkStart, chunkEnd)) {
564
0
            U32 const ldmHSize = 1U << params->hashLog;
565
0
            U32 const correction = ZSTD_window_correctOverflow(
566
0
                &ldmState->window, /* cycleLog */ 0, maxDist, chunkStart);
567
0
            ZSTD_ldm_reduceTable(ldmState->hashTable, ldmHSize, correction);
568
            /* invalidate dictionaries on overflow correction */
569
0
            ldmState->loadedDictEnd = 0;
570
0
        }
571
        /* 2. We enforce the maximum offset allowed.
572
         *
573
         * kMaxChunkSize should be small enough that we don't lose too much of
574
         * the window through early invalidation.
575
         * TODO: * Test the chunk size.
576
         *       * Try invalidation after the sequence generation and test the
577
         *         offset against maxDist directly.
578
         *
579
         * NOTE: Because of dictionaries + sequence splitting we MUST make sure
580
         * that any offset used is valid at the END of the sequence, since it may
581
         * be split into two sequences. This condition holds when using
582
         * ZSTD_window_enforceMaxDist(), but if we move to checking offsets
583
         * against maxDist directly, we'll have to carefully handle that case.
584
         */
585
0
        ZSTD_window_enforceMaxDist(&ldmState->window, chunkEnd, maxDist, &ldmState->loadedDictEnd, NULL);
586
        /* 3. Generate the sequences for the chunk, and get newLeftoverSize. */
587
0
        newLeftoverSize = ZSTD_ldm_generateSequences_internal(
588
0
            ldmState, sequences, params, chunkStart, chunkSize);
589
0
        if (ZSTD_isError(newLeftoverSize))
590
0
            return newLeftoverSize;
591
        /* 4. We add the leftover literals from previous iterations to the first
592
         *    newly generated sequence, or add the `newLeftoverSize` if none are
593
         *    generated.
594
         */
595
        /* Prepend the leftover literals from the last call */
596
0
        if (prevSize < sequences->size) {
597
0
            sequences->seq[prevSize].litLength += (U32)leftoverSize;
598
0
            leftoverSize = newLeftoverSize;
599
0
        } else {
600
0
            assert(newLeftoverSize == chunkSize);
601
0
            leftoverSize += chunkSize;
602
0
        }
603
0
    }
604
0
    return 0;
605
0
}
606
607
void
608
ZSTD_ldm_skipSequences(RawSeqStore_t* rawSeqStore, size_t srcSize, U32 const minMatch)
609
6
{
610
6
    while (srcSize > 0 && rawSeqStore->pos < rawSeqStore->size) {
611
0
        rawSeq* seq = rawSeqStore->seq + rawSeqStore->pos;
612
0
        if (srcSize <= seq->litLength) {
613
            /* Skip past srcSize literals */
614
0
            seq->litLength -= (U32)srcSize;
615
0
            return;
616
0
        }
617
0
        srcSize -= seq->litLength;
618
0
        seq->litLength = 0;
619
0
        if (srcSize < seq->matchLength) {
620
            /* Skip past the first srcSize of the match */
621
0
            seq->matchLength -= (U32)srcSize;
622
0
            if (seq->matchLength < minMatch) {
623
                /* The match is too short, omit it */
624
0
                if (rawSeqStore->pos + 1 < rawSeqStore->size) {
625
0
                    seq[1].litLength += seq[0].matchLength;
626
0
                }
627
0
                rawSeqStore->pos++;
628
0
            }
629
0
            return;
630
0
        }
631
0
        srcSize -= seq->matchLength;
632
0
        seq->matchLength = 0;
633
0
        rawSeqStore->pos++;
634
0
    }
635
6
}
636
637
/**
638
 * If the sequence length is longer than remaining then the sequence is split
639
 * between this block and the next.
640
 *
641
 * Returns the current sequence to handle, or if the rest of the block should
642
 * be literals, it returns a sequence with offset == 0.
643
 */
644
static rawSeq maybeSplitSequence(RawSeqStore_t* rawSeqStore,
645
                                 U32 const remaining, U32 const minMatch)
646
0
{
647
0
    rawSeq sequence = rawSeqStore->seq[rawSeqStore->pos];
648
0
    assert(sequence.offset > 0);
649
    /* Likely: No partial sequence */
650
0
    if (remaining >= sequence.litLength + sequence.matchLength) {
651
0
        rawSeqStore->pos++;
652
0
        return sequence;
653
0
    }
654
    /* Cut the sequence short (offset == 0 ==> rest is literals). */
655
0
    if (remaining <= sequence.litLength) {
656
0
        sequence.offset = 0;
657
0
    } else if (remaining < sequence.litLength + sequence.matchLength) {
658
0
        sequence.matchLength = remaining - sequence.litLength;
659
0
        if (sequence.matchLength < minMatch) {
660
0
            sequence.offset = 0;
661
0
        }
662
0
    }
663
    /* Skip past `remaining` bytes for the future sequences. */
664
0
    ZSTD_ldm_skipSequences(rawSeqStore, remaining, minMatch);
665
0
    return sequence;
666
0
}
667
668
0
void ZSTD_ldm_skipRawSeqStoreBytes(RawSeqStore_t* rawSeqStore, size_t nbBytes) {
669
0
    U32 currPos = (U32)(rawSeqStore->posInSequence + nbBytes);
670
0
    while (currPos && rawSeqStore->pos < rawSeqStore->size) {
671
0
        rawSeq currSeq = rawSeqStore->seq[rawSeqStore->pos];
672
0
        if (currPos >= currSeq.litLength + currSeq.matchLength) {
673
0
            currPos -= currSeq.litLength + currSeq.matchLength;
674
0
            rawSeqStore->pos++;
675
0
        } else {
676
0
            rawSeqStore->posInSequence = currPos;
677
0
            break;
678
0
        }
679
0
    }
680
0
    if (currPos == 0 || rawSeqStore->pos == rawSeqStore->size) {
681
0
        rawSeqStore->posInSequence = 0;
682
0
    }
683
0
}
684
685
size_t ZSTD_ldm_blockCompress(RawSeqStore_t* rawSeqStore,
686
    ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
687
    ZSTD_ParamSwitch_e useRowMatchFinder,
688
    void const* src, size_t srcSize)
689
0
{
690
0
    const ZSTD_compressionParameters* const cParams = &ms->cParams;
691
0
    unsigned const minMatch = cParams->minMatch;
692
0
    ZSTD_BlockCompressor_f const blockCompressor =
693
0
        ZSTD_selectBlockCompressor(cParams->strategy, useRowMatchFinder, ZSTD_matchState_dictMode(ms));
694
    /* Input bounds */
695
0
    BYTE const* const istart = (BYTE const*)src;
696
0
    BYTE const* const iend = istart + srcSize;
697
    /* Input positions */
698
0
    BYTE const* ip = istart;
699
700
0
    DEBUGLOG(5, "ZSTD_ldm_blockCompress: srcSize=%zu", srcSize);
701
    /* If using opt parser, use LDMs only as candidates rather than always accepting them */
702
0
    if (cParams->strategy >= ZSTD_btopt) {
703
0
        size_t lastLLSize;
704
0
        ms->ldmSeqStore = rawSeqStore;
705
0
        lastLLSize = blockCompressor(ms, seqStore, rep, src, srcSize);
706
0
        ZSTD_ldm_skipRawSeqStoreBytes(rawSeqStore, srcSize);
707
0
        return lastLLSize;
708
0
    }
709
710
0
    assert(rawSeqStore->pos <= rawSeqStore->size);
711
0
    assert(rawSeqStore->size <= rawSeqStore->capacity);
712
    /* Loop through each sequence and apply the block compressor to the literals */
713
0
    while (rawSeqStore->pos < rawSeqStore->size && ip < iend) {
714
        /* maybeSplitSequence updates rawSeqStore->pos */
715
0
        rawSeq const sequence = maybeSplitSequence(rawSeqStore,
716
0
                                                   (U32)(iend - ip), minMatch);
717
        /* End signal */
718
0
        if (sequence.offset == 0)
719
0
            break;
720
721
0
        assert(ip + sequence.litLength + sequence.matchLength <= iend);
722
723
        /* Fill tables for block compressor */
724
0
        ZSTD_ldm_limitTableUpdate(ms, ip);
725
0
        ZSTD_ldm_fillFastTables(ms, ip);
726
        /* Run the block compressor */
727
0
        DEBUGLOG(5, "pos %u : calling block compressor on segment of size %u", (unsigned)(ip-istart), sequence.litLength);
728
0
        {
729
0
            int i;
730
0
            size_t const newLitLength =
731
0
                blockCompressor(ms, seqStore, rep, ip, sequence.litLength);
732
0
            ip += sequence.litLength;
733
            /* Update the repcodes */
734
0
            for (i = ZSTD_REP_NUM - 1; i > 0; i--)
735
0
                rep[i] = rep[i-1];
736
0
            rep[0] = sequence.offset;
737
            /* Store the sequence */
738
0
            ZSTD_storeSeq(seqStore, newLitLength, ip - newLitLength, iend,
739
0
                          OFFSET_TO_OFFBASE(sequence.offset),
740
0
                          sequence.matchLength);
741
0
            ip += sequence.matchLength;
742
0
        }
743
0
    }
744
    /* Fill the tables for the block compressor */
745
0
    ZSTD_ldm_limitTableUpdate(ms, ip);
746
0
    ZSTD_ldm_fillFastTables(ms, ip);
747
    /* Compress the last literals */
748
0
    return blockCompressor(ms, seqStore, rep, ip, iend - ip);
749
0
}