Coverage Report

Created: 2025-08-28 07:58

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