Coverage Report

Created: 2025-03-15 06:58

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