Coverage Report

Created: 2025-06-20 06:13

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