Coverage Report

Created: 2025-07-23 08:18

/src/zstd/lib/compress/zstd_compress.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
/*-*************************************
12
*  Dependencies
13
***************************************/
14
#include "../common/allocations.h"  /* ZSTD_customMalloc, ZSTD_customCalloc, ZSTD_customFree */
15
#include "../common/zstd_deps.h"  /* INT_MAX, ZSTD_memset, ZSTD_memcpy */
16
#include "../common/mem.h"
17
#include "../common/error_private.h"
18
#include "hist.h"           /* HIST_countFast_wksp */
19
#define FSE_STATIC_LINKING_ONLY   /* FSE_encodeSymbol */
20
#include "../common/fse.h"
21
#include "../common/huf.h"
22
#include "zstd_compress_internal.h"
23
#include "zstd_compress_sequences.h"
24
#include "zstd_compress_literals.h"
25
#include "zstd_fast.h"
26
#include "zstd_double_fast.h"
27
#include "zstd_lazy.h"
28
#include "zstd_opt.h"
29
#include "zstd_ldm.h"
30
#include "zstd_compress_superblock.h"
31
#include  "../common/bits.h"      /* ZSTD_highbit32, ZSTD_rotateRight_U64 */
32
33
/* ***************************************************************
34
*  Tuning parameters
35
*****************************************************************/
36
/*!
37
 * COMPRESS_HEAPMODE :
38
 * Select how default decompression function ZSTD_compress() allocates its context,
39
 * on stack (0, default), or into heap (1).
40
 * Note that functions with explicit context such as ZSTD_compressCCtx() are unaffected.
41
 */
42
#ifndef ZSTD_COMPRESS_HEAPMODE
43
#  define ZSTD_COMPRESS_HEAPMODE 0
44
#endif
45
46
/*!
47
 * ZSTD_HASHLOG3_MAX :
48
 * Maximum size of the hash table dedicated to find 3-bytes matches,
49
 * in log format, aka 17 => 1 << 17 == 128Ki positions.
50
 * This structure is only used in zstd_opt.
51
 * Since allocation is centralized for all strategies, it has to be known here.
52
 * The actual (selected) size of the hash table is then stored in ZSTD_MatchState_t.hashLog3,
53
 * so that zstd_opt.c doesn't need to know about this constant.
54
 */
55
#ifndef ZSTD_HASHLOG3_MAX
56
#  define ZSTD_HASHLOG3_MAX 17
57
#endif
58
59
60
/*-*************************************
61
*  Forward declarations
62
***************************************/
63
size_t convertSequences_noRepcodes(SeqDef* dstSeqs, const ZSTD_Sequence* inSeqs,
64
    size_t nbSequences);
65
66
67
/*-*************************************
68
*  Helper functions
69
***************************************/
70
/* ZSTD_compressBound()
71
 * Note that the result from this function is only valid for
72
 * the one-pass compression functions.
73
 * When employing the streaming mode,
74
 * if flushes are frequently altering the size of blocks,
75
 * the overhead from block headers can make the compressed data larger
76
 * than the return value of ZSTD_compressBound().
77
 */
78
78.9k
size_t ZSTD_compressBound(size_t srcSize) {
79
78.9k
    size_t const r = ZSTD_COMPRESSBOUND(srcSize);
80
78.9k
    if (r==0) return ERROR(srcSize_wrong);
81
78.9k
    return r;
82
78.9k
}
83
84
85
/*-*************************************
86
*  Context memory management
87
***************************************/
88
struct ZSTD_CDict_s {
89
    const void* dictContent;
90
    size_t dictContentSize;
91
    ZSTD_dictContentType_e dictContentType; /* The dictContentType the CDict was created with */
92
    U32* entropyWorkspace; /* entropy workspace of HUF_WORKSPACE_SIZE bytes */
93
    ZSTD_cwksp workspace;
94
    ZSTD_MatchState_t matchState;
95
    ZSTD_compressedBlockState_t cBlockState;
96
    ZSTD_customMem customMem;
97
    U32 dictID;
98
    int compressionLevel; /* 0 indicates that advanced API was used to select CDict params */
99
    ZSTD_ParamSwitch_e useRowMatchFinder; /* Indicates whether the CDict was created with params that would use
100
                                           * row-based matchfinder. Unless the cdict is reloaded, we will use
101
                                           * the same greedy/lazy matchfinder at compression time.
102
                                           */
103
};  /* typedef'd to ZSTD_CDict within "zstd.h" */
104
105
ZSTD_CCtx* ZSTD_createCCtx(void)
106
0
{
107
0
    return ZSTD_createCCtx_advanced(ZSTD_defaultCMem);
108
0
}
109
110
static void ZSTD_initCCtx(ZSTD_CCtx* cctx, ZSTD_customMem memManager)
111
6.05k
{
112
6.05k
    assert(cctx != NULL);
113
6.05k
    ZSTD_memset(cctx, 0, sizeof(*cctx));
114
6.05k
    cctx->customMem = memManager;
115
6.05k
    cctx->bmi2 = ZSTD_cpuSupportsBmi2();
116
6.05k
    {   size_t const err = ZSTD_CCtx_reset(cctx, ZSTD_reset_parameters);
117
6.05k
        assert(!ZSTD_isError(err));
118
6.05k
        (void)err;
119
6.05k
    }
120
6.05k
}
121
122
ZSTD_CCtx* ZSTD_createCCtx_advanced(ZSTD_customMem customMem)
123
6.05k
{
124
6.05k
    ZSTD_STATIC_ASSERT(zcss_init==0);
125
6.05k
    ZSTD_STATIC_ASSERT(ZSTD_CONTENTSIZE_UNKNOWN==(0ULL - 1));
126
6.05k
    if ((!customMem.customAlloc) ^ (!customMem.customFree)) return NULL;
127
6.05k
    {   ZSTD_CCtx* const cctx = (ZSTD_CCtx*)ZSTD_customMalloc(sizeof(ZSTD_CCtx), customMem);
128
6.05k
        if (!cctx) return NULL;
129
6.05k
        ZSTD_initCCtx(cctx, customMem);
130
6.05k
        return cctx;
131
6.05k
    }
132
6.05k
}
133
134
ZSTD_CCtx* ZSTD_initStaticCCtx(void* workspace, size_t workspaceSize)
135
0
{
136
0
    ZSTD_cwksp ws;
137
0
    ZSTD_CCtx* cctx;
138
0
    if (workspaceSize <= sizeof(ZSTD_CCtx)) return NULL;  /* minimum size */
139
0
    if ((size_t)workspace & 7) return NULL;  /* must be 8-aligned */
140
0
    ZSTD_cwksp_init(&ws, workspace, workspaceSize, ZSTD_cwksp_static_alloc);
141
142
0
    cctx = (ZSTD_CCtx*)ZSTD_cwksp_reserve_object(&ws, sizeof(ZSTD_CCtx));
143
0
    if (cctx == NULL) return NULL;
144
145
0
    ZSTD_memset(cctx, 0, sizeof(ZSTD_CCtx));
146
0
    ZSTD_cwksp_move(&cctx->workspace, &ws);
147
0
    cctx->staticSize = workspaceSize;
148
149
    /* statically sized space. tmpWorkspace never moves (but prev/next block swap places) */
150
0
    if (!ZSTD_cwksp_check_available(&cctx->workspace, TMP_WORKSPACE_SIZE + 2 * sizeof(ZSTD_compressedBlockState_t))) return NULL;
151
0
    cctx->blockState.prevCBlock = (ZSTD_compressedBlockState_t*)ZSTD_cwksp_reserve_object(&cctx->workspace, sizeof(ZSTD_compressedBlockState_t));
152
0
    cctx->blockState.nextCBlock = (ZSTD_compressedBlockState_t*)ZSTD_cwksp_reserve_object(&cctx->workspace, sizeof(ZSTD_compressedBlockState_t));
153
0
    cctx->tmpWorkspace = ZSTD_cwksp_reserve_object(&cctx->workspace, TMP_WORKSPACE_SIZE);
154
0
    cctx->tmpWkspSize = TMP_WORKSPACE_SIZE;
155
0
    cctx->bmi2 = ZSTD_cpuid_bmi2(ZSTD_cpuid());
156
0
    return cctx;
157
0
}
158
159
/**
160
 * Clears and frees all of the dictionaries in the CCtx.
161
 */
162
static void ZSTD_clearAllDicts(ZSTD_CCtx* cctx)
163
27.6k
{
164
27.6k
    ZSTD_customFree(cctx->localDict.dictBuffer, cctx->customMem);
165
27.6k
    ZSTD_freeCDict(cctx->localDict.cdict);
166
27.6k
    ZSTD_memset(&cctx->localDict, 0, sizeof(cctx->localDict));
167
27.6k
    ZSTD_memset(&cctx->prefixDict, 0, sizeof(cctx->prefixDict));
168
27.6k
    cctx->cdict = NULL;
169
27.6k
}
170
171
static size_t ZSTD_sizeof_localDict(ZSTD_localDict dict)
172
0
{
173
0
    size_t const bufferSize = dict.dictBuffer != NULL ? dict.dictSize : 0;
174
0
    size_t const cdictSize = ZSTD_sizeof_CDict(dict.cdict);
175
0
    return bufferSize + cdictSize;
176
0
}
177
178
static void ZSTD_freeCCtxContent(ZSTD_CCtx* cctx)
179
6.05k
{
180
6.05k
    assert(cctx != NULL);
181
6.05k
    assert(cctx->staticSize == 0);
182
6.05k
    ZSTD_clearAllDicts(cctx);
183
6.05k
#ifdef ZSTD_MULTITHREAD
184
6.05k
    ZSTDMT_freeCCtx(cctx->mtctx); cctx->mtctx = NULL;
185
6.05k
#endif
186
6.05k
    ZSTD_cwksp_free(&cctx->workspace, cctx->customMem);
187
6.05k
}
188
189
size_t ZSTD_freeCCtx(ZSTD_CCtx* cctx)
190
6.05k
{
191
6.05k
    DEBUGLOG(3, "ZSTD_freeCCtx (address: %p)", (void*)cctx);
192
6.05k
    if (cctx==NULL) return 0;   /* support free on NULL */
193
6.05k
    RETURN_ERROR_IF(cctx->staticSize, memory_allocation,
194
6.05k
                    "not compatible with static CCtx");
195
6.05k
    {   int cctxInWorkspace = ZSTD_cwksp_owns_buffer(&cctx->workspace, cctx);
196
6.05k
        ZSTD_freeCCtxContent(cctx);
197
6.05k
        if (!cctxInWorkspace) ZSTD_customFree(cctx, cctx->customMem);
198
6.05k
    }
199
6.05k
    return 0;
200
6.05k
}
201
202
203
static size_t ZSTD_sizeof_mtctx(const ZSTD_CCtx* cctx)
204
0
{
205
0
#ifdef ZSTD_MULTITHREAD
206
0
    return ZSTDMT_sizeof_CCtx(cctx->mtctx);
207
#else
208
    (void)cctx;
209
    return 0;
210
#endif
211
0
}
212
213
214
size_t ZSTD_sizeof_CCtx(const ZSTD_CCtx* cctx)
215
0
{
216
0
    if (cctx==NULL) return 0;   /* support sizeof on NULL */
217
    /* cctx may be in the workspace */
218
0
    return (cctx->workspace.workspace == cctx ? 0 : sizeof(*cctx))
219
0
           + ZSTD_cwksp_sizeof(&cctx->workspace)
220
0
           + ZSTD_sizeof_localDict(cctx->localDict)
221
0
           + ZSTD_sizeof_mtctx(cctx);
222
0
}
223
224
size_t ZSTD_sizeof_CStream(const ZSTD_CStream* zcs)
225
0
{
226
0
    return ZSTD_sizeof_CCtx(zcs);  /* same object */
227
0
}
228
229
/* private API call, for dictBuilder only */
230
0
const SeqStore_t* ZSTD_getSeqStore(const ZSTD_CCtx* ctx) { return &(ctx->seqStore); }
231
232
/* Returns true if the strategy supports using a row based matchfinder */
233
162k
static int ZSTD_rowMatchFinderSupported(const ZSTD_strategy strategy) {
234
162k
    return (strategy >= ZSTD_greedy && strategy <= ZSTD_lazy2);
235
162k
}
236
237
/* Returns true if the strategy and useRowMatchFinder mode indicate that we will use the row based matchfinder
238
 * for this compression.
239
 */
240
146k
static int ZSTD_rowMatchFinderUsed(const ZSTD_strategy strategy, const ZSTD_ParamSwitch_e mode) {
241
146k
    assert(mode != ZSTD_ps_auto);
242
146k
    return ZSTD_rowMatchFinderSupported(strategy) && (mode == ZSTD_ps_enable);
243
146k
}
244
245
/* Returns row matchfinder usage given an initial mode and cParams */
246
static ZSTD_ParamSwitch_e ZSTD_resolveRowMatchFinderMode(ZSTD_ParamSwitch_e mode,
247
15.4k
                                                         const ZSTD_compressionParameters* const cParams) {
248
#ifdef ZSTD_LINUX_KERNEL
249
    /* The Linux Kernel does not use SIMD, and 128KB is a very common size, e.g. in BtrFS.
250
     * The row match finder is slower for this size without SIMD, so disable it.
251
     */
252
    const unsigned kWindowLogLowerBound = 17;
253
#else
254
15.4k
    const unsigned kWindowLogLowerBound = 14;
255
15.4k
#endif
256
15.4k
    if (mode != ZSTD_ps_auto) return mode; /* if requested enabled, but no SIMD, we still will use row matchfinder */
257
15.4k
    mode = ZSTD_ps_disable;
258
15.4k
    if (!ZSTD_rowMatchFinderSupported(cParams->strategy)) return mode;
259
15.4k
    if (cParams->windowLog > kWindowLogLowerBound) mode = ZSTD_ps_enable;
260
15.4k
    return mode;
261
15.4k
}
262
263
/* Returns block splitter usage (generally speaking, when using slower/stronger compression modes) */
264
static ZSTD_ParamSwitch_e ZSTD_resolveBlockSplitterMode(ZSTD_ParamSwitch_e mode,
265
15.4k
                                                        const ZSTD_compressionParameters* const cParams) {
266
15.4k
    if (mode != ZSTD_ps_auto) return mode;
267
15.4k
    return (cParams->strategy >= ZSTD_btopt && cParams->windowLog >= 17) ? ZSTD_ps_enable : ZSTD_ps_disable;
268
15.4k
}
269
270
/* Returns 1 if the arguments indicate that we should allocate a chainTable, 0 otherwise */
271
static int ZSTD_allocateChainTable(const ZSTD_strategy strategy,
272
                                   const ZSTD_ParamSwitch_e useRowMatchFinder,
273
31.3k
                                   const U32 forDDSDict) {
274
31.3k
    assert(useRowMatchFinder != ZSTD_ps_auto);
275
    /* We always should allocate a chaintable if we are allocating a matchstate for a DDS dictionary matchstate.
276
     * We do not allocate a chaintable if we are using ZSTD_fast, or are using the row-based matchfinder.
277
     */
278
31.3k
    return forDDSDict || ((strategy != ZSTD_fast) && !ZSTD_rowMatchFinderUsed(strategy, useRowMatchFinder));
279
31.3k
}
280
281
/* Returns ZSTD_ps_enable if compression parameters are such that we should
282
 * enable long distance matching (wlog >= 27, strategy >= btopt).
283
 * Returns ZSTD_ps_disable otherwise.
284
 */
285
static ZSTD_ParamSwitch_e ZSTD_resolveEnableLdm(ZSTD_ParamSwitch_e mode,
286
15.4k
                                 const ZSTD_compressionParameters* const cParams) {
287
15.4k
    if (mode != ZSTD_ps_auto) return mode;
288
15.4k
    return (cParams->strategy >= ZSTD_btopt && cParams->windowLog >= 27) ? ZSTD_ps_enable : ZSTD_ps_disable;
289
15.4k
}
290
291
15.4k
static int ZSTD_resolveExternalSequenceValidation(int mode) {
292
15.4k
    return mode;
293
15.4k
}
294
295
/* Resolves maxBlockSize to the default if no value is present. */
296
46.4k
static size_t ZSTD_resolveMaxBlockSize(size_t maxBlockSize) {
297
46.4k
    if (maxBlockSize == 0) {
298
15.4k
        return ZSTD_BLOCKSIZE_MAX;
299
30.9k
    } else {
300
30.9k
        return maxBlockSize;
301
30.9k
    }
302
46.4k
}
303
304
15.4k
static ZSTD_ParamSwitch_e ZSTD_resolveExternalRepcodeSearch(ZSTD_ParamSwitch_e value, int cLevel) {
305
15.4k
    if (value != ZSTD_ps_auto) return value;
306
15.4k
    if (cLevel < 10) {
307
15.4k
        return ZSTD_ps_disable;
308
15.4k
    } else {
309
0
        return ZSTD_ps_enable;
310
0
    }
311
15.4k
}
312
313
/* Returns 1 if compression parameters are such that CDict hashtable and chaintable indices are tagged.
314
 * If so, the tags need to be removed in ZSTD_resetCCtx_byCopyingCDict. */
315
0
static int ZSTD_CDictIndicesAreTagged(const ZSTD_compressionParameters* const cParams) {
316
0
    return cParams->strategy == ZSTD_fast || cParams->strategy == ZSTD_dfast;
317
0
}
318
319
static ZSTD_CCtx_params ZSTD_makeCCtxParamsFromCParams(
320
        ZSTD_compressionParameters cParams)
321
0
{
322
0
    ZSTD_CCtx_params cctxParams;
323
    /* should not matter, as all cParams are presumed properly defined */
324
0
    ZSTD_CCtxParams_init(&cctxParams, ZSTD_CLEVEL_DEFAULT);
325
0
    cctxParams.cParams = cParams;
326
327
    /* Adjust advanced params according to cParams */
328
0
    cctxParams.ldmParams.enableLdm = ZSTD_resolveEnableLdm(cctxParams.ldmParams.enableLdm, &cParams);
329
0
    if (cctxParams.ldmParams.enableLdm == ZSTD_ps_enable) {
330
0
        ZSTD_ldm_adjustParameters(&cctxParams.ldmParams, &cParams);
331
0
        assert(cctxParams.ldmParams.hashLog >= cctxParams.ldmParams.bucketSizeLog);
332
0
        assert(cctxParams.ldmParams.hashRateLog < 32);
333
0
    }
334
0
    cctxParams.postBlockSplitter = ZSTD_resolveBlockSplitterMode(cctxParams.postBlockSplitter, &cParams);
335
0
    cctxParams.useRowMatchFinder = ZSTD_resolveRowMatchFinderMode(cctxParams.useRowMatchFinder, &cParams);
336
0
    cctxParams.validateSequences = ZSTD_resolveExternalSequenceValidation(cctxParams.validateSequences);
337
0
    cctxParams.maxBlockSize = ZSTD_resolveMaxBlockSize(cctxParams.maxBlockSize);
338
0
    cctxParams.searchForExternalRepcodes = ZSTD_resolveExternalRepcodeSearch(cctxParams.searchForExternalRepcodes,
339
0
                                                                             cctxParams.compressionLevel);
340
0
    assert(!ZSTD_checkCParams(cParams));
341
0
    return cctxParams;
342
0
}
343
344
static ZSTD_CCtx_params* ZSTD_createCCtxParams_advanced(
345
        ZSTD_customMem customMem)
346
0
{
347
0
    ZSTD_CCtx_params* params;
348
0
    if ((!customMem.customAlloc) ^ (!customMem.customFree)) return NULL;
349
0
    params = (ZSTD_CCtx_params*)ZSTD_customCalloc(
350
0
            sizeof(ZSTD_CCtx_params), customMem);
351
0
    if (!params) { return NULL; }
352
0
    ZSTD_CCtxParams_init(params, ZSTD_CLEVEL_DEFAULT);
353
0
    params->customMem = customMem;
354
0
    return params;
355
0
}
356
357
ZSTD_CCtx_params* ZSTD_createCCtxParams(void)
358
0
{
359
0
    return ZSTD_createCCtxParams_advanced(ZSTD_defaultCMem);
360
0
}
361
362
size_t ZSTD_freeCCtxParams(ZSTD_CCtx_params* params)
363
0
{
364
0
    if (params == NULL) { return 0; }
365
0
    ZSTD_customFree(params, params->customMem);
366
0
    return 0;
367
0
}
368
369
size_t ZSTD_CCtxParams_reset(ZSTD_CCtx_params* params)
370
6.05k
{
371
6.05k
    return ZSTD_CCtxParams_init(params, ZSTD_CLEVEL_DEFAULT);
372
6.05k
}
373
374
6.05k
size_t ZSTD_CCtxParams_init(ZSTD_CCtx_params* cctxParams, int compressionLevel) {
375
6.05k
    RETURN_ERROR_IF(!cctxParams, GENERIC, "NULL pointer!");
376
6.05k
    ZSTD_memset(cctxParams, 0, sizeof(*cctxParams));
377
6.05k
    cctxParams->compressionLevel = compressionLevel;
378
6.05k
    cctxParams->fParams.contentSizeFlag = 1;
379
6.05k
    return 0;
380
6.05k
}
381
382
0
#define ZSTD_NO_CLEVEL 0
383
384
/**
385
 * Initializes `cctxParams` from `params` and `compressionLevel`.
386
 * @param compressionLevel If params are derived from a compression level then that compression level, otherwise ZSTD_NO_CLEVEL.
387
 */
388
static void
389
ZSTD_CCtxParams_init_internal(ZSTD_CCtx_params* cctxParams,
390
                        const ZSTD_parameters* params,
391
                              int compressionLevel)
392
0
{
393
0
    assert(!ZSTD_checkCParams(params->cParams));
394
0
    ZSTD_memset(cctxParams, 0, sizeof(*cctxParams));
395
0
    cctxParams->cParams = params->cParams;
396
0
    cctxParams->fParams = params->fParams;
397
    /* Should not matter, as all cParams are presumed properly defined.
398
     * But, set it for tracing anyway.
399
     */
400
0
    cctxParams->compressionLevel = compressionLevel;
401
0
    cctxParams->useRowMatchFinder = ZSTD_resolveRowMatchFinderMode(cctxParams->useRowMatchFinder, &params->cParams);
402
0
    cctxParams->postBlockSplitter = ZSTD_resolveBlockSplitterMode(cctxParams->postBlockSplitter, &params->cParams);
403
0
    cctxParams->ldmParams.enableLdm = ZSTD_resolveEnableLdm(cctxParams->ldmParams.enableLdm, &params->cParams);
404
0
    cctxParams->validateSequences = ZSTD_resolveExternalSequenceValidation(cctxParams->validateSequences);
405
0
    cctxParams->maxBlockSize = ZSTD_resolveMaxBlockSize(cctxParams->maxBlockSize);
406
0
    cctxParams->searchForExternalRepcodes = ZSTD_resolveExternalRepcodeSearch(cctxParams->searchForExternalRepcodes, compressionLevel);
407
0
    DEBUGLOG(4, "ZSTD_CCtxParams_init_internal: useRowMatchFinder=%d, useBlockSplitter=%d ldm=%d",
408
0
                cctxParams->useRowMatchFinder, cctxParams->postBlockSplitter, cctxParams->ldmParams.enableLdm);
409
0
}
410
411
size_t ZSTD_CCtxParams_init_advanced(ZSTD_CCtx_params* cctxParams, ZSTD_parameters params)
412
0
{
413
0
    RETURN_ERROR_IF(!cctxParams, GENERIC, "NULL pointer!");
414
0
    FORWARD_IF_ERROR( ZSTD_checkCParams(params.cParams) , "");
415
0
    ZSTD_CCtxParams_init_internal(cctxParams, &params, ZSTD_NO_CLEVEL);
416
0
    return 0;
417
0
}
418
419
/**
420
 * Sets cctxParams' cParams and fParams from params, but otherwise leaves them alone.
421
 * @param params Validated zstd parameters.
422
 */
423
static void ZSTD_CCtxParams_setZstdParams(
424
        ZSTD_CCtx_params* cctxParams, const ZSTD_parameters* params)
425
0
{
426
0
    assert(!ZSTD_checkCParams(params->cParams));
427
0
    cctxParams->cParams = params->cParams;
428
0
    cctxParams->fParams = params->fParams;
429
    /* Should not matter, as all cParams are presumed properly defined.
430
     * But, set it for tracing anyway.
431
     */
432
0
    cctxParams->compressionLevel = ZSTD_NO_CLEVEL;
433
0
}
434
435
ZSTD_bounds ZSTD_cParam_getBounds(ZSTD_cParameter param)
436
15.4k
{
437
15.4k
    ZSTD_bounds bounds = { 0, 0, 0 };
438
439
15.4k
    switch(param)
440
15.4k
    {
441
15.4k
    case ZSTD_c_compressionLevel:
442
15.4k
        bounds.lowerBound = ZSTD_minCLevel();
443
15.4k
        bounds.upperBound = ZSTD_maxCLevel();
444
15.4k
        return bounds;
445
446
0
    case ZSTD_c_windowLog:
447
0
        bounds.lowerBound = ZSTD_WINDOWLOG_MIN;
448
0
        bounds.upperBound = ZSTD_WINDOWLOG_MAX;
449
0
        return bounds;
450
451
0
    case ZSTD_c_hashLog:
452
0
        bounds.lowerBound = ZSTD_HASHLOG_MIN;
453
0
        bounds.upperBound = ZSTD_HASHLOG_MAX;
454
0
        return bounds;
455
456
0
    case ZSTD_c_chainLog:
457
0
        bounds.lowerBound = ZSTD_CHAINLOG_MIN;
458
0
        bounds.upperBound = ZSTD_CHAINLOG_MAX;
459
0
        return bounds;
460
461
0
    case ZSTD_c_searchLog:
462
0
        bounds.lowerBound = ZSTD_SEARCHLOG_MIN;
463
0
        bounds.upperBound = ZSTD_SEARCHLOG_MAX;
464
0
        return bounds;
465
466
0
    case ZSTD_c_minMatch:
467
0
        bounds.lowerBound = ZSTD_MINMATCH_MIN;
468
0
        bounds.upperBound = ZSTD_MINMATCH_MAX;
469
0
        return bounds;
470
471
0
    case ZSTD_c_targetLength:
472
0
        bounds.lowerBound = ZSTD_TARGETLENGTH_MIN;
473
0
        bounds.upperBound = ZSTD_TARGETLENGTH_MAX;
474
0
        return bounds;
475
476
0
    case ZSTD_c_strategy:
477
0
        bounds.lowerBound = ZSTD_STRATEGY_MIN;
478
0
        bounds.upperBound = ZSTD_STRATEGY_MAX;
479
0
        return bounds;
480
481
0
    case ZSTD_c_contentSizeFlag:
482
0
        bounds.lowerBound = 0;
483
0
        bounds.upperBound = 1;
484
0
        return bounds;
485
486
0
    case ZSTD_c_checksumFlag:
487
0
        bounds.lowerBound = 0;
488
0
        bounds.upperBound = 1;
489
0
        return bounds;
490
491
0
    case ZSTD_c_dictIDFlag:
492
0
        bounds.lowerBound = 0;
493
0
        bounds.upperBound = 1;
494
0
        return bounds;
495
496
0
    case ZSTD_c_nbWorkers:
497
0
        bounds.lowerBound = 0;
498
0
#ifdef ZSTD_MULTITHREAD
499
0
        bounds.upperBound = ZSTDMT_NBWORKERS_MAX;
500
#else
501
        bounds.upperBound = 0;
502
#endif
503
0
        return bounds;
504
505
0
    case ZSTD_c_jobSize:
506
0
        bounds.lowerBound = 0;
507
0
#ifdef ZSTD_MULTITHREAD
508
0
        bounds.upperBound = ZSTDMT_JOBSIZE_MAX;
509
#else
510
        bounds.upperBound = 0;
511
#endif
512
0
        return bounds;
513
514
0
    case ZSTD_c_overlapLog:
515
0
#ifdef ZSTD_MULTITHREAD
516
0
        bounds.lowerBound = ZSTD_OVERLAPLOG_MIN;
517
0
        bounds.upperBound = ZSTD_OVERLAPLOG_MAX;
518
#else
519
        bounds.lowerBound = 0;
520
        bounds.upperBound = 0;
521
#endif
522
0
        return bounds;
523
524
0
    case ZSTD_c_enableDedicatedDictSearch:
525
0
        bounds.lowerBound = 0;
526
0
        bounds.upperBound = 1;
527
0
        return bounds;
528
529
0
    case ZSTD_c_enableLongDistanceMatching:
530
0
        bounds.lowerBound = (int)ZSTD_ps_auto;
531
0
        bounds.upperBound = (int)ZSTD_ps_disable;
532
0
        return bounds;
533
534
0
    case ZSTD_c_ldmHashLog:
535
0
        bounds.lowerBound = ZSTD_LDM_HASHLOG_MIN;
536
0
        bounds.upperBound = ZSTD_LDM_HASHLOG_MAX;
537
0
        return bounds;
538
539
0
    case ZSTD_c_ldmMinMatch:
540
0
        bounds.lowerBound = ZSTD_LDM_MINMATCH_MIN;
541
0
        bounds.upperBound = ZSTD_LDM_MINMATCH_MAX;
542
0
        return bounds;
543
544
0
    case ZSTD_c_ldmBucketSizeLog:
545
0
        bounds.lowerBound = ZSTD_LDM_BUCKETSIZELOG_MIN;
546
0
        bounds.upperBound = ZSTD_LDM_BUCKETSIZELOG_MAX;
547
0
        return bounds;
548
549
0
    case ZSTD_c_ldmHashRateLog:
550
0
        bounds.lowerBound = ZSTD_LDM_HASHRATELOG_MIN;
551
0
        bounds.upperBound = ZSTD_LDM_HASHRATELOG_MAX;
552
0
        return bounds;
553
554
    /* experimental parameters */
555
0
    case ZSTD_c_rsyncable:
556
0
        bounds.lowerBound = 0;
557
0
        bounds.upperBound = 1;
558
0
        return bounds;
559
560
0
    case ZSTD_c_forceMaxWindow :
561
0
        bounds.lowerBound = 0;
562
0
        bounds.upperBound = 1;
563
0
        return bounds;
564
565
0
    case ZSTD_c_format:
566
0
        ZSTD_STATIC_ASSERT(ZSTD_f_zstd1 < ZSTD_f_zstd1_magicless);
567
0
        bounds.lowerBound = ZSTD_f_zstd1;
568
0
        bounds.upperBound = ZSTD_f_zstd1_magicless;   /* note : how to ensure at compile time that this is the highest value enum ? */
569
0
        return bounds;
570
571
0
    case ZSTD_c_forceAttachDict:
572
0
        ZSTD_STATIC_ASSERT(ZSTD_dictDefaultAttach < ZSTD_dictForceLoad);
573
0
        bounds.lowerBound = ZSTD_dictDefaultAttach;
574
0
        bounds.upperBound = ZSTD_dictForceLoad;       /* note : how to ensure at compile time that this is the highest value enum ? */
575
0
        return bounds;
576
577
0
    case ZSTD_c_literalCompressionMode:
578
0
        ZSTD_STATIC_ASSERT(ZSTD_ps_auto < ZSTD_ps_enable && ZSTD_ps_enable < ZSTD_ps_disable);
579
0
        bounds.lowerBound = (int)ZSTD_ps_auto;
580
0
        bounds.upperBound = (int)ZSTD_ps_disable;
581
0
        return bounds;
582
583
0
    case ZSTD_c_targetCBlockSize:
584
0
        bounds.lowerBound = ZSTD_TARGETCBLOCKSIZE_MIN;
585
0
        bounds.upperBound = ZSTD_TARGETCBLOCKSIZE_MAX;
586
0
        return bounds;
587
588
0
    case ZSTD_c_srcSizeHint:
589
0
        bounds.lowerBound = ZSTD_SRCSIZEHINT_MIN;
590
0
        bounds.upperBound = ZSTD_SRCSIZEHINT_MAX;
591
0
        return bounds;
592
593
0
    case ZSTD_c_stableInBuffer:
594
0
    case ZSTD_c_stableOutBuffer:
595
0
        bounds.lowerBound = (int)ZSTD_bm_buffered;
596
0
        bounds.upperBound = (int)ZSTD_bm_stable;
597
0
        return bounds;
598
599
0
    case ZSTD_c_blockDelimiters:
600
0
        bounds.lowerBound = (int)ZSTD_sf_noBlockDelimiters;
601
0
        bounds.upperBound = (int)ZSTD_sf_explicitBlockDelimiters;
602
0
        return bounds;
603
604
0
    case ZSTD_c_validateSequences:
605
0
        bounds.lowerBound = 0;
606
0
        bounds.upperBound = 1;
607
0
        return bounds;
608
609
0
    case ZSTD_c_splitAfterSequences:
610
0
        bounds.lowerBound = (int)ZSTD_ps_auto;
611
0
        bounds.upperBound = (int)ZSTD_ps_disable;
612
0
        return bounds;
613
614
0
    case ZSTD_c_blockSplitterLevel:
615
0
        bounds.lowerBound = 0;
616
0
        bounds.upperBound = ZSTD_BLOCKSPLITTER_LEVEL_MAX;
617
0
        return bounds;
618
619
0
    case ZSTD_c_useRowMatchFinder:
620
0
        bounds.lowerBound = (int)ZSTD_ps_auto;
621
0
        bounds.upperBound = (int)ZSTD_ps_disable;
622
0
        return bounds;
623
624
0
    case ZSTD_c_deterministicRefPrefix:
625
0
        bounds.lowerBound = 0;
626
0
        bounds.upperBound = 1;
627
0
        return bounds;
628
629
0
    case ZSTD_c_prefetchCDictTables:
630
0
        bounds.lowerBound = (int)ZSTD_ps_auto;
631
0
        bounds.upperBound = (int)ZSTD_ps_disable;
632
0
        return bounds;
633
634
0
    case ZSTD_c_enableSeqProducerFallback:
635
0
        bounds.lowerBound = 0;
636
0
        bounds.upperBound = 1;
637
0
        return bounds;
638
639
0
    case ZSTD_c_maxBlockSize:
640
0
        bounds.lowerBound = ZSTD_BLOCKSIZE_MAX_MIN;
641
0
        bounds.upperBound = ZSTD_BLOCKSIZE_MAX;
642
0
        return bounds;
643
644
0
    case ZSTD_c_repcodeResolution:
645
0
        bounds.lowerBound = (int)ZSTD_ps_auto;
646
0
        bounds.upperBound = (int)ZSTD_ps_disable;
647
0
        return bounds;
648
649
0
    default:
650
0
        bounds.error = ERROR(parameter_unsupported);
651
0
        return bounds;
652
15.4k
    }
653
15.4k
}
654
655
/* ZSTD_cParam_clampBounds:
656
 * Clamps the value into the bounded range.
657
 */
658
static size_t ZSTD_cParam_clampBounds(ZSTD_cParameter cParam, int* value)
659
15.4k
{
660
15.4k
    ZSTD_bounds const bounds = ZSTD_cParam_getBounds(cParam);
661
15.4k
    if (ZSTD_isError(bounds.error)) return bounds.error;
662
15.4k
    if (*value < bounds.lowerBound) *value = bounds.lowerBound;
663
15.4k
    if (*value > bounds.upperBound) *value = bounds.upperBound;
664
15.4k
    return 0;
665
15.4k
}
666
667
#define BOUNDCHECK(cParam, val)                                       \
668
0
    do {                                                              \
669
0
        RETURN_ERROR_IF(!ZSTD_cParam_withinBounds(cParam,val),        \
670
0
                        parameter_outOfBound, "Param out of bounds"); \
671
0
    } while (0)
672
673
674
static int ZSTD_isUpdateAuthorized(ZSTD_cParameter param)
675
0
{
676
0
    switch(param)
677
0
    {
678
0
    case ZSTD_c_compressionLevel:
679
0
    case ZSTD_c_hashLog:
680
0
    case ZSTD_c_chainLog:
681
0
    case ZSTD_c_searchLog:
682
0
    case ZSTD_c_minMatch:
683
0
    case ZSTD_c_targetLength:
684
0
    case ZSTD_c_strategy:
685
0
    case ZSTD_c_blockSplitterLevel:
686
0
        return 1;
687
688
0
    case ZSTD_c_format:
689
0
    case ZSTD_c_windowLog:
690
0
    case ZSTD_c_contentSizeFlag:
691
0
    case ZSTD_c_checksumFlag:
692
0
    case ZSTD_c_dictIDFlag:
693
0
    case ZSTD_c_forceMaxWindow :
694
0
    case ZSTD_c_nbWorkers:
695
0
    case ZSTD_c_jobSize:
696
0
    case ZSTD_c_overlapLog:
697
0
    case ZSTD_c_rsyncable:
698
0
    case ZSTD_c_enableDedicatedDictSearch:
699
0
    case ZSTD_c_enableLongDistanceMatching:
700
0
    case ZSTD_c_ldmHashLog:
701
0
    case ZSTD_c_ldmMinMatch:
702
0
    case ZSTD_c_ldmBucketSizeLog:
703
0
    case ZSTD_c_ldmHashRateLog:
704
0
    case ZSTD_c_forceAttachDict:
705
0
    case ZSTD_c_literalCompressionMode:
706
0
    case ZSTD_c_targetCBlockSize:
707
0
    case ZSTD_c_srcSizeHint:
708
0
    case ZSTD_c_stableInBuffer:
709
0
    case ZSTD_c_stableOutBuffer:
710
0
    case ZSTD_c_blockDelimiters:
711
0
    case ZSTD_c_validateSequences:
712
0
    case ZSTD_c_splitAfterSequences:
713
0
    case ZSTD_c_useRowMatchFinder:
714
0
    case ZSTD_c_deterministicRefPrefix:
715
0
    case ZSTD_c_prefetchCDictTables:
716
0
    case ZSTD_c_enableSeqProducerFallback:
717
0
    case ZSTD_c_maxBlockSize:
718
0
    case ZSTD_c_repcodeResolution:
719
0
    default:
720
0
        return 0;
721
0
    }
722
0
}
723
724
size_t ZSTD_CCtx_setParameter(ZSTD_CCtx* cctx, ZSTD_cParameter param, int value)
725
15.4k
{
726
15.4k
    DEBUGLOG(4, "ZSTD_CCtx_setParameter (%i, %i)", (int)param, value);
727
15.4k
    if (cctx->streamStage != zcss_init) {
728
0
        if (ZSTD_isUpdateAuthorized(param)) {
729
0
            cctx->cParamsChanged = 1;
730
0
        } else {
731
0
            RETURN_ERROR(stage_wrong, "can only set params in cctx init stage");
732
0
    }   }
733
734
15.4k
    switch(param)
735
15.4k
    {
736
0
    case ZSTD_c_nbWorkers:
737
0
        RETURN_ERROR_IF((value!=0) && cctx->staticSize, parameter_unsupported,
738
0
                        "MT not compatible with static alloc");
739
0
        break;
740
741
15.4k
    case ZSTD_c_compressionLevel:
742
15.4k
    case ZSTD_c_windowLog:
743
15.4k
    case ZSTD_c_hashLog:
744
15.4k
    case ZSTD_c_chainLog:
745
15.4k
    case ZSTD_c_searchLog:
746
15.4k
    case ZSTD_c_minMatch:
747
15.4k
    case ZSTD_c_targetLength:
748
15.4k
    case ZSTD_c_strategy:
749
15.4k
    case ZSTD_c_ldmHashRateLog:
750
15.4k
    case ZSTD_c_format:
751
15.4k
    case ZSTD_c_contentSizeFlag:
752
15.4k
    case ZSTD_c_checksumFlag:
753
15.4k
    case ZSTD_c_dictIDFlag:
754
15.4k
    case ZSTD_c_forceMaxWindow:
755
15.4k
    case ZSTD_c_forceAttachDict:
756
15.4k
    case ZSTD_c_literalCompressionMode:
757
15.4k
    case ZSTD_c_jobSize:
758
15.4k
    case ZSTD_c_overlapLog:
759
15.4k
    case ZSTD_c_rsyncable:
760
15.4k
    case ZSTD_c_enableDedicatedDictSearch:
761
15.4k
    case ZSTD_c_enableLongDistanceMatching:
762
15.4k
    case ZSTD_c_ldmHashLog:
763
15.4k
    case ZSTD_c_ldmMinMatch:
764
15.4k
    case ZSTD_c_ldmBucketSizeLog:
765
15.4k
    case ZSTD_c_targetCBlockSize:
766
15.4k
    case ZSTD_c_srcSizeHint:
767
15.4k
    case ZSTD_c_stableInBuffer:
768
15.4k
    case ZSTD_c_stableOutBuffer:
769
15.4k
    case ZSTD_c_blockDelimiters:
770
15.4k
    case ZSTD_c_validateSequences:
771
15.4k
    case ZSTD_c_splitAfterSequences:
772
15.4k
    case ZSTD_c_blockSplitterLevel:
773
15.4k
    case ZSTD_c_useRowMatchFinder:
774
15.4k
    case ZSTD_c_deterministicRefPrefix:
775
15.4k
    case ZSTD_c_prefetchCDictTables:
776
15.4k
    case ZSTD_c_enableSeqProducerFallback:
777
15.4k
    case ZSTD_c_maxBlockSize:
778
15.4k
    case ZSTD_c_repcodeResolution:
779
15.4k
        break;
780
781
0
    default: RETURN_ERROR(parameter_unsupported, "unknown parameter");
782
15.4k
    }
783
15.4k
    return ZSTD_CCtxParams_setParameter(&cctx->requestedParams, param, value);
784
15.4k
}
785
786
size_t ZSTD_CCtxParams_setParameter(ZSTD_CCtx_params* CCtxParams,
787
                                    ZSTD_cParameter param, int value)
788
15.4k
{
789
15.4k
    DEBUGLOG(4, "ZSTD_CCtxParams_setParameter (%i, %i)", (int)param, value);
790
15.4k
    switch(param)
791
15.4k
    {
792
0
    case ZSTD_c_format :
793
0
        BOUNDCHECK(ZSTD_c_format, value);
794
0
        CCtxParams->format = (ZSTD_format_e)value;
795
0
        return (size_t)CCtxParams->format;
796
797
15.4k
    case ZSTD_c_compressionLevel : {
798
15.4k
        FORWARD_IF_ERROR(ZSTD_cParam_clampBounds(param, &value), "");
799
15.4k
        if (value == 0)
800
0
            CCtxParams->compressionLevel = ZSTD_CLEVEL_DEFAULT; /* 0 == default */
801
15.4k
        else
802
15.4k
            CCtxParams->compressionLevel = value;
803
15.4k
        if (CCtxParams->compressionLevel >= 0) return (size_t)CCtxParams->compressionLevel;
804
0
        return 0;  /* return type (size_t) cannot represent negative values */
805
15.4k
    }
806
807
0
    case ZSTD_c_windowLog :
808
0
        if (value!=0)   /* 0 => use default */
809
0
            BOUNDCHECK(ZSTD_c_windowLog, value);
810
0
        CCtxParams->cParams.windowLog = (U32)value;
811
0
        return CCtxParams->cParams.windowLog;
812
813
0
    case ZSTD_c_hashLog :
814
0
        if (value!=0)   /* 0 => use default */
815
0
            BOUNDCHECK(ZSTD_c_hashLog, value);
816
0
        CCtxParams->cParams.hashLog = (U32)value;
817
0
        return CCtxParams->cParams.hashLog;
818
819
0
    case ZSTD_c_chainLog :
820
0
        if (value!=0)   /* 0 => use default */
821
0
            BOUNDCHECK(ZSTD_c_chainLog, value);
822
0
        CCtxParams->cParams.chainLog = (U32)value;
823
0
        return CCtxParams->cParams.chainLog;
824
825
0
    case ZSTD_c_searchLog :
826
0
        if (value!=0)   /* 0 => use default */
827
0
            BOUNDCHECK(ZSTD_c_searchLog, value);
828
0
        CCtxParams->cParams.searchLog = (U32)value;
829
0
        return (size_t)value;
830
831
0
    case ZSTD_c_minMatch :
832
0
        if (value!=0)   /* 0 => use default */
833
0
            BOUNDCHECK(ZSTD_c_minMatch, value);
834
0
        CCtxParams->cParams.minMatch = (U32)value;
835
0
        return CCtxParams->cParams.minMatch;
836
837
0
    case ZSTD_c_targetLength :
838
0
        BOUNDCHECK(ZSTD_c_targetLength, value);
839
0
        CCtxParams->cParams.targetLength = (U32)value;
840
0
        return CCtxParams->cParams.targetLength;
841
842
0
    case ZSTD_c_strategy :
843
0
        if (value!=0)   /* 0 => use default */
844
0
            BOUNDCHECK(ZSTD_c_strategy, value);
845
0
        CCtxParams->cParams.strategy = (ZSTD_strategy)value;
846
0
        return (size_t)CCtxParams->cParams.strategy;
847
848
0
    case ZSTD_c_contentSizeFlag :
849
        /* Content size written in frame header _when known_ (default:1) */
850
0
        DEBUGLOG(4, "set content size flag = %u", (value!=0));
851
0
        CCtxParams->fParams.contentSizeFlag = value != 0;
852
0
        return (size_t)CCtxParams->fParams.contentSizeFlag;
853
854
0
    case ZSTD_c_checksumFlag :
855
        /* A 32-bits content checksum will be calculated and written at end of frame (default:0) */
856
0
        CCtxParams->fParams.checksumFlag = value != 0;
857
0
        return (size_t)CCtxParams->fParams.checksumFlag;
858
859
0
    case ZSTD_c_dictIDFlag : /* When applicable, dictionary's dictID is provided in frame header (default:1) */
860
0
        DEBUGLOG(4, "set dictIDFlag = %u", (value!=0));
861
0
        CCtxParams->fParams.noDictIDFlag = !value;
862
0
        return !CCtxParams->fParams.noDictIDFlag;
863
864
0
    case ZSTD_c_forceMaxWindow :
865
0
        CCtxParams->forceWindow = (value != 0);
866
0
        return (size_t)CCtxParams->forceWindow;
867
868
0
    case ZSTD_c_forceAttachDict : {
869
0
        const ZSTD_dictAttachPref_e pref = (ZSTD_dictAttachPref_e)value;
870
0
        BOUNDCHECK(ZSTD_c_forceAttachDict, (int)pref);
871
0
        CCtxParams->attachDictPref = pref;
872
0
        return CCtxParams->attachDictPref;
873
0
    }
874
875
0
    case ZSTD_c_literalCompressionMode : {
876
0
        const ZSTD_ParamSwitch_e lcm = (ZSTD_ParamSwitch_e)value;
877
0
        BOUNDCHECK(ZSTD_c_literalCompressionMode, (int)lcm);
878
0
        CCtxParams->literalCompressionMode = lcm;
879
0
        return CCtxParams->literalCompressionMode;
880
0
    }
881
882
0
    case ZSTD_c_nbWorkers :
883
#ifndef ZSTD_MULTITHREAD
884
        RETURN_ERROR_IF(value!=0, parameter_unsupported, "not compiled with multithreading");
885
        return 0;
886
#else
887
0
        FORWARD_IF_ERROR(ZSTD_cParam_clampBounds(param, &value), "");
888
0
        CCtxParams->nbWorkers = value;
889
0
        return (size_t)(CCtxParams->nbWorkers);
890
0
#endif
891
892
0
    case ZSTD_c_jobSize :
893
#ifndef ZSTD_MULTITHREAD
894
        RETURN_ERROR_IF(value!=0, parameter_unsupported, "not compiled with multithreading");
895
        return 0;
896
#else
897
        /* Adjust to the minimum non-default value. */
898
0
        if (value != 0 && value < ZSTDMT_JOBSIZE_MIN)
899
0
            value = ZSTDMT_JOBSIZE_MIN;
900
0
        FORWARD_IF_ERROR(ZSTD_cParam_clampBounds(param, &value), "");
901
0
        assert(value >= 0);
902
0
        CCtxParams->jobSize = (size_t)value;
903
0
        return CCtxParams->jobSize;
904
0
#endif
905
906
0
    case ZSTD_c_overlapLog :
907
#ifndef ZSTD_MULTITHREAD
908
        RETURN_ERROR_IF(value!=0, parameter_unsupported, "not compiled with multithreading");
909
        return 0;
910
#else
911
0
        FORWARD_IF_ERROR(ZSTD_cParam_clampBounds(ZSTD_c_overlapLog, &value), "");
912
0
        CCtxParams->overlapLog = value;
913
0
        return (size_t)CCtxParams->overlapLog;
914
0
#endif
915
916
0
    case ZSTD_c_rsyncable :
917
#ifndef ZSTD_MULTITHREAD
918
        RETURN_ERROR_IF(value!=0, parameter_unsupported, "not compiled with multithreading");
919
        return 0;
920
#else
921
0
        FORWARD_IF_ERROR(ZSTD_cParam_clampBounds(ZSTD_c_overlapLog, &value), "");
922
0
        CCtxParams->rsyncable = value;
923
0
        return (size_t)CCtxParams->rsyncable;
924
0
#endif
925
926
0
    case ZSTD_c_enableDedicatedDictSearch :
927
0
        CCtxParams->enableDedicatedDictSearch = (value!=0);
928
0
        return (size_t)CCtxParams->enableDedicatedDictSearch;
929
930
0
    case ZSTD_c_enableLongDistanceMatching :
931
0
        BOUNDCHECK(ZSTD_c_enableLongDistanceMatching, value);
932
0
        CCtxParams->ldmParams.enableLdm = (ZSTD_ParamSwitch_e)value;
933
0
        return CCtxParams->ldmParams.enableLdm;
934
935
0
    case ZSTD_c_ldmHashLog :
936
0
        if (value!=0)   /* 0 ==> auto */
937
0
            BOUNDCHECK(ZSTD_c_ldmHashLog, value);
938
0
        CCtxParams->ldmParams.hashLog = (U32)value;
939
0
        return CCtxParams->ldmParams.hashLog;
940
941
0
    case ZSTD_c_ldmMinMatch :
942
0
        if (value!=0)   /* 0 ==> default */
943
0
            BOUNDCHECK(ZSTD_c_ldmMinMatch, value);
944
0
        CCtxParams->ldmParams.minMatchLength = (U32)value;
945
0
        return CCtxParams->ldmParams.minMatchLength;
946
947
0
    case ZSTD_c_ldmBucketSizeLog :
948
0
        if (value!=0)   /* 0 ==> default */
949
0
            BOUNDCHECK(ZSTD_c_ldmBucketSizeLog, value);
950
0
        CCtxParams->ldmParams.bucketSizeLog = (U32)value;
951
0
        return CCtxParams->ldmParams.bucketSizeLog;
952
953
0
    case ZSTD_c_ldmHashRateLog :
954
0
        if (value!=0)   /* 0 ==> default */
955
0
            BOUNDCHECK(ZSTD_c_ldmHashRateLog, value);
956
0
        CCtxParams->ldmParams.hashRateLog = (U32)value;
957
0
        return CCtxParams->ldmParams.hashRateLog;
958
959
0
    case ZSTD_c_targetCBlockSize :
960
0
        if (value!=0) {  /* 0 ==> default */
961
0
            value = MAX(value, ZSTD_TARGETCBLOCKSIZE_MIN);
962
0
            BOUNDCHECK(ZSTD_c_targetCBlockSize, value);
963
0
        }
964
0
        CCtxParams->targetCBlockSize = (U32)value;
965
0
        return CCtxParams->targetCBlockSize;
966
967
0
    case ZSTD_c_srcSizeHint :
968
0
        if (value!=0)    /* 0 ==> default */
969
0
            BOUNDCHECK(ZSTD_c_srcSizeHint, value);
970
0
        CCtxParams->srcSizeHint = value;
971
0
        return (size_t)CCtxParams->srcSizeHint;
972
973
0
    case ZSTD_c_stableInBuffer:
974
0
        BOUNDCHECK(ZSTD_c_stableInBuffer, value);
975
0
        CCtxParams->inBufferMode = (ZSTD_bufferMode_e)value;
976
0
        return CCtxParams->inBufferMode;
977
978
0
    case ZSTD_c_stableOutBuffer:
979
0
        BOUNDCHECK(ZSTD_c_stableOutBuffer, value);
980
0
        CCtxParams->outBufferMode = (ZSTD_bufferMode_e)value;
981
0
        return CCtxParams->outBufferMode;
982
983
0
    case ZSTD_c_blockDelimiters:
984
0
        BOUNDCHECK(ZSTD_c_blockDelimiters, value);
985
0
        CCtxParams->blockDelimiters = (ZSTD_SequenceFormat_e)value;
986
0
        return CCtxParams->blockDelimiters;
987
988
0
    case ZSTD_c_validateSequences:
989
0
        BOUNDCHECK(ZSTD_c_validateSequences, value);
990
0
        CCtxParams->validateSequences = value;
991
0
        return (size_t)CCtxParams->validateSequences;
992
993
0
    case ZSTD_c_splitAfterSequences:
994
0
        BOUNDCHECK(ZSTD_c_splitAfterSequences, value);
995
0
        CCtxParams->postBlockSplitter = (ZSTD_ParamSwitch_e)value;
996
0
        return CCtxParams->postBlockSplitter;
997
998
0
    case ZSTD_c_blockSplitterLevel:
999
0
        BOUNDCHECK(ZSTD_c_blockSplitterLevel, value);
1000
0
        CCtxParams->preBlockSplitter_level = value;
1001
0
        return (size_t)CCtxParams->preBlockSplitter_level;
1002
1003
0
    case ZSTD_c_useRowMatchFinder:
1004
0
        BOUNDCHECK(ZSTD_c_useRowMatchFinder, value);
1005
0
        CCtxParams->useRowMatchFinder = (ZSTD_ParamSwitch_e)value;
1006
0
        return CCtxParams->useRowMatchFinder;
1007
1008
0
    case ZSTD_c_deterministicRefPrefix:
1009
0
        BOUNDCHECK(ZSTD_c_deterministicRefPrefix, value);
1010
0
        CCtxParams->deterministicRefPrefix = !!value;
1011
0
        return (size_t)CCtxParams->deterministicRefPrefix;
1012
1013
0
    case ZSTD_c_prefetchCDictTables:
1014
0
        BOUNDCHECK(ZSTD_c_prefetchCDictTables, value);
1015
0
        CCtxParams->prefetchCDictTables = (ZSTD_ParamSwitch_e)value;
1016
0
        return CCtxParams->prefetchCDictTables;
1017
1018
0
    case ZSTD_c_enableSeqProducerFallback:
1019
0
        BOUNDCHECK(ZSTD_c_enableSeqProducerFallback, value);
1020
0
        CCtxParams->enableMatchFinderFallback = value;
1021
0
        return (size_t)CCtxParams->enableMatchFinderFallback;
1022
1023
0
    case ZSTD_c_maxBlockSize:
1024
0
        if (value!=0)    /* 0 ==> default */
1025
0
            BOUNDCHECK(ZSTD_c_maxBlockSize, value);
1026
0
        assert(value>=0);
1027
0
        CCtxParams->maxBlockSize = (size_t)value;
1028
0
        return CCtxParams->maxBlockSize;
1029
1030
0
    case ZSTD_c_repcodeResolution:
1031
0
        BOUNDCHECK(ZSTD_c_repcodeResolution, value);
1032
0
        CCtxParams->searchForExternalRepcodes = (ZSTD_ParamSwitch_e)value;
1033
0
        return CCtxParams->searchForExternalRepcodes;
1034
1035
0
    default: RETURN_ERROR(parameter_unsupported, "unknown parameter");
1036
15.4k
    }
1037
15.4k
}
1038
1039
size_t ZSTD_CCtx_getParameter(ZSTD_CCtx const* cctx, ZSTD_cParameter param, int* value)
1040
0
{
1041
0
    return ZSTD_CCtxParams_getParameter(&cctx->requestedParams, param, value);
1042
0
}
1043
1044
size_t ZSTD_CCtxParams_getParameter(
1045
        ZSTD_CCtx_params const* CCtxParams, ZSTD_cParameter param, int* value)
1046
0
{
1047
0
    switch(param)
1048
0
    {
1049
0
    case ZSTD_c_format :
1050
0
        *value = (int)CCtxParams->format;
1051
0
        break;
1052
0
    case ZSTD_c_compressionLevel :
1053
0
        *value = CCtxParams->compressionLevel;
1054
0
        break;
1055
0
    case ZSTD_c_windowLog :
1056
0
        *value = (int)CCtxParams->cParams.windowLog;
1057
0
        break;
1058
0
    case ZSTD_c_hashLog :
1059
0
        *value = (int)CCtxParams->cParams.hashLog;
1060
0
        break;
1061
0
    case ZSTD_c_chainLog :
1062
0
        *value = (int)CCtxParams->cParams.chainLog;
1063
0
        break;
1064
0
    case ZSTD_c_searchLog :
1065
0
        *value = (int)CCtxParams->cParams.searchLog;
1066
0
        break;
1067
0
    case ZSTD_c_minMatch :
1068
0
        *value = (int)CCtxParams->cParams.minMatch;
1069
0
        break;
1070
0
    case ZSTD_c_targetLength :
1071
0
        *value = (int)CCtxParams->cParams.targetLength;
1072
0
        break;
1073
0
    case ZSTD_c_strategy :
1074
0
        *value = (int)CCtxParams->cParams.strategy;
1075
0
        break;
1076
0
    case ZSTD_c_contentSizeFlag :
1077
0
        *value = CCtxParams->fParams.contentSizeFlag;
1078
0
        break;
1079
0
    case ZSTD_c_checksumFlag :
1080
0
        *value = CCtxParams->fParams.checksumFlag;
1081
0
        break;
1082
0
    case ZSTD_c_dictIDFlag :
1083
0
        *value = !CCtxParams->fParams.noDictIDFlag;
1084
0
        break;
1085
0
    case ZSTD_c_forceMaxWindow :
1086
0
        *value = CCtxParams->forceWindow;
1087
0
        break;
1088
0
    case ZSTD_c_forceAttachDict :
1089
0
        *value = (int)CCtxParams->attachDictPref;
1090
0
        break;
1091
0
    case ZSTD_c_literalCompressionMode :
1092
0
        *value = (int)CCtxParams->literalCompressionMode;
1093
0
        break;
1094
0
    case ZSTD_c_nbWorkers :
1095
#ifndef ZSTD_MULTITHREAD
1096
        assert(CCtxParams->nbWorkers == 0);
1097
#endif
1098
0
        *value = CCtxParams->nbWorkers;
1099
0
        break;
1100
0
    case ZSTD_c_jobSize :
1101
#ifndef ZSTD_MULTITHREAD
1102
        RETURN_ERROR(parameter_unsupported, "not compiled with multithreading");
1103
#else
1104
0
        assert(CCtxParams->jobSize <= INT_MAX);
1105
0
        *value = (int)CCtxParams->jobSize;
1106
0
        break;
1107
0
#endif
1108
0
    case ZSTD_c_overlapLog :
1109
#ifndef ZSTD_MULTITHREAD
1110
        RETURN_ERROR(parameter_unsupported, "not compiled with multithreading");
1111
#else
1112
0
        *value = CCtxParams->overlapLog;
1113
0
        break;
1114
0
#endif
1115
0
    case ZSTD_c_rsyncable :
1116
#ifndef ZSTD_MULTITHREAD
1117
        RETURN_ERROR(parameter_unsupported, "not compiled with multithreading");
1118
#else
1119
0
        *value = CCtxParams->rsyncable;
1120
0
        break;
1121
0
#endif
1122
0
    case ZSTD_c_enableDedicatedDictSearch :
1123
0
        *value = CCtxParams->enableDedicatedDictSearch;
1124
0
        break;
1125
0
    case ZSTD_c_enableLongDistanceMatching :
1126
0
        *value = (int)CCtxParams->ldmParams.enableLdm;
1127
0
        break;
1128
0
    case ZSTD_c_ldmHashLog :
1129
0
        *value = (int)CCtxParams->ldmParams.hashLog;
1130
0
        break;
1131
0
    case ZSTD_c_ldmMinMatch :
1132
0
        *value = (int)CCtxParams->ldmParams.minMatchLength;
1133
0
        break;
1134
0
    case ZSTD_c_ldmBucketSizeLog :
1135
0
        *value = (int)CCtxParams->ldmParams.bucketSizeLog;
1136
0
        break;
1137
0
    case ZSTD_c_ldmHashRateLog :
1138
0
        *value = (int)CCtxParams->ldmParams.hashRateLog;
1139
0
        break;
1140
0
    case ZSTD_c_targetCBlockSize :
1141
0
        *value = (int)CCtxParams->targetCBlockSize;
1142
0
        break;
1143
0
    case ZSTD_c_srcSizeHint :
1144
0
        *value = (int)CCtxParams->srcSizeHint;
1145
0
        break;
1146
0
    case ZSTD_c_stableInBuffer :
1147
0
        *value = (int)CCtxParams->inBufferMode;
1148
0
        break;
1149
0
    case ZSTD_c_stableOutBuffer :
1150
0
        *value = (int)CCtxParams->outBufferMode;
1151
0
        break;
1152
0
    case ZSTD_c_blockDelimiters :
1153
0
        *value = (int)CCtxParams->blockDelimiters;
1154
0
        break;
1155
0
    case ZSTD_c_validateSequences :
1156
0
        *value = (int)CCtxParams->validateSequences;
1157
0
        break;
1158
0
    case ZSTD_c_splitAfterSequences :
1159
0
        *value = (int)CCtxParams->postBlockSplitter;
1160
0
        break;
1161
0
    case ZSTD_c_blockSplitterLevel :
1162
0
        *value = CCtxParams->preBlockSplitter_level;
1163
0
        break;
1164
0
    case ZSTD_c_useRowMatchFinder :
1165
0
        *value = (int)CCtxParams->useRowMatchFinder;
1166
0
        break;
1167
0
    case ZSTD_c_deterministicRefPrefix:
1168
0
        *value = (int)CCtxParams->deterministicRefPrefix;
1169
0
        break;
1170
0
    case ZSTD_c_prefetchCDictTables:
1171
0
        *value = (int)CCtxParams->prefetchCDictTables;
1172
0
        break;
1173
0
    case ZSTD_c_enableSeqProducerFallback:
1174
0
        *value = CCtxParams->enableMatchFinderFallback;
1175
0
        break;
1176
0
    case ZSTD_c_maxBlockSize:
1177
0
        *value = (int)CCtxParams->maxBlockSize;
1178
0
        break;
1179
0
    case ZSTD_c_repcodeResolution:
1180
0
        *value = (int)CCtxParams->searchForExternalRepcodes;
1181
0
        break;
1182
0
    default: RETURN_ERROR(parameter_unsupported, "unknown parameter");
1183
0
    }
1184
0
    return 0;
1185
0
}
1186
1187
/** ZSTD_CCtx_setParametersUsingCCtxParams() :
1188
 *  just applies `params` into `cctx`
1189
 *  no action is performed, parameters are merely stored.
1190
 *  If ZSTDMT is enabled, parameters are pushed to cctx->mtctx.
1191
 *    This is possible even if a compression is ongoing.
1192
 *    In which case, new parameters will be applied on the fly, starting with next compression job.
1193
 */
1194
size_t ZSTD_CCtx_setParametersUsingCCtxParams(
1195
        ZSTD_CCtx* cctx, const ZSTD_CCtx_params* params)
1196
0
{
1197
0
    DEBUGLOG(4, "ZSTD_CCtx_setParametersUsingCCtxParams");
1198
0
    RETURN_ERROR_IF(cctx->streamStage != zcss_init, stage_wrong,
1199
0
                    "The context is in the wrong stage!");
1200
0
    RETURN_ERROR_IF(cctx->cdict, stage_wrong,
1201
0
                    "Can't override parameters with cdict attached (some must "
1202
0
                    "be inherited from the cdict).");
1203
1204
0
    cctx->requestedParams = *params;
1205
0
    return 0;
1206
0
}
1207
1208
size_t ZSTD_CCtx_setCParams(ZSTD_CCtx* cctx, ZSTD_compressionParameters cparams)
1209
0
{
1210
0
    ZSTD_STATIC_ASSERT(sizeof(cparams) == 7 * 4 /* all params are listed below */);
1211
0
    DEBUGLOG(4, "ZSTD_CCtx_setCParams");
1212
    /* only update if all parameters are valid */
1213
0
    FORWARD_IF_ERROR(ZSTD_checkCParams(cparams), "");
1214
0
    FORWARD_IF_ERROR(ZSTD_CCtx_setParameter(cctx, ZSTD_c_windowLog, (int)cparams.windowLog), "");
1215
0
    FORWARD_IF_ERROR(ZSTD_CCtx_setParameter(cctx, ZSTD_c_chainLog, (int)cparams.chainLog), "");
1216
0
    FORWARD_IF_ERROR(ZSTD_CCtx_setParameter(cctx, ZSTD_c_hashLog, (int)cparams.hashLog), "");
1217
0
    FORWARD_IF_ERROR(ZSTD_CCtx_setParameter(cctx, ZSTD_c_searchLog, (int)cparams.searchLog), "");
1218
0
    FORWARD_IF_ERROR(ZSTD_CCtx_setParameter(cctx, ZSTD_c_minMatch, (int)cparams.minMatch), "");
1219
0
    FORWARD_IF_ERROR(ZSTD_CCtx_setParameter(cctx, ZSTD_c_targetLength, (int)cparams.targetLength), "");
1220
0
    FORWARD_IF_ERROR(ZSTD_CCtx_setParameter(cctx, ZSTD_c_strategy, (int)cparams.strategy), "");
1221
0
    return 0;
1222
0
}
1223
1224
size_t ZSTD_CCtx_setFParams(ZSTD_CCtx* cctx, ZSTD_frameParameters fparams)
1225
0
{
1226
0
    ZSTD_STATIC_ASSERT(sizeof(fparams) == 3 * 4 /* all params are listed below */);
1227
0
    DEBUGLOG(4, "ZSTD_CCtx_setFParams");
1228
0
    FORWARD_IF_ERROR(ZSTD_CCtx_setParameter(cctx, ZSTD_c_contentSizeFlag, fparams.contentSizeFlag != 0), "");
1229
0
    FORWARD_IF_ERROR(ZSTD_CCtx_setParameter(cctx, ZSTD_c_checksumFlag, fparams.checksumFlag != 0), "");
1230
0
    FORWARD_IF_ERROR(ZSTD_CCtx_setParameter(cctx, ZSTD_c_dictIDFlag, fparams.noDictIDFlag == 0), "");
1231
0
    return 0;
1232
0
}
1233
1234
size_t ZSTD_CCtx_setParams(ZSTD_CCtx* cctx, ZSTD_parameters params)
1235
0
{
1236
0
    DEBUGLOG(4, "ZSTD_CCtx_setParams");
1237
    /* First check cParams, because we want to update all or none. */
1238
0
    FORWARD_IF_ERROR(ZSTD_checkCParams(params.cParams), "");
1239
    /* Next set fParams, because this could fail if the cctx isn't in init stage. */
1240
0
    FORWARD_IF_ERROR(ZSTD_CCtx_setFParams(cctx, params.fParams), "");
1241
    /* Finally set cParams, which should succeed. */
1242
0
    FORWARD_IF_ERROR(ZSTD_CCtx_setCParams(cctx, params.cParams), "");
1243
0
    return 0;
1244
0
}
1245
1246
size_t ZSTD_CCtx_setPledgedSrcSize(ZSTD_CCtx* cctx, unsigned long long pledgedSrcSize)
1247
0
{
1248
0
    DEBUGLOG(4, "ZSTD_CCtx_setPledgedSrcSize to %llu bytes", pledgedSrcSize);
1249
0
    RETURN_ERROR_IF(cctx->streamStage != zcss_init, stage_wrong,
1250
0
                    "Can't set pledgedSrcSize when not in init stage.");
1251
0
    cctx->pledgedSrcSizePlusOne = pledgedSrcSize+1;
1252
0
    return 0;
1253
0
}
1254
1255
static ZSTD_compressionParameters ZSTD_dedicatedDictSearch_getCParams(
1256
        int const compressionLevel,
1257
        size_t const dictSize);
1258
static int ZSTD_dedicatedDictSearch_isSupported(
1259
        const ZSTD_compressionParameters* cParams);
1260
static void ZSTD_dedicatedDictSearch_revertCParams(
1261
        ZSTD_compressionParameters* cParams);
1262
1263
/**
1264
 * Initializes the local dictionary using requested parameters.
1265
 * NOTE: Initialization does not employ the pledged src size,
1266
 * because the dictionary may be used for multiple compressions.
1267
 */
1268
static size_t ZSTD_initLocalDict(ZSTD_CCtx* cctx)
1269
15.4k
{
1270
15.4k
    ZSTD_localDict* const dl = &cctx->localDict;
1271
15.4k
    if (dl->dict == NULL) {
1272
        /* No local dictionary. */
1273
15.4k
        assert(dl->dictBuffer == NULL);
1274
15.4k
        assert(dl->cdict == NULL);
1275
15.4k
        assert(dl->dictSize == 0);
1276
15.4k
        return 0;
1277
15.4k
    }
1278
0
    if (dl->cdict != NULL) {
1279
        /* Local dictionary already initialized. */
1280
0
        assert(cctx->cdict == dl->cdict);
1281
0
        return 0;
1282
0
    }
1283
0
    assert(dl->dictSize > 0);
1284
0
    assert(cctx->cdict == NULL);
1285
0
    assert(cctx->prefixDict.dict == NULL);
1286
1287
0
    dl->cdict = ZSTD_createCDict_advanced2(
1288
0
            dl->dict,
1289
0
            dl->dictSize,
1290
0
            ZSTD_dlm_byRef,
1291
0
            dl->dictContentType,
1292
0
            &cctx->requestedParams,
1293
0
            cctx->customMem);
1294
0
    RETURN_ERROR_IF(!dl->cdict, memory_allocation, "ZSTD_createCDict_advanced failed");
1295
0
    cctx->cdict = dl->cdict;
1296
0
    return 0;
1297
0
}
1298
1299
size_t ZSTD_CCtx_loadDictionary_advanced(
1300
        ZSTD_CCtx* cctx,
1301
        const void* dict, size_t dictSize,
1302
        ZSTD_dictLoadMethod_e dictLoadMethod,
1303
        ZSTD_dictContentType_e dictContentType)
1304
0
{
1305
0
    DEBUGLOG(4, "ZSTD_CCtx_loadDictionary_advanced (size: %u)", (U32)dictSize);
1306
0
    RETURN_ERROR_IF(cctx->streamStage != zcss_init, stage_wrong,
1307
0
                    "Can't load a dictionary when cctx is not in init stage.");
1308
0
    ZSTD_clearAllDicts(cctx);  /* erase any previously set dictionary */
1309
0
    if (dict == NULL || dictSize == 0)  /* no dictionary */
1310
0
        return 0;
1311
0
    if (dictLoadMethod == ZSTD_dlm_byRef) {
1312
0
        cctx->localDict.dict = dict;
1313
0
    } else {
1314
        /* copy dictionary content inside CCtx to own its lifetime */
1315
0
        void* dictBuffer;
1316
0
        RETURN_ERROR_IF(cctx->staticSize, memory_allocation,
1317
0
                        "static CCtx can't allocate for an internal copy of dictionary");
1318
0
        dictBuffer = ZSTD_customMalloc(dictSize, cctx->customMem);
1319
0
        RETURN_ERROR_IF(dictBuffer==NULL, memory_allocation,
1320
0
                        "allocation failed for dictionary content");
1321
0
        ZSTD_memcpy(dictBuffer, dict, dictSize);
1322
0
        cctx->localDict.dictBuffer = dictBuffer;  /* owned ptr to free */
1323
0
        cctx->localDict.dict = dictBuffer;        /* read-only reference */
1324
0
    }
1325
0
    cctx->localDict.dictSize = dictSize;
1326
0
    cctx->localDict.dictContentType = dictContentType;
1327
0
    return 0;
1328
0
}
1329
1330
size_t ZSTD_CCtx_loadDictionary_byReference(
1331
      ZSTD_CCtx* cctx, const void* dict, size_t dictSize)
1332
0
{
1333
0
    return ZSTD_CCtx_loadDictionary_advanced(
1334
0
            cctx, dict, dictSize, ZSTD_dlm_byRef, ZSTD_dct_auto);
1335
0
}
1336
1337
size_t ZSTD_CCtx_loadDictionary(ZSTD_CCtx* cctx, const void* dict, size_t dictSize)
1338
0
{
1339
0
    return ZSTD_CCtx_loadDictionary_advanced(
1340
0
            cctx, dict, dictSize, ZSTD_dlm_byCopy, ZSTD_dct_auto);
1341
0
}
1342
1343
1344
size_t ZSTD_CCtx_refCDict(ZSTD_CCtx* cctx, const ZSTD_CDict* cdict)
1345
15.4k
{
1346
15.4k
    RETURN_ERROR_IF(cctx->streamStage != zcss_init, stage_wrong,
1347
15.4k
                    "Can't ref a dict when ctx not in init stage.");
1348
    /* Free the existing local cdict (if any) to save memory. */
1349
15.4k
    ZSTD_clearAllDicts(cctx);
1350
15.4k
    cctx->cdict = cdict;
1351
15.4k
    return 0;
1352
15.4k
}
1353
1354
size_t ZSTD_CCtx_refThreadPool(ZSTD_CCtx* cctx, ZSTD_threadPool* pool)
1355
0
{
1356
0
    RETURN_ERROR_IF(cctx->streamStage != zcss_init, stage_wrong,
1357
0
                    "Can't ref a pool when ctx not in init stage.");
1358
0
    cctx->pool = pool;
1359
0
    return 0;
1360
0
}
1361
1362
size_t ZSTD_CCtx_refPrefix(ZSTD_CCtx* cctx, const void* prefix, size_t prefixSize)
1363
0
{
1364
0
    return ZSTD_CCtx_refPrefix_advanced(cctx, prefix, prefixSize, ZSTD_dct_rawContent);
1365
0
}
1366
1367
size_t ZSTD_CCtx_refPrefix_advanced(
1368
        ZSTD_CCtx* cctx, const void* prefix, size_t prefixSize, ZSTD_dictContentType_e dictContentType)
1369
0
{
1370
0
    RETURN_ERROR_IF(cctx->streamStage != zcss_init, stage_wrong,
1371
0
                    "Can't ref a prefix when ctx not in init stage.");
1372
0
    ZSTD_clearAllDicts(cctx);
1373
0
    if (prefix != NULL && prefixSize > 0) {
1374
0
        cctx->prefixDict.dict = prefix;
1375
0
        cctx->prefixDict.dictSize = prefixSize;
1376
0
        cctx->prefixDict.dictContentType = dictContentType;
1377
0
    }
1378
0
    return 0;
1379
0
}
1380
1381
/*! ZSTD_CCtx_reset() :
1382
 *  Also dumps dictionary */
1383
size_t ZSTD_CCtx_reset(ZSTD_CCtx* cctx, ZSTD_ResetDirective reset)
1384
37.0k
{
1385
37.0k
    if ( (reset == ZSTD_reset_session_only)
1386
37.0k
      || (reset == ZSTD_reset_session_and_parameters) ) {
1387
30.9k
        cctx->streamStage = zcss_init;
1388
30.9k
        cctx->pledgedSrcSizePlusOne = 0;
1389
30.9k
    }
1390
37.0k
    if ( (reset == ZSTD_reset_parameters)
1391
37.0k
      || (reset == ZSTD_reset_session_and_parameters) ) {
1392
6.05k
        RETURN_ERROR_IF(cctx->streamStage != zcss_init, stage_wrong,
1393
6.05k
                        "Reset parameters is only possible during init stage.");
1394
6.05k
        ZSTD_clearAllDicts(cctx);
1395
6.05k
        return ZSTD_CCtxParams_reset(&cctx->requestedParams);
1396
6.05k
    }
1397
30.9k
    return 0;
1398
37.0k
}
1399
1400
1401
/** ZSTD_checkCParams() :
1402
    control CParam values remain within authorized range.
1403
    @return : 0, or an error code if one value is beyond authorized range */
1404
size_t ZSTD_checkCParams(ZSTD_compressionParameters cParams)
1405
0
{
1406
0
    BOUNDCHECK(ZSTD_c_windowLog, (int)cParams.windowLog);
1407
0
    BOUNDCHECK(ZSTD_c_chainLog,  (int)cParams.chainLog);
1408
0
    BOUNDCHECK(ZSTD_c_hashLog,   (int)cParams.hashLog);
1409
0
    BOUNDCHECK(ZSTD_c_searchLog, (int)cParams.searchLog);
1410
0
    BOUNDCHECK(ZSTD_c_minMatch,  (int)cParams.minMatch);
1411
0
    BOUNDCHECK(ZSTD_c_targetLength,(int)cParams.targetLength);
1412
0
    BOUNDCHECK(ZSTD_c_strategy,  (int)cParams.strategy);
1413
0
    return 0;
1414
0
}
1415
1416
/** ZSTD_clampCParams() :
1417
 *  make CParam values within valid range.
1418
 *  @return : valid CParams */
1419
static ZSTD_compressionParameters
1420
ZSTD_clampCParams(ZSTD_compressionParameters cParams)
1421
0
{
1422
0
#   define CLAMP_TYPE(cParam, val, type)                                      \
1423
0
        do {                                                                  \
1424
0
            ZSTD_bounds const bounds = ZSTD_cParam_getBounds(cParam);         \
1425
0
            if ((int)val<bounds.lowerBound) val=(type)bounds.lowerBound;      \
1426
0
            else if ((int)val>bounds.upperBound) val=(type)bounds.upperBound; \
1427
0
        } while (0)
1428
0
#   define CLAMP(cParam, val) CLAMP_TYPE(cParam, val, unsigned)
1429
0
    CLAMP(ZSTD_c_windowLog, cParams.windowLog);
1430
0
    CLAMP(ZSTD_c_chainLog,  cParams.chainLog);
1431
0
    CLAMP(ZSTD_c_hashLog,   cParams.hashLog);
1432
0
    CLAMP(ZSTD_c_searchLog, cParams.searchLog);
1433
0
    CLAMP(ZSTD_c_minMatch,  cParams.minMatch);
1434
0
    CLAMP(ZSTD_c_targetLength,cParams.targetLength);
1435
0
    CLAMP_TYPE(ZSTD_c_strategy,cParams.strategy, ZSTD_strategy);
1436
0
    return cParams;
1437
0
}
1438
1439
/** ZSTD_cycleLog() :
1440
 *  condition for correct operation : hashLog > 1 */
1441
U32 ZSTD_cycleLog(U32 hashLog, ZSTD_strategy strat)
1442
53.6k
{
1443
53.6k
    U32 const btScale = ((U32)strat >= (U32)ZSTD_btlazy2);
1444
53.6k
    return hashLog - btScale;
1445
53.6k
}
1446
1447
/** ZSTD_dictAndWindowLog() :
1448
 * Returns an adjusted window log that is large enough to fit the source and the dictionary.
1449
 * The zstd format says that the entire dictionary is valid if one byte of the dictionary
1450
 * is within the window. So the hashLog and chainLog should be large enough to reference both
1451
 * the dictionary and the window. So we must use this adjusted dictAndWindowLog when downsizing
1452
 * the hashLog and windowLog.
1453
 * NOTE: srcSize must not be ZSTD_CONTENTSIZE_UNKNOWN.
1454
 */
1455
static U32 ZSTD_dictAndWindowLog(U32 windowLog, U64 srcSize, U64 dictSize)
1456
0
{
1457
0
    const U64 maxWindowSize = 1ULL << ZSTD_WINDOWLOG_MAX;
1458
    /* No dictionary ==> No change */
1459
0
    if (dictSize == 0) {
1460
0
        return windowLog;
1461
0
    }
1462
0
    assert(windowLog <= ZSTD_WINDOWLOG_MAX);
1463
0
    assert(srcSize != ZSTD_CONTENTSIZE_UNKNOWN); /* Handled in ZSTD_adjustCParams_internal() */
1464
0
    {
1465
0
        U64 const windowSize = 1ULL << windowLog;
1466
0
        U64 const dictAndWindowSize = dictSize + windowSize;
1467
        /* If the window size is already large enough to fit both the source and the dictionary
1468
         * then just use the window size. Otherwise adjust so that it fits the dictionary and
1469
         * the window.
1470
         */
1471
0
        if (windowSize >= dictSize + srcSize) {
1472
0
            return windowLog; /* Window size large enough already */
1473
0
        } else if (dictAndWindowSize >= maxWindowSize) {
1474
0
            return ZSTD_WINDOWLOG_MAX; /* Larger than max window log */
1475
0
        } else  {
1476
0
            return ZSTD_highbit32((U32)dictAndWindowSize - 1) + 1;
1477
0
        }
1478
0
    }
1479
0
}
1480
1481
/** ZSTD_adjustCParams_internal() :
1482
 *  optimize `cPar` for a specified input (`srcSize` and `dictSize`).
1483
 *  mostly downsize to reduce memory consumption and initialization latency.
1484
 * `srcSize` can be ZSTD_CONTENTSIZE_UNKNOWN when not known.
1485
 * `mode` is the mode for parameter adjustment. See docs for `ZSTD_CParamMode_e`.
1486
 *  note : `srcSize==0` means 0!
1487
 *  condition : cPar is presumed validated (can be checked using ZSTD_checkCParams()). */
1488
static ZSTD_compressionParameters
1489
ZSTD_adjustCParams_internal(ZSTD_compressionParameters cPar,
1490
                            unsigned long long srcSize,
1491
                            size_t dictSize,
1492
                            ZSTD_CParamMode_e mode,
1493
                            ZSTD_ParamSwitch_e useRowMatchFinder)
1494
30.9k
{
1495
30.9k
    const U64 minSrcSize = 513; /* (1<<9) + 1 */
1496
30.9k
    const U64 maxWindowResize = 1ULL << (ZSTD_WINDOWLOG_MAX-1);
1497
30.9k
    assert(ZSTD_checkCParams(cPar)==0);
1498
1499
    /* Cascade the selected strategy down to the next-highest one built into
1500
     * this binary. */
1501
#ifdef ZSTD_EXCLUDE_BTULTRA_BLOCK_COMPRESSOR
1502
    if (cPar.strategy == ZSTD_btultra2) {
1503
        cPar.strategy = ZSTD_btultra;
1504
    }
1505
    if (cPar.strategy == ZSTD_btultra) {
1506
        cPar.strategy = ZSTD_btopt;
1507
    }
1508
#endif
1509
#ifdef ZSTD_EXCLUDE_BTOPT_BLOCK_COMPRESSOR
1510
    if (cPar.strategy == ZSTD_btopt) {
1511
        cPar.strategy = ZSTD_btlazy2;
1512
    }
1513
#endif
1514
#ifdef ZSTD_EXCLUDE_BTLAZY2_BLOCK_COMPRESSOR
1515
    if (cPar.strategy == ZSTD_btlazy2) {
1516
        cPar.strategy = ZSTD_lazy2;
1517
    }
1518
#endif
1519
#ifdef ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR
1520
    if (cPar.strategy == ZSTD_lazy2) {
1521
        cPar.strategy = ZSTD_lazy;
1522
    }
1523
#endif
1524
#ifdef ZSTD_EXCLUDE_LAZY_BLOCK_COMPRESSOR
1525
    if (cPar.strategy == ZSTD_lazy) {
1526
        cPar.strategy = ZSTD_greedy;
1527
    }
1528
#endif
1529
#ifdef ZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR
1530
    if (cPar.strategy == ZSTD_greedy) {
1531
        cPar.strategy = ZSTD_dfast;
1532
    }
1533
#endif
1534
#ifdef ZSTD_EXCLUDE_DFAST_BLOCK_COMPRESSOR
1535
    if (cPar.strategy == ZSTD_dfast) {
1536
        cPar.strategy = ZSTD_fast;
1537
        cPar.targetLength = 0;
1538
    }
1539
#endif
1540
1541
30.9k
    switch (mode) {
1542
0
    case ZSTD_cpm_unknown:
1543
30.9k
    case ZSTD_cpm_noAttachDict:
1544
        /* If we don't know the source size, don't make any
1545
         * assumptions about it. We will already have selected
1546
         * smaller parameters if a dictionary is in use.
1547
         */
1548
30.9k
        break;
1549
0
    case ZSTD_cpm_createCDict:
1550
        /* Assume a small source size when creating a dictionary
1551
         * with an unknown source size.
1552
         */
1553
0
        if (dictSize && srcSize == ZSTD_CONTENTSIZE_UNKNOWN)
1554
0
            srcSize = minSrcSize;
1555
0
        break;
1556
0
    case ZSTD_cpm_attachDict:
1557
        /* Dictionary has its own dedicated parameters which have
1558
         * already been selected. We are selecting parameters
1559
         * for only the source.
1560
         */
1561
0
        dictSize = 0;
1562
0
        break;
1563
0
    default:
1564
0
        assert(0);
1565
0
        break;
1566
30.9k
    }
1567
1568
    /* resize windowLog if input is small enough, to use less memory */
1569
30.9k
    if ( (srcSize <= maxWindowResize)
1570
30.9k
      && (dictSize <= maxWindowResize) )  {
1571
0
        U32 const tSize = (U32)(srcSize + dictSize);
1572
0
        static U32 const hashSizeMin = 1 << ZSTD_HASHLOG_MIN;
1573
0
        U32 const srcLog = (tSize < hashSizeMin) ? ZSTD_HASHLOG_MIN :
1574
0
                            ZSTD_highbit32(tSize-1) + 1;
1575
0
        if (cPar.windowLog > srcLog) cPar.windowLog = srcLog;
1576
0
    }
1577
30.9k
    if (srcSize != ZSTD_CONTENTSIZE_UNKNOWN) {
1578
0
        U32 const dictAndWindowLog = ZSTD_dictAndWindowLog(cPar.windowLog, (U64)srcSize, (U64)dictSize);
1579
0
        U32 const cycleLog = ZSTD_cycleLog(cPar.chainLog, cPar.strategy);
1580
0
        if (cPar.hashLog > dictAndWindowLog+1) cPar.hashLog = dictAndWindowLog+1;
1581
0
        if (cycleLog > dictAndWindowLog)
1582
0
            cPar.chainLog -= (cycleLog - dictAndWindowLog);
1583
0
    }
1584
1585
30.9k
    if (cPar.windowLog < ZSTD_WINDOWLOG_ABSOLUTEMIN)
1586
0
        cPar.windowLog = ZSTD_WINDOWLOG_ABSOLUTEMIN;  /* minimum wlog required for valid frame header */
1587
1588
    /* We can't use more than 32 bits of hash in total, so that means that we require:
1589
     * (hashLog + 8) <= 32 && (chainLog + 8) <= 32
1590
     */
1591
30.9k
    if (mode == ZSTD_cpm_createCDict && ZSTD_CDictIndicesAreTagged(&cPar)) {
1592
0
        U32 const maxShortCacheHashLog = 32 - ZSTD_SHORT_CACHE_TAG_BITS;
1593
0
        if (cPar.hashLog > maxShortCacheHashLog) {
1594
0
            cPar.hashLog = maxShortCacheHashLog;
1595
0
        }
1596
0
        if (cPar.chainLog > maxShortCacheHashLog) {
1597
0
            cPar.chainLog = maxShortCacheHashLog;
1598
0
        }
1599
0
    }
1600
1601
1602
    /* At this point, we aren't 100% sure if we are using the row match finder.
1603
     * Unless it is explicitly disabled, conservatively assume that it is enabled.
1604
     * In this case it will only be disabled for small sources, so shrinking the
1605
     * hash log a little bit shouldn't result in any ratio loss.
1606
     */
1607
30.9k
    if (useRowMatchFinder == ZSTD_ps_auto)
1608
30.9k
        useRowMatchFinder = ZSTD_ps_enable;
1609
1610
    /* We can't hash more than 32-bits in total. So that means that we require:
1611
     * (hashLog - rowLog + 8) <= 32
1612
     */
1613
30.9k
    if (ZSTD_rowMatchFinderUsed(cPar.strategy, useRowMatchFinder)) {
1614
        /* Switch to 32-entry rows if searchLog is 5 (or more) */
1615
30.9k
        U32 const rowLog = BOUNDED(4, cPar.searchLog, 6);
1616
30.9k
        U32 const maxRowHashLog = 32 - ZSTD_ROW_HASH_TAG_BITS;
1617
30.9k
        U32 const maxHashLog = maxRowHashLog + rowLog;
1618
30.9k
        assert(cPar.hashLog >= rowLog);
1619
30.9k
        if (cPar.hashLog > maxHashLog) {
1620
0
            cPar.hashLog = maxHashLog;
1621
0
        }
1622
30.9k
    }
1623
1624
30.9k
    return cPar;
1625
30.9k
}
1626
1627
ZSTD_compressionParameters
1628
ZSTD_adjustCParams(ZSTD_compressionParameters cPar,
1629
                   unsigned long long srcSize,
1630
                   size_t dictSize)
1631
0
{
1632
0
    cPar = ZSTD_clampCParams(cPar);   /* resulting cPar is necessarily valid (all parameters within range) */
1633
0
    if (srcSize == 0) srcSize = ZSTD_CONTENTSIZE_UNKNOWN;
1634
0
    return ZSTD_adjustCParams_internal(cPar, srcSize, dictSize, ZSTD_cpm_unknown, ZSTD_ps_auto);
1635
0
}
1636
1637
static ZSTD_compressionParameters ZSTD_getCParams_internal(int compressionLevel, unsigned long long srcSizeHint, size_t dictSize, ZSTD_CParamMode_e mode);
1638
static ZSTD_parameters ZSTD_getParams_internal(int compressionLevel, unsigned long long srcSizeHint, size_t dictSize, ZSTD_CParamMode_e mode);
1639
1640
static void ZSTD_overrideCParams(
1641
              ZSTD_compressionParameters* cParams,
1642
        const ZSTD_compressionParameters* overrides)
1643
15.4k
{
1644
15.4k
    if (overrides->windowLog)    cParams->windowLog    = overrides->windowLog;
1645
15.4k
    if (overrides->hashLog)      cParams->hashLog      = overrides->hashLog;
1646
15.4k
    if (overrides->chainLog)     cParams->chainLog     = overrides->chainLog;
1647
15.4k
    if (overrides->searchLog)    cParams->searchLog    = overrides->searchLog;
1648
15.4k
    if (overrides->minMatch)     cParams->minMatch     = overrides->minMatch;
1649
15.4k
    if (overrides->targetLength) cParams->targetLength = overrides->targetLength;
1650
15.4k
    if (overrides->strategy)     cParams->strategy     = overrides->strategy;
1651
15.4k
}
1652
1653
ZSTD_compressionParameters ZSTD_getCParamsFromCCtxParams(
1654
        const ZSTD_CCtx_params* CCtxParams, U64 srcSizeHint, size_t dictSize, ZSTD_CParamMode_e mode)
1655
15.4k
{
1656
15.4k
    ZSTD_compressionParameters cParams;
1657
15.4k
    if (srcSizeHint == ZSTD_CONTENTSIZE_UNKNOWN && CCtxParams->srcSizeHint > 0) {
1658
0
        assert(CCtxParams->srcSizeHint>=0);
1659
0
        srcSizeHint = (U64)CCtxParams->srcSizeHint;
1660
0
    }
1661
15.4k
    cParams = ZSTD_getCParams_internal(CCtxParams->compressionLevel, srcSizeHint, dictSize, mode);
1662
15.4k
    if (CCtxParams->ldmParams.enableLdm == ZSTD_ps_enable) cParams.windowLog = ZSTD_LDM_DEFAULT_WINDOW_LOG;
1663
15.4k
    ZSTD_overrideCParams(&cParams, &CCtxParams->cParams);
1664
15.4k
    assert(!ZSTD_checkCParams(cParams));
1665
    /* srcSizeHint == 0 means 0 */
1666
15.4k
    return ZSTD_adjustCParams_internal(cParams, srcSizeHint, dictSize, mode, CCtxParams->useRowMatchFinder);
1667
15.4k
}
1668
1669
static size_t
1670
ZSTD_sizeof_matchState(const ZSTD_compressionParameters* const cParams,
1671
                       const ZSTD_ParamSwitch_e useRowMatchFinder,
1672
                       const int enableDedicatedDictSearch,
1673
                       const U32 forCCtx)
1674
15.4k
{
1675
    /* chain table size should be 0 for fast or row-hash strategies */
1676
15.4k
    size_t const chainSize = ZSTD_allocateChainTable(cParams->strategy, useRowMatchFinder, enableDedicatedDictSearch && !forCCtx)
1677
15.4k
                                ? ((size_t)1 << cParams->chainLog)
1678
15.4k
                                : 0;
1679
15.4k
    size_t const hSize = ((size_t)1) << cParams->hashLog;
1680
15.4k
    U32    const hashLog3 = (forCCtx && cParams->minMatch==3) ? MIN(ZSTD_HASHLOG3_MAX, cParams->windowLog) : 0;
1681
15.4k
    size_t const h3Size = hashLog3 ? ((size_t)1) << hashLog3 : 0;
1682
    /* We don't use ZSTD_cwksp_alloc_size() here because the tables aren't
1683
     * surrounded by redzones in ASAN. */
1684
15.4k
    size_t const tableSpace = chainSize * sizeof(U32)
1685
15.4k
                            + hSize * sizeof(U32)
1686
15.4k
                            + h3Size * sizeof(U32);
1687
15.4k
    size_t const optPotentialSpace =
1688
15.4k
        ZSTD_cwksp_aligned64_alloc_size((MaxML+1) * sizeof(U32))
1689
15.4k
      + ZSTD_cwksp_aligned64_alloc_size((MaxLL+1) * sizeof(U32))
1690
15.4k
      + ZSTD_cwksp_aligned64_alloc_size((MaxOff+1) * sizeof(U32))
1691
15.4k
      + ZSTD_cwksp_aligned64_alloc_size((1<<Litbits) * sizeof(U32))
1692
15.4k
      + ZSTD_cwksp_aligned64_alloc_size(ZSTD_OPT_SIZE * sizeof(ZSTD_match_t))
1693
15.4k
      + ZSTD_cwksp_aligned64_alloc_size(ZSTD_OPT_SIZE * sizeof(ZSTD_optimal_t));
1694
15.4k
    size_t const lazyAdditionalSpace = ZSTD_rowMatchFinderUsed(cParams->strategy, useRowMatchFinder)
1695
15.4k
                                            ? ZSTD_cwksp_aligned64_alloc_size(hSize)
1696
15.4k
                                            : 0;
1697
15.4k
    size_t const optSpace = (forCCtx && (cParams->strategy >= ZSTD_btopt))
1698
15.4k
                                ? optPotentialSpace
1699
15.4k
                                : 0;
1700
15.4k
    size_t const slackSpace = ZSTD_cwksp_slack_space_required();
1701
1702
    /* tables are guaranteed to be sized in multiples of 64 bytes (or 16 uint32_t) */
1703
15.4k
    ZSTD_STATIC_ASSERT(ZSTD_HASHLOG_MIN >= 4 && ZSTD_WINDOWLOG_MIN >= 4 && ZSTD_CHAINLOG_MIN >= 4);
1704
15.4k
    assert(useRowMatchFinder != ZSTD_ps_auto);
1705
1706
15.4k
    DEBUGLOG(4, "chainSize: %u - hSize: %u - h3Size: %u",
1707
15.4k
                (U32)chainSize, (U32)hSize, (U32)h3Size);
1708
15.4k
    return tableSpace + optSpace + slackSpace + lazyAdditionalSpace;
1709
15.4k
}
1710
1711
/* Helper function for calculating memory requirements.
1712
 * Gives a tighter bound than ZSTD_sequenceBound() by taking minMatch into account. */
1713
30.9k
static size_t ZSTD_maxNbSeq(size_t blockSize, unsigned minMatch, int useSequenceProducer) {
1714
30.9k
    U32 const divider = (minMatch==3 || useSequenceProducer) ? 3 : 4;
1715
30.9k
    return blockSize / divider;
1716
30.9k
}
1717
1718
static size_t ZSTD_estimateCCtxSize_usingCCtxParams_internal(
1719
        const ZSTD_compressionParameters* cParams,
1720
        const ldmParams_t* ldmParams,
1721
        const int isStatic,
1722
        const ZSTD_ParamSwitch_e useRowMatchFinder,
1723
        const size_t buffInSize,
1724
        const size_t buffOutSize,
1725
        const U64 pledgedSrcSize,
1726
        int useSequenceProducer,
1727
        size_t maxBlockSize)
1728
15.4k
{
1729
15.4k
    size_t const windowSize = (size_t) BOUNDED(1ULL, 1ULL << cParams->windowLog, pledgedSrcSize);
1730
15.4k
    size_t const blockSize = MIN(ZSTD_resolveMaxBlockSize(maxBlockSize), windowSize);
1731
15.4k
    size_t const maxNbSeq = ZSTD_maxNbSeq(blockSize, cParams->minMatch, useSequenceProducer);
1732
15.4k
    size_t const tokenSpace = ZSTD_cwksp_alloc_size(WILDCOPY_OVERLENGTH + blockSize)
1733
15.4k
                            + ZSTD_cwksp_aligned64_alloc_size(maxNbSeq * sizeof(SeqDef))
1734
15.4k
                            + 3 * ZSTD_cwksp_alloc_size(maxNbSeq * sizeof(BYTE));
1735
15.4k
    size_t const tmpWorkSpace = ZSTD_cwksp_alloc_size(TMP_WORKSPACE_SIZE);
1736
15.4k
    size_t const blockStateSpace = 2 * ZSTD_cwksp_alloc_size(sizeof(ZSTD_compressedBlockState_t));
1737
15.4k
    size_t const matchStateSize = ZSTD_sizeof_matchState(cParams, useRowMatchFinder, /* enableDedicatedDictSearch */ 0, /* forCCtx */ 1);
1738
1739
15.4k
    size_t const ldmSpace = ZSTD_ldm_getTableSize(*ldmParams);
1740
15.4k
    size_t const maxNbLdmSeq = ZSTD_ldm_getMaxNbSeq(*ldmParams, blockSize);
1741
15.4k
    size_t const ldmSeqSpace = ldmParams->enableLdm == ZSTD_ps_enable ?
1742
15.4k
        ZSTD_cwksp_aligned64_alloc_size(maxNbLdmSeq * sizeof(rawSeq)) : 0;
1743
1744
1745
15.4k
    size_t const bufferSpace = ZSTD_cwksp_alloc_size(buffInSize)
1746
15.4k
                             + ZSTD_cwksp_alloc_size(buffOutSize);
1747
1748
15.4k
    size_t const cctxSpace = isStatic ? ZSTD_cwksp_alloc_size(sizeof(ZSTD_CCtx)) : 0;
1749
1750
15.4k
    size_t const maxNbExternalSeq = ZSTD_sequenceBound(blockSize);
1751
15.4k
    size_t const externalSeqSpace = useSequenceProducer
1752
15.4k
        ? ZSTD_cwksp_aligned64_alloc_size(maxNbExternalSeq * sizeof(ZSTD_Sequence))
1753
15.4k
        : 0;
1754
1755
15.4k
    size_t const neededSpace =
1756
15.4k
        cctxSpace +
1757
15.4k
        tmpWorkSpace +
1758
15.4k
        blockStateSpace +
1759
15.4k
        ldmSpace +
1760
15.4k
        ldmSeqSpace +
1761
15.4k
        matchStateSize +
1762
15.4k
        tokenSpace +
1763
15.4k
        bufferSpace +
1764
15.4k
        externalSeqSpace;
1765
1766
15.4k
    DEBUGLOG(5, "estimate workspace : %u", (U32)neededSpace);
1767
15.4k
    return neededSpace;
1768
15.4k
}
1769
1770
size_t ZSTD_estimateCCtxSize_usingCCtxParams(const ZSTD_CCtx_params* params)
1771
0
{
1772
0
    ZSTD_compressionParameters const cParams =
1773
0
                ZSTD_getCParamsFromCCtxParams(params, ZSTD_CONTENTSIZE_UNKNOWN, 0, ZSTD_cpm_noAttachDict);
1774
0
    ZSTD_ParamSwitch_e const useRowMatchFinder = ZSTD_resolveRowMatchFinderMode(params->useRowMatchFinder,
1775
0
                                                                               &cParams);
1776
1777
0
    RETURN_ERROR_IF(params->nbWorkers > 0, GENERIC, "Estimate CCtx size is supported for single-threaded compression only.");
1778
    /* estimateCCtxSize is for one-shot compression. So no buffers should
1779
     * be needed. However, we still allocate two 0-sized buffers, which can
1780
     * take space under ASAN. */
1781
0
    return ZSTD_estimateCCtxSize_usingCCtxParams_internal(
1782
0
        &cParams, &params->ldmParams, 1, useRowMatchFinder, 0, 0, ZSTD_CONTENTSIZE_UNKNOWN, ZSTD_hasExtSeqProd(params), params->maxBlockSize);
1783
0
}
1784
1785
size_t ZSTD_estimateCCtxSize_usingCParams(ZSTD_compressionParameters cParams)
1786
0
{
1787
0
    ZSTD_CCtx_params initialParams = ZSTD_makeCCtxParamsFromCParams(cParams);
1788
0
    if (ZSTD_rowMatchFinderSupported(cParams.strategy)) {
1789
        /* Pick bigger of not using and using row-based matchfinder for greedy and lazy strategies */
1790
0
        size_t noRowCCtxSize;
1791
0
        size_t rowCCtxSize;
1792
0
        initialParams.useRowMatchFinder = ZSTD_ps_disable;
1793
0
        noRowCCtxSize = ZSTD_estimateCCtxSize_usingCCtxParams(&initialParams);
1794
0
        initialParams.useRowMatchFinder = ZSTD_ps_enable;
1795
0
        rowCCtxSize = ZSTD_estimateCCtxSize_usingCCtxParams(&initialParams);
1796
0
        return MAX(noRowCCtxSize, rowCCtxSize);
1797
0
    } else {
1798
0
        return ZSTD_estimateCCtxSize_usingCCtxParams(&initialParams);
1799
0
    }
1800
0
}
1801
1802
static size_t ZSTD_estimateCCtxSize_internal(int compressionLevel)
1803
0
{
1804
0
    int tier = 0;
1805
0
    size_t largestSize = 0;
1806
0
    static const unsigned long long srcSizeTiers[4] = {16 KB, 128 KB, 256 KB, ZSTD_CONTENTSIZE_UNKNOWN};
1807
0
    for (; tier < 4; ++tier) {
1808
        /* Choose the set of cParams for a given level across all srcSizes that give the largest cctxSize */
1809
0
        ZSTD_compressionParameters const cParams = ZSTD_getCParams_internal(compressionLevel, srcSizeTiers[tier], 0, ZSTD_cpm_noAttachDict);
1810
0
        largestSize = MAX(ZSTD_estimateCCtxSize_usingCParams(cParams), largestSize);
1811
0
    }
1812
0
    return largestSize;
1813
0
}
1814
1815
size_t ZSTD_estimateCCtxSize(int compressionLevel)
1816
0
{
1817
0
    int level;
1818
0
    size_t memBudget = 0;
1819
0
    for (level=MIN(compressionLevel, 1); level<=compressionLevel; level++) {
1820
        /* Ensure monotonically increasing memory usage as compression level increases */
1821
0
        size_t const newMB = ZSTD_estimateCCtxSize_internal(level);
1822
0
        if (newMB > memBudget) memBudget = newMB;
1823
0
    }
1824
0
    return memBudget;
1825
0
}
1826
1827
size_t ZSTD_estimateCStreamSize_usingCCtxParams(const ZSTD_CCtx_params* params)
1828
0
{
1829
0
    RETURN_ERROR_IF(params->nbWorkers > 0, GENERIC, "Estimate CCtx size is supported for single-threaded compression only.");
1830
0
    {   ZSTD_compressionParameters const cParams =
1831
0
                ZSTD_getCParamsFromCCtxParams(params, ZSTD_CONTENTSIZE_UNKNOWN, 0, ZSTD_cpm_noAttachDict);
1832
0
        size_t const blockSize = MIN(ZSTD_resolveMaxBlockSize(params->maxBlockSize), (size_t)1 << cParams.windowLog);
1833
0
        size_t const inBuffSize = (params->inBufferMode == ZSTD_bm_buffered)
1834
0
                ? ((size_t)1 << cParams.windowLog) + blockSize
1835
0
                : 0;
1836
0
        size_t const outBuffSize = (params->outBufferMode == ZSTD_bm_buffered)
1837
0
                ? ZSTD_compressBound(blockSize) + 1
1838
0
                : 0;
1839
0
        ZSTD_ParamSwitch_e const useRowMatchFinder = ZSTD_resolveRowMatchFinderMode(params->useRowMatchFinder, &params->cParams);
1840
1841
0
        return ZSTD_estimateCCtxSize_usingCCtxParams_internal(
1842
0
            &cParams, &params->ldmParams, 1, useRowMatchFinder, inBuffSize, outBuffSize,
1843
0
            ZSTD_CONTENTSIZE_UNKNOWN, ZSTD_hasExtSeqProd(params), params->maxBlockSize);
1844
0
    }
1845
0
}
1846
1847
size_t ZSTD_estimateCStreamSize_usingCParams(ZSTD_compressionParameters cParams)
1848
0
{
1849
0
    ZSTD_CCtx_params initialParams = ZSTD_makeCCtxParamsFromCParams(cParams);
1850
0
    if (ZSTD_rowMatchFinderSupported(cParams.strategy)) {
1851
        /* Pick bigger of not using and using row-based matchfinder for greedy and lazy strategies */
1852
0
        size_t noRowCCtxSize;
1853
0
        size_t rowCCtxSize;
1854
0
        initialParams.useRowMatchFinder = ZSTD_ps_disable;
1855
0
        noRowCCtxSize = ZSTD_estimateCStreamSize_usingCCtxParams(&initialParams);
1856
0
        initialParams.useRowMatchFinder = ZSTD_ps_enable;
1857
0
        rowCCtxSize = ZSTD_estimateCStreamSize_usingCCtxParams(&initialParams);
1858
0
        return MAX(noRowCCtxSize, rowCCtxSize);
1859
0
    } else {
1860
0
        return ZSTD_estimateCStreamSize_usingCCtxParams(&initialParams);
1861
0
    }
1862
0
}
1863
1864
static size_t ZSTD_estimateCStreamSize_internal(int compressionLevel)
1865
0
{
1866
0
    ZSTD_compressionParameters const cParams = ZSTD_getCParams_internal(compressionLevel, ZSTD_CONTENTSIZE_UNKNOWN, 0, ZSTD_cpm_noAttachDict);
1867
0
    return ZSTD_estimateCStreamSize_usingCParams(cParams);
1868
0
}
1869
1870
size_t ZSTD_estimateCStreamSize(int compressionLevel)
1871
0
{
1872
0
    int level;
1873
0
    size_t memBudget = 0;
1874
0
    for (level=MIN(compressionLevel, 1); level<=compressionLevel; level++) {
1875
0
        size_t const newMB = ZSTD_estimateCStreamSize_internal(level);
1876
0
        if (newMB > memBudget) memBudget = newMB;
1877
0
    }
1878
0
    return memBudget;
1879
0
}
1880
1881
/* ZSTD_getFrameProgression():
1882
 * tells how much data has been consumed (input) and produced (output) for current frame.
1883
 * able to count progression inside worker threads (non-blocking mode).
1884
 */
1885
ZSTD_frameProgression ZSTD_getFrameProgression(const ZSTD_CCtx* cctx)
1886
0
{
1887
0
#ifdef ZSTD_MULTITHREAD
1888
0
    if (cctx->appliedParams.nbWorkers > 0) {
1889
0
        return ZSTDMT_getFrameProgression(cctx->mtctx);
1890
0
    }
1891
0
#endif
1892
0
    {   ZSTD_frameProgression fp;
1893
0
        size_t const buffered = (cctx->inBuff == NULL) ? 0 :
1894
0
                                cctx->inBuffPos - cctx->inToCompress;
1895
0
        if (buffered) assert(cctx->inBuffPos >= cctx->inToCompress);
1896
0
        assert(buffered <= ZSTD_BLOCKSIZE_MAX);
1897
0
        fp.ingested = cctx->consumedSrcSize + buffered;
1898
0
        fp.consumed = cctx->consumedSrcSize;
1899
0
        fp.produced = cctx->producedCSize;
1900
0
        fp.flushed  = cctx->producedCSize;   /* simplified; some data might still be left within streaming output buffer */
1901
0
        fp.currentJobID = 0;
1902
0
        fp.nbActiveWorkers = 0;
1903
0
        return fp;
1904
0
}   }
1905
1906
/*! ZSTD_toFlushNow()
1907
 *  Only useful for multithreading scenarios currently (nbWorkers >= 1).
1908
 */
1909
size_t ZSTD_toFlushNow(ZSTD_CCtx* cctx)
1910
0
{
1911
0
#ifdef ZSTD_MULTITHREAD
1912
0
    if (cctx->appliedParams.nbWorkers > 0) {
1913
0
        return ZSTDMT_toFlushNow(cctx->mtctx);
1914
0
    }
1915
0
#endif
1916
0
    (void)cctx;
1917
0
    return 0;   /* over-simplification; could also check if context is currently running in streaming mode, and in which case, report how many bytes are left to be flushed within output buffer */
1918
0
}
1919
1920
static void ZSTD_assertEqualCParams(ZSTD_compressionParameters cParams1,
1921
                                    ZSTD_compressionParameters cParams2)
1922
53.6k
{
1923
53.6k
    (void)cParams1;
1924
53.6k
    (void)cParams2;
1925
53.6k
    assert(cParams1.windowLog    == cParams2.windowLog);
1926
53.6k
    assert(cParams1.chainLog     == cParams2.chainLog);
1927
53.6k
    assert(cParams1.hashLog      == cParams2.hashLog);
1928
53.6k
    assert(cParams1.searchLog    == cParams2.searchLog);
1929
53.6k
    assert(cParams1.minMatch     == cParams2.minMatch);
1930
53.6k
    assert(cParams1.targetLength == cParams2.targetLength);
1931
53.6k
    assert(cParams1.strategy     == cParams2.strategy);
1932
53.6k
}
1933
1934
void ZSTD_reset_compressedBlockState(ZSTD_compressedBlockState_t* bs)
1935
15.4k
{
1936
15.4k
    int i;
1937
61.9k
    for (i = 0; i < ZSTD_REP_NUM; ++i)
1938
46.4k
        bs->rep[i] = repStartValue[i];
1939
15.4k
    bs->entropy.huf.repeatMode = HUF_repeat_none;
1940
15.4k
    bs->entropy.fse.offcode_repeatMode = FSE_repeat_none;
1941
15.4k
    bs->entropy.fse.matchlength_repeatMode = FSE_repeat_none;
1942
15.4k
    bs->entropy.fse.litlength_repeatMode = FSE_repeat_none;
1943
15.4k
}
1944
1945
/*! ZSTD_invalidateMatchState()
1946
 *  Invalidate all the matches in the match finder tables.
1947
 *  Requires nextSrc and base to be set (can be NULL).
1948
 */
1949
static void ZSTD_invalidateMatchState(ZSTD_MatchState_t* ms)
1950
15.4k
{
1951
15.4k
    ZSTD_window_clear(&ms->window);
1952
1953
15.4k
    ms->nextToUpdate = ms->window.dictLimit;
1954
15.4k
    ms->loadedDictEnd = 0;
1955
15.4k
    ms->opt.litLengthSum = 0;  /* force reset of btopt stats */
1956
15.4k
    ms->dictMatchState = NULL;
1957
15.4k
}
1958
1959
/**
1960
 * Controls, for this matchState reset, whether the tables need to be cleared /
1961
 * prepared for the coming compression (ZSTDcrp_makeClean), or whether the
1962
 * tables can be left unclean (ZSTDcrp_leaveDirty), because we know that a
1963
 * subsequent operation will overwrite the table space anyways (e.g., copying
1964
 * the matchState contents in from a CDict).
1965
 */
1966
typedef enum {
1967
    ZSTDcrp_makeClean,
1968
    ZSTDcrp_leaveDirty
1969
} ZSTD_compResetPolicy_e;
1970
1971
/**
1972
 * Controls, for this matchState reset, whether indexing can continue where it
1973
 * left off (ZSTDirp_continue), or whether it needs to be restarted from zero
1974
 * (ZSTDirp_reset).
1975
 */
1976
typedef enum {
1977
    ZSTDirp_continue,
1978
    ZSTDirp_reset
1979
} ZSTD_indexResetPolicy_e;
1980
1981
typedef enum {
1982
    ZSTD_resetTarget_CDict,
1983
    ZSTD_resetTarget_CCtx
1984
} ZSTD_resetTarget_e;
1985
1986
/* Mixes bits in a 64 bits in a value, based on XXH3_rrmxmx */
1987
30.9k
static U64 ZSTD_bitmix(U64 val, U64 len) {
1988
30.9k
    val ^= ZSTD_rotateRight_U64(val, 49) ^ ZSTD_rotateRight_U64(val, 24);
1989
30.9k
    val *= 0x9FB21C651E98DF25ULL;
1990
30.9k
    val ^= (val >> 35) + len ;
1991
30.9k
    val *= 0x9FB21C651E98DF25ULL;
1992
30.9k
    return val ^ (val >> 28);
1993
30.9k
}
1994
1995
/* Mixes in the hashSalt and hashSaltEntropy to create a new hashSalt */
1996
15.4k
static void ZSTD_advanceHashSalt(ZSTD_MatchState_t* ms) {
1997
15.4k
    ms->hashSalt = ZSTD_bitmix(ms->hashSalt, 8) ^ ZSTD_bitmix((U64) ms->hashSaltEntropy, 4);
1998
15.4k
}
1999
2000
static size_t
2001
ZSTD_reset_matchState(ZSTD_MatchState_t* ms,
2002
                      ZSTD_cwksp* ws,
2003
                const ZSTD_compressionParameters* cParams,
2004
                const ZSTD_ParamSwitch_e useRowMatchFinder,
2005
                const ZSTD_compResetPolicy_e crp,
2006
                const ZSTD_indexResetPolicy_e forceResetIndex,
2007
                const ZSTD_resetTarget_e forWho)
2008
15.4k
{
2009
    /* disable chain table allocation for fast or row-based strategies */
2010
15.4k
    size_t const chainSize = ZSTD_allocateChainTable(cParams->strategy, useRowMatchFinder,
2011
15.4k
                                                     ms->dedicatedDictSearch && (forWho == ZSTD_resetTarget_CDict))
2012
15.4k
                                ? ((size_t)1 << cParams->chainLog)
2013
15.4k
                                : 0;
2014
15.4k
    size_t const hSize = ((size_t)1) << cParams->hashLog;
2015
15.4k
    U32    const hashLog3 = ((forWho == ZSTD_resetTarget_CCtx) && cParams->minMatch==3) ? MIN(ZSTD_HASHLOG3_MAX, cParams->windowLog) : 0;
2016
15.4k
    size_t const h3Size = hashLog3 ? ((size_t)1) << hashLog3 : 0;
2017
2018
15.4k
    DEBUGLOG(4, "reset indices : %u", forceResetIndex == ZSTDirp_reset);
2019
15.4k
    assert(useRowMatchFinder != ZSTD_ps_auto);
2020
15.4k
    if (forceResetIndex == ZSTDirp_reset) {
2021
6.05k
        ZSTD_window_init(&ms->window);
2022
6.05k
        ZSTD_cwksp_mark_tables_dirty(ws);
2023
6.05k
    }
2024
2025
15.4k
    ms->hashLog3 = hashLog3;
2026
15.4k
    ms->lazySkipping = 0;
2027
2028
15.4k
    ZSTD_invalidateMatchState(ms);
2029
2030
15.4k
    assert(!ZSTD_cwksp_reserve_failed(ws)); /* check that allocation hasn't already failed */
2031
2032
15.4k
    ZSTD_cwksp_clear_tables(ws);
2033
2034
15.4k
    DEBUGLOG(5, "reserving table space");
2035
    /* table Space */
2036
15.4k
    ms->hashTable = (U32*)ZSTD_cwksp_reserve_table(ws, hSize * sizeof(U32));
2037
15.4k
    ms->chainTable = (U32*)ZSTD_cwksp_reserve_table(ws, chainSize * sizeof(U32));
2038
15.4k
    ms->hashTable3 = (U32*)ZSTD_cwksp_reserve_table(ws, h3Size * sizeof(U32));
2039
15.4k
    RETURN_ERROR_IF(ZSTD_cwksp_reserve_failed(ws), memory_allocation,
2040
15.4k
                    "failed a workspace allocation in ZSTD_reset_matchState");
2041
2042
15.4k
    DEBUGLOG(4, "reset table : %u", crp!=ZSTDcrp_leaveDirty);
2043
15.4k
    if (crp!=ZSTDcrp_leaveDirty) {
2044
        /* reset tables only */
2045
15.4k
        ZSTD_cwksp_clean_tables(ws);
2046
15.4k
    }
2047
2048
15.4k
    if (ZSTD_rowMatchFinderUsed(cParams->strategy, useRowMatchFinder)) {
2049
        /* Row match finder needs an additional table of hashes ("tags") */
2050
15.4k
        size_t const tagTableSize = hSize;
2051
        /* We want to generate a new salt in case we reset a Cctx, but we always want to use
2052
         * 0 when we reset a Cdict */
2053
15.4k
        if(forWho == ZSTD_resetTarget_CCtx) {
2054
15.4k
            ms->tagTable = (BYTE*) ZSTD_cwksp_reserve_aligned_init_once(ws, tagTableSize);
2055
15.4k
            ZSTD_advanceHashSalt(ms);
2056
15.4k
        } else {
2057
            /* When we are not salting we want to always memset the memory */
2058
0
            ms->tagTable = (BYTE*) ZSTD_cwksp_reserve_aligned64(ws, tagTableSize);
2059
0
            ZSTD_memset(ms->tagTable, 0, tagTableSize);
2060
0
            ms->hashSalt = 0;
2061
0
        }
2062
15.4k
        {   /* Switch to 32-entry rows if searchLog is 5 (or more) */
2063
15.4k
            U32 const rowLog = BOUNDED(4, cParams->searchLog, 6);
2064
15.4k
            assert(cParams->hashLog >= rowLog);
2065
15.4k
            ms->rowHashLog = cParams->hashLog - rowLog;
2066
15.4k
        }
2067
15.4k
    }
2068
2069
    /* opt parser space */
2070
15.4k
    if ((forWho == ZSTD_resetTarget_CCtx) && (cParams->strategy >= ZSTD_btopt)) {
2071
0
        DEBUGLOG(4, "reserving optimal parser space");
2072
0
        ms->opt.litFreq = (unsigned*)ZSTD_cwksp_reserve_aligned64(ws, (1<<Litbits) * sizeof(unsigned));
2073
0
        ms->opt.litLengthFreq = (unsigned*)ZSTD_cwksp_reserve_aligned64(ws, (MaxLL+1) * sizeof(unsigned));
2074
0
        ms->opt.matchLengthFreq = (unsigned*)ZSTD_cwksp_reserve_aligned64(ws, (MaxML+1) * sizeof(unsigned));
2075
0
        ms->opt.offCodeFreq = (unsigned*)ZSTD_cwksp_reserve_aligned64(ws, (MaxOff+1) * sizeof(unsigned));
2076
0
        ms->opt.matchTable = (ZSTD_match_t*)ZSTD_cwksp_reserve_aligned64(ws, ZSTD_OPT_SIZE * sizeof(ZSTD_match_t));
2077
0
        ms->opt.priceTable = (ZSTD_optimal_t*)ZSTD_cwksp_reserve_aligned64(ws, ZSTD_OPT_SIZE * sizeof(ZSTD_optimal_t));
2078
0
    }
2079
2080
15.4k
    ms->cParams = *cParams;
2081
2082
15.4k
    RETURN_ERROR_IF(ZSTD_cwksp_reserve_failed(ws), memory_allocation,
2083
15.4k
                    "failed a workspace allocation in ZSTD_reset_matchState");
2084
15.4k
    return 0;
2085
15.4k
}
2086
2087
/* ZSTD_indexTooCloseToMax() :
2088
 * minor optimization : prefer memset() rather than reduceIndex()
2089
 * which is measurably slow in some circumstances (reported for Visual Studio).
2090
 * Works when re-using a context for a lot of smallish inputs :
2091
 * if all inputs are smaller than ZSTD_INDEXOVERFLOW_MARGIN,
2092
 * memset() will be triggered before reduceIndex().
2093
 */
2094
15.4k
#define ZSTD_INDEXOVERFLOW_MARGIN (16 MB)
2095
static int ZSTD_indexTooCloseToMax(ZSTD_window_t w)
2096
15.4k
{
2097
15.4k
    return (size_t)(w.nextSrc - w.base) > (ZSTD_CURRENT_MAX - ZSTD_INDEXOVERFLOW_MARGIN);
2098
15.4k
}
2099
2100
/** ZSTD_dictTooBig():
2101
 * When dictionaries are larger than ZSTD_CHUNKSIZE_MAX they can't be loaded in
2102
 * one go generically. So we ensure that in that case we reset the tables to zero,
2103
 * so that we can load as much of the dictionary as possible.
2104
 */
2105
static int ZSTD_dictTooBig(size_t const loadedDictSize)
2106
15.4k
{
2107
15.4k
    return loadedDictSize > ZSTD_CHUNKSIZE_MAX;
2108
15.4k
}
2109
2110
/*! ZSTD_resetCCtx_internal() :
2111
 * @param loadedDictSize The size of the dictionary to be loaded
2112
 * into the context, if any. If no dictionary is used, or the
2113
 * dictionary is being attached / copied, then pass 0.
2114
 * note : `params` are assumed fully validated at this stage.
2115
 */
2116
static size_t ZSTD_resetCCtx_internal(ZSTD_CCtx* zc,
2117
                                      ZSTD_CCtx_params const* params,
2118
                                      U64 const pledgedSrcSize,
2119
                                      size_t const loadedDictSize,
2120
                                      ZSTD_compResetPolicy_e const crp,
2121
                                      ZSTD_buffered_policy_e const zbuff)
2122
15.4k
{
2123
15.4k
    ZSTD_cwksp* const ws = &zc->workspace;
2124
15.4k
    DEBUGLOG(4, "ZSTD_resetCCtx_internal: pledgedSrcSize=%u, wlog=%u, useRowMatchFinder=%d useBlockSplitter=%d",
2125
15.4k
                (U32)pledgedSrcSize, params->cParams.windowLog, (int)params->useRowMatchFinder, (int)params->postBlockSplitter);
2126
15.4k
    assert(!ZSTD_isError(ZSTD_checkCParams(params->cParams)));
2127
2128
15.4k
    zc->isFirstBlock = 1;
2129
2130
    /* Set applied params early so we can modify them for LDM,
2131
     * and point params at the applied params.
2132
     */
2133
15.4k
    zc->appliedParams = *params;
2134
15.4k
    params = &zc->appliedParams;
2135
2136
15.4k
    assert(params->useRowMatchFinder != ZSTD_ps_auto);
2137
15.4k
    assert(params->postBlockSplitter != ZSTD_ps_auto);
2138
15.4k
    assert(params->ldmParams.enableLdm != ZSTD_ps_auto);
2139
15.4k
    assert(params->maxBlockSize != 0);
2140
15.4k
    if (params->ldmParams.enableLdm == ZSTD_ps_enable) {
2141
        /* Adjust long distance matching parameters */
2142
0
        ZSTD_ldm_adjustParameters(&zc->appliedParams.ldmParams, &params->cParams);
2143
0
        assert(params->ldmParams.hashLog >= params->ldmParams.bucketSizeLog);
2144
0
        assert(params->ldmParams.hashRateLog < 32);
2145
0
    }
2146
2147
15.4k
    {   size_t const windowSize = MAX(1, (size_t)MIN(((U64)1 << params->cParams.windowLog), pledgedSrcSize));
2148
15.4k
        size_t const blockSize = MIN(params->maxBlockSize, windowSize);
2149
15.4k
        size_t const maxNbSeq = ZSTD_maxNbSeq(blockSize, params->cParams.minMatch, ZSTD_hasExtSeqProd(params));
2150
15.4k
        size_t const buffOutSize = (zbuff == ZSTDb_buffered && params->outBufferMode == ZSTD_bm_buffered)
2151
15.4k
                ? ZSTD_compressBound(blockSize) + 1
2152
15.4k
                : 0;
2153
15.4k
        size_t const buffInSize = (zbuff == ZSTDb_buffered && params->inBufferMode == ZSTD_bm_buffered)
2154
15.4k
                ? windowSize + blockSize
2155
15.4k
                : 0;
2156
15.4k
        size_t const maxNbLdmSeq = ZSTD_ldm_getMaxNbSeq(params->ldmParams, blockSize);
2157
2158
15.4k
        int const indexTooClose = ZSTD_indexTooCloseToMax(zc->blockState.matchState.window);
2159
15.4k
        int const dictTooBig = ZSTD_dictTooBig(loadedDictSize);
2160
15.4k
        ZSTD_indexResetPolicy_e needsIndexReset =
2161
15.4k
            (indexTooClose || dictTooBig || !zc->initialized) ? ZSTDirp_reset : ZSTDirp_continue;
2162
2163
15.4k
        size_t const neededSpace =
2164
15.4k
            ZSTD_estimateCCtxSize_usingCCtxParams_internal(
2165
15.4k
                &params->cParams, &params->ldmParams, zc->staticSize != 0, params->useRowMatchFinder,
2166
15.4k
                buffInSize, buffOutSize, pledgedSrcSize, ZSTD_hasExtSeqProd(params), params->maxBlockSize);
2167
2168
15.4k
        FORWARD_IF_ERROR(neededSpace, "cctx size estimate failed!");
2169
2170
15.4k
        if (!zc->staticSize) ZSTD_cwksp_bump_oversized_duration(ws, 0);
2171
2172
15.4k
        {   /* Check if workspace is large enough, alloc a new one if needed */
2173
15.4k
            int const workspaceTooSmall = ZSTD_cwksp_sizeof(ws) < neededSpace;
2174
15.4k
            int const workspaceWasteful = ZSTD_cwksp_check_wasteful(ws, neededSpace);
2175
15.4k
            int resizeWorkspace = workspaceTooSmall || workspaceWasteful;
2176
15.4k
            DEBUGLOG(4, "Need %zu B workspace", neededSpace);
2177
15.4k
            DEBUGLOG(4, "windowSize: %zu - blockSize: %zu", windowSize, blockSize);
2178
2179
15.4k
            if (resizeWorkspace) {
2180
6.05k
                DEBUGLOG(4, "Resize workspaceSize from %zuKB to %zuKB",
2181
6.05k
                            ZSTD_cwksp_sizeof(ws) >> 10,
2182
6.05k
                            neededSpace >> 10);
2183
2184
6.05k
                RETURN_ERROR_IF(zc->staticSize, memory_allocation, "static cctx : no resize");
2185
2186
6.05k
                needsIndexReset = ZSTDirp_reset;
2187
2188
6.05k
                ZSTD_cwksp_free(ws, zc->customMem);
2189
6.05k
                FORWARD_IF_ERROR(ZSTD_cwksp_create(ws, neededSpace, zc->customMem), "");
2190
2191
6.05k
                DEBUGLOG(5, "reserving object space");
2192
                /* Statically sized space.
2193
                 * tmpWorkspace never moves,
2194
                 * though prev/next block swap places */
2195
6.05k
                assert(ZSTD_cwksp_check_available(ws, 2 * sizeof(ZSTD_compressedBlockState_t)));
2196
6.05k
                zc->blockState.prevCBlock = (ZSTD_compressedBlockState_t*) ZSTD_cwksp_reserve_object(ws, sizeof(ZSTD_compressedBlockState_t));
2197
6.05k
                RETURN_ERROR_IF(zc->blockState.prevCBlock == NULL, memory_allocation, "couldn't allocate prevCBlock");
2198
6.05k
                zc->blockState.nextCBlock = (ZSTD_compressedBlockState_t*) ZSTD_cwksp_reserve_object(ws, sizeof(ZSTD_compressedBlockState_t));
2199
6.05k
                RETURN_ERROR_IF(zc->blockState.nextCBlock == NULL, memory_allocation, "couldn't allocate nextCBlock");
2200
6.05k
                zc->tmpWorkspace = ZSTD_cwksp_reserve_object(ws, TMP_WORKSPACE_SIZE);
2201
6.05k
                RETURN_ERROR_IF(zc->tmpWorkspace == NULL, memory_allocation, "couldn't allocate tmpWorkspace");
2202
6.05k
                zc->tmpWkspSize = TMP_WORKSPACE_SIZE;
2203
6.05k
        }   }
2204
2205
15.4k
        ZSTD_cwksp_clear(ws);
2206
2207
        /* init params */
2208
15.4k
        zc->blockState.matchState.cParams = params->cParams;
2209
15.4k
        zc->blockState.matchState.prefetchCDictTables = params->prefetchCDictTables == ZSTD_ps_enable;
2210
15.4k
        zc->pledgedSrcSizePlusOne = pledgedSrcSize+1;
2211
15.4k
        zc->consumedSrcSize = 0;
2212
15.4k
        zc->producedCSize = 0;
2213
15.4k
        if (pledgedSrcSize == ZSTD_CONTENTSIZE_UNKNOWN)
2214
15.4k
            zc->appliedParams.fParams.contentSizeFlag = 0;
2215
15.4k
        DEBUGLOG(4, "pledged content size : %u ; flag : %u",
2216
15.4k
            (unsigned)pledgedSrcSize, zc->appliedParams.fParams.contentSizeFlag);
2217
15.4k
        zc->blockSizeMax = blockSize;
2218
2219
15.4k
        XXH64_reset(&zc->xxhState, 0);
2220
15.4k
        zc->stage = ZSTDcs_init;
2221
15.4k
        zc->dictID = 0;
2222
15.4k
        zc->dictContentSize = 0;
2223
2224
15.4k
        ZSTD_reset_compressedBlockState(zc->blockState.prevCBlock);
2225
2226
15.4k
        FORWARD_IF_ERROR(ZSTD_reset_matchState(
2227
15.4k
                &zc->blockState.matchState,
2228
15.4k
                ws,
2229
15.4k
                &params->cParams,
2230
15.4k
                params->useRowMatchFinder,
2231
15.4k
                crp,
2232
15.4k
                needsIndexReset,
2233
15.4k
                ZSTD_resetTarget_CCtx), "");
2234
2235
15.4k
        zc->seqStore.sequencesStart = (SeqDef*)ZSTD_cwksp_reserve_aligned64(ws, maxNbSeq * sizeof(SeqDef));
2236
2237
        /* ldm hash table */
2238
15.4k
        if (params->ldmParams.enableLdm == ZSTD_ps_enable) {
2239
            /* TODO: avoid memset? */
2240
0
            size_t const ldmHSize = ((size_t)1) << params->ldmParams.hashLog;
2241
0
            zc->ldmState.hashTable = (ldmEntry_t*)ZSTD_cwksp_reserve_aligned64(ws, ldmHSize * sizeof(ldmEntry_t));
2242
0
            ZSTD_memset(zc->ldmState.hashTable, 0, ldmHSize * sizeof(ldmEntry_t));
2243
0
            zc->ldmSequences = (rawSeq*)ZSTD_cwksp_reserve_aligned64(ws, maxNbLdmSeq * sizeof(rawSeq));
2244
0
            zc->maxNbLdmSequences = maxNbLdmSeq;
2245
2246
0
            ZSTD_window_init(&zc->ldmState.window);
2247
0
            zc->ldmState.loadedDictEnd = 0;
2248
0
        }
2249
2250
        /* reserve space for block-level external sequences */
2251
15.4k
        if (ZSTD_hasExtSeqProd(params)) {
2252
0
            size_t const maxNbExternalSeq = ZSTD_sequenceBound(blockSize);
2253
0
            zc->extSeqBufCapacity = maxNbExternalSeq;
2254
0
            zc->extSeqBuf =
2255
0
                (ZSTD_Sequence*)ZSTD_cwksp_reserve_aligned64(ws, maxNbExternalSeq * sizeof(ZSTD_Sequence));
2256
0
        }
2257
2258
        /* buffers */
2259
2260
        /* ZSTD_wildcopy() is used to copy into the literals buffer,
2261
         * so we have to oversize the buffer by WILDCOPY_OVERLENGTH bytes.
2262
         */
2263
15.4k
        zc->seqStore.litStart = ZSTD_cwksp_reserve_buffer(ws, blockSize + WILDCOPY_OVERLENGTH);
2264
15.4k
        zc->seqStore.maxNbLit = blockSize;
2265
2266
15.4k
        zc->bufferedPolicy = zbuff;
2267
15.4k
        zc->inBuffSize = buffInSize;
2268
15.4k
        zc->inBuff = (char*)ZSTD_cwksp_reserve_buffer(ws, buffInSize);
2269
15.4k
        zc->outBuffSize = buffOutSize;
2270
15.4k
        zc->outBuff = (char*)ZSTD_cwksp_reserve_buffer(ws, buffOutSize);
2271
2272
        /* ldm bucketOffsets table */
2273
15.4k
        if (params->ldmParams.enableLdm == ZSTD_ps_enable) {
2274
            /* TODO: avoid memset? */
2275
0
            size_t const numBuckets =
2276
0
                  ((size_t)1) << (params->ldmParams.hashLog -
2277
0
                                  params->ldmParams.bucketSizeLog);
2278
0
            zc->ldmState.bucketOffsets = ZSTD_cwksp_reserve_buffer(ws, numBuckets);
2279
0
            ZSTD_memset(zc->ldmState.bucketOffsets, 0, numBuckets);
2280
0
        }
2281
2282
        /* sequences storage */
2283
15.4k
        ZSTD_referenceExternalSequences(zc, NULL, 0);
2284
15.4k
        zc->seqStore.maxNbSeq = maxNbSeq;
2285
15.4k
        zc->seqStore.llCode = ZSTD_cwksp_reserve_buffer(ws, maxNbSeq * sizeof(BYTE));
2286
15.4k
        zc->seqStore.mlCode = ZSTD_cwksp_reserve_buffer(ws, maxNbSeq * sizeof(BYTE));
2287
15.4k
        zc->seqStore.ofCode = ZSTD_cwksp_reserve_buffer(ws, maxNbSeq * sizeof(BYTE));
2288
2289
15.4k
        DEBUGLOG(3, "wksp: finished allocating, %zd bytes remain available", ZSTD_cwksp_available_space(ws));
2290
15.4k
        assert(ZSTD_cwksp_estimated_space_within_bounds(ws, neededSpace));
2291
2292
15.4k
        zc->initialized = 1;
2293
2294
15.4k
        return 0;
2295
15.4k
    }
2296
15.4k
}
2297
2298
/* ZSTD_invalidateRepCodes() :
2299
 * ensures next compression will not use repcodes from previous block.
2300
 * Note : only works with regular variant;
2301
 *        do not use with extDict variant ! */
2302
0
void ZSTD_invalidateRepCodes(ZSTD_CCtx* cctx) {
2303
0
    int i;
2304
0
    for (i=0; i<ZSTD_REP_NUM; i++) cctx->blockState.prevCBlock->rep[i] = 0;
2305
0
    assert(!ZSTD_window_hasExtDict(cctx->blockState.matchState.window));
2306
0
}
2307
2308
/* These are the approximate sizes for each strategy past which copying the
2309
 * dictionary tables into the working context is faster than using them
2310
 * in-place.
2311
 */
2312
static const size_t attachDictSizeCutoffs[ZSTD_STRATEGY_MAX+1] = {
2313
    8 KB,  /* unused */
2314
    8 KB,  /* ZSTD_fast */
2315
    16 KB, /* ZSTD_dfast */
2316
    32 KB, /* ZSTD_greedy */
2317
    32 KB, /* ZSTD_lazy */
2318
    32 KB, /* ZSTD_lazy2 */
2319
    32 KB, /* ZSTD_btlazy2 */
2320
    32 KB, /* ZSTD_btopt */
2321
    8 KB,  /* ZSTD_btultra */
2322
    8 KB   /* ZSTD_btultra2 */
2323
};
2324
2325
static int ZSTD_shouldAttachDict(const ZSTD_CDict* cdict,
2326
                                 const ZSTD_CCtx_params* params,
2327
                                 U64 pledgedSrcSize)
2328
0
{
2329
0
    size_t cutoff = attachDictSizeCutoffs[cdict->matchState.cParams.strategy];
2330
0
    int const dedicatedDictSearch = cdict->matchState.dedicatedDictSearch;
2331
0
    return dedicatedDictSearch
2332
0
        || ( ( pledgedSrcSize <= cutoff
2333
0
            || pledgedSrcSize == ZSTD_CONTENTSIZE_UNKNOWN
2334
0
            || params->attachDictPref == ZSTD_dictForceAttach )
2335
0
          && params->attachDictPref != ZSTD_dictForceCopy
2336
0
          && !params->forceWindow ); /* dictMatchState isn't correctly
2337
                                      * handled in _enforceMaxDist */
2338
0
}
2339
2340
static size_t
2341
ZSTD_resetCCtx_byAttachingCDict(ZSTD_CCtx* cctx,
2342
                        const ZSTD_CDict* cdict,
2343
                        ZSTD_CCtx_params params,
2344
                        U64 pledgedSrcSize,
2345
                        ZSTD_buffered_policy_e zbuff)
2346
0
{
2347
0
    DEBUGLOG(4, "ZSTD_resetCCtx_byAttachingCDict() pledgedSrcSize=%llu",
2348
0
                (unsigned long long)pledgedSrcSize);
2349
0
    {
2350
0
        ZSTD_compressionParameters adjusted_cdict_cParams = cdict->matchState.cParams;
2351
0
        unsigned const windowLog = params.cParams.windowLog;
2352
0
        assert(windowLog != 0);
2353
        /* Resize working context table params for input only, since the dict
2354
         * has its own tables. */
2355
        /* pledgedSrcSize == 0 means 0! */
2356
2357
0
        if (cdict->matchState.dedicatedDictSearch) {
2358
0
            ZSTD_dedicatedDictSearch_revertCParams(&adjusted_cdict_cParams);
2359
0
        }
2360
2361
0
        params.cParams = ZSTD_adjustCParams_internal(adjusted_cdict_cParams, pledgedSrcSize,
2362
0
                                                     cdict->dictContentSize, ZSTD_cpm_attachDict,
2363
0
                                                     params.useRowMatchFinder);
2364
0
        params.cParams.windowLog = windowLog;
2365
0
        params.useRowMatchFinder = cdict->useRowMatchFinder;    /* cdict overrides */
2366
0
        FORWARD_IF_ERROR(ZSTD_resetCCtx_internal(cctx, &params, pledgedSrcSize,
2367
0
                                                 /* loadedDictSize */ 0,
2368
0
                                                 ZSTDcrp_makeClean, zbuff), "");
2369
0
        assert(cctx->appliedParams.cParams.strategy == adjusted_cdict_cParams.strategy);
2370
0
    }
2371
2372
0
    {   const U32 cdictEnd = (U32)( cdict->matchState.window.nextSrc
2373
0
                                  - cdict->matchState.window.base);
2374
0
        const U32 cdictLen = cdictEnd - cdict->matchState.window.dictLimit;
2375
0
        if (cdictLen == 0) {
2376
            /* don't even attach dictionaries with no contents */
2377
0
            DEBUGLOG(4, "skipping attaching empty dictionary");
2378
0
        } else {
2379
0
            DEBUGLOG(4, "attaching dictionary into context");
2380
0
            cctx->blockState.matchState.dictMatchState = &cdict->matchState;
2381
2382
            /* prep working match state so dict matches never have negative indices
2383
             * when they are translated to the working context's index space. */
2384
0
            if (cctx->blockState.matchState.window.dictLimit < cdictEnd) {
2385
0
                cctx->blockState.matchState.window.nextSrc =
2386
0
                    cctx->blockState.matchState.window.base + cdictEnd;
2387
0
                ZSTD_window_clear(&cctx->blockState.matchState.window);
2388
0
            }
2389
            /* loadedDictEnd is expressed within the referential of the active context */
2390
0
            cctx->blockState.matchState.loadedDictEnd = cctx->blockState.matchState.window.dictLimit;
2391
0
    }   }
2392
2393
0
    cctx->dictID = cdict->dictID;
2394
0
    cctx->dictContentSize = cdict->dictContentSize;
2395
2396
    /* copy block state */
2397
0
    ZSTD_memcpy(cctx->blockState.prevCBlock, &cdict->cBlockState, sizeof(cdict->cBlockState));
2398
2399
0
    return 0;
2400
0
}
2401
2402
static void ZSTD_copyCDictTableIntoCCtx(U32* dst, U32 const* src, size_t tableSize,
2403
0
                                        ZSTD_compressionParameters const* cParams) {
2404
0
    if (ZSTD_CDictIndicesAreTagged(cParams)){
2405
        /* Remove tags from the CDict table if they are present.
2406
         * See docs on "short cache" in zstd_compress_internal.h for context. */
2407
0
        size_t i;
2408
0
        for (i = 0; i < tableSize; i++) {
2409
0
            U32 const taggedIndex = src[i];
2410
0
            U32 const index = taggedIndex >> ZSTD_SHORT_CACHE_TAG_BITS;
2411
0
            dst[i] = index;
2412
0
        }
2413
0
    } else {
2414
0
        ZSTD_memcpy(dst, src, tableSize * sizeof(U32));
2415
0
    }
2416
0
}
2417
2418
static size_t ZSTD_resetCCtx_byCopyingCDict(ZSTD_CCtx* cctx,
2419
                            const ZSTD_CDict* cdict,
2420
                            ZSTD_CCtx_params params,
2421
                            U64 pledgedSrcSize,
2422
                            ZSTD_buffered_policy_e zbuff)
2423
0
{
2424
0
    const ZSTD_compressionParameters *cdict_cParams = &cdict->matchState.cParams;
2425
2426
0
    assert(!cdict->matchState.dedicatedDictSearch);
2427
0
    DEBUGLOG(4, "ZSTD_resetCCtx_byCopyingCDict() pledgedSrcSize=%llu",
2428
0
                (unsigned long long)pledgedSrcSize);
2429
2430
0
    {   unsigned const windowLog = params.cParams.windowLog;
2431
0
        assert(windowLog != 0);
2432
        /* Copy only compression parameters related to tables. */
2433
0
        params.cParams = *cdict_cParams;
2434
0
        params.cParams.windowLog = windowLog;
2435
0
        params.useRowMatchFinder = cdict->useRowMatchFinder;
2436
0
        FORWARD_IF_ERROR(ZSTD_resetCCtx_internal(cctx, &params, pledgedSrcSize,
2437
0
                                                 /* loadedDictSize */ 0,
2438
0
                                                 ZSTDcrp_leaveDirty, zbuff), "");
2439
0
        assert(cctx->appliedParams.cParams.strategy == cdict_cParams->strategy);
2440
0
        assert(cctx->appliedParams.cParams.hashLog == cdict_cParams->hashLog);
2441
0
        assert(cctx->appliedParams.cParams.chainLog == cdict_cParams->chainLog);
2442
0
    }
2443
2444
0
    ZSTD_cwksp_mark_tables_dirty(&cctx->workspace);
2445
0
    assert(params.useRowMatchFinder != ZSTD_ps_auto);
2446
2447
    /* copy tables */
2448
0
    {   size_t const chainSize = ZSTD_allocateChainTable(cdict_cParams->strategy, cdict->useRowMatchFinder, 0 /* DDS guaranteed disabled */)
2449
0
                                                            ? ((size_t)1 << cdict_cParams->chainLog)
2450
0
                                                            : 0;
2451
0
        size_t const hSize =  (size_t)1 << cdict_cParams->hashLog;
2452
2453
0
        ZSTD_copyCDictTableIntoCCtx(cctx->blockState.matchState.hashTable,
2454
0
                                cdict->matchState.hashTable,
2455
0
                                hSize, cdict_cParams);
2456
2457
        /* Do not copy cdict's chainTable if cctx has parameters such that it would not use chainTable */
2458
0
        if (ZSTD_allocateChainTable(cctx->appliedParams.cParams.strategy, cctx->appliedParams.useRowMatchFinder, 0 /* forDDSDict */)) {
2459
0
            ZSTD_copyCDictTableIntoCCtx(cctx->blockState.matchState.chainTable,
2460
0
                                    cdict->matchState.chainTable,
2461
0
                                    chainSize, cdict_cParams);
2462
0
        }
2463
        /* copy tag table */
2464
0
        if (ZSTD_rowMatchFinderUsed(cdict_cParams->strategy, cdict->useRowMatchFinder)) {
2465
0
            size_t const tagTableSize = hSize;
2466
0
            ZSTD_memcpy(cctx->blockState.matchState.tagTable,
2467
0
                        cdict->matchState.tagTable,
2468
0
                        tagTableSize);
2469
0
            cctx->blockState.matchState.hashSalt = cdict->matchState.hashSalt;
2470
0
        }
2471
0
    }
2472
2473
    /* Zero the hashTable3, since the cdict never fills it */
2474
0
    assert(cctx->blockState.matchState.hashLog3 <= 31);
2475
0
    {   U32 const h3log = cctx->blockState.matchState.hashLog3;
2476
0
        size_t const h3Size = h3log ? ((size_t)1 << h3log) : 0;
2477
0
        assert(cdict->matchState.hashLog3 == 0);
2478
0
        ZSTD_memset(cctx->blockState.matchState.hashTable3, 0, h3Size * sizeof(U32));
2479
0
    }
2480
2481
0
    ZSTD_cwksp_mark_tables_clean(&cctx->workspace);
2482
2483
    /* copy dictionary offsets */
2484
0
    {   ZSTD_MatchState_t const* srcMatchState = &cdict->matchState;
2485
0
        ZSTD_MatchState_t* dstMatchState = &cctx->blockState.matchState;
2486
0
        dstMatchState->window       = srcMatchState->window;
2487
0
        dstMatchState->nextToUpdate = srcMatchState->nextToUpdate;
2488
0
        dstMatchState->loadedDictEnd= srcMatchState->loadedDictEnd;
2489
0
    }
2490
2491
0
    cctx->dictID = cdict->dictID;
2492
0
    cctx->dictContentSize = cdict->dictContentSize;
2493
2494
    /* copy block state */
2495
0
    ZSTD_memcpy(cctx->blockState.prevCBlock, &cdict->cBlockState, sizeof(cdict->cBlockState));
2496
2497
0
    return 0;
2498
0
}
2499
2500
/* We have a choice between copying the dictionary context into the working
2501
 * context, or referencing the dictionary context from the working context
2502
 * in-place. We decide here which strategy to use. */
2503
static size_t ZSTD_resetCCtx_usingCDict(ZSTD_CCtx* cctx,
2504
                            const ZSTD_CDict* cdict,
2505
                            const ZSTD_CCtx_params* params,
2506
                            U64 pledgedSrcSize,
2507
                            ZSTD_buffered_policy_e zbuff)
2508
0
{
2509
2510
0
    DEBUGLOG(4, "ZSTD_resetCCtx_usingCDict (pledgedSrcSize=%u)",
2511
0
                (unsigned)pledgedSrcSize);
2512
2513
0
    if (ZSTD_shouldAttachDict(cdict, params, pledgedSrcSize)) {
2514
0
        return ZSTD_resetCCtx_byAttachingCDict(
2515
0
            cctx, cdict, *params, pledgedSrcSize, zbuff);
2516
0
    } else {
2517
0
        return ZSTD_resetCCtx_byCopyingCDict(
2518
0
            cctx, cdict, *params, pledgedSrcSize, zbuff);
2519
0
    }
2520
0
}
2521
2522
/*! ZSTD_copyCCtx_internal() :
2523
 *  Duplicate an existing context `srcCCtx` into another one `dstCCtx`.
2524
 *  Only works during stage ZSTDcs_init (i.e. after creation, but before first call to ZSTD_compressContinue()).
2525
 *  The "context", in this case, refers to the hash and chain tables,
2526
 *  entropy tables, and dictionary references.
2527
 * `windowLog` value is enforced if != 0, otherwise value is copied from srcCCtx.
2528
 * @return : 0, or an error code */
2529
static size_t ZSTD_copyCCtx_internal(ZSTD_CCtx* dstCCtx,
2530
                            const ZSTD_CCtx* srcCCtx,
2531
                            ZSTD_frameParameters fParams,
2532
                            U64 pledgedSrcSize,
2533
                            ZSTD_buffered_policy_e zbuff)
2534
0
{
2535
0
    RETURN_ERROR_IF(srcCCtx->stage!=ZSTDcs_init, stage_wrong,
2536
0
                    "Can't copy a ctx that's not in init stage.");
2537
0
    DEBUGLOG(5, "ZSTD_copyCCtx_internal");
2538
0
    ZSTD_memcpy(&dstCCtx->customMem, &srcCCtx->customMem, sizeof(ZSTD_customMem));
2539
0
    {   ZSTD_CCtx_params params = dstCCtx->requestedParams;
2540
        /* Copy only compression parameters related to tables. */
2541
0
        params.cParams = srcCCtx->appliedParams.cParams;
2542
0
        assert(srcCCtx->appliedParams.useRowMatchFinder != ZSTD_ps_auto);
2543
0
        assert(srcCCtx->appliedParams.postBlockSplitter != ZSTD_ps_auto);
2544
0
        assert(srcCCtx->appliedParams.ldmParams.enableLdm != ZSTD_ps_auto);
2545
0
        params.useRowMatchFinder = srcCCtx->appliedParams.useRowMatchFinder;
2546
0
        params.postBlockSplitter = srcCCtx->appliedParams.postBlockSplitter;
2547
0
        params.ldmParams = srcCCtx->appliedParams.ldmParams;
2548
0
        params.fParams = fParams;
2549
0
        params.maxBlockSize = srcCCtx->appliedParams.maxBlockSize;
2550
0
        ZSTD_resetCCtx_internal(dstCCtx, &params, pledgedSrcSize,
2551
0
                                /* loadedDictSize */ 0,
2552
0
                                ZSTDcrp_leaveDirty, zbuff);
2553
0
        assert(dstCCtx->appliedParams.cParams.windowLog == srcCCtx->appliedParams.cParams.windowLog);
2554
0
        assert(dstCCtx->appliedParams.cParams.strategy == srcCCtx->appliedParams.cParams.strategy);
2555
0
        assert(dstCCtx->appliedParams.cParams.hashLog == srcCCtx->appliedParams.cParams.hashLog);
2556
0
        assert(dstCCtx->appliedParams.cParams.chainLog == srcCCtx->appliedParams.cParams.chainLog);
2557
0
        assert(dstCCtx->blockState.matchState.hashLog3 == srcCCtx->blockState.matchState.hashLog3);
2558
0
    }
2559
2560
0
    ZSTD_cwksp_mark_tables_dirty(&dstCCtx->workspace);
2561
2562
    /* copy tables */
2563
0
    {   size_t const chainSize = ZSTD_allocateChainTable(srcCCtx->appliedParams.cParams.strategy,
2564
0
                                                         srcCCtx->appliedParams.useRowMatchFinder,
2565
0
                                                         0 /* forDDSDict */)
2566
0
                                    ? ((size_t)1 << srcCCtx->appliedParams.cParams.chainLog)
2567
0
                                    : 0;
2568
0
        size_t const hSize =  (size_t)1 << srcCCtx->appliedParams.cParams.hashLog;
2569
0
        U32 const h3log = srcCCtx->blockState.matchState.hashLog3;
2570
0
        size_t const h3Size = h3log ? ((size_t)1 << h3log) : 0;
2571
2572
0
        ZSTD_memcpy(dstCCtx->blockState.matchState.hashTable,
2573
0
               srcCCtx->blockState.matchState.hashTable,
2574
0
               hSize * sizeof(U32));
2575
0
        ZSTD_memcpy(dstCCtx->blockState.matchState.chainTable,
2576
0
               srcCCtx->blockState.matchState.chainTable,
2577
0
               chainSize * sizeof(U32));
2578
0
        ZSTD_memcpy(dstCCtx->blockState.matchState.hashTable3,
2579
0
               srcCCtx->blockState.matchState.hashTable3,
2580
0
               h3Size * sizeof(U32));
2581
0
    }
2582
2583
0
    ZSTD_cwksp_mark_tables_clean(&dstCCtx->workspace);
2584
2585
    /* copy dictionary offsets */
2586
0
    {
2587
0
        const ZSTD_MatchState_t* srcMatchState = &srcCCtx->blockState.matchState;
2588
0
        ZSTD_MatchState_t* dstMatchState = &dstCCtx->blockState.matchState;
2589
0
        dstMatchState->window       = srcMatchState->window;
2590
0
        dstMatchState->nextToUpdate = srcMatchState->nextToUpdate;
2591
0
        dstMatchState->loadedDictEnd= srcMatchState->loadedDictEnd;
2592
0
    }
2593
0
    dstCCtx->dictID = srcCCtx->dictID;
2594
0
    dstCCtx->dictContentSize = srcCCtx->dictContentSize;
2595
2596
    /* copy block state */
2597
0
    ZSTD_memcpy(dstCCtx->blockState.prevCBlock, srcCCtx->blockState.prevCBlock, sizeof(*srcCCtx->blockState.prevCBlock));
2598
2599
0
    return 0;
2600
0
}
2601
2602
/*! ZSTD_copyCCtx() :
2603
 *  Duplicate an existing context `srcCCtx` into another one `dstCCtx`.
2604
 *  Only works during stage ZSTDcs_init (i.e. after creation, but before first call to ZSTD_compressContinue()).
2605
 *  pledgedSrcSize==0 means "unknown".
2606
*   @return : 0, or an error code */
2607
size_t ZSTD_copyCCtx(ZSTD_CCtx* dstCCtx, const ZSTD_CCtx* srcCCtx, unsigned long long pledgedSrcSize)
2608
0
{
2609
0
    ZSTD_frameParameters fParams = { 1 /*content*/, 0 /*checksum*/, 0 /*noDictID*/ };
2610
0
    ZSTD_buffered_policy_e const zbuff = srcCCtx->bufferedPolicy;
2611
0
    ZSTD_STATIC_ASSERT((U32)ZSTDb_buffered==1);
2612
0
    if (pledgedSrcSize==0) pledgedSrcSize = ZSTD_CONTENTSIZE_UNKNOWN;
2613
0
    fParams.contentSizeFlag = (pledgedSrcSize != ZSTD_CONTENTSIZE_UNKNOWN);
2614
2615
0
    return ZSTD_copyCCtx_internal(dstCCtx, srcCCtx,
2616
0
                                fParams, pledgedSrcSize,
2617
0
                                zbuff);
2618
0
}
2619
2620
2621
684M
#define ZSTD_ROWSIZE 16
2622
/*! ZSTD_reduceTable() :
2623
 *  reduce table indexes by `reducerValue`, or squash to zero.
2624
 *  PreserveMark preserves "unsorted mark" for btlazy2 strategy.
2625
 *  It must be set to a clear 0/1 value, to remove branch during inlining.
2626
 *  Presume table size is a multiple of ZSTD_ROWSIZE
2627
 *  to help auto-vectorization */
2628
FORCE_INLINE_TEMPLATE void
2629
ZSTD_reduceTable_internal (U32* const table, U32 const size, U32 const reducerValue, int const preserveMark)
2630
307
{
2631
307
    int const nbRows = (int)size / ZSTD_ROWSIZE;
2632
307
    int cellNb = 0;
2633
307
    int rowNb;
2634
    /* Protect special index values < ZSTD_WINDOW_START_INDEX. */
2635
307
    U32 const reducerThreshold = reducerValue + ZSTD_WINDOW_START_INDEX;
2636
307
    assert((size & (ZSTD_ROWSIZE-1)) == 0);  /* multiple of ZSTD_ROWSIZE */
2637
307
    assert(size < (1U<<31));   /* can be cast to int */
2638
2639
#if ZSTD_MEMORY_SANITIZER && !defined (ZSTD_MSAN_DONT_POISON_WORKSPACE)
2640
    /* To validate that the table reuse logic is sound, and that we don't
2641
     * access table space that we haven't cleaned, we re-"poison" the table
2642
     * space every time we mark it dirty.
2643
     *
2644
     * This function however is intended to operate on those dirty tables and
2645
     * re-clean them. So when this function is used correctly, we can unpoison
2646
     * the memory it operated on. This introduces a blind spot though, since
2647
     * if we now try to operate on __actually__ poisoned memory, we will not
2648
     * detect that. */
2649
    __msan_unpoison(table, size * sizeof(U32));
2650
#endif
2651
2652
40.2M
    for (rowNb=0 ; rowNb < nbRows ; rowNb++) {
2653
40.2M
        int column;
2654
684M
        for (column=0; column<ZSTD_ROWSIZE; column++) {
2655
643M
            U32 newVal;
2656
643M
            if (preserveMark && table[cellNb] == ZSTD_DUBT_UNSORTED_MARK) {
2657
                /* This write is pointless, but is required(?) for the compiler
2658
                 * to auto-vectorize the loop. */
2659
0
                newVal = ZSTD_DUBT_UNSORTED_MARK;
2660
643M
            } else if (table[cellNb] < reducerThreshold) {
2661
643M
                newVal = 0;
2662
643M
            } else {
2663
745k
                newVal = table[cellNb] - reducerValue;
2664
745k
            }
2665
643M
            table[cellNb] = newVal;
2666
643M
            cellNb++;
2667
643M
    }   }
2668
307
}
2669
2670
static void ZSTD_reduceTable(U32* const table, U32 const size, U32 const reducerValue)
2671
307
{
2672
307
    ZSTD_reduceTable_internal(table, size, reducerValue, 0);
2673
307
}
2674
2675
static void ZSTD_reduceTable_btlazy2(U32* const table, U32 const size, U32 const reducerValue)
2676
0
{
2677
0
    ZSTD_reduceTable_internal(table, size, reducerValue, 1);
2678
0
}
2679
2680
/*! ZSTD_reduceIndex() :
2681
*   rescale all indexes to avoid future overflow (indexes are U32) */
2682
static void ZSTD_reduceIndex (ZSTD_MatchState_t* ms, ZSTD_CCtx_params const* params, const U32 reducerValue)
2683
307
{
2684
307
    {   U32 const hSize = (U32)1 << params->cParams.hashLog;
2685
307
        ZSTD_reduceTable(ms->hashTable, hSize, reducerValue);
2686
307
    }
2687
2688
307
    if (ZSTD_allocateChainTable(params->cParams.strategy, params->useRowMatchFinder, (U32)ms->dedicatedDictSearch)) {
2689
0
        U32 const chainSize = (U32)1 << params->cParams.chainLog;
2690
0
        if (params->cParams.strategy == ZSTD_btlazy2)
2691
0
            ZSTD_reduceTable_btlazy2(ms->chainTable, chainSize, reducerValue);
2692
0
        else
2693
0
            ZSTD_reduceTable(ms->chainTable, chainSize, reducerValue);
2694
0
    }
2695
2696
307
    if (ms->hashLog3) {
2697
0
        U32 const h3Size = (U32)1 << ms->hashLog3;
2698
0
        ZSTD_reduceTable(ms->hashTable3, h3Size, reducerValue);
2699
0
    }
2700
307
}
2701
2702
2703
/*-*******************************************************
2704
*  Block entropic compression
2705
*********************************************************/
2706
2707
/* See doc/zstd_compression_format.md for detailed format description */
2708
2709
int ZSTD_seqToCodes(const SeqStore_t* seqStorePtr)
2710
53.5k
{
2711
53.5k
    const SeqDef* const sequences = seqStorePtr->sequencesStart;
2712
53.5k
    BYTE* const llCodeTable = seqStorePtr->llCode;
2713
53.5k
    BYTE* const ofCodeTable = seqStorePtr->ofCode;
2714
53.5k
    BYTE* const mlCodeTable = seqStorePtr->mlCode;
2715
53.5k
    U32 const nbSeq = (U32)(seqStorePtr->sequences - seqStorePtr->sequencesStart);
2716
53.5k
    U32 u;
2717
53.5k
    int longOffsets = 0;
2718
53.5k
    assert(nbSeq <= seqStorePtr->maxNbSeq);
2719
33.3M
    for (u=0; u<nbSeq; u++) {
2720
33.2M
        U32 const llv = sequences[u].litLength;
2721
33.2M
        U32 const ofCode = ZSTD_highbit32(sequences[u].offBase);
2722
33.2M
        U32 const mlv = sequences[u].mlBase;
2723
33.2M
        llCodeTable[u] = (BYTE)ZSTD_LLcode(llv);
2724
33.2M
        ofCodeTable[u] = (BYTE)ofCode;
2725
33.2M
        mlCodeTable[u] = (BYTE)ZSTD_MLcode(mlv);
2726
33.2M
        assert(!(MEM_64bits() && ofCode >= STREAM_ACCUMULATOR_MIN));
2727
33.2M
        if (MEM_32bits() && ofCode >= STREAM_ACCUMULATOR_MIN)
2728
0
            longOffsets = 1;
2729
33.2M
    }
2730
53.5k
    if (seqStorePtr->longLengthType==ZSTD_llt_literalLength)
2731
22
        llCodeTable[seqStorePtr->longLengthPos] = MaxLL;
2732
53.5k
    if (seqStorePtr->longLengthType==ZSTD_llt_matchLength)
2733
20.1k
        mlCodeTable[seqStorePtr->longLengthPos] = MaxML;
2734
53.5k
    return longOffsets;
2735
53.5k
}
2736
2737
/* ZSTD_useTargetCBlockSize():
2738
 * Returns if target compressed block size param is being used.
2739
 * If used, compression will do best effort to make a compressed block size to be around targetCBlockSize.
2740
 * Returns 1 if true, 0 otherwise. */
2741
static int ZSTD_useTargetCBlockSize(const ZSTD_CCtx_params* cctxParams)
2742
53.6k
{
2743
53.6k
    DEBUGLOG(5, "ZSTD_useTargetCBlockSize (targetCBlockSize=%zu)", cctxParams->targetCBlockSize);
2744
53.6k
    return (cctxParams->targetCBlockSize != 0);
2745
53.6k
}
2746
2747
/* ZSTD_blockSplitterEnabled():
2748
 * Returns if block splitting param is being used
2749
 * If used, compression will do best effort to split a block in order to improve compression ratio.
2750
 * At the time this function is called, the parameter must be finalized.
2751
 * Returns 1 if true, 0 otherwise. */
2752
static int ZSTD_blockSplitterEnabled(ZSTD_CCtx_params* cctxParams)
2753
53.6k
{
2754
53.6k
    DEBUGLOG(5, "ZSTD_blockSplitterEnabled (postBlockSplitter=%d)", cctxParams->postBlockSplitter);
2755
53.6k
    assert(cctxParams->postBlockSplitter != ZSTD_ps_auto);
2756
53.6k
    return (cctxParams->postBlockSplitter == ZSTD_ps_enable);
2757
53.6k
}
2758
2759
/* Type returned by ZSTD_buildSequencesStatistics containing finalized symbol encoding types
2760
 * and size of the sequences statistics
2761
 */
2762
typedef struct {
2763
    U32 LLtype;
2764
    U32 Offtype;
2765
    U32 MLtype;
2766
    size_t size;
2767
    size_t lastCountSize; /* Accounts for bug in 1.3.4. More detail in ZSTD_entropyCompressSeqStore_internal() */
2768
    int longOffsets;
2769
} ZSTD_symbolEncodingTypeStats_t;
2770
2771
/* ZSTD_buildSequencesStatistics():
2772
 * Returns a ZSTD_symbolEncodingTypeStats_t, or a zstd error code in the `size` field.
2773
 * Modifies `nextEntropy` to have the appropriate values as a side effect.
2774
 * nbSeq must be greater than 0.
2775
 *
2776
 * entropyWkspSize must be of size at least ENTROPY_WORKSPACE_SIZE - (MaxSeq + 1)*sizeof(U32)
2777
 */
2778
static ZSTD_symbolEncodingTypeStats_t
2779
ZSTD_buildSequencesStatistics(
2780
                const SeqStore_t* seqStorePtr, size_t nbSeq,
2781
                const ZSTD_fseCTables_t* prevEntropy, ZSTD_fseCTables_t* nextEntropy,
2782
                      BYTE* dst, const BYTE* const dstEnd,
2783
                      ZSTD_strategy strategy, unsigned* countWorkspace,
2784
                      void* entropyWorkspace, size_t entropyWkspSize)
2785
53.5k
{
2786
53.5k
    BYTE* const ostart = dst;
2787
53.5k
    const BYTE* const oend = dstEnd;
2788
53.5k
    BYTE* op = ostart;
2789
53.5k
    FSE_CTable* CTable_LitLength = nextEntropy->litlengthCTable;
2790
53.5k
    FSE_CTable* CTable_OffsetBits = nextEntropy->offcodeCTable;
2791
53.5k
    FSE_CTable* CTable_MatchLength = nextEntropy->matchlengthCTable;
2792
53.5k
    const BYTE* const ofCodeTable = seqStorePtr->ofCode;
2793
53.5k
    const BYTE* const llCodeTable = seqStorePtr->llCode;
2794
53.5k
    const BYTE* const mlCodeTable = seqStorePtr->mlCode;
2795
53.5k
    ZSTD_symbolEncodingTypeStats_t stats;
2796
2797
53.5k
    stats.lastCountSize = 0;
2798
    /* convert length/distances into codes */
2799
53.5k
    stats.longOffsets = ZSTD_seqToCodes(seqStorePtr);
2800
53.5k
    assert(op <= oend);
2801
53.5k
    assert(nbSeq != 0); /* ZSTD_selectEncodingType() divides by nbSeq */
2802
    /* build CTable for Literal Lengths */
2803
53.5k
    {   unsigned max = MaxLL;
2804
53.5k
        size_t const mostFrequent = HIST_countFast_wksp(countWorkspace, &max, llCodeTable, nbSeq, entropyWorkspace, entropyWkspSize);   /* can't fail */
2805
53.5k
        DEBUGLOG(5, "Building LL table");
2806
53.5k
        nextEntropy->litlength_repeatMode = prevEntropy->litlength_repeatMode;
2807
53.5k
        stats.LLtype = ZSTD_selectEncodingType(&nextEntropy->litlength_repeatMode,
2808
53.5k
                                        countWorkspace, max, mostFrequent, nbSeq,
2809
53.5k
                                        LLFSELog, prevEntropy->litlengthCTable,
2810
53.5k
                                        LL_defaultNorm, LL_defaultNormLog,
2811
53.5k
                                        ZSTD_defaultAllowed, strategy);
2812
53.5k
        assert(set_basic < set_compressed && set_rle < set_compressed);
2813
53.5k
        assert(!(stats.LLtype < set_compressed && nextEntropy->litlength_repeatMode != FSE_repeat_none)); /* We don't copy tables */
2814
53.5k
        {   size_t const countSize = ZSTD_buildCTable(
2815
53.5k
                op, (size_t)(oend - op),
2816
53.5k
                CTable_LitLength, LLFSELog, (SymbolEncodingType_e)stats.LLtype,
2817
53.5k
                countWorkspace, max, llCodeTable, nbSeq,
2818
53.5k
                LL_defaultNorm, LL_defaultNormLog, MaxLL,
2819
53.5k
                prevEntropy->litlengthCTable,
2820
53.5k
                sizeof(prevEntropy->litlengthCTable),
2821
53.5k
                entropyWorkspace, entropyWkspSize);
2822
53.5k
            if (ZSTD_isError(countSize)) {
2823
0
                DEBUGLOG(3, "ZSTD_buildCTable for LitLens failed");
2824
0
                stats.size = countSize;
2825
0
                return stats;
2826
0
            }
2827
53.5k
            if (stats.LLtype == set_compressed)
2828
20.9k
                stats.lastCountSize = countSize;
2829
53.5k
            op += countSize;
2830
53.5k
            assert(op <= oend);
2831
53.5k
    }   }
2832
    /* build CTable for Offsets */
2833
53.5k
    {   unsigned max = MaxOff;
2834
53.5k
        size_t const mostFrequent = HIST_countFast_wksp(
2835
53.5k
            countWorkspace, &max, ofCodeTable, nbSeq, entropyWorkspace, entropyWkspSize);  /* can't fail */
2836
        /* We can only use the basic table if max <= DefaultMaxOff, otherwise the offsets are too large */
2837
53.5k
        ZSTD_DefaultPolicy_e const defaultPolicy = (max <= DefaultMaxOff) ? ZSTD_defaultAllowed : ZSTD_defaultDisallowed;
2838
53.5k
        DEBUGLOG(5, "Building OF table");
2839
53.5k
        nextEntropy->offcode_repeatMode = prevEntropy->offcode_repeatMode;
2840
53.5k
        stats.Offtype = ZSTD_selectEncodingType(&nextEntropy->offcode_repeatMode,
2841
53.5k
                                        countWorkspace, max, mostFrequent, nbSeq,
2842
53.5k
                                        OffFSELog, prevEntropy->offcodeCTable,
2843
53.5k
                                        OF_defaultNorm, OF_defaultNormLog,
2844
53.5k
                                        defaultPolicy, strategy);
2845
53.5k
        assert(!(stats.Offtype < set_compressed && nextEntropy->offcode_repeatMode != FSE_repeat_none)); /* We don't copy tables */
2846
53.5k
        {   size_t const countSize = ZSTD_buildCTable(
2847
53.5k
                op, (size_t)(oend - op),
2848
53.5k
                CTable_OffsetBits, OffFSELog, (SymbolEncodingType_e)stats.Offtype,
2849
53.5k
                countWorkspace, max, ofCodeTable, nbSeq,
2850
53.5k
                OF_defaultNorm, OF_defaultNormLog, DefaultMaxOff,
2851
53.5k
                prevEntropy->offcodeCTable,
2852
53.5k
                sizeof(prevEntropy->offcodeCTable),
2853
53.5k
                entropyWorkspace, entropyWkspSize);
2854
53.5k
            if (ZSTD_isError(countSize)) {
2855
0
                DEBUGLOG(3, "ZSTD_buildCTable for Offsets failed");
2856
0
                stats.size = countSize;
2857
0
                return stats;
2858
0
            }
2859
53.5k
            if (stats.Offtype == set_compressed)
2860
25.9k
                stats.lastCountSize = countSize;
2861
53.5k
            op += countSize;
2862
53.5k
            assert(op <= oend);
2863
53.5k
    }   }
2864
    /* build CTable for MatchLengths */
2865
53.5k
    {   unsigned max = MaxML;
2866
53.5k
        size_t const mostFrequent = HIST_countFast_wksp(
2867
53.5k
            countWorkspace, &max, mlCodeTable, nbSeq, entropyWorkspace, entropyWkspSize);   /* can't fail */
2868
53.5k
        DEBUGLOG(5, "Building ML table (remaining space : %i)", (int)(oend-op));
2869
53.5k
        nextEntropy->matchlength_repeatMode = prevEntropy->matchlength_repeatMode;
2870
53.5k
        stats.MLtype = ZSTD_selectEncodingType(&nextEntropy->matchlength_repeatMode,
2871
53.5k
                                        countWorkspace, max, mostFrequent, nbSeq,
2872
53.5k
                                        MLFSELog, prevEntropy->matchlengthCTable,
2873
53.5k
                                        ML_defaultNorm, ML_defaultNormLog,
2874
53.5k
                                        ZSTD_defaultAllowed, strategy);
2875
53.5k
        assert(!(stats.MLtype < set_compressed && nextEntropy->matchlength_repeatMode != FSE_repeat_none)); /* We don't copy tables */
2876
53.5k
        {   size_t const countSize = ZSTD_buildCTable(
2877
53.5k
                op, (size_t)(oend - op),
2878
53.5k
                CTable_MatchLength, MLFSELog, (SymbolEncodingType_e)stats.MLtype,
2879
53.5k
                countWorkspace, max, mlCodeTable, nbSeq,
2880
53.5k
                ML_defaultNorm, ML_defaultNormLog, MaxML,
2881
53.5k
                prevEntropy->matchlengthCTable,
2882
53.5k
                sizeof(prevEntropy->matchlengthCTable),
2883
53.5k
                entropyWorkspace, entropyWkspSize);
2884
53.5k
            if (ZSTD_isError(countSize)) {
2885
0
                DEBUGLOG(3, "ZSTD_buildCTable for MatchLengths failed");
2886
0
                stats.size = countSize;
2887
0
                return stats;
2888
0
            }
2889
53.5k
            if (stats.MLtype == set_compressed)
2890
19.9k
                stats.lastCountSize = countSize;
2891
53.5k
            op += countSize;
2892
53.5k
            assert(op <= oend);
2893
53.5k
    }   }
2894
0
    stats.size = (size_t)(op-ostart);
2895
53.5k
    return stats;
2896
53.5k
}
2897
2898
/* ZSTD_entropyCompressSeqStore_internal():
2899
 * compresses both literals and sequences
2900
 * Returns compressed size of block, or a zstd error.
2901
 */
2902
53.5k
#define SUSPECT_UNCOMPRESSIBLE_LITERAL_RATIO 20
2903
MEM_STATIC size_t
2904
ZSTD_entropyCompressSeqStore_internal(
2905
                              void* dst, size_t dstCapacity,
2906
                        const void* literals, size_t litSize,
2907
                        const SeqStore_t* seqStorePtr,
2908
                        const ZSTD_entropyCTables_t* prevEntropy,
2909
                              ZSTD_entropyCTables_t* nextEntropy,
2910
                        const ZSTD_CCtx_params* cctxParams,
2911
                              void* entropyWorkspace, size_t entropyWkspSize,
2912
                        const int bmi2)
2913
53.6k
{
2914
53.6k
    ZSTD_strategy const strategy = cctxParams->cParams.strategy;
2915
53.6k
    unsigned* count = (unsigned*)entropyWorkspace;
2916
53.6k
    FSE_CTable* CTable_LitLength = nextEntropy->fse.litlengthCTable;
2917
53.6k
    FSE_CTable* CTable_OffsetBits = nextEntropy->fse.offcodeCTable;
2918
53.6k
    FSE_CTable* CTable_MatchLength = nextEntropy->fse.matchlengthCTable;
2919
53.6k
    const SeqDef* const sequences = seqStorePtr->sequencesStart;
2920
53.6k
    const size_t nbSeq = (size_t)(seqStorePtr->sequences - seqStorePtr->sequencesStart);
2921
53.6k
    const BYTE* const ofCodeTable = seqStorePtr->ofCode;
2922
53.6k
    const BYTE* const llCodeTable = seqStorePtr->llCode;
2923
53.6k
    const BYTE* const mlCodeTable = seqStorePtr->mlCode;
2924
53.6k
    BYTE* const ostart = (BYTE*)dst;
2925
53.6k
    BYTE* const oend = ostart + dstCapacity;
2926
53.6k
    BYTE* op = ostart;
2927
53.6k
    size_t lastCountSize;
2928
53.6k
    int longOffsets = 0;
2929
2930
53.6k
    entropyWorkspace = count + (MaxSeq + 1);
2931
53.6k
    entropyWkspSize -= (MaxSeq + 1) * sizeof(*count);
2932
2933
53.6k
    DEBUGLOG(5, "ZSTD_entropyCompressSeqStore_internal (nbSeq=%zu, dstCapacity=%zu)", nbSeq, dstCapacity);
2934
53.6k
    ZSTD_STATIC_ASSERT(HUF_WORKSPACE_SIZE >= (1<<MAX(MLFSELog,LLFSELog)));
2935
53.6k
    assert(entropyWkspSize >= HUF_WORKSPACE_SIZE);
2936
2937
    /* Compress literals */
2938
53.6k
    {   size_t const numSequences = (size_t)(seqStorePtr->sequences - seqStorePtr->sequencesStart);
2939
        /* Base suspicion of uncompressibility on ratio of literals to sequences */
2940
53.6k
        int const suspectUncompressible = (numSequences == 0) || (litSize / numSequences >= SUSPECT_UNCOMPRESSIBLE_LITERAL_RATIO);
2941
2942
53.6k
        size_t const cSize = ZSTD_compressLiterals(
2943
53.6k
                                    op, dstCapacity,
2944
53.6k
                                    literals, litSize,
2945
53.6k
                                    entropyWorkspace, entropyWkspSize,
2946
53.6k
                                    &prevEntropy->huf, &nextEntropy->huf,
2947
53.6k
                                    cctxParams->cParams.strategy,
2948
53.6k
                                    ZSTD_literalsCompressionIsDisabled(cctxParams),
2949
53.6k
                                    suspectUncompressible, bmi2);
2950
53.6k
        FORWARD_IF_ERROR(cSize, "ZSTD_compressLiterals failed");
2951
53.6k
        assert(cSize <= dstCapacity);
2952
53.6k
        op += cSize;
2953
53.6k
    }
2954
2955
    /* Sequences Header */
2956
53.6k
    RETURN_ERROR_IF((oend-op) < 3 /*max nbSeq Size*/ + 1 /*seqHead*/,
2957
53.6k
                    dstSize_tooSmall, "Can't fit seq hdr in output buf!");
2958
53.6k
    if (nbSeq < 128) {
2959
31.3k
        *op++ = (BYTE)nbSeq;
2960
31.3k
    } else if (nbSeq < LONGNBSEQ) {
2961
22.2k
        op[0] = (BYTE)((nbSeq>>8) + 0x80);
2962
22.2k
        op[1] = (BYTE)nbSeq;
2963
22.2k
        op+=2;
2964
22.2k
    } else {
2965
0
        op[0]=0xFF;
2966
0
        MEM_writeLE16(op+1, (U16)(nbSeq - LONGNBSEQ));
2967
0
        op+=3;
2968
0
    }
2969
53.6k
    assert(op <= oend);
2970
53.6k
    if (nbSeq==0) {
2971
        /* Copy the old tables over as if we repeated them */
2972
86
        ZSTD_memcpy(&nextEntropy->fse, &prevEntropy->fse, sizeof(prevEntropy->fse));
2973
86
        return (size_t)(op - ostart);
2974
86
    }
2975
53.5k
    {   BYTE* const seqHead = op++;
2976
        /* build stats for sequences */
2977
53.5k
        const ZSTD_symbolEncodingTypeStats_t stats =
2978
53.5k
                ZSTD_buildSequencesStatistics(seqStorePtr, nbSeq,
2979
53.5k
                                             &prevEntropy->fse, &nextEntropy->fse,
2980
53.5k
                                              op, oend,
2981
53.5k
                                              strategy, count,
2982
53.5k
                                              entropyWorkspace, entropyWkspSize);
2983
53.5k
        FORWARD_IF_ERROR(stats.size, "ZSTD_buildSequencesStatistics failed!");
2984
53.5k
        *seqHead = (BYTE)((stats.LLtype<<6) + (stats.Offtype<<4) + (stats.MLtype<<2));
2985
53.5k
        lastCountSize = stats.lastCountSize;
2986
53.5k
        op += stats.size;
2987
53.5k
        longOffsets = stats.longOffsets;
2988
53.5k
    }
2989
2990
0
    {   size_t const bitstreamSize = ZSTD_encodeSequences(
2991
53.5k
                                        op, (size_t)(oend - op),
2992
53.5k
                                        CTable_MatchLength, mlCodeTable,
2993
53.5k
                                        CTable_OffsetBits, ofCodeTable,
2994
53.5k
                                        CTable_LitLength, llCodeTable,
2995
53.5k
                                        sequences, nbSeq,
2996
53.5k
                                        longOffsets, bmi2);
2997
53.5k
        FORWARD_IF_ERROR(bitstreamSize, "ZSTD_encodeSequences failed");
2998
53.5k
        op += bitstreamSize;
2999
53.5k
        assert(op <= oend);
3000
        /* zstd versions <= 1.3.4 mistakenly report corruption when
3001
         * FSE_readNCount() receives a buffer < 4 bytes.
3002
         * Fixed by https://github.com/facebook/zstd/pull/1146.
3003
         * This can happen when the last set_compressed table present is 2
3004
         * bytes and the bitstream is only one byte.
3005
         * In this exceedingly rare case, we will simply emit an uncompressed
3006
         * block, since it isn't worth optimizing.
3007
         */
3008
53.5k
        if (lastCountSize && (lastCountSize + bitstreamSize) < 4) {
3009
            /* lastCountSize >= 2 && bitstreamSize > 0 ==> lastCountSize == 3 */
3010
0
            assert(lastCountSize + bitstreamSize == 3);
3011
0
            DEBUGLOG(5, "Avoiding bug in zstd decoder in versions <= 1.3.4 by "
3012
0
                        "emitting an uncompressed block.");
3013
0
            return 0;
3014
0
        }
3015
53.5k
    }
3016
3017
53.5k
    DEBUGLOG(5, "compressed block size : %u", (unsigned)(op - ostart));
3018
53.5k
    return (size_t)(op - ostart);
3019
53.5k
}
3020
3021
static size_t
3022
ZSTD_entropyCompressSeqStore_wExtLitBuffer(
3023
                          void* dst, size_t dstCapacity,
3024
                    const void* literals, size_t litSize,
3025
                          size_t blockSize,
3026
                    const SeqStore_t* seqStorePtr,
3027
                    const ZSTD_entropyCTables_t* prevEntropy,
3028
                          ZSTD_entropyCTables_t* nextEntropy,
3029
                    const ZSTD_CCtx_params* cctxParams,
3030
                          void* entropyWorkspace, size_t entropyWkspSize,
3031
                          int bmi2)
3032
53.6k
{
3033
53.6k
    size_t const cSize = ZSTD_entropyCompressSeqStore_internal(
3034
53.6k
                            dst, dstCapacity,
3035
53.6k
                            literals, litSize,
3036
53.6k
                            seqStorePtr, prevEntropy, nextEntropy, cctxParams,
3037
53.6k
                            entropyWorkspace, entropyWkspSize, bmi2);
3038
53.6k
    if (cSize == 0) return 0;
3039
    /* When srcSize <= dstCapacity, there is enough space to write a raw uncompressed block.
3040
     * Since we ran out of space, block must be not compressible, so fall back to raw uncompressed block.
3041
     */
3042
53.6k
    if ((cSize == ERROR(dstSize_tooSmall)) & (blockSize <= dstCapacity)) {
3043
0
        DEBUGLOG(4, "not enough dstCapacity (%zu) for ZSTD_entropyCompressSeqStore_internal()=> do not compress block", dstCapacity);
3044
0
        return 0;  /* block not compressed */
3045
0
    }
3046
53.6k
    FORWARD_IF_ERROR(cSize, "ZSTD_entropyCompressSeqStore_internal failed");
3047
3048
    /* Check compressibility */
3049
53.6k
    {   size_t const maxCSize = blockSize - ZSTD_minGain(blockSize, cctxParams->cParams.strategy);
3050
53.6k
        if (cSize >= maxCSize) return 0;  /* block not compressed */
3051
53.6k
    }
3052
53.4k
    DEBUGLOG(5, "ZSTD_entropyCompressSeqStore() cSize: %zu", cSize);
3053
    /* libzstd decoder before  > v1.5.4 is not compatible with compressed blocks of size ZSTD_BLOCKSIZE_MAX exactly.
3054
     * This restriction is indirectly already fulfilled by respecting ZSTD_minGain() condition above.
3055
     */
3056
53.4k
    assert(cSize < ZSTD_BLOCKSIZE_MAX);
3057
53.4k
    return cSize;
3058
53.6k
}
3059
3060
static size_t
3061
ZSTD_entropyCompressSeqStore(
3062
                    const SeqStore_t* seqStorePtr,
3063
                    const ZSTD_entropyCTables_t* prevEntropy,
3064
                          ZSTD_entropyCTables_t* nextEntropy,
3065
                    const ZSTD_CCtx_params* cctxParams,
3066
                          void* dst, size_t dstCapacity,
3067
                          size_t srcSize,
3068
                          void* entropyWorkspace, size_t entropyWkspSize,
3069
                          int bmi2)
3070
53.6k
{
3071
53.6k
    return ZSTD_entropyCompressSeqStore_wExtLitBuffer(
3072
53.6k
                dst, dstCapacity,
3073
53.6k
                seqStorePtr->litStart, (size_t)(seqStorePtr->lit - seqStorePtr->litStart),
3074
53.6k
                srcSize,
3075
53.6k
                seqStorePtr,
3076
53.6k
                prevEntropy, nextEntropy,
3077
53.6k
                cctxParams,
3078
53.6k
                entropyWorkspace, entropyWkspSize,
3079
53.6k
                bmi2);
3080
53.6k
}
3081
3082
/* ZSTD_selectBlockCompressor() :
3083
 * Not static, but internal use only (used by long distance matcher)
3084
 * assumption : strat is a valid strategy */
3085
ZSTD_BlockCompressor_f ZSTD_selectBlockCompressor(ZSTD_strategy strat, ZSTD_ParamSwitch_e useRowMatchFinder, ZSTD_dictMode_e dictMode)
3086
53.6k
{
3087
53.6k
    static const ZSTD_BlockCompressor_f blockCompressor[4][ZSTD_STRATEGY_MAX+1] = {
3088
53.6k
        { ZSTD_compressBlock_fast  /* default for 0 */,
3089
53.6k
          ZSTD_compressBlock_fast,
3090
53.6k
          ZSTD_COMPRESSBLOCK_DOUBLEFAST,
3091
53.6k
          ZSTD_COMPRESSBLOCK_GREEDY,
3092
53.6k
          ZSTD_COMPRESSBLOCK_LAZY,
3093
53.6k
          ZSTD_COMPRESSBLOCK_LAZY2,
3094
53.6k
          ZSTD_COMPRESSBLOCK_BTLAZY2,
3095
53.6k
          ZSTD_COMPRESSBLOCK_BTOPT,
3096
53.6k
          ZSTD_COMPRESSBLOCK_BTULTRA,
3097
53.6k
          ZSTD_COMPRESSBLOCK_BTULTRA2
3098
53.6k
        },
3099
53.6k
        { ZSTD_compressBlock_fast_extDict  /* default for 0 */,
3100
53.6k
          ZSTD_compressBlock_fast_extDict,
3101
53.6k
          ZSTD_COMPRESSBLOCK_DOUBLEFAST_EXTDICT,
3102
53.6k
          ZSTD_COMPRESSBLOCK_GREEDY_EXTDICT,
3103
53.6k
          ZSTD_COMPRESSBLOCK_LAZY_EXTDICT,
3104
53.6k
          ZSTD_COMPRESSBLOCK_LAZY2_EXTDICT,
3105
53.6k
          ZSTD_COMPRESSBLOCK_BTLAZY2_EXTDICT,
3106
53.6k
          ZSTD_COMPRESSBLOCK_BTOPT_EXTDICT,
3107
53.6k
          ZSTD_COMPRESSBLOCK_BTULTRA_EXTDICT,
3108
53.6k
          ZSTD_COMPRESSBLOCK_BTULTRA_EXTDICT
3109
53.6k
        },
3110
53.6k
        { ZSTD_compressBlock_fast_dictMatchState  /* default for 0 */,
3111
53.6k
          ZSTD_compressBlock_fast_dictMatchState,
3112
53.6k
          ZSTD_COMPRESSBLOCK_DOUBLEFAST_DICTMATCHSTATE,
3113
53.6k
          ZSTD_COMPRESSBLOCK_GREEDY_DICTMATCHSTATE,
3114
53.6k
          ZSTD_COMPRESSBLOCK_LAZY_DICTMATCHSTATE,
3115
53.6k
          ZSTD_COMPRESSBLOCK_LAZY2_DICTMATCHSTATE,
3116
53.6k
          ZSTD_COMPRESSBLOCK_BTLAZY2_DICTMATCHSTATE,
3117
53.6k
          ZSTD_COMPRESSBLOCK_BTOPT_DICTMATCHSTATE,
3118
53.6k
          ZSTD_COMPRESSBLOCK_BTULTRA_DICTMATCHSTATE,
3119
53.6k
          ZSTD_COMPRESSBLOCK_BTULTRA_DICTMATCHSTATE
3120
53.6k
        },
3121
53.6k
        { NULL  /* default for 0 */,
3122
53.6k
          NULL,
3123
53.6k
          NULL,
3124
53.6k
          ZSTD_COMPRESSBLOCK_GREEDY_DEDICATEDDICTSEARCH,
3125
53.6k
          ZSTD_COMPRESSBLOCK_LAZY_DEDICATEDDICTSEARCH,
3126
53.6k
          ZSTD_COMPRESSBLOCK_LAZY2_DEDICATEDDICTSEARCH,
3127
53.6k
          NULL,
3128
53.6k
          NULL,
3129
53.6k
          NULL,
3130
53.6k
          NULL }
3131
53.6k
    };
3132
53.6k
    ZSTD_BlockCompressor_f selectedCompressor;
3133
53.6k
    ZSTD_STATIC_ASSERT((unsigned)ZSTD_fast == 1);
3134
3135
53.6k
    assert(ZSTD_cParam_withinBounds(ZSTD_c_strategy, (int)strat));
3136
53.6k
    DEBUGLOG(5, "Selected block compressor: dictMode=%d strat=%d rowMatchfinder=%d", (int)dictMode, (int)strat, (int)useRowMatchFinder);
3137
53.6k
    if (ZSTD_rowMatchFinderUsed(strat, useRowMatchFinder)) {
3138
53.6k
        static const ZSTD_BlockCompressor_f rowBasedBlockCompressors[4][3] = {
3139
53.6k
            {
3140
53.6k
                ZSTD_COMPRESSBLOCK_GREEDY_ROW,
3141
53.6k
                ZSTD_COMPRESSBLOCK_LAZY_ROW,
3142
53.6k
                ZSTD_COMPRESSBLOCK_LAZY2_ROW
3143
53.6k
            },
3144
53.6k
            {
3145
53.6k
                ZSTD_COMPRESSBLOCK_GREEDY_EXTDICT_ROW,
3146
53.6k
                ZSTD_COMPRESSBLOCK_LAZY_EXTDICT_ROW,
3147
53.6k
                ZSTD_COMPRESSBLOCK_LAZY2_EXTDICT_ROW
3148
53.6k
            },
3149
53.6k
            {
3150
53.6k
                ZSTD_COMPRESSBLOCK_GREEDY_DICTMATCHSTATE_ROW,
3151
53.6k
                ZSTD_COMPRESSBLOCK_LAZY_DICTMATCHSTATE_ROW,
3152
53.6k
                ZSTD_COMPRESSBLOCK_LAZY2_DICTMATCHSTATE_ROW
3153
53.6k
            },
3154
53.6k
            {
3155
53.6k
                ZSTD_COMPRESSBLOCK_GREEDY_DEDICATEDDICTSEARCH_ROW,
3156
53.6k
                ZSTD_COMPRESSBLOCK_LAZY_DEDICATEDDICTSEARCH_ROW,
3157
53.6k
                ZSTD_COMPRESSBLOCK_LAZY2_DEDICATEDDICTSEARCH_ROW
3158
53.6k
            }
3159
53.6k
        };
3160
53.6k
        DEBUGLOG(5, "Selecting a row-based matchfinder");
3161
53.6k
        assert(useRowMatchFinder != ZSTD_ps_auto);
3162
53.6k
        selectedCompressor = rowBasedBlockCompressors[(int)dictMode][(int)strat - (int)ZSTD_greedy];
3163
53.6k
    } else {
3164
0
        selectedCompressor = blockCompressor[(int)dictMode][(int)strat];
3165
0
    }
3166
53.6k
    assert(selectedCompressor != NULL);
3167
53.6k
    return selectedCompressor;
3168
53.6k
}
3169
3170
static void ZSTD_storeLastLiterals(SeqStore_t* seqStorePtr,
3171
                                   const BYTE* anchor, size_t lastLLSize)
3172
53.6k
{
3173
53.6k
    ZSTD_memcpy(seqStorePtr->lit, anchor, lastLLSize);
3174
53.6k
    seqStorePtr->lit += lastLLSize;
3175
53.6k
}
3176
3177
void ZSTD_resetSeqStore(SeqStore_t* ssPtr)
3178
53.6k
{
3179
53.6k
    ssPtr->lit = ssPtr->litStart;
3180
53.6k
    ssPtr->sequences = ssPtr->sequencesStart;
3181
53.6k
    ssPtr->longLengthType = ZSTD_llt_none;
3182
53.6k
}
3183
3184
/* ZSTD_postProcessSequenceProducerResult() :
3185
 * Validates and post-processes sequences obtained through the external matchfinder API:
3186
 *   - Checks whether nbExternalSeqs represents an error condition.
3187
 *   - Appends a block delimiter to outSeqs if one is not already present.
3188
 *     See zstd.h for context regarding block delimiters.
3189
 * Returns the number of sequences after post-processing, or an error code. */
3190
static size_t ZSTD_postProcessSequenceProducerResult(
3191
    ZSTD_Sequence* outSeqs, size_t nbExternalSeqs, size_t outSeqsCapacity, size_t srcSize
3192
0
) {
3193
0
    RETURN_ERROR_IF(
3194
0
        nbExternalSeqs > outSeqsCapacity,
3195
0
        sequenceProducer_failed,
3196
0
        "External sequence producer returned error code %lu",
3197
0
        (unsigned long)nbExternalSeqs
3198
0
    );
3199
3200
0
    RETURN_ERROR_IF(
3201
0
        nbExternalSeqs == 0 && srcSize > 0,
3202
0
        sequenceProducer_failed,
3203
0
        "Got zero sequences from external sequence producer for a non-empty src buffer!"
3204
0
    );
3205
3206
0
    if (srcSize == 0) {
3207
0
        ZSTD_memset(&outSeqs[0], 0, sizeof(ZSTD_Sequence));
3208
0
        return 1;
3209
0
    }
3210
3211
0
    {
3212
0
        ZSTD_Sequence const lastSeq = outSeqs[nbExternalSeqs - 1];
3213
3214
        /* We can return early if lastSeq is already a block delimiter. */
3215
0
        if (lastSeq.offset == 0 && lastSeq.matchLength == 0) {
3216
0
            return nbExternalSeqs;
3217
0
        }
3218
3219
        /* This error condition is only possible if the external matchfinder
3220
         * produced an invalid parse, by definition of ZSTD_sequenceBound(). */
3221
0
        RETURN_ERROR_IF(
3222
0
            nbExternalSeqs == outSeqsCapacity,
3223
0
            sequenceProducer_failed,
3224
0
            "nbExternalSeqs == outSeqsCapacity but lastSeq is not a block delimiter!"
3225
0
        );
3226
3227
        /* lastSeq is not a block delimiter, so we need to append one. */
3228
0
        ZSTD_memset(&outSeqs[nbExternalSeqs], 0, sizeof(ZSTD_Sequence));
3229
0
        return nbExternalSeqs + 1;
3230
0
    }
3231
0
}
3232
3233
/* ZSTD_fastSequenceLengthSum() :
3234
 * Returns sum(litLen) + sum(matchLen) + lastLits for *seqBuf*.
3235
 * Similar to another function in zstd_compress.c (determine_blockSize),
3236
 * except it doesn't check for a block delimiter to end summation.
3237
 * Removing the early exit allows the compiler to auto-vectorize (https://godbolt.org/z/cY1cajz9P).
3238
 * This function can be deleted and replaced by determine_blockSize after we resolve issue #3456. */
3239
0
static size_t ZSTD_fastSequenceLengthSum(ZSTD_Sequence const* seqBuf, size_t seqBufSize) {
3240
0
    size_t matchLenSum, litLenSum, i;
3241
0
    matchLenSum = 0;
3242
0
    litLenSum = 0;
3243
0
    for (i = 0; i < seqBufSize; i++) {
3244
0
        litLenSum += seqBuf[i].litLength;
3245
0
        matchLenSum += seqBuf[i].matchLength;
3246
0
    }
3247
0
    return litLenSum + matchLenSum;
3248
0
}
3249
3250
/**
3251
 * Function to validate sequences produced by a block compressor.
3252
 */
3253
static void ZSTD_validateSeqStore(const SeqStore_t* seqStore, const ZSTD_compressionParameters* cParams)
3254
53.6k
{
3255
#if DEBUGLEVEL >= 1
3256
    const SeqDef* seq = seqStore->sequencesStart;
3257
    const SeqDef* const seqEnd = seqStore->sequences;
3258
    size_t const matchLenLowerBound = cParams->minMatch == 3 ? 3 : 4;
3259
    for (; seq < seqEnd; ++seq) {
3260
        const ZSTD_SequenceLength seqLength = ZSTD_getSequenceLength(seqStore, seq);
3261
        assert(seqLength.matchLength >= matchLenLowerBound);
3262
        (void)seqLength;
3263
        (void)matchLenLowerBound;
3264
    }
3265
#else
3266
53.6k
    (void)seqStore;
3267
53.6k
    (void)cParams;
3268
53.6k
#endif
3269
53.6k
}
3270
3271
static size_t
3272
ZSTD_transferSequences_wBlockDelim(ZSTD_CCtx* cctx,
3273
                                   ZSTD_SequencePosition* seqPos,
3274
                             const ZSTD_Sequence* const inSeqs, size_t inSeqsSize,
3275
                             const void* src, size_t blockSize,
3276
                                   ZSTD_ParamSwitch_e externalRepSearch);
3277
3278
typedef enum { ZSTDbss_compress, ZSTDbss_noCompress } ZSTD_BuildSeqStore_e;
3279
3280
static size_t ZSTD_buildSeqStore(ZSTD_CCtx* zc, const void* src, size_t srcSize)
3281
53.6k
{
3282
53.6k
    ZSTD_MatchState_t* const ms = &zc->blockState.matchState;
3283
53.6k
    DEBUGLOG(5, "ZSTD_buildSeqStore (srcSize=%zu)", srcSize);
3284
53.6k
    assert(srcSize <= ZSTD_BLOCKSIZE_MAX);
3285
    /* Assert that we have correctly flushed the ctx params into the ms's copy */
3286
53.6k
    ZSTD_assertEqualCParams(zc->appliedParams.cParams, ms->cParams);
3287
    /* TODO: See 3090. We reduced MIN_CBLOCK_SIZE from 3 to 2 so to compensate we are adding
3288
     * additional 1. We need to revisit and change this logic to be more consistent */
3289
53.6k
    if (srcSize < MIN_CBLOCK_SIZE+ZSTD_blockHeaderSize+1+1) {
3290
11
        if (zc->appliedParams.cParams.strategy >= ZSTD_btopt) {
3291
0
            ZSTD_ldm_skipRawSeqStoreBytes(&zc->externSeqStore, srcSize);
3292
11
        } else {
3293
11
            ZSTD_ldm_skipSequences(&zc->externSeqStore, srcSize, zc->appliedParams.cParams.minMatch);
3294
11
        }
3295
11
        return ZSTDbss_noCompress; /* don't even attempt compression below a certain srcSize */
3296
11
    }
3297
53.6k
    ZSTD_resetSeqStore(&(zc->seqStore));
3298
    /* required for optimal parser to read stats from dictionary */
3299
53.6k
    ms->opt.symbolCosts = &zc->blockState.prevCBlock->entropy;
3300
    /* tell the optimal parser how we expect to compress literals */
3301
53.6k
    ms->opt.literalCompressionMode = zc->appliedParams.literalCompressionMode;
3302
    /* a gap between an attached dict and the current window is not safe,
3303
     * they must remain adjacent,
3304
     * and when that stops being the case, the dict must be unset */
3305
53.6k
    assert(ms->dictMatchState == NULL || ms->loadedDictEnd == ms->window.dictLimit);
3306
3307
    /* limited update after a very long match */
3308
53.6k
    {   const BYTE* const base = ms->window.base;
3309
53.6k
        const BYTE* const istart = (const BYTE*)src;
3310
53.6k
        const U32 curr = (U32)(istart-base);
3311
53.6k
        if (sizeof(ptrdiff_t)==8) assert(istart - base < (ptrdiff_t)(U32)(-1));   /* ensure no overflow */
3312
53.6k
        if (curr > ms->nextToUpdate + 384)
3313
30.7k
            ms->nextToUpdate = curr - MIN(192, (U32)(curr - ms->nextToUpdate - 384));
3314
53.6k
    }
3315
3316
    /* select and store sequences */
3317
53.6k
    {   ZSTD_dictMode_e const dictMode = ZSTD_matchState_dictMode(ms);
3318
53.6k
        size_t lastLLSize;
3319
53.6k
        {   int i;
3320
214k
            for (i = 0; i < ZSTD_REP_NUM; ++i)
3321
160k
                zc->blockState.nextCBlock->rep[i] = zc->blockState.prevCBlock->rep[i];
3322
53.6k
        }
3323
53.6k
        if (zc->externSeqStore.pos < zc->externSeqStore.size) {
3324
0
            assert(zc->appliedParams.ldmParams.enableLdm == ZSTD_ps_disable);
3325
3326
            /* External matchfinder + LDM is technically possible, just not implemented yet.
3327
             * We need to revisit soon and implement it. */
3328
0
            RETURN_ERROR_IF(
3329
0
                ZSTD_hasExtSeqProd(&zc->appliedParams),
3330
0
                parameter_combination_unsupported,
3331
0
                "Long-distance matching with external sequence producer enabled is not currently supported."
3332
0
            );
3333
3334
            /* Updates ldmSeqStore.pos */
3335
0
            lastLLSize =
3336
0
                ZSTD_ldm_blockCompress(&zc->externSeqStore,
3337
0
                                       ms, &zc->seqStore,
3338
0
                                       zc->blockState.nextCBlock->rep,
3339
0
                                       zc->appliedParams.useRowMatchFinder,
3340
0
                                       src, srcSize);
3341
0
            assert(zc->externSeqStore.pos <= zc->externSeqStore.size);
3342
53.6k
        } else if (zc->appliedParams.ldmParams.enableLdm == ZSTD_ps_enable) {
3343
0
            RawSeqStore_t ldmSeqStore = kNullRawSeqStore;
3344
3345
            /* External matchfinder + LDM is technically possible, just not implemented yet.
3346
             * We need to revisit soon and implement it. */
3347
0
            RETURN_ERROR_IF(
3348
0
                ZSTD_hasExtSeqProd(&zc->appliedParams),
3349
0
                parameter_combination_unsupported,
3350
0
                "Long-distance matching with external sequence producer enabled is not currently supported."
3351
0
            );
3352
3353
0
            ldmSeqStore.seq = zc->ldmSequences;
3354
0
            ldmSeqStore.capacity = zc->maxNbLdmSequences;
3355
            /* Updates ldmSeqStore.size */
3356
0
            FORWARD_IF_ERROR(ZSTD_ldm_generateSequences(&zc->ldmState, &ldmSeqStore,
3357
0
                                               &zc->appliedParams.ldmParams,
3358
0
                                               src, srcSize), "");
3359
            /* Updates ldmSeqStore.pos */
3360
0
            lastLLSize =
3361
0
                ZSTD_ldm_blockCompress(&ldmSeqStore,
3362
0
                                       ms, &zc->seqStore,
3363
0
                                       zc->blockState.nextCBlock->rep,
3364
0
                                       zc->appliedParams.useRowMatchFinder,
3365
0
                                       src, srcSize);
3366
0
            assert(ldmSeqStore.pos == ldmSeqStore.size);
3367
53.6k
        } else if (ZSTD_hasExtSeqProd(&zc->appliedParams)) {
3368
0
            assert(
3369
0
                zc->extSeqBufCapacity >= ZSTD_sequenceBound(srcSize)
3370
0
            );
3371
0
            assert(zc->appliedParams.extSeqProdFunc != NULL);
3372
3373
0
            {   U32 const windowSize = (U32)1 << zc->appliedParams.cParams.windowLog;
3374
3375
0
                size_t const nbExternalSeqs = (zc->appliedParams.extSeqProdFunc)(
3376
0
                    zc->appliedParams.extSeqProdState,
3377
0
                    zc->extSeqBuf,
3378
0
                    zc->extSeqBufCapacity,
3379
0
                    src, srcSize,
3380
0
                    NULL, 0,  /* dict and dictSize, currently not supported */
3381
0
                    zc->appliedParams.compressionLevel,
3382
0
                    windowSize
3383
0
                );
3384
3385
0
                size_t const nbPostProcessedSeqs = ZSTD_postProcessSequenceProducerResult(
3386
0
                    zc->extSeqBuf,
3387
0
                    nbExternalSeqs,
3388
0
                    zc->extSeqBufCapacity,
3389
0
                    srcSize
3390
0
                );
3391
3392
                /* Return early if there is no error, since we don't need to worry about last literals */
3393
0
                if (!ZSTD_isError(nbPostProcessedSeqs)) {
3394
0
                    ZSTD_SequencePosition seqPos = {0,0,0};
3395
0
                    size_t const seqLenSum = ZSTD_fastSequenceLengthSum(zc->extSeqBuf, nbPostProcessedSeqs);
3396
0
                    RETURN_ERROR_IF(seqLenSum > srcSize, externalSequences_invalid, "External sequences imply too large a block!");
3397
0
                    FORWARD_IF_ERROR(
3398
0
                        ZSTD_transferSequences_wBlockDelim(
3399
0
                            zc, &seqPos,
3400
0
                            zc->extSeqBuf, nbPostProcessedSeqs,
3401
0
                            src, srcSize,
3402
0
                            zc->appliedParams.searchForExternalRepcodes
3403
0
                        ),
3404
0
                        "Failed to copy external sequences to seqStore!"
3405
0
                    );
3406
0
                    ms->ldmSeqStore = NULL;
3407
0
                    DEBUGLOG(5, "Copied %lu sequences from external sequence producer to internal seqStore.", (unsigned long)nbExternalSeqs);
3408
0
                    return ZSTDbss_compress;
3409
0
                }
3410
3411
                /* Propagate the error if fallback is disabled */
3412
0
                if (!zc->appliedParams.enableMatchFinderFallback) {
3413
0
                    return nbPostProcessedSeqs;
3414
0
                }
3415
3416
                /* Fallback to software matchfinder */
3417
0
                {   ZSTD_BlockCompressor_f const blockCompressor =
3418
0
                        ZSTD_selectBlockCompressor(
3419
0
                            zc->appliedParams.cParams.strategy,
3420
0
                            zc->appliedParams.useRowMatchFinder,
3421
0
                            dictMode);
3422
0
                    ms->ldmSeqStore = NULL;
3423
0
                    DEBUGLOG(
3424
0
                        5,
3425
0
                        "External sequence producer returned error code %lu. Falling back to internal parser.",
3426
0
                        (unsigned long)nbExternalSeqs
3427
0
                    );
3428
0
                    lastLLSize = blockCompressor(ms, &zc->seqStore, zc->blockState.nextCBlock->rep, src, srcSize);
3429
0
            }   }
3430
53.6k
        } else {   /* not long range mode and no external matchfinder */
3431
53.6k
            ZSTD_BlockCompressor_f const blockCompressor = ZSTD_selectBlockCompressor(
3432
53.6k
                    zc->appliedParams.cParams.strategy,
3433
53.6k
                    zc->appliedParams.useRowMatchFinder,
3434
53.6k
                    dictMode);
3435
53.6k
            ms->ldmSeqStore = NULL;
3436
53.6k
            lastLLSize = blockCompressor(ms, &zc->seqStore, zc->blockState.nextCBlock->rep, src, srcSize);
3437
53.6k
        }
3438
53.6k
        {   const BYTE* const lastLiterals = (const BYTE*)src + srcSize - lastLLSize;
3439
53.6k
            ZSTD_storeLastLiterals(&zc->seqStore, lastLiterals, lastLLSize);
3440
53.6k
    }   }
3441
0
    ZSTD_validateSeqStore(&zc->seqStore, &zc->appliedParams.cParams);
3442
53.6k
    return ZSTDbss_compress;
3443
53.6k
}
3444
3445
static size_t ZSTD_copyBlockSequences(SeqCollector* seqCollector, const SeqStore_t* seqStore, const U32 prevRepcodes[ZSTD_REP_NUM])
3446
0
{
3447
0
    const SeqDef* inSeqs = seqStore->sequencesStart;
3448
0
    const size_t nbInSequences = (size_t)(seqStore->sequences - inSeqs);
3449
0
    const size_t nbInLiterals = (size_t)(seqStore->lit - seqStore->litStart);
3450
3451
0
    ZSTD_Sequence* outSeqs = seqCollector->seqIndex == 0 ? seqCollector->seqStart : seqCollector->seqStart + seqCollector->seqIndex;
3452
0
    const size_t nbOutSequences = nbInSequences + 1;
3453
0
    size_t nbOutLiterals = 0;
3454
0
    Repcodes_t repcodes;
3455
0
    size_t i;
3456
3457
    /* Bounds check that we have enough space for every input sequence
3458
     * and the block delimiter
3459
     */
3460
0
    assert(seqCollector->seqIndex <= seqCollector->maxSequences);
3461
0
    RETURN_ERROR_IF(
3462
0
        nbOutSequences > (size_t)(seqCollector->maxSequences - seqCollector->seqIndex),
3463
0
        dstSize_tooSmall,
3464
0
        "Not enough space to copy sequences");
3465
3466
0
    ZSTD_memcpy(&repcodes, prevRepcodes, sizeof(repcodes));
3467
0
    for (i = 0; i < nbInSequences; ++i) {
3468
0
        U32 rawOffset;
3469
0
        outSeqs[i].litLength = inSeqs[i].litLength;
3470
0
        outSeqs[i].matchLength = inSeqs[i].mlBase + MINMATCH;
3471
0
        outSeqs[i].rep = 0;
3472
3473
        /* Handle the possible single length >= 64K
3474
         * There can only be one because we add MINMATCH to every match length,
3475
         * and blocks are at most 128K.
3476
         */
3477
0
        if (i == seqStore->longLengthPos) {
3478
0
            if (seqStore->longLengthType == ZSTD_llt_literalLength) {
3479
0
                outSeqs[i].litLength += 0x10000;
3480
0
            } else if (seqStore->longLengthType == ZSTD_llt_matchLength) {
3481
0
                outSeqs[i].matchLength += 0x10000;
3482
0
            }
3483
0
        }
3484
3485
        /* Determine the raw offset given the offBase, which may be a repcode. */
3486
0
        if (OFFBASE_IS_REPCODE(inSeqs[i].offBase)) {
3487
0
            const U32 repcode = OFFBASE_TO_REPCODE(inSeqs[i].offBase);
3488
0
            assert(repcode > 0);
3489
0
            outSeqs[i].rep = repcode;
3490
0
            if (outSeqs[i].litLength != 0) {
3491
0
                rawOffset = repcodes.rep[repcode - 1];
3492
0
            } else {
3493
0
                if (repcode == 3) {
3494
0
                    assert(repcodes.rep[0] > 1);
3495
0
                    rawOffset = repcodes.rep[0] - 1;
3496
0
                } else {
3497
0
                    rawOffset = repcodes.rep[repcode];
3498
0
                }
3499
0
            }
3500
0
        } else {
3501
0
            rawOffset = OFFBASE_TO_OFFSET(inSeqs[i].offBase);
3502
0
        }
3503
0
        outSeqs[i].offset = rawOffset;
3504
3505
        /* Update repcode history for the sequence */
3506
0
        ZSTD_updateRep(repcodes.rep,
3507
0
                       inSeqs[i].offBase,
3508
0
                       inSeqs[i].litLength == 0);
3509
3510
0
        nbOutLiterals += outSeqs[i].litLength;
3511
0
    }
3512
    /* Insert last literals (if any exist) in the block as a sequence with ml == off == 0.
3513
     * If there are no last literals, then we'll emit (of: 0, ml: 0, ll: 0), which is a marker
3514
     * for the block boundary, according to the API.
3515
     */
3516
0
    assert(nbInLiterals >= nbOutLiterals);
3517
0
    {
3518
0
        const size_t lastLLSize = nbInLiterals - nbOutLiterals;
3519
0
        outSeqs[nbInSequences].litLength = (U32)lastLLSize;
3520
0
        outSeqs[nbInSequences].matchLength = 0;
3521
0
        outSeqs[nbInSequences].offset = 0;
3522
0
        assert(nbOutSequences == nbInSequences + 1);
3523
0
    }
3524
0
    seqCollector->seqIndex += nbOutSequences;
3525
0
    assert(seqCollector->seqIndex <= seqCollector->maxSequences);
3526
3527
0
    return 0;
3528
0
}
3529
3530
15.4k
size_t ZSTD_sequenceBound(size_t srcSize) {
3531
15.4k
    const size_t maxNbSeq = (srcSize / ZSTD_MINMATCH_MIN) + 1;
3532
15.4k
    const size_t maxNbDelims = (srcSize / ZSTD_BLOCKSIZE_MAX_MIN) + 1;
3533
15.4k
    return maxNbSeq + maxNbDelims;
3534
15.4k
}
3535
3536
size_t ZSTD_generateSequences(ZSTD_CCtx* zc, ZSTD_Sequence* outSeqs,
3537
                              size_t outSeqsSize, const void* src, size_t srcSize)
3538
0
{
3539
0
    const size_t dstCapacity = ZSTD_compressBound(srcSize);
3540
0
    void* dst; /* Make C90 happy. */
3541
0
    SeqCollector seqCollector;
3542
0
    {
3543
0
        int targetCBlockSize;
3544
0
        FORWARD_IF_ERROR(ZSTD_CCtx_getParameter(zc, ZSTD_c_targetCBlockSize, &targetCBlockSize), "");
3545
0
        RETURN_ERROR_IF(targetCBlockSize != 0, parameter_unsupported, "targetCBlockSize != 0");
3546
0
    }
3547
0
    {
3548
0
        int nbWorkers;
3549
0
        FORWARD_IF_ERROR(ZSTD_CCtx_getParameter(zc, ZSTD_c_nbWorkers, &nbWorkers), "");
3550
0
        RETURN_ERROR_IF(nbWorkers != 0, parameter_unsupported, "nbWorkers != 0");
3551
0
    }
3552
3553
0
    dst = ZSTD_customMalloc(dstCapacity, ZSTD_defaultCMem);
3554
0
    RETURN_ERROR_IF(dst == NULL, memory_allocation, "NULL pointer!");
3555
3556
0
    seqCollector.collectSequences = 1;
3557
0
    seqCollector.seqStart = outSeqs;
3558
0
    seqCollector.seqIndex = 0;
3559
0
    seqCollector.maxSequences = outSeqsSize;
3560
0
    zc->seqCollector = seqCollector;
3561
3562
0
    {
3563
0
        const size_t ret = ZSTD_compress2(zc, dst, dstCapacity, src, srcSize);
3564
0
        ZSTD_customFree(dst, ZSTD_defaultCMem);
3565
0
        FORWARD_IF_ERROR(ret, "ZSTD_compress2 failed");
3566
0
    }
3567
0
    assert(zc->seqCollector.seqIndex <= ZSTD_sequenceBound(srcSize));
3568
0
    return zc->seqCollector.seqIndex;
3569
0
}
3570
3571
0
size_t ZSTD_mergeBlockDelimiters(ZSTD_Sequence* sequences, size_t seqsSize) {
3572
0
    size_t in = 0;
3573
0
    size_t out = 0;
3574
0
    for (; in < seqsSize; ++in) {
3575
0
        if (sequences[in].offset == 0 && sequences[in].matchLength == 0) {
3576
0
            if (in != seqsSize - 1) {
3577
0
                sequences[in+1].litLength += sequences[in].litLength;
3578
0
            }
3579
0
        } else {
3580
0
            sequences[out] = sequences[in];
3581
0
            ++out;
3582
0
        }
3583
0
    }
3584
0
    return out;
3585
0
}
3586
3587
/* Unrolled loop to read four size_ts of input at a time. Returns 1 if is RLE, 0 if not. */
3588
14.6k
static int ZSTD_isRLE(const BYTE* src, size_t length) {
3589
14.6k
    const BYTE* ip = src;
3590
14.6k
    const BYTE value = ip[0];
3591
14.6k
    const size_t valueST = (size_t)((U64)value * 0x0101010101010101ULL);
3592
14.6k
    const size_t unrollSize = sizeof(size_t) * 4;
3593
14.6k
    const size_t unrollMask = unrollSize - 1;
3594
14.6k
    const size_t prefixLength = length & unrollMask;
3595
14.6k
    size_t i;
3596
14.6k
    if (length == 1) return 1;
3597
    /* Check if prefix is RLE first before using unrolled loop */
3598
14.6k
    if (prefixLength && ZSTD_count(ip+1, ip, ip+prefixLength) != prefixLength-1) {
3599
1.47k
        return 0;
3600
1.47k
    }
3601
3.02M
    for (i = prefixLength; i != length; i += unrollSize) {
3602
3.02M
        size_t u;
3603
15.0M
        for (u = 0; u < unrollSize; u += sizeof(size_t)) {
3604
12.0M
            if (MEM_readST(ip + i + u) != valueST) {
3605
12.3k
                return 0;
3606
12.3k
    }   }   }
3607
831
    return 1;
3608
13.1k
}
3609
3610
/* Returns true if the given block may be RLE.
3611
 * This is just a heuristic based on the compressibility.
3612
 * It may return both false positives and false negatives.
3613
 */
3614
static int ZSTD_maybeRLE(SeqStore_t const* seqStore)
3615
0
{
3616
0
    size_t const nbSeqs = (size_t)(seqStore->sequences - seqStore->sequencesStart);
3617
0
    size_t const nbLits = (size_t)(seqStore->lit - seqStore->litStart);
3618
3619
0
    return nbSeqs < 4 && nbLits < 10;
3620
0
}
3621
3622
static void
3623
ZSTD_blockState_confirmRepcodesAndEntropyTables(ZSTD_blockState_t* const bs)
3624
52.6k
{
3625
52.6k
    ZSTD_compressedBlockState_t* const tmp = bs->prevCBlock;
3626
52.6k
    bs->prevCBlock = bs->nextCBlock;
3627
52.6k
    bs->nextCBlock = tmp;
3628
52.6k
}
3629
3630
/* Writes the block header */
3631
static void
3632
writeBlockHeader(void* op, size_t cSize, size_t blockSize, U32 lastBlock)
3633
0
{
3634
0
    U32 const cBlockHeader = cSize == 1 ?
3635
0
                        lastBlock + (((U32)bt_rle)<<1) + (U32)(blockSize << 3) :
3636
0
                        lastBlock + (((U32)bt_compressed)<<1) + (U32)(cSize << 3);
3637
0
    MEM_writeLE24(op, cBlockHeader);
3638
0
    DEBUGLOG(5, "writeBlockHeader: cSize: %zu blockSize: %zu lastBlock: %u", cSize, blockSize, lastBlock);
3639
0
}
3640
3641
/** ZSTD_buildBlockEntropyStats_literals() :
3642
 *  Builds entropy for the literals.
3643
 *  Stores literals block type (raw, rle, compressed, repeat) and
3644
 *  huffman description table to hufMetadata.
3645
 *  Requires ENTROPY_WORKSPACE_SIZE workspace
3646
 * @return : size of huffman description table, or an error code
3647
 */
3648
static size_t
3649
ZSTD_buildBlockEntropyStats_literals(void* const src, size_t srcSize,
3650
                               const ZSTD_hufCTables_t* prevHuf,
3651
                                     ZSTD_hufCTables_t* nextHuf,
3652
                                     ZSTD_hufCTablesMetadata_t* hufMetadata,
3653
                               const int literalsCompressionIsDisabled,
3654
                                     void* workspace, size_t wkspSize,
3655
                                     int hufFlags)
3656
0
{
3657
0
    BYTE* const wkspStart = (BYTE*)workspace;
3658
0
    BYTE* const wkspEnd = wkspStart + wkspSize;
3659
0
    BYTE* const countWkspStart = wkspStart;
3660
0
    unsigned* const countWksp = (unsigned*)workspace;
3661
0
    const size_t countWkspSize = (HUF_SYMBOLVALUE_MAX + 1) * sizeof(unsigned);
3662
0
    BYTE* const nodeWksp = countWkspStart + countWkspSize;
3663
0
    const size_t nodeWkspSize = (size_t)(wkspEnd - nodeWksp);
3664
0
    unsigned maxSymbolValue = HUF_SYMBOLVALUE_MAX;
3665
0
    unsigned huffLog = LitHufLog;
3666
0
    HUF_repeat repeat = prevHuf->repeatMode;
3667
0
    DEBUGLOG(5, "ZSTD_buildBlockEntropyStats_literals (srcSize=%zu)", srcSize);
3668
3669
    /* Prepare nextEntropy assuming reusing the existing table */
3670
0
    ZSTD_memcpy(nextHuf, prevHuf, sizeof(*prevHuf));
3671
3672
0
    if (literalsCompressionIsDisabled) {
3673
0
        DEBUGLOG(5, "set_basic - disabled");
3674
0
        hufMetadata->hType = set_basic;
3675
0
        return 0;
3676
0
    }
3677
3678
    /* small ? don't even attempt compression (speed opt) */
3679
0
#ifndef COMPRESS_LITERALS_SIZE_MIN
3680
0
# define COMPRESS_LITERALS_SIZE_MIN 63  /* heuristic */
3681
0
#endif
3682
0
    {   size_t const minLitSize = (prevHuf->repeatMode == HUF_repeat_valid) ? 6 : COMPRESS_LITERALS_SIZE_MIN;
3683
0
        if (srcSize <= minLitSize) {
3684
0
            DEBUGLOG(5, "set_basic - too small");
3685
0
            hufMetadata->hType = set_basic;
3686
0
            return 0;
3687
0
    }   }
3688
3689
    /* Scan input and build symbol stats */
3690
0
    {   size_t const largest =
3691
0
            HIST_count_wksp (countWksp, &maxSymbolValue,
3692
0
                            (const BYTE*)src, srcSize,
3693
0
                            workspace, wkspSize);
3694
0
        FORWARD_IF_ERROR(largest, "HIST_count_wksp failed");
3695
0
        if (largest == srcSize) {
3696
            /* only one literal symbol */
3697
0
            DEBUGLOG(5, "set_rle");
3698
0
            hufMetadata->hType = set_rle;
3699
0
            return 0;
3700
0
        }
3701
0
        if (largest <= (srcSize >> 7)+4) {
3702
            /* heuristic: likely not compressible */
3703
0
            DEBUGLOG(5, "set_basic - no gain");
3704
0
            hufMetadata->hType = set_basic;
3705
0
            return 0;
3706
0
    }   }
3707
3708
    /* Validate the previous Huffman table */
3709
0
    if (repeat == HUF_repeat_check
3710
0
      && !HUF_validateCTable((HUF_CElt const*)prevHuf->CTable, countWksp, maxSymbolValue)) {
3711
0
        repeat = HUF_repeat_none;
3712
0
    }
3713
3714
    /* Build Huffman Tree */
3715
0
    ZSTD_memset(nextHuf->CTable, 0, sizeof(nextHuf->CTable));
3716
0
    huffLog = HUF_optimalTableLog(huffLog, srcSize, maxSymbolValue, nodeWksp, nodeWkspSize, nextHuf->CTable, countWksp, hufFlags);
3717
0
    assert(huffLog <= LitHufLog);
3718
0
    {   size_t const maxBits = HUF_buildCTable_wksp((HUF_CElt*)nextHuf->CTable, countWksp,
3719
0
                                                    maxSymbolValue, huffLog,
3720
0
                                                    nodeWksp, nodeWkspSize);
3721
0
        FORWARD_IF_ERROR(maxBits, "HUF_buildCTable_wksp");
3722
0
        huffLog = (U32)maxBits;
3723
0
    }
3724
0
    {   /* Build and write the CTable */
3725
0
        size_t const newCSize = HUF_estimateCompressedSize(
3726
0
                (HUF_CElt*)nextHuf->CTable, countWksp, maxSymbolValue);
3727
0
        size_t const hSize = HUF_writeCTable_wksp(
3728
0
                hufMetadata->hufDesBuffer, sizeof(hufMetadata->hufDesBuffer),
3729
0
                (HUF_CElt*)nextHuf->CTable, maxSymbolValue, huffLog,
3730
0
                nodeWksp, nodeWkspSize);
3731
        /* Check against repeating the previous CTable */
3732
0
        if (repeat != HUF_repeat_none) {
3733
0
            size_t const oldCSize = HUF_estimateCompressedSize(
3734
0
                    (HUF_CElt const*)prevHuf->CTable, countWksp, maxSymbolValue);
3735
0
            if (oldCSize < srcSize && (oldCSize <= hSize + newCSize || hSize + 12 >= srcSize)) {
3736
0
                DEBUGLOG(5, "set_repeat - smaller");
3737
0
                ZSTD_memcpy(nextHuf, prevHuf, sizeof(*prevHuf));
3738
0
                hufMetadata->hType = set_repeat;
3739
0
                return 0;
3740
0
        }   }
3741
0
        if (newCSize + hSize >= srcSize) {
3742
0
            DEBUGLOG(5, "set_basic - no gains");
3743
0
            ZSTD_memcpy(nextHuf, prevHuf, sizeof(*prevHuf));
3744
0
            hufMetadata->hType = set_basic;
3745
0
            return 0;
3746
0
        }
3747
0
        DEBUGLOG(5, "set_compressed (hSize=%u)", (U32)hSize);
3748
0
        hufMetadata->hType = set_compressed;
3749
0
        nextHuf->repeatMode = HUF_repeat_check;
3750
0
        return hSize;
3751
0
    }
3752
0
}
3753
3754
3755
/* ZSTD_buildDummySequencesStatistics():
3756
 * Returns a ZSTD_symbolEncodingTypeStats_t with all encoding types as set_basic,
3757
 * and updates nextEntropy to the appropriate repeatMode.
3758
 */
3759
static ZSTD_symbolEncodingTypeStats_t
3760
ZSTD_buildDummySequencesStatistics(ZSTD_fseCTables_t* nextEntropy)
3761
0
{
3762
0
    ZSTD_symbolEncodingTypeStats_t stats = {set_basic, set_basic, set_basic, 0, 0, 0};
3763
0
    nextEntropy->litlength_repeatMode = FSE_repeat_none;
3764
0
    nextEntropy->offcode_repeatMode = FSE_repeat_none;
3765
0
    nextEntropy->matchlength_repeatMode = FSE_repeat_none;
3766
0
    return stats;
3767
0
}
3768
3769
/** ZSTD_buildBlockEntropyStats_sequences() :
3770
 *  Builds entropy for the sequences.
3771
 *  Stores symbol compression modes and fse table to fseMetadata.
3772
 *  Requires ENTROPY_WORKSPACE_SIZE wksp.
3773
 * @return : size of fse tables or error code */
3774
static size_t
3775
ZSTD_buildBlockEntropyStats_sequences(
3776
                const SeqStore_t* seqStorePtr,
3777
                const ZSTD_fseCTables_t* prevEntropy,
3778
                      ZSTD_fseCTables_t* nextEntropy,
3779
                const ZSTD_CCtx_params* cctxParams,
3780
                      ZSTD_fseCTablesMetadata_t* fseMetadata,
3781
                      void* workspace, size_t wkspSize)
3782
0
{
3783
0
    ZSTD_strategy const strategy = cctxParams->cParams.strategy;
3784
0
    size_t const nbSeq = (size_t)(seqStorePtr->sequences - seqStorePtr->sequencesStart);
3785
0
    BYTE* const ostart = fseMetadata->fseTablesBuffer;
3786
0
    BYTE* const oend = ostart + sizeof(fseMetadata->fseTablesBuffer);
3787
0
    BYTE* op = ostart;
3788
0
    unsigned* countWorkspace = (unsigned*)workspace;
3789
0
    unsigned* entropyWorkspace = countWorkspace + (MaxSeq + 1);
3790
0
    size_t entropyWorkspaceSize = wkspSize - (MaxSeq + 1) * sizeof(*countWorkspace);
3791
0
    ZSTD_symbolEncodingTypeStats_t stats;
3792
3793
0
    DEBUGLOG(5, "ZSTD_buildBlockEntropyStats_sequences (nbSeq=%zu)", nbSeq);
3794
0
    stats = nbSeq != 0 ? ZSTD_buildSequencesStatistics(seqStorePtr, nbSeq,
3795
0
                                          prevEntropy, nextEntropy, op, oend,
3796
0
                                          strategy, countWorkspace,
3797
0
                                          entropyWorkspace, entropyWorkspaceSize)
3798
0
                       : ZSTD_buildDummySequencesStatistics(nextEntropy);
3799
0
    FORWARD_IF_ERROR(stats.size, "ZSTD_buildSequencesStatistics failed!");
3800
0
    fseMetadata->llType = (SymbolEncodingType_e) stats.LLtype;
3801
0
    fseMetadata->ofType = (SymbolEncodingType_e) stats.Offtype;
3802
0
    fseMetadata->mlType = (SymbolEncodingType_e) stats.MLtype;
3803
0
    fseMetadata->lastCountSize = stats.lastCountSize;
3804
0
    return stats.size;
3805
0
}
3806
3807
3808
/** ZSTD_buildBlockEntropyStats() :
3809
 *  Builds entropy for the block.
3810
 *  Requires workspace size ENTROPY_WORKSPACE_SIZE
3811
 * @return : 0 on success, or an error code
3812
 *  Note : also employed in superblock
3813
 */
3814
size_t ZSTD_buildBlockEntropyStats(
3815
            const SeqStore_t* seqStorePtr,
3816
            const ZSTD_entropyCTables_t* prevEntropy,
3817
                  ZSTD_entropyCTables_t* nextEntropy,
3818
            const ZSTD_CCtx_params* cctxParams,
3819
                  ZSTD_entropyCTablesMetadata_t* entropyMetadata,
3820
                  void* workspace, size_t wkspSize)
3821
0
{
3822
0
    size_t const litSize = (size_t)(seqStorePtr->lit - seqStorePtr->litStart);
3823
0
    int const huf_useOptDepth = (cctxParams->cParams.strategy >= HUF_OPTIMAL_DEPTH_THRESHOLD);
3824
0
    int const hufFlags = huf_useOptDepth ? HUF_flags_optimalDepth : 0;
3825
3826
0
    entropyMetadata->hufMetadata.hufDesSize =
3827
0
        ZSTD_buildBlockEntropyStats_literals(seqStorePtr->litStart, litSize,
3828
0
                                            &prevEntropy->huf, &nextEntropy->huf,
3829
0
                                            &entropyMetadata->hufMetadata,
3830
0
                                            ZSTD_literalsCompressionIsDisabled(cctxParams),
3831
0
                                            workspace, wkspSize, hufFlags);
3832
3833
0
    FORWARD_IF_ERROR(entropyMetadata->hufMetadata.hufDesSize, "ZSTD_buildBlockEntropyStats_literals failed");
3834
0
    entropyMetadata->fseMetadata.fseTablesSize =
3835
0
        ZSTD_buildBlockEntropyStats_sequences(seqStorePtr,
3836
0
                                              &prevEntropy->fse, &nextEntropy->fse,
3837
0
                                              cctxParams,
3838
0
                                              &entropyMetadata->fseMetadata,
3839
0
                                              workspace, wkspSize);
3840
0
    FORWARD_IF_ERROR(entropyMetadata->fseMetadata.fseTablesSize, "ZSTD_buildBlockEntropyStats_sequences failed");
3841
0
    return 0;
3842
0
}
3843
3844
/* Returns the size estimate for the literals section (header + content) of a block */
3845
static size_t
3846
ZSTD_estimateBlockSize_literal(const BYTE* literals, size_t litSize,
3847
                               const ZSTD_hufCTables_t* huf,
3848
                               const ZSTD_hufCTablesMetadata_t* hufMetadata,
3849
                               void* workspace, size_t wkspSize,
3850
                               int writeEntropy)
3851
0
{
3852
0
    unsigned* const countWksp = (unsigned*)workspace;
3853
0
    unsigned maxSymbolValue = HUF_SYMBOLVALUE_MAX;
3854
0
    size_t literalSectionHeaderSize = 3 + (litSize >= 1 KB) + (litSize >= 16 KB);
3855
0
    U32 singleStream = litSize < 256;
3856
3857
0
    if (hufMetadata->hType == set_basic) return litSize;
3858
0
    else if (hufMetadata->hType == set_rle) return 1;
3859
0
    else if (hufMetadata->hType == set_compressed || hufMetadata->hType == set_repeat) {
3860
0
        size_t const largest = HIST_count_wksp (countWksp, &maxSymbolValue, (const BYTE*)literals, litSize, workspace, wkspSize);
3861
0
        if (ZSTD_isError(largest)) return litSize;
3862
0
        {   size_t cLitSizeEstimate = HUF_estimateCompressedSize((const HUF_CElt*)huf->CTable, countWksp, maxSymbolValue);
3863
0
            if (writeEntropy) cLitSizeEstimate += hufMetadata->hufDesSize;
3864
0
            if (!singleStream) cLitSizeEstimate += 6; /* multi-stream huffman uses 6-byte jump table */
3865
0
            return cLitSizeEstimate + literalSectionHeaderSize;
3866
0
    }   }
3867
0
    assert(0); /* impossible */
3868
0
    return 0;
3869
0
}
3870
3871
/* Returns the size estimate for the FSE-compressed symbols (of, ml, ll) of a block */
3872
static size_t
3873
ZSTD_estimateBlockSize_symbolType(SymbolEncodingType_e type,
3874
                    const BYTE* codeTable, size_t nbSeq, unsigned maxCode,
3875
                    const FSE_CTable* fseCTable,
3876
                    const U8* additionalBits,
3877
                    short const* defaultNorm, U32 defaultNormLog, U32 defaultMax,
3878
                    void* workspace, size_t wkspSize)
3879
0
{
3880
0
    unsigned* const countWksp = (unsigned*)workspace;
3881
0
    const BYTE* ctp = codeTable;
3882
0
    const BYTE* const ctStart = ctp;
3883
0
    const BYTE* const ctEnd = ctStart + nbSeq;
3884
0
    size_t cSymbolTypeSizeEstimateInBits = 0;
3885
0
    unsigned max = maxCode;
3886
3887
0
    HIST_countFast_wksp(countWksp, &max, codeTable, nbSeq, workspace, wkspSize);  /* can't fail */
3888
0
    if (type == set_basic) {
3889
        /* We selected this encoding type, so it must be valid. */
3890
0
        assert(max <= defaultMax);
3891
0
        (void)defaultMax;
3892
0
        cSymbolTypeSizeEstimateInBits = ZSTD_crossEntropyCost(defaultNorm, defaultNormLog, countWksp, max);
3893
0
    } else if (type == set_rle) {
3894
0
        cSymbolTypeSizeEstimateInBits = 0;
3895
0
    } else if (type == set_compressed || type == set_repeat) {
3896
0
        cSymbolTypeSizeEstimateInBits = ZSTD_fseBitCost(fseCTable, countWksp, max);
3897
0
    }
3898
0
    if (ZSTD_isError(cSymbolTypeSizeEstimateInBits)) {
3899
0
        return nbSeq * 10;
3900
0
    }
3901
0
    while (ctp < ctEnd) {
3902
0
        if (additionalBits) cSymbolTypeSizeEstimateInBits += additionalBits[*ctp];
3903
0
        else cSymbolTypeSizeEstimateInBits += *ctp; /* for offset, offset code is also the number of additional bits */
3904
0
        ctp++;
3905
0
    }
3906
0
    return cSymbolTypeSizeEstimateInBits >> 3;
3907
0
}
3908
3909
/* Returns the size estimate for the sequences section (header + content) of a block */
3910
static size_t
3911
ZSTD_estimateBlockSize_sequences(const BYTE* ofCodeTable,
3912
                                 const BYTE* llCodeTable,
3913
                                 const BYTE* mlCodeTable,
3914
                                 size_t nbSeq,
3915
                                 const ZSTD_fseCTables_t* fseTables,
3916
                                 const ZSTD_fseCTablesMetadata_t* fseMetadata,
3917
                                 void* workspace, size_t wkspSize,
3918
                                 int writeEntropy)
3919
0
{
3920
0
    size_t sequencesSectionHeaderSize = 1 /* seqHead */ + 1 /* min seqSize size */ + (nbSeq >= 128) + (nbSeq >= LONGNBSEQ);
3921
0
    size_t cSeqSizeEstimate = 0;
3922
0
    cSeqSizeEstimate += ZSTD_estimateBlockSize_symbolType(fseMetadata->ofType, ofCodeTable, nbSeq, MaxOff,
3923
0
                                    fseTables->offcodeCTable, NULL,
3924
0
                                    OF_defaultNorm, OF_defaultNormLog, DefaultMaxOff,
3925
0
                                    workspace, wkspSize);
3926
0
    cSeqSizeEstimate += ZSTD_estimateBlockSize_symbolType(fseMetadata->llType, llCodeTable, nbSeq, MaxLL,
3927
0
                                    fseTables->litlengthCTable, LL_bits,
3928
0
                                    LL_defaultNorm, LL_defaultNormLog, MaxLL,
3929
0
                                    workspace, wkspSize);
3930
0
    cSeqSizeEstimate += ZSTD_estimateBlockSize_symbolType(fseMetadata->mlType, mlCodeTable, nbSeq, MaxML,
3931
0
                                    fseTables->matchlengthCTable, ML_bits,
3932
0
                                    ML_defaultNorm, ML_defaultNormLog, MaxML,
3933
0
                                    workspace, wkspSize);
3934
0
    if (writeEntropy) cSeqSizeEstimate += fseMetadata->fseTablesSize;
3935
0
    return cSeqSizeEstimate + sequencesSectionHeaderSize;
3936
0
}
3937
3938
/* Returns the size estimate for a given stream of literals, of, ll, ml */
3939
static size_t
3940
ZSTD_estimateBlockSize(const BYTE* literals, size_t litSize,
3941
                       const BYTE* ofCodeTable,
3942
                       const BYTE* llCodeTable,
3943
                       const BYTE* mlCodeTable,
3944
                       size_t nbSeq,
3945
                       const ZSTD_entropyCTables_t* entropy,
3946
                       const ZSTD_entropyCTablesMetadata_t* entropyMetadata,
3947
                       void* workspace, size_t wkspSize,
3948
                       int writeLitEntropy, int writeSeqEntropy)
3949
0
{
3950
0
    size_t const literalsSize = ZSTD_estimateBlockSize_literal(literals, litSize,
3951
0
                                    &entropy->huf, &entropyMetadata->hufMetadata,
3952
0
                                    workspace, wkspSize, writeLitEntropy);
3953
0
    size_t const seqSize = ZSTD_estimateBlockSize_sequences(ofCodeTable, llCodeTable, mlCodeTable,
3954
0
                                    nbSeq, &entropy->fse, &entropyMetadata->fseMetadata,
3955
0
                                    workspace, wkspSize, writeSeqEntropy);
3956
0
    return seqSize + literalsSize + ZSTD_blockHeaderSize;
3957
0
}
3958
3959
/* Builds entropy statistics and uses them for blocksize estimation.
3960
 *
3961
 * @return: estimated compressed size of the seqStore, or a zstd error.
3962
 */
3963
static size_t
3964
ZSTD_buildEntropyStatisticsAndEstimateSubBlockSize(SeqStore_t* seqStore, ZSTD_CCtx* zc)
3965
0
{
3966
0
    ZSTD_entropyCTablesMetadata_t* const entropyMetadata = &zc->blockSplitCtx.entropyMetadata;
3967
0
    DEBUGLOG(6, "ZSTD_buildEntropyStatisticsAndEstimateSubBlockSize()");
3968
0
    FORWARD_IF_ERROR(ZSTD_buildBlockEntropyStats(seqStore,
3969
0
                    &zc->blockState.prevCBlock->entropy,
3970
0
                    &zc->blockState.nextCBlock->entropy,
3971
0
                    &zc->appliedParams,
3972
0
                    entropyMetadata,
3973
0
                    zc->tmpWorkspace, zc->tmpWkspSize), "");
3974
0
    return ZSTD_estimateBlockSize(
3975
0
                    seqStore->litStart, (size_t)(seqStore->lit - seqStore->litStart),
3976
0
                    seqStore->ofCode, seqStore->llCode, seqStore->mlCode,
3977
0
                    (size_t)(seqStore->sequences - seqStore->sequencesStart),
3978
0
                    &zc->blockState.nextCBlock->entropy,
3979
0
                    entropyMetadata,
3980
0
                    zc->tmpWorkspace, zc->tmpWkspSize,
3981
0
                    (int)(entropyMetadata->hufMetadata.hType == set_compressed), 1);
3982
0
}
3983
3984
/* Returns literals bytes represented in a seqStore */
3985
static size_t ZSTD_countSeqStoreLiteralsBytes(const SeqStore_t* const seqStore)
3986
0
{
3987
0
    size_t literalsBytes = 0;
3988
0
    size_t const nbSeqs = (size_t)(seqStore->sequences - seqStore->sequencesStart);
3989
0
    size_t i;
3990
0
    for (i = 0; i < nbSeqs; ++i) {
3991
0
        SeqDef const seq = seqStore->sequencesStart[i];
3992
0
        literalsBytes += seq.litLength;
3993
0
        if (i == seqStore->longLengthPos && seqStore->longLengthType == ZSTD_llt_literalLength) {
3994
0
            literalsBytes += 0x10000;
3995
0
    }   }
3996
0
    return literalsBytes;
3997
0
}
3998
3999
/* Returns match bytes represented in a seqStore */
4000
static size_t ZSTD_countSeqStoreMatchBytes(const SeqStore_t* const seqStore)
4001
0
{
4002
0
    size_t matchBytes = 0;
4003
0
    size_t const nbSeqs = (size_t)(seqStore->sequences - seqStore->sequencesStart);
4004
0
    size_t i;
4005
0
    for (i = 0; i < nbSeqs; ++i) {
4006
0
        SeqDef seq = seqStore->sequencesStart[i];
4007
0
        matchBytes += seq.mlBase + MINMATCH;
4008
0
        if (i == seqStore->longLengthPos && seqStore->longLengthType == ZSTD_llt_matchLength) {
4009
0
            matchBytes += 0x10000;
4010
0
    }   }
4011
0
    return matchBytes;
4012
0
}
4013
4014
/* Derives the seqStore that is a chunk of the originalSeqStore from [startIdx, endIdx).
4015
 * Stores the result in resultSeqStore.
4016
 */
4017
static void ZSTD_deriveSeqStoreChunk(SeqStore_t* resultSeqStore,
4018
                               const SeqStore_t* originalSeqStore,
4019
                                     size_t startIdx, size_t endIdx)
4020
0
{
4021
0
    *resultSeqStore = *originalSeqStore;
4022
0
    if (startIdx > 0) {
4023
0
        resultSeqStore->sequences = originalSeqStore->sequencesStart + startIdx;
4024
0
        resultSeqStore->litStart += ZSTD_countSeqStoreLiteralsBytes(resultSeqStore);
4025
0
    }
4026
4027
    /* Move longLengthPos into the correct position if necessary */
4028
0
    if (originalSeqStore->longLengthType != ZSTD_llt_none) {
4029
0
        if (originalSeqStore->longLengthPos < startIdx || originalSeqStore->longLengthPos > endIdx) {
4030
0
            resultSeqStore->longLengthType = ZSTD_llt_none;
4031
0
        } else {
4032
0
            resultSeqStore->longLengthPos -= (U32)startIdx;
4033
0
        }
4034
0
    }
4035
0
    resultSeqStore->sequencesStart = originalSeqStore->sequencesStart + startIdx;
4036
0
    resultSeqStore->sequences = originalSeqStore->sequencesStart + endIdx;
4037
0
    if (endIdx == (size_t)(originalSeqStore->sequences - originalSeqStore->sequencesStart)) {
4038
        /* This accounts for possible last literals if the derived chunk reaches the end of the block */
4039
0
        assert(resultSeqStore->lit == originalSeqStore->lit);
4040
0
    } else {
4041
0
        size_t const literalsBytes = ZSTD_countSeqStoreLiteralsBytes(resultSeqStore);
4042
0
        resultSeqStore->lit = resultSeqStore->litStart + literalsBytes;
4043
0
    }
4044
0
    resultSeqStore->llCode += startIdx;
4045
0
    resultSeqStore->mlCode += startIdx;
4046
0
    resultSeqStore->ofCode += startIdx;
4047
0
}
4048
4049
/**
4050
 * Returns the raw offset represented by the combination of offBase, ll0, and repcode history.
4051
 * offBase must represent a repcode in the numeric representation of ZSTD_storeSeq().
4052
 */
4053
static U32
4054
ZSTD_resolveRepcodeToRawOffset(const U32 rep[ZSTD_REP_NUM], const U32 offBase, const U32 ll0)
4055
0
{
4056
0
    U32 const adjustedRepCode = OFFBASE_TO_REPCODE(offBase) - 1 + ll0;  /* [ 0 - 3 ] */
4057
0
    assert(OFFBASE_IS_REPCODE(offBase));
4058
0
    if (adjustedRepCode == ZSTD_REP_NUM) {
4059
0
        assert(ll0);
4060
        /* litlength == 0 and offCode == 2 implies selection of first repcode - 1
4061
         * This is only valid if it results in a valid offset value, aka > 0.
4062
         * Note : it may happen that `rep[0]==1` in exceptional circumstances.
4063
         * In which case this function will return 0, which is an invalid offset.
4064
         * It's not an issue though, since this value will be
4065
         * compared and discarded within ZSTD_seqStore_resolveOffCodes().
4066
         */
4067
0
        return rep[0] - 1;
4068
0
    }
4069
0
    return rep[adjustedRepCode];
4070
0
}
4071
4072
/**
4073
 * ZSTD_seqStore_resolveOffCodes() reconciles any possible divergences in offset history that may arise
4074
 * due to emission of RLE/raw blocks that disturb the offset history,
4075
 * and replaces any repcodes within the seqStore that may be invalid.
4076
 *
4077
 * dRepcodes are updated as would be on the decompression side.
4078
 * cRepcodes are updated exactly in accordance with the seqStore.
4079
 *
4080
 * Note : this function assumes seq->offBase respects the following numbering scheme :
4081
 *        0 : invalid
4082
 *        1-3 : repcode 1-3
4083
 *        4+ : real_offset+3
4084
 */
4085
static void
4086
ZSTD_seqStore_resolveOffCodes(Repcodes_t* const dRepcodes, Repcodes_t* const cRepcodes,
4087
                        const SeqStore_t* const seqStore, U32 const nbSeq)
4088
0
{
4089
0
    U32 idx = 0;
4090
0
    U32 const longLitLenIdx = seqStore->longLengthType == ZSTD_llt_literalLength ? seqStore->longLengthPos : nbSeq;
4091
0
    for (; idx < nbSeq; ++idx) {
4092
0
        SeqDef* const seq = seqStore->sequencesStart + idx;
4093
0
        U32 const ll0 = (seq->litLength == 0) && (idx != longLitLenIdx);
4094
0
        U32 const offBase = seq->offBase;
4095
0
        assert(offBase > 0);
4096
0
        if (OFFBASE_IS_REPCODE(offBase)) {
4097
0
            U32 const dRawOffset = ZSTD_resolveRepcodeToRawOffset(dRepcodes->rep, offBase, ll0);
4098
0
            U32 const cRawOffset = ZSTD_resolveRepcodeToRawOffset(cRepcodes->rep, offBase, ll0);
4099
            /* Adjust simulated decompression repcode history if we come across a mismatch. Replace
4100
             * the repcode with the offset it actually references, determined by the compression
4101
             * repcode history.
4102
             */
4103
0
            if (dRawOffset != cRawOffset) {
4104
0
                seq->offBase = OFFSET_TO_OFFBASE(cRawOffset);
4105
0
            }
4106
0
        }
4107
        /* Compression repcode history is always updated with values directly from the unmodified seqStore.
4108
         * Decompression repcode history may use modified seq->offset value taken from compression repcode history.
4109
         */
4110
0
        ZSTD_updateRep(dRepcodes->rep, seq->offBase, ll0);
4111
0
        ZSTD_updateRep(cRepcodes->rep, offBase, ll0);
4112
0
    }
4113
0
}
4114
4115
/* ZSTD_compressSeqStore_singleBlock():
4116
 * Compresses a seqStore into a block with a block header, into the buffer dst.
4117
 *
4118
 * Returns the total size of that block (including header) or a ZSTD error code.
4119
 */
4120
static size_t
4121
ZSTD_compressSeqStore_singleBlock(ZSTD_CCtx* zc,
4122
                            const SeqStore_t* const seqStore,
4123
                                  Repcodes_t* const dRep, Repcodes_t* const cRep,
4124
                                  void* dst, size_t dstCapacity,
4125
                            const void* src, size_t srcSize,
4126
                                  U32 lastBlock, U32 isPartition)
4127
0
{
4128
0
    const U32 rleMaxLength = 25;
4129
0
    BYTE* op = (BYTE*)dst;
4130
0
    const BYTE* ip = (const BYTE*)src;
4131
0
    size_t cSize;
4132
0
    size_t cSeqsSize;
4133
4134
    /* In case of an RLE or raw block, the simulated decompression repcode history must be reset */
4135
0
    Repcodes_t const dRepOriginal = *dRep;
4136
0
    DEBUGLOG(5, "ZSTD_compressSeqStore_singleBlock");
4137
0
    if (isPartition)
4138
0
        ZSTD_seqStore_resolveOffCodes(dRep, cRep, seqStore, (U32)(seqStore->sequences - seqStore->sequencesStart));
4139
4140
0
    RETURN_ERROR_IF(dstCapacity < ZSTD_blockHeaderSize, dstSize_tooSmall, "Block header doesn't fit");
4141
0
    cSeqsSize = ZSTD_entropyCompressSeqStore(seqStore,
4142
0
                &zc->blockState.prevCBlock->entropy, &zc->blockState.nextCBlock->entropy,
4143
0
                &zc->appliedParams,
4144
0
                op + ZSTD_blockHeaderSize, dstCapacity - ZSTD_blockHeaderSize,
4145
0
                srcSize,
4146
0
                zc->tmpWorkspace, zc->tmpWkspSize /* statically allocated in resetCCtx */,
4147
0
                zc->bmi2);
4148
0
    FORWARD_IF_ERROR(cSeqsSize, "ZSTD_entropyCompressSeqStore failed!");
4149
4150
0
    if (!zc->isFirstBlock &&
4151
0
        cSeqsSize < rleMaxLength &&
4152
0
        ZSTD_isRLE((BYTE const*)src, srcSize)) {
4153
        /* We don't want to emit our first block as a RLE even if it qualifies because
4154
        * doing so will cause the decoder (cli only) to throw a "should consume all input error."
4155
        * This is only an issue for zstd <= v1.4.3
4156
        */
4157
0
        cSeqsSize = 1;
4158
0
    }
4159
4160
    /* Sequence collection not supported when block splitting */
4161
0
    if (zc->seqCollector.collectSequences) {
4162
0
        FORWARD_IF_ERROR(ZSTD_copyBlockSequences(&zc->seqCollector, seqStore, dRepOriginal.rep), "copyBlockSequences failed");
4163
0
        ZSTD_blockState_confirmRepcodesAndEntropyTables(&zc->blockState);
4164
0
        return 0;
4165
0
    }
4166
4167
0
    if (cSeqsSize == 0) {
4168
0
        cSize = ZSTD_noCompressBlock(op, dstCapacity, ip, srcSize, lastBlock);
4169
0
        FORWARD_IF_ERROR(cSize, "Nocompress block failed");
4170
0
        DEBUGLOG(5, "Writing out nocompress block, size: %zu", cSize);
4171
0
        *dRep = dRepOriginal; /* reset simulated decompression repcode history */
4172
0
    } else if (cSeqsSize == 1) {
4173
0
        cSize = ZSTD_rleCompressBlock(op, dstCapacity, *ip, srcSize, lastBlock);
4174
0
        FORWARD_IF_ERROR(cSize, "RLE compress block failed");
4175
0
        DEBUGLOG(5, "Writing out RLE block, size: %zu", cSize);
4176
0
        *dRep = dRepOriginal; /* reset simulated decompression repcode history */
4177
0
    } else {
4178
0
        ZSTD_blockState_confirmRepcodesAndEntropyTables(&zc->blockState);
4179
0
        writeBlockHeader(op, cSeqsSize, srcSize, lastBlock);
4180
0
        cSize = ZSTD_blockHeaderSize + cSeqsSize;
4181
0
        DEBUGLOG(5, "Writing out compressed block, size: %zu", cSize);
4182
0
    }
4183
4184
0
    if (zc->blockState.prevCBlock->entropy.fse.offcode_repeatMode == FSE_repeat_valid)
4185
0
        zc->blockState.prevCBlock->entropy.fse.offcode_repeatMode = FSE_repeat_check;
4186
4187
0
    return cSize;
4188
0
}
4189
4190
/* Struct to keep track of where we are in our recursive calls. */
4191
typedef struct {
4192
    U32* splitLocations;    /* Array of split indices */
4193
    size_t idx;             /* The current index within splitLocations being worked on */
4194
} seqStoreSplits;
4195
4196
0
#define MIN_SEQUENCES_BLOCK_SPLITTING 300
4197
4198
/* Helper function to perform the recursive search for block splits.
4199
 * Estimates the cost of seqStore prior to split, and estimates the cost of splitting the sequences in half.
4200
 * If advantageous to split, then we recurse down the two sub-blocks.
4201
 * If not, or if an error occurred in estimation, then we do not recurse.
4202
 *
4203
 * Note: The recursion depth is capped by a heuristic minimum number of sequences,
4204
 * defined by MIN_SEQUENCES_BLOCK_SPLITTING.
4205
 * In theory, this means the absolute largest recursion depth is 10 == log2(maxNbSeqInBlock/MIN_SEQUENCES_BLOCK_SPLITTING).
4206
 * In practice, recursion depth usually doesn't go beyond 4.
4207
 *
4208
 * Furthermore, the number of splits is capped by ZSTD_MAX_NB_BLOCK_SPLITS.
4209
 * At ZSTD_MAX_NB_BLOCK_SPLITS == 196 with the current existing blockSize
4210
 * maximum of 128 KB, this value is actually impossible to reach.
4211
 */
4212
static void
4213
ZSTD_deriveBlockSplitsHelper(seqStoreSplits* splits, size_t startIdx, size_t endIdx,
4214
                             ZSTD_CCtx* zc, const SeqStore_t* origSeqStore)
4215
0
{
4216
0
    SeqStore_t* const fullSeqStoreChunk = &zc->blockSplitCtx.fullSeqStoreChunk;
4217
0
    SeqStore_t* const firstHalfSeqStore = &zc->blockSplitCtx.firstHalfSeqStore;
4218
0
    SeqStore_t* const secondHalfSeqStore = &zc->blockSplitCtx.secondHalfSeqStore;
4219
0
    size_t estimatedOriginalSize;
4220
0
    size_t estimatedFirstHalfSize;
4221
0
    size_t estimatedSecondHalfSize;
4222
0
    size_t midIdx = (startIdx + endIdx)/2;
4223
4224
0
    DEBUGLOG(5, "ZSTD_deriveBlockSplitsHelper: startIdx=%zu endIdx=%zu", startIdx, endIdx);
4225
0
    assert(endIdx >= startIdx);
4226
0
    if (endIdx - startIdx < MIN_SEQUENCES_BLOCK_SPLITTING || splits->idx >= ZSTD_MAX_NB_BLOCK_SPLITS) {
4227
0
        DEBUGLOG(6, "ZSTD_deriveBlockSplitsHelper: Too few sequences (%zu)", endIdx - startIdx);
4228
0
        return;
4229
0
    }
4230
0
    ZSTD_deriveSeqStoreChunk(fullSeqStoreChunk, origSeqStore, startIdx, endIdx);
4231
0
    ZSTD_deriveSeqStoreChunk(firstHalfSeqStore, origSeqStore, startIdx, midIdx);
4232
0
    ZSTD_deriveSeqStoreChunk(secondHalfSeqStore, origSeqStore, midIdx, endIdx);
4233
0
    estimatedOriginalSize = ZSTD_buildEntropyStatisticsAndEstimateSubBlockSize(fullSeqStoreChunk, zc);
4234
0
    estimatedFirstHalfSize = ZSTD_buildEntropyStatisticsAndEstimateSubBlockSize(firstHalfSeqStore, zc);
4235
0
    estimatedSecondHalfSize = ZSTD_buildEntropyStatisticsAndEstimateSubBlockSize(secondHalfSeqStore, zc);
4236
0
    DEBUGLOG(5, "Estimated original block size: %zu -- First half split: %zu -- Second half split: %zu",
4237
0
             estimatedOriginalSize, estimatedFirstHalfSize, estimatedSecondHalfSize);
4238
0
    if (ZSTD_isError(estimatedOriginalSize) || ZSTD_isError(estimatedFirstHalfSize) || ZSTD_isError(estimatedSecondHalfSize)) {
4239
0
        return;
4240
0
    }
4241
0
    if (estimatedFirstHalfSize + estimatedSecondHalfSize < estimatedOriginalSize) {
4242
0
        DEBUGLOG(5, "split decided at seqNb:%zu", midIdx);
4243
0
        ZSTD_deriveBlockSplitsHelper(splits, startIdx, midIdx, zc, origSeqStore);
4244
0
        splits->splitLocations[splits->idx] = (U32)midIdx;
4245
0
        splits->idx++;
4246
0
        ZSTD_deriveBlockSplitsHelper(splits, midIdx, endIdx, zc, origSeqStore);
4247
0
    }
4248
0
}
4249
4250
/* Base recursive function.
4251
 * Populates a table with intra-block partition indices that can improve compression ratio.
4252
 *
4253
 * @return: number of splits made (which equals the size of the partition table - 1).
4254
 */
4255
static size_t ZSTD_deriveBlockSplits(ZSTD_CCtx* zc, U32 partitions[], U32 nbSeq)
4256
0
{
4257
0
    seqStoreSplits splits;
4258
0
    splits.splitLocations = partitions;
4259
0
    splits.idx = 0;
4260
0
    if (nbSeq <= 4) {
4261
0
        DEBUGLOG(5, "ZSTD_deriveBlockSplits: Too few sequences to split (%u <= 4)", nbSeq);
4262
        /* Refuse to try and split anything with less than 4 sequences */
4263
0
        return 0;
4264
0
    }
4265
0
    ZSTD_deriveBlockSplitsHelper(&splits, 0, nbSeq, zc, &zc->seqStore);
4266
0
    splits.splitLocations[splits.idx] = nbSeq;
4267
0
    DEBUGLOG(5, "ZSTD_deriveBlockSplits: final nb partitions: %zu", splits.idx+1);
4268
0
    return splits.idx;
4269
0
}
4270
4271
/* ZSTD_compressBlock_splitBlock():
4272
 * Attempts to split a given block into multiple blocks to improve compression ratio.
4273
 *
4274
 * Returns combined size of all blocks (which includes headers), or a ZSTD error code.
4275
 */
4276
static size_t
4277
ZSTD_compressBlock_splitBlock_internal(ZSTD_CCtx* zc,
4278
                                    void* dst, size_t dstCapacity,
4279
                              const void* src, size_t blockSize,
4280
                                    U32 lastBlock, U32 nbSeq)
4281
0
{
4282
0
    size_t cSize = 0;
4283
0
    const BYTE* ip = (const BYTE*)src;
4284
0
    BYTE* op = (BYTE*)dst;
4285
0
    size_t i = 0;
4286
0
    size_t srcBytesTotal = 0;
4287
0
    U32* const partitions = zc->blockSplitCtx.partitions; /* size == ZSTD_MAX_NB_BLOCK_SPLITS */
4288
0
    SeqStore_t* const nextSeqStore = &zc->blockSplitCtx.nextSeqStore;
4289
0
    SeqStore_t* const currSeqStore = &zc->blockSplitCtx.currSeqStore;
4290
0
    size_t const numSplits = ZSTD_deriveBlockSplits(zc, partitions, nbSeq);
4291
4292
    /* If a block is split and some partitions are emitted as RLE/uncompressed, then repcode history
4293
     * may become invalid. In order to reconcile potentially invalid repcodes, we keep track of two
4294
     * separate repcode histories that simulate repcode history on compression and decompression side,
4295
     * and use the histories to determine whether we must replace a particular repcode with its raw offset.
4296
     *
4297
     * 1) cRep gets updated for each partition, regardless of whether the block was emitted as uncompressed
4298
     *    or RLE. This allows us to retrieve the offset value that an invalid repcode references within
4299
     *    a nocompress/RLE block.
4300
     * 2) dRep gets updated only for compressed partitions, and when a repcode gets replaced, will use
4301
     *    the replacement offset value rather than the original repcode to update the repcode history.
4302
     *    dRep also will be the final repcode history sent to the next block.
4303
     *
4304
     * See ZSTD_seqStore_resolveOffCodes() for more details.
4305
     */
4306
0
    Repcodes_t dRep;
4307
0
    Repcodes_t cRep;
4308
0
    ZSTD_memcpy(dRep.rep, zc->blockState.prevCBlock->rep, sizeof(Repcodes_t));
4309
0
    ZSTD_memcpy(cRep.rep, zc->blockState.prevCBlock->rep, sizeof(Repcodes_t));
4310
0
    ZSTD_memset(nextSeqStore, 0, sizeof(SeqStore_t));
4311
4312
0
    DEBUGLOG(5, "ZSTD_compressBlock_splitBlock_internal (dstCapacity=%u, dictLimit=%u, nextToUpdate=%u)",
4313
0
                (unsigned)dstCapacity, (unsigned)zc->blockState.matchState.window.dictLimit,
4314
0
                (unsigned)zc->blockState.matchState.nextToUpdate);
4315
4316
0
    if (numSplits == 0) {
4317
0
        size_t cSizeSingleBlock =
4318
0
            ZSTD_compressSeqStore_singleBlock(zc, &zc->seqStore,
4319
0
                                            &dRep, &cRep,
4320
0
                                            op, dstCapacity,
4321
0
                                            ip, blockSize,
4322
0
                                            lastBlock, 0 /* isPartition */);
4323
0
        FORWARD_IF_ERROR(cSizeSingleBlock, "Compressing single block from splitBlock_internal() failed!");
4324
0
        DEBUGLOG(5, "ZSTD_compressBlock_splitBlock_internal: No splits");
4325
0
        assert(zc->blockSizeMax <= ZSTD_BLOCKSIZE_MAX);
4326
0
        assert(cSizeSingleBlock <= zc->blockSizeMax + ZSTD_blockHeaderSize);
4327
0
        return cSizeSingleBlock;
4328
0
    }
4329
4330
0
    ZSTD_deriveSeqStoreChunk(currSeqStore, &zc->seqStore, 0, partitions[0]);
4331
0
    for (i = 0; i <= numSplits; ++i) {
4332
0
        size_t cSizeChunk;
4333
0
        U32 const lastPartition = (i == numSplits);
4334
0
        U32 lastBlockEntireSrc = 0;
4335
4336
0
        size_t srcBytes = ZSTD_countSeqStoreLiteralsBytes(currSeqStore) + ZSTD_countSeqStoreMatchBytes(currSeqStore);
4337
0
        srcBytesTotal += srcBytes;
4338
0
        if (lastPartition) {
4339
            /* This is the final partition, need to account for possible last literals */
4340
0
            srcBytes += blockSize - srcBytesTotal;
4341
0
            lastBlockEntireSrc = lastBlock;
4342
0
        } else {
4343
0
            ZSTD_deriveSeqStoreChunk(nextSeqStore, &zc->seqStore, partitions[i], partitions[i+1]);
4344
0
        }
4345
4346
0
        cSizeChunk = ZSTD_compressSeqStore_singleBlock(zc, currSeqStore,
4347
0
                                                      &dRep, &cRep,
4348
0
                                                       op, dstCapacity,
4349
0
                                                       ip, srcBytes,
4350
0
                                                       lastBlockEntireSrc, 1 /* isPartition */);
4351
0
        DEBUGLOG(5, "Estimated size: %zu vs %zu : actual size",
4352
0
                    ZSTD_buildEntropyStatisticsAndEstimateSubBlockSize(currSeqStore, zc), cSizeChunk);
4353
0
        FORWARD_IF_ERROR(cSizeChunk, "Compressing chunk failed!");
4354
4355
0
        ip += srcBytes;
4356
0
        op += cSizeChunk;
4357
0
        dstCapacity -= cSizeChunk;
4358
0
        cSize += cSizeChunk;
4359
0
        *currSeqStore = *nextSeqStore;
4360
0
        assert(cSizeChunk <= zc->blockSizeMax + ZSTD_blockHeaderSize);
4361
0
    }
4362
    /* cRep and dRep may have diverged during the compression.
4363
     * If so, we use the dRep repcodes for the next block.
4364
     */
4365
0
    ZSTD_memcpy(zc->blockState.prevCBlock->rep, dRep.rep, sizeof(Repcodes_t));
4366
0
    return cSize;
4367
0
}
4368
4369
static size_t
4370
ZSTD_compressBlock_splitBlock(ZSTD_CCtx* zc,
4371
                              void* dst, size_t dstCapacity,
4372
                              const void* src, size_t srcSize, U32 lastBlock)
4373
0
{
4374
0
    U32 nbSeq;
4375
0
    size_t cSize;
4376
0
    DEBUGLOG(5, "ZSTD_compressBlock_splitBlock");
4377
0
    assert(zc->appliedParams.postBlockSplitter == ZSTD_ps_enable);
4378
4379
0
    {   const size_t bss = ZSTD_buildSeqStore(zc, src, srcSize);
4380
0
        FORWARD_IF_ERROR(bss, "ZSTD_buildSeqStore failed");
4381
0
        if (bss == ZSTDbss_noCompress) {
4382
0
            if (zc->blockState.prevCBlock->entropy.fse.offcode_repeatMode == FSE_repeat_valid)
4383
0
                zc->blockState.prevCBlock->entropy.fse.offcode_repeatMode = FSE_repeat_check;
4384
0
            RETURN_ERROR_IF(zc->seqCollector.collectSequences, sequenceProducer_failed, "Uncompressible block");
4385
0
            cSize = ZSTD_noCompressBlock(dst, dstCapacity, src, srcSize, lastBlock);
4386
0
            FORWARD_IF_ERROR(cSize, "ZSTD_noCompressBlock failed");
4387
0
            DEBUGLOG(5, "ZSTD_compressBlock_splitBlock: Nocompress block");
4388
0
            return cSize;
4389
0
        }
4390
0
        nbSeq = (U32)(zc->seqStore.sequences - zc->seqStore.sequencesStart);
4391
0
    }
4392
4393
0
    cSize = ZSTD_compressBlock_splitBlock_internal(zc, dst, dstCapacity, src, srcSize, lastBlock, nbSeq);
4394
0
    FORWARD_IF_ERROR(cSize, "Splitting blocks failed!");
4395
0
    return cSize;
4396
0
}
4397
4398
static size_t
4399
ZSTD_compressBlock_internal(ZSTD_CCtx* zc,
4400
                            void* dst, size_t dstCapacity,
4401
                            const void* src, size_t srcSize, U32 frame)
4402
53.6k
{
4403
    /* This is an estimated upper bound for the length of an rle block.
4404
     * This isn't the actual upper bound.
4405
     * Finding the real threshold needs further investigation.
4406
     */
4407
53.6k
    const U32 rleMaxLength = 25;
4408
53.6k
    size_t cSize;
4409
53.6k
    const BYTE* ip = (const BYTE*)src;
4410
53.6k
    BYTE* op = (BYTE*)dst;
4411
53.6k
    DEBUGLOG(5, "ZSTD_compressBlock_internal (dstCapacity=%u, dictLimit=%u, nextToUpdate=%u)",
4412
53.6k
                (unsigned)dstCapacity, (unsigned)zc->blockState.matchState.window.dictLimit,
4413
53.6k
                (unsigned)zc->blockState.matchState.nextToUpdate);
4414
4415
53.6k
    {   const size_t bss = ZSTD_buildSeqStore(zc, src, srcSize);
4416
53.6k
        FORWARD_IF_ERROR(bss, "ZSTD_buildSeqStore failed");
4417
53.6k
        if (bss == ZSTDbss_noCompress) {
4418
11
            RETURN_ERROR_IF(zc->seqCollector.collectSequences, sequenceProducer_failed, "Uncompressible block");
4419
11
            cSize = 0;
4420
11
            goto out;
4421
11
        }
4422
53.6k
    }
4423
4424
53.6k
    if (zc->seqCollector.collectSequences) {
4425
0
        FORWARD_IF_ERROR(ZSTD_copyBlockSequences(&zc->seqCollector, ZSTD_getSeqStore(zc), zc->blockState.prevCBlock->rep), "copyBlockSequences failed");
4426
0
        ZSTD_blockState_confirmRepcodesAndEntropyTables(&zc->blockState);
4427
0
        return 0;
4428
0
    }
4429
4430
    /* encode sequences and literals */
4431
53.6k
    cSize = ZSTD_entropyCompressSeqStore(&zc->seqStore,
4432
53.6k
            &zc->blockState.prevCBlock->entropy, &zc->blockState.nextCBlock->entropy,
4433
53.6k
            &zc->appliedParams,
4434
53.6k
            dst, dstCapacity,
4435
53.6k
            srcSize,
4436
53.6k
            zc->tmpWorkspace, zc->tmpWkspSize /* statically allocated in resetCCtx */,
4437
53.6k
            zc->bmi2);
4438
4439
53.6k
    if (frame &&
4440
        /* We don't want to emit our first block as a RLE even if it qualifies because
4441
         * doing so will cause the decoder (cli only) to throw a "should consume all input error."
4442
         * This is only an issue for zstd <= v1.4.3
4443
         */
4444
53.6k
        !zc->isFirstBlock &&
4445
53.6k
        cSize < rleMaxLength &&
4446
53.6k
        ZSTD_isRLE(ip, srcSize))
4447
831
    {
4448
831
        cSize = 1;
4449
831
        op[0] = ip[0];
4450
831
    }
4451
4452
53.6k
out:
4453
53.6k
    if (!ZSTD_isError(cSize) && cSize > 1) {
4454
52.6k
        ZSTD_blockState_confirmRepcodesAndEntropyTables(&zc->blockState);
4455
52.6k
    }
4456
    /* We check that dictionaries have offset codes available for the first
4457
     * block. After the first block, the offcode table might not have large
4458
     * enough codes to represent the offsets in the data.
4459
     */
4460
53.6k
    if (zc->blockState.prevCBlock->entropy.fse.offcode_repeatMode == FSE_repeat_valid)
4461
0
        zc->blockState.prevCBlock->entropy.fse.offcode_repeatMode = FSE_repeat_check;
4462
4463
53.6k
    return cSize;
4464
53.6k
}
4465
4466
static size_t ZSTD_compressBlock_targetCBlockSize_body(ZSTD_CCtx* zc,
4467
                               void* dst, size_t dstCapacity,
4468
                               const void* src, size_t srcSize,
4469
                               const size_t bss, U32 lastBlock)
4470
0
{
4471
0
    DEBUGLOG(6, "Attempting ZSTD_compressSuperBlock()");
4472
0
    if (bss == ZSTDbss_compress) {
4473
0
        if (/* We don't want to emit our first block as a RLE even if it qualifies because
4474
            * doing so will cause the decoder (cli only) to throw a "should consume all input error."
4475
            * This is only an issue for zstd <= v1.4.3
4476
            */
4477
0
            !zc->isFirstBlock &&
4478
0
            ZSTD_maybeRLE(&zc->seqStore) &&
4479
0
            ZSTD_isRLE((BYTE const*)src, srcSize))
4480
0
        {
4481
0
            return ZSTD_rleCompressBlock(dst, dstCapacity, *(BYTE const*)src, srcSize, lastBlock);
4482
0
        }
4483
        /* Attempt superblock compression.
4484
         *
4485
         * Note that compressed size of ZSTD_compressSuperBlock() is not bound by the
4486
         * standard ZSTD_compressBound(). This is a problem, because even if we have
4487
         * space now, taking an extra byte now could cause us to run out of space later
4488
         * and violate ZSTD_compressBound().
4489
         *
4490
         * Define blockBound(blockSize) = blockSize + ZSTD_blockHeaderSize.
4491
         *
4492
         * In order to respect ZSTD_compressBound() we must attempt to emit a raw
4493
         * uncompressed block in these cases:
4494
         *   * cSize == 0: Return code for an uncompressed block.
4495
         *   * cSize == dstSize_tooSmall: We may have expanded beyond blockBound(srcSize).
4496
         *     ZSTD_noCompressBlock() will return dstSize_tooSmall if we are really out of
4497
         *     output space.
4498
         *   * cSize >= blockBound(srcSize): We have expanded the block too much so
4499
         *     emit an uncompressed block.
4500
         */
4501
0
        {   size_t const cSize =
4502
0
                ZSTD_compressSuperBlock(zc, dst, dstCapacity, src, srcSize, lastBlock);
4503
0
            if (cSize != ERROR(dstSize_tooSmall)) {
4504
0
                size_t const maxCSize =
4505
0
                    srcSize - ZSTD_minGain(srcSize, zc->appliedParams.cParams.strategy);
4506
0
                FORWARD_IF_ERROR(cSize, "ZSTD_compressSuperBlock failed");
4507
0
                if (cSize != 0 && cSize < maxCSize + ZSTD_blockHeaderSize) {
4508
0
                    ZSTD_blockState_confirmRepcodesAndEntropyTables(&zc->blockState);
4509
0
                    return cSize;
4510
0
                }
4511
0
            }
4512
0
        }
4513
0
    } /* if (bss == ZSTDbss_compress)*/
4514
4515
0
    DEBUGLOG(6, "Resorting to ZSTD_noCompressBlock()");
4516
    /* Superblock compression failed, attempt to emit a single no compress block.
4517
     * The decoder will be able to stream this block since it is uncompressed.
4518
     */
4519
0
    return ZSTD_noCompressBlock(dst, dstCapacity, src, srcSize, lastBlock);
4520
0
}
4521
4522
static size_t ZSTD_compressBlock_targetCBlockSize(ZSTD_CCtx* zc,
4523
                               void* dst, size_t dstCapacity,
4524
                               const void* src, size_t srcSize,
4525
                               U32 lastBlock)
4526
0
{
4527
0
    size_t cSize = 0;
4528
0
    const size_t bss = ZSTD_buildSeqStore(zc, src, srcSize);
4529
0
    DEBUGLOG(5, "ZSTD_compressBlock_targetCBlockSize (dstCapacity=%u, dictLimit=%u, nextToUpdate=%u, srcSize=%zu)",
4530
0
                (unsigned)dstCapacity, (unsigned)zc->blockState.matchState.window.dictLimit, (unsigned)zc->blockState.matchState.nextToUpdate, srcSize);
4531
0
    FORWARD_IF_ERROR(bss, "ZSTD_buildSeqStore failed");
4532
4533
0
    cSize = ZSTD_compressBlock_targetCBlockSize_body(zc, dst, dstCapacity, src, srcSize, bss, lastBlock);
4534
0
    FORWARD_IF_ERROR(cSize, "ZSTD_compressBlock_targetCBlockSize_body failed");
4535
4536
0
    if (zc->blockState.prevCBlock->entropy.fse.offcode_repeatMode == FSE_repeat_valid)
4537
0
        zc->blockState.prevCBlock->entropy.fse.offcode_repeatMode = FSE_repeat_check;
4538
4539
0
    return cSize;
4540
0
}
4541
4542
static void ZSTD_overflowCorrectIfNeeded(ZSTD_MatchState_t* ms,
4543
                                         ZSTD_cwksp* ws,
4544
                                         ZSTD_CCtx_params const* params,
4545
                                         void const* ip,
4546
                                         void const* iend)
4547
53.6k
{
4548
53.6k
    U32 const cycleLog = ZSTD_cycleLog(params->cParams.chainLog, params->cParams.strategy);
4549
53.6k
    U32 const maxDist = (U32)1 << params->cParams.windowLog;
4550
53.6k
    if (ZSTD_window_needOverflowCorrection(ms->window, cycleLog, maxDist, ms->loadedDictEnd, ip, iend)) {
4551
307
        U32 const correction = ZSTD_window_correctOverflow(&ms->window, cycleLog, maxDist, ip);
4552
307
        ZSTD_STATIC_ASSERT(ZSTD_CHAINLOG_MAX <= 30);
4553
307
        ZSTD_STATIC_ASSERT(ZSTD_WINDOWLOG_MAX_32 <= 30);
4554
307
        ZSTD_STATIC_ASSERT(ZSTD_WINDOWLOG_MAX <= 31);
4555
307
        ZSTD_cwksp_mark_tables_dirty(ws);
4556
307
        ZSTD_reduceIndex(ms, params, correction);
4557
307
        ZSTD_cwksp_mark_tables_clean(ws);
4558
307
        if (ms->nextToUpdate < correction) ms->nextToUpdate = 0;
4559
307
        else ms->nextToUpdate -= correction;
4560
        /* invalidate dictionaries on overflow correction */
4561
307
        ms->loadedDictEnd = 0;
4562
307
        ms->dictMatchState = NULL;
4563
307
    }
4564
53.6k
}
4565
4566
#include "zstd_preSplit.h"
4567
4568
static size_t ZSTD_optimalBlockSize(ZSTD_CCtx* cctx, const void* src, size_t srcSize, size_t blockSizeMax, int splitLevel, ZSTD_strategy strat, S64 savings)
4569
53.6k
{
4570
    /* split level based on compression strategy, from `fast` to `btultra2` */
4571
53.6k
    static const int splitLevels[] = { 0, 0, 1, 2, 2, 3, 3, 4, 4, 4 };
4572
    /* note: conservatively only split full blocks (128 KB) currently.
4573
     * While it's possible to go lower, let's keep it simple for a first implementation.
4574
     * Besides, benefits of splitting are reduced when blocks are already small.
4575
     */
4576
53.6k
    if (srcSize < 128 KB || blockSizeMax < 128 KB)
4577
21.1k
        return MIN(srcSize, blockSizeMax);
4578
    /* do not split incompressible data though:
4579
     * require verified savings to allow pre-splitting.
4580
     * Note: as a consequence, the first full block is not split.
4581
     */
4582
32.4k
    if (savings < 3) {
4583
6.98k
        DEBUGLOG(6, "don't attempt splitting: savings (%i) too low", (int)savings);
4584
6.98k
        return 128 KB;
4585
6.98k
    }
4586
    /* apply @splitLevel, or use default value (which depends on @strat).
4587
     * note that splitting heuristic is still conditioned by @savings >= 3,
4588
     * so the first block will not reach this code path */
4589
25.4k
    if (splitLevel == 1) return 128 KB;
4590
25.4k
    if (splitLevel == 0) {
4591
25.4k
        assert(ZSTD_fast <= strat && strat <= ZSTD_btultra2);
4592
25.4k
        splitLevel = splitLevels[strat];
4593
25.4k
    } else {
4594
0
        assert(2 <= splitLevel && splitLevel <= 6);
4595
0
        splitLevel -= 2;
4596
0
    }
4597
25.4k
    return ZSTD_splitBlock(src, blockSizeMax, splitLevel, cctx->tmpWorkspace, cctx->tmpWkspSize);
4598
25.4k
}
4599
4600
/*! ZSTD_compress_frameChunk() :
4601
*   Compress a chunk of data into one or multiple blocks.
4602
*   All blocks will be terminated, all input will be consumed.
4603
*   Function will issue an error if there is not enough `dstCapacity` to hold the compressed content.
4604
*   Frame is supposed already started (header already produced)
4605
*  @return : compressed size, or an error code
4606
*/
4607
static size_t ZSTD_compress_frameChunk(ZSTD_CCtx* cctx,
4608
                                     void* dst, size_t dstCapacity,
4609
                               const void* src, size_t srcSize,
4610
                                     U32 lastFrameChunk)
4611
47.8k
{
4612
47.8k
    size_t blockSizeMax = cctx->blockSizeMax;
4613
47.8k
    size_t remaining = srcSize;
4614
47.8k
    const BYTE* ip = (const BYTE*)src;
4615
47.8k
    BYTE* const ostart = (BYTE*)dst;
4616
47.8k
    BYTE* op = ostart;
4617
47.8k
    U32 const maxDist = (U32)1 << cctx->appliedParams.cParams.windowLog;
4618
47.8k
    S64 savings = (S64)cctx->consumedSrcSize - (S64)cctx->producedCSize;
4619
4620
47.8k
    assert(cctx->appliedParams.cParams.windowLog <= ZSTD_WINDOWLOG_MAX);
4621
4622
47.8k
    DEBUGLOG(5, "ZSTD_compress_frameChunk (srcSize=%u, blockSizeMax=%u)", (unsigned)srcSize, (unsigned)blockSizeMax);
4623
47.8k
    if (cctx->appliedParams.fParams.checksumFlag && srcSize)
4624
0
        XXH64_update(&cctx->xxhState, src, srcSize);
4625
4626
101k
    while (remaining) {
4627
53.6k
        ZSTD_MatchState_t* const ms = &cctx->blockState.matchState;
4628
53.6k
        size_t const blockSize = ZSTD_optimalBlockSize(cctx,
4629
53.6k
                                ip, remaining,
4630
53.6k
                                blockSizeMax,
4631
53.6k
                                cctx->appliedParams.preBlockSplitter_level,
4632
53.6k
                                cctx->appliedParams.cParams.strategy,
4633
53.6k
                                savings);
4634
53.6k
        U32 const lastBlock = lastFrameChunk & (blockSize == remaining);
4635
53.6k
        assert(blockSize <= remaining);
4636
4637
        /* TODO: See 3090. We reduced MIN_CBLOCK_SIZE from 3 to 2 so to compensate we are adding
4638
         * additional 1. We need to revisit and change this logic to be more consistent */
4639
53.6k
        RETURN_ERROR_IF(dstCapacity < ZSTD_blockHeaderSize + MIN_CBLOCK_SIZE + 1,
4640
53.6k
                        dstSize_tooSmall,
4641
53.6k
                        "not enough space to store compressed block");
4642
4643
53.6k
        ZSTD_overflowCorrectIfNeeded(
4644
53.6k
            ms, &cctx->workspace, &cctx->appliedParams, ip, ip + blockSize);
4645
53.6k
        ZSTD_checkDictValidity(&ms->window, ip + blockSize, maxDist, &ms->loadedDictEnd, &ms->dictMatchState);
4646
53.6k
        ZSTD_window_enforceMaxDist(&ms->window, ip, maxDist, &ms->loadedDictEnd, &ms->dictMatchState);
4647
4648
        /* Ensure hash/chain table insertion resumes no sooner than lowlimit */
4649
53.6k
        if (ms->nextToUpdate < ms->window.lowLimit) ms->nextToUpdate = ms->window.lowLimit;
4650
4651
53.6k
        {   size_t cSize;
4652
53.6k
            if (ZSTD_useTargetCBlockSize(&cctx->appliedParams)) {
4653
0
                cSize = ZSTD_compressBlock_targetCBlockSize(cctx, op, dstCapacity, ip, blockSize, lastBlock);
4654
0
                FORWARD_IF_ERROR(cSize, "ZSTD_compressBlock_targetCBlockSize failed");
4655
0
                assert(cSize > 0);
4656
0
                assert(cSize <= blockSize + ZSTD_blockHeaderSize);
4657
53.6k
            } else if (ZSTD_blockSplitterEnabled(&cctx->appliedParams)) {
4658
0
                cSize = ZSTD_compressBlock_splitBlock(cctx, op, dstCapacity, ip, blockSize, lastBlock);
4659
0
                FORWARD_IF_ERROR(cSize, "ZSTD_compressBlock_splitBlock failed");
4660
0
                assert(cSize > 0 || cctx->seqCollector.collectSequences == 1);
4661
53.6k
            } else {
4662
53.6k
                cSize = ZSTD_compressBlock_internal(cctx,
4663
53.6k
                                        op+ZSTD_blockHeaderSize, dstCapacity-ZSTD_blockHeaderSize,
4664
53.6k
                                        ip, blockSize, 1 /* frame */);
4665
53.6k
                FORWARD_IF_ERROR(cSize, "ZSTD_compressBlock_internal failed");
4666
4667
53.6k
                if (cSize == 0) {  /* block is not compressible */
4668
172
                    cSize = ZSTD_noCompressBlock(op, dstCapacity, ip, blockSize, lastBlock);
4669
172
                    FORWARD_IF_ERROR(cSize, "ZSTD_noCompressBlock failed");
4670
53.4k
                } else {
4671
53.4k
                    U32 const cBlockHeader = cSize == 1 ?
4672
831
                        lastBlock + (((U32)bt_rle)<<1) + (U32)(blockSize << 3) :
4673
53.4k
                        lastBlock + (((U32)bt_compressed)<<1) + (U32)(cSize << 3);
4674
53.4k
                    MEM_writeLE24(op, cBlockHeader);
4675
53.4k
                    cSize += ZSTD_blockHeaderSize;
4676
53.4k
                }
4677
53.6k
            }  /* if (ZSTD_useTargetCBlockSize(&cctx->appliedParams))*/
4678
4679
            /* @savings is employed to ensure that splitting doesn't worsen expansion of incompressible data.
4680
             * Without splitting, the maximum expansion is 3 bytes per full block.
4681
             * An adversarial input could attempt to fudge the split detector,
4682
             * and make it split incompressible data, resulting in more block headers.
4683
             * Note that, since ZSTD_COMPRESSBOUND() assumes a worst case scenario of 1KB per block,
4684
             * and the splitter never creates blocks that small (current lower limit is 8 KB),
4685
             * there is already no risk to expand beyond ZSTD_COMPRESSBOUND() limit.
4686
             * But if the goal is to not expand by more than 3-bytes per 128 KB full block,
4687
             * then yes, it becomes possible to make the block splitter oversplit incompressible data.
4688
             * Using @savings, we enforce an even more conservative condition,
4689
             * requiring the presence of enough savings (at least 3 bytes) to authorize splitting,
4690
             * otherwise only full blocks are used.
4691
             * But being conservative is fine,
4692
             * since splitting barely compressible blocks is not fruitful anyway */
4693
53.6k
            savings += (S64)blockSize - (S64)cSize;
4694
4695
53.6k
            ip += blockSize;
4696
53.6k
            assert(remaining >= blockSize);
4697
53.6k
            remaining -= blockSize;
4698
53.6k
            op += cSize;
4699
53.6k
            assert(dstCapacity >= cSize);
4700
53.6k
            dstCapacity -= cSize;
4701
53.6k
            cctx->isFirstBlock = 0;
4702
53.6k
            DEBUGLOG(5, "ZSTD_compress_frameChunk: adding a block of size %u",
4703
53.6k
                        (unsigned)cSize);
4704
53.6k
    }   }
4705
4706
47.8k
    if (lastFrameChunk && (op>ostart)) cctx->stage = ZSTDcs_ending;
4707
47.8k
    return (size_t)(op-ostart);
4708
47.8k
}
4709
4710
4711
static size_t ZSTD_writeFrameHeader(void* dst, size_t dstCapacity,
4712
                                    const ZSTD_CCtx_params* params,
4713
                                    U64 pledgedSrcSize, U32 dictID)
4714
15.4k
{
4715
15.4k
    BYTE* const op = (BYTE*)dst;
4716
15.4k
    U32   const dictIDSizeCodeLength = (dictID>0) + (dictID>=256) + (dictID>=65536);   /* 0-3 */
4717
15.4k
    U32   const dictIDSizeCode = params->fParams.noDictIDFlag ? 0 : dictIDSizeCodeLength;   /* 0-3 */
4718
15.4k
    U32   const checksumFlag = params->fParams.checksumFlag>0;
4719
15.4k
    U32   const windowSize = (U32)1 << params->cParams.windowLog;
4720
15.4k
    U32   const singleSegment = params->fParams.contentSizeFlag && (windowSize >= pledgedSrcSize);
4721
15.4k
    BYTE  const windowLogByte = (BYTE)((params->cParams.windowLog - ZSTD_WINDOWLOG_ABSOLUTEMIN) << 3);
4722
15.4k
    U32   const fcsCode = params->fParams.contentSizeFlag ?
4723
15.4k
                     (pledgedSrcSize>=256) + (pledgedSrcSize>=65536+256) + (pledgedSrcSize>=0xFFFFFFFFU) : 0;  /* 0-3 */
4724
15.4k
    BYTE  const frameHeaderDescriptionByte = (BYTE)(dictIDSizeCode + (checksumFlag<<2) + (singleSegment<<5) + (fcsCode<<6) );
4725
15.4k
    size_t pos=0;
4726
4727
15.4k
    assert(!(params->fParams.contentSizeFlag && pledgedSrcSize == ZSTD_CONTENTSIZE_UNKNOWN));
4728
15.4k
    RETURN_ERROR_IF(dstCapacity < ZSTD_FRAMEHEADERSIZE_MAX, dstSize_tooSmall,
4729
15.4k
                    "dst buf is too small to fit worst-case frame header size.");
4730
15.4k
    DEBUGLOG(4, "ZSTD_writeFrameHeader : dictIDFlag : %u ; dictID : %u ; dictIDSizeCode : %u",
4731
15.4k
                !params->fParams.noDictIDFlag, (unsigned)dictID, (unsigned)dictIDSizeCode);
4732
15.4k
    if (params->format == ZSTD_f_zstd1) {
4733
15.4k
        MEM_writeLE32(dst, ZSTD_MAGICNUMBER);
4734
15.4k
        pos = 4;
4735
15.4k
    }
4736
15.4k
    op[pos++] = frameHeaderDescriptionByte;
4737
15.4k
    if (!singleSegment) op[pos++] = windowLogByte;
4738
15.4k
    switch(dictIDSizeCode)
4739
15.4k
    {
4740
0
        default:
4741
0
            assert(0); /* impossible */
4742
0
            ZSTD_FALLTHROUGH;
4743
15.4k
        case 0 : break;
4744
0
        case 1 : op[pos] = (BYTE)(dictID); pos++; break;
4745
0
        case 2 : MEM_writeLE16(op+pos, (U16)dictID); pos+=2; break;
4746
0
        case 3 : MEM_writeLE32(op+pos, dictID); pos+=4; break;
4747
15.4k
    }
4748
15.4k
    switch(fcsCode)
4749
15.4k
    {
4750
0
        default:
4751
0
            assert(0); /* impossible */
4752
0
            ZSTD_FALLTHROUGH;
4753
15.4k
        case 0 : if (singleSegment) op[pos++] = (BYTE)(pledgedSrcSize); break;
4754
0
        case 1 : MEM_writeLE16(op+pos, (U16)(pledgedSrcSize-256)); pos+=2; break;
4755
0
        case 2 : MEM_writeLE32(op+pos, (U32)(pledgedSrcSize)); pos+=4; break;
4756
0
        case 3 : MEM_writeLE64(op+pos, (U64)(pledgedSrcSize)); pos+=8; break;
4757
15.4k
    }
4758
15.4k
    return pos;
4759
15.4k
}
4760
4761
/* ZSTD_writeSkippableFrame_advanced() :
4762
 * Writes out a skippable frame with the specified magic number variant (16 are supported),
4763
 * from ZSTD_MAGIC_SKIPPABLE_START to ZSTD_MAGIC_SKIPPABLE_START+15, and the desired source data.
4764
 *
4765
 * Returns the total number of bytes written, or a ZSTD error code.
4766
 */
4767
size_t ZSTD_writeSkippableFrame(void* dst, size_t dstCapacity,
4768
0
                                const void* src, size_t srcSize, unsigned magicVariant) {
4769
0
    BYTE* op = (BYTE*)dst;
4770
0
    RETURN_ERROR_IF(dstCapacity < srcSize + ZSTD_SKIPPABLEHEADERSIZE /* Skippable frame overhead */,
4771
0
                    dstSize_tooSmall, "Not enough room for skippable frame");
4772
0
    RETURN_ERROR_IF(srcSize > (unsigned)0xFFFFFFFF, srcSize_wrong, "Src size too large for skippable frame");
4773
0
    RETURN_ERROR_IF(magicVariant > 15, parameter_outOfBound, "Skippable frame magic number variant not supported");
4774
4775
0
    MEM_writeLE32(op, (U32)(ZSTD_MAGIC_SKIPPABLE_START + magicVariant));
4776
0
    MEM_writeLE32(op+4, (U32)srcSize);
4777
0
    ZSTD_memcpy(op+8, src, srcSize);
4778
0
    return srcSize + ZSTD_SKIPPABLEHEADERSIZE;
4779
0
}
4780
4781
/* ZSTD_writeLastEmptyBlock() :
4782
 * output an empty Block with end-of-frame mark to complete a frame
4783
 * @return : size of data written into `dst` (== ZSTD_blockHeaderSize (defined in zstd_internal.h))
4784
 *           or an error code if `dstCapacity` is too small (<ZSTD_blockHeaderSize)
4785
 */
4786
size_t ZSTD_writeLastEmptyBlock(void* dst, size_t dstCapacity)
4787
0
{
4788
0
    RETURN_ERROR_IF(dstCapacity < ZSTD_blockHeaderSize, dstSize_tooSmall,
4789
0
                    "dst buf is too small to write frame trailer empty block.");
4790
0
    {   U32 const cBlockHeader24 = 1 /*lastBlock*/ + (((U32)bt_raw)<<1);  /* 0 size */
4791
0
        MEM_writeLE24(dst, cBlockHeader24);
4792
0
        return ZSTD_blockHeaderSize;
4793
0
    }
4794
0
}
4795
4796
void ZSTD_referenceExternalSequences(ZSTD_CCtx* cctx, rawSeq* seq, size_t nbSeq)
4797
15.4k
{
4798
15.4k
    assert(cctx->stage == ZSTDcs_init);
4799
15.4k
    assert(nbSeq == 0 || cctx->appliedParams.ldmParams.enableLdm != ZSTD_ps_enable);
4800
15.4k
    cctx->externSeqStore.seq = seq;
4801
15.4k
    cctx->externSeqStore.size = nbSeq;
4802
15.4k
    cctx->externSeqStore.capacity = nbSeq;
4803
15.4k
    cctx->externSeqStore.pos = 0;
4804
15.4k
    cctx->externSeqStore.posInSequence = 0;
4805
15.4k
}
4806
4807
4808
static size_t ZSTD_compressContinue_internal (ZSTD_CCtx* cctx,
4809
                              void* dst, size_t dstCapacity,
4810
                        const void* src, size_t srcSize,
4811
                               U32 frame, U32 lastFrameChunk)
4812
47.9k
{
4813
47.9k
    ZSTD_MatchState_t* const ms = &cctx->blockState.matchState;
4814
47.9k
    size_t fhSize = 0;
4815
4816
47.9k
    DEBUGLOG(5, "ZSTD_compressContinue_internal, stage: %u, srcSize: %u",
4817
47.9k
                cctx->stage, (unsigned)srcSize);
4818
47.9k
    RETURN_ERROR_IF(cctx->stage==ZSTDcs_created, stage_wrong,
4819
47.9k
                    "missing init (ZSTD_compressBegin)");
4820
4821
47.9k
    if (frame && (cctx->stage==ZSTDcs_init)) {
4822
15.4k
        fhSize = ZSTD_writeFrameHeader(dst, dstCapacity, &cctx->appliedParams,
4823
15.4k
                                       cctx->pledgedSrcSizePlusOne-1, cctx->dictID);
4824
15.4k
        FORWARD_IF_ERROR(fhSize, "ZSTD_writeFrameHeader failed");
4825
15.4k
        assert(fhSize <= dstCapacity);
4826
15.4k
        dstCapacity -= fhSize;
4827
15.4k
        dst = (char*)dst + fhSize;
4828
15.4k
        cctx->stage = ZSTDcs_ongoing;
4829
15.4k
    }
4830
4831
47.9k
    if (!srcSize) return fhSize;  /* do not generate an empty block if no input */
4832
4833
47.8k
    if (!ZSTD_window_update(&ms->window, src, srcSize, ms->forceNonContiguous)) {
4834
15.4k
        ms->forceNonContiguous = 0;
4835
15.4k
        ms->nextToUpdate = ms->window.dictLimit;
4836
15.4k
    }
4837
47.8k
    if (cctx->appliedParams.ldmParams.enableLdm == ZSTD_ps_enable) {
4838
0
        ZSTD_window_update(&cctx->ldmState.window, src, srcSize, /* forceNonContiguous */ 0);
4839
0
    }
4840
4841
47.8k
    if (!frame) {
4842
        /* overflow check and correction for block mode */
4843
0
        ZSTD_overflowCorrectIfNeeded(
4844
0
            ms, &cctx->workspace, &cctx->appliedParams,
4845
0
            src, (BYTE const*)src + srcSize);
4846
0
    }
4847
4848
47.8k
    DEBUGLOG(5, "ZSTD_compressContinue_internal (blockSize=%u)", (unsigned)cctx->blockSizeMax);
4849
47.8k
    {   size_t const cSize = frame ?
4850
47.8k
                             ZSTD_compress_frameChunk (cctx, dst, dstCapacity, src, srcSize, lastFrameChunk) :
4851
47.8k
                             ZSTD_compressBlock_internal (cctx, dst, dstCapacity, src, srcSize, 0 /* frame */);
4852
47.8k
        FORWARD_IF_ERROR(cSize, "%s", frame ? "ZSTD_compress_frameChunk failed" : "ZSTD_compressBlock_internal failed");
4853
47.8k
        cctx->consumedSrcSize += srcSize;
4854
47.8k
        cctx->producedCSize += (cSize + fhSize);
4855
47.8k
        assert(!(cctx->appliedParams.fParams.contentSizeFlag && cctx->pledgedSrcSizePlusOne == 0));
4856
47.8k
        if (cctx->pledgedSrcSizePlusOne != 0) {  /* control src size */
4857
0
            ZSTD_STATIC_ASSERT(ZSTD_CONTENTSIZE_UNKNOWN == (unsigned long long)-1);
4858
0
            RETURN_ERROR_IF(
4859
0
                cctx->consumedSrcSize+1 > cctx->pledgedSrcSizePlusOne,
4860
0
                srcSize_wrong,
4861
0
                "error : pledgedSrcSize = %u, while realSrcSize >= %u",
4862
0
                (unsigned)cctx->pledgedSrcSizePlusOne-1,
4863
0
                (unsigned)cctx->consumedSrcSize);
4864
0
        }
4865
47.8k
        return cSize + fhSize;
4866
47.8k
    }
4867
47.8k
}
4868
4869
size_t ZSTD_compressContinue_public(ZSTD_CCtx* cctx,
4870
                                        void* dst, size_t dstCapacity,
4871
                                  const void* src, size_t srcSize)
4872
32.4k
{
4873
32.4k
    DEBUGLOG(5, "ZSTD_compressContinue (srcSize=%u)", (unsigned)srcSize);
4874
32.4k
    return ZSTD_compressContinue_internal(cctx, dst, dstCapacity, src, srcSize, 1 /* frame mode */, 0 /* last chunk */);
4875
32.4k
}
4876
4877
/* NOTE: Must just wrap ZSTD_compressContinue_public() */
4878
size_t ZSTD_compressContinue(ZSTD_CCtx* cctx,
4879
                             void* dst, size_t dstCapacity,
4880
                       const void* src, size_t srcSize)
4881
0
{
4882
0
    return ZSTD_compressContinue_public(cctx, dst, dstCapacity, src, srcSize);
4883
0
}
4884
4885
static size_t ZSTD_getBlockSize_deprecated(const ZSTD_CCtx* cctx)
4886
0
{
4887
0
    ZSTD_compressionParameters const cParams = cctx->appliedParams.cParams;
4888
0
    assert(!ZSTD_checkCParams(cParams));
4889
0
    return MIN(cctx->appliedParams.maxBlockSize, (size_t)1 << cParams.windowLog);
4890
0
}
4891
4892
/* NOTE: Must just wrap ZSTD_getBlockSize_deprecated() */
4893
size_t ZSTD_getBlockSize(const ZSTD_CCtx* cctx)
4894
0
{
4895
0
    return ZSTD_getBlockSize_deprecated(cctx);
4896
0
}
4897
4898
/* NOTE: Must just wrap ZSTD_compressBlock_deprecated() */
4899
size_t ZSTD_compressBlock_deprecated(ZSTD_CCtx* cctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize)
4900
0
{
4901
0
    DEBUGLOG(5, "ZSTD_compressBlock: srcSize = %u", (unsigned)srcSize);
4902
0
    { size_t const blockSizeMax = ZSTD_getBlockSize_deprecated(cctx);
4903
0
      RETURN_ERROR_IF(srcSize > blockSizeMax, srcSize_wrong, "input is larger than a block"); }
4904
4905
0
    return ZSTD_compressContinue_internal(cctx, dst, dstCapacity, src, srcSize, 0 /* frame mode */, 0 /* last chunk */);
4906
0
}
4907
4908
/* NOTE: Must just wrap ZSTD_compressBlock_deprecated() */
4909
size_t ZSTD_compressBlock(ZSTD_CCtx* cctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize)
4910
0
{
4911
0
    return ZSTD_compressBlock_deprecated(cctx, dst, dstCapacity, src, srcSize);
4912
0
}
4913
4914
/*! ZSTD_loadDictionaryContent() :
4915
 *  @return : 0, or an error code
4916
 */
4917
static size_t
4918
ZSTD_loadDictionaryContent(ZSTD_MatchState_t* ms,
4919
                        ldmState_t* ls,
4920
                        ZSTD_cwksp* ws,
4921
                        ZSTD_CCtx_params const* params,
4922
                        const void* src, size_t srcSize,
4923
                        ZSTD_dictTableLoadMethod_e dtlm,
4924
                        ZSTD_tableFillPurpose_e tfp)
4925
0
{
4926
0
    const BYTE* ip = (const BYTE*) src;
4927
0
    const BYTE* const iend = ip + srcSize;
4928
0
    int const loadLdmDict = params->ldmParams.enableLdm == ZSTD_ps_enable && ls != NULL;
4929
4930
    /* Assert that the ms params match the params we're being given */
4931
0
    ZSTD_assertEqualCParams(params->cParams, ms->cParams);
4932
4933
0
    {   /* Ensure large dictionaries can't cause index overflow */
4934
4935
        /* Allow the dictionary to set indices up to exactly ZSTD_CURRENT_MAX.
4936
         * Dictionaries right at the edge will immediately trigger overflow
4937
         * correction, but I don't want to insert extra constraints here.
4938
         */
4939
0
        U32 maxDictSize = ZSTD_CURRENT_MAX - ZSTD_WINDOW_START_INDEX;
4940
4941
0
        int const CDictTaggedIndices = ZSTD_CDictIndicesAreTagged(&params->cParams);
4942
0
        if (CDictTaggedIndices && tfp == ZSTD_tfp_forCDict) {
4943
            /* Some dictionary matchfinders in zstd use "short cache",
4944
             * which treats the lower ZSTD_SHORT_CACHE_TAG_BITS of each
4945
             * CDict hashtable entry as a tag rather than as part of an index.
4946
             * When short cache is used, we need to truncate the dictionary
4947
             * so that its indices don't overlap with the tag. */
4948
0
            U32 const shortCacheMaxDictSize = (1u << (32 - ZSTD_SHORT_CACHE_TAG_BITS)) - ZSTD_WINDOW_START_INDEX;
4949
0
            maxDictSize = MIN(maxDictSize, shortCacheMaxDictSize);
4950
0
            assert(!loadLdmDict);
4951
0
        }
4952
4953
        /* If the dictionary is too large, only load the suffix of the dictionary. */
4954
0
        if (srcSize > maxDictSize) {
4955
0
            ip = iend - maxDictSize;
4956
0
            src = ip;
4957
0
            srcSize = maxDictSize;
4958
0
        }
4959
0
    }
4960
4961
0
    if (srcSize > ZSTD_CHUNKSIZE_MAX) {
4962
        /* We must have cleared our windows when our source is this large. */
4963
0
        assert(ZSTD_window_isEmpty(ms->window));
4964
0
        if (loadLdmDict) assert(ZSTD_window_isEmpty(ls->window));
4965
0
    }
4966
0
    ZSTD_window_update(&ms->window, src, srcSize, /* forceNonContiguous */ 0);
4967
4968
0
    DEBUGLOG(4, "ZSTD_loadDictionaryContent: useRowMatchFinder=%d", (int)params->useRowMatchFinder);
4969
4970
0
    if (loadLdmDict) { /* Load the entire dict into LDM matchfinders. */
4971
0
        DEBUGLOG(4, "ZSTD_loadDictionaryContent: Trigger loadLdmDict");
4972
0
        ZSTD_window_update(&ls->window, src, srcSize, /* forceNonContiguous */ 0);
4973
0
        ls->loadedDictEnd = params->forceWindow ? 0 : (U32)(iend - ls->window.base);
4974
0
        ZSTD_ldm_fillHashTable(ls, ip, iend, &params->ldmParams);
4975
0
        DEBUGLOG(4, "ZSTD_loadDictionaryContent: ZSTD_ldm_fillHashTable completes");
4976
0
    }
4977
4978
    /* If the dict is larger than we can reasonably index in our tables, only load the suffix. */
4979
0
    {   U32 maxDictSize = 1U << MIN(MAX(params->cParams.hashLog + 3, params->cParams.chainLog + 1), 31);
4980
0
        if (srcSize > maxDictSize) {
4981
0
            ip = iend - maxDictSize;
4982
0
            src = ip;
4983
0
            srcSize = maxDictSize;
4984
0
        }
4985
0
    }
4986
4987
0
    ms->nextToUpdate = (U32)(ip - ms->window.base);
4988
0
    ms->loadedDictEnd = params->forceWindow ? 0 : (U32)(iend - ms->window.base);
4989
0
    ms->forceNonContiguous = params->deterministicRefPrefix;
4990
4991
0
    if (srcSize <= HASH_READ_SIZE) return 0;
4992
4993
0
    ZSTD_overflowCorrectIfNeeded(ms, ws, params, ip, iend);
4994
4995
0
    switch(params->cParams.strategy)
4996
0
    {
4997
0
    case ZSTD_fast:
4998
0
        ZSTD_fillHashTable(ms, iend, dtlm, tfp);
4999
0
        break;
5000
0
    case ZSTD_dfast:
5001
0
#ifndef ZSTD_EXCLUDE_DFAST_BLOCK_COMPRESSOR
5002
0
        ZSTD_fillDoubleHashTable(ms, iend, dtlm, tfp);
5003
#else
5004
        assert(0); /* shouldn't be called: cparams should've been adjusted. */
5005
#endif
5006
0
        break;
5007
5008
0
    case ZSTD_greedy:
5009
0
    case ZSTD_lazy:
5010
0
    case ZSTD_lazy2:
5011
0
#if !defined(ZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR) \
5012
0
 || !defined(ZSTD_EXCLUDE_LAZY_BLOCK_COMPRESSOR) \
5013
0
 || !defined(ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR)
5014
0
        assert(srcSize >= HASH_READ_SIZE);
5015
0
        if (ms->dedicatedDictSearch) {
5016
0
            assert(ms->chainTable != NULL);
5017
0
            ZSTD_dedicatedDictSearch_lazy_loadDictionary(ms, iend-HASH_READ_SIZE);
5018
0
        } else {
5019
0
            assert(params->useRowMatchFinder != ZSTD_ps_auto);
5020
0
            if (params->useRowMatchFinder == ZSTD_ps_enable) {
5021
0
                size_t const tagTableSize = ((size_t)1 << params->cParams.hashLog);
5022
0
                ZSTD_memset(ms->tagTable, 0, tagTableSize);
5023
0
                ZSTD_row_update(ms, iend-HASH_READ_SIZE);
5024
0
                DEBUGLOG(4, "Using row-based hash table for lazy dict");
5025
0
            } else {
5026
0
                ZSTD_insertAndFindFirstIndex(ms, iend-HASH_READ_SIZE);
5027
0
                DEBUGLOG(4, "Using chain-based hash table for lazy dict");
5028
0
            }
5029
0
        }
5030
#else
5031
        assert(0); /* shouldn't be called: cparams should've been adjusted. */
5032
#endif
5033
0
        break;
5034
5035
0
    case ZSTD_btlazy2:   /* we want the dictionary table fully sorted */
5036
0
    case ZSTD_btopt:
5037
0
    case ZSTD_btultra:
5038
0
    case ZSTD_btultra2:
5039
0
#if !defined(ZSTD_EXCLUDE_BTLAZY2_BLOCK_COMPRESSOR) \
5040
0
 || !defined(ZSTD_EXCLUDE_BTOPT_BLOCK_COMPRESSOR) \
5041
0
 || !defined(ZSTD_EXCLUDE_BTULTRA_BLOCK_COMPRESSOR)
5042
0
        assert(srcSize >= HASH_READ_SIZE);
5043
0
        DEBUGLOG(4, "Fill %u bytes into the Binary Tree", (unsigned)srcSize);
5044
0
        ZSTD_updateTree(ms, iend-HASH_READ_SIZE, iend);
5045
#else
5046
        assert(0); /* shouldn't be called: cparams should've been adjusted. */
5047
#endif
5048
0
        break;
5049
5050
0
    default:
5051
0
        assert(0);  /* not possible : not a valid strategy id */
5052
0
    }
5053
5054
0
    ms->nextToUpdate = (U32)(iend - ms->window.base);
5055
0
    return 0;
5056
0
}
5057
5058
5059
/* Dictionaries that assign zero probability to symbols that show up causes problems
5060
 * when FSE encoding. Mark dictionaries with zero probability symbols as FSE_repeat_check
5061
 * and only dictionaries with 100% valid symbols can be assumed valid.
5062
 */
5063
static FSE_repeat ZSTD_dictNCountRepeat(short* normalizedCounter, unsigned dictMaxSymbolValue, unsigned maxSymbolValue)
5064
0
{
5065
0
    U32 s;
5066
0
    if (dictMaxSymbolValue < maxSymbolValue) {
5067
0
        return FSE_repeat_check;
5068
0
    }
5069
0
    for (s = 0; s <= maxSymbolValue; ++s) {
5070
0
        if (normalizedCounter[s] == 0) {
5071
0
            return FSE_repeat_check;
5072
0
        }
5073
0
    }
5074
0
    return FSE_repeat_valid;
5075
0
}
5076
5077
size_t ZSTD_loadCEntropy(ZSTD_compressedBlockState_t* bs, void* workspace,
5078
                         const void* const dict, size_t dictSize)
5079
0
{
5080
0
    short offcodeNCount[MaxOff+1];
5081
0
    unsigned offcodeMaxValue = MaxOff;
5082
0
    const BYTE* dictPtr = (const BYTE*)dict;    /* skip magic num and dict ID */
5083
0
    const BYTE* const dictEnd = dictPtr + dictSize;
5084
0
    dictPtr += 8;
5085
0
    bs->entropy.huf.repeatMode = HUF_repeat_check;
5086
5087
0
    {   unsigned maxSymbolValue = 255;
5088
0
        unsigned hasZeroWeights = 1;
5089
0
        size_t const hufHeaderSize = HUF_readCTable((HUF_CElt*)bs->entropy.huf.CTable, &maxSymbolValue, dictPtr,
5090
0
            (size_t)(dictEnd-dictPtr), &hasZeroWeights);
5091
5092
        /* We only set the loaded table as valid if it contains all non-zero
5093
         * weights. Otherwise, we set it to check */
5094
0
        if (!hasZeroWeights && maxSymbolValue == 255)
5095
0
            bs->entropy.huf.repeatMode = HUF_repeat_valid;
5096
5097
0
        RETURN_ERROR_IF(HUF_isError(hufHeaderSize), dictionary_corrupted, "");
5098
0
        dictPtr += hufHeaderSize;
5099
0
    }
5100
5101
0
    {   unsigned offcodeLog;
5102
0
        size_t const offcodeHeaderSize = FSE_readNCount(offcodeNCount, &offcodeMaxValue, &offcodeLog, dictPtr, (size_t)(dictEnd-dictPtr));
5103
0
        RETURN_ERROR_IF(FSE_isError(offcodeHeaderSize), dictionary_corrupted, "");
5104
0
        RETURN_ERROR_IF(offcodeLog > OffFSELog, dictionary_corrupted, "");
5105
        /* fill all offset symbols to avoid garbage at end of table */
5106
0
        RETURN_ERROR_IF(FSE_isError(FSE_buildCTable_wksp(
5107
0
                bs->entropy.fse.offcodeCTable,
5108
0
                offcodeNCount, MaxOff, offcodeLog,
5109
0
                workspace, HUF_WORKSPACE_SIZE)),
5110
0
            dictionary_corrupted, "");
5111
        /* Defer checking offcodeMaxValue because we need to know the size of the dictionary content */
5112
0
        dictPtr += offcodeHeaderSize;
5113
0
    }
5114
5115
0
    {   short matchlengthNCount[MaxML+1];
5116
0
        unsigned matchlengthMaxValue = MaxML, matchlengthLog;
5117
0
        size_t const matchlengthHeaderSize = FSE_readNCount(matchlengthNCount, &matchlengthMaxValue, &matchlengthLog, dictPtr, (size_t)(dictEnd-dictPtr));
5118
0
        RETURN_ERROR_IF(FSE_isError(matchlengthHeaderSize), dictionary_corrupted, "");
5119
0
        RETURN_ERROR_IF(matchlengthLog > MLFSELog, dictionary_corrupted, "");
5120
0
        RETURN_ERROR_IF(FSE_isError(FSE_buildCTable_wksp(
5121
0
                bs->entropy.fse.matchlengthCTable,
5122
0
                matchlengthNCount, matchlengthMaxValue, matchlengthLog,
5123
0
                workspace, HUF_WORKSPACE_SIZE)),
5124
0
            dictionary_corrupted, "");
5125
0
        bs->entropy.fse.matchlength_repeatMode = ZSTD_dictNCountRepeat(matchlengthNCount, matchlengthMaxValue, MaxML);
5126
0
        dictPtr += matchlengthHeaderSize;
5127
0
    }
5128
5129
0
    {   short litlengthNCount[MaxLL+1];
5130
0
        unsigned litlengthMaxValue = MaxLL, litlengthLog;
5131
0
        size_t const litlengthHeaderSize = FSE_readNCount(litlengthNCount, &litlengthMaxValue, &litlengthLog, dictPtr, (size_t)(dictEnd-dictPtr));
5132
0
        RETURN_ERROR_IF(FSE_isError(litlengthHeaderSize), dictionary_corrupted, "");
5133
0
        RETURN_ERROR_IF(litlengthLog > LLFSELog, dictionary_corrupted, "");
5134
0
        RETURN_ERROR_IF(FSE_isError(FSE_buildCTable_wksp(
5135
0
                bs->entropy.fse.litlengthCTable,
5136
0
                litlengthNCount, litlengthMaxValue, litlengthLog,
5137
0
                workspace, HUF_WORKSPACE_SIZE)),
5138
0
            dictionary_corrupted, "");
5139
0
        bs->entropy.fse.litlength_repeatMode = ZSTD_dictNCountRepeat(litlengthNCount, litlengthMaxValue, MaxLL);
5140
0
        dictPtr += litlengthHeaderSize;
5141
0
    }
5142
5143
0
    RETURN_ERROR_IF(dictPtr+12 > dictEnd, dictionary_corrupted, "");
5144
0
    bs->rep[0] = MEM_readLE32(dictPtr+0);
5145
0
    bs->rep[1] = MEM_readLE32(dictPtr+4);
5146
0
    bs->rep[2] = MEM_readLE32(dictPtr+8);
5147
0
    dictPtr += 12;
5148
5149
0
    {   size_t const dictContentSize = (size_t)(dictEnd - dictPtr);
5150
0
        U32 offcodeMax = MaxOff;
5151
0
        if (dictContentSize <= ((U32)-1) - 128 KB) {
5152
0
            U32 const maxOffset = (U32)dictContentSize + 128 KB; /* The maximum offset that must be supported */
5153
0
            offcodeMax = ZSTD_highbit32(maxOffset); /* Calculate minimum offset code required to represent maxOffset */
5154
0
        }
5155
        /* All offset values <= dictContentSize + 128 KB must be representable for a valid table */
5156
0
        bs->entropy.fse.offcode_repeatMode = ZSTD_dictNCountRepeat(offcodeNCount, offcodeMaxValue, MIN(offcodeMax, MaxOff));
5157
5158
        /* All repCodes must be <= dictContentSize and != 0 */
5159
0
        {   U32 u;
5160
0
            for (u=0; u<3; u++) {
5161
0
                RETURN_ERROR_IF(bs->rep[u] == 0, dictionary_corrupted, "");
5162
0
                RETURN_ERROR_IF(bs->rep[u] > dictContentSize, dictionary_corrupted, "");
5163
0
    }   }   }
5164
5165
0
    return (size_t)(dictPtr - (const BYTE*)dict);
5166
0
}
5167
5168
/* Dictionary format :
5169
 * See :
5170
 * https://github.com/facebook/zstd/blob/release/doc/zstd_compression_format.md#dictionary-format
5171
 */
5172
/*! ZSTD_loadZstdDictionary() :
5173
 * @return : dictID, or an error code
5174
 *  assumptions : magic number supposed already checked
5175
 *                dictSize supposed >= 8
5176
 */
5177
static size_t ZSTD_loadZstdDictionary(ZSTD_compressedBlockState_t* bs,
5178
                                      ZSTD_MatchState_t* ms,
5179
                                      ZSTD_cwksp* ws,
5180
                                      ZSTD_CCtx_params const* params,
5181
                                      const void* dict, size_t dictSize,
5182
                                      ZSTD_dictTableLoadMethod_e dtlm,
5183
                                      ZSTD_tableFillPurpose_e tfp,
5184
                                      void* workspace)
5185
0
{
5186
0
    const BYTE* dictPtr = (const BYTE*)dict;
5187
0
    const BYTE* const dictEnd = dictPtr + dictSize;
5188
0
    size_t dictID;
5189
0
    size_t eSize;
5190
0
    ZSTD_STATIC_ASSERT(HUF_WORKSPACE_SIZE >= (1<<MAX(MLFSELog,LLFSELog)));
5191
0
    assert(dictSize >= 8);
5192
0
    assert(MEM_readLE32(dictPtr) == ZSTD_MAGIC_DICTIONARY);
5193
5194
0
    dictID = params->fParams.noDictIDFlag ? 0 :  MEM_readLE32(dictPtr + 4 /* skip magic number */ );
5195
0
    eSize = ZSTD_loadCEntropy(bs, workspace, dict, dictSize);
5196
0
    FORWARD_IF_ERROR(eSize, "ZSTD_loadCEntropy failed");
5197
0
    dictPtr += eSize;
5198
5199
0
    {
5200
0
        size_t const dictContentSize = (size_t)(dictEnd - dictPtr);
5201
0
        FORWARD_IF_ERROR(ZSTD_loadDictionaryContent(
5202
0
            ms, NULL, ws, params, dictPtr, dictContentSize, dtlm, tfp), "");
5203
0
    }
5204
0
    return dictID;
5205
0
}
5206
5207
/** ZSTD_compress_insertDictionary() :
5208
*   @return : dictID, or an error code */
5209
static size_t
5210
ZSTD_compress_insertDictionary(ZSTD_compressedBlockState_t* bs,
5211
                               ZSTD_MatchState_t* ms,
5212
                               ldmState_t* ls,
5213
                               ZSTD_cwksp* ws,
5214
                         const ZSTD_CCtx_params* params,
5215
                         const void* dict, size_t dictSize,
5216
                               ZSTD_dictContentType_e dictContentType,
5217
                               ZSTD_dictTableLoadMethod_e dtlm,
5218
                               ZSTD_tableFillPurpose_e tfp,
5219
                               void* workspace)
5220
15.4k
{
5221
15.4k
    DEBUGLOG(4, "ZSTD_compress_insertDictionary (dictSize=%u)", (U32)dictSize);
5222
15.4k
    if ((dict==NULL) || (dictSize<8)) {
5223
15.4k
        RETURN_ERROR_IF(dictContentType == ZSTD_dct_fullDict, dictionary_wrong, "");
5224
15.4k
        return 0;
5225
15.4k
    }
5226
5227
0
    ZSTD_reset_compressedBlockState(bs);
5228
5229
    /* dict restricted modes */
5230
0
    if (dictContentType == ZSTD_dct_rawContent)
5231
0
        return ZSTD_loadDictionaryContent(ms, ls, ws, params, dict, dictSize, dtlm, tfp);
5232
5233
0
    if (MEM_readLE32(dict) != ZSTD_MAGIC_DICTIONARY) {
5234
0
        if (dictContentType == ZSTD_dct_auto) {
5235
0
            DEBUGLOG(4, "raw content dictionary detected");
5236
0
            return ZSTD_loadDictionaryContent(
5237
0
                ms, ls, ws, params, dict, dictSize, dtlm, tfp);
5238
0
        }
5239
0
        RETURN_ERROR_IF(dictContentType == ZSTD_dct_fullDict, dictionary_wrong, "");
5240
0
        assert(0);   /* impossible */
5241
0
    }
5242
5243
    /* dict as full zstd dictionary */
5244
0
    return ZSTD_loadZstdDictionary(
5245
0
        bs, ms, ws, params, dict, dictSize, dtlm, tfp, workspace);
5246
0
}
5247
5248
0
#define ZSTD_USE_CDICT_PARAMS_SRCSIZE_CUTOFF (128 KB)
5249
0
#define ZSTD_USE_CDICT_PARAMS_DICTSIZE_MULTIPLIER (6ULL)
5250
5251
/*! ZSTD_compressBegin_internal() :
5252
 * Assumption : either @dict OR @cdict (or none) is non-NULL, never both
5253
 * @return : 0, or an error code */
5254
static size_t ZSTD_compressBegin_internal(ZSTD_CCtx* cctx,
5255
                                    const void* dict, size_t dictSize,
5256
                                    ZSTD_dictContentType_e dictContentType,
5257
                                    ZSTD_dictTableLoadMethod_e dtlm,
5258
                                    const ZSTD_CDict* cdict,
5259
                                    const ZSTD_CCtx_params* params, U64 pledgedSrcSize,
5260
                                    ZSTD_buffered_policy_e zbuff)
5261
15.4k
{
5262
15.4k
    size_t const dictContentSize = cdict ? cdict->dictContentSize : dictSize;
5263
15.4k
#if ZSTD_TRACE
5264
15.4k
    cctx->traceCtx = (ZSTD_trace_compress_begin != NULL) ? ZSTD_trace_compress_begin(cctx) : 0;
5265
15.4k
#endif
5266
15.4k
    DEBUGLOG(4, "ZSTD_compressBegin_internal: wlog=%u", params->cParams.windowLog);
5267
    /* params are supposed to be fully validated at this point */
5268
15.4k
    assert(!ZSTD_isError(ZSTD_checkCParams(params->cParams)));
5269
15.4k
    assert(!((dict) && (cdict)));  /* either dict or cdict, not both */
5270
15.4k
    if ( (cdict)
5271
15.4k
      && (cdict->dictContentSize > 0)
5272
15.4k
      && ( pledgedSrcSize < ZSTD_USE_CDICT_PARAMS_SRCSIZE_CUTOFF
5273
0
        || pledgedSrcSize < cdict->dictContentSize * ZSTD_USE_CDICT_PARAMS_DICTSIZE_MULTIPLIER
5274
0
        || pledgedSrcSize == ZSTD_CONTENTSIZE_UNKNOWN
5275
0
        || cdict->compressionLevel == 0)
5276
15.4k
      && (params->attachDictPref != ZSTD_dictForceLoad) ) {
5277
0
        return ZSTD_resetCCtx_usingCDict(cctx, cdict, params, pledgedSrcSize, zbuff);
5278
0
    }
5279
5280
15.4k
    FORWARD_IF_ERROR( ZSTD_resetCCtx_internal(cctx, params, pledgedSrcSize,
5281
15.4k
                                     dictContentSize,
5282
15.4k
                                     ZSTDcrp_makeClean, zbuff) , "");
5283
15.4k
    {   size_t const dictID = cdict ?
5284
0
                ZSTD_compress_insertDictionary(
5285
0
                        cctx->blockState.prevCBlock, &cctx->blockState.matchState,
5286
0
                        &cctx->ldmState, &cctx->workspace, &cctx->appliedParams, cdict->dictContent,
5287
0
                        cdict->dictContentSize, cdict->dictContentType, dtlm,
5288
0
                        ZSTD_tfp_forCCtx, cctx->tmpWorkspace)
5289
15.4k
              : ZSTD_compress_insertDictionary(
5290
15.4k
                        cctx->blockState.prevCBlock, &cctx->blockState.matchState,
5291
15.4k
                        &cctx->ldmState, &cctx->workspace, &cctx->appliedParams, dict, dictSize,
5292
15.4k
                        dictContentType, dtlm, ZSTD_tfp_forCCtx, cctx->tmpWorkspace);
5293
15.4k
        FORWARD_IF_ERROR(dictID, "ZSTD_compress_insertDictionary failed");
5294
15.4k
        assert(dictID <= UINT_MAX);
5295
15.4k
        cctx->dictID = (U32)dictID;
5296
15.4k
        cctx->dictContentSize = dictContentSize;
5297
15.4k
    }
5298
0
    return 0;
5299
15.4k
}
5300
5301
size_t ZSTD_compressBegin_advanced_internal(ZSTD_CCtx* cctx,
5302
                                    const void* dict, size_t dictSize,
5303
                                    ZSTD_dictContentType_e dictContentType,
5304
                                    ZSTD_dictTableLoadMethod_e dtlm,
5305
                                    const ZSTD_CDict* cdict,
5306
                                    const ZSTD_CCtx_params* params,
5307
                                    unsigned long long pledgedSrcSize)
5308
0
{
5309
0
    DEBUGLOG(4, "ZSTD_compressBegin_advanced_internal: wlog=%u", params->cParams.windowLog);
5310
    /* compression parameters verification and optimization */
5311
0
    FORWARD_IF_ERROR( ZSTD_checkCParams(params->cParams) , "");
5312
0
    return ZSTD_compressBegin_internal(cctx,
5313
0
                                       dict, dictSize, dictContentType, dtlm,
5314
0
                                       cdict,
5315
0
                                       params, pledgedSrcSize,
5316
0
                                       ZSTDb_not_buffered);
5317
0
}
5318
5319
/*! ZSTD_compressBegin_advanced() :
5320
*   @return : 0, or an error code */
5321
size_t ZSTD_compressBegin_advanced(ZSTD_CCtx* cctx,
5322
                             const void* dict, size_t dictSize,
5323
                                   ZSTD_parameters params, unsigned long long pledgedSrcSize)
5324
0
{
5325
0
    ZSTD_CCtx_params cctxParams;
5326
0
    ZSTD_CCtxParams_init_internal(&cctxParams, &params, ZSTD_NO_CLEVEL);
5327
0
    return ZSTD_compressBegin_advanced_internal(cctx,
5328
0
                                            dict, dictSize, ZSTD_dct_auto, ZSTD_dtlm_fast,
5329
0
                                            NULL /*cdict*/,
5330
0
                                            &cctxParams, pledgedSrcSize);
5331
0
}
5332
5333
static size_t
5334
ZSTD_compressBegin_usingDict_deprecated(ZSTD_CCtx* cctx, const void* dict, size_t dictSize, int compressionLevel)
5335
0
{
5336
0
    ZSTD_CCtx_params cctxParams;
5337
0
    {   ZSTD_parameters const params = ZSTD_getParams_internal(compressionLevel, ZSTD_CONTENTSIZE_UNKNOWN, dictSize, ZSTD_cpm_noAttachDict);
5338
0
        ZSTD_CCtxParams_init_internal(&cctxParams, &params, (compressionLevel == 0) ? ZSTD_CLEVEL_DEFAULT : compressionLevel);
5339
0
    }
5340
0
    DEBUGLOG(4, "ZSTD_compressBegin_usingDict (dictSize=%u)", (unsigned)dictSize);
5341
0
    return ZSTD_compressBegin_internal(cctx, dict, dictSize, ZSTD_dct_auto, ZSTD_dtlm_fast, NULL,
5342
0
                                       &cctxParams, ZSTD_CONTENTSIZE_UNKNOWN, ZSTDb_not_buffered);
5343
0
}
5344
5345
size_t
5346
ZSTD_compressBegin_usingDict(ZSTD_CCtx* cctx, const void* dict, size_t dictSize, int compressionLevel)
5347
0
{
5348
0
    return ZSTD_compressBegin_usingDict_deprecated(cctx, dict, dictSize, compressionLevel);
5349
0
}
5350
5351
size_t ZSTD_compressBegin(ZSTD_CCtx* cctx, int compressionLevel)
5352
0
{
5353
0
    return ZSTD_compressBegin_usingDict_deprecated(cctx, NULL, 0, compressionLevel);
5354
0
}
5355
5356
5357
/*! ZSTD_writeEpilogue() :
5358
*   Ends a frame.
5359
*   @return : nb of bytes written into dst (or an error code) */
5360
static size_t ZSTD_writeEpilogue(ZSTD_CCtx* cctx, void* dst, size_t dstCapacity)
5361
15.4k
{
5362
15.4k
    BYTE* const ostart = (BYTE*)dst;
5363
15.4k
    BYTE* op = ostart;
5364
5365
15.4k
    DEBUGLOG(4, "ZSTD_writeEpilogue");
5366
15.4k
    RETURN_ERROR_IF(cctx->stage == ZSTDcs_created, stage_wrong, "init missing");
5367
5368
    /* special case : empty frame */
5369
15.4k
    if (cctx->stage == ZSTDcs_init) {
5370
0
        size_t fhSize = ZSTD_writeFrameHeader(dst, dstCapacity, &cctx->appliedParams, 0, 0);
5371
0
        FORWARD_IF_ERROR(fhSize, "ZSTD_writeFrameHeader failed");
5372
0
        dstCapacity -= fhSize;
5373
0
        op += fhSize;
5374
0
        cctx->stage = ZSTDcs_ongoing;
5375
0
    }
5376
5377
15.4k
    if (cctx->stage != ZSTDcs_ending) {
5378
        /* write one last empty block, make it the "last" block */
5379
22
        U32 const cBlockHeader24 = 1 /* last block */ + (((U32)bt_raw)<<1) + 0;
5380
22
        ZSTD_STATIC_ASSERT(ZSTD_BLOCKHEADERSIZE == 3);
5381
22
        RETURN_ERROR_IF(dstCapacity<3, dstSize_tooSmall, "no room for epilogue");
5382
22
        MEM_writeLE24(op, cBlockHeader24);
5383
22
        op += ZSTD_blockHeaderSize;
5384
22
        dstCapacity -= ZSTD_blockHeaderSize;
5385
22
    }
5386
5387
15.4k
    if (cctx->appliedParams.fParams.checksumFlag) {
5388
0
        U32 const checksum = (U32) XXH64_digest(&cctx->xxhState);
5389
0
        RETURN_ERROR_IF(dstCapacity<4, dstSize_tooSmall, "no room for checksum");
5390
0
        DEBUGLOG(4, "ZSTD_writeEpilogue: write checksum : %08X", (unsigned)checksum);
5391
0
        MEM_writeLE32(op, checksum);
5392
0
        op += 4;
5393
0
    }
5394
5395
15.4k
    cctx->stage = ZSTDcs_created;  /* return to "created but no init" status */
5396
15.4k
    return (size_t)(op-ostart);
5397
15.4k
}
5398
5399
void ZSTD_CCtx_trace(ZSTD_CCtx* cctx, size_t extraCSize)
5400
15.4k
{
5401
15.4k
#if ZSTD_TRACE
5402
15.4k
    if (cctx->traceCtx && ZSTD_trace_compress_end != NULL) {
5403
0
        int const streaming = cctx->inBuffSize > 0 || cctx->outBuffSize > 0 || cctx->appliedParams.nbWorkers > 0;
5404
0
        ZSTD_Trace trace;
5405
0
        ZSTD_memset(&trace, 0, sizeof(trace));
5406
0
        trace.version = ZSTD_VERSION_NUMBER;
5407
0
        trace.streaming = streaming;
5408
0
        trace.dictionaryID = cctx->dictID;
5409
0
        trace.dictionarySize = cctx->dictContentSize;
5410
0
        trace.uncompressedSize = cctx->consumedSrcSize;
5411
0
        trace.compressedSize = cctx->producedCSize + extraCSize;
5412
0
        trace.params = &cctx->appliedParams;
5413
0
        trace.cctx = cctx;
5414
0
        ZSTD_trace_compress_end(cctx->traceCtx, &trace);
5415
0
    }
5416
15.4k
    cctx->traceCtx = 0;
5417
#else
5418
    (void)cctx;
5419
    (void)extraCSize;
5420
#endif
5421
15.4k
}
5422
5423
size_t ZSTD_compressEnd_public(ZSTD_CCtx* cctx,
5424
                               void* dst, size_t dstCapacity,
5425
                         const void* src, size_t srcSize)
5426
15.4k
{
5427
15.4k
    size_t endResult;
5428
15.4k
    size_t const cSize = ZSTD_compressContinue_internal(cctx,
5429
15.4k
                                dst, dstCapacity, src, srcSize,
5430
15.4k
                                1 /* frame mode */, 1 /* last chunk */);
5431
15.4k
    FORWARD_IF_ERROR(cSize, "ZSTD_compressContinue_internal failed");
5432
15.4k
    endResult = ZSTD_writeEpilogue(cctx, (char*)dst + cSize, dstCapacity-cSize);
5433
15.4k
    FORWARD_IF_ERROR(endResult, "ZSTD_writeEpilogue failed");
5434
15.4k
    assert(!(cctx->appliedParams.fParams.contentSizeFlag && cctx->pledgedSrcSizePlusOne == 0));
5435
15.4k
    if (cctx->pledgedSrcSizePlusOne != 0) {  /* control src size */
5436
0
        ZSTD_STATIC_ASSERT(ZSTD_CONTENTSIZE_UNKNOWN == (unsigned long long)-1);
5437
0
        DEBUGLOG(4, "end of frame : controlling src size");
5438
0
        RETURN_ERROR_IF(
5439
0
            cctx->pledgedSrcSizePlusOne != cctx->consumedSrcSize+1,
5440
0
            srcSize_wrong,
5441
0
             "error : pledgedSrcSize = %u, while realSrcSize = %u",
5442
0
            (unsigned)cctx->pledgedSrcSizePlusOne-1,
5443
0
            (unsigned)cctx->consumedSrcSize);
5444
0
    }
5445
15.4k
    ZSTD_CCtx_trace(cctx, endResult);
5446
15.4k
    return cSize + endResult;
5447
15.4k
}
5448
5449
/* NOTE: Must just wrap ZSTD_compressEnd_public() */
5450
size_t ZSTD_compressEnd(ZSTD_CCtx* cctx,
5451
                        void* dst, size_t dstCapacity,
5452
                  const void* src, size_t srcSize)
5453
0
{
5454
0
    return ZSTD_compressEnd_public(cctx, dst, dstCapacity, src, srcSize);
5455
0
}
5456
5457
size_t ZSTD_compress_advanced (ZSTD_CCtx* cctx,
5458
                               void* dst, size_t dstCapacity,
5459
                         const void* src, size_t srcSize,
5460
                         const void* dict,size_t dictSize,
5461
                               ZSTD_parameters params)
5462
0
{
5463
0
    DEBUGLOG(4, "ZSTD_compress_advanced");
5464
0
    FORWARD_IF_ERROR(ZSTD_checkCParams(params.cParams), "");
5465
0
    ZSTD_CCtxParams_init_internal(&cctx->simpleApiParams, &params, ZSTD_NO_CLEVEL);
5466
0
    return ZSTD_compress_advanced_internal(cctx,
5467
0
                                           dst, dstCapacity,
5468
0
                                           src, srcSize,
5469
0
                                           dict, dictSize,
5470
0
                                           &cctx->simpleApiParams);
5471
0
}
5472
5473
/* Internal */
5474
size_t ZSTD_compress_advanced_internal(
5475
        ZSTD_CCtx* cctx,
5476
        void* dst, size_t dstCapacity,
5477
        const void* src, size_t srcSize,
5478
        const void* dict,size_t dictSize,
5479
        const ZSTD_CCtx_params* params)
5480
0
{
5481
0
    DEBUGLOG(4, "ZSTD_compress_advanced_internal (srcSize:%u)", (unsigned)srcSize);
5482
0
    FORWARD_IF_ERROR( ZSTD_compressBegin_internal(cctx,
5483
0
                         dict, dictSize, ZSTD_dct_auto, ZSTD_dtlm_fast, NULL,
5484
0
                         params, srcSize, ZSTDb_not_buffered) , "");
5485
0
    return ZSTD_compressEnd_public(cctx, dst, dstCapacity, src, srcSize);
5486
0
}
5487
5488
size_t ZSTD_compress_usingDict(ZSTD_CCtx* cctx,
5489
                               void* dst, size_t dstCapacity,
5490
                         const void* src, size_t srcSize,
5491
                         const void* dict, size_t dictSize,
5492
                               int compressionLevel)
5493
0
{
5494
0
    {
5495
0
        ZSTD_parameters const params = ZSTD_getParams_internal(compressionLevel, srcSize, dict ? dictSize : 0, ZSTD_cpm_noAttachDict);
5496
0
        assert(params.fParams.contentSizeFlag == 1);
5497
0
        ZSTD_CCtxParams_init_internal(&cctx->simpleApiParams, &params, (compressionLevel == 0) ? ZSTD_CLEVEL_DEFAULT: compressionLevel);
5498
0
    }
5499
0
    DEBUGLOG(4, "ZSTD_compress_usingDict (srcSize=%u)", (unsigned)srcSize);
5500
0
    return ZSTD_compress_advanced_internal(cctx, dst, dstCapacity, src, srcSize, dict, dictSize, &cctx->simpleApiParams);
5501
0
}
5502
5503
size_t ZSTD_compressCCtx(ZSTD_CCtx* cctx,
5504
                         void* dst, size_t dstCapacity,
5505
                   const void* src, size_t srcSize,
5506
                         int compressionLevel)
5507
0
{
5508
0
    DEBUGLOG(4, "ZSTD_compressCCtx (srcSize=%u)", (unsigned)srcSize);
5509
0
    assert(cctx != NULL);
5510
0
    return ZSTD_compress_usingDict(cctx, dst, dstCapacity, src, srcSize, NULL, 0, compressionLevel);
5511
0
}
5512
5513
size_t ZSTD_compress(void* dst, size_t dstCapacity,
5514
               const void* src, size_t srcSize,
5515
                     int compressionLevel)
5516
0
{
5517
0
    size_t result;
5518
#if ZSTD_COMPRESS_HEAPMODE
5519
    ZSTD_CCtx* cctx = ZSTD_createCCtx();
5520
    RETURN_ERROR_IF(!cctx, memory_allocation, "ZSTD_createCCtx failed");
5521
    result = ZSTD_compressCCtx(cctx, dst, dstCapacity, src, srcSize, compressionLevel);
5522
    ZSTD_freeCCtx(cctx);
5523
#else
5524
0
    ZSTD_CCtx ctxBody;
5525
0
    ZSTD_initCCtx(&ctxBody, ZSTD_defaultCMem);
5526
0
    result = ZSTD_compressCCtx(&ctxBody, dst, dstCapacity, src, srcSize, compressionLevel);
5527
0
    ZSTD_freeCCtxContent(&ctxBody);   /* can't free ctxBody itself, as it's on stack; free only heap content */
5528
0
#endif
5529
0
    return result;
5530
0
}
5531
5532
5533
/* =====  Dictionary API  ===== */
5534
5535
/*! ZSTD_estimateCDictSize_advanced() :
5536
 *  Estimate amount of memory that will be needed to create a dictionary with following arguments */
5537
size_t ZSTD_estimateCDictSize_advanced(
5538
        size_t dictSize, ZSTD_compressionParameters cParams,
5539
        ZSTD_dictLoadMethod_e dictLoadMethod)
5540
0
{
5541
0
    DEBUGLOG(5, "sizeof(ZSTD_CDict) : %u", (unsigned)sizeof(ZSTD_CDict));
5542
0
    return ZSTD_cwksp_alloc_size(sizeof(ZSTD_CDict))
5543
0
         + ZSTD_cwksp_alloc_size(HUF_WORKSPACE_SIZE)
5544
         /* enableDedicatedDictSearch == 1 ensures that CDict estimation will not be too small
5545
          * in case we are using DDS with row-hash. */
5546
0
         + ZSTD_sizeof_matchState(&cParams, ZSTD_resolveRowMatchFinderMode(ZSTD_ps_auto, &cParams),
5547
0
                                  /* enableDedicatedDictSearch */ 1, /* forCCtx */ 0)
5548
0
         + (dictLoadMethod == ZSTD_dlm_byRef ? 0
5549
0
            : ZSTD_cwksp_alloc_size(ZSTD_cwksp_align(dictSize, sizeof(void *))));
5550
0
}
5551
5552
size_t ZSTD_estimateCDictSize(size_t dictSize, int compressionLevel)
5553
0
{
5554
0
    ZSTD_compressionParameters const cParams = ZSTD_getCParams_internal(compressionLevel, ZSTD_CONTENTSIZE_UNKNOWN, dictSize, ZSTD_cpm_createCDict);
5555
0
    return ZSTD_estimateCDictSize_advanced(dictSize, cParams, ZSTD_dlm_byCopy);
5556
0
}
5557
5558
size_t ZSTD_sizeof_CDict(const ZSTD_CDict* cdict)
5559
0
{
5560
0
    if (cdict==NULL) return 0;   /* support sizeof on NULL */
5561
0
    DEBUGLOG(5, "sizeof(*cdict) : %u", (unsigned)sizeof(*cdict));
5562
    /* cdict may be in the workspace */
5563
0
    return (cdict->workspace.workspace == cdict ? 0 : sizeof(*cdict))
5564
0
        + ZSTD_cwksp_sizeof(&cdict->workspace);
5565
0
}
5566
5567
static size_t ZSTD_initCDict_internal(
5568
                    ZSTD_CDict* cdict,
5569
              const void* dictBuffer, size_t dictSize,
5570
                    ZSTD_dictLoadMethod_e dictLoadMethod,
5571
                    ZSTD_dictContentType_e dictContentType,
5572
                    ZSTD_CCtx_params params)
5573
0
{
5574
0
    DEBUGLOG(3, "ZSTD_initCDict_internal (dictContentType:%u)", (unsigned)dictContentType);
5575
0
    assert(!ZSTD_checkCParams(params.cParams));
5576
0
    cdict->matchState.cParams = params.cParams;
5577
0
    cdict->matchState.dedicatedDictSearch = params.enableDedicatedDictSearch;
5578
0
    if ((dictLoadMethod == ZSTD_dlm_byRef) || (!dictBuffer) || (!dictSize)) {
5579
0
        cdict->dictContent = dictBuffer;
5580
0
    } else {
5581
0
         void *internalBuffer = ZSTD_cwksp_reserve_object(&cdict->workspace, ZSTD_cwksp_align(dictSize, sizeof(void*)));
5582
0
        RETURN_ERROR_IF(!internalBuffer, memory_allocation, "NULL pointer!");
5583
0
        cdict->dictContent = internalBuffer;
5584
0
        ZSTD_memcpy(internalBuffer, dictBuffer, dictSize);
5585
0
    }
5586
0
    cdict->dictContentSize = dictSize;
5587
0
    cdict->dictContentType = dictContentType;
5588
5589
0
    cdict->entropyWorkspace = (U32*)ZSTD_cwksp_reserve_object(&cdict->workspace, HUF_WORKSPACE_SIZE);
5590
5591
5592
    /* Reset the state to no dictionary */
5593
0
    ZSTD_reset_compressedBlockState(&cdict->cBlockState);
5594
0
    FORWARD_IF_ERROR(ZSTD_reset_matchState(
5595
0
        &cdict->matchState,
5596
0
        &cdict->workspace,
5597
0
        &params.cParams,
5598
0
        params.useRowMatchFinder,
5599
0
        ZSTDcrp_makeClean,
5600
0
        ZSTDirp_reset,
5601
0
        ZSTD_resetTarget_CDict), "");
5602
    /* (Maybe) load the dictionary
5603
     * Skips loading the dictionary if it is < 8 bytes.
5604
     */
5605
0
    {   params.compressionLevel = ZSTD_CLEVEL_DEFAULT;
5606
0
        params.fParams.contentSizeFlag = 1;
5607
0
        {   size_t const dictID = ZSTD_compress_insertDictionary(
5608
0
                    &cdict->cBlockState, &cdict->matchState, NULL, &cdict->workspace,
5609
0
                    &params, cdict->dictContent, cdict->dictContentSize,
5610
0
                    dictContentType, ZSTD_dtlm_full, ZSTD_tfp_forCDict, cdict->entropyWorkspace);
5611
0
            FORWARD_IF_ERROR(dictID, "ZSTD_compress_insertDictionary failed");
5612
0
            assert(dictID <= (size_t)(U32)-1);
5613
0
            cdict->dictID = (U32)dictID;
5614
0
        }
5615
0
    }
5616
5617
0
    return 0;
5618
0
}
5619
5620
static ZSTD_CDict*
5621
ZSTD_createCDict_advanced_internal(size_t dictSize,
5622
                                ZSTD_dictLoadMethod_e dictLoadMethod,
5623
                                ZSTD_compressionParameters cParams,
5624
                                ZSTD_ParamSwitch_e useRowMatchFinder,
5625
                                int enableDedicatedDictSearch,
5626
                                ZSTD_customMem customMem)
5627
0
{
5628
0
    if ((!customMem.customAlloc) ^ (!customMem.customFree)) return NULL;
5629
0
    DEBUGLOG(3, "ZSTD_createCDict_advanced_internal (dictSize=%u)", (unsigned)dictSize);
5630
5631
0
    {   size_t const workspaceSize =
5632
0
            ZSTD_cwksp_alloc_size(sizeof(ZSTD_CDict)) +
5633
0
            ZSTD_cwksp_alloc_size(HUF_WORKSPACE_SIZE) +
5634
0
            ZSTD_sizeof_matchState(&cParams, useRowMatchFinder, enableDedicatedDictSearch, /* forCCtx */ 0) +
5635
0
            (dictLoadMethod == ZSTD_dlm_byRef ? 0
5636
0
             : ZSTD_cwksp_alloc_size(ZSTD_cwksp_align(dictSize, sizeof(void*))));
5637
0
        void* const workspace = ZSTD_customMalloc(workspaceSize, customMem);
5638
0
        ZSTD_cwksp ws;
5639
0
        ZSTD_CDict* cdict;
5640
5641
0
        if (!workspace) {
5642
0
            ZSTD_customFree(workspace, customMem);
5643
0
            return NULL;
5644
0
        }
5645
5646
0
        ZSTD_cwksp_init(&ws, workspace, workspaceSize, ZSTD_cwksp_dynamic_alloc);
5647
5648
0
        cdict = (ZSTD_CDict*)ZSTD_cwksp_reserve_object(&ws, sizeof(ZSTD_CDict));
5649
0
        assert(cdict != NULL);
5650
0
        ZSTD_cwksp_move(&cdict->workspace, &ws);
5651
0
        cdict->customMem = customMem;
5652
0
        cdict->compressionLevel = ZSTD_NO_CLEVEL; /* signals advanced API usage */
5653
0
        cdict->useRowMatchFinder = useRowMatchFinder;
5654
0
        return cdict;
5655
0
    }
5656
0
}
5657
5658
ZSTD_CDict* ZSTD_createCDict_advanced(const void* dictBuffer, size_t dictSize,
5659
                                      ZSTD_dictLoadMethod_e dictLoadMethod,
5660
                                      ZSTD_dictContentType_e dictContentType,
5661
                                      ZSTD_compressionParameters cParams,
5662
                                      ZSTD_customMem customMem)
5663
0
{
5664
0
    ZSTD_CCtx_params cctxParams;
5665
0
    ZSTD_memset(&cctxParams, 0, sizeof(cctxParams));
5666
0
    DEBUGLOG(3, "ZSTD_createCDict_advanced, dictSize=%u, mode=%u", (unsigned)dictSize, (unsigned)dictContentType);
5667
0
    ZSTD_CCtxParams_init(&cctxParams, 0);
5668
0
    cctxParams.cParams = cParams;
5669
0
    cctxParams.customMem = customMem;
5670
0
    return ZSTD_createCDict_advanced2(
5671
0
        dictBuffer, dictSize,
5672
0
        dictLoadMethod, dictContentType,
5673
0
        &cctxParams, customMem);
5674
0
}
5675
5676
ZSTD_CDict* ZSTD_createCDict_advanced2(
5677
        const void* dict, size_t dictSize,
5678
        ZSTD_dictLoadMethod_e dictLoadMethod,
5679
        ZSTD_dictContentType_e dictContentType,
5680
        const ZSTD_CCtx_params* originalCctxParams,
5681
        ZSTD_customMem customMem)
5682
0
{
5683
0
    ZSTD_CCtx_params cctxParams = *originalCctxParams;
5684
0
    ZSTD_compressionParameters cParams;
5685
0
    ZSTD_CDict* cdict;
5686
5687
0
    DEBUGLOG(3, "ZSTD_createCDict_advanced2, dictSize=%u, mode=%u", (unsigned)dictSize, (unsigned)dictContentType);
5688
0
    if (!customMem.customAlloc ^ !customMem.customFree) return NULL;
5689
5690
0
    if (cctxParams.enableDedicatedDictSearch) {
5691
0
        cParams = ZSTD_dedicatedDictSearch_getCParams(
5692
0
            cctxParams.compressionLevel, dictSize);
5693
0
        ZSTD_overrideCParams(&cParams, &cctxParams.cParams);
5694
0
    } else {
5695
0
        cParams = ZSTD_getCParamsFromCCtxParams(
5696
0
            &cctxParams, ZSTD_CONTENTSIZE_UNKNOWN, dictSize, ZSTD_cpm_createCDict);
5697
0
    }
5698
5699
0
    if (!ZSTD_dedicatedDictSearch_isSupported(&cParams)) {
5700
        /* Fall back to non-DDSS params */
5701
0
        cctxParams.enableDedicatedDictSearch = 0;
5702
0
        cParams = ZSTD_getCParamsFromCCtxParams(
5703
0
            &cctxParams, ZSTD_CONTENTSIZE_UNKNOWN, dictSize, ZSTD_cpm_createCDict);
5704
0
    }
5705
5706
0
    DEBUGLOG(3, "ZSTD_createCDict_advanced2: DedicatedDictSearch=%u", cctxParams.enableDedicatedDictSearch);
5707
0
    cctxParams.cParams = cParams;
5708
0
    cctxParams.useRowMatchFinder = ZSTD_resolveRowMatchFinderMode(cctxParams.useRowMatchFinder, &cParams);
5709
5710
0
    cdict = ZSTD_createCDict_advanced_internal(dictSize,
5711
0
                        dictLoadMethod, cctxParams.cParams,
5712
0
                        cctxParams.useRowMatchFinder, cctxParams.enableDedicatedDictSearch,
5713
0
                        customMem);
5714
5715
0
    if (!cdict || ZSTD_isError( ZSTD_initCDict_internal(cdict,
5716
0
                                    dict, dictSize,
5717
0
                                    dictLoadMethod, dictContentType,
5718
0
                                    cctxParams) )) {
5719
0
        ZSTD_freeCDict(cdict);
5720
0
        return NULL;
5721
0
    }
5722
5723
0
    return cdict;
5724
0
}
5725
5726
ZSTD_CDict* ZSTD_createCDict(const void* dict, size_t dictSize, int compressionLevel)
5727
0
{
5728
0
    ZSTD_compressionParameters cParams = ZSTD_getCParams_internal(compressionLevel, ZSTD_CONTENTSIZE_UNKNOWN, dictSize, ZSTD_cpm_createCDict);
5729
0
    ZSTD_CDict* const cdict = ZSTD_createCDict_advanced(dict, dictSize,
5730
0
                                                  ZSTD_dlm_byCopy, ZSTD_dct_auto,
5731
0
                                                  cParams, ZSTD_defaultCMem);
5732
0
    if (cdict)
5733
0
        cdict->compressionLevel = (compressionLevel == 0) ? ZSTD_CLEVEL_DEFAULT : compressionLevel;
5734
0
    return cdict;
5735
0
}
5736
5737
ZSTD_CDict* ZSTD_createCDict_byReference(const void* dict, size_t dictSize, int compressionLevel)
5738
0
{
5739
0
    ZSTD_compressionParameters cParams = ZSTD_getCParams_internal(compressionLevel, ZSTD_CONTENTSIZE_UNKNOWN, dictSize, ZSTD_cpm_createCDict);
5740
0
    ZSTD_CDict* const cdict = ZSTD_createCDict_advanced(dict, dictSize,
5741
0
                                     ZSTD_dlm_byRef, ZSTD_dct_auto,
5742
0
                                     cParams, ZSTD_defaultCMem);
5743
0
    if (cdict)
5744
0
        cdict->compressionLevel = (compressionLevel == 0) ? ZSTD_CLEVEL_DEFAULT : compressionLevel;
5745
0
    return cdict;
5746
0
}
5747
5748
size_t ZSTD_freeCDict(ZSTD_CDict* cdict)
5749
27.6k
{
5750
27.6k
    if (cdict==NULL) return 0;   /* support free on NULL */
5751
0
    {   ZSTD_customMem const cMem = cdict->customMem;
5752
0
        int cdictInWorkspace = ZSTD_cwksp_owns_buffer(&cdict->workspace, cdict);
5753
0
        ZSTD_cwksp_free(&cdict->workspace, cMem);
5754
0
        if (!cdictInWorkspace) {
5755
0
            ZSTD_customFree(cdict, cMem);
5756
0
        }
5757
0
        return 0;
5758
27.6k
    }
5759
27.6k
}
5760
5761
/*! ZSTD_initStaticCDict_advanced() :
5762
 *  Generate a digested dictionary in provided memory area.
5763
 *  workspace: The memory area to emplace the dictionary into.
5764
 *             Provided pointer must 8-bytes aligned.
5765
 *             It must outlive dictionary usage.
5766
 *  workspaceSize: Use ZSTD_estimateCDictSize()
5767
 *                 to determine how large workspace must be.
5768
 *  cParams : use ZSTD_getCParams() to transform a compression level
5769
 *            into its relevant cParams.
5770
 * @return : pointer to ZSTD_CDict*, or NULL if error (size too small)
5771
 *  Note : there is no corresponding "free" function.
5772
 *         Since workspace was allocated externally, it must be freed externally.
5773
 */
5774
const ZSTD_CDict* ZSTD_initStaticCDict(
5775
                                 void* workspace, size_t workspaceSize,
5776
                           const void* dict, size_t dictSize,
5777
                                 ZSTD_dictLoadMethod_e dictLoadMethod,
5778
                                 ZSTD_dictContentType_e dictContentType,
5779
                                 ZSTD_compressionParameters cParams)
5780
0
{
5781
0
    ZSTD_ParamSwitch_e const useRowMatchFinder = ZSTD_resolveRowMatchFinderMode(ZSTD_ps_auto, &cParams);
5782
    /* enableDedicatedDictSearch == 1 ensures matchstate is not too small in case this CDict will be used for DDS + row hash */
5783
0
    size_t const matchStateSize = ZSTD_sizeof_matchState(&cParams, useRowMatchFinder, /* enableDedicatedDictSearch */ 1, /* forCCtx */ 0);
5784
0
    size_t const neededSize = ZSTD_cwksp_alloc_size(sizeof(ZSTD_CDict))
5785
0
                            + (dictLoadMethod == ZSTD_dlm_byRef ? 0
5786
0
                               : ZSTD_cwksp_alloc_size(ZSTD_cwksp_align(dictSize, sizeof(void*))))
5787
0
                            + ZSTD_cwksp_alloc_size(HUF_WORKSPACE_SIZE)
5788
0
                            + matchStateSize;
5789
0
    ZSTD_CDict* cdict;
5790
0
    ZSTD_CCtx_params params;
5791
5792
0
    DEBUGLOG(4, "ZSTD_initStaticCDict (dictSize==%u)", (unsigned)dictSize);
5793
0
    if ((size_t)workspace & 7) return NULL;  /* 8-aligned */
5794
5795
0
    {
5796
0
        ZSTD_cwksp ws;
5797
0
        ZSTD_cwksp_init(&ws, workspace, workspaceSize, ZSTD_cwksp_static_alloc);
5798
0
        cdict = (ZSTD_CDict*)ZSTD_cwksp_reserve_object(&ws, sizeof(ZSTD_CDict));
5799
0
        if (cdict == NULL) return NULL;
5800
0
        ZSTD_cwksp_move(&cdict->workspace, &ws);
5801
0
    }
5802
5803
0
    if (workspaceSize < neededSize) return NULL;
5804
5805
0
    ZSTD_CCtxParams_init(&params, 0);
5806
0
    params.cParams = cParams;
5807
0
    params.useRowMatchFinder = useRowMatchFinder;
5808
0
    cdict->useRowMatchFinder = useRowMatchFinder;
5809
0
    cdict->compressionLevel = ZSTD_NO_CLEVEL;
5810
5811
0
    if (ZSTD_isError( ZSTD_initCDict_internal(cdict,
5812
0
                                              dict, dictSize,
5813
0
                                              dictLoadMethod, dictContentType,
5814
0
                                              params) ))
5815
0
        return NULL;
5816
5817
0
    return cdict;
5818
0
}
5819
5820
ZSTD_compressionParameters ZSTD_getCParamsFromCDict(const ZSTD_CDict* cdict)
5821
0
{
5822
0
    assert(cdict != NULL);
5823
0
    return cdict->matchState.cParams;
5824
0
}
5825
5826
/*! ZSTD_getDictID_fromCDict() :
5827
 *  Provides the dictID of the dictionary loaded into `cdict`.
5828
 *  If @return == 0, the dictionary is not conformant to Zstandard specification, or empty.
5829
 *  Non-conformant dictionaries can still be loaded, but as content-only dictionaries. */
5830
unsigned ZSTD_getDictID_fromCDict(const ZSTD_CDict* cdict)
5831
0
{
5832
0
    if (cdict==NULL) return 0;
5833
0
    return cdict->dictID;
5834
0
}
5835
5836
/* ZSTD_compressBegin_usingCDict_internal() :
5837
 * Implementation of various ZSTD_compressBegin_usingCDict* functions.
5838
 */
5839
static size_t ZSTD_compressBegin_usingCDict_internal(
5840
    ZSTD_CCtx* const cctx, const ZSTD_CDict* const cdict,
5841
    ZSTD_frameParameters const fParams, unsigned long long const pledgedSrcSize)
5842
0
{
5843
0
    ZSTD_CCtx_params cctxParams;
5844
0
    DEBUGLOG(4, "ZSTD_compressBegin_usingCDict_internal");
5845
0
    RETURN_ERROR_IF(cdict==NULL, dictionary_wrong, "NULL pointer!");
5846
    /* Initialize the cctxParams from the cdict */
5847
0
    {
5848
0
        ZSTD_parameters params;
5849
0
        params.fParams = fParams;
5850
0
        params.cParams = ( pledgedSrcSize < ZSTD_USE_CDICT_PARAMS_SRCSIZE_CUTOFF
5851
0
                        || pledgedSrcSize < cdict->dictContentSize * ZSTD_USE_CDICT_PARAMS_DICTSIZE_MULTIPLIER
5852
0
                        || pledgedSrcSize == ZSTD_CONTENTSIZE_UNKNOWN
5853
0
                        || cdict->compressionLevel == 0 ) ?
5854
0
                ZSTD_getCParamsFromCDict(cdict)
5855
0
              : ZSTD_getCParams(cdict->compressionLevel,
5856
0
                                pledgedSrcSize,
5857
0
                                cdict->dictContentSize);
5858
0
        ZSTD_CCtxParams_init_internal(&cctxParams, &params, cdict->compressionLevel);
5859
0
    }
5860
    /* Increase window log to fit the entire dictionary and source if the
5861
     * source size is known. Limit the increase to 19, which is the
5862
     * window log for compression level 1 with the largest source size.
5863
     */
5864
0
    if (pledgedSrcSize != ZSTD_CONTENTSIZE_UNKNOWN) {
5865
0
        U32 const limitedSrcSize = (U32)MIN(pledgedSrcSize, 1U << 19);
5866
0
        U32 const limitedSrcLog = limitedSrcSize > 1 ? ZSTD_highbit32(limitedSrcSize - 1) + 1 : 1;
5867
0
        cctxParams.cParams.windowLog = MAX(cctxParams.cParams.windowLog, limitedSrcLog);
5868
0
    }
5869
0
    return ZSTD_compressBegin_internal(cctx,
5870
0
                                        NULL, 0, ZSTD_dct_auto, ZSTD_dtlm_fast,
5871
0
                                        cdict,
5872
0
                                        &cctxParams, pledgedSrcSize,
5873
0
                                        ZSTDb_not_buffered);
5874
0
}
5875
5876
5877
/* ZSTD_compressBegin_usingCDict_advanced() :
5878
 * This function is DEPRECATED.
5879
 * cdict must be != NULL */
5880
size_t ZSTD_compressBegin_usingCDict_advanced(
5881
    ZSTD_CCtx* const cctx, const ZSTD_CDict* const cdict,
5882
    ZSTD_frameParameters const fParams, unsigned long long const pledgedSrcSize)
5883
0
{
5884
0
    return ZSTD_compressBegin_usingCDict_internal(cctx, cdict, fParams, pledgedSrcSize);
5885
0
}
5886
5887
/* ZSTD_compressBegin_usingCDict() :
5888
 * cdict must be != NULL */
5889
size_t ZSTD_compressBegin_usingCDict_deprecated(ZSTD_CCtx* cctx, const ZSTD_CDict* cdict)
5890
0
{
5891
0
    ZSTD_frameParameters const fParams = { 0 /*content*/, 0 /*checksum*/, 0 /*noDictID*/ };
5892
0
    return ZSTD_compressBegin_usingCDict_internal(cctx, cdict, fParams, ZSTD_CONTENTSIZE_UNKNOWN);
5893
0
}
5894
5895
size_t ZSTD_compressBegin_usingCDict(ZSTD_CCtx* cctx, const ZSTD_CDict* cdict)
5896
0
{
5897
0
    return ZSTD_compressBegin_usingCDict_deprecated(cctx, cdict);
5898
0
}
5899
5900
/*! ZSTD_compress_usingCDict_internal():
5901
 * Implementation of various ZSTD_compress_usingCDict* functions.
5902
 */
5903
static size_t ZSTD_compress_usingCDict_internal(ZSTD_CCtx* cctx,
5904
                                void* dst, size_t dstCapacity,
5905
                                const void* src, size_t srcSize,
5906
                                const ZSTD_CDict* cdict, ZSTD_frameParameters fParams)
5907
0
{
5908
0
    FORWARD_IF_ERROR(ZSTD_compressBegin_usingCDict_internal(cctx, cdict, fParams, srcSize), ""); /* will check if cdict != NULL */
5909
0
    return ZSTD_compressEnd_public(cctx, dst, dstCapacity, src, srcSize);
5910
0
}
5911
5912
/*! ZSTD_compress_usingCDict_advanced():
5913
 * This function is DEPRECATED.
5914
 */
5915
size_t ZSTD_compress_usingCDict_advanced(ZSTD_CCtx* cctx,
5916
                                void* dst, size_t dstCapacity,
5917
                                const void* src, size_t srcSize,
5918
                                const ZSTD_CDict* cdict, ZSTD_frameParameters fParams)
5919
0
{
5920
0
    return ZSTD_compress_usingCDict_internal(cctx, dst, dstCapacity, src, srcSize, cdict, fParams);
5921
0
}
5922
5923
/*! ZSTD_compress_usingCDict() :
5924
 *  Compression using a digested Dictionary.
5925
 *  Faster startup than ZSTD_compress_usingDict(), recommended when same dictionary is used multiple times.
5926
 *  Note that compression parameters are decided at CDict creation time
5927
 *  while frame parameters are hardcoded */
5928
size_t ZSTD_compress_usingCDict(ZSTD_CCtx* cctx,
5929
                                void* dst, size_t dstCapacity,
5930
                                const void* src, size_t srcSize,
5931
                                const ZSTD_CDict* cdict)
5932
0
{
5933
0
    ZSTD_frameParameters const fParams = { 1 /*content*/, 0 /*checksum*/, 0 /*noDictID*/ };
5934
0
    return ZSTD_compress_usingCDict_internal(cctx, dst, dstCapacity, src, srcSize, cdict, fParams);
5935
0
}
5936
5937
5938
5939
/* ******************************************************************
5940
*  Streaming
5941
********************************************************************/
5942
5943
ZSTD_CStream* ZSTD_createCStream(void)
5944
6.05k
{
5945
6.05k
    DEBUGLOG(3, "ZSTD_createCStream");
5946
6.05k
    return ZSTD_createCStream_advanced(ZSTD_defaultCMem);
5947
6.05k
}
5948
5949
ZSTD_CStream* ZSTD_initStaticCStream(void *workspace, size_t workspaceSize)
5950
0
{
5951
0
    return ZSTD_initStaticCCtx(workspace, workspaceSize);
5952
0
}
5953
5954
ZSTD_CStream* ZSTD_createCStream_advanced(ZSTD_customMem customMem)
5955
6.05k
{   /* CStream and CCtx are now same object */
5956
6.05k
    return ZSTD_createCCtx_advanced(customMem);
5957
6.05k
}
5958
5959
size_t ZSTD_freeCStream(ZSTD_CStream* zcs)
5960
6.05k
{
5961
6.05k
    return ZSTD_freeCCtx(zcs);   /* same object */
5962
6.05k
}
5963
5964
5965
5966
/*======   Initialization   ======*/
5967
5968
0
size_t ZSTD_CStreamInSize(void)  { return ZSTD_BLOCKSIZE_MAX; }
5969
5970
size_t ZSTD_CStreamOutSize(void)
5971
0
{
5972
0
    return ZSTD_compressBound(ZSTD_BLOCKSIZE_MAX) + ZSTD_blockHeaderSize + 4 /* 32-bits hash */ ;
5973
0
}
5974
5975
static ZSTD_CParamMode_e ZSTD_getCParamMode(ZSTD_CDict const* cdict, ZSTD_CCtx_params const* params, U64 pledgedSrcSize)
5976
15.4k
{
5977
15.4k
    if (cdict != NULL && ZSTD_shouldAttachDict(cdict, params, pledgedSrcSize))
5978
0
        return ZSTD_cpm_attachDict;
5979
15.4k
    else
5980
15.4k
        return ZSTD_cpm_noAttachDict;
5981
15.4k
}
5982
5983
/* ZSTD_resetCStream():
5984
 * pledgedSrcSize == 0 means "unknown" */
5985
size_t ZSTD_resetCStream(ZSTD_CStream* zcs, unsigned long long pss)
5986
0
{
5987
    /* temporary : 0 interpreted as "unknown" during transition period.
5988
     * Users willing to specify "unknown" **must** use ZSTD_CONTENTSIZE_UNKNOWN.
5989
     * 0 will be interpreted as "empty" in the future.
5990
     */
5991
0
    U64 const pledgedSrcSize = (pss==0) ? ZSTD_CONTENTSIZE_UNKNOWN : pss;
5992
0
    DEBUGLOG(4, "ZSTD_resetCStream: pledgedSrcSize = %u", (unsigned)pledgedSrcSize);
5993
0
    FORWARD_IF_ERROR( ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only) , "");
5994
0
    FORWARD_IF_ERROR( ZSTD_CCtx_setPledgedSrcSize(zcs, pledgedSrcSize) , "");
5995
0
    return 0;
5996
0
}
5997
5998
/*! ZSTD_initCStream_internal() :
5999
 *  Note : for lib/compress only. Used by zstdmt_compress.c.
6000
 *  Assumption 1 : params are valid
6001
 *  Assumption 2 : either dict, or cdict, is defined, not both */
6002
size_t ZSTD_initCStream_internal(ZSTD_CStream* zcs,
6003
                    const void* dict, size_t dictSize, const ZSTD_CDict* cdict,
6004
                    const ZSTD_CCtx_params* params,
6005
                    unsigned long long pledgedSrcSize)
6006
0
{
6007
0
    DEBUGLOG(4, "ZSTD_initCStream_internal");
6008
0
    FORWARD_IF_ERROR( ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only) , "");
6009
0
    FORWARD_IF_ERROR( ZSTD_CCtx_setPledgedSrcSize(zcs, pledgedSrcSize) , "");
6010
0
    assert(!ZSTD_isError(ZSTD_checkCParams(params->cParams)));
6011
0
    zcs->requestedParams = *params;
6012
0
    assert(!((dict) && (cdict)));  /* either dict or cdict, not both */
6013
0
    if (dict) {
6014
0
        FORWARD_IF_ERROR( ZSTD_CCtx_loadDictionary(zcs, dict, dictSize) , "");
6015
0
    } else {
6016
        /* Dictionary is cleared if !cdict */
6017
0
        FORWARD_IF_ERROR( ZSTD_CCtx_refCDict(zcs, cdict) , "");
6018
0
    }
6019
0
    return 0;
6020
0
}
6021
6022
/* ZSTD_initCStream_usingCDict_advanced() :
6023
 * same as ZSTD_initCStream_usingCDict(), with control over frame parameters */
6024
size_t ZSTD_initCStream_usingCDict_advanced(ZSTD_CStream* zcs,
6025
                                            const ZSTD_CDict* cdict,
6026
                                            ZSTD_frameParameters fParams,
6027
                                            unsigned long long pledgedSrcSize)
6028
0
{
6029
0
    DEBUGLOG(4, "ZSTD_initCStream_usingCDict_advanced");
6030
0
    FORWARD_IF_ERROR( ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only) , "");
6031
0
    FORWARD_IF_ERROR( ZSTD_CCtx_setPledgedSrcSize(zcs, pledgedSrcSize) , "");
6032
0
    zcs->requestedParams.fParams = fParams;
6033
0
    FORWARD_IF_ERROR( ZSTD_CCtx_refCDict(zcs, cdict) , "");
6034
0
    return 0;
6035
0
}
6036
6037
/* note : cdict must outlive compression session */
6038
size_t ZSTD_initCStream_usingCDict(ZSTD_CStream* zcs, const ZSTD_CDict* cdict)
6039
0
{
6040
0
    DEBUGLOG(4, "ZSTD_initCStream_usingCDict");
6041
0
    FORWARD_IF_ERROR( ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only) , "");
6042
0
    FORWARD_IF_ERROR( ZSTD_CCtx_refCDict(zcs, cdict) , "");
6043
0
    return 0;
6044
0
}
6045
6046
6047
/* ZSTD_initCStream_advanced() :
6048
 * pledgedSrcSize must be exact.
6049
 * if srcSize is not known at init time, use value ZSTD_CONTENTSIZE_UNKNOWN.
6050
 * dict is loaded with default parameters ZSTD_dct_auto and ZSTD_dlm_byCopy. */
6051
size_t ZSTD_initCStream_advanced(ZSTD_CStream* zcs,
6052
                                 const void* dict, size_t dictSize,
6053
                                 ZSTD_parameters params, unsigned long long pss)
6054
0
{
6055
    /* for compatibility with older programs relying on this behavior.
6056
     * Users should now specify ZSTD_CONTENTSIZE_UNKNOWN.
6057
     * This line will be removed in the future.
6058
     */
6059
0
    U64 const pledgedSrcSize = (pss==0 && params.fParams.contentSizeFlag==0) ? ZSTD_CONTENTSIZE_UNKNOWN : pss;
6060
0
    DEBUGLOG(4, "ZSTD_initCStream_advanced");
6061
0
    FORWARD_IF_ERROR( ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only) , "");
6062
0
    FORWARD_IF_ERROR( ZSTD_CCtx_setPledgedSrcSize(zcs, pledgedSrcSize) , "");
6063
0
    FORWARD_IF_ERROR( ZSTD_checkCParams(params.cParams) , "");
6064
0
    ZSTD_CCtxParams_setZstdParams(&zcs->requestedParams, &params);
6065
0
    FORWARD_IF_ERROR( ZSTD_CCtx_loadDictionary(zcs, dict, dictSize) , "");
6066
0
    return 0;
6067
0
}
6068
6069
size_t ZSTD_initCStream_usingDict(ZSTD_CStream* zcs, const void* dict, size_t dictSize, int compressionLevel)
6070
0
{
6071
0
    DEBUGLOG(4, "ZSTD_initCStream_usingDict");
6072
0
    FORWARD_IF_ERROR( ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only) , "");
6073
0
    FORWARD_IF_ERROR( ZSTD_CCtx_setParameter(zcs, ZSTD_c_compressionLevel, compressionLevel) , "");
6074
0
    FORWARD_IF_ERROR( ZSTD_CCtx_loadDictionary(zcs, dict, dictSize) , "");
6075
0
    return 0;
6076
0
}
6077
6078
size_t ZSTD_initCStream_srcSize(ZSTD_CStream* zcs, int compressionLevel, unsigned long long pss)
6079
0
{
6080
    /* temporary : 0 interpreted as "unknown" during transition period.
6081
     * Users willing to specify "unknown" **must** use ZSTD_CONTENTSIZE_UNKNOWN.
6082
     * 0 will be interpreted as "empty" in the future.
6083
     */
6084
0
    U64 const pledgedSrcSize = (pss==0) ? ZSTD_CONTENTSIZE_UNKNOWN : pss;
6085
0
    DEBUGLOG(4, "ZSTD_initCStream_srcSize");
6086
0
    FORWARD_IF_ERROR( ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only) , "");
6087
0
    FORWARD_IF_ERROR( ZSTD_CCtx_refCDict(zcs, NULL) , "");
6088
0
    FORWARD_IF_ERROR( ZSTD_CCtx_setParameter(zcs, ZSTD_c_compressionLevel, compressionLevel) , "");
6089
0
    FORWARD_IF_ERROR( ZSTD_CCtx_setPledgedSrcSize(zcs, pledgedSrcSize) , "");
6090
0
    return 0;
6091
0
}
6092
6093
size_t ZSTD_initCStream(ZSTD_CStream* zcs, int compressionLevel)
6094
15.4k
{
6095
15.4k
    DEBUGLOG(4, "ZSTD_initCStream");
6096
15.4k
    FORWARD_IF_ERROR( ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only) , "");
6097
15.4k
    FORWARD_IF_ERROR( ZSTD_CCtx_refCDict(zcs, NULL) , "");
6098
15.4k
    FORWARD_IF_ERROR( ZSTD_CCtx_setParameter(zcs, ZSTD_c_compressionLevel, compressionLevel) , "");
6099
15.4k
    return 0;
6100
15.4k
}
6101
6102
/*======   Compression   ======*/
6103
6104
static size_t ZSTD_nextInputSizeHint(const ZSTD_CCtx* cctx)
6105
20.0M
{
6106
20.0M
    if (cctx->appliedParams.inBufferMode == ZSTD_bm_stable) {
6107
0
        return cctx->blockSizeMax - cctx->stableIn_notConsumed;
6108
0
    }
6109
20.0M
    assert(cctx->appliedParams.inBufferMode == ZSTD_bm_buffered);
6110
20.0M
    {   size_t hintInSize = cctx->inBuffTarget - cctx->inBuffPos;
6111
20.0M
        if (hintInSize==0) hintInSize = cctx->blockSizeMax;
6112
20.0M
        return hintInSize;
6113
20.0M
    }
6114
20.0M
}
6115
6116
/** ZSTD_compressStream_generic():
6117
 *  internal function for all *compressStream*() variants
6118
 * @return : hint size for next input to complete ongoing block */
6119
static size_t ZSTD_compressStream_generic(ZSTD_CStream* zcs,
6120
                                          ZSTD_outBuffer* output,
6121
                                          ZSTD_inBuffer* input,
6122
                                          ZSTD_EndDirective const flushMode)
6123
10.0M
{
6124
10.0M
    const char* const istart = (assert(input != NULL), (const char*)input->src);
6125
10.0M
    const char* const iend = (istart != NULL) ? istart + input->size : istart;
6126
10.0M
    const char* ip = (istart != NULL) ? istart + input->pos : istart;
6127
10.0M
    char* const ostart = (assert(output != NULL), (char*)output->dst);
6128
10.0M
    char* const oend = (ostart != NULL) ? ostart + output->size : ostart;
6129
10.0M
    char* op = (ostart != NULL) ? ostart + output->pos : ostart;
6130
10.0M
    U32 someMoreWork = 1;
6131
6132
    /* check expectations */
6133
10.0M
    DEBUGLOG(5, "ZSTD_compressStream_generic, flush=%i, srcSize = %zu", (int)flushMode, input->size - input->pos);
6134
10.0M
    assert(zcs != NULL);
6135
10.0M
    if (zcs->appliedParams.inBufferMode == ZSTD_bm_stable) {
6136
0
        assert(input->pos >= zcs->stableIn_notConsumed);
6137
0
        input->pos -= zcs->stableIn_notConsumed;
6138
0
        if (ip) ip -= zcs->stableIn_notConsumed;
6139
0
        zcs->stableIn_notConsumed = 0;
6140
0
    }
6141
10.0M
    if (zcs->appliedParams.inBufferMode == ZSTD_bm_buffered) {
6142
10.0M
        assert(zcs->inBuff != NULL);
6143
10.0M
        assert(zcs->inBuffSize > 0);
6144
10.0M
    }
6145
10.0M
    if (zcs->appliedParams.outBufferMode == ZSTD_bm_buffered) {
6146
10.0M
        assert(zcs->outBuff !=  NULL);
6147
10.0M
        assert(zcs->outBuffSize > 0);
6148
10.0M
    }
6149
10.0M
    if (input->src == NULL) assert(input->size == 0);
6150
10.0M
    assert(input->pos <= input->size);
6151
10.0M
    if (output->dst == NULL) assert(output->size == 0);
6152
10.0M
    assert(output->pos <= output->size);
6153
10.0M
    assert((U32)flushMode <= (U32)ZSTD_e_end);
6154
6155
20.1M
    while (someMoreWork) {
6156
10.0M
        switch(zcs->streamStage)
6157
10.0M
        {
6158
0
        case zcss_init:
6159
0
            RETURN_ERROR(init_missing, "call ZSTD_initCStream() first!");
6160
6161
10.0M
        case zcss_load:
6162
10.0M
            if ( (flushMode == ZSTD_e_end)
6163
10.0M
              && ( (size_t)(oend-op) >= ZSTD_compressBound((size_t)(iend-ip))     /* Enough output space */
6164
15.4k
                || zcs->appliedParams.outBufferMode == ZSTD_bm_stable)  /* OR we are allowed to return dstSizeTooSmall */
6165
10.0M
              && (zcs->inBuffPos == 0) ) {
6166
                /* shortcut to compression pass directly into output buffer */
6167
0
                size_t const cSize = ZSTD_compressEnd_public(zcs,
6168
0
                                                op, (size_t)(oend-op),
6169
0
                                                ip, (size_t)(iend-ip));
6170
0
                DEBUGLOG(4, "ZSTD_compressEnd : cSize=%u", (unsigned)cSize);
6171
0
                FORWARD_IF_ERROR(cSize, "ZSTD_compressEnd failed");
6172
0
                ip = iend;
6173
0
                op += cSize;
6174
0
                zcs->frameEnded = 1;
6175
0
                ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only);
6176
0
                someMoreWork = 0; break;
6177
0
            }
6178
            /* complete loading into inBuffer in buffered mode */
6179
10.0M
            if (zcs->appliedParams.inBufferMode == ZSTD_bm_buffered) {
6180
10.0M
                size_t const toLoad = zcs->inBuffTarget - zcs->inBuffPos;
6181
10.0M
                size_t const loaded = ZSTD_limitCopy(
6182
10.0M
                                        zcs->inBuff + zcs->inBuffPos, toLoad,
6183
10.0M
                                        ip, (size_t)(iend-ip));
6184
10.0M
                zcs->inBuffPos += loaded;
6185
10.0M
                if (ip) ip += loaded;
6186
10.0M
                if ( (flushMode == ZSTD_e_continue)
6187
10.0M
                  && (zcs->inBuffPos < zcs->inBuffTarget) ) {
6188
                    /* not enough input to fill full block : stop here */
6189
10.0M
                    someMoreWork = 0; break;
6190
10.0M
                }
6191
47.9k
                if ( (flushMode == ZSTD_e_flush)
6192
47.9k
                  && (zcs->inBuffPos == zcs->inToCompress) ) {
6193
                    /* empty */
6194
0
                    someMoreWork = 0; break;
6195
0
                }
6196
47.9k
            } else {
6197
0
                assert(zcs->appliedParams.inBufferMode == ZSTD_bm_stable);
6198
0
                if ( (flushMode == ZSTD_e_continue)
6199
0
                  && ( (size_t)(iend - ip) < zcs->blockSizeMax) ) {
6200
                    /* can't compress a full block : stop here */
6201
0
                    zcs->stableIn_notConsumed = (size_t)(iend - ip);
6202
0
                    ip = iend;  /* pretend to have consumed input */
6203
0
                    someMoreWork = 0; break;
6204
0
                }
6205
0
                if ( (flushMode == ZSTD_e_flush)
6206
0
                  && (ip == iend) ) {
6207
                    /* empty */
6208
0
                    someMoreWork = 0; break;
6209
0
                }
6210
0
            }
6211
            /* compress current block (note : this stage cannot be stopped in the middle) */
6212
47.9k
            DEBUGLOG(5, "stream compression stage (flushMode==%u)", flushMode);
6213
47.9k
            {   int const inputBuffered = (zcs->appliedParams.inBufferMode == ZSTD_bm_buffered);
6214
47.9k
                void* cDst;
6215
47.9k
                size_t cSize;
6216
47.9k
                size_t oSize = (size_t)(oend-op);
6217
47.9k
                size_t const iSize = inputBuffered ? zcs->inBuffPos - zcs->inToCompress
6218
47.9k
                                                   : MIN((size_t)(iend - ip), zcs->blockSizeMax);
6219
47.9k
                if (oSize >= ZSTD_compressBound(iSize) || zcs->appliedParams.outBufferMode == ZSTD_bm_stable)
6220
47.9k
                    cDst = op;   /* compress into output buffer, to skip flush stage */
6221
0
                else
6222
0
                    cDst = zcs->outBuff, oSize = zcs->outBuffSize;
6223
47.9k
                if (inputBuffered) {
6224
47.9k
                    unsigned const lastBlock = (flushMode == ZSTD_e_end) && (ip==iend);
6225
47.9k
                    cSize = lastBlock ?
6226
15.4k
                            ZSTD_compressEnd_public(zcs, cDst, oSize,
6227
15.4k
                                        zcs->inBuff + zcs->inToCompress, iSize) :
6228
47.9k
                            ZSTD_compressContinue_public(zcs, cDst, oSize,
6229
32.4k
                                        zcs->inBuff + zcs->inToCompress, iSize);
6230
47.9k
                    FORWARD_IF_ERROR(cSize, "%s", lastBlock ? "ZSTD_compressEnd failed" : "ZSTD_compressContinue failed");
6231
47.9k
                    zcs->frameEnded = lastBlock;
6232
                    /* prepare next block */
6233
47.9k
                    zcs->inBuffTarget = zcs->inBuffPos + zcs->blockSizeMax;
6234
47.9k
                    if (zcs->inBuffTarget > zcs->inBuffSize)
6235
0
                        zcs->inBuffPos = 0, zcs->inBuffTarget = zcs->blockSizeMax;
6236
47.9k
                    DEBUGLOG(5, "inBuffTarget:%u / inBuffSize:%u",
6237
47.9k
                            (unsigned)zcs->inBuffTarget, (unsigned)zcs->inBuffSize);
6238
47.9k
                    if (!lastBlock)
6239
32.4k
                        assert(zcs->inBuffTarget <= zcs->inBuffSize);
6240
47.9k
                    zcs->inToCompress = zcs->inBuffPos;
6241
47.9k
                } else { /* !inputBuffered, hence ZSTD_bm_stable */
6242
0
                    unsigned const lastBlock = (flushMode == ZSTD_e_end) && (ip + iSize == iend);
6243
0
                    cSize = lastBlock ?
6244
0
                            ZSTD_compressEnd_public(zcs, cDst, oSize, ip, iSize) :
6245
0
                            ZSTD_compressContinue_public(zcs, cDst, oSize, ip, iSize);
6246
                    /* Consume the input prior to error checking to mirror buffered mode. */
6247
0
                    if (ip) ip += iSize;
6248
0
                    FORWARD_IF_ERROR(cSize, "%s", lastBlock ? "ZSTD_compressEnd failed" : "ZSTD_compressContinue failed");
6249
0
                    zcs->frameEnded = lastBlock;
6250
0
                    if (lastBlock) assert(ip == iend);
6251
0
                }
6252
47.9k
                if (cDst == op) {  /* no need to flush */
6253
47.9k
                    op += cSize;
6254
47.9k
                    if (zcs->frameEnded) {
6255
15.4k
                        DEBUGLOG(5, "Frame completed directly in outBuffer");
6256
15.4k
                        someMoreWork = 0;
6257
15.4k
                        ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only);
6258
15.4k
                    }
6259
47.9k
                    break;
6260
47.9k
                }
6261
0
                zcs->outBuffContentSize = cSize;
6262
0
                zcs->outBuffFlushedSize = 0;
6263
0
                zcs->streamStage = zcss_flush; /* pass-through to flush stage */
6264
0
            }
6265
0
      ZSTD_FALLTHROUGH;
6266
0
        case zcss_flush:
6267
0
            DEBUGLOG(5, "flush stage");
6268
0
            assert(zcs->appliedParams.outBufferMode == ZSTD_bm_buffered);
6269
0
            {   size_t const toFlush = zcs->outBuffContentSize - zcs->outBuffFlushedSize;
6270
0
                size_t const flushed = ZSTD_limitCopy(op, (size_t)(oend-op),
6271
0
                            zcs->outBuff + zcs->outBuffFlushedSize, toFlush);
6272
0
                DEBUGLOG(5, "toFlush: %u into %u ==> flushed: %u",
6273
0
                            (unsigned)toFlush, (unsigned)(oend-op), (unsigned)flushed);
6274
0
                if (flushed)
6275
0
                    op += flushed;
6276
0
                zcs->outBuffFlushedSize += flushed;
6277
0
                if (toFlush!=flushed) {
6278
                    /* flush not fully completed, presumably because dst is too small */
6279
0
                    assert(op==oend);
6280
0
                    someMoreWork = 0;
6281
0
                    break;
6282
0
                }
6283
0
                zcs->outBuffContentSize = zcs->outBuffFlushedSize = 0;
6284
0
                if (zcs->frameEnded) {
6285
0
                    DEBUGLOG(5, "Frame completed on flush");
6286
0
                    someMoreWork = 0;
6287
0
                    ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only);
6288
0
                    break;
6289
0
                }
6290
0
                zcs->streamStage = zcss_load;
6291
0
                break;
6292
0
            }
6293
6294
0
        default: /* impossible */
6295
0
            assert(0);
6296
10.0M
        }
6297
10.0M
    }
6298
6299
10.0M
    input->pos = (size_t)(ip - istart);
6300
10.0M
    output->pos = (size_t)(op - ostart);
6301
10.0M
    if (zcs->frameEnded) return 0;
6302
10.0M
    return ZSTD_nextInputSizeHint(zcs);
6303
10.0M
}
6304
6305
static size_t ZSTD_nextInputSizeHint_MTorST(const ZSTD_CCtx* cctx)
6306
10.0M
{
6307
10.0M
#ifdef ZSTD_MULTITHREAD
6308
10.0M
    if (cctx->appliedParams.nbWorkers >= 1) {
6309
0
        assert(cctx->mtctx != NULL);
6310
0
        return ZSTDMT_nextInputSizeHint(cctx->mtctx);
6311
0
    }
6312
10.0M
#endif
6313
10.0M
    return ZSTD_nextInputSizeHint(cctx);
6314
6315
10.0M
}
6316
6317
size_t ZSTD_compressStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output, ZSTD_inBuffer* input)
6318
10.0M
{
6319
10.0M
    FORWARD_IF_ERROR( ZSTD_compressStream2(zcs, output, input, ZSTD_e_continue) , "");
6320
10.0M
    return ZSTD_nextInputSizeHint_MTorST(zcs);
6321
10.0M
}
6322
6323
/* After a compression call set the expected input/output buffer.
6324
 * This is validated at the start of the next compression call.
6325
 */
6326
static void
6327
ZSTD_setBufferExpectations(ZSTD_CCtx* cctx, const ZSTD_outBuffer* output, const ZSTD_inBuffer* input)
6328
10.0M
{
6329
10.0M
    DEBUGLOG(5, "ZSTD_setBufferExpectations (for advanced stable in/out modes)");
6330
10.0M
    if (cctx->appliedParams.inBufferMode == ZSTD_bm_stable) {
6331
0
        cctx->expectedInBuffer = *input;
6332
0
    }
6333
10.0M
    if (cctx->appliedParams.outBufferMode == ZSTD_bm_stable) {
6334
0
        cctx->expectedOutBufferSize = output->size - output->pos;
6335
0
    }
6336
10.0M
}
6337
6338
/* Validate that the input/output buffers match the expectations set by
6339
 * ZSTD_setBufferExpectations.
6340
 */
6341
static size_t ZSTD_checkBufferStability(ZSTD_CCtx const* cctx,
6342
                                        ZSTD_outBuffer const* output,
6343
                                        ZSTD_inBuffer const* input,
6344
                                        ZSTD_EndDirective endOp)
6345
10.0M
{
6346
10.0M
    if (cctx->appliedParams.inBufferMode == ZSTD_bm_stable) {
6347
0
        ZSTD_inBuffer const expect = cctx->expectedInBuffer;
6348
0
        if (expect.src != input->src || expect.pos != input->pos)
6349
0
            RETURN_ERROR(stabilityCondition_notRespected, "ZSTD_c_stableInBuffer enabled but input differs!");
6350
0
    }
6351
10.0M
    (void)endOp;
6352
10.0M
    if (cctx->appliedParams.outBufferMode == ZSTD_bm_stable) {
6353
0
        size_t const outBufferSize = output->size - output->pos;
6354
0
        if (cctx->expectedOutBufferSize != outBufferSize)
6355
0
            RETURN_ERROR(stabilityCondition_notRespected, "ZSTD_c_stableOutBuffer enabled but output size differs!");
6356
0
    }
6357
10.0M
    return 0;
6358
10.0M
}
6359
6360
/*
6361
 * If @endOp == ZSTD_e_end, @inSize becomes pledgedSrcSize.
6362
 * Otherwise, it's ignored.
6363
 * @return: 0 on success, or a ZSTD_error code otherwise.
6364
 */
6365
static size_t ZSTD_CCtx_init_compressStream2(ZSTD_CCtx* cctx,
6366
                                             ZSTD_EndDirective endOp,
6367
                                             size_t inSize)
6368
15.4k
{
6369
15.4k
    ZSTD_CCtx_params params = cctx->requestedParams;
6370
15.4k
    ZSTD_prefixDict const prefixDict = cctx->prefixDict;
6371
15.4k
    FORWARD_IF_ERROR( ZSTD_initLocalDict(cctx) , ""); /* Init the local dict if present. */
6372
15.4k
    ZSTD_memset(&cctx->prefixDict, 0, sizeof(cctx->prefixDict));   /* single usage */
6373
15.4k
    assert(prefixDict.dict==NULL || cctx->cdict==NULL);    /* only one can be set */
6374
15.4k
    if (cctx->cdict && !cctx->localDict.cdict) {
6375
        /* Let the cdict's compression level take priority over the requested params.
6376
         * But do not take the cdict's compression level if the "cdict" is actually a localDict
6377
         * generated from ZSTD_initLocalDict().
6378
         */
6379
0
        params.compressionLevel = cctx->cdict->compressionLevel;
6380
0
    }
6381
15.4k
    DEBUGLOG(4, "ZSTD_CCtx_init_compressStream2 : transparent init stage");
6382
15.4k
    if (endOp == ZSTD_e_end) cctx->pledgedSrcSizePlusOne = inSize + 1;  /* auto-determine pledgedSrcSize */
6383
6384
15.4k
    {   size_t const dictSize = prefixDict.dict
6385
15.4k
                ? prefixDict.dictSize
6386
15.4k
                : (cctx->cdict ? cctx->cdict->dictContentSize : 0);
6387
15.4k
        ZSTD_CParamMode_e const mode = ZSTD_getCParamMode(cctx->cdict, &params, cctx->pledgedSrcSizePlusOne - 1);
6388
15.4k
        params.cParams = ZSTD_getCParamsFromCCtxParams(
6389
15.4k
                &params, cctx->pledgedSrcSizePlusOne-1,
6390
15.4k
                dictSize, mode);
6391
15.4k
    }
6392
6393
15.4k
    params.postBlockSplitter = ZSTD_resolveBlockSplitterMode(params.postBlockSplitter, &params.cParams);
6394
15.4k
    params.ldmParams.enableLdm = ZSTD_resolveEnableLdm(params.ldmParams.enableLdm, &params.cParams);
6395
15.4k
    params.useRowMatchFinder = ZSTD_resolveRowMatchFinderMode(params.useRowMatchFinder, &params.cParams);
6396
15.4k
    params.validateSequences = ZSTD_resolveExternalSequenceValidation(params.validateSequences);
6397
15.4k
    params.maxBlockSize = ZSTD_resolveMaxBlockSize(params.maxBlockSize);
6398
15.4k
    params.searchForExternalRepcodes = ZSTD_resolveExternalRepcodeSearch(params.searchForExternalRepcodes, params.compressionLevel);
6399
6400
15.4k
#ifdef ZSTD_MULTITHREAD
6401
    /* If external matchfinder is enabled, make sure to fail before checking job size (for consistency) */
6402
15.4k
    RETURN_ERROR_IF(
6403
15.4k
        ZSTD_hasExtSeqProd(&params) && params.nbWorkers >= 1,
6404
15.4k
        parameter_combination_unsupported,
6405
15.4k
        "External sequence producer isn't supported with nbWorkers >= 1"
6406
15.4k
    );
6407
6408
15.4k
    if ((cctx->pledgedSrcSizePlusOne-1) <= ZSTDMT_JOBSIZE_MIN) {
6409
0
        params.nbWorkers = 0; /* do not invoke multi-threading when src size is too small */
6410
0
    }
6411
15.4k
    if (params.nbWorkers > 0) {
6412
0
# if ZSTD_TRACE
6413
0
        cctx->traceCtx = (ZSTD_trace_compress_begin != NULL) ? ZSTD_trace_compress_begin(cctx) : 0;
6414
0
# endif
6415
        /* mt context creation */
6416
0
        if (cctx->mtctx == NULL) {
6417
0
            DEBUGLOG(4, "ZSTD_compressStream2: creating new mtctx for nbWorkers=%u",
6418
0
                        params.nbWorkers);
6419
0
            cctx->mtctx = ZSTDMT_createCCtx_advanced((U32)params.nbWorkers, cctx->customMem, cctx->pool);
6420
0
            RETURN_ERROR_IF(cctx->mtctx == NULL, memory_allocation, "NULL pointer!");
6421
0
        }
6422
        /* mt compression */
6423
0
        DEBUGLOG(4, "call ZSTDMT_initCStream_internal as nbWorkers=%u", params.nbWorkers);
6424
0
        FORWARD_IF_ERROR( ZSTDMT_initCStream_internal(
6425
0
                    cctx->mtctx,
6426
0
                    prefixDict.dict, prefixDict.dictSize, prefixDict.dictContentType,
6427
0
                    cctx->cdict, params, cctx->pledgedSrcSizePlusOne-1) , "");
6428
0
        cctx->dictID = cctx->cdict ? cctx->cdict->dictID : 0;
6429
0
        cctx->dictContentSize = cctx->cdict ? cctx->cdict->dictContentSize : prefixDict.dictSize;
6430
0
        cctx->consumedSrcSize = 0;
6431
0
        cctx->producedCSize = 0;
6432
0
        cctx->streamStage = zcss_load;
6433
0
        cctx->appliedParams = params;
6434
0
    } else
6435
15.4k
#endif  /* ZSTD_MULTITHREAD */
6436
15.4k
    {   U64 const pledgedSrcSize = cctx->pledgedSrcSizePlusOne - 1;
6437
15.4k
        assert(!ZSTD_isError(ZSTD_checkCParams(params.cParams)));
6438
15.4k
        FORWARD_IF_ERROR( ZSTD_compressBegin_internal(cctx,
6439
15.4k
                prefixDict.dict, prefixDict.dictSize, prefixDict.dictContentType, ZSTD_dtlm_fast,
6440
15.4k
                cctx->cdict,
6441
15.4k
                &params, pledgedSrcSize,
6442
15.4k
                ZSTDb_buffered) , "");
6443
15.4k
        assert(cctx->appliedParams.nbWorkers == 0);
6444
15.4k
        cctx->inToCompress = 0;
6445
15.4k
        cctx->inBuffPos = 0;
6446
15.4k
        if (cctx->appliedParams.inBufferMode == ZSTD_bm_buffered) {
6447
            /* for small input: avoid automatic flush on reaching end of block, since
6448
            * it would require to add a 3-bytes null block to end frame
6449
            */
6450
15.4k
            cctx->inBuffTarget = cctx->blockSizeMax + (cctx->blockSizeMax == pledgedSrcSize);
6451
15.4k
        } else {
6452
0
            cctx->inBuffTarget = 0;
6453
0
        }
6454
15.4k
        cctx->outBuffContentSize = cctx->outBuffFlushedSize = 0;
6455
15.4k
        cctx->streamStage = zcss_load;
6456
15.4k
        cctx->frameEnded = 0;
6457
15.4k
    }
6458
15.4k
    return 0;
6459
15.4k
}
6460
6461
/* @return provides a minimum amount of data remaining to be flushed from internal buffers
6462
 */
6463
size_t ZSTD_compressStream2( ZSTD_CCtx* cctx,
6464
                             ZSTD_outBuffer* output,
6465
                             ZSTD_inBuffer* input,
6466
                             ZSTD_EndDirective endOp)
6467
10.0M
{
6468
10.0M
    DEBUGLOG(5, "ZSTD_compressStream2, endOp=%u ", (unsigned)endOp);
6469
    /* check conditions */
6470
10.0M
    RETURN_ERROR_IF(output->pos > output->size, dstSize_tooSmall, "invalid output buffer");
6471
10.0M
    RETURN_ERROR_IF(input->pos  > input->size, srcSize_wrong, "invalid input buffer");
6472
10.0M
    RETURN_ERROR_IF((U32)endOp > (U32)ZSTD_e_end, parameter_outOfBound, "invalid endDirective");
6473
10.0M
    assert(cctx != NULL);
6474
6475
    /* transparent initialization stage */
6476
10.0M
    if (cctx->streamStage == zcss_init) {
6477
15.4k
        size_t const inputSize = input->size - input->pos;  /* no obligation to start from pos==0 */
6478
15.4k
        size_t const totalInputSize = inputSize + cctx->stableIn_notConsumed;
6479
15.4k
        if ( (cctx->requestedParams.inBufferMode == ZSTD_bm_stable) /* input is presumed stable, across invocations */
6480
15.4k
          && (endOp == ZSTD_e_continue)                             /* no flush requested, more input to come */
6481
15.4k
          && (totalInputSize < ZSTD_BLOCKSIZE_MAX) ) {              /* not even reached one block yet */
6482
0
            if (cctx->stableIn_notConsumed) {  /* not the first time */
6483
                /* check stable source guarantees */
6484
0
                RETURN_ERROR_IF(input->src != cctx->expectedInBuffer.src, stabilityCondition_notRespected, "stableInBuffer condition not respected: wrong src pointer");
6485
0
                RETURN_ERROR_IF(input->pos != cctx->expectedInBuffer.size, stabilityCondition_notRespected, "stableInBuffer condition not respected: externally modified pos");
6486
0
            }
6487
            /* pretend input was consumed, to give a sense forward progress */
6488
0
            input->pos = input->size;
6489
            /* save stable inBuffer, for later control, and flush/end */
6490
0
            cctx->expectedInBuffer = *input;
6491
            /* but actually input wasn't consumed, so keep track of position from where compression shall resume */
6492
0
            cctx->stableIn_notConsumed += inputSize;
6493
            /* don't initialize yet, wait for the first block of flush() order, for better parameters adaptation */
6494
0
            return ZSTD_FRAMEHEADERSIZE_MIN(cctx->requestedParams.format);  /* at least some header to produce */
6495
0
        }
6496
15.4k
        FORWARD_IF_ERROR(ZSTD_CCtx_init_compressStream2(cctx, endOp, totalInputSize), "compressStream2 initialization failed");
6497
15.4k
        ZSTD_setBufferExpectations(cctx, output, input);   /* Set initial buffer expectations now that we've initialized */
6498
15.4k
    }
6499
    /* end of transparent initialization stage */
6500
6501
10.0M
    FORWARD_IF_ERROR(ZSTD_checkBufferStability(cctx, output, input, endOp), "invalid buffers");
6502
    /* compression stage */
6503
10.0M
#ifdef ZSTD_MULTITHREAD
6504
10.0M
    if (cctx->appliedParams.nbWorkers > 0) {
6505
0
        size_t flushMin;
6506
0
        if (cctx->cParamsChanged) {
6507
0
            ZSTDMT_updateCParams_whileCompressing(cctx->mtctx, &cctx->requestedParams);
6508
0
            cctx->cParamsChanged = 0;
6509
0
        }
6510
0
        if (cctx->stableIn_notConsumed) {
6511
0
            assert(cctx->appliedParams.inBufferMode == ZSTD_bm_stable);
6512
            /* some early data was skipped - make it available for consumption */
6513
0
            assert(input->pos >= cctx->stableIn_notConsumed);
6514
0
            input->pos -= cctx->stableIn_notConsumed;
6515
0
            cctx->stableIn_notConsumed = 0;
6516
0
        }
6517
0
        for (;;) {
6518
0
            size_t const ipos = input->pos;
6519
0
            size_t const opos = output->pos;
6520
0
            flushMin = ZSTDMT_compressStream_generic(cctx->mtctx, output, input, endOp);
6521
0
            cctx->consumedSrcSize += (U64)(input->pos - ipos);
6522
0
            cctx->producedCSize += (U64)(output->pos - opos);
6523
0
            if ( ZSTD_isError(flushMin)
6524
0
              || (endOp == ZSTD_e_end && flushMin == 0) ) { /* compression completed */
6525
0
                if (flushMin == 0)
6526
0
                    ZSTD_CCtx_trace(cctx, 0);
6527
0
                ZSTD_CCtx_reset(cctx, ZSTD_reset_session_only);
6528
0
            }
6529
0
            FORWARD_IF_ERROR(flushMin, "ZSTDMT_compressStream_generic failed");
6530
6531
0
            if (endOp == ZSTD_e_continue) {
6532
                /* We only require some progress with ZSTD_e_continue, not maximal progress.
6533
                 * We're done if we've consumed or produced any bytes, or either buffer is
6534
                 * full.
6535
                 */
6536
0
                if (input->pos != ipos || output->pos != opos || input->pos == input->size || output->pos == output->size)
6537
0
                    break;
6538
0
            } else {
6539
0
                assert(endOp == ZSTD_e_flush || endOp == ZSTD_e_end);
6540
                /* We require maximal progress. We're done when the flush is complete or the
6541
                 * output buffer is full.
6542
                 */
6543
0
                if (flushMin == 0 || output->pos == output->size)
6544
0
                    break;
6545
0
            }
6546
0
        }
6547
0
        DEBUGLOG(5, "completed ZSTD_compressStream2 delegating to ZSTDMT_compressStream_generic");
6548
        /* Either we don't require maximum forward progress, we've finished the
6549
         * flush, or we are out of output space.
6550
         */
6551
0
        assert(endOp == ZSTD_e_continue || flushMin == 0 || output->pos == output->size);
6552
0
        ZSTD_setBufferExpectations(cctx, output, input);
6553
0
        return flushMin;
6554
0
    }
6555
10.0M
#endif /* ZSTD_MULTITHREAD */
6556
10.0M
    FORWARD_IF_ERROR( ZSTD_compressStream_generic(cctx, output, input, endOp) , "");
6557
10.0M
    DEBUGLOG(5, "completed ZSTD_compressStream2");
6558
10.0M
    ZSTD_setBufferExpectations(cctx, output, input);
6559
10.0M
    return cctx->outBuffContentSize - cctx->outBuffFlushedSize; /* remaining to flush */
6560
10.0M
}
6561
6562
size_t ZSTD_compressStream2_simpleArgs (
6563
                            ZSTD_CCtx* cctx,
6564
                            void* dst, size_t dstCapacity, size_t* dstPos,
6565
                      const void* src, size_t srcSize, size_t* srcPos,
6566
                            ZSTD_EndDirective endOp)
6567
0
{
6568
0
    ZSTD_outBuffer output;
6569
0
    ZSTD_inBuffer  input;
6570
0
    output.dst = dst;
6571
0
    output.size = dstCapacity;
6572
0
    output.pos = *dstPos;
6573
0
    input.src = src;
6574
0
    input.size = srcSize;
6575
0
    input.pos = *srcPos;
6576
    /* ZSTD_compressStream2() will check validity of dstPos and srcPos */
6577
0
    {   size_t const cErr = ZSTD_compressStream2(cctx, &output, &input, endOp);
6578
0
        *dstPos = output.pos;
6579
0
        *srcPos = input.pos;
6580
0
        return cErr;
6581
0
    }
6582
0
}
6583
6584
size_t ZSTD_compress2(ZSTD_CCtx* cctx,
6585
                      void* dst, size_t dstCapacity,
6586
                      const void* src, size_t srcSize)
6587
0
{
6588
0
    ZSTD_bufferMode_e const originalInBufferMode = cctx->requestedParams.inBufferMode;
6589
0
    ZSTD_bufferMode_e const originalOutBufferMode = cctx->requestedParams.outBufferMode;
6590
0
    DEBUGLOG(4, "ZSTD_compress2 (srcSize=%u)", (unsigned)srcSize);
6591
0
    ZSTD_CCtx_reset(cctx, ZSTD_reset_session_only);
6592
    /* Enable stable input/output buffers. */
6593
0
    cctx->requestedParams.inBufferMode = ZSTD_bm_stable;
6594
0
    cctx->requestedParams.outBufferMode = ZSTD_bm_stable;
6595
0
    {   size_t oPos = 0;
6596
0
        size_t iPos = 0;
6597
0
        size_t const result = ZSTD_compressStream2_simpleArgs(cctx,
6598
0
                                        dst, dstCapacity, &oPos,
6599
0
                                        src, srcSize, &iPos,
6600
0
                                        ZSTD_e_end);
6601
        /* Reset to the original values. */
6602
0
        cctx->requestedParams.inBufferMode = originalInBufferMode;
6603
0
        cctx->requestedParams.outBufferMode = originalOutBufferMode;
6604
6605
0
        FORWARD_IF_ERROR(result, "ZSTD_compressStream2_simpleArgs failed");
6606
0
        if (result != 0) {  /* compression not completed, due to lack of output space */
6607
0
            assert(oPos == dstCapacity);
6608
0
            RETURN_ERROR(dstSize_tooSmall, "");
6609
0
        }
6610
0
        assert(iPos == srcSize);   /* all input is expected consumed */
6611
0
        return oPos;
6612
0
    }
6613
0
}
6614
6615
/* ZSTD_validateSequence() :
6616
 * @offBase : must use the format required by ZSTD_storeSeq()
6617
 * @returns a ZSTD error code if sequence is not valid
6618
 */
6619
static size_t
6620
ZSTD_validateSequence(U32 offBase, U32 matchLength, U32 minMatch,
6621
                      size_t posInSrc, U32 windowLog, size_t dictSize, int useSequenceProducer)
6622
0
{
6623
0
    U32 const windowSize = 1u << windowLog;
6624
    /* posInSrc represents the amount of data the decoder would decode up to this point.
6625
     * As long as the amount of data decoded is less than or equal to window size, offsets may be
6626
     * larger than the total length of output decoded in order to reference the dict, even larger than
6627
     * window size. After output surpasses windowSize, we're limited to windowSize offsets again.
6628
     */
6629
0
    size_t const offsetBound = posInSrc > windowSize ? (size_t)windowSize : posInSrc + (size_t)dictSize;
6630
0
    size_t const matchLenLowerBound = (minMatch == 3 || useSequenceProducer) ? 3 : 4;
6631
0
    RETURN_ERROR_IF(offBase > OFFSET_TO_OFFBASE(offsetBound), externalSequences_invalid, "Offset too large!");
6632
    /* Validate maxNbSeq is large enough for the given matchLength and minMatch */
6633
0
    RETURN_ERROR_IF(matchLength < matchLenLowerBound, externalSequences_invalid, "Matchlength too small for the minMatch");
6634
0
    return 0;
6635
0
}
6636
6637
/* Returns an offset code, given a sequence's raw offset, the ongoing repcode array, and whether litLength == 0 */
6638
static U32 ZSTD_finalizeOffBase(U32 rawOffset, const U32 rep[ZSTD_REP_NUM], U32 ll0)
6639
0
{
6640
0
    U32 offBase = OFFSET_TO_OFFBASE(rawOffset);
6641
6642
0
    if (!ll0 && rawOffset == rep[0]) {
6643
0
        offBase = REPCODE1_TO_OFFBASE;
6644
0
    } else if (rawOffset == rep[1]) {
6645
0
        offBase = REPCODE_TO_OFFBASE(2 - ll0);
6646
0
    } else if (rawOffset == rep[2]) {
6647
0
        offBase = REPCODE_TO_OFFBASE(3 - ll0);
6648
0
    } else if (ll0 && rawOffset == rep[0] - 1) {
6649
0
        offBase = REPCODE3_TO_OFFBASE;
6650
0
    }
6651
0
    return offBase;
6652
0
}
6653
6654
/* This function scans through an array of ZSTD_Sequence,
6655
 * storing the sequences it reads, until it reaches a block delimiter.
6656
 * Note that the block delimiter includes the last literals of the block.
6657
 * @blockSize must be == sum(sequence_lengths).
6658
 * @returns @blockSize on success, and a ZSTD_error otherwise.
6659
 */
6660
static size_t
6661
ZSTD_transferSequences_wBlockDelim(ZSTD_CCtx* cctx,
6662
                                   ZSTD_SequencePosition* seqPos,
6663
                             const ZSTD_Sequence* const inSeqs, size_t inSeqsSize,
6664
                             const void* src, size_t blockSize,
6665
                                   ZSTD_ParamSwitch_e externalRepSearch)
6666
0
{
6667
0
    U32 idx = seqPos->idx;
6668
0
    U32 const startIdx = idx;
6669
0
    BYTE const* ip = (BYTE const*)(src);
6670
0
    const BYTE* const iend = ip + blockSize;
6671
0
    Repcodes_t updatedRepcodes;
6672
0
    U32 dictSize;
6673
6674
0
    DEBUGLOG(5, "ZSTD_transferSequences_wBlockDelim (blockSize = %zu)", blockSize);
6675
6676
0
    if (cctx->cdict) {
6677
0
        dictSize = (U32)cctx->cdict->dictContentSize;
6678
0
    } else if (cctx->prefixDict.dict) {
6679
0
        dictSize = (U32)cctx->prefixDict.dictSize;
6680
0
    } else {
6681
0
        dictSize = 0;
6682
0
    }
6683
0
    ZSTD_memcpy(updatedRepcodes.rep, cctx->blockState.prevCBlock->rep, sizeof(Repcodes_t));
6684
0
    for (; idx < inSeqsSize && (inSeqs[idx].matchLength != 0 || inSeqs[idx].offset != 0); ++idx) {
6685
0
        U32 const litLength = inSeqs[idx].litLength;
6686
0
        U32 const matchLength = inSeqs[idx].matchLength;
6687
0
        U32 offBase;
6688
6689
0
        if (externalRepSearch == ZSTD_ps_disable) {
6690
0
            offBase = OFFSET_TO_OFFBASE(inSeqs[idx].offset);
6691
0
        } else {
6692
0
            U32 const ll0 = (litLength == 0);
6693
0
            offBase = ZSTD_finalizeOffBase(inSeqs[idx].offset, updatedRepcodes.rep, ll0);
6694
0
            ZSTD_updateRep(updatedRepcodes.rep, offBase, ll0);
6695
0
        }
6696
6697
0
        DEBUGLOG(6, "Storing sequence: (of: %u, ml: %u, ll: %u)", offBase, matchLength, litLength);
6698
0
        if (cctx->appliedParams.validateSequences) {
6699
0
            seqPos->posInSrc += litLength + matchLength;
6700
0
            FORWARD_IF_ERROR(ZSTD_validateSequence(offBase, matchLength, cctx->appliedParams.cParams.minMatch,
6701
0
                                                seqPos->posInSrc,
6702
0
                                                cctx->appliedParams.cParams.windowLog, dictSize,
6703
0
                                                ZSTD_hasExtSeqProd(&cctx->appliedParams)),
6704
0
                                                "Sequence validation failed");
6705
0
        }
6706
0
        RETURN_ERROR_IF(idx - seqPos->idx >= cctx->seqStore.maxNbSeq, externalSequences_invalid,
6707
0
                        "Not enough memory allocated. Try adjusting ZSTD_c_minMatch.");
6708
0
        ZSTD_storeSeq(&cctx->seqStore, litLength, ip, iend, offBase, matchLength);
6709
0
        ip += matchLength + litLength;
6710
0
    }
6711
0
    RETURN_ERROR_IF(idx == inSeqsSize, externalSequences_invalid, "Block delimiter not found.");
6712
6713
    /* If we skipped repcode search while parsing, we need to update repcodes now */
6714
0
    assert(externalRepSearch != ZSTD_ps_auto);
6715
0
    assert(idx >= startIdx);
6716
0
    if (externalRepSearch == ZSTD_ps_disable && idx != startIdx) {
6717
0
        U32* const rep = updatedRepcodes.rep;
6718
0
        U32 lastSeqIdx = idx - 1; /* index of last non-block-delimiter sequence */
6719
6720
0
        if (lastSeqIdx >= startIdx + 2) {
6721
0
            rep[2] = inSeqs[lastSeqIdx - 2].offset;
6722
0
            rep[1] = inSeqs[lastSeqIdx - 1].offset;
6723
0
            rep[0] = inSeqs[lastSeqIdx].offset;
6724
0
        } else if (lastSeqIdx == startIdx + 1) {
6725
0
            rep[2] = rep[0];
6726
0
            rep[1] = inSeqs[lastSeqIdx - 1].offset;
6727
0
            rep[0] = inSeqs[lastSeqIdx].offset;
6728
0
        } else {
6729
0
            assert(lastSeqIdx == startIdx);
6730
0
            rep[2] = rep[1];
6731
0
            rep[1] = rep[0];
6732
0
            rep[0] = inSeqs[lastSeqIdx].offset;
6733
0
        }
6734
0
    }
6735
6736
0
    ZSTD_memcpy(cctx->blockState.nextCBlock->rep, updatedRepcodes.rep, sizeof(Repcodes_t));
6737
6738
0
    if (inSeqs[idx].litLength) {
6739
0
        DEBUGLOG(6, "Storing last literals of size: %u", inSeqs[idx].litLength);
6740
0
        ZSTD_storeLastLiterals(&cctx->seqStore, ip, inSeqs[idx].litLength);
6741
0
        ip += inSeqs[idx].litLength;
6742
0
        seqPos->posInSrc += inSeqs[idx].litLength;
6743
0
    }
6744
0
    RETURN_ERROR_IF(ip != iend, externalSequences_invalid, "Blocksize doesn't agree with block delimiter!");
6745
0
    seqPos->idx = idx+1;
6746
0
    return blockSize;
6747
0
}
6748
6749
/*
6750
 * This function attempts to scan through @blockSize bytes in @src
6751
 * represented by the sequences in @inSeqs,
6752
 * storing any (partial) sequences.
6753
 *
6754
 * Occasionally, we may want to reduce the actual number of bytes consumed from @src
6755
 * to avoid splitting a match, notably if it would produce a match smaller than MINMATCH.
6756
 *
6757
 * @returns the number of bytes consumed from @src, necessarily <= @blockSize.
6758
 * Otherwise, it may return a ZSTD error if something went wrong.
6759
 */
6760
static size_t
6761
ZSTD_transferSequences_noDelim(ZSTD_CCtx* cctx,
6762
                               ZSTD_SequencePosition* seqPos,
6763
                         const ZSTD_Sequence* const inSeqs, size_t inSeqsSize,
6764
                         const void* src, size_t blockSize,
6765
                               ZSTD_ParamSwitch_e externalRepSearch)
6766
0
{
6767
0
    U32 idx = seqPos->idx;
6768
0
    U32 startPosInSequence = seqPos->posInSequence;
6769
0
    U32 endPosInSequence = seqPos->posInSequence + (U32)blockSize;
6770
0
    size_t dictSize;
6771
0
    const BYTE* const istart = (const BYTE*)(src);
6772
0
    const BYTE* ip = istart;
6773
0
    const BYTE* iend = istart + blockSize;  /* May be adjusted if we decide to process fewer than blockSize bytes */
6774
0
    Repcodes_t updatedRepcodes;
6775
0
    U32 bytesAdjustment = 0;
6776
0
    U32 finalMatchSplit = 0;
6777
6778
    /* TODO(embg) support fast parsing mode in noBlockDelim mode */
6779
0
    (void)externalRepSearch;
6780
6781
0
    if (cctx->cdict) {
6782
0
        dictSize = cctx->cdict->dictContentSize;
6783
0
    } else if (cctx->prefixDict.dict) {
6784
0
        dictSize = cctx->prefixDict.dictSize;
6785
0
    } else {
6786
0
        dictSize = 0;
6787
0
    }
6788
0
    DEBUGLOG(5, "ZSTD_transferSequences_noDelim: idx: %u PIS: %u blockSize: %zu", idx, startPosInSequence, blockSize);
6789
0
    DEBUGLOG(5, "Start seq: idx: %u (of: %u ml: %u ll: %u)", idx, inSeqs[idx].offset, inSeqs[idx].matchLength, inSeqs[idx].litLength);
6790
0
    ZSTD_memcpy(updatedRepcodes.rep, cctx->blockState.prevCBlock->rep, sizeof(Repcodes_t));
6791
0
    while (endPosInSequence && idx < inSeqsSize && !finalMatchSplit) {
6792
0
        const ZSTD_Sequence currSeq = inSeqs[idx];
6793
0
        U32 litLength = currSeq.litLength;
6794
0
        U32 matchLength = currSeq.matchLength;
6795
0
        U32 const rawOffset = currSeq.offset;
6796
0
        U32 offBase;
6797
6798
        /* Modify the sequence depending on where endPosInSequence lies */
6799
0
        if (endPosInSequence >= currSeq.litLength + currSeq.matchLength) {
6800
0
            if (startPosInSequence >= litLength) {
6801
0
                startPosInSequence -= litLength;
6802
0
                litLength = 0;
6803
0
                matchLength -= startPosInSequence;
6804
0
            } else {
6805
0
                litLength -= startPosInSequence;
6806
0
            }
6807
            /* Move to the next sequence */
6808
0
            endPosInSequence -= currSeq.litLength + currSeq.matchLength;
6809
0
            startPosInSequence = 0;
6810
0
        } else {
6811
            /* This is the final (partial) sequence we're adding from inSeqs, and endPosInSequence
6812
               does not reach the end of the match. So, we have to split the sequence */
6813
0
            DEBUGLOG(6, "Require a split: diff: %u, idx: %u PIS: %u",
6814
0
                     currSeq.litLength + currSeq.matchLength - endPosInSequence, idx, endPosInSequence);
6815
0
            if (endPosInSequence > litLength) {
6816
0
                U32 firstHalfMatchLength;
6817
0
                litLength = startPosInSequence >= litLength ? 0 : litLength - startPosInSequence;
6818
0
                firstHalfMatchLength = endPosInSequence - startPosInSequence - litLength;
6819
0
                if (matchLength > blockSize && firstHalfMatchLength >= cctx->appliedParams.cParams.minMatch) {
6820
                    /* Only ever split the match if it is larger than the block size */
6821
0
                    U32 secondHalfMatchLength = currSeq.matchLength + currSeq.litLength - endPosInSequence;
6822
0
                    if (secondHalfMatchLength < cctx->appliedParams.cParams.minMatch) {
6823
                        /* Move the endPosInSequence backward so that it creates match of minMatch length */
6824
0
                        endPosInSequence -= cctx->appliedParams.cParams.minMatch - secondHalfMatchLength;
6825
0
                        bytesAdjustment = cctx->appliedParams.cParams.minMatch - secondHalfMatchLength;
6826
0
                        firstHalfMatchLength -= bytesAdjustment;
6827
0
                    }
6828
0
                    matchLength = firstHalfMatchLength;
6829
                    /* Flag that we split the last match - after storing the sequence, exit the loop,
6830
                       but keep the value of endPosInSequence */
6831
0
                    finalMatchSplit = 1;
6832
0
                } else {
6833
                    /* Move the position in sequence backwards so that we don't split match, and break to store
6834
                     * the last literals. We use the original currSeq.litLength as a marker for where endPosInSequence
6835
                     * should go. We prefer to do this whenever it is not necessary to split the match, or if doing so
6836
                     * would cause the first half of the match to be too small
6837
                     */
6838
0
                    bytesAdjustment = endPosInSequence - currSeq.litLength;
6839
0
                    endPosInSequence = currSeq.litLength;
6840
0
                    break;
6841
0
                }
6842
0
            } else {
6843
                /* This sequence ends inside the literals, break to store the last literals */
6844
0
                break;
6845
0
            }
6846
0
        }
6847
        /* Check if this offset can be represented with a repcode */
6848
0
        {   U32 const ll0 = (litLength == 0);
6849
0
            offBase = ZSTD_finalizeOffBase(rawOffset, updatedRepcodes.rep, ll0);
6850
0
            ZSTD_updateRep(updatedRepcodes.rep, offBase, ll0);
6851
0
        }
6852
6853
0
        if (cctx->appliedParams.validateSequences) {
6854
0
            seqPos->posInSrc += litLength + matchLength;
6855
0
            FORWARD_IF_ERROR(ZSTD_validateSequence(offBase, matchLength, cctx->appliedParams.cParams.minMatch, seqPos->posInSrc,
6856
0
                                                   cctx->appliedParams.cParams.windowLog, dictSize, ZSTD_hasExtSeqProd(&cctx->appliedParams)),
6857
0
                                                   "Sequence validation failed");
6858
0
        }
6859
0
        DEBUGLOG(6, "Storing sequence: (of: %u, ml: %u, ll: %u)", offBase, matchLength, litLength);
6860
0
        RETURN_ERROR_IF(idx - seqPos->idx >= cctx->seqStore.maxNbSeq, externalSequences_invalid,
6861
0
                        "Not enough memory allocated. Try adjusting ZSTD_c_minMatch.");
6862
0
        ZSTD_storeSeq(&cctx->seqStore, litLength, ip, iend, offBase, matchLength);
6863
0
        ip += matchLength + litLength;
6864
0
        if (!finalMatchSplit)
6865
0
            idx++; /* Next Sequence */
6866
0
    }
6867
0
    DEBUGLOG(5, "Ending seq: idx: %u (of: %u ml: %u ll: %u)", idx, inSeqs[idx].offset, inSeqs[idx].matchLength, inSeqs[idx].litLength);
6868
0
    assert(idx == inSeqsSize || endPosInSequence <= inSeqs[idx].litLength + inSeqs[idx].matchLength);
6869
0
    seqPos->idx = idx;
6870
0
    seqPos->posInSequence = endPosInSequence;
6871
0
    ZSTD_memcpy(cctx->blockState.nextCBlock->rep, updatedRepcodes.rep, sizeof(Repcodes_t));
6872
6873
0
    iend -= bytesAdjustment;
6874
0
    if (ip != iend) {
6875
        /* Store any last literals */
6876
0
        U32 const lastLLSize = (U32)(iend - ip);
6877
0
        assert(ip <= iend);
6878
0
        DEBUGLOG(6, "Storing last literals of size: %u", lastLLSize);
6879
0
        ZSTD_storeLastLiterals(&cctx->seqStore, ip, lastLLSize);
6880
0
        seqPos->posInSrc += lastLLSize;
6881
0
    }
6882
6883
0
    return (size_t)(iend-istart);
6884
0
}
6885
6886
/* @seqPos represents a position within @inSeqs,
6887
 * it is read and updated by this function,
6888
 * once the goal to produce a block of size @blockSize is reached.
6889
 * @return: nb of bytes consumed from @src, necessarily <= @blockSize.
6890
 */
6891
typedef size_t (*ZSTD_SequenceCopier_f)(ZSTD_CCtx* cctx,
6892
                                        ZSTD_SequencePosition* seqPos,
6893
                                  const ZSTD_Sequence* const inSeqs, size_t inSeqsSize,
6894
                                  const void* src, size_t blockSize,
6895
                                        ZSTD_ParamSwitch_e externalRepSearch);
6896
6897
static ZSTD_SequenceCopier_f ZSTD_selectSequenceCopier(ZSTD_SequenceFormat_e mode)
6898
0
{
6899
0
    assert(ZSTD_cParam_withinBounds(ZSTD_c_blockDelimiters, (int)mode));
6900
0
    if (mode == ZSTD_sf_explicitBlockDelimiters) {
6901
0
        return ZSTD_transferSequences_wBlockDelim;
6902
0
    }
6903
0
    assert(mode == ZSTD_sf_noBlockDelimiters);
6904
0
    return ZSTD_transferSequences_noDelim;
6905
0
}
6906
6907
/* Discover the size of next block by searching for the delimiter.
6908
 * Note that a block delimiter **must** exist in this mode,
6909
 * otherwise it's an input error.
6910
 * The block size retrieved will be later compared to ensure it remains within bounds */
6911
static size_t
6912
blockSize_explicitDelimiter(const ZSTD_Sequence* inSeqs, size_t inSeqsSize, ZSTD_SequencePosition seqPos)
6913
0
{
6914
0
    int end = 0;
6915
0
    size_t blockSize = 0;
6916
0
    size_t spos = seqPos.idx;
6917
0
    DEBUGLOG(6, "blockSize_explicitDelimiter : seq %zu / %zu", spos, inSeqsSize);
6918
0
    assert(spos <= inSeqsSize);
6919
0
    while (spos < inSeqsSize) {
6920
0
        end = (inSeqs[spos].offset == 0);
6921
0
        blockSize += inSeqs[spos].litLength + inSeqs[spos].matchLength;
6922
0
        if (end) {
6923
0
            if (inSeqs[spos].matchLength != 0)
6924
0
                RETURN_ERROR(externalSequences_invalid, "delimiter format error : both matchlength and offset must be == 0");
6925
0
            break;
6926
0
        }
6927
0
        spos++;
6928
0
    }
6929
0
    if (!end)
6930
0
        RETURN_ERROR(externalSequences_invalid, "Reached end of sequences without finding a block delimiter");
6931
0
    return blockSize;
6932
0
}
6933
6934
static size_t determine_blockSize(ZSTD_SequenceFormat_e mode,
6935
                           size_t blockSize, size_t remaining,
6936
                     const ZSTD_Sequence* inSeqs, size_t inSeqsSize,
6937
                           ZSTD_SequencePosition seqPos)
6938
0
{
6939
0
    DEBUGLOG(6, "determine_blockSize : remainingSize = %zu", remaining);
6940
0
    if (mode == ZSTD_sf_noBlockDelimiters) {
6941
        /* Note: more a "target" block size */
6942
0
        return MIN(remaining, blockSize);
6943
0
    }
6944
0
    assert(mode == ZSTD_sf_explicitBlockDelimiters);
6945
0
    {   size_t const explicitBlockSize = blockSize_explicitDelimiter(inSeqs, inSeqsSize, seqPos);
6946
0
        FORWARD_IF_ERROR(explicitBlockSize, "Error while determining block size with explicit delimiters");
6947
0
        if (explicitBlockSize > blockSize)
6948
0
            RETURN_ERROR(externalSequences_invalid, "sequences incorrectly define a too large block");
6949
0
        if (explicitBlockSize > remaining)
6950
0
            RETURN_ERROR(externalSequences_invalid, "sequences define a frame longer than source");
6951
0
        return explicitBlockSize;
6952
0
    }
6953
0
}
6954
6955
/* Compress all provided sequences, block-by-block.
6956
 *
6957
 * Returns the cumulative size of all compressed blocks (including their headers),
6958
 * otherwise a ZSTD error.
6959
 */
6960
static size_t
6961
ZSTD_compressSequences_internal(ZSTD_CCtx* cctx,
6962
                                void* dst, size_t dstCapacity,
6963
                          const ZSTD_Sequence* inSeqs, size_t inSeqsSize,
6964
                          const void* src, size_t srcSize)
6965
0
{
6966
0
    size_t cSize = 0;
6967
0
    size_t remaining = srcSize;
6968
0
    ZSTD_SequencePosition seqPos = {0, 0, 0};
6969
6970
0
    const BYTE* ip = (BYTE const*)src;
6971
0
    BYTE* op = (BYTE*)dst;
6972
0
    ZSTD_SequenceCopier_f const sequenceCopier = ZSTD_selectSequenceCopier(cctx->appliedParams.blockDelimiters);
6973
6974
0
    DEBUGLOG(4, "ZSTD_compressSequences_internal srcSize: %zu, inSeqsSize: %zu", srcSize, inSeqsSize);
6975
    /* Special case: empty frame */
6976
0
    if (remaining == 0) {
6977
0
        U32 const cBlockHeader24 = 1 /* last block */ + (((U32)bt_raw)<<1);
6978
0
        RETURN_ERROR_IF(dstCapacity<4, dstSize_tooSmall, "No room for empty frame block header");
6979
0
        MEM_writeLE32(op, cBlockHeader24);
6980
0
        op += ZSTD_blockHeaderSize;
6981
0
        dstCapacity -= ZSTD_blockHeaderSize;
6982
0
        cSize += ZSTD_blockHeaderSize;
6983
0
    }
6984
6985
0
    while (remaining) {
6986
0
        size_t compressedSeqsSize;
6987
0
        size_t cBlockSize;
6988
0
        size_t blockSize = determine_blockSize(cctx->appliedParams.blockDelimiters,
6989
0
                                        cctx->blockSizeMax, remaining,
6990
0
                                        inSeqs, inSeqsSize, seqPos);
6991
0
        U32 const lastBlock = (blockSize == remaining);
6992
0
        FORWARD_IF_ERROR(blockSize, "Error while trying to determine block size");
6993
0
        assert(blockSize <= remaining);
6994
0
        ZSTD_resetSeqStore(&cctx->seqStore);
6995
6996
0
        blockSize = sequenceCopier(cctx,
6997
0
                                   &seqPos, inSeqs, inSeqsSize,
6998
0
                                   ip, blockSize,
6999
0
                                   cctx->appliedParams.searchForExternalRepcodes);
7000
0
        FORWARD_IF_ERROR(blockSize, "Bad sequence copy");
7001
7002
        /* If blocks are too small, emit as a nocompress block */
7003
        /* TODO: See 3090. We reduced MIN_CBLOCK_SIZE from 3 to 2 so to compensate we are adding
7004
         * additional 1. We need to revisit and change this logic to be more consistent */
7005
0
        if (blockSize < MIN_CBLOCK_SIZE+ZSTD_blockHeaderSize+1+1) {
7006
0
            cBlockSize = ZSTD_noCompressBlock(op, dstCapacity, ip, blockSize, lastBlock);
7007
0
            FORWARD_IF_ERROR(cBlockSize, "Nocompress block failed");
7008
0
            DEBUGLOG(5, "Block too small (%zu): data remains uncompressed: cSize=%zu", blockSize, cBlockSize);
7009
0
            cSize += cBlockSize;
7010
0
            ip += blockSize;
7011
0
            op += cBlockSize;
7012
0
            remaining -= blockSize;
7013
0
            dstCapacity -= cBlockSize;
7014
0
            continue;
7015
0
        }
7016
7017
0
        RETURN_ERROR_IF(dstCapacity < ZSTD_blockHeaderSize, dstSize_tooSmall, "not enough dstCapacity to write a new compressed block");
7018
0
        compressedSeqsSize = ZSTD_entropyCompressSeqStore(&cctx->seqStore,
7019
0
                                &cctx->blockState.prevCBlock->entropy, &cctx->blockState.nextCBlock->entropy,
7020
0
                                &cctx->appliedParams,
7021
0
                                op + ZSTD_blockHeaderSize /* Leave space for block header */, dstCapacity - ZSTD_blockHeaderSize,
7022
0
                                blockSize,
7023
0
                                cctx->tmpWorkspace, cctx->tmpWkspSize /* statically allocated in resetCCtx */,
7024
0
                                cctx->bmi2);
7025
0
        FORWARD_IF_ERROR(compressedSeqsSize, "Compressing sequences of block failed");
7026
0
        DEBUGLOG(5, "Compressed sequences size: %zu", compressedSeqsSize);
7027
7028
0
        if (!cctx->isFirstBlock &&
7029
0
            ZSTD_maybeRLE(&cctx->seqStore) &&
7030
0
            ZSTD_isRLE(ip, blockSize)) {
7031
            /* Note: don't emit the first block as RLE even if it qualifies because
7032
             * doing so will cause the decoder (cli <= v1.4.3 only) to throw an (invalid) error
7033
             * "should consume all input error."
7034
             */
7035
0
            compressedSeqsSize = 1;
7036
0
        }
7037
7038
0
        if (compressedSeqsSize == 0) {
7039
            /* ZSTD_noCompressBlock writes the block header as well */
7040
0
            cBlockSize = ZSTD_noCompressBlock(op, dstCapacity, ip, blockSize, lastBlock);
7041
0
            FORWARD_IF_ERROR(cBlockSize, "ZSTD_noCompressBlock failed");
7042
0
            DEBUGLOG(5, "Writing out nocompress block, size: %zu", cBlockSize);
7043
0
        } else if (compressedSeqsSize == 1) {
7044
0
            cBlockSize = ZSTD_rleCompressBlock(op, dstCapacity, *ip, blockSize, lastBlock);
7045
0
            FORWARD_IF_ERROR(cBlockSize, "ZSTD_rleCompressBlock failed");
7046
0
            DEBUGLOG(5, "Writing out RLE block, size: %zu", cBlockSize);
7047
0
        } else {
7048
0
            U32 cBlockHeader;
7049
            /* Error checking and repcodes update */
7050
0
            ZSTD_blockState_confirmRepcodesAndEntropyTables(&cctx->blockState);
7051
0
            if (cctx->blockState.prevCBlock->entropy.fse.offcode_repeatMode == FSE_repeat_valid)
7052
0
                cctx->blockState.prevCBlock->entropy.fse.offcode_repeatMode = FSE_repeat_check;
7053
7054
            /* Write block header into beginning of block*/
7055
0
            cBlockHeader = lastBlock + (((U32)bt_compressed)<<1) + (U32)(compressedSeqsSize << 3);
7056
0
            MEM_writeLE24(op, cBlockHeader);
7057
0
            cBlockSize = ZSTD_blockHeaderSize + compressedSeqsSize;
7058
0
            DEBUGLOG(5, "Writing out compressed block, size: %zu", cBlockSize);
7059
0
        }
7060
7061
0
        cSize += cBlockSize;
7062
7063
0
        if (lastBlock) {
7064
0
            break;
7065
0
        } else {
7066
0
            ip += blockSize;
7067
0
            op += cBlockSize;
7068
0
            remaining -= blockSize;
7069
0
            dstCapacity -= cBlockSize;
7070
0
            cctx->isFirstBlock = 0;
7071
0
        }
7072
0
        DEBUGLOG(5, "cSize running total: %zu (remaining dstCapacity=%zu)", cSize, dstCapacity);
7073
0
    }
7074
7075
0
    DEBUGLOG(4, "cSize final total: %zu", cSize);
7076
0
    return cSize;
7077
0
}
7078
7079
size_t ZSTD_compressSequences(ZSTD_CCtx* cctx,
7080
                              void* dst, size_t dstCapacity,
7081
                              const ZSTD_Sequence* inSeqs, size_t inSeqsSize,
7082
                              const void* src, size_t srcSize)
7083
0
{
7084
0
    BYTE* op = (BYTE*)dst;
7085
0
    size_t cSize = 0;
7086
7087
    /* Transparent initialization stage, same as compressStream2() */
7088
0
    DEBUGLOG(4, "ZSTD_compressSequences (nbSeqs=%zu,dstCapacity=%zu)", inSeqsSize, dstCapacity);
7089
0
    assert(cctx != NULL);
7090
0
    FORWARD_IF_ERROR(ZSTD_CCtx_init_compressStream2(cctx, ZSTD_e_end, srcSize), "CCtx initialization failed");
7091
7092
    /* Begin writing output, starting with frame header */
7093
0
    {   size_t const frameHeaderSize = ZSTD_writeFrameHeader(op, dstCapacity,
7094
0
                    &cctx->appliedParams, srcSize, cctx->dictID);
7095
0
        op += frameHeaderSize;
7096
0
        assert(frameHeaderSize <= dstCapacity);
7097
0
        dstCapacity -= frameHeaderSize;
7098
0
        cSize += frameHeaderSize;
7099
0
    }
7100
0
    if (cctx->appliedParams.fParams.checksumFlag && srcSize) {
7101
0
        XXH64_update(&cctx->xxhState, src, srcSize);
7102
0
    }
7103
7104
    /* Now generate compressed blocks */
7105
0
    {   size_t const cBlocksSize = ZSTD_compressSequences_internal(cctx,
7106
0
                                                           op, dstCapacity,
7107
0
                                                           inSeqs, inSeqsSize,
7108
0
                                                           src, srcSize);
7109
0
        FORWARD_IF_ERROR(cBlocksSize, "Compressing blocks failed!");
7110
0
        cSize += cBlocksSize;
7111
0
        assert(cBlocksSize <= dstCapacity);
7112
0
        dstCapacity -= cBlocksSize;
7113
0
    }
7114
7115
    /* Complete with frame checksum, if needed */
7116
0
    if (cctx->appliedParams.fParams.checksumFlag) {
7117
0
        U32 const checksum = (U32) XXH64_digest(&cctx->xxhState);
7118
0
        RETURN_ERROR_IF(dstCapacity<4, dstSize_tooSmall, "no room for checksum");
7119
0
        DEBUGLOG(4, "Write checksum : %08X", (unsigned)checksum);
7120
0
        MEM_writeLE32((char*)dst + cSize, checksum);
7121
0
        cSize += 4;
7122
0
    }
7123
7124
0
    DEBUGLOG(4, "Final compressed size: %zu", cSize);
7125
0
    return cSize;
7126
0
}
7127
7128
7129
#if defined(ZSTD_ARCH_X86_AVX2)
7130
7131
#include <immintrin.h>  /* AVX2 intrinsics */
7132
7133
/*
7134
 * Convert 2 sequences per iteration, using AVX2 intrinsics:
7135
 *   - offset -> offBase = offset + 2
7136
 *   - litLength -> (U16) litLength
7137
 *   - matchLength -> (U16)(matchLength - 3)
7138
 *   - rep is ignored
7139
 * Store only 8 bytes per SeqDef (offBase[4], litLength[2], mlBase[2]).
7140
 *
7141
 * At the end, instead of extracting two __m128i,
7142
 * we use _mm256_permute4x64_epi64(..., 0xE8) to move lane2 into lane1,
7143
 * then store the lower 16 bytes in one go.
7144
 *
7145
 * @returns 0 on succes, with no long length detected
7146
 * @returns > 0 if there is one long length (> 65535),
7147
 * indicating the position, and type.
7148
 */
7149
size_t convertSequences_noRepcodes(
7150
    SeqDef* dstSeqs,
7151
    const ZSTD_Sequence* inSeqs,
7152
    size_t nbSequences)
7153
{
7154
    /*
7155
     * addition:
7156
     *   For each 128-bit half: (offset+2, litLength+0, matchLength-3, rep+0)
7157
     */
7158
    const __m256i addition = _mm256_setr_epi32(
7159
        ZSTD_REP_NUM, 0, -MINMATCH, 0,    /* for sequence i */
7160
        ZSTD_REP_NUM, 0, -MINMATCH, 0     /* for sequence i+1 */
7161
    );
7162
7163
    /* limit: check if there is a long length */
7164
    const __m256i limit = _mm256_set1_epi32(65535);
7165
7166
    /*
7167
     * shuffle mask for byte-level rearrangement in each 128-bit half:
7168
     *
7169
     * Input layout (after addition) per 128-bit half:
7170
     *   [ offset+2 (4 bytes) | litLength (4 bytes) | matchLength (4 bytes) | rep (4 bytes) ]
7171
     * We only need:
7172
     *   offBase (4 bytes) = offset+2
7173
     *   litLength (2 bytes) = low 2 bytes of litLength
7174
     *   mlBase (2 bytes) = low 2 bytes of (matchLength)
7175
     * => Bytes [0..3, 4..5, 8..9], zero the rest.
7176
     */
7177
    const __m256i mask = _mm256_setr_epi8(
7178
        /* For the lower 128 bits => sequence i */
7179
         0, 1, 2, 3,       /* offset+2 */
7180
         4, 5,             /* litLength (16 bits) */
7181
         8, 9,             /* matchLength (16 bits) */
7182
         (BYTE)0x80, (BYTE)0x80, (BYTE)0x80, (BYTE)0x80,
7183
         (BYTE)0x80, (BYTE)0x80, (BYTE)0x80, (BYTE)0x80,
7184
7185
        /* For the upper 128 bits => sequence i+1 */
7186
        16,17,18,19,       /* offset+2 */
7187
        20,21,             /* litLength */
7188
        24,25,             /* matchLength */
7189
        (BYTE)0x80, (BYTE)0x80, (BYTE)0x80, (BYTE)0x80,
7190
        (BYTE)0x80, (BYTE)0x80, (BYTE)0x80, (BYTE)0x80
7191
    );
7192
7193
    /*
7194
     * Next, we'll use _mm256_permute4x64_epi64(vshf, 0xE8).
7195
     * Explanation of 0xE8 = 11101000b => [lane0, lane2, lane2, lane3].
7196
     * So the lower 128 bits become [lane0, lane2] => combining seq0 and seq1.
7197
     */
7198
#define PERM_LANE_0X_E8 0xE8  /* [0,2,2,3] in lane indices */
7199
7200
    size_t longLen = 0, i = 0;
7201
7202
    /* AVX permutation depends on the specific definition of target structures */
7203
    ZSTD_STATIC_ASSERT(sizeof(ZSTD_Sequence) == 16);
7204
    ZSTD_STATIC_ASSERT(offsetof(ZSTD_Sequence, offset) == 0);
7205
    ZSTD_STATIC_ASSERT(offsetof(ZSTD_Sequence, litLength) == 4);
7206
    ZSTD_STATIC_ASSERT(offsetof(ZSTD_Sequence, matchLength) == 8);
7207
    ZSTD_STATIC_ASSERT(sizeof(SeqDef) == 8);
7208
    ZSTD_STATIC_ASSERT(offsetof(SeqDef, offBase) == 0);
7209
    ZSTD_STATIC_ASSERT(offsetof(SeqDef, litLength) == 4);
7210
    ZSTD_STATIC_ASSERT(offsetof(SeqDef, mlBase) == 6);
7211
7212
    /* Process 2 sequences per loop iteration */
7213
    for (; i + 1 < nbSequences; i += 2) {
7214
        /* Load 2 ZSTD_Sequence (32 bytes) */
7215
        __m256i vin  = _mm256_loadu_si256((const __m256i*)(const void*)&inSeqs[i]);
7216
7217
        /* Add {2, 0, -3, 0} in each 128-bit half */
7218
        __m256i vadd = _mm256_add_epi32(vin, addition);
7219
7220
        /* Check for long length */
7221
        __m256i ll_cmp  = _mm256_cmpgt_epi32(vadd, limit);  /* 0xFFFFFFFF for element > 65535 */
7222
        int ll_res  = _mm256_movemask_epi8(ll_cmp);
7223
7224
        /* Shuffle bytes so each half gives us the 8 bytes we need */
7225
        __m256i vshf = _mm256_shuffle_epi8(vadd, mask);
7226
        /*
7227
         * Now:
7228
         *   Lane0 = seq0's 8 bytes
7229
         *   Lane1 = 0
7230
         *   Lane2 = seq1's 8 bytes
7231
         *   Lane3 = 0
7232
         */
7233
7234
        /* Permute 64-bit lanes => move Lane2 down into Lane1. */
7235
        __m256i vperm = _mm256_permute4x64_epi64(vshf, PERM_LANE_0X_E8);
7236
        /*
7237
         * Now the lower 16 bytes (Lane0+Lane1) = [seq0, seq1].
7238
         * The upper 16 bytes are [Lane2, Lane3] = [seq1, 0], but we won't use them.
7239
         */
7240
7241
        /* Store only the lower 16 bytes => 2 SeqDef (8 bytes each) */
7242
        _mm_storeu_si128((__m128i *)(void*)&dstSeqs[i], _mm256_castsi256_si128(vperm));
7243
        /*
7244
         * This writes out 16 bytes total:
7245
         *   - offset 0..7  => seq0 (offBase, litLength, mlBase)
7246
         *   - offset 8..15 => seq1 (offBase, litLength, mlBase)
7247
         */
7248
7249
        /* check (unlikely) long lengths > 65535
7250
         * indices for lengths correspond to bits [4..7], [8..11], [20..23], [24..27]
7251
         * => combined mask = 0x0FF00FF0
7252
         */
7253
        if (UNLIKELY((ll_res & 0x0FF00FF0) != 0)) {
7254
            /* long length detected: let's figure out which one*/
7255
            if (inSeqs[i].matchLength > 65535+MINMATCH) {
7256
                assert(longLen == 0);
7257
                longLen = i + 1;
7258
            }
7259
            if (inSeqs[i].litLength > 65535) {
7260
                assert(longLen == 0);
7261
                longLen = i + nbSequences + 1;
7262
            }
7263
            if (inSeqs[i+1].matchLength > 65535+MINMATCH) {
7264
                assert(longLen == 0);
7265
                longLen = i + 1 + 1;
7266
            }
7267
            if (inSeqs[i+1].litLength > 65535) {
7268
                assert(longLen == 0);
7269
                longLen = i + 1 + nbSequences + 1;
7270
            }
7271
        }
7272
    }
7273
7274
    /* Handle leftover if @nbSequences is odd */
7275
    if (i < nbSequences) {
7276
        /* process last sequence */
7277
        assert(i == nbSequences - 1);
7278
        dstSeqs[i].offBase = OFFSET_TO_OFFBASE(inSeqs[i].offset);
7279
        dstSeqs[i].litLength = (U16)inSeqs[i].litLength;
7280
        dstSeqs[i].mlBase = (U16)(inSeqs[i].matchLength - MINMATCH);
7281
        /* check (unlikely) long lengths > 65535 */
7282
        if (UNLIKELY(inSeqs[i].matchLength > 65535+MINMATCH)) {
7283
            assert(longLen == 0);
7284
            longLen = i + 1;
7285
        }
7286
        if (UNLIKELY(inSeqs[i].litLength > 65535)) {
7287
            assert(longLen == 0);
7288
            longLen = i + nbSequences + 1;
7289
        }
7290
    }
7291
7292
    return longLen;
7293
}
7294
7295
#elif defined ZSTD_ARCH_RISCV_RVV
7296
#include <riscv_vector.h>
7297
/*
7298
 * Convert `vl` sequences per iteration, using RVV intrinsics:
7299
 *   - offset -> offBase = offset + 2
7300
 *   - litLength -> (U16) litLength
7301
 *   - matchLength -> (U16)(matchLength - 3)
7302
 *   - rep is ignored
7303
 * Store only 8 bytes per SeqDef (offBase[4], litLength[2], mlBase[2]).
7304
 *
7305
 * @returns 0 on succes, with no long length detected
7306
 * @returns > 0 if there is one long length (> 65535),
7307
 * indicating the position, and type.
7308
 */
7309
size_t convertSequences_noRepcodes(SeqDef* dstSeqs, const ZSTD_Sequence* inSeqs, size_t nbSequences) {
7310
    size_t longLen = 0;
7311
    size_t vl = 0;
7312
    typedef uint32_t __attribute__((may_alias)) aliased_u32;
7313
    /* RVV depends on the specific definition of target structures */
7314
    ZSTD_STATIC_ASSERT(sizeof(ZSTD_Sequence) == 16);
7315
    ZSTD_STATIC_ASSERT(offsetof(ZSTD_Sequence, offset) == 0);
7316
    ZSTD_STATIC_ASSERT(offsetof(ZSTD_Sequence, litLength) == 4);
7317
    ZSTD_STATIC_ASSERT(offsetof(ZSTD_Sequence, matchLength) == 8);
7318
    ZSTD_STATIC_ASSERT(sizeof(SeqDef) == 8);
7319
    ZSTD_STATIC_ASSERT(offsetof(SeqDef, offBase) == 0);
7320
    ZSTD_STATIC_ASSERT(offsetof(SeqDef, litLength) == 4);
7321
    ZSTD_STATIC_ASSERT(offsetof(SeqDef, mlBase) == 6);
7322
    
7323
    for (size_t i = 0; i < nbSequences; i += vl) {
7324
7325
        vl = __riscv_vsetvl_e32m2(nbSequences-i);       
7326
        {
7327
            // Loading structure member variables
7328
            vuint32m2x4_t v_tuple = __riscv_vlseg4e32_v_u32m2x4(
7329
                (const aliased_u32*)((const void*)&inSeqs[i]), 
7330
                vl
7331
            );
7332
            vuint32m2_t v_offset = __riscv_vget_v_u32m2x4_u32m2(v_tuple, 0);
7333
            vuint32m2_t v_lit = __riscv_vget_v_u32m2x4_u32m2(v_tuple, 1);
7334
            vuint32m2_t v_match = __riscv_vget_v_u32m2x4_u32m2(v_tuple, 2);
7335
            // offset + ZSTD_REP_NUM
7336
            vuint32m2_t v_offBase = __riscv_vadd_vx_u32m2(v_offset, ZSTD_REP_NUM, vl); 
7337
            // Check for integer overflow
7338
            // Cast to a 16-bit variable
7339
            vbool16_t lit_overflow = __riscv_vmsgtu_vx_u32m2_b16(v_lit, 65535, vl);
7340
            vuint16m1_t v_lit_clamped = __riscv_vncvt_x_x_w_u16m1(v_lit, vl);
7341
7342
            vbool16_t ml_overflow = __riscv_vmsgtu_vx_u32m2_b16(v_match, 65535+MINMATCH, vl);
7343
            vuint16m1_t v_ml_clamped = __riscv_vncvt_x_x_w_u16m1(__riscv_vsub_vx_u32m2(v_match, MINMATCH, vl), vl);
7344
7345
            // Pack two 16-bit fields into a 32-bit value (little-endian)
7346
            // The lower 16 bits contain litLength, and the upper 16 bits contain mlBase
7347
            vuint32m2_t v_lit_ml_combined = __riscv_vsll_vx_u32m2(
7348
                __riscv_vwcvtu_x_x_v_u32m2(v_ml_clamped, vl), // Convert matchLength to 32-bit
7349
                16, 
7350
                vl
7351
            );
7352
            v_lit_ml_combined = __riscv_vor_vv_u32m2(
7353
                v_lit_ml_combined,
7354
                __riscv_vwcvtu_x_x_v_u32m2(v_lit_clamped, vl),
7355
                vl
7356
            );
7357
            {
7358
                // Create a vector of SeqDef structures
7359
                // Store the offBase, litLength, and mlBase in a vector of SeqDef
7360
                vuint32m2x2_t store_data = __riscv_vcreate_v_u32m2x2(
7361
                    v_offBase,          
7362
                    v_lit_ml_combined   
7363
                );
7364
                __riscv_vsseg2e32_v_u32m2x2(
7365
                    (aliased_u32*)((void*)&dstSeqs[i]), 
7366
                    store_data,             
7367
                    vl                      
7368
                );
7369
            }
7370
            {
7371
                // Find the first index where an overflow occurs
7372
                int first_ml = __riscv_vfirst_m_b16(ml_overflow, vl);
7373
                int first_lit = __riscv_vfirst_m_b16(lit_overflow, vl);
7374
7375
                if (UNLIKELY(first_ml != -1)) {
7376
                    assert(longLen == 0);
7377
                    longLen = i + first_ml + 1;
7378
                }
7379
                if (UNLIKELY(first_lit != -1)) {
7380
                    assert(longLen == 0);
7381
                    longLen = i + first_lit + 1 + nbSequences;
7382
                }
7383
            }
7384
        }
7385
    }
7386
    return longLen;
7387
}
7388
7389
/* the vector implementation could also be ported to SSSE3,
7390
 * but since this implementation is targeting modern systems (>= Sapphire Rapid),
7391
 * it's not useful to develop and maintain code for older pre-AVX2 platforms */
7392
7393
#elif defined(ZSTD_ARCH_ARM_NEON) && (defined(__aarch64__) || defined(_M_ARM64))
7394
7395
size_t convertSequences_noRepcodes(
7396
    SeqDef* dstSeqs,
7397
    const ZSTD_Sequence* inSeqs,
7398
    size_t nbSequences)
7399
{
7400
    size_t longLen = 0;
7401
    size_t n = 0;
7402
7403
    /* Neon permutation depends on the specific definition of target structures. */
7404
    ZSTD_STATIC_ASSERT(sizeof(ZSTD_Sequence) == 16);
7405
    ZSTD_STATIC_ASSERT(offsetof(ZSTD_Sequence, offset) == 0);
7406
    ZSTD_STATIC_ASSERT(offsetof(ZSTD_Sequence, litLength) == 4);
7407
    ZSTD_STATIC_ASSERT(offsetof(ZSTD_Sequence, matchLength) == 8);
7408
    ZSTD_STATIC_ASSERT(sizeof(SeqDef) == 8);
7409
    ZSTD_STATIC_ASSERT(offsetof(SeqDef, offBase) == 0);
7410
    ZSTD_STATIC_ASSERT(offsetof(SeqDef, litLength) == 4);
7411
    ZSTD_STATIC_ASSERT(offsetof(SeqDef, mlBase) == 6);
7412
7413
    if (nbSequences > 3) {
7414
        static const ZSTD_ALIGNED(16) U32 constAddition[4] = {
7415
            ZSTD_REP_NUM, 0, -MINMATCH, 0
7416
        };
7417
        static const ZSTD_ALIGNED(16) U8 constMask[16] = {
7418
            0, 1, 2, 3, 4, 5, 8, 9, 16, 17, 18, 19, 20, 21, 24, 25
7419
        };
7420
        static const ZSTD_ALIGNED(16) U16 constCounter[8] = {
7421
            1, 1, 1, 1, 2, 2, 2, 2
7422
        };
7423
7424
        const uint32x4_t vaddition = vld1q_u32(constAddition);
7425
        const uint8x16_t vmask = vld1q_u8(constMask);
7426
        uint16x8_t vcounter = vld1q_u16(constCounter);
7427
        uint16x8_t vindex01 = vdupq_n_u16(0);
7428
        uint16x8_t vindex23 = vdupq_n_u16(0);
7429
7430
        do {
7431
            /* Load 4 ZSTD_Sequence (64 bytes). */
7432
            const uint32x4_t vin0 = vld1q_u32(&inSeqs[n + 0].offset);
7433
            const uint32x4_t vin1 = vld1q_u32(&inSeqs[n + 1].offset);
7434
            const uint32x4_t vin2 = vld1q_u32(&inSeqs[n + 2].offset);
7435
            const uint32x4_t vin3 = vld1q_u32(&inSeqs[n + 3].offset);
7436
7437
            /* Add {ZSTD_REP_NUM, 0, -MINMATCH, 0} to each vector. */
7438
            const uint8x16x2_t vadd01 = { {
7439
                vreinterpretq_u8_u32(vaddq_u32(vin0, vaddition)),
7440
                vreinterpretq_u8_u32(vaddq_u32(vin1, vaddition)),
7441
            } };
7442
            const uint8x16x2_t vadd23 = { {
7443
                vreinterpretq_u8_u32(vaddq_u32(vin2, vaddition)),
7444
                vreinterpretq_u8_u32(vaddq_u32(vin3, vaddition)),
7445
            } };
7446
7447
            /* Shuffle and pack bytes so each vector contains 2 SeqDef structures. */
7448
            const uint8x16_t vout01 = vqtbl2q_u8(vadd01, vmask);
7449
            const uint8x16_t vout23 = vqtbl2q_u8(vadd23, vmask);
7450
7451
            /* Pack the upper 16-bits of 32-bit lanes for overflow check. */
7452
            uint16x8_t voverflow01 = vuzp2q_u16(vreinterpretq_u16_u8(vadd01.val[0]),
7453
                                                vreinterpretq_u16_u8(vadd01.val[1]));
7454
            uint16x8_t voverflow23 = vuzp2q_u16(vreinterpretq_u16_u8(vadd23.val[0]),
7455
                                                vreinterpretq_u16_u8(vadd23.val[1]));
7456
7457
            /* Store 4 SeqDef structures. */
7458
            vst1q_u32(&dstSeqs[n + 0].offBase, vreinterpretq_u32_u8(vout01));
7459
            vst1q_u32(&dstSeqs[n + 2].offBase, vreinterpretq_u32_u8(vout23));
7460
7461
            /* Create masks in case of overflow. */
7462
            voverflow01 = vcgtzq_s16(vreinterpretq_s16_u16(voverflow01));
7463
            voverflow23 = vcgtzq_s16(vreinterpretq_s16_u16(voverflow23));
7464
7465
            /* Update overflow indices. */
7466
            vindex01 = vbslq_u16(voverflow01, vcounter, vindex01);
7467
            vindex23 = vbslq_u16(voverflow23, vcounter, vindex23);
7468
7469
            /* Update counter for overflow check. */
7470
            vcounter = vaddq_u16(vcounter, vdupq_n_u16(4));
7471
7472
            n += 4;
7473
        } while(n < nbSequences - 3);
7474
7475
        /* Fixup indices in the second vector, we saved an additional counter
7476
           in the loop to update the second overflow index, we need to add 2
7477
           here when the indices are not 0. */
7478
        {   uint16x8_t nonzero = vtstq_u16(vindex23, vindex23);
7479
            vindex23 = vsubq_u16(vindex23, nonzero);
7480
            vindex23 = vsubq_u16(vindex23, nonzero);
7481
        }
7482
7483
        /* Merge indices in the vectors, maximums are needed. */
7484
        vindex01 = vmaxq_u16(vindex01, vindex23);
7485
        vindex01 = vmaxq_u16(vindex01, vextq_u16(vindex01, vindex01, 4));
7486
7487
        /* Compute `longLen`, maximums of matchLength and litLength
7488
           with a preference on litLength. */
7489
        {   U64 maxLitMatchIndices = vgetq_lane_u64(vreinterpretq_u64_u16(vindex01), 0);
7490
            size_t maxLitIndex = (maxLitMatchIndices >> 16) & 0xFFFF;
7491
            size_t maxMatchIndex = (maxLitMatchIndices >> 32) & 0xFFFF;
7492
            longLen = maxLitIndex > maxMatchIndex ? maxLitIndex + nbSequences
7493
                                                  : maxMatchIndex;
7494
        }
7495
    }
7496
7497
    /* Handle remaining elements. */
7498
    for (; n < nbSequences; n++) {
7499
        dstSeqs[n].offBase = OFFSET_TO_OFFBASE(inSeqs[n].offset);
7500
        dstSeqs[n].litLength = (U16)inSeqs[n].litLength;
7501
        dstSeqs[n].mlBase = (U16)(inSeqs[n].matchLength - MINMATCH);
7502
        /* Check for long length > 65535. */
7503
        if (UNLIKELY(inSeqs[n].matchLength > 65535 + MINMATCH)) {
7504
            assert(longLen == 0);
7505
            longLen = n + 1;
7506
        }
7507
        if (UNLIKELY(inSeqs[n].litLength > 65535)) {
7508
            assert(longLen == 0);
7509
            longLen = n + nbSequences + 1;
7510
        }
7511
    }
7512
    return longLen;
7513
}
7514
7515
#else /* No vectorization. */
7516
7517
size_t convertSequences_noRepcodes(
7518
    SeqDef* dstSeqs,
7519
    const ZSTD_Sequence* inSeqs,
7520
    size_t nbSequences)
7521
0
{
7522
0
    size_t longLen = 0;
7523
0
    size_t n;
7524
0
    for (n=0; n<nbSequences; n++) {
7525
0
        dstSeqs[n].offBase = OFFSET_TO_OFFBASE(inSeqs[n].offset);
7526
0
        dstSeqs[n].litLength = (U16)inSeqs[n].litLength;
7527
0
        dstSeqs[n].mlBase = (U16)(inSeqs[n].matchLength - MINMATCH);
7528
        /* Check for long length > 65535. */
7529
0
        if (UNLIKELY(inSeqs[n].matchLength > 65535+MINMATCH)) {
7530
0
            assert(longLen == 0);
7531
0
            longLen = n + 1;
7532
0
        }
7533
0
        if (UNLIKELY(inSeqs[n].litLength > 65535)) {
7534
0
            assert(longLen == 0);
7535
0
            longLen = n + nbSequences + 1;
7536
0
        }
7537
0
    }
7538
0
    return longLen;
7539
0
}
7540
7541
#endif
7542
7543
/*
7544
 * Precondition: Sequences must end on an explicit Block Delimiter
7545
 * @return: 0 on success, or an error code.
7546
 * Note: Sequence validation functionality has been disabled (removed).
7547
 * This is helpful to generate a lean main pipeline, improving performance.
7548
 * It may be re-inserted later.
7549
 */
7550
size_t ZSTD_convertBlockSequences(ZSTD_CCtx* cctx,
7551
                const ZSTD_Sequence* const inSeqs, size_t nbSequences,
7552
                int repcodeResolution)
7553
0
{
7554
0
    Repcodes_t updatedRepcodes;
7555
0
    size_t seqNb = 0;
7556
7557
0
    DEBUGLOG(5, "ZSTD_convertBlockSequences (nbSequences = %zu)", nbSequences);
7558
7559
0
    RETURN_ERROR_IF(nbSequences >= cctx->seqStore.maxNbSeq, externalSequences_invalid,
7560
0
                    "Not enough memory allocated. Try adjusting ZSTD_c_minMatch.");
7561
7562
0
    ZSTD_memcpy(updatedRepcodes.rep, cctx->blockState.prevCBlock->rep, sizeof(Repcodes_t));
7563
7564
    /* check end condition */
7565
0
    assert(nbSequences >= 1);
7566
0
    assert(inSeqs[nbSequences-1].matchLength == 0);
7567
0
    assert(inSeqs[nbSequences-1].offset == 0);
7568
7569
    /* Convert Sequences from public format to internal format */
7570
0
    if (!repcodeResolution) {
7571
0
        size_t const longl = convertSequences_noRepcodes(cctx->seqStore.sequencesStart, inSeqs, nbSequences-1);
7572
0
        cctx->seqStore.sequences = cctx->seqStore.sequencesStart + nbSequences-1;
7573
0
        if (longl) {
7574
0
            DEBUGLOG(5, "long length");
7575
0
            assert(cctx->seqStore.longLengthType == ZSTD_llt_none);
7576
0
            if (longl <= nbSequences-1) {
7577
0
                DEBUGLOG(5, "long match length detected at pos %zu", longl-1);
7578
0
                cctx->seqStore.longLengthType = ZSTD_llt_matchLength;
7579
0
                cctx->seqStore.longLengthPos = (U32)(longl-1);
7580
0
            } else {
7581
0
                DEBUGLOG(5, "long literals length detected at pos %zu", longl-nbSequences);
7582
0
                assert(longl <= 2* (nbSequences-1));
7583
0
                cctx->seqStore.longLengthType = ZSTD_llt_literalLength;
7584
0
                cctx->seqStore.longLengthPos = (U32)(longl-(nbSequences-1)-1);
7585
0
            }
7586
0
        }
7587
0
    } else {
7588
0
        for (seqNb = 0; seqNb < nbSequences - 1 ; seqNb++) {
7589
0
            U32 const litLength = inSeqs[seqNb].litLength;
7590
0
            U32 const matchLength = inSeqs[seqNb].matchLength;
7591
0
            U32 const ll0 = (litLength == 0);
7592
0
            U32 const offBase = ZSTD_finalizeOffBase(inSeqs[seqNb].offset, updatedRepcodes.rep, ll0);
7593
7594
0
            DEBUGLOG(6, "Storing sequence: (of: %u, ml: %u, ll: %u)", offBase, matchLength, litLength);
7595
0
            ZSTD_storeSeqOnly(&cctx->seqStore, litLength, offBase, matchLength);
7596
0
            ZSTD_updateRep(updatedRepcodes.rep, offBase, ll0);
7597
0
        }
7598
0
    }
7599
7600
    /* If we skipped repcode search while parsing, we need to update repcodes now */
7601
0
    if (!repcodeResolution && nbSequences > 1) {
7602
0
        U32* const rep = updatedRepcodes.rep;
7603
7604
0
        if (nbSequences >= 4) {
7605
0
            U32 lastSeqIdx = (U32)nbSequences - 2; /* index of last full sequence */
7606
0
            rep[2] = inSeqs[lastSeqIdx - 2].offset;
7607
0
            rep[1] = inSeqs[lastSeqIdx - 1].offset;
7608
0
            rep[0] = inSeqs[lastSeqIdx].offset;
7609
0
        } else if (nbSequences == 3) {
7610
0
            rep[2] = rep[0];
7611
0
            rep[1] = inSeqs[0].offset;
7612
0
            rep[0] = inSeqs[1].offset;
7613
0
        } else {
7614
0
            assert(nbSequences == 2);
7615
0
            rep[2] = rep[1];
7616
0
            rep[1] = rep[0];
7617
0
            rep[0] = inSeqs[0].offset;
7618
0
        }
7619
0
    }
7620
7621
0
    ZSTD_memcpy(cctx->blockState.nextCBlock->rep, updatedRepcodes.rep, sizeof(Repcodes_t));
7622
7623
0
    return 0;
7624
0
}
7625
7626
#if defined(ZSTD_ARCH_X86_AVX2)
7627
7628
BlockSummary ZSTD_get1BlockSummary(const ZSTD_Sequence* seqs, size_t nbSeqs)
7629
{
7630
    size_t i;
7631
    __m256i const zeroVec = _mm256_setzero_si256();
7632
    __m256i sumVec = zeroVec;  /* accumulates match+lit in 32-bit lanes */
7633
    ZSTD_ALIGNED(32) U32 tmp[8];      /* temporary buffer for reduction */
7634
    size_t mSum = 0, lSum = 0;
7635
    ZSTD_STATIC_ASSERT(sizeof(ZSTD_Sequence) == 16);
7636
7637
    /* Process 2 structs (32 bytes) at a time */
7638
    for (i = 0; i + 2 <= nbSeqs; i += 2) {
7639
        /* Load two consecutive ZSTD_Sequence (8×4 = 32 bytes) */
7640
        __m256i data     = _mm256_loadu_si256((const __m256i*)(const void*)&seqs[i]);
7641
        /* check end of block signal */
7642
        __m256i cmp      = _mm256_cmpeq_epi32(data, zeroVec);
7643
        int cmp_res      = _mm256_movemask_epi8(cmp);
7644
        /* indices for match lengths correspond to bits [8..11], [24..27]
7645
         * => combined mask = 0x0F000F00 */
7646
        ZSTD_STATIC_ASSERT(offsetof(ZSTD_Sequence, matchLength) == 8);
7647
        if (cmp_res & 0x0F000F00) break;
7648
        /* Accumulate in sumVec */
7649
        sumVec           = _mm256_add_epi32(sumVec, data);
7650
    }
7651
7652
    /* Horizontal reduction */
7653
    _mm256_store_si256((__m256i*)tmp, sumVec);
7654
    lSum = tmp[1] + tmp[5];
7655
    mSum = tmp[2] + tmp[6];
7656
7657
    /* Handle the leftover */
7658
    for (; i < nbSeqs; i++) {
7659
        lSum += seqs[i].litLength;
7660
        mSum += seqs[i].matchLength;
7661
        if (seqs[i].matchLength == 0) break; /* end of block */
7662
    }
7663
7664
    if (i==nbSeqs) {
7665
        /* reaching end of sequences: end of block signal was not present */
7666
        BlockSummary bs;
7667
        bs.nbSequences = ERROR(externalSequences_invalid);
7668
        return bs;
7669
    }
7670
    {   BlockSummary bs;
7671
        bs.nbSequences = i+1;
7672
        bs.blockSize = lSum + mSum;
7673
        bs.litSize = lSum;
7674
        return bs;
7675
    }
7676
}
7677
7678
#elif defined ZSTD_ARCH_RISCV_RVV
7679
7680
BlockSummary ZSTD_get1BlockSummary(const ZSTD_Sequence* seqs, size_t nbSeqs)
7681
{
7682
    size_t totalMatchSize = 0;
7683
    size_t litSize = 0;
7684
    size_t i = 0;
7685
    int found_terminator = 0; 
7686
    size_t vl_max = __riscv_vsetvlmax_e32m1();
7687
    typedef uint32_t __attribute__((may_alias)) aliased_u32;
7688
    vuint32m1_t v_lit_sum = __riscv_vmv_v_x_u32m1(0, vl_max);
7689
    vuint32m1_t v_match_sum = __riscv_vmv_v_x_u32m1(0, vl_max);
7690
7691
    for (; i  < nbSeqs; ) {
7692
        size_t vl = __riscv_vsetvl_e32m2(nbSeqs - i); 
7693
7694
        vuint32m2x4_t v_tuple = __riscv_vlseg4e32_v_u32m2x4(
7695
            (const aliased_u32*)((const void*)&seqs[i]), 
7696
            vl
7697
        );
7698
        vuint32m2_t v_lit = __riscv_vget_v_u32m2x4_u32m2(v_tuple, 1);
7699
        vuint32m2_t v_match = __riscv_vget_v_u32m2x4_u32m2(v_tuple, 2);
7700
7701
        // Check if any element has a matchLength of 0
7702
        vbool16_t mask = __riscv_vmseq_vx_u32m2_b16(v_match, 0, vl);
7703
        int first_zero = __riscv_vfirst_m_b16(mask, vl);
7704
7705
        if (first_zero >= 0) {
7706
            // Find the first zero byte and set the effective length to that index + 1 to 
7707
            // recompute the cumulative vector length of literals and matches
7708
            vl = first_zero + 1;
7709
            
7710
            // recompute the cumulative vector length of literals and matches
7711
            v_lit_sum = __riscv_vredsum_vs_u32m2_u32m1(__riscv_vslidedown_vx_u32m2(v_lit, 0, vl), v_lit_sum, vl);
7712
            v_match_sum = __riscv_vredsum_vs_u32m2_u32m1(__riscv_vslidedown_vx_u32m2(v_match, 0, vl), v_match_sum, vl);
7713
7714
            i += vl;
7715
            found_terminator = 1; 
7716
            assert(seqs[i - 1].offset == 0);
7717
            break;
7718
        } else {
7719
7720
            v_lit_sum = __riscv_vredsum_vs_u32m2_u32m1(v_lit, v_lit_sum, vl);
7721
            v_match_sum = __riscv_vredsum_vs_u32m2_u32m1(v_match, v_match_sum, vl);
7722
            i += vl;
7723
        }
7724
    }
7725
    litSize = __riscv_vmv_x_s_u32m1_u32(v_lit_sum);
7726
    totalMatchSize = __riscv_vmv_x_s_u32m1_u32(v_match_sum);
7727
7728
    if (!found_terminator && i==nbSeqs) {
7729
        BlockSummary bs;
7730
        bs.nbSequences = ERROR(externalSequences_invalid);
7731
        return bs;
7732
    }
7733
    {   BlockSummary bs;
7734
        bs.nbSequences = i;
7735
        bs.blockSize = litSize + totalMatchSize;
7736
        bs.litSize = litSize;
7737
        return bs;
7738
    }
7739
}
7740
7741
#else
7742
7743
/*
7744
 * The function assumes `litMatchLength` is a packed 64-bit value where the
7745
 * lower 32 bits represent the match length. The check varies based on the
7746
 * system's endianness:
7747
 * - On little-endian systems, it verifies if the entire 64-bit value is at most
7748
 * 0xFFFFFFFF, indicating the match length (lower 32 bits) is zero.
7749
 * - On big-endian systems, it directly checks if the lower 32 bits are zero.
7750
 *
7751
 * @returns 1 if the match length is zero, 0 otherwise.
7752
 */
7753
FORCE_INLINE_TEMPLATE int matchLengthHalfIsZero(U64 litMatchLength)
7754
0
{
7755
0
    if (MEM_isLittleEndian()) {
7756
0
        return litMatchLength <= 0xFFFFFFFFULL;
7757
0
    } else {
7758
0
        return (U32)litMatchLength == 0;
7759
0
    }
7760
0
}
7761
7762
BlockSummary ZSTD_get1BlockSummary(const ZSTD_Sequence* seqs, size_t nbSeqs)
7763
0
{
7764
    /* Use multiple accumulators for efficient use of wide out-of-order machines. */
7765
0
    U64 litMatchSize0 = 0;
7766
0
    U64 litMatchSize1 = 0;
7767
0
    U64 litMatchSize2 = 0;
7768
0
    U64 litMatchSize3 = 0;
7769
0
    size_t n = 0;
7770
7771
0
    ZSTD_STATIC_ASSERT(offsetof(ZSTD_Sequence, litLength) + 4 == offsetof(ZSTD_Sequence, matchLength));
7772
0
    ZSTD_STATIC_ASSERT(offsetof(ZSTD_Sequence, matchLength) + 4 == offsetof(ZSTD_Sequence, rep));
7773
0
    assert(seqs);
7774
7775
0
    if (nbSeqs > 3) {
7776
        /* Process the input in 4 independent streams to reach high throughput. */
7777
0
        do {
7778
            /* Load `litLength` and `matchLength` as a packed `U64`. It is safe
7779
             * to use 64-bit unsigned arithmetic here because the sum of `litLength`
7780
             * and `matchLength` cannot exceed the block size, so the 32-bit
7781
             * subparts will never overflow. */
7782
0
            U64 litMatchLength = MEM_read64(&seqs[n].litLength);
7783
0
            litMatchSize0 += litMatchLength;
7784
0
            if (matchLengthHalfIsZero(litMatchLength)) {
7785
0
                assert(seqs[n].offset == 0);
7786
0
                goto _out;
7787
0
            }
7788
7789
0
            litMatchLength = MEM_read64(&seqs[n + 1].litLength);
7790
0
            litMatchSize1 += litMatchLength;
7791
0
            if (matchLengthHalfIsZero(litMatchLength)) {
7792
0
                n += 1;
7793
0
                assert(seqs[n].offset == 0);
7794
0
                goto _out;
7795
0
            }
7796
7797
0
            litMatchLength = MEM_read64(&seqs[n + 2].litLength);
7798
0
            litMatchSize2 += litMatchLength;
7799
0
            if (matchLengthHalfIsZero(litMatchLength)) {
7800
0
                n += 2;
7801
0
                assert(seqs[n].offset == 0);
7802
0
                goto _out;
7803
0
            }
7804
7805
0
            litMatchLength = MEM_read64(&seqs[n + 3].litLength);
7806
0
            litMatchSize3 += litMatchLength;
7807
0
            if (matchLengthHalfIsZero(litMatchLength)) {
7808
0
                n += 3;
7809
0
                assert(seqs[n].offset == 0);
7810
0
                goto _out;
7811
0
            }
7812
7813
0
            n += 4;
7814
0
        } while(n < nbSeqs - 3);
7815
0
    }
7816
7817
0
    for (; n < nbSeqs; n++) {
7818
0
        U64 litMatchLength = MEM_read64(&seqs[n].litLength);
7819
0
        litMatchSize0 += litMatchLength;
7820
0
        if (matchLengthHalfIsZero(litMatchLength)) {
7821
0
            assert(seqs[n].offset == 0);
7822
0
            goto _out;
7823
0
        }
7824
0
    }
7825
    /* At this point n == nbSeqs, so no end terminator. */
7826
0
    {   BlockSummary bs;
7827
0
        bs.nbSequences = ERROR(externalSequences_invalid);
7828
0
        return bs;
7829
0
    }
7830
0
_out:
7831
0
    litMatchSize0 += litMatchSize1 + litMatchSize2 + litMatchSize3;
7832
0
    {   BlockSummary bs;
7833
0
        bs.nbSequences = n + 1;
7834
0
        if (MEM_isLittleEndian()) {
7835
0
            bs.litSize = (U32)litMatchSize0;
7836
0
            bs.blockSize = bs.litSize + (litMatchSize0 >> 32);
7837
0
        } else {
7838
0
            bs.litSize = litMatchSize0 >> 32;
7839
0
            bs.blockSize = bs.litSize + (U32)litMatchSize0;
7840
0
        }
7841
0
        return bs;
7842
0
    }
7843
0
}
7844
#endif
7845
7846
7847
static size_t
7848
ZSTD_compressSequencesAndLiterals_internal(ZSTD_CCtx* cctx,
7849
                                void* dst, size_t dstCapacity,
7850
                          const ZSTD_Sequence* inSeqs, size_t nbSequences,
7851
                          const void* literals, size_t litSize, size_t srcSize)
7852
0
{
7853
0
    size_t remaining = srcSize;
7854
0
    size_t cSize = 0;
7855
0
    BYTE* op = (BYTE*)dst;
7856
0
    int const repcodeResolution = (cctx->appliedParams.searchForExternalRepcodes == ZSTD_ps_enable);
7857
0
    assert(cctx->appliedParams.searchForExternalRepcodes != ZSTD_ps_auto);
7858
7859
0
    DEBUGLOG(4, "ZSTD_compressSequencesAndLiterals_internal: nbSeqs=%zu, litSize=%zu", nbSequences, litSize);
7860
0
    RETURN_ERROR_IF(nbSequences == 0, externalSequences_invalid, "Requires at least 1 end-of-block");
7861
7862
    /* Special case: empty frame */
7863
0
    if ((nbSequences == 1) && (inSeqs[0].litLength == 0)) {
7864
0
        U32 const cBlockHeader24 = 1 /* last block */ + (((U32)bt_raw)<<1);
7865
0
        RETURN_ERROR_IF(dstCapacity<3, dstSize_tooSmall, "No room for empty frame block header");
7866
0
        MEM_writeLE24(op, cBlockHeader24);
7867
0
        op += ZSTD_blockHeaderSize;
7868
0
        dstCapacity -= ZSTD_blockHeaderSize;
7869
0
        cSize += ZSTD_blockHeaderSize;
7870
0
    }
7871
7872
0
    while (nbSequences) {
7873
0
        size_t compressedSeqsSize, cBlockSize, conversionStatus;
7874
0
        BlockSummary const block = ZSTD_get1BlockSummary(inSeqs, nbSequences);
7875
0
        U32 const lastBlock = (block.nbSequences == nbSequences);
7876
0
        FORWARD_IF_ERROR(block.nbSequences, "Error while trying to determine nb of sequences for a block");
7877
0
        assert(block.nbSequences <= nbSequences);
7878
0
        RETURN_ERROR_IF(block.litSize > litSize, externalSequences_invalid, "discrepancy: Sequences require more literals than present in buffer");
7879
0
        ZSTD_resetSeqStore(&cctx->seqStore);
7880
7881
0
        conversionStatus = ZSTD_convertBlockSequences(cctx,
7882
0
                            inSeqs, block.nbSequences,
7883
0
                            repcodeResolution);
7884
0
        FORWARD_IF_ERROR(conversionStatus, "Bad sequence conversion");
7885
0
        inSeqs += block.nbSequences;
7886
0
        nbSequences -= block.nbSequences;
7887
0
        remaining -= block.blockSize;
7888
7889
        /* Note: when blockSize is very small, other variant send it uncompressed.
7890
         * Here, we still send the sequences, because we don't have the original source to send it uncompressed.
7891
         * One could imagine in theory reproducing the source from the sequences,
7892
         * but that's complex and costly memory intensive, and goes against the objectives of this variant. */
7893
7894
0
        RETURN_ERROR_IF(dstCapacity < ZSTD_blockHeaderSize, dstSize_tooSmall, "not enough dstCapacity to write a new compressed block");
7895
7896
0
        compressedSeqsSize = ZSTD_entropyCompressSeqStore_internal(
7897
0
                                op + ZSTD_blockHeaderSize /* Leave space for block header */, dstCapacity - ZSTD_blockHeaderSize,
7898
0
                                literals, block.litSize,
7899
0
                                &cctx->seqStore,
7900
0
                                &cctx->blockState.prevCBlock->entropy, &cctx->blockState.nextCBlock->entropy,
7901
0
                                &cctx->appliedParams,
7902
0
                                cctx->tmpWorkspace, cctx->tmpWkspSize /* statically allocated in resetCCtx */,
7903
0
                                cctx->bmi2);
7904
0
        FORWARD_IF_ERROR(compressedSeqsSize, "Compressing sequences of block failed");
7905
        /* note: the spec forbids for any compressed block to be larger than maximum block size */
7906
0
        if (compressedSeqsSize > cctx->blockSizeMax) compressedSeqsSize = 0;
7907
0
        DEBUGLOG(5, "Compressed sequences size: %zu", compressedSeqsSize);
7908
0
        litSize -= block.litSize;
7909
0
        literals = (const char*)literals + block.litSize;
7910
7911
        /* Note: difficult to check source for RLE block when only Literals are provided,
7912
         * but it could be considered from analyzing the sequence directly */
7913
7914
0
        if (compressedSeqsSize == 0) {
7915
            /* Sending uncompressed blocks is out of reach, because the source is not provided.
7916
             * In theory, one could use the sequences to regenerate the source, like a decompressor,
7917
             * but it's complex, and memory hungry, killing the purpose of this variant.
7918
             * Current outcome: generate an error code.
7919
             */
7920
0
            RETURN_ERROR(cannotProduce_uncompressedBlock, "ZSTD_compressSequencesAndLiterals cannot generate an uncompressed block");
7921
0
        } else {
7922
0
            U32 cBlockHeader;
7923
0
            assert(compressedSeqsSize > 1); /* no RLE */
7924
            /* Error checking and repcodes update */
7925
0
            ZSTD_blockState_confirmRepcodesAndEntropyTables(&cctx->blockState);
7926
0
            if (cctx->blockState.prevCBlock->entropy.fse.offcode_repeatMode == FSE_repeat_valid)
7927
0
                cctx->blockState.prevCBlock->entropy.fse.offcode_repeatMode = FSE_repeat_check;
7928
7929
            /* Write block header into beginning of block*/
7930
0
            cBlockHeader = lastBlock + (((U32)bt_compressed)<<1) + (U32)(compressedSeqsSize << 3);
7931
0
            MEM_writeLE24(op, cBlockHeader);
7932
0
            cBlockSize = ZSTD_blockHeaderSize + compressedSeqsSize;
7933
0
            DEBUGLOG(5, "Writing out compressed block, size: %zu", cBlockSize);
7934
0
        }
7935
7936
0
        cSize += cBlockSize;
7937
0
        op += cBlockSize;
7938
0
        dstCapacity -= cBlockSize;
7939
0
        cctx->isFirstBlock = 0;
7940
0
        DEBUGLOG(5, "cSize running total: %zu (remaining dstCapacity=%zu)", cSize, dstCapacity);
7941
7942
0
        if (lastBlock) {
7943
0
            assert(nbSequences == 0);
7944
0
            break;
7945
0
        }
7946
0
    }
7947
7948
0
    RETURN_ERROR_IF(litSize != 0, externalSequences_invalid, "literals must be entirely and exactly consumed");
7949
0
    RETURN_ERROR_IF(remaining != 0, externalSequences_invalid, "Sequences must represent a total of exactly srcSize=%zu", srcSize);
7950
0
    DEBUGLOG(4, "cSize final total: %zu", cSize);
7951
0
    return cSize;
7952
0
}
7953
7954
size_t
7955
ZSTD_compressSequencesAndLiterals(ZSTD_CCtx* cctx,
7956
                    void* dst, size_t dstCapacity,
7957
                    const ZSTD_Sequence* inSeqs, size_t inSeqsSize,
7958
                    const void* literals, size_t litSize, size_t litCapacity,
7959
                    size_t decompressedSize)
7960
0
{
7961
0
    BYTE* op = (BYTE*)dst;
7962
0
    size_t cSize = 0;
7963
7964
    /* Transparent initialization stage, same as compressStream2() */
7965
0
    DEBUGLOG(4, "ZSTD_compressSequencesAndLiterals (dstCapacity=%zu)", dstCapacity);
7966
0
    assert(cctx != NULL);
7967
0
    if (litCapacity < litSize) {
7968
0
        RETURN_ERROR(workSpace_tooSmall, "literals buffer is not large enough: must be at least 8 bytes larger than litSize (risk of read out-of-bound)");
7969
0
    }
7970
0
    FORWARD_IF_ERROR(ZSTD_CCtx_init_compressStream2(cctx, ZSTD_e_end, decompressedSize), "CCtx initialization failed");
7971
7972
0
    if (cctx->appliedParams.blockDelimiters == ZSTD_sf_noBlockDelimiters) {
7973
0
        RETURN_ERROR(frameParameter_unsupported, "This mode is only compatible with explicit delimiters");
7974
0
    }
7975
0
    if (cctx->appliedParams.validateSequences) {
7976
0
        RETURN_ERROR(parameter_unsupported, "This mode is not compatible with Sequence validation");
7977
0
    }
7978
0
    if (cctx->appliedParams.fParams.checksumFlag) {
7979
0
        RETURN_ERROR(frameParameter_unsupported, "this mode is not compatible with frame checksum");
7980
0
    }
7981
7982
    /* Begin writing output, starting with frame header */
7983
0
    {   size_t const frameHeaderSize = ZSTD_writeFrameHeader(op, dstCapacity,
7984
0
                    &cctx->appliedParams, decompressedSize, cctx->dictID);
7985
0
        op += frameHeaderSize;
7986
0
        assert(frameHeaderSize <= dstCapacity);
7987
0
        dstCapacity -= frameHeaderSize;
7988
0
        cSize += frameHeaderSize;
7989
0
    }
7990
7991
    /* Now generate compressed blocks */
7992
0
    {   size_t const cBlocksSize = ZSTD_compressSequencesAndLiterals_internal(cctx,
7993
0
                                            op, dstCapacity,
7994
0
                                            inSeqs, inSeqsSize,
7995
0
                                            literals, litSize, decompressedSize);
7996
0
        FORWARD_IF_ERROR(cBlocksSize, "Compressing blocks failed!");
7997
0
        cSize += cBlocksSize;
7998
0
        assert(cBlocksSize <= dstCapacity);
7999
0
        dstCapacity -= cBlocksSize;
8000
0
    }
8001
8002
0
    DEBUGLOG(4, "Final compressed size: %zu", cSize);
8003
0
    return cSize;
8004
0
}
8005
8006
/*======   Finalize   ======*/
8007
8008
static ZSTD_inBuffer inBuffer_forEndFlush(const ZSTD_CStream* zcs)
8009
15.4k
{
8010
15.4k
    const ZSTD_inBuffer nullInput = { NULL, 0, 0 };
8011
15.4k
    const int stableInput = (zcs->appliedParams.inBufferMode == ZSTD_bm_stable);
8012
15.4k
    return stableInput ? zcs->expectedInBuffer : nullInput;
8013
15.4k
}
8014
8015
/*! ZSTD_flushStream() :
8016
 * @return : amount of data remaining to flush */
8017
size_t ZSTD_flushStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output)
8018
0
{
8019
0
    ZSTD_inBuffer input = inBuffer_forEndFlush(zcs);
8020
0
    input.size = input.pos; /* do not ingest more input during flush */
8021
0
    return ZSTD_compressStream2(zcs, output, &input, ZSTD_e_flush);
8022
0
}
8023
8024
size_t ZSTD_endStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output)
8025
15.4k
{
8026
15.4k
    ZSTD_inBuffer input = inBuffer_forEndFlush(zcs);
8027
15.4k
    size_t const remainingToFlush = ZSTD_compressStream2(zcs, output, &input, ZSTD_e_end);
8028
15.4k
    FORWARD_IF_ERROR(remainingToFlush , "ZSTD_compressStream2(,,ZSTD_e_end) failed");
8029
15.4k
    if (zcs->appliedParams.nbWorkers > 0) return remainingToFlush;   /* minimal estimation */
8030
    /* single thread mode : attempt to calculate remaining to flush more precisely */
8031
15.4k
    {   size_t const lastBlockSize = zcs->frameEnded ? 0 : ZSTD_BLOCKHEADERSIZE;
8032
15.4k
        size_t const checksumSize = (size_t)(zcs->frameEnded ? 0 : zcs->appliedParams.fParams.checksumFlag * 4);
8033
15.4k
        size_t const toFlush = remainingToFlush + lastBlockSize + checksumSize;
8034
15.4k
        DEBUGLOG(4, "ZSTD_endStream : remaining to flush : %u", (unsigned)toFlush);
8035
15.4k
        return toFlush;
8036
15.4k
    }
8037
15.4k
}
8038
8039
8040
/*-=====  Pre-defined compression levels  =====-*/
8041
#include "clevels.h"
8042
8043
27.6k
int ZSTD_maxCLevel(void) { return ZSTD_MAX_CLEVEL; }
8044
15.4k
int ZSTD_minCLevel(void) { return (int)-ZSTD_TARGETLENGTH_MAX; }
8045
0
int ZSTD_defaultCLevel(void) { return ZSTD_CLEVEL_DEFAULT; }
8046
8047
static ZSTD_compressionParameters ZSTD_dedicatedDictSearch_getCParams(int const compressionLevel, size_t const dictSize)
8048
0
{
8049
0
    ZSTD_compressionParameters cParams = ZSTD_getCParams_internal(compressionLevel, 0, dictSize, ZSTD_cpm_createCDict);
8050
0
    switch (cParams.strategy) {
8051
0
        case ZSTD_fast:
8052
0
        case ZSTD_dfast:
8053
0
            break;
8054
0
        case ZSTD_greedy:
8055
0
        case ZSTD_lazy:
8056
0
        case ZSTD_lazy2:
8057
0
            cParams.hashLog += ZSTD_LAZY_DDSS_BUCKET_LOG;
8058
0
            break;
8059
0
        case ZSTD_btlazy2:
8060
0
        case ZSTD_btopt:
8061
0
        case ZSTD_btultra:
8062
0
        case ZSTD_btultra2:
8063
0
            break;
8064
0
    }
8065
0
    return cParams;
8066
0
}
8067
8068
static int ZSTD_dedicatedDictSearch_isSupported(
8069
        ZSTD_compressionParameters const* cParams)
8070
0
{
8071
0
    return (cParams->strategy >= ZSTD_greedy)
8072
0
        && (cParams->strategy <= ZSTD_lazy2)
8073
0
        && (cParams->hashLog > cParams->chainLog)
8074
0
        && (cParams->chainLog <= 24);
8075
0
}
8076
8077
/**
8078
 * Reverses the adjustment applied to cparams when enabling dedicated dict
8079
 * search. This is used to recover the params set to be used in the working
8080
 * context. (Otherwise, those tables would also grow.)
8081
 */
8082
static void ZSTD_dedicatedDictSearch_revertCParams(
8083
0
        ZSTD_compressionParameters* cParams) {
8084
0
    switch (cParams->strategy) {
8085
0
        case ZSTD_fast:
8086
0
        case ZSTD_dfast:
8087
0
            break;
8088
0
        case ZSTD_greedy:
8089
0
        case ZSTD_lazy:
8090
0
        case ZSTD_lazy2:
8091
0
            cParams->hashLog -= ZSTD_LAZY_DDSS_BUCKET_LOG;
8092
0
            if (cParams->hashLog < ZSTD_HASHLOG_MIN) {
8093
0
                cParams->hashLog = ZSTD_HASHLOG_MIN;
8094
0
            }
8095
0
            break;
8096
0
        case ZSTD_btlazy2:
8097
0
        case ZSTD_btopt:
8098
0
        case ZSTD_btultra:
8099
0
        case ZSTD_btultra2:
8100
0
            break;
8101
0
    }
8102
0
}
8103
8104
static U64 ZSTD_getCParamRowSize(U64 srcSizeHint, size_t dictSize, ZSTD_CParamMode_e mode)
8105
15.4k
{
8106
15.4k
    switch (mode) {
8107
0
    case ZSTD_cpm_unknown:
8108
15.4k
    case ZSTD_cpm_noAttachDict:
8109
15.4k
    case ZSTD_cpm_createCDict:
8110
15.4k
        break;
8111
0
    case ZSTD_cpm_attachDict:
8112
0
        dictSize = 0;
8113
0
        break;
8114
0
    default:
8115
0
        assert(0);
8116
0
        break;
8117
15.4k
    }
8118
15.4k
    {   int const unknown = srcSizeHint == ZSTD_CONTENTSIZE_UNKNOWN;
8119
15.4k
        size_t const addedSize = unknown && dictSize > 0 ? 500 : 0;
8120
15.4k
        return unknown && dictSize == 0 ? ZSTD_CONTENTSIZE_UNKNOWN : srcSizeHint+dictSize+addedSize;
8121
15.4k
    }
8122
15.4k
}
8123
8124
/*! ZSTD_getCParams_internal() :
8125
 * @return ZSTD_compressionParameters structure for a selected compression level, srcSize and dictSize.
8126
 *  Note: srcSizeHint 0 means 0, use ZSTD_CONTENTSIZE_UNKNOWN for unknown.
8127
 *        Use dictSize == 0 for unknown or unused.
8128
 *  Note: `mode` controls how we treat the `dictSize`. See docs for `ZSTD_CParamMode_e`. */
8129
static ZSTD_compressionParameters ZSTD_getCParams_internal(int compressionLevel, unsigned long long srcSizeHint, size_t dictSize, ZSTD_CParamMode_e mode)
8130
15.4k
{
8131
15.4k
    U64 const rSize = ZSTD_getCParamRowSize(srcSizeHint, dictSize, mode);
8132
15.4k
    U32 const tableID = (rSize <= 256 KB) + (rSize <= 128 KB) + (rSize <= 16 KB);
8133
15.4k
    int row;
8134
15.4k
    DEBUGLOG(5, "ZSTD_getCParams_internal (cLevel=%i)", compressionLevel);
8135
8136
    /* row */
8137
15.4k
    if (compressionLevel == 0) row = ZSTD_CLEVEL_DEFAULT;   /* 0 == default */
8138
15.4k
    else if (compressionLevel < 0) row = 0;   /* entry 0 is baseline for fast mode */
8139
15.4k
    else if (compressionLevel > ZSTD_MAX_CLEVEL) row = ZSTD_MAX_CLEVEL;
8140
15.4k
    else row = compressionLevel;
8141
8142
15.4k
    {   ZSTD_compressionParameters cp = ZSTD_defaultCParameters[tableID][row];
8143
15.4k
        DEBUGLOG(5, "ZSTD_getCParams_internal selected tableID: %u row: %u strat: %u", tableID, row, (U32)cp.strategy);
8144
        /* acceleration factor */
8145
15.4k
        if (compressionLevel < 0) {
8146
0
            int const clampedCompressionLevel = MAX(ZSTD_minCLevel(), compressionLevel);
8147
0
            cp.targetLength = (unsigned)(-clampedCompressionLevel);
8148
0
        }
8149
        /* refine parameters based on srcSize & dictSize */
8150
15.4k
        return ZSTD_adjustCParams_internal(cp, srcSizeHint, dictSize, mode, ZSTD_ps_auto);
8151
15.4k
    }
8152
15.4k
}
8153
8154
/*! ZSTD_getCParams() :
8155
 * @return ZSTD_compressionParameters structure for a selected compression level, srcSize and dictSize.
8156
 *  Size values are optional, provide 0 if not known or unused */
8157
ZSTD_compressionParameters ZSTD_getCParams(int compressionLevel, unsigned long long srcSizeHint, size_t dictSize)
8158
0
{
8159
0
    if (srcSizeHint == 0) srcSizeHint = ZSTD_CONTENTSIZE_UNKNOWN;
8160
0
    return ZSTD_getCParams_internal(compressionLevel, srcSizeHint, dictSize, ZSTD_cpm_unknown);
8161
0
}
8162
8163
/*! ZSTD_getParams() :
8164
 *  same idea as ZSTD_getCParams()
8165
 * @return a `ZSTD_parameters` structure (instead of `ZSTD_compressionParameters`).
8166
 *  Fields of `ZSTD_frameParameters` are set to default values */
8167
static ZSTD_parameters
8168
ZSTD_getParams_internal(int compressionLevel, unsigned long long srcSizeHint, size_t dictSize, ZSTD_CParamMode_e mode)
8169
0
{
8170
0
    ZSTD_parameters params;
8171
0
    ZSTD_compressionParameters const cParams = ZSTD_getCParams_internal(compressionLevel, srcSizeHint, dictSize, mode);
8172
0
    DEBUGLOG(5, "ZSTD_getParams (cLevel=%i)", compressionLevel);
8173
0
    ZSTD_memset(&params, 0, sizeof(params));
8174
0
    params.cParams = cParams;
8175
0
    params.fParams.contentSizeFlag = 1;
8176
0
    return params;
8177
0
}
8178
8179
/*! ZSTD_getParams() :
8180
 *  same idea as ZSTD_getCParams()
8181
 * @return a `ZSTD_parameters` structure (instead of `ZSTD_compressionParameters`).
8182
 *  Fields of `ZSTD_frameParameters` are set to default values */
8183
ZSTD_parameters ZSTD_getParams(int compressionLevel, unsigned long long srcSizeHint, size_t dictSize)
8184
0
{
8185
0
    if (srcSizeHint == 0) srcSizeHint = ZSTD_CONTENTSIZE_UNKNOWN;
8186
0
    return ZSTD_getParams_internal(compressionLevel, srcSizeHint, dictSize, ZSTD_cpm_unknown);
8187
0
}
8188
8189
void ZSTD_registerSequenceProducer(
8190
    ZSTD_CCtx* zc,
8191
    void* extSeqProdState,
8192
    ZSTD_sequenceProducer_F extSeqProdFunc)
8193
0
{
8194
0
    assert(zc != NULL);
8195
0
    ZSTD_CCtxParams_registerSequenceProducer(
8196
0
        &zc->requestedParams, extSeqProdState, extSeqProdFunc
8197
0
    );
8198
0
}
8199
8200
void ZSTD_CCtxParams_registerSequenceProducer(
8201
  ZSTD_CCtx_params* params,
8202
  void* extSeqProdState,
8203
  ZSTD_sequenceProducer_F extSeqProdFunc)
8204
0
{
8205
0
    assert(params != NULL);
8206
0
    if (extSeqProdFunc != NULL) {
8207
0
        params->extSeqProdFunc = extSeqProdFunc;
8208
0
        params->extSeqProdState = extSeqProdState;
8209
0
    } else {
8210
0
        params->extSeqProdFunc = NULL;
8211
0
        params->extSeqProdState = NULL;
8212
0
    }
8213
0
}