Coverage Report

Created: 2026-12-01 06:39

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