Coverage Report

Created: 2026-06-07 06:27

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