Coverage Report

Created: 2026-09-14 07:37

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