Coverage Report

Created: 2022-08-24 06:40

/src/duckdb/third_party/zstd/compress/zstd_compress.cpp
Line
Count
Source (jump to first uncovered line)
1
/*
2
 * Copyright (c) 2016-2020, Yann Collet, Facebook, Inc.
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 <limits.h>         /* INT_MAX */
15
#include <string.h>         /* memset */
16
#include "zstd/common/mem.h"
17
#include "zstd/compress/hist.h"           /* HIST_countFast_wksp */
18
#include "zstd/common/fse.h"
19
#include "zstd/common/fse_static.h"
20
#include "zstd/common/huf.h"
21
#include "zstd/common/huf_static.h"
22
#include "zstd/compress/zstd_compress_internal.h"
23
#include "zstd/compress/zstd_compress_sequences.h"
24
#include "zstd/compress/zstd_compress_literals.h"
25
#include "zstd/compress/zstd_fast.h"
26
#include "zstd/compress/zstd_double_fast.h"
27
#include "zstd/compress/zstd_lazy.h"
28
#include "zstd/compress/zstd_opt.h"
29
#include "zstd/compress/zstd_ldm.h"
30
#include "zstd/compress/zstd_compress_superblock.h"
31
32
33
namespace duckdb_zstd {
34
/*-*************************************
35
*  Helper functions
36
***************************************/
37
/* ZSTD_compressBound()
38
 * Note that the result from this function is only compatible with the "normal"
39
 * full-block strategy.
40
 * When there are a lot of small blocks due to frequent flush in streaming mode
41
 * the overhead of headers can make the compressed data to be larger than the
42
 * return value of ZSTD_compressBound().
43
 */
44
0
size_t ZSTD_compressBound(size_t srcSize) {
45
0
    return ZSTD_COMPRESSBOUND(srcSize);
46
0
}
47
48
49
/*-*************************************
50
*  Context memory management
51
***************************************/
52
struct ZSTD_CDict_s {
53
    const void* dictContent;
54
    size_t dictContentSize;
55
    U32* entropyWorkspace; /* entropy workspace of HUF_WORKSPACE_SIZE bytes */
56
    ZSTD_cwksp workspace;
57
    ZSTD_matchState_t matchState;
58
    ZSTD_compressedBlockState_t cBlockState;
59
    ZSTD_customMem customMem;
60
    U32 dictID;
61
    int compressionLevel; /* 0 indicates that advanced API was used to select CDict params */
62
};  /* typedef'd to ZSTD_CDict within "zstd.h" */
63
64
ZSTD_CCtx* ZSTD_createCCtx(void)
65
0
{
66
0
    return ZSTD_createCCtx_advanced({NULL, NULL, NULL});
67
0
}
68
69
static void ZSTD_initCCtx(ZSTD_CCtx* cctx, ZSTD_customMem memManager)
70
0
{
71
0
    assert(cctx != NULL);
72
0
    memset(cctx, 0, sizeof(*cctx));
73
0
    cctx->customMem = memManager;
74
0
    cctx->bmi2 = 0;
75
0
    {   size_t const err = ZSTD_CCtx_reset(cctx, ZSTD_reset_parameters);
76
0
        assert(!ZSTD_isError(err));
77
0
        (void)err;
78
0
    }
79
0
}
80
81
ZSTD_CCtx* ZSTD_createCCtx_advanced(ZSTD_customMem customMem)
82
0
{
83
0
    ZSTD_STATIC_ASSERT(zcss_init==0);
84
0
    ZSTD_STATIC_ASSERT(ZSTD_CONTENTSIZE_UNKNOWN==(0ULL - 1));
85
0
    if (!customMem.customAlloc ^ !customMem.customFree) return NULL;
86
0
    {   ZSTD_CCtx* const cctx = (ZSTD_CCtx*)ZSTD_malloc(sizeof(ZSTD_CCtx), customMem);
87
0
        if (!cctx) return NULL;
88
0
        ZSTD_initCCtx(cctx, customMem);
89
0
        return cctx;
90
0
    }
91
0
}
92
93
ZSTD_CCtx* ZSTD_initStaticCCtx(void* workspace, size_t workspaceSize)
94
0
{
95
0
    ZSTD_cwksp ws;
96
0
    ZSTD_CCtx* cctx;
97
0
    if (workspaceSize <= sizeof(ZSTD_CCtx)) return NULL;  /* minimum size */
98
0
    if ((size_t)workspace & 7) return NULL;  /* must be 8-aligned */
99
0
    ZSTD_cwksp_init(&ws, workspace, workspaceSize);
100
101
0
    cctx = (ZSTD_CCtx*)ZSTD_cwksp_reserve_object(&ws, sizeof(ZSTD_CCtx));
102
0
    if (cctx == NULL) return NULL;
103
104
0
    memset(cctx, 0, sizeof(ZSTD_CCtx));
105
0
    ZSTD_cwksp_move(&cctx->workspace, &ws);
106
0
    cctx->staticSize = workspaceSize;
107
108
    /* statically sized space. entropyWorkspace never moves (but prev/next block swap places) */
109
0
    if (!ZSTD_cwksp_check_available(&cctx->workspace, HUF_WORKSPACE_SIZE + 2 * sizeof(ZSTD_compressedBlockState_t))) return NULL;
110
0
    cctx->blockState.prevCBlock = (ZSTD_compressedBlockState_t*)ZSTD_cwksp_reserve_object(&cctx->workspace, sizeof(ZSTD_compressedBlockState_t));
111
0
    cctx->blockState.nextCBlock = (ZSTD_compressedBlockState_t*)ZSTD_cwksp_reserve_object(&cctx->workspace, sizeof(ZSTD_compressedBlockState_t));
112
0
    cctx->entropyWorkspace = (U32*)ZSTD_cwksp_reserve_object(&cctx->workspace, HUF_WORKSPACE_SIZE);
113
0
    cctx->bmi2 = 0;
114
0
    return cctx;
115
0
}
116
117
/**
118
 * Clears and frees all of the dictionaries in the CCtx.
119
 */
120
static void ZSTD_clearAllDicts(ZSTD_CCtx* cctx)
121
0
{
122
0
    ZSTD_free(cctx->localDict.dictBuffer, cctx->customMem);
123
0
    ZSTD_freeCDict(cctx->localDict.cdict);
124
0
    memset(&cctx->localDict, 0, sizeof(cctx->localDict));
125
0
    memset(&cctx->prefixDict, 0, sizeof(cctx->prefixDict));
126
0
    cctx->cdict = NULL;
127
0
}
128
129
static size_t ZSTD_sizeof_localDict(ZSTD_localDict dict)
130
0
{
131
0
    size_t const bufferSize = dict.dictBuffer != NULL ? dict.dictSize : 0;
132
0
    size_t const cdictSize = ZSTD_sizeof_CDict(dict.cdict);
133
0
    return bufferSize + cdictSize;
134
0
}
135
136
static void ZSTD_freeCCtxContent(ZSTD_CCtx* cctx)
137
0
{
138
0
    assert(cctx != NULL);
139
0
    assert(cctx->staticSize == 0);
140
0
    ZSTD_clearAllDicts(cctx);
141
#ifdef ZSTD_MULTITHREAD
142
    ZSTDMT_freeCCtx(cctx->mtctx); cctx->mtctx = NULL;
143
#endif
144
0
    ZSTD_cwksp_free(&cctx->workspace, cctx->customMem);
145
0
}
146
147
size_t ZSTD_freeCCtx(ZSTD_CCtx* cctx)
148
0
{
149
0
    if (cctx==NULL) return 0;   /* support free on NULL */
150
0
    RETURN_ERROR_IF(cctx->staticSize, memory_allocation,
151
0
                    "not compatible with static CCtx");
152
0
    {
153
0
        int cctxInWorkspace = ZSTD_cwksp_owns_buffer(&cctx->workspace, cctx);
154
0
        ZSTD_freeCCtxContent(cctx);
155
0
        if (!cctxInWorkspace) {
156
0
            ZSTD_free(cctx, cctx->customMem);
157
0
        }
158
0
    }
159
0
    return 0;
160
0
}
161
162
163
static size_t ZSTD_sizeof_mtctx(const ZSTD_CCtx* cctx)
164
0
{
165
#ifdef ZSTD_MULTITHREAD
166
    return ZSTDMT_sizeof_CCtx(cctx->mtctx);
167
#else
168
0
    (void)cctx;
169
0
    return 0;
170
0
#endif
171
0
}
172
173
174
size_t ZSTD_sizeof_CCtx(const ZSTD_CCtx* cctx)
175
0
{
176
0
    if (cctx==NULL) return 0;   /* support sizeof on NULL */
177
    /* cctx may be in the workspace */
178
0
    return (cctx->workspace.workspace == cctx ? 0 : sizeof(*cctx))
179
0
           + ZSTD_cwksp_sizeof(&cctx->workspace)
180
0
           + ZSTD_sizeof_localDict(cctx->localDict)
181
0
           + ZSTD_sizeof_mtctx(cctx);
182
0
}
183
184
size_t ZSTD_sizeof_CStream(const ZSTD_CStream* zcs)
185
0
{
186
0
    return ZSTD_sizeof_CCtx(zcs);  /* same object */
187
0
}
188
189
/* private API call, for dictBuilder only */
190
0
const seqStore_t* ZSTD_getSeqStore(const ZSTD_CCtx* ctx) { return &(ctx->seqStore); }
191
192
static ZSTD_CCtx_params ZSTD_makeCCtxParamsFromCParams(
193
        ZSTD_compressionParameters cParams)
194
0
{
195
0
    ZSTD_CCtx_params cctxParams;
196
0
    memset(&cctxParams, 0, sizeof(cctxParams));
197
0
    cctxParams.cParams = cParams;
198
0
    cctxParams.compressionLevel = ZSTD_CLEVEL_DEFAULT;  /* should not matter, as all cParams are presumed properly defined */
199
0
    assert(!ZSTD_checkCParams(cParams));
200
0
    cctxParams.fParams.contentSizeFlag = 1;
201
0
    return cctxParams;
202
0
}
203
204
static ZSTD_CCtx_params* ZSTD_createCCtxParams_advanced(
205
        ZSTD_customMem customMem)
206
0
{
207
0
    ZSTD_CCtx_params* params;
208
0
    if (!customMem.customAlloc ^ !customMem.customFree) return NULL;
209
0
    params = (ZSTD_CCtx_params*)ZSTD_calloc(
210
0
            sizeof(ZSTD_CCtx_params), customMem);
211
0
    if (!params) { return NULL; }
212
0
    params->customMem = customMem;
213
0
    params->compressionLevel = ZSTD_CLEVEL_DEFAULT;
214
0
    params->fParams.contentSizeFlag = 1;
215
0
    return params;
216
0
}
217
218
ZSTD_CCtx_params* ZSTD_createCCtxParams(void)
219
0
{
220
0
    return ZSTD_createCCtxParams_advanced(ZSTDInternalConstants::ZSTD_defaultCMem);
221
0
}
222
223
size_t ZSTD_freeCCtxParams(ZSTD_CCtx_params* params)
224
0
{
225
0
    if (params == NULL) { return 0; }
226
0
    ZSTD_free(params, params->customMem);
227
0
    return 0;
228
0
}
229
230
size_t ZSTD_CCtxParams_reset(ZSTD_CCtx_params* params)
231
0
{
232
0
    return ZSTD_CCtxParams_init(params, ZSTD_CLEVEL_DEFAULT);
233
0
}
234
235
0
size_t ZSTD_CCtxParams_init(ZSTD_CCtx_params* cctxParams, int compressionLevel) {
236
0
    RETURN_ERROR_IF(!cctxParams, GENERIC, "NULL pointer!");
237
0
    memset(cctxParams, 0, sizeof(*cctxParams));
238
0
    cctxParams->compressionLevel = compressionLevel;
239
0
    cctxParams->fParams.contentSizeFlag = 1;
240
0
    return 0;
241
0
}
242
243
size_t ZSTD_CCtxParams_init_advanced(ZSTD_CCtx_params* cctxParams, ZSTD_parameters params)
244
0
{
245
0
    RETURN_ERROR_IF(!cctxParams, GENERIC, "NULL pointer!");
246
0
    FORWARD_IF_ERROR( ZSTD_checkCParams(params.cParams) , "");
247
0
    memset(cctxParams, 0, sizeof(*cctxParams));
248
0
    assert(!ZSTD_checkCParams(params.cParams));
249
0
    cctxParams->cParams = params.cParams;
250
0
    cctxParams->fParams = params.fParams;
251
0
    cctxParams->compressionLevel = ZSTD_CLEVEL_DEFAULT;   /* should not matter, as all cParams are presumed properly defined */
252
0
    return 0;
253
0
}
254
255
/* ZSTD_assignParamsToCCtxParams() :
256
 * params is presumed valid at this stage */
257
static ZSTD_CCtx_params ZSTD_assignParamsToCCtxParams(
258
        const ZSTD_CCtx_params* cctxParams, const ZSTD_parameters* params)
259
0
{
260
0
    ZSTD_CCtx_params ret = *cctxParams;
261
0
    assert(!ZSTD_checkCParams(params->cParams));
262
0
    ret.cParams = params->cParams;
263
0
    ret.fParams = params->fParams;
264
0
    ret.compressionLevel = ZSTD_CLEVEL_DEFAULT;   /* should not matter, as all cParams are presumed properly defined */
265
0
    return ret;
266
0
}
267
268
ZSTD_bounds ZSTD_cParam_getBounds(ZSTD_cParameter param)
269
0
{
270
0
    ZSTD_bounds bounds = { 0, 0, 0 };
271
272
0
    switch(param)
273
0
    {
274
0
    case ZSTD_c_compressionLevel:
275
0
        bounds.lowerBound = ZSTD_minCLevel();
276
0
        bounds.upperBound = ZSTD_maxCLevel();
277
0
        return bounds;
278
279
0
    case ZSTD_c_windowLog:
280
0
        bounds.lowerBound = ZSTD_WINDOWLOG_MIN;
281
0
        bounds.upperBound = ZSTD_WINDOWLOG_MAX;
282
0
        return bounds;
283
284
0
    case ZSTD_c_hashLog:
285
0
        bounds.lowerBound = ZSTD_HASHLOG_MIN;
286
0
        bounds.upperBound = ZSTD_HASHLOG_MAX;
287
0
        return bounds;
288
289
0
    case ZSTD_c_chainLog:
290
0
        bounds.lowerBound = ZSTD_CHAINLOG_MIN;
291
0
        bounds.upperBound = ZSTD_CHAINLOG_MAX;
292
0
        return bounds;
293
294
0
    case ZSTD_c_searchLog:
295
0
        bounds.lowerBound = ZSTD_SEARCHLOG_MIN;
296
0
        bounds.upperBound = ZSTD_SEARCHLOG_MAX;
297
0
        return bounds;
298
299
0
    case ZSTD_c_minMatch:
300
0
        bounds.lowerBound = ZSTD_MINMATCH_MIN;
301
0
        bounds.upperBound = ZSTD_MINMATCH_MAX;
302
0
        return bounds;
303
304
0
    case ZSTD_c_targetLength:
305
0
        bounds.lowerBound = ZSTD_TARGETLENGTH_MIN;
306
0
        bounds.upperBound = ZSTD_TARGETLENGTH_MAX;
307
0
        return bounds;
308
309
0
    case ZSTD_c_strategy:
310
0
        bounds.lowerBound = ZSTD_STRATEGY_MIN;
311
0
        bounds.upperBound = ZSTD_STRATEGY_MAX;
312
0
        return bounds;
313
314
0
    case ZSTD_c_contentSizeFlag:
315
0
        bounds.lowerBound = 0;
316
0
        bounds.upperBound = 1;
317
0
        return bounds;
318
319
0
    case ZSTD_c_checksumFlag:
320
0
        bounds.lowerBound = 0;
321
0
        bounds.upperBound = 1;
322
0
        return bounds;
323
324
0
    case ZSTD_c_dictIDFlag:
325
0
        bounds.lowerBound = 0;
326
0
        bounds.upperBound = 1;
327
0
        return bounds;
328
329
0
    case ZSTD_c_nbWorkers:
330
0
        bounds.lowerBound = 0;
331
#ifdef ZSTD_MULTITHREAD
332
        bounds.upperBound = ZSTDMT_NBWORKERS_MAX;
333
#else
334
0
        bounds.upperBound = 0;
335
0
#endif
336
0
        return bounds;
337
338
0
    case ZSTD_c_jobSize:
339
0
        bounds.lowerBound = 0;
340
#ifdef ZSTD_MULTITHREAD
341
        bounds.upperBound = ZSTDMT_JOBSIZE_MAX;
342
#else
343
0
        bounds.upperBound = 0;
344
0
#endif
345
0
        return bounds;
346
347
0
    case ZSTD_c_overlapLog:
348
#ifdef ZSTD_MULTITHREAD
349
        bounds.lowerBound = ZSTD_OVERLAPLOG_MIN;
350
        bounds.upperBound = ZSTD_OVERLAPLOG_MAX;
351
#else
352
0
        bounds.lowerBound = 0;
353
0
        bounds.upperBound = 0;
354
0
#endif
355
0
        return bounds;
356
357
0
    case ZSTD_c_enableLongDistanceMatching:
358
0
        bounds.lowerBound = 0;
359
0
        bounds.upperBound = 1;
360
0
        return bounds;
361
362
0
    case ZSTD_c_ldmHashLog:
363
0
        bounds.lowerBound = ZSTD_LDM_HASHLOG_MIN;
364
0
        bounds.upperBound = ZSTD_LDM_HASHLOG_MAX;
365
0
        return bounds;
366
367
0
    case ZSTD_c_ldmMinMatch:
368
0
        bounds.lowerBound = ZSTD_LDM_MINMATCH_MIN;
369
0
        bounds.upperBound = ZSTD_LDM_MINMATCH_MAX;
370
0
        return bounds;
371
372
0
    case ZSTD_c_ldmBucketSizeLog:
373
0
        bounds.lowerBound = ZSTD_LDM_BUCKETSIZELOG_MIN;
374
0
        bounds.upperBound = ZSTD_LDM_BUCKETSIZELOG_MAX;
375
0
        return bounds;
376
377
0
    case ZSTD_c_ldmHashRateLog:
378
0
        bounds.lowerBound = ZSTD_LDM_HASHRATELOG_MIN;
379
0
        bounds.upperBound = ZSTD_LDM_HASHRATELOG_MAX;
380
0
        return bounds;
381
382
    /* experimental parameters */
383
0
    case ZSTD_c_rsyncable:
384
0
        bounds.lowerBound = 0;
385
0
        bounds.upperBound = 1;
386
0
        return bounds;
387
388
0
    case ZSTD_c_forceMaxWindow :
389
0
        bounds.lowerBound = 0;
390
0
        bounds.upperBound = 1;
391
0
        return bounds;
392
393
0
    case ZSTD_c_format:
394
0
        ZSTD_STATIC_ASSERT(ZSTD_f_zstd1 < ZSTD_f_zstd1_magicless);
395
0
        bounds.lowerBound = ZSTD_f_zstd1;
396
0
        bounds.upperBound = ZSTD_f_zstd1_magicless;   /* note : how to ensure at compile time that this is the highest value enum ? */
397
0
        return bounds;
398
399
0
    case ZSTD_c_forceAttachDict:
400
0
        ZSTD_STATIC_ASSERT(ZSTD_dictDefaultAttach < ZSTD_dictForceCopy);
401
0
        bounds.lowerBound = ZSTD_dictDefaultAttach;
402
0
        bounds.upperBound = ZSTD_dictForceLoad;       /* note : how to ensure at compile time that this is the highest value enum ? */
403
0
        return bounds;
404
405
0
    case ZSTD_c_literalCompressionMode:
406
0
        ZSTD_STATIC_ASSERT(ZSTD_lcm_auto < ZSTD_lcm_huffman && ZSTD_lcm_huffman < ZSTD_lcm_uncompressed);
407
0
        bounds.lowerBound = ZSTD_lcm_auto;
408
0
        bounds.upperBound = ZSTD_lcm_uncompressed;
409
0
        return bounds;
410
411
0
    case ZSTD_c_targetCBlockSize:
412
0
        bounds.lowerBound = ZSTD_TARGETCBLOCKSIZE_MIN;
413
0
        bounds.upperBound = ZSTD_TARGETCBLOCKSIZE_MAX;
414
0
        return bounds;
415
416
0
    case ZSTD_c_srcSizeHint:
417
0
        bounds.lowerBound = ZSTD_SRCSIZEHINT_MIN;
418
0
        bounds.upperBound = ZSTD_SRCSIZEHINT_MAX;
419
0
        return bounds;
420
421
0
    default:
422
0
        bounds.error = ERROR(parameter_unsupported);
423
0
        return bounds;
424
0
    }
425
0
}
426
427
/* ZSTD_cParam_clampBounds:
428
 * Clamps the value into the bounded range.
429
 */
430
static size_t ZSTD_cParam_clampBounds(ZSTD_cParameter cParam, int* value)
431
0
{
432
0
    ZSTD_bounds const bounds = ZSTD_cParam_getBounds(cParam);
433
0
    if (ZSTD_isError(bounds.error)) return bounds.error;
434
0
    if (*value < bounds.lowerBound) *value = bounds.lowerBound;
435
0
    if (*value > bounds.upperBound) *value = bounds.upperBound;
436
0
    return 0;
437
0
}
438
439
0
#define BOUNDCHECK(cParam, val) { \
440
0
    RETURN_ERROR_IF(!ZSTD_cParam_withinBounds(cParam,val), \
441
0
                    parameter_outOfBound, "Param out of bounds"); \
442
0
}
443
444
445
static int ZSTD_isUpdateAuthorized(ZSTD_cParameter param)
446
0
{
447
0
    switch(param)
448
0
    {
449
0
    case ZSTD_c_compressionLevel:
450
0
    case ZSTD_c_hashLog:
451
0
    case ZSTD_c_chainLog:
452
0
    case ZSTD_c_searchLog:
453
0
    case ZSTD_c_minMatch:
454
0
    case ZSTD_c_targetLength:
455
0
    case ZSTD_c_strategy:
456
0
        return 1;
457
458
0
    case ZSTD_c_format:
459
0
    case ZSTD_c_windowLog:
460
0
    case ZSTD_c_contentSizeFlag:
461
0
    case ZSTD_c_checksumFlag:
462
0
    case ZSTD_c_dictIDFlag:
463
0
    case ZSTD_c_forceMaxWindow :
464
0
    case ZSTD_c_nbWorkers:
465
0
    case ZSTD_c_jobSize:
466
0
    case ZSTD_c_overlapLog:
467
0
    case ZSTD_c_rsyncable:
468
0
    case ZSTD_c_enableLongDistanceMatching:
469
0
    case ZSTD_c_ldmHashLog:
470
0
    case ZSTD_c_ldmMinMatch:
471
0
    case ZSTD_c_ldmBucketSizeLog:
472
0
    case ZSTD_c_ldmHashRateLog:
473
0
    case ZSTD_c_forceAttachDict:
474
0
    case ZSTD_c_literalCompressionMode:
475
0
    case ZSTD_c_targetCBlockSize:
476
0
    case ZSTD_c_srcSizeHint:
477
0
    default:
478
0
        return 0;
479
0
    }
480
0
}
481
482
size_t ZSTD_CCtx_setParameter(ZSTD_CCtx* cctx, ZSTD_cParameter param, int value)
483
0
{
484
0
    DEBUGLOG(4, "ZSTD_CCtx_setParameter (%i, %i)", (int)param, value);
485
0
    if (cctx->streamStage != zcss_init) {
486
0
        if (ZSTD_isUpdateAuthorized(param)) {
487
0
            cctx->cParamsChanged = 1;
488
0
        } else {
489
0
            RETURN_ERROR(stage_wrong, "can only set params in ctx init stage");
490
0
    }   }
491
492
0
    switch(param)
493
0
    {
494
0
    case ZSTD_c_nbWorkers:
495
0
        RETURN_ERROR_IF((value!=0) && cctx->staticSize, parameter_unsupported,
496
0
                        "MT not compatible with static alloc");
497
0
        break;
498
499
0
    case ZSTD_c_compressionLevel:
500
0
    case ZSTD_c_windowLog:
501
0
    case ZSTD_c_hashLog:
502
0
    case ZSTD_c_chainLog:
503
0
    case ZSTD_c_searchLog:
504
0
    case ZSTD_c_minMatch:
505
0
    case ZSTD_c_targetLength:
506
0
    case ZSTD_c_strategy:
507
0
    case ZSTD_c_ldmHashRateLog:
508
0
    case ZSTD_c_format:
509
0
    case ZSTD_c_contentSizeFlag:
510
0
    case ZSTD_c_checksumFlag:
511
0
    case ZSTD_c_dictIDFlag:
512
0
    case ZSTD_c_forceMaxWindow:
513
0
    case ZSTD_c_forceAttachDict:
514
0
    case ZSTD_c_literalCompressionMode:
515
0
    case ZSTD_c_jobSize:
516
0
    case ZSTD_c_overlapLog:
517
0
    case ZSTD_c_rsyncable:
518
0
    case ZSTD_c_enableLongDistanceMatching:
519
0
    case ZSTD_c_ldmHashLog:
520
0
    case ZSTD_c_ldmMinMatch:
521
0
    case ZSTD_c_ldmBucketSizeLog:
522
0
    case ZSTD_c_targetCBlockSize:
523
0
    case ZSTD_c_srcSizeHint:
524
0
        break;
525
526
0
    default: RETURN_ERROR(parameter_unsupported, "unknown parameter");
527
0
    }
528
0
    return ZSTD_CCtxParams_setParameter(&cctx->requestedParams, param, value);
529
0
}
530
531
size_t ZSTD_CCtxParams_setParameter(ZSTD_CCtx_params* CCtxParams,
532
                                    ZSTD_cParameter param, int value)
533
0
{
534
0
    DEBUGLOG(4, "ZSTD_CCtxParams_setParameter (%i, %i)", (int)param, value);
535
0
    switch(param)
536
0
    {
537
0
    case ZSTD_c_format :
538
0
        BOUNDCHECK(ZSTD_c_format, value);
539
0
        CCtxParams->format = (ZSTD_format_e)value;
540
0
        return (size_t)CCtxParams->format;
541
542
0
    case ZSTD_c_compressionLevel : {
543
0
        FORWARD_IF_ERROR(ZSTD_cParam_clampBounds(param, &value), "");
544
0
        if (value) {  /* 0 : does not change current level */
545
0
            CCtxParams->compressionLevel = value;
546
0
        }
547
0
        if (CCtxParams->compressionLevel >= 0) return (size_t)CCtxParams->compressionLevel;
548
0
        return 0;  /* return type (size_t) cannot represent negative values */
549
0
    }
550
551
0
    case ZSTD_c_windowLog :
552
0
        if (value!=0)   /* 0 => use default */
553
0
            BOUNDCHECK(ZSTD_c_windowLog, value);
554
0
        CCtxParams->cParams.windowLog = (U32)value;
555
0
        return CCtxParams->cParams.windowLog;
556
557
0
    case ZSTD_c_hashLog :
558
0
        if (value!=0)   /* 0 => use default */
559
0
            BOUNDCHECK(ZSTD_c_hashLog, value);
560
0
        CCtxParams->cParams.hashLog = (U32)value;
561
0
        return CCtxParams->cParams.hashLog;
562
563
0
    case ZSTD_c_chainLog :
564
0
        if (value!=0)   /* 0 => use default */
565
0
            BOUNDCHECK(ZSTD_c_chainLog, value);
566
0
        CCtxParams->cParams.chainLog = (U32)value;
567
0
        return CCtxParams->cParams.chainLog;
568
569
0
    case ZSTD_c_searchLog :
570
0
        if (value!=0)   /* 0 => use default */
571
0
            BOUNDCHECK(ZSTD_c_searchLog, value);
572
0
        CCtxParams->cParams.searchLog = (U32)value;
573
0
        return (size_t)value;
574
575
0
    case ZSTD_c_minMatch :
576
0
        if (value!=0)   /* 0 => use default */
577
0
            BOUNDCHECK(ZSTD_c_minMatch, value);
578
0
        CCtxParams->cParams.minMatch = value;
579
0
        return CCtxParams->cParams.minMatch;
580
581
0
    case ZSTD_c_targetLength :
582
0
        BOUNDCHECK(ZSTD_c_targetLength, value);
583
0
        CCtxParams->cParams.targetLength = value;
584
0
        return CCtxParams->cParams.targetLength;
585
586
0
    case ZSTD_c_strategy :
587
0
        if (value!=0)   /* 0 => use default */
588
0
            BOUNDCHECK(ZSTD_c_strategy, value);
589
0
        CCtxParams->cParams.strategy = (ZSTD_strategy)value;
590
0
        return (size_t)CCtxParams->cParams.strategy;
591
592
0
    case ZSTD_c_contentSizeFlag :
593
        /* Content size written in frame header _when known_ (default:1) */
594
0
        DEBUGLOG(4, "set content size flag = %u", (value!=0));
595
0
        CCtxParams->fParams.contentSizeFlag = value != 0;
596
0
        return CCtxParams->fParams.contentSizeFlag;
597
598
0
    case ZSTD_c_checksumFlag :
599
        /* A 32-bits content checksum will be calculated and written at end of frame (default:0) */
600
0
        CCtxParams->fParams.checksumFlag = value != 0;
601
0
        return CCtxParams->fParams.checksumFlag;
602
603
0
    case ZSTD_c_dictIDFlag : /* When applicable, dictionary's dictID is provided in frame header (default:1) */
604
0
        DEBUGLOG(4, "set dictIDFlag = %u", (value!=0));
605
0
        CCtxParams->fParams.noDictIDFlag = !value;
606
0
        return !CCtxParams->fParams.noDictIDFlag;
607
608
0
    case ZSTD_c_forceMaxWindow :
609
0
        CCtxParams->forceWindow = (value != 0);
610
0
        return CCtxParams->forceWindow;
611
612
0
    case ZSTD_c_forceAttachDict : {
613
0
        const ZSTD_dictAttachPref_e pref = (ZSTD_dictAttachPref_e)value;
614
0
        BOUNDCHECK(ZSTD_c_forceAttachDict, pref);
615
0
        CCtxParams->attachDictPref = pref;
616
0
        return CCtxParams->attachDictPref;
617
0
    }
618
619
0
    case ZSTD_c_literalCompressionMode : {
620
0
        const ZSTD_literalCompressionMode_e lcm = (ZSTD_literalCompressionMode_e)value;
621
0
        BOUNDCHECK(ZSTD_c_literalCompressionMode, lcm);
622
0
        CCtxParams->literalCompressionMode = lcm;
623
0
        return CCtxParams->literalCompressionMode;
624
0
    }
625
626
0
    case ZSTD_c_nbWorkers :
627
0
#ifndef ZSTD_MULTITHREAD
628
0
        RETURN_ERROR_IF(value!=0, parameter_unsupported, "not compiled with multithreading");
629
0
        return 0;
630
#else
631
        FORWARD_IF_ERROR(ZSTD_cParam_clampBounds(param, &value), "");
632
        CCtxParams->nbWorkers = value;
633
        return CCtxParams->nbWorkers;
634
#endif
635
636
0
    case ZSTD_c_jobSize :
637
0
#ifndef ZSTD_MULTITHREAD
638
0
        RETURN_ERROR_IF(value!=0, parameter_unsupported, "not compiled with multithreading");
639
0
        return 0;
640
#else
641
        /* Adjust to the minimum non-default value. */
642
        if (value != 0 && value < ZSTDMT_JOBSIZE_MIN)
643
            value = ZSTDMT_JOBSIZE_MIN;
644
        FORWARD_IF_ERROR(ZSTD_cParam_clampBounds(param, &value), "");
645
        assert(value >= 0);
646
        CCtxParams->jobSize = value;
647
        return CCtxParams->jobSize;
648
#endif
649
650
0
    case ZSTD_c_overlapLog :
651
0
#ifndef ZSTD_MULTITHREAD
652
0
        RETURN_ERROR_IF(value!=0, parameter_unsupported, "not compiled with multithreading");
653
0
        return 0;
654
#else
655
        FORWARD_IF_ERROR(ZSTD_cParam_clampBounds(ZSTD_c_overlapLog, &value), "");
656
        CCtxParams->overlapLog = value;
657
        return CCtxParams->overlapLog;
658
#endif
659
660
0
    case ZSTD_c_rsyncable :
661
0
#ifndef ZSTD_MULTITHREAD
662
0
        RETURN_ERROR_IF(value!=0, parameter_unsupported, "not compiled with multithreading");
663
0
        return 0;
664
#else
665
        FORWARD_IF_ERROR(ZSTD_cParam_clampBounds(ZSTD_c_overlapLog, &value), "");
666
        CCtxParams->rsyncable = value;
667
        return CCtxParams->rsyncable;
668
#endif
669
670
0
    case ZSTD_c_enableLongDistanceMatching :
671
0
        CCtxParams->ldmParams.enableLdm = (value!=0);
672
0
        return CCtxParams->ldmParams.enableLdm;
673
674
0
    case ZSTD_c_ldmHashLog :
675
0
        if (value!=0)   /* 0 ==> auto */
676
0
            BOUNDCHECK(ZSTD_c_ldmHashLog, value);
677
0
        CCtxParams->ldmParams.hashLog = value;
678
0
        return CCtxParams->ldmParams.hashLog;
679
680
0
    case ZSTD_c_ldmMinMatch :
681
0
        if (value!=0)   /* 0 ==> default */
682
0
            BOUNDCHECK(ZSTD_c_ldmMinMatch, value);
683
0
        CCtxParams->ldmParams.minMatchLength = value;
684
0
        return CCtxParams->ldmParams.minMatchLength;
685
686
0
    case ZSTD_c_ldmBucketSizeLog :
687
0
        if (value!=0)   /* 0 ==> default */
688
0
            BOUNDCHECK(ZSTD_c_ldmBucketSizeLog, value);
689
0
        CCtxParams->ldmParams.bucketSizeLog = value;
690
0
        return CCtxParams->ldmParams.bucketSizeLog;
691
692
0
    case ZSTD_c_ldmHashRateLog :
693
0
        RETURN_ERROR_IF(value > ZSTD_WINDOWLOG_MAX - ZSTD_HASHLOG_MIN,
694
0
                        parameter_outOfBound, "Param out of bounds!");
695
0
        CCtxParams->ldmParams.hashRateLog = value;
696
0
        return CCtxParams->ldmParams.hashRateLog;
697
698
0
    case ZSTD_c_targetCBlockSize :
699
0
        if (value!=0)   /* 0 ==> default */
700
0
            BOUNDCHECK(ZSTD_c_targetCBlockSize, value);
701
0
        CCtxParams->targetCBlockSize = value;
702
0
        return CCtxParams->targetCBlockSize;
703
704
0
    case ZSTD_c_srcSizeHint :
705
0
        if (value!=0)    /* 0 ==> default */
706
0
            BOUNDCHECK(ZSTD_c_srcSizeHint, value);
707
0
        CCtxParams->srcSizeHint = value;
708
0
        return CCtxParams->srcSizeHint;
709
710
0
    default: RETURN_ERROR(parameter_unsupported, "unknown parameter");
711
0
    }
712
0
}
713
714
size_t ZSTD_CCtx_getParameter(ZSTD_CCtx* cctx, ZSTD_cParameter param, int* value)
715
0
{
716
0
    return ZSTD_CCtxParams_getParameter(&cctx->requestedParams, param, value);
717
0
}
718
719
size_t ZSTD_CCtxParams_getParameter(
720
        ZSTD_CCtx_params* CCtxParams, ZSTD_cParameter param, int* value)
721
0
{
722
0
    switch(param)
723
0
    {
724
0
    case ZSTD_c_format :
725
0
        *value = CCtxParams->format;
726
0
        break;
727
0
    case ZSTD_c_compressionLevel :
728
0
        *value = CCtxParams->compressionLevel;
729
0
        break;
730
0
    case ZSTD_c_windowLog :
731
0
        *value = (int)CCtxParams->cParams.windowLog;
732
0
        break;
733
0
    case ZSTD_c_hashLog :
734
0
        *value = (int)CCtxParams->cParams.hashLog;
735
0
        break;
736
0
    case ZSTD_c_chainLog :
737
0
        *value = (int)CCtxParams->cParams.chainLog;
738
0
        break;
739
0
    case ZSTD_c_searchLog :
740
0
        *value = CCtxParams->cParams.searchLog;
741
0
        break;
742
0
    case ZSTD_c_minMatch :
743
0
        *value = CCtxParams->cParams.minMatch;
744
0
        break;
745
0
    case ZSTD_c_targetLength :
746
0
        *value = CCtxParams->cParams.targetLength;
747
0
        break;
748
0
    case ZSTD_c_strategy :
749
0
        *value = (unsigned)CCtxParams->cParams.strategy;
750
0
        break;
751
0
    case ZSTD_c_contentSizeFlag :
752
0
        *value = CCtxParams->fParams.contentSizeFlag;
753
0
        break;
754
0
    case ZSTD_c_checksumFlag :
755
0
        *value = CCtxParams->fParams.checksumFlag;
756
0
        break;
757
0
    case ZSTD_c_dictIDFlag :
758
0
        *value = !CCtxParams->fParams.noDictIDFlag;
759
0
        break;
760
0
    case ZSTD_c_forceMaxWindow :
761
0
        *value = CCtxParams->forceWindow;
762
0
        break;
763
0
    case ZSTD_c_forceAttachDict :
764
0
        *value = CCtxParams->attachDictPref;
765
0
        break;
766
0
    case ZSTD_c_literalCompressionMode :
767
0
        *value = CCtxParams->literalCompressionMode;
768
0
        break;
769
0
    case ZSTD_c_nbWorkers :
770
0
#ifndef ZSTD_MULTITHREAD
771
0
        assert(CCtxParams->nbWorkers == 0);
772
0
#endif
773
0
        *value = CCtxParams->nbWorkers;
774
0
        break;
775
0
    case ZSTD_c_jobSize :
776
0
#ifndef ZSTD_MULTITHREAD
777
0
        RETURN_ERROR(parameter_unsupported, "not compiled with multithreading");
778
#else
779
        assert(CCtxParams->jobSize <= INT_MAX);
780
        *value = (int)CCtxParams->jobSize;
781
        break;
782
#endif
783
0
    case ZSTD_c_overlapLog :
784
0
#ifndef ZSTD_MULTITHREAD
785
0
        RETURN_ERROR(parameter_unsupported, "not compiled with multithreading");
786
#else
787
        *value = CCtxParams->overlapLog;
788
        break;
789
#endif
790
0
    case ZSTD_c_rsyncable :
791
0
#ifndef ZSTD_MULTITHREAD
792
0
        RETURN_ERROR(parameter_unsupported, "not compiled with multithreading");
793
#else
794
        *value = CCtxParams->rsyncable;
795
        break;
796
#endif
797
0
    case ZSTD_c_enableLongDistanceMatching :
798
0
        *value = CCtxParams->ldmParams.enableLdm;
799
0
        break;
800
0
    case ZSTD_c_ldmHashLog :
801
0
        *value = CCtxParams->ldmParams.hashLog;
802
0
        break;
803
0
    case ZSTD_c_ldmMinMatch :
804
0
        *value = CCtxParams->ldmParams.minMatchLength;
805
0
        break;
806
0
    case ZSTD_c_ldmBucketSizeLog :
807
0
        *value = CCtxParams->ldmParams.bucketSizeLog;
808
0
        break;
809
0
    case ZSTD_c_ldmHashRateLog :
810
0
        *value = CCtxParams->ldmParams.hashRateLog;
811
0
        break;
812
0
    case ZSTD_c_targetCBlockSize :
813
0
        *value = (int)CCtxParams->targetCBlockSize;
814
0
        break;
815
0
    case ZSTD_c_srcSizeHint :
816
0
        *value = (int)CCtxParams->srcSizeHint;
817
0
        break;
818
0
    default: RETURN_ERROR(parameter_unsupported, "unknown parameter");
819
0
    }
820
0
    return 0;
821
0
}
822
823
/** ZSTD_CCtx_setParametersUsingCCtxParams() :
824
 *  just applies `params` into `cctx`
825
 *  no action is performed, parameters are merely stored.
826
 *  If ZSTDMT is enabled, parameters are pushed to cctx->mtctx.
827
 *    This is possible even if a compression is ongoing.
828
 *    In which case, new parameters will be applied on the fly, starting with next compression job.
829
 */
830
size_t ZSTD_CCtx_setParametersUsingCCtxParams(
831
        ZSTD_CCtx* cctx, const ZSTD_CCtx_params* params)
832
0
{
833
0
    DEBUGLOG(4, "ZSTD_CCtx_setParametersUsingCCtxParams");
834
0
    RETURN_ERROR_IF(cctx->streamStage != zcss_init, stage_wrong,
835
0
                    "The context is in the wrong stage!");
836
0
    RETURN_ERROR_IF(cctx->cdict, stage_wrong,
837
0
                    "Can't override parameters with cdict attached (some must "
838
0
                    "be inherited from the cdict).");
839
840
0
    cctx->requestedParams = *params;
841
0
    return 0;
842
0
}
843
844
ZSTDLIB_API size_t ZSTD_CCtx_setPledgedSrcSize(ZSTD_CCtx* cctx, unsigned long long pledgedSrcSize)
845
0
{
846
0
    DEBUGLOG(4, "ZSTD_CCtx_setPledgedSrcSize to %u bytes", (U32)pledgedSrcSize);
847
0
    RETURN_ERROR_IF(cctx->streamStage != zcss_init, stage_wrong,
848
0
                    "Can't set pledgedSrcSize when not in init stage.");
849
0
    cctx->pledgedSrcSizePlusOne = pledgedSrcSize+1;
850
0
    return 0;
851
0
}
852
853
/**
854
 * Initializes the local dict using the requested parameters.
855
 * NOTE: This does not use the pledged src size, because it may be used for more
856
 * than one compression.
857
 */
858
static size_t ZSTD_initLocalDict(ZSTD_CCtx* cctx)
859
0
{
860
0
    ZSTD_localDict* const dl = &cctx->localDict;
861
0
    ZSTD_compressionParameters const cParams = ZSTD_getCParamsFromCCtxParams(
862
0
            &cctx->requestedParams, ZSTD_CONTENTSIZE_UNKNOWN, dl->dictSize);
863
0
    if (dl->dict == NULL) {
864
        /* No local dictionary. */
865
0
        assert(dl->dictBuffer == NULL);
866
0
        assert(dl->cdict == NULL);
867
0
        assert(dl->dictSize == 0);
868
0
        return 0;
869
0
    }
870
0
    if (dl->cdict != NULL) {
871
0
        assert(cctx->cdict == dl->cdict);
872
        /* Local dictionary already initialized. */
873
0
        return 0;
874
0
    }
875
0
    assert(dl->dictSize > 0);
876
0
    assert(cctx->cdict == NULL);
877
0
    assert(cctx->prefixDict.dict == NULL);
878
879
0
    dl->cdict = ZSTD_createCDict_advanced(
880
0
            dl->dict,
881
0
            dl->dictSize,
882
0
            ZSTD_dlm_byRef,
883
0
            dl->dictContentType,
884
0
            cParams,
885
0
            cctx->customMem);
886
0
    RETURN_ERROR_IF(!dl->cdict, memory_allocation, "ZSTD_createCDict_advanced failed");
887
0
    cctx->cdict = dl->cdict;
888
0
    return 0;
889
0
}
890
891
size_t ZSTD_CCtx_loadDictionary_advanced(
892
        ZSTD_CCtx* cctx, const void* dict, size_t dictSize,
893
        ZSTD_dictLoadMethod_e dictLoadMethod, ZSTD_dictContentType_e dictContentType)
894
0
{
895
0
    RETURN_ERROR_IF(cctx->streamStage != zcss_init, stage_wrong,
896
0
                    "Can't load a dictionary when ctx is not in init stage.");
897
0
    RETURN_ERROR_IF(cctx->staticSize, memory_allocation,
898
0
                    "no malloc for static CCtx");
899
0
    DEBUGLOG(4, "ZSTD_CCtx_loadDictionary_advanced (size: %u)", (U32)dictSize);
900
0
    ZSTD_clearAllDicts(cctx);  /* in case one already exists */
901
0
    if (dict == NULL || dictSize == 0)  /* no dictionary mode */
902
0
        return 0;
903
0
    if (dictLoadMethod == ZSTD_dlm_byRef) {
904
0
        cctx->localDict.dict = dict;
905
0
    } else {
906
0
        void* dictBuffer = ZSTD_malloc(dictSize, cctx->customMem);
907
0
        RETURN_ERROR_IF(!dictBuffer, memory_allocation, "NULL pointer!");
908
0
        memcpy(dictBuffer, dict, dictSize);
909
0
        cctx->localDict.dictBuffer = dictBuffer;
910
0
        cctx->localDict.dict = dictBuffer;
911
0
    }
912
0
    cctx->localDict.dictSize = dictSize;
913
0
    cctx->localDict.dictContentType = dictContentType;
914
0
    return 0;
915
0
}
916
917
ZSTDLIB_API size_t ZSTD_CCtx_loadDictionary_byReference(
918
      ZSTD_CCtx* cctx, const void* dict, size_t dictSize)
919
0
{
920
0
    return ZSTD_CCtx_loadDictionary_advanced(
921
0
            cctx, dict, dictSize, ZSTD_dlm_byRef, ZSTD_dct_auto);
922
0
}
923
924
ZSTDLIB_API size_t ZSTD_CCtx_loadDictionary(ZSTD_CCtx* cctx, const void* dict, size_t dictSize)
925
0
{
926
0
    return ZSTD_CCtx_loadDictionary_advanced(
927
0
            cctx, dict, dictSize, ZSTD_dlm_byCopy, ZSTD_dct_auto);
928
0
}
929
930
931
size_t ZSTD_CCtx_refCDict(ZSTD_CCtx* cctx, const ZSTD_CDict* cdict)
932
0
{
933
0
    RETURN_ERROR_IF(cctx->streamStage != zcss_init, stage_wrong,
934
0
                    "Can't ref a dict when ctx not in init stage.");
935
    /* Free the existing local cdict (if any) to save memory. */
936
0
    ZSTD_clearAllDicts(cctx);
937
0
    cctx->cdict = cdict;
938
0
    return 0;
939
0
}
940
941
size_t ZSTD_CCtx_refPrefix(ZSTD_CCtx* cctx, const void* prefix, size_t prefixSize)
942
0
{
943
0
    return ZSTD_CCtx_refPrefix_advanced(cctx, prefix, prefixSize, ZSTD_dct_rawContent);
944
0
}
945
946
size_t ZSTD_CCtx_refPrefix_advanced(
947
        ZSTD_CCtx* cctx, const void* prefix, size_t prefixSize, ZSTD_dictContentType_e dictContentType)
948
0
{
949
0
    RETURN_ERROR_IF(cctx->streamStage != zcss_init, stage_wrong,
950
0
                    "Can't ref a prefix when ctx not in init stage.");
951
0
    ZSTD_clearAllDicts(cctx);
952
0
    if (prefix != NULL && prefixSize > 0) {
953
0
        cctx->prefixDict.dict = prefix;
954
0
        cctx->prefixDict.dictSize = prefixSize;
955
0
        cctx->prefixDict.dictContentType = dictContentType;
956
0
    }
957
0
    return 0;
958
0
}
959
960
/*! ZSTD_CCtx_reset() :
961
 *  Also dumps dictionary */
962
size_t ZSTD_CCtx_reset(ZSTD_CCtx* cctx, ZSTD_ResetDirective reset)
963
0
{
964
0
    if ( (reset == ZSTD_reset_session_only)
965
0
      || (reset == ZSTD_reset_session_and_parameters) ) {
966
0
        cctx->streamStage = zcss_init;
967
0
        cctx->pledgedSrcSizePlusOne = 0;
968
0
    }
969
0
    if ( (reset == ZSTD_reset_parameters)
970
0
      || (reset == ZSTD_reset_session_and_parameters) ) {
971
0
        RETURN_ERROR_IF(cctx->streamStage != zcss_init, stage_wrong,
972
0
                        "Can't reset parameters only when not in init stage.");
973
0
        ZSTD_clearAllDicts(cctx);
974
0
        return ZSTD_CCtxParams_reset(&cctx->requestedParams);
975
0
    }
976
0
    return 0;
977
0
}
978
979
980
/** ZSTD_checkCParams() :
981
    control CParam values remain within authorized range.
982
    @return : 0, or an error code if one value is beyond authorized range */
983
size_t ZSTD_checkCParams(ZSTD_compressionParameters cParams)
984
0
{
985
0
    BOUNDCHECK(ZSTD_c_windowLog, (int)cParams.windowLog);
986
0
    BOUNDCHECK(ZSTD_c_chainLog,  (int)cParams.chainLog);
987
0
    BOUNDCHECK(ZSTD_c_hashLog,   (int)cParams.hashLog);
988
0
    BOUNDCHECK(ZSTD_c_searchLog, (int)cParams.searchLog);
989
0
    BOUNDCHECK(ZSTD_c_minMatch,  (int)cParams.minMatch);
990
0
    BOUNDCHECK(ZSTD_c_targetLength,(int)cParams.targetLength);
991
0
    BOUNDCHECK(ZSTD_c_strategy,  cParams.strategy);
992
0
    return 0;
993
0
}
994
995
/** ZSTD_clampCParams() :
996
 *  make CParam values within valid range.
997
 *  @return : valid CParams */
998
static ZSTD_compressionParameters
999
ZSTD_clampCParams(ZSTD_compressionParameters cParams)
1000
0
{
1001
0
#   define CLAMP_TYPE(cParam, val, type) {                                \
1002
0
        ZSTD_bounds const bounds = ZSTD_cParam_getBounds(cParam);         \
1003
0
        if ((int)val<bounds.lowerBound) val=(type)bounds.lowerBound;      \
1004
0
        else if ((int)val>bounds.upperBound) val=(type)bounds.upperBound; \
1005
0
    }
1006
0
#   define CLAMP(cParam, val) CLAMP_TYPE(cParam, val, unsigned)
1007
0
    CLAMP(ZSTD_c_windowLog, cParams.windowLog);
1008
0
    CLAMP(ZSTD_c_chainLog,  cParams.chainLog);
1009
0
    CLAMP(ZSTD_c_hashLog,   cParams.hashLog);
1010
0
    CLAMP(ZSTD_c_searchLog, cParams.searchLog);
1011
0
    CLAMP(ZSTD_c_minMatch,  cParams.minMatch);
1012
0
    CLAMP(ZSTD_c_targetLength,cParams.targetLength);
1013
0
    CLAMP_TYPE(ZSTD_c_strategy,cParams.strategy, ZSTD_strategy);
1014
0
    return cParams;
1015
0
}
1016
1017
/** ZSTD_cycleLog() :
1018
 *  condition for correct operation : hashLog > 1 */
1019
U32 ZSTD_cycleLog(U32 hashLog, ZSTD_strategy strat)
1020
0
{
1021
0
    U32 const btScale = ((U32)strat >= (U32)ZSTD_btlazy2);
1022
0
    return hashLog - btScale;
1023
0
}
1024
1025
/** ZSTD_adjustCParams_internal() :
1026
 *  optimize `cPar` for a specified input (`srcSize` and `dictSize`).
1027
 *  mostly downsize to reduce memory consumption and initialization latency.
1028
 * `srcSize` can be ZSTD_CONTENTSIZE_UNKNOWN when not known.
1029
 *  note : `srcSize==0` means 0!
1030
 *  condition : cPar is presumed validated (can be checked using ZSTD_checkCParams()). */
1031
static ZSTD_compressionParameters
1032
ZSTD_adjustCParams_internal(ZSTD_compressionParameters cPar,
1033
                            unsigned long long srcSize,
1034
                            size_t dictSize)
1035
0
{
1036
0
    static const U64 minSrcSize = 513; /* (1<<9) + 1 */
1037
0
    static const U64 maxWindowResize = 1ULL << (ZSTD_WINDOWLOG_MAX-1);
1038
0
    assert(ZSTD_checkCParams(cPar)==0);
1039
1040
0
    if (dictSize && srcSize == ZSTD_CONTENTSIZE_UNKNOWN)
1041
0
        srcSize = minSrcSize;
1042
1043
    /* resize windowLog if input is small enough, to use less memory */
1044
0
    if ( (srcSize < maxWindowResize)
1045
0
      && (dictSize < maxWindowResize) )  {
1046
0
        U32 const tSize = (U32)(srcSize + dictSize);
1047
0
        static U32 const hashSizeMin = 1 << ZSTD_HASHLOG_MIN;
1048
0
        U32 const srcLog = (tSize < hashSizeMin) ? ZSTD_HASHLOG_MIN :
1049
0
                            ZSTD_highbit32(tSize-1) + 1;
1050
0
        if (cPar.windowLog > srcLog) cPar.windowLog = srcLog;
1051
0
    }
1052
0
    if (cPar.hashLog > cPar.windowLog+1) cPar.hashLog = cPar.windowLog+1;
1053
0
    {   U32 const cycleLog = ZSTD_cycleLog(cPar.chainLog, cPar.strategy);
1054
0
        if (cycleLog > cPar.windowLog)
1055
0
            cPar.chainLog -= (cycleLog - cPar.windowLog);
1056
0
    }
1057
1058
0
    if (cPar.windowLog < ZSTD_WINDOWLOG_ABSOLUTEMIN)
1059
0
        cPar.windowLog = ZSTD_WINDOWLOG_ABSOLUTEMIN;  /* minimum wlog required for valid frame header */
1060
1061
0
    return cPar;
1062
0
}
1063
1064
ZSTD_compressionParameters
1065
ZSTD_adjustCParams(ZSTD_compressionParameters cPar,
1066
                   unsigned long long srcSize,
1067
                   size_t dictSize)
1068
0
{
1069
0
    cPar = ZSTD_clampCParams(cPar);   /* resulting cPar is necessarily valid (all parameters within range) */
1070
0
    if (srcSize == 0) srcSize = ZSTD_CONTENTSIZE_UNKNOWN;
1071
0
    return ZSTD_adjustCParams_internal(cPar, srcSize, dictSize);
1072
0
}
1073
1074
static ZSTD_compressionParameters ZSTD_getCParams_internal(int compressionLevel, unsigned long long srcSizeHint, size_t dictSize);
1075
static ZSTD_parameters ZSTD_getParams_internal(int compressionLevel, unsigned long long srcSizeHint, size_t dictSize);
1076
1077
ZSTD_compressionParameters ZSTD_getCParamsFromCCtxParams(
1078
        const ZSTD_CCtx_params* CCtxParams, U64 srcSizeHint, size_t dictSize)
1079
0
{
1080
0
    ZSTD_compressionParameters cParams;
1081
0
    if (srcSizeHint == ZSTD_CONTENTSIZE_UNKNOWN && CCtxParams->srcSizeHint > 0) {
1082
0
      srcSizeHint = CCtxParams->srcSizeHint;
1083
0
    }
1084
0
    cParams = ZSTD_getCParams_internal(CCtxParams->compressionLevel, srcSizeHint, dictSize);
1085
0
    if (CCtxParams->ldmParams.enableLdm) cParams.windowLog = ZSTD_LDM_DEFAULT_WINDOW_LOG;
1086
0
    if (CCtxParams->cParams.windowLog) cParams.windowLog = CCtxParams->cParams.windowLog;
1087
0
    if (CCtxParams->cParams.hashLog) cParams.hashLog = CCtxParams->cParams.hashLog;
1088
0
    if (CCtxParams->cParams.chainLog) cParams.chainLog = CCtxParams->cParams.chainLog;
1089
0
    if (CCtxParams->cParams.searchLog) cParams.searchLog = CCtxParams->cParams.searchLog;
1090
0
    if (CCtxParams->cParams.minMatch) cParams.minMatch = CCtxParams->cParams.minMatch;
1091
0
    if (CCtxParams->cParams.targetLength) cParams.targetLength = CCtxParams->cParams.targetLength;
1092
0
    if (CCtxParams->cParams.strategy) cParams.strategy = CCtxParams->cParams.strategy;
1093
0
    assert(!ZSTD_checkCParams(cParams));
1094
    /* srcSizeHint == 0 means 0 */
1095
0
    return ZSTD_adjustCParams_internal(cParams, srcSizeHint, dictSize);
1096
0
}
1097
1098
static size_t
1099
ZSTD_sizeof_matchState(const ZSTD_compressionParameters* const cParams,
1100
                       const U32 forCCtx)
1101
0
{
1102
0
    size_t const chainSize = (cParams->strategy == ZSTD_fast) ? 0 : ((size_t)1 << cParams->chainLog);
1103
0
    size_t const hSize = ((size_t)1) << cParams->hashLog;
1104
0
    U32    const hashLog3 = (forCCtx && cParams->minMatch==3) ? MIN(ZSTD_HASHLOG3_MAX, cParams->windowLog) : 0;
1105
0
    size_t const h3Size = hashLog3 ? ((size_t)1) << hashLog3 : 0;
1106
    /* We don't use ZSTD_cwksp_alloc_size() here because the tables aren't
1107
     * surrounded by redzones in ASAN. */
1108
0
    size_t const tableSpace = chainSize * sizeof(U32)
1109
0
                            + hSize * sizeof(U32)
1110
0
                            + h3Size * sizeof(U32);
1111
0
    size_t const optPotentialSpace =
1112
0
        ZSTD_cwksp_alloc_size((MaxML+1) * sizeof(U32))
1113
0
      + ZSTD_cwksp_alloc_size((MaxLL+1) * sizeof(U32))
1114
0
      + ZSTD_cwksp_alloc_size((MaxOff+1) * sizeof(U32))
1115
0
      + ZSTD_cwksp_alloc_size((1<<Litbits) * sizeof(U32))
1116
0
      + ZSTD_cwksp_alloc_size((ZSTD_OPT_NUM+1) * sizeof(ZSTD_match_t))
1117
0
      + ZSTD_cwksp_alloc_size((ZSTD_OPT_NUM+1) * sizeof(ZSTD_optimal_t));
1118
0
    size_t const optSpace = (forCCtx && (cParams->strategy >= ZSTD_btopt))
1119
0
                                ? optPotentialSpace
1120
0
                                : 0;
1121
0
    DEBUGLOG(4, "chainSize: %u - hSize: %u - h3Size: %u",
1122
0
                (U32)chainSize, (U32)hSize, (U32)h3Size);
1123
0
    return tableSpace + optSpace;
1124
0
}
1125
1126
size_t ZSTD_estimateCCtxSize_usingCCtxParams(const ZSTD_CCtx_params* params)
1127
0
{
1128
0
    RETURN_ERROR_IF(params->nbWorkers > 0, GENERIC, "Estimate CCtx size is supported for single-threaded compression only.");
1129
0
    {   ZSTD_compressionParameters const cParams =
1130
0
                ZSTD_getCParamsFromCCtxParams(params, ZSTD_CONTENTSIZE_UNKNOWN, 0);
1131
0
        size_t const blockSize = MIN(ZSTD_BLOCKSIZE_MAX, (size_t)1 << cParams.windowLog);
1132
0
        U32    const divider = (cParams.minMatch==3) ? 3 : 4;
1133
0
        size_t const maxNbSeq = blockSize / divider;
1134
0
        size_t const tokenSpace = ZSTD_cwksp_alloc_size(WILDCOPY_OVERLENGTH + blockSize)
1135
0
                                + ZSTD_cwksp_alloc_size(maxNbSeq * sizeof(seqDef))
1136
0
                                + 3 * ZSTD_cwksp_alloc_size(maxNbSeq * sizeof(BYTE));
1137
0
        size_t const entropySpace = ZSTD_cwksp_alloc_size(HUF_WORKSPACE_SIZE);
1138
0
        size_t const blockStateSpace = 2 * ZSTD_cwksp_alloc_size(sizeof(ZSTD_compressedBlockState_t));
1139
0
        size_t const matchStateSize = ZSTD_sizeof_matchState(&cParams, /* forCCtx */ 1);
1140
1141
0
        size_t const ldmSpace = ZSTD_ldm_getTableSize(params->ldmParams);
1142
0
        size_t const ldmSeqSpace = ZSTD_cwksp_alloc_size(ZSTD_ldm_getMaxNbSeq(params->ldmParams, blockSize) * sizeof(rawSeq));
1143
1144
        /* estimateCCtxSize is for one-shot compression. So no buffers should
1145
         * be needed. However, we still allocate two 0-sized buffers, which can
1146
         * take space under ASAN. */
1147
0
        size_t const bufferSpace = ZSTD_cwksp_alloc_size(0)
1148
0
                                 + ZSTD_cwksp_alloc_size(0);
1149
1150
0
        size_t const cctxSpace = ZSTD_cwksp_alloc_size(sizeof(ZSTD_CCtx));
1151
1152
0
        size_t const neededSpace =
1153
0
            cctxSpace +
1154
0
            entropySpace +
1155
0
            blockStateSpace +
1156
0
            ldmSpace +
1157
0
            ldmSeqSpace +
1158
0
            matchStateSize +
1159
0
            tokenSpace +
1160
0
            bufferSpace;
1161
1162
0
        DEBUGLOG(5, "estimate workspace : %u", (U32)neededSpace);
1163
0
        return neededSpace;
1164
0
    }
1165
0
}
1166
1167
size_t ZSTD_estimateCCtxSize_usingCParams(ZSTD_compressionParameters cParams)
1168
0
{
1169
0
    ZSTD_CCtx_params const params = ZSTD_makeCCtxParamsFromCParams(cParams);
1170
0
    return ZSTD_estimateCCtxSize_usingCCtxParams(&params);
1171
0
}
1172
1173
static size_t ZSTD_estimateCCtxSize_internal(int compressionLevel)
1174
0
{
1175
0
    ZSTD_compressionParameters const cParams = ZSTD_getCParams_internal(compressionLevel, ZSTD_CONTENTSIZE_UNKNOWN, 0);
1176
0
    return ZSTD_estimateCCtxSize_usingCParams(cParams);
1177
0
}
1178
1179
size_t ZSTD_estimateCCtxSize(int compressionLevel)
1180
0
{
1181
0
    int level;
1182
0
    size_t memBudget = 0;
1183
0
    for (level=MIN(compressionLevel, 1); level<=compressionLevel; level++) {
1184
0
        size_t const newMB = ZSTD_estimateCCtxSize_internal(level);
1185
0
        if (newMB > memBudget) memBudget = newMB;
1186
0
    }
1187
0
    return memBudget;
1188
0
}
1189
1190
size_t ZSTD_estimateCStreamSize_usingCCtxParams(const ZSTD_CCtx_params* params)
1191
0
{
1192
0
    RETURN_ERROR_IF(params->nbWorkers > 0, GENERIC, "Estimate CCtx size is supported for single-threaded compression only.");
1193
0
    {   ZSTD_compressionParameters const cParams =
1194
0
                ZSTD_getCParamsFromCCtxParams(params, ZSTD_CONTENTSIZE_UNKNOWN, 0);
1195
0
        size_t const CCtxSize = ZSTD_estimateCCtxSize_usingCCtxParams(params);
1196
0
        size_t const blockSize = MIN(ZSTD_BLOCKSIZE_MAX, (size_t)1 << cParams.windowLog);
1197
0
        size_t const inBuffSize = ((size_t)1 << cParams.windowLog) + blockSize;
1198
0
        size_t const outBuffSize = ZSTD_compressBound(blockSize) + 1;
1199
0
        size_t const streamingSize = ZSTD_cwksp_alloc_size(inBuffSize)
1200
0
                                   + ZSTD_cwksp_alloc_size(outBuffSize);
1201
1202
0
        return CCtxSize + streamingSize;
1203
0
    }
1204
0
}
1205
1206
size_t ZSTD_estimateCStreamSize_usingCParams(ZSTD_compressionParameters cParams)
1207
0
{
1208
0
    ZSTD_CCtx_params const params = ZSTD_makeCCtxParamsFromCParams(cParams);
1209
0
    return ZSTD_estimateCStreamSize_usingCCtxParams(&params);
1210
0
}
1211
1212
static size_t ZSTD_estimateCStreamSize_internal(int compressionLevel)
1213
0
{
1214
0
    ZSTD_compressionParameters const cParams = ZSTD_getCParams_internal(compressionLevel, ZSTD_CONTENTSIZE_UNKNOWN, 0);
1215
0
    return ZSTD_estimateCStreamSize_usingCParams(cParams);
1216
0
}
1217
1218
size_t ZSTD_estimateCStreamSize(int compressionLevel)
1219
0
{
1220
0
    int level;
1221
0
    size_t memBudget = 0;
1222
0
    for (level=MIN(compressionLevel, 1); level<=compressionLevel; level++) {
1223
0
        size_t const newMB = ZSTD_estimateCStreamSize_internal(level);
1224
0
        if (newMB > memBudget) memBudget = newMB;
1225
0
    }
1226
0
    return memBudget;
1227
0
}
1228
1229
/* ZSTD_getFrameProgression():
1230
 * tells how much data has been consumed (input) and produced (output) for current frame.
1231
 * able to count progression inside worker threads (non-blocking mode).
1232
 */
1233
ZSTD_frameProgression ZSTD_getFrameProgression(const ZSTD_CCtx* cctx)
1234
0
{
1235
#ifdef ZSTD_MULTITHREAD
1236
    if (cctx->appliedParams.nbWorkers > 0) {
1237
        return ZSTDMT_getFrameProgression(cctx->mtctx);
1238
    }
1239
#endif
1240
0
    {   ZSTD_frameProgression fp;
1241
0
        size_t const buffered = (cctx->inBuff == NULL) ? 0 :
1242
0
                                cctx->inBuffPos - cctx->inToCompress;
1243
0
        if (buffered) assert(cctx->inBuffPos >= cctx->inToCompress);
1244
0
        assert(buffered <= ZSTD_BLOCKSIZE_MAX);
1245
0
        fp.ingested = cctx->consumedSrcSize + buffered;
1246
0
        fp.consumed = cctx->consumedSrcSize;
1247
0
        fp.produced = cctx->producedCSize;
1248
0
        fp.flushed  = cctx->producedCSize;   /* simplified; some data might still be left within streaming output buffer */
1249
0
        fp.currentJobID = 0;
1250
0
        fp.nbActiveWorkers = 0;
1251
0
        return fp;
1252
0
}   }
1253
1254
/*! ZSTD_toFlushNow()
1255
 *  Only useful for multithreading scenarios currently (nbWorkers >= 1).
1256
 */
1257
size_t ZSTD_toFlushNow(ZSTD_CCtx* cctx)
1258
0
{
1259
#ifdef ZSTD_MULTITHREAD
1260
    if (cctx->appliedParams.nbWorkers > 0) {
1261
        return ZSTDMT_toFlushNow(cctx->mtctx);
1262
    }
1263
#endif
1264
0
    (void)cctx;
1265
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 */
1266
0
}
1267
1268
static void ZSTD_assertEqualCParams(ZSTD_compressionParameters cParams1,
1269
                                    ZSTD_compressionParameters cParams2)
1270
0
{
1271
0
    (void)cParams1;
1272
0
    (void)cParams2;
1273
0
    assert(cParams1.windowLog    == cParams2.windowLog);
1274
0
    assert(cParams1.chainLog     == cParams2.chainLog);
1275
0
    assert(cParams1.hashLog      == cParams2.hashLog);
1276
0
    assert(cParams1.searchLog    == cParams2.searchLog);
1277
0
    assert(cParams1.minMatch     == cParams2.minMatch);
1278
0
    assert(cParams1.targetLength == cParams2.targetLength);
1279
0
    assert(cParams1.strategy     == cParams2.strategy);
1280
0
}
1281
1282
void ZSTD_reset_compressedBlockState(ZSTD_compressedBlockState_t* bs)
1283
0
{
1284
0
    int i;
1285
0
    for (i = 0; i < ZSTD_REP_NUM; ++i)
1286
0
        bs->rep[i] = ZSTDInternalConstants::repStartValue[i];
1287
0
    bs->entropy.huf.repeatMode = HUF_repeat_none;
1288
0
    bs->entropy.fse.offcode_repeatMode = FSE_repeat_none;
1289
0
    bs->entropy.fse.matchlength_repeatMode = FSE_repeat_none;
1290
0
    bs->entropy.fse.litlength_repeatMode = FSE_repeat_none;
1291
0
}
1292
1293
/*! ZSTD_invalidateMatchState()
1294
 *  Invalidate all the matches in the match finder tables.
1295
 *  Requires nextSrc and base to be set (can be NULL).
1296
 */
1297
static void ZSTD_invalidateMatchState(ZSTD_matchState_t* ms)
1298
0
{
1299
0
    ZSTD_window_clear(&ms->window);
1300
1301
0
    ms->nextToUpdate = ms->window.dictLimit;
1302
0
    ms->loadedDictEnd = 0;
1303
0
    ms->opt.litLengthSum = 0;  /* force reset of btopt stats */
1304
0
    ms->dictMatchState = NULL;
1305
0
}
1306
1307
/**
1308
 * Indicates whether this compression proceeds directly from user-provided
1309
 * source buffer to user-provided destination buffer (ZSTDb_not_buffered), or
1310
 * whether the context needs to buffer the input/output (ZSTDb_buffered).
1311
 */
1312
typedef enum {
1313
    ZSTDb_not_buffered,
1314
    ZSTDb_buffered
1315
} ZSTD_buffered_policy_e;
1316
1317
/**
1318
 * Controls, for this matchState reset, whether the tables need to be cleared /
1319
 * prepared for the coming compression (ZSTDcrp_makeClean), or whether the
1320
 * tables can be left unclean (ZSTDcrp_leaveDirty), because we know that a
1321
 * subsequent operation will overwrite the table space anyways (e.g., copying
1322
 * the matchState contents in from a CDict).
1323
 */
1324
typedef enum {
1325
    ZSTDcrp_makeClean,
1326
    ZSTDcrp_leaveDirty
1327
} ZSTD_compResetPolicy_e;
1328
1329
/**
1330
 * Controls, for this matchState reset, whether indexing can continue where it
1331
 * left off (ZSTDirp_continue), or whether it needs to be restarted from zero
1332
 * (ZSTDirp_reset).
1333
 */
1334
typedef enum {
1335
    ZSTDirp_continue,
1336
    ZSTDirp_reset
1337
} ZSTD_indexResetPolicy_e;
1338
1339
typedef enum {
1340
    ZSTD_resetTarget_CDict,
1341
    ZSTD_resetTarget_CCtx
1342
} ZSTD_resetTarget_e;
1343
1344
static size_t
1345
ZSTD_reset_matchState(ZSTD_matchState_t* ms,
1346
                      ZSTD_cwksp* ws,
1347
                const ZSTD_compressionParameters* cParams,
1348
                const ZSTD_compResetPolicy_e crp,
1349
                const ZSTD_indexResetPolicy_e forceResetIndex,
1350
                const ZSTD_resetTarget_e forWho)
1351
0
{
1352
0
    size_t const chainSize = (cParams->strategy == ZSTD_fast) ? 0 : ((size_t)1 << cParams->chainLog);
1353
0
    size_t const hSize = ((size_t)1) << cParams->hashLog;
1354
0
    U32    const hashLog3 = ((forWho == ZSTD_resetTarget_CCtx) && cParams->minMatch==3) ? MIN(ZSTD_HASHLOG3_MAX, cParams->windowLog) : 0;
1355
0
    size_t const h3Size = hashLog3 ? ((size_t)1) << hashLog3 : 0;
1356
1357
0
    DEBUGLOG(4, "reset indices : %u", forceResetIndex == ZSTDirp_reset);
1358
0
    if (forceResetIndex == ZSTDirp_reset) {
1359
0
        ZSTD_window_init(&ms->window);
1360
0
        ZSTD_cwksp_mark_tables_dirty(ws);
1361
0
    }
1362
1363
0
    ms->hashLog3 = hashLog3;
1364
1365
0
    ZSTD_invalidateMatchState(ms);
1366
1367
0
    assert(!ZSTD_cwksp_reserve_failed(ws)); /* check that allocation hasn't already failed */
1368
1369
0
    ZSTD_cwksp_clear_tables(ws);
1370
1371
0
    DEBUGLOG(5, "reserving table space");
1372
    /* table Space */
1373
0
    ms->hashTable = (U32*)ZSTD_cwksp_reserve_table(ws, hSize * sizeof(U32));
1374
0
    ms->chainTable = (U32*)ZSTD_cwksp_reserve_table(ws, chainSize * sizeof(U32));
1375
0
    ms->hashTable3 = (U32*)ZSTD_cwksp_reserve_table(ws, h3Size * sizeof(U32));
1376
0
    RETURN_ERROR_IF(ZSTD_cwksp_reserve_failed(ws), memory_allocation,
1377
0
                    "failed a workspace allocation in ZSTD_reset_matchState");
1378
1379
0
    DEBUGLOG(4, "reset table : %u", crp!=ZSTDcrp_leaveDirty);
1380
0
    if (crp!=ZSTDcrp_leaveDirty) {
1381
        /* reset tables only */
1382
0
        ZSTD_cwksp_clean_tables(ws);
1383
0
    }
1384
1385
    /* opt parser space */
1386
0
    if ((forWho == ZSTD_resetTarget_CCtx) && (cParams->strategy >= ZSTD_btopt)) {
1387
0
        DEBUGLOG(4, "reserving optimal parser space");
1388
0
        ms->opt.litFreq = (unsigned*)ZSTD_cwksp_reserve_aligned(ws, (1<<Litbits) * sizeof(unsigned));
1389
0
        ms->opt.litLengthFreq = (unsigned*)ZSTD_cwksp_reserve_aligned(ws, (MaxLL+1) * sizeof(unsigned));
1390
0
        ms->opt.matchLengthFreq = (unsigned*)ZSTD_cwksp_reserve_aligned(ws, (MaxML+1) * sizeof(unsigned));
1391
0
        ms->opt.offCodeFreq = (unsigned*)ZSTD_cwksp_reserve_aligned(ws, (MaxOff+1) * sizeof(unsigned));
1392
0
        ms->opt.matchTable = (ZSTD_match_t*)ZSTD_cwksp_reserve_aligned(ws, (ZSTD_OPT_NUM+1) * sizeof(ZSTD_match_t));
1393
0
        ms->opt.priceTable = (ZSTD_optimal_t*)ZSTD_cwksp_reserve_aligned(ws, (ZSTD_OPT_NUM+1) * sizeof(ZSTD_optimal_t));
1394
0
    }
1395
1396
0
    ms->cParams = *cParams;
1397
1398
0
    RETURN_ERROR_IF(ZSTD_cwksp_reserve_failed(ws), memory_allocation,
1399
0
                    "failed a workspace allocation in ZSTD_reset_matchState");
1400
1401
0
    return 0;
1402
0
}
1403
1404
/* ZSTD_indexTooCloseToMax() :
1405
 * minor optimization : prefer memset() rather than reduceIndex()
1406
 * which is measurably slow in some circumstances (reported for Visual Studio).
1407
 * Works when re-using a context for a lot of smallish inputs :
1408
 * if all inputs are smaller than ZSTD_INDEXOVERFLOW_MARGIN,
1409
 * memset() will be triggered before reduceIndex().
1410
 */
1411
0
#define ZSTD_INDEXOVERFLOW_MARGIN (16 MB)
1412
static int ZSTD_indexTooCloseToMax(ZSTD_window_t w)
1413
0
{
1414
0
    return (size_t)(w.nextSrc - w.base) > (ZSTD_CURRENT_MAX - ZSTD_INDEXOVERFLOW_MARGIN);
1415
0
}
1416
1417
/*! ZSTD_resetCCtx_internal() :
1418
    note : `params` are assumed fully validated at this stage */
1419
static size_t ZSTD_resetCCtx_internal(ZSTD_CCtx* zc,
1420
                                      ZSTD_CCtx_params params,
1421
                                      U64 const pledgedSrcSize,
1422
                                      ZSTD_compResetPolicy_e const crp,
1423
                                      ZSTD_buffered_policy_e const zbuff)
1424
0
{
1425
0
    ZSTD_cwksp* const ws = &zc->workspace;
1426
0
    DEBUGLOG(4, "ZSTD_resetCCtx_internal: pledgedSrcSize=%u, wlog=%u",
1427
0
                (U32)pledgedSrcSize, params.cParams.windowLog);
1428
0
    assert(!ZSTD_isError(ZSTD_checkCParams(params.cParams)));
1429
1430
0
    zc->isFirstBlock = 1;
1431
1432
0
    if (params.ldmParams.enableLdm) {
1433
        /* Adjust long distance matching parameters */
1434
0
        ZSTD_ldm_adjustParameters(&params.ldmParams, &params.cParams);
1435
0
        assert(params.ldmParams.hashLog >= params.ldmParams.bucketSizeLog);
1436
0
        assert(params.ldmParams.hashRateLog < 32);
1437
0
        zc->ldmState.hashPower = ZSTD_rollingHash_primePower(params.ldmParams.minMatchLength);
1438
0
    }
1439
1440
0
    {   size_t const windowSize = MAX(1, (size_t)MIN(((U64)1 << params.cParams.windowLog), pledgedSrcSize));
1441
0
        size_t const blockSize = MIN(ZSTD_BLOCKSIZE_MAX, windowSize);
1442
0
        U32    const divider = (params.cParams.minMatch==3) ? 3 : 4;
1443
0
        size_t const maxNbSeq = blockSize / divider;
1444
0
        size_t const tokenSpace = ZSTD_cwksp_alloc_size(WILDCOPY_OVERLENGTH + blockSize)
1445
0
                                + ZSTD_cwksp_alloc_size(maxNbSeq * sizeof(seqDef))
1446
0
                                + 3 * ZSTD_cwksp_alloc_size(maxNbSeq * sizeof(BYTE));
1447
0
        size_t const buffOutSize = (zbuff==ZSTDb_buffered) ? ZSTD_compressBound(blockSize)+1 : 0;
1448
0
        size_t const buffInSize = (zbuff==ZSTDb_buffered) ? windowSize + blockSize : 0;
1449
0
        size_t const matchStateSize = ZSTD_sizeof_matchState(&params.cParams, /* forCCtx */ 1);
1450
0
        size_t const maxNbLdmSeq = ZSTD_ldm_getMaxNbSeq(params.ldmParams, blockSize);
1451
1452
0
        ZSTD_indexResetPolicy_e needsIndexReset = zc->initialized ? ZSTDirp_continue : ZSTDirp_reset;
1453
1454
0
        if (ZSTD_indexTooCloseToMax(zc->blockState.matchState.window)) {
1455
0
            needsIndexReset = ZSTDirp_reset;
1456
0
        }
1457
1458
0
        if (!zc->staticSize) ZSTD_cwksp_bump_oversized_duration(ws, 0);
1459
1460
        /* Check if workspace is large enough, alloc a new one if needed */
1461
0
        {   size_t const cctxSpace = zc->staticSize ? ZSTD_cwksp_alloc_size(sizeof(ZSTD_CCtx)) : 0;
1462
0
            size_t const entropySpace = ZSTD_cwksp_alloc_size(HUF_WORKSPACE_SIZE);
1463
0
            size_t const blockStateSpace = 2 * ZSTD_cwksp_alloc_size(sizeof(ZSTD_compressedBlockState_t));
1464
0
            size_t const bufferSpace = ZSTD_cwksp_alloc_size(buffInSize) + ZSTD_cwksp_alloc_size(buffOutSize);
1465
0
            size_t const ldmSpace = ZSTD_ldm_getTableSize(params.ldmParams);
1466
0
            size_t const ldmSeqSpace = ZSTD_cwksp_alloc_size(maxNbLdmSeq * sizeof(rawSeq));
1467
1468
0
            size_t const neededSpace =
1469
0
                cctxSpace +
1470
0
                entropySpace +
1471
0
                blockStateSpace +
1472
0
                ldmSpace +
1473
0
                ldmSeqSpace +
1474
0
                matchStateSize +
1475
0
                tokenSpace +
1476
0
                bufferSpace;
1477
1478
0
            int const workspaceTooSmall = ZSTD_cwksp_sizeof(ws) < neededSpace;
1479
0
            int const workspaceWasteful = ZSTD_cwksp_check_wasteful(ws, neededSpace);
1480
1481
0
            DEBUGLOG(4, "Need %zuKB workspace, including %zuKB for match state, and %zuKB for buffers",
1482
0
                        neededSpace>>10, matchStateSize>>10, bufferSpace>>10);
1483
0
            DEBUGLOG(4, "windowSize: %zu - blockSize: %zu", windowSize, blockSize);
1484
1485
0
            if (workspaceTooSmall || workspaceWasteful) {
1486
0
                DEBUGLOG(4, "Resize workspaceSize from %zuKB to %zuKB",
1487
0
                            ZSTD_cwksp_sizeof(ws) >> 10,
1488
0
                            neededSpace >> 10);
1489
1490
0
                RETURN_ERROR_IF(zc->staticSize, memory_allocation, "static cctx : no resize");
1491
1492
0
                needsIndexReset = ZSTDirp_reset;
1493
1494
0
                ZSTD_cwksp_free(ws, zc->customMem);
1495
0
                FORWARD_IF_ERROR(ZSTD_cwksp_create(ws, neededSpace, zc->customMem), "");
1496
1497
0
                DEBUGLOG(5, "reserving object space");
1498
                /* Statically sized space.
1499
                 * entropyWorkspace never moves,
1500
                 * though prev/next block swap places */
1501
0
                assert(ZSTD_cwksp_check_available(ws, 2 * sizeof(ZSTD_compressedBlockState_t)));
1502
0
                zc->blockState.prevCBlock = (ZSTD_compressedBlockState_t*) ZSTD_cwksp_reserve_object(ws, sizeof(ZSTD_compressedBlockState_t));
1503
0
                RETURN_ERROR_IF(zc->blockState.prevCBlock == NULL, memory_allocation, "couldn't allocate prevCBlock");
1504
0
                zc->blockState.nextCBlock = (ZSTD_compressedBlockState_t*) ZSTD_cwksp_reserve_object(ws, sizeof(ZSTD_compressedBlockState_t));
1505
0
                RETURN_ERROR_IF(zc->blockState.nextCBlock == NULL, memory_allocation, "couldn't allocate nextCBlock");
1506
0
                zc->entropyWorkspace = (U32*) ZSTD_cwksp_reserve_object(ws, HUF_WORKSPACE_SIZE);
1507
0
                RETURN_ERROR_IF(zc->blockState.nextCBlock == NULL, memory_allocation, "couldn't allocate entropyWorkspace");
1508
0
        }   }
1509
1510
0
        ZSTD_cwksp_clear(ws);
1511
1512
        /* init params */
1513
0
        zc->appliedParams = params;
1514
0
        zc->blockState.matchState.cParams = params.cParams;
1515
0
        zc->pledgedSrcSizePlusOne = pledgedSrcSize+1;
1516
0
        zc->consumedSrcSize = 0;
1517
0
        zc->producedCSize = 0;
1518
0
        if (pledgedSrcSize == ZSTD_CONTENTSIZE_UNKNOWN)
1519
0
            zc->appliedParams.fParams.contentSizeFlag = 0;
1520
0
        DEBUGLOG(4, "pledged content size : %u ; flag : %u",
1521
0
            (unsigned)pledgedSrcSize, zc->appliedParams.fParams.contentSizeFlag);
1522
0
        zc->blockSize = blockSize;
1523
1524
0
        XXH64_reset(&zc->xxhState, 0);
1525
0
        zc->stage = ZSTDcs_init;
1526
0
        zc->dictID = 0;
1527
1528
0
        ZSTD_reset_compressedBlockState(zc->blockState.prevCBlock);
1529
1530
        /* ZSTD_wildcopy() is used to copy into the literals buffer,
1531
         * so we have to oversize the buffer by WILDCOPY_OVERLENGTH bytes.
1532
         */
1533
0
        zc->seqStore.litStart = ZSTD_cwksp_reserve_buffer(ws, blockSize + WILDCOPY_OVERLENGTH);
1534
0
        zc->seqStore.maxNbLit = blockSize;
1535
1536
        /* buffers */
1537
0
        zc->inBuffSize = buffInSize;
1538
0
        zc->inBuff = (char*)ZSTD_cwksp_reserve_buffer(ws, buffInSize);
1539
0
        zc->outBuffSize = buffOutSize;
1540
0
        zc->outBuff = (char*)ZSTD_cwksp_reserve_buffer(ws, buffOutSize);
1541
1542
        /* ldm bucketOffsets table */
1543
0
        if (params.ldmParams.enableLdm) {
1544
            /* TODO: avoid memset? */
1545
0
            size_t const ldmBucketSize =
1546
0
                  ((size_t)1) << (params.ldmParams.hashLog -
1547
0
                                  params.ldmParams.bucketSizeLog);
1548
0
            zc->ldmState.bucketOffsets = ZSTD_cwksp_reserve_buffer(ws, ldmBucketSize);
1549
0
            memset(zc->ldmState.bucketOffsets, 0, ldmBucketSize);
1550
0
        }
1551
1552
        /* sequences storage */
1553
0
        ZSTD_referenceExternalSequences(zc, NULL, 0);
1554
0
        zc->seqStore.maxNbSeq = maxNbSeq;
1555
0
        zc->seqStore.llCode = ZSTD_cwksp_reserve_buffer(ws, maxNbSeq * sizeof(BYTE));
1556
0
        zc->seqStore.mlCode = ZSTD_cwksp_reserve_buffer(ws, maxNbSeq * sizeof(BYTE));
1557
0
        zc->seqStore.ofCode = ZSTD_cwksp_reserve_buffer(ws, maxNbSeq * sizeof(BYTE));
1558
0
        zc->seqStore.sequencesStart = (seqDef*)ZSTD_cwksp_reserve_aligned(ws, maxNbSeq * sizeof(seqDef));
1559
1560
0
        FORWARD_IF_ERROR(ZSTD_reset_matchState(
1561
0
            &zc->blockState.matchState,
1562
0
            ws,
1563
0
            &params.cParams,
1564
0
            crp,
1565
0
            needsIndexReset,
1566
0
            ZSTD_resetTarget_CCtx), "");
1567
1568
        /* ldm hash table */
1569
0
        if (params.ldmParams.enableLdm) {
1570
            /* TODO: avoid memset? */
1571
0
            size_t const ldmHSize = ((size_t)1) << params.ldmParams.hashLog;
1572
0
            zc->ldmState.hashTable = (ldmEntry_t*)ZSTD_cwksp_reserve_aligned(ws, ldmHSize * sizeof(ldmEntry_t));
1573
0
            memset(zc->ldmState.hashTable, 0, ldmHSize * sizeof(ldmEntry_t));
1574
0
            zc->ldmSequences = (rawSeq*)ZSTD_cwksp_reserve_aligned(ws, maxNbLdmSeq * sizeof(rawSeq));
1575
0
            zc->maxNbLdmSequences = maxNbLdmSeq;
1576
1577
0
            ZSTD_window_init(&zc->ldmState.window);
1578
0
            ZSTD_window_clear(&zc->ldmState.window);
1579
0
            zc->ldmState.loadedDictEnd = 0;
1580
0
        }
1581
1582
0
        DEBUGLOG(3, "wksp: finished allocating, %zd bytes remain available", ZSTD_cwksp_available_space(ws));
1583
0
        zc->initialized = 1;
1584
1585
0
        return 0;
1586
0
    }
1587
0
}
1588
1589
/* ZSTD_invalidateRepCodes() :
1590
 * ensures next compression will not use repcodes from previous block.
1591
 * Note : only works with regular variant;
1592
 *        do not use with extDict variant ! */
1593
0
void ZSTD_invalidateRepCodes(ZSTD_CCtx* cctx) {
1594
0
    int i;
1595
0
    for (i=0; i<ZSTD_REP_NUM; i++) cctx->blockState.prevCBlock->rep[i] = 0;
1596
0
    assert(!ZSTD_window_hasExtDict(cctx->blockState.matchState.window));
1597
0
}
1598
1599
/* These are the approximate sizes for each strategy past which copying the
1600
 * dictionary tables into the working context is faster than using them
1601
 * in-place.
1602
 */
1603
static const size_t attachDictSizeCutoffs[ZSTD_STRATEGY_MAX+1] = {
1604
    8 KB,  /* unused */
1605
    8 KB,  /* ZSTD_fast */
1606
    16 KB, /* ZSTD_dfast */
1607
    32 KB, /* ZSTD_greedy */
1608
    32 KB, /* ZSTD_lazy */
1609
    32 KB, /* ZSTD_lazy2 */
1610
    32 KB, /* ZSTD_btlazy2 */
1611
    32 KB, /* ZSTD_btopt */
1612
    8 KB,  /* ZSTD_btultra */
1613
    8 KB   /* ZSTD_btultra2 */
1614
};
1615
1616
static int ZSTD_shouldAttachDict(const ZSTD_CDict* cdict,
1617
                                 const ZSTD_CCtx_params* params,
1618
                                 U64 pledgedSrcSize)
1619
0
{
1620
0
    size_t cutoff = attachDictSizeCutoffs[cdict->matchState.cParams.strategy];
1621
0
    return ( pledgedSrcSize <= cutoff
1622
0
          || pledgedSrcSize == ZSTD_CONTENTSIZE_UNKNOWN
1623
0
          || params->attachDictPref == ZSTD_dictForceAttach )
1624
0
        && params->attachDictPref != ZSTD_dictForceCopy
1625
0
        && !params->forceWindow; /* dictMatchState isn't correctly
1626
                                 * handled in _enforceMaxDist */
1627
0
}
1628
1629
static size_t
1630
ZSTD_resetCCtx_byAttachingCDict(ZSTD_CCtx* cctx,
1631
                        const ZSTD_CDict* cdict,
1632
                        ZSTD_CCtx_params params,
1633
                        U64 pledgedSrcSize,
1634
                        ZSTD_buffered_policy_e zbuff)
1635
0
{
1636
0
    {   const ZSTD_compressionParameters* const cdict_cParams = &cdict->matchState.cParams;
1637
0
        unsigned const windowLog = params.cParams.windowLog;
1638
0
        assert(windowLog != 0);
1639
        /* Resize working context table params for input only, since the dict
1640
         * has its own tables. */
1641
        /* pledgeSrcSize == 0 means 0! */
1642
0
        params.cParams = ZSTD_adjustCParams_internal(*cdict_cParams, pledgedSrcSize, 0);
1643
0
        params.cParams.windowLog = windowLog;
1644
0
        FORWARD_IF_ERROR(ZSTD_resetCCtx_internal(cctx, params, pledgedSrcSize,
1645
0
                                                 ZSTDcrp_makeClean, zbuff), "");
1646
0
        assert(cctx->appliedParams.cParams.strategy == cdict_cParams->strategy);
1647
0
    }
1648
1649
0
    {   const U32 cdictEnd = (U32)( cdict->matchState.window.nextSrc
1650
0
                                  - cdict->matchState.window.base);
1651
0
        const U32 cdictLen = cdictEnd - cdict->matchState.window.dictLimit;
1652
0
        if (cdictLen == 0) {
1653
            /* don't even attach dictionaries with no contents */
1654
0
            DEBUGLOG(4, "skipping attaching empty dictionary");
1655
0
        } else {
1656
0
            DEBUGLOG(4, "attaching dictionary into context");
1657
0
            cctx->blockState.matchState.dictMatchState = &cdict->matchState;
1658
1659
            /* prep working match state so dict matches never have negative indices
1660
             * when they are translated to the working context's index space. */
1661
0
            if (cctx->blockState.matchState.window.dictLimit < cdictEnd) {
1662
0
                cctx->blockState.matchState.window.nextSrc =
1663
0
                    cctx->blockState.matchState.window.base + cdictEnd;
1664
0
                ZSTD_window_clear(&cctx->blockState.matchState.window);
1665
0
            }
1666
            /* loadedDictEnd is expressed within the referential of the active context */
1667
0
            cctx->blockState.matchState.loadedDictEnd = cctx->blockState.matchState.window.dictLimit;
1668
0
    }   }
1669
1670
0
    cctx->dictID = cdict->dictID;
1671
1672
    /* copy block state */
1673
0
    memcpy(cctx->blockState.prevCBlock, &cdict->cBlockState, sizeof(cdict->cBlockState));
1674
1675
0
    return 0;
1676
0
}
1677
1678
static size_t ZSTD_resetCCtx_byCopyingCDict(ZSTD_CCtx* cctx,
1679
                            const ZSTD_CDict* cdict,
1680
                            ZSTD_CCtx_params params,
1681
                            U64 pledgedSrcSize,
1682
                            ZSTD_buffered_policy_e zbuff)
1683
0
{
1684
0
    const ZSTD_compressionParameters *cdict_cParams = &cdict->matchState.cParams;
1685
1686
0
    DEBUGLOG(4, "copying dictionary into context");
1687
1688
0
    {   unsigned const windowLog = params.cParams.windowLog;
1689
0
        assert(windowLog != 0);
1690
        /* Copy only compression parameters related to tables. */
1691
0
        params.cParams = *cdict_cParams;
1692
0
        params.cParams.windowLog = windowLog;
1693
0
        FORWARD_IF_ERROR(ZSTD_resetCCtx_internal(cctx, params, pledgedSrcSize,
1694
0
                                                 ZSTDcrp_leaveDirty, zbuff), "");
1695
0
        assert(cctx->appliedParams.cParams.strategy == cdict_cParams->strategy);
1696
0
        assert(cctx->appliedParams.cParams.hashLog == cdict_cParams->hashLog);
1697
0
        assert(cctx->appliedParams.cParams.chainLog == cdict_cParams->chainLog);
1698
0
    }
1699
1700
0
    ZSTD_cwksp_mark_tables_dirty(&cctx->workspace);
1701
1702
    /* copy tables */
1703
0
    {   size_t const chainSize = (cdict_cParams->strategy == ZSTD_fast) ? 0 : ((size_t)1 << cdict_cParams->chainLog);
1704
0
        size_t const hSize =  (size_t)1 << cdict_cParams->hashLog;
1705
1706
0
        memcpy(cctx->blockState.matchState.hashTable,
1707
0
               cdict->matchState.hashTable,
1708
0
               hSize * sizeof(U32));
1709
0
        memcpy(cctx->blockState.matchState.chainTable,
1710
0
               cdict->matchState.chainTable,
1711
0
               chainSize * sizeof(U32));
1712
0
    }
1713
1714
    /* Zero the hashTable3, since the cdict never fills it */
1715
0
    {   int const h3log = cctx->blockState.matchState.hashLog3;
1716
0
        size_t const h3Size = h3log ? ((size_t)1 << h3log) : 0;
1717
0
        assert(cdict->matchState.hashLog3 == 0);
1718
0
        memset(cctx->blockState.matchState.hashTable3, 0, h3Size * sizeof(U32));
1719
0
    }
1720
1721
0
    ZSTD_cwksp_mark_tables_clean(&cctx->workspace);
1722
1723
    /* copy dictionary offsets */
1724
0
    {   ZSTD_matchState_t const* srcMatchState = &cdict->matchState;
1725
0
        ZSTD_matchState_t* dstMatchState = &cctx->blockState.matchState;
1726
0
        dstMatchState->window       = srcMatchState->window;
1727
0
        dstMatchState->nextToUpdate = srcMatchState->nextToUpdate;
1728
0
        dstMatchState->loadedDictEnd= srcMatchState->loadedDictEnd;
1729
0
    }
1730
1731
0
    cctx->dictID = cdict->dictID;
1732
1733
    /* copy block state */
1734
0
    memcpy(cctx->blockState.prevCBlock, &cdict->cBlockState, sizeof(cdict->cBlockState));
1735
1736
0
    return 0;
1737
0
}
1738
1739
/* We have a choice between copying the dictionary context into the working
1740
 * context, or referencing the dictionary context from the working context
1741
 * in-place. We decide here which strategy to use. */
1742
static size_t ZSTD_resetCCtx_usingCDict(ZSTD_CCtx* cctx,
1743
                            const ZSTD_CDict* cdict,
1744
                            const ZSTD_CCtx_params* params,
1745
                            U64 pledgedSrcSize,
1746
                            ZSTD_buffered_policy_e zbuff)
1747
0
{
1748
1749
0
    DEBUGLOG(4, "ZSTD_resetCCtx_usingCDict (pledgedSrcSize=%u)",
1750
0
                (unsigned)pledgedSrcSize);
1751
1752
0
    if (ZSTD_shouldAttachDict(cdict, params, pledgedSrcSize)) {
1753
0
        return ZSTD_resetCCtx_byAttachingCDict(
1754
0
            cctx, cdict, *params, pledgedSrcSize, zbuff);
1755
0
    } else {
1756
0
        return ZSTD_resetCCtx_byCopyingCDict(
1757
0
            cctx, cdict, *params, pledgedSrcSize, zbuff);
1758
0
    }
1759
0
}
1760
1761
/*! ZSTD_copyCCtx_internal() :
1762
 *  Duplicate an existing context `srcCCtx` into another one `dstCCtx`.
1763
 *  Only works during stage ZSTDcs_init (i.e. after creation, but before first call to ZSTD_compressContinue()).
1764
 *  The "context", in this case, refers to the hash and chain tables,
1765
 *  entropy tables, and dictionary references.
1766
 * `windowLog` value is enforced if != 0, otherwise value is copied from srcCCtx.
1767
 * @return : 0, or an error code */
1768
static size_t ZSTD_copyCCtx_internal(ZSTD_CCtx* dstCCtx,
1769
                            const ZSTD_CCtx* srcCCtx,
1770
                            ZSTD_frameParameters fParams,
1771
                            U64 pledgedSrcSize,
1772
                            ZSTD_buffered_policy_e zbuff)
1773
0
{
1774
0
    DEBUGLOG(5, "ZSTD_copyCCtx_internal");
1775
0
    RETURN_ERROR_IF(srcCCtx->stage!=ZSTDcs_init, stage_wrong,
1776
0
                    "Can't copy a ctx that's not in init stage.");
1777
1778
0
    memcpy(&dstCCtx->customMem, &srcCCtx->customMem, sizeof(ZSTD_customMem));
1779
0
    {   ZSTD_CCtx_params params = dstCCtx->requestedParams;
1780
        /* Copy only compression parameters related to tables. */
1781
0
        params.cParams = srcCCtx->appliedParams.cParams;
1782
0
        params.fParams = fParams;
1783
0
        ZSTD_resetCCtx_internal(dstCCtx, params, pledgedSrcSize,
1784
0
                                ZSTDcrp_leaveDirty, zbuff);
1785
0
        assert(dstCCtx->appliedParams.cParams.windowLog == srcCCtx->appliedParams.cParams.windowLog);
1786
0
        assert(dstCCtx->appliedParams.cParams.strategy == srcCCtx->appliedParams.cParams.strategy);
1787
0
        assert(dstCCtx->appliedParams.cParams.hashLog == srcCCtx->appliedParams.cParams.hashLog);
1788
0
        assert(dstCCtx->appliedParams.cParams.chainLog == srcCCtx->appliedParams.cParams.chainLog);
1789
0
        assert(dstCCtx->blockState.matchState.hashLog3 == srcCCtx->blockState.matchState.hashLog3);
1790
0
    }
1791
1792
0
    ZSTD_cwksp_mark_tables_dirty(&dstCCtx->workspace);
1793
1794
    /* copy tables */
1795
0
    {   size_t const chainSize = (srcCCtx->appliedParams.cParams.strategy == ZSTD_fast) ? 0 : ((size_t)1 << srcCCtx->appliedParams.cParams.chainLog);
1796
0
        size_t const hSize =  (size_t)1 << srcCCtx->appliedParams.cParams.hashLog;
1797
0
        int const h3log = srcCCtx->blockState.matchState.hashLog3;
1798
0
        size_t const h3Size = h3log ? ((size_t)1 << h3log) : 0;
1799
1800
0
        memcpy(dstCCtx->blockState.matchState.hashTable,
1801
0
               srcCCtx->blockState.matchState.hashTable,
1802
0
               hSize * sizeof(U32));
1803
0
        memcpy(dstCCtx->blockState.matchState.chainTable,
1804
0
               srcCCtx->blockState.matchState.chainTable,
1805
0
               chainSize * sizeof(U32));
1806
0
        memcpy(dstCCtx->blockState.matchState.hashTable3,
1807
0
               srcCCtx->blockState.matchState.hashTable3,
1808
0
               h3Size * sizeof(U32));
1809
0
    }
1810
1811
0
    ZSTD_cwksp_mark_tables_clean(&dstCCtx->workspace);
1812
1813
    /* copy dictionary offsets */
1814
0
    {
1815
0
        const ZSTD_matchState_t* srcMatchState = &srcCCtx->blockState.matchState;
1816
0
        ZSTD_matchState_t* dstMatchState = &dstCCtx->blockState.matchState;
1817
0
        dstMatchState->window       = srcMatchState->window;
1818
0
        dstMatchState->nextToUpdate = srcMatchState->nextToUpdate;
1819
0
        dstMatchState->loadedDictEnd= srcMatchState->loadedDictEnd;
1820
0
    }
1821
0
    dstCCtx->dictID = srcCCtx->dictID;
1822
1823
    /* copy block state */
1824
0
    memcpy(dstCCtx->blockState.prevCBlock, srcCCtx->blockState.prevCBlock, sizeof(*srcCCtx->blockState.prevCBlock));
1825
1826
0
    return 0;
1827
0
}
1828
1829
/*! ZSTD_copyCCtx() :
1830
 *  Duplicate an existing context `srcCCtx` into another one `dstCCtx`.
1831
 *  Only works during stage ZSTDcs_init (i.e. after creation, but before first call to ZSTD_compressContinue()).
1832
 *  pledgedSrcSize==0 means "unknown".
1833
*   @return : 0, or an error code */
1834
size_t ZSTD_copyCCtx(ZSTD_CCtx* dstCCtx, const ZSTD_CCtx* srcCCtx, unsigned long long pledgedSrcSize)
1835
0
{
1836
0
    ZSTD_frameParameters fParams = { 1 /*content*/, 0 /*checksum*/, 0 /*noDictID*/ };
1837
0
    ZSTD_buffered_policy_e const zbuff = (ZSTD_buffered_policy_e)(srcCCtx->inBuffSize>0);
1838
0
    ZSTD_STATIC_ASSERT((U32)ZSTDb_buffered==1);
1839
0
    if (pledgedSrcSize==0) pledgedSrcSize = ZSTD_CONTENTSIZE_UNKNOWN;
1840
0
    fParams.contentSizeFlag = (pledgedSrcSize != ZSTD_CONTENTSIZE_UNKNOWN);
1841
1842
0
    return ZSTD_copyCCtx_internal(dstCCtx, srcCCtx,
1843
0
                                fParams, pledgedSrcSize,
1844
0
                                zbuff);
1845
0
}
1846
1847
1848
0
#define ZSTD_ROWSIZE 16
1849
/*! ZSTD_reduceTable() :
1850
 *  reduce table indexes by `reducerValue`, or squash to zero.
1851
 *  PreserveMark preserves "unsorted mark" for btlazy2 strategy.
1852
 *  It must be set to a clear 0/1 value, to remove branch during inlining.
1853
 *  Presume table size is a multiple of ZSTD_ROWSIZE
1854
 *  to help auto-vectorization */
1855
FORCE_INLINE_TEMPLATE void
1856
ZSTD_reduceTable_internal (U32* const table, U32 const size, U32 const reducerValue, int const preserveMark)
1857
0
{
1858
0
    int const nbRows = (int)size / ZSTD_ROWSIZE;
1859
0
    int cellNb = 0;
1860
0
    int rowNb;
1861
0
    assert((size & (ZSTD_ROWSIZE-1)) == 0);  /* multiple of ZSTD_ROWSIZE */
1862
0
    assert(size < (1U<<31));   /* can be casted to int */
1863
1864
#if defined (MEMORY_SANITIZER) && !defined (ZSTD_MSAN_DONT_POISON_WORKSPACE)
1865
    /* To validate that the table re-use logic is sound, and that we don't
1866
     * access table space that we haven't cleaned, we re-"poison" the table
1867
     * space every time we mark it dirty.
1868
     *
1869
     * This function however is intended to operate on those dirty tables and
1870
     * re-clean them. So when this function is used correctly, we can unpoison
1871
     * the memory it operated on. This introduces a blind spot though, since
1872
     * if we now try to operate on __actually__ poisoned memory, we will not
1873
     * detect that. */
1874
    __msan_unpoison(table, size * sizeof(U32));
1875
#endif
1876
1877
0
    for (rowNb=0 ; rowNb < nbRows ; rowNb++) {
1878
0
        int column;
1879
0
        for (column=0; column<ZSTD_ROWSIZE; column++) {
1880
0
            if (preserveMark) {
1881
0
                U32 const adder = (table[cellNb] == ZSTD_DUBT_UNSORTED_MARK) ? reducerValue : 0;
1882
0
                table[cellNb] += adder;
1883
0
            }
1884
0
            if (table[cellNb] < reducerValue) table[cellNb] = 0;
1885
0
            else table[cellNb] -= reducerValue;
1886
0
            cellNb++;
1887
0
    }   }
1888
0
}
1889
1890
static void ZSTD_reduceTable(U32* const table, U32 const size, U32 const reducerValue)
1891
0
{
1892
0
    ZSTD_reduceTable_internal(table, size, reducerValue, 0);
1893
0
}
1894
1895
static void ZSTD_reduceTable_btlazy2(U32* const table, U32 const size, U32 const reducerValue)
1896
0
{
1897
0
    ZSTD_reduceTable_internal(table, size, reducerValue, 1);
1898
0
}
1899
1900
/*! ZSTD_reduceIndex() :
1901
*   rescale all indexes to avoid future overflow (indexes are U32) */
1902
static void ZSTD_reduceIndex (ZSTD_matchState_t* ms, ZSTD_CCtx_params const* params, const U32 reducerValue)
1903
0
{
1904
0
    {   U32 const hSize = (U32)1 << params->cParams.hashLog;
1905
0
        ZSTD_reduceTable(ms->hashTable, hSize, reducerValue);
1906
0
    }
1907
1908
0
    if (params->cParams.strategy != ZSTD_fast) {
1909
0
        U32 const chainSize = (U32)1 << params->cParams.chainLog;
1910
0
        if (params->cParams.strategy == ZSTD_btlazy2)
1911
0
            ZSTD_reduceTable_btlazy2(ms->chainTable, chainSize, reducerValue);
1912
0
        else
1913
0
            ZSTD_reduceTable(ms->chainTable, chainSize, reducerValue);
1914
0
    }
1915
1916
0
    if (ms->hashLog3) {
1917
0
        U32 const h3Size = (U32)1 << ms->hashLog3;
1918
0
        ZSTD_reduceTable(ms->hashTable3, h3Size, reducerValue);
1919
0
    }
1920
0
}
1921
1922
1923
/*-*******************************************************
1924
*  Block entropic compression
1925
*********************************************************/
1926
1927
/* See doc/zstd_compression_format.md for detailed format description */
1928
1929
void ZSTD_seqToCodes(const seqStore_t* seqStorePtr)
1930
0
{
1931
0
    const seqDef* const sequences = seqStorePtr->sequencesStart;
1932
0
    BYTE* const llCodeTable = seqStorePtr->llCode;
1933
0
    BYTE* const ofCodeTable = seqStorePtr->ofCode;
1934
0
    BYTE* const mlCodeTable = seqStorePtr->mlCode;
1935
0
    U32 const nbSeq = (U32)(seqStorePtr->sequences - seqStorePtr->sequencesStart);
1936
0
    U32 u;
1937
0
    assert(nbSeq <= seqStorePtr->maxNbSeq);
1938
0
    for (u=0; u<nbSeq; u++) {
1939
0
        U32 const llv = sequences[u].litLength;
1940
0
        U32 const mlv = sequences[u].matchLength;
1941
0
        llCodeTable[u] = (BYTE)ZSTD_LLcode(llv);
1942
0
        ofCodeTable[u] = (BYTE)ZSTD_highbit32(sequences[u].offset);
1943
0
        mlCodeTable[u] = (BYTE)ZSTD_MLcode(mlv);
1944
0
    }
1945
0
    if (seqStorePtr->longLengthID==1)
1946
0
        llCodeTable[seqStorePtr->longLengthPos] = MaxLL;
1947
0
    if (seqStorePtr->longLengthID==2)
1948
0
        mlCodeTable[seqStorePtr->longLengthPos] = MaxML;
1949
0
}
1950
1951
/* ZSTD_useTargetCBlockSize():
1952
 * Returns if target compressed block size param is being used.
1953
 * If used, compression will do best effort to make a compressed block size to be around targetCBlockSize.
1954
 * Returns 1 if true, 0 otherwise. */
1955
static int ZSTD_useTargetCBlockSize(const ZSTD_CCtx_params* cctxParams)
1956
0
{
1957
0
    DEBUGLOG(5, "ZSTD_useTargetCBlockSize (targetCBlockSize=%zu)", cctxParams->targetCBlockSize);
1958
0
    return (cctxParams->targetCBlockSize != 0);
1959
0
}
1960
1961
/* ZSTD_compressSequences_internal():
1962
 * actually compresses both literals and sequences */
1963
MEM_STATIC size_t
1964
ZSTD_compressSequences_internal(seqStore_t* seqStorePtr,
1965
                          const ZSTD_entropyCTables_t* prevEntropy,
1966
                                ZSTD_entropyCTables_t* nextEntropy,
1967
                          const ZSTD_CCtx_params* cctxParams,
1968
                                void* dst, size_t dstCapacity,
1969
                                void* entropyWorkspace, size_t entropyWkspSize,
1970
                          const int bmi2)
1971
0
{
1972
0
    const int longOffsets = cctxParams->cParams.windowLog > STREAM_ACCUMULATOR_MIN;
1973
0
    ZSTD_strategy const strategy = cctxParams->cParams.strategy;
1974
0
    unsigned count[MaxSeq+1];
1975
0
    FSE_CTable* CTable_LitLength = nextEntropy->fse.litlengthCTable;
1976
0
    FSE_CTable* CTable_OffsetBits = nextEntropy->fse.offcodeCTable;
1977
0
    FSE_CTable* CTable_MatchLength = nextEntropy->fse.matchlengthCTable;
1978
0
    U32 LLtype, Offtype, MLtype;   /* compressed, raw or rle */
1979
0
    const seqDef* const sequences = seqStorePtr->sequencesStart;
1980
0
    const BYTE* const ofCodeTable = seqStorePtr->ofCode;
1981
0
    const BYTE* const llCodeTable = seqStorePtr->llCode;
1982
0
    const BYTE* const mlCodeTable = seqStorePtr->mlCode;
1983
0
    BYTE* const ostart = (BYTE*)dst;
1984
0
    BYTE* const oend = ostart + dstCapacity;
1985
0
    BYTE* op = ostart;
1986
0
    size_t const nbSeq = (size_t)(seqStorePtr->sequences - seqStorePtr->sequencesStart);
1987
0
    BYTE* seqHead;
1988
0
    BYTE* lastNCount = NULL;
1989
1990
0
    DEBUGLOG(5, "ZSTD_compressSequences_internal (nbSeq=%zu)", nbSeq);
1991
0
    ZSTD_STATIC_ASSERT(HUF_WORKSPACE_SIZE >= (1<<MAX(MLFSELog,LLFSELog)));
1992
1993
    /* Compress literals */
1994
0
    {   const BYTE* const literals = seqStorePtr->litStart;
1995
0
        size_t const litSize = (size_t)(seqStorePtr->lit - literals);
1996
0
        size_t const cSize = ZSTD_compressLiterals(
1997
0
                                    &prevEntropy->huf, &nextEntropy->huf,
1998
0
                                    cctxParams->cParams.strategy,
1999
0
                                    ZSTD_disableLiteralsCompression(cctxParams),
2000
0
                                    op, dstCapacity,
2001
0
                                    literals, litSize,
2002
0
                                    entropyWorkspace, entropyWkspSize,
2003
0
                                    bmi2);
2004
0
        FORWARD_IF_ERROR(cSize, "ZSTD_compressLiterals failed");
2005
0
        assert(cSize <= dstCapacity);
2006
0
        op += cSize;
2007
0
    }
2008
2009
    /* Sequences Header */
2010
0
    RETURN_ERROR_IF((oend-op) < 3 /*max nbSeq Size*/ + 1 /*seqHead*/,
2011
0
                    dstSize_tooSmall, "Can't fit seq hdr in output buf!");
2012
0
    if (nbSeq < 128) {
2013
0
        *op++ = (BYTE)nbSeq;
2014
0
    } else if (nbSeq < LONGNBSEQ) {
2015
0
        op[0] = (BYTE)((nbSeq>>8) + 0x80);
2016
0
        op[1] = (BYTE)nbSeq;
2017
0
        op+=2;
2018
0
    } else {
2019
0
        op[0]=0xFF;
2020
0
        MEM_writeLE16(op+1, (U16)(nbSeq - LONGNBSEQ));
2021
0
        op+=3;
2022
0
    }
2023
0
    assert(op <= oend);
2024
0
    if (nbSeq==0) {
2025
        /* Copy the old tables over as if we repeated them */
2026
0
        memcpy(&nextEntropy->fse, &prevEntropy->fse, sizeof(prevEntropy->fse));
2027
0
        return (size_t)(op - ostart);
2028
0
    }
2029
2030
    /* seqHead : flags for FSE encoding type */
2031
0
    seqHead = op++;
2032
0
    assert(op <= oend);
2033
2034
    /* convert length/distances into codes */
2035
0
    ZSTD_seqToCodes(seqStorePtr);
2036
    /* build CTable for Literal Lengths */
2037
0
    {   unsigned max = MaxLL;
2038
0
        size_t const mostFrequent = HIST_countFast_wksp(count, &max, llCodeTable, nbSeq, entropyWorkspace, entropyWkspSize);   /* can't fail */
2039
0
        DEBUGLOG(5, "Building LL table");
2040
0
        nextEntropy->fse.litlength_repeatMode = prevEntropy->fse.litlength_repeatMode;
2041
0
        LLtype = ZSTD_selectEncodingType(&nextEntropy->fse.litlength_repeatMode,
2042
0
                                        count, max, mostFrequent, nbSeq,
2043
0
                                        LLFSELog, prevEntropy->fse.litlengthCTable,
2044
0
                                        ZSTDInternalConstants::LL_defaultNorm, ZSTDInternalConstants::LL_defaultNormLog,
2045
0
                                        ZSTD_defaultAllowed, strategy);
2046
0
        assert(set_basic < set_compressed && set_rle < set_compressed);
2047
0
        assert(!(LLtype < set_compressed && nextEntropy->fse.litlength_repeatMode != FSE_repeat_none)); /* We don't copy tables */
2048
0
        {   size_t const countSize = ZSTD_buildCTable(
2049
0
                op, (size_t)(oend - op),
2050
0
                CTable_LitLength, LLFSELog, (symbolEncodingType_e)LLtype,
2051
0
                count, max, llCodeTable, nbSeq,
2052
0
                ZSTDInternalConstants::LL_defaultNorm, ZSTDInternalConstants::LL_defaultNormLog, MaxLL,
2053
0
                prevEntropy->fse.litlengthCTable,
2054
0
                sizeof(prevEntropy->fse.litlengthCTable),
2055
0
                entropyWorkspace, entropyWkspSize);
2056
0
            FORWARD_IF_ERROR(countSize, "ZSTD_buildCTable for LitLens failed");
2057
0
            if (LLtype == set_compressed)
2058
0
                lastNCount = op;
2059
0
            op += countSize;
2060
0
            assert(op <= oend);
2061
0
    }   }
2062
    /* build CTable for Offsets */
2063
0
    {   unsigned max = MaxOff;
2064
0
        size_t const mostFrequent = HIST_countFast_wksp(
2065
0
            count, &max, ofCodeTable, nbSeq, entropyWorkspace, entropyWkspSize);  /* can't fail */
2066
        /* We can only use the basic table if max <= DefaultMaxOff, otherwise the offsets are too large */
2067
0
        ZSTD_defaultPolicy_e const defaultPolicy = (max <= DefaultMaxOff) ? ZSTD_defaultAllowed : ZSTD_defaultDisallowed;
2068
0
        DEBUGLOG(5, "Building OF table");
2069
0
        nextEntropy->fse.offcode_repeatMode = prevEntropy->fse.offcode_repeatMode;
2070
0
        Offtype = ZSTD_selectEncodingType(&nextEntropy->fse.offcode_repeatMode,
2071
0
                                        count, max, mostFrequent, nbSeq,
2072
0
                                        OffFSELog, prevEntropy->fse.offcodeCTable,
2073
0
                                        ZSTDInternalConstants::OF_defaultNorm, ZSTDInternalConstants::OF_defaultNormLog,
2074
0
                                        defaultPolicy, strategy);
2075
0
        assert(!(Offtype < set_compressed && nextEntropy->fse.offcode_repeatMode != FSE_repeat_none)); /* We don't copy tables */
2076
0
        {   size_t const countSize = ZSTD_buildCTable(
2077
0
                op, (size_t)(oend - op),
2078
0
                CTable_OffsetBits, OffFSELog, (symbolEncodingType_e)Offtype,
2079
0
                count, max, ofCodeTable, nbSeq,
2080
0
                ZSTDInternalConstants::OF_defaultNorm, ZSTDInternalConstants::OF_defaultNormLog, DefaultMaxOff,
2081
0
                prevEntropy->fse.offcodeCTable,
2082
0
                sizeof(prevEntropy->fse.offcodeCTable),
2083
0
                entropyWorkspace, entropyWkspSize);
2084
0
            FORWARD_IF_ERROR(countSize, "ZSTD_buildCTable for Offsets failed");
2085
0
            if (Offtype == set_compressed)
2086
0
                lastNCount = op;
2087
0
            op += countSize;
2088
0
            assert(op <= oend);
2089
0
    }   }
2090
    /* build CTable for MatchLengths */
2091
0
    {   unsigned max = MaxML;
2092
0
        size_t const mostFrequent = HIST_countFast_wksp(
2093
0
            count, &max, mlCodeTable, nbSeq, entropyWorkspace, entropyWkspSize);   /* can't fail */
2094
0
        DEBUGLOG(5, "Building ML table (remaining space : %i)", (int)(oend-op));
2095
0
        nextEntropy->fse.matchlength_repeatMode = prevEntropy->fse.matchlength_repeatMode;
2096
0
        MLtype = ZSTD_selectEncodingType(&nextEntropy->fse.matchlength_repeatMode,
2097
0
                                        count, max, mostFrequent, nbSeq,
2098
0
                                        MLFSELog, prevEntropy->fse.matchlengthCTable,
2099
0
                                        ZSTDInternalConstants::ML_defaultNorm, ZSTDInternalConstants::ML_defaultNormLog,
2100
0
                                        ZSTD_defaultAllowed, strategy);
2101
0
        assert(!(MLtype < set_compressed && nextEntropy->fse.matchlength_repeatMode != FSE_repeat_none)); /* We don't copy tables */
2102
0
        {   size_t const countSize = ZSTD_buildCTable(
2103
0
                op, (size_t)(oend - op),
2104
0
                CTable_MatchLength, MLFSELog, (symbolEncodingType_e)MLtype,
2105
0
                count, max, mlCodeTable, nbSeq,
2106
0
                ZSTDInternalConstants::ML_defaultNorm, ZSTDInternalConstants::ML_defaultNormLog, MaxML,
2107
0
                prevEntropy->fse.matchlengthCTable,
2108
0
                sizeof(prevEntropy->fse.matchlengthCTable),
2109
0
                entropyWorkspace, entropyWkspSize);
2110
0
            FORWARD_IF_ERROR(countSize, "ZSTD_buildCTable for MatchLengths failed");
2111
0
            if (MLtype == set_compressed)
2112
0
                lastNCount = op;
2113
0
            op += countSize;
2114
0
            assert(op <= oend);
2115
0
    }   }
2116
2117
0
    *seqHead = (BYTE)((LLtype<<6) + (Offtype<<4) + (MLtype<<2));
2118
2119
0
    {   size_t const bitstreamSize = ZSTD_encodeSequences(
2120
0
                                        op, (size_t)(oend - op),
2121
0
                                        CTable_MatchLength, mlCodeTable,
2122
0
                                        CTable_OffsetBits, ofCodeTable,
2123
0
                                        CTable_LitLength, llCodeTable,
2124
0
                                        sequences, nbSeq,
2125
0
                                        longOffsets, bmi2);
2126
0
        FORWARD_IF_ERROR(bitstreamSize, "ZSTD_encodeSequences failed");
2127
0
        op += bitstreamSize;
2128
0
        assert(op <= oend);
2129
        /* zstd versions <= 1.3.4 mistakenly report corruption when
2130
         * FSE_readNCount() receives a buffer < 4 bytes.
2131
         * Fixed by https://github.com/facebook/zstd/pull/1146.
2132
         * This can happen when the last set_compressed table present is 2
2133
         * bytes and the bitstream is only one byte.
2134
         * In this exceedingly rare case, we will simply emit an uncompressed
2135
         * block, since it isn't worth optimizing.
2136
         */
2137
0
        if (lastNCount && (op - lastNCount) < 4) {
2138
            /* NCountSize >= 2 && bitstreamSize > 0 ==> lastCountSize == 3 */
2139
0
            assert(op - lastNCount == 3);
2140
0
            DEBUGLOG(5, "Avoiding bug in zstd decoder in versions <= 1.3.4 by "
2141
0
                        "emitting an uncompressed block.");
2142
0
            return 0;
2143
0
        }
2144
0
    }
2145
2146
0
    DEBUGLOG(5, "compressed block size : %u", (unsigned)(op - ostart));
2147
0
    return (size_t)(op - ostart);
2148
0
}
2149
2150
MEM_STATIC size_t
2151
ZSTD_compressSequences(seqStore_t* seqStorePtr,
2152
                       const ZSTD_entropyCTables_t* prevEntropy,
2153
                             ZSTD_entropyCTables_t* nextEntropy,
2154
                       const ZSTD_CCtx_params* cctxParams,
2155
                             void* dst, size_t dstCapacity,
2156
                             size_t srcSize,
2157
                             void* entropyWorkspace, size_t entropyWkspSize,
2158
                             int bmi2)
2159
0
{
2160
0
    size_t const cSize = ZSTD_compressSequences_internal(
2161
0
                            seqStorePtr, prevEntropy, nextEntropy, cctxParams,
2162
0
                            dst, dstCapacity,
2163
0
                            entropyWorkspace, entropyWkspSize, bmi2);
2164
0
    if (cSize == 0) return 0;
2165
    /* When srcSize <= dstCapacity, there is enough space to write a raw uncompressed block.
2166
     * Since we ran out of space, block must be not compressible, so fall back to raw uncompressed block.
2167
     */
2168
0
    if ((cSize == ERROR(dstSize_tooSmall)) & (srcSize <= dstCapacity))
2169
0
        return 0;  /* block not compressed */
2170
0
    FORWARD_IF_ERROR(cSize, "ZSTD_compressSequences_internal failed");
2171
2172
    /* Check compressibility */
2173
0
    {   size_t const maxCSize = srcSize - ZSTD_minGain(srcSize, cctxParams->cParams.strategy);
2174
0
        if (cSize >= maxCSize) return 0;  /* block not compressed */
2175
0
    }
2176
2177
0
    return cSize;
2178
0
}
2179
2180
/* ZSTD_selectBlockCompressor() :
2181
 * Not static, but internal use only (used by long distance matcher)
2182
 * assumption : strat is a valid strategy */
2183
ZSTD_blockCompressor ZSTD_selectBlockCompressor(ZSTD_strategy strat, ZSTD_dictMode_e dictMode)
2184
0
{
2185
0
    static const ZSTD_blockCompressor blockCompressor[3][ZSTD_STRATEGY_MAX+1] = {
2186
0
        { ZSTD_compressBlock_fast  /* default for 0 */,
2187
0
          ZSTD_compressBlock_fast,
2188
0
          ZSTD_compressBlock_doubleFast,
2189
0
          ZSTD_compressBlock_greedy,
2190
0
          ZSTD_compressBlock_lazy,
2191
0
          ZSTD_compressBlock_lazy2,
2192
0
          ZSTD_compressBlock_btlazy2,
2193
0
          ZSTD_compressBlock_btopt,
2194
0
          ZSTD_compressBlock_btultra,
2195
0
          ZSTD_compressBlock_btultra2 },
2196
0
        { ZSTD_compressBlock_fast_extDict  /* default for 0 */,
2197
0
          ZSTD_compressBlock_fast_extDict,
2198
0
          ZSTD_compressBlock_doubleFast_extDict,
2199
0
          ZSTD_compressBlock_greedy_extDict,
2200
0
          ZSTD_compressBlock_lazy_extDict,
2201
0
          ZSTD_compressBlock_lazy2_extDict,
2202
0
          ZSTD_compressBlock_btlazy2_extDict,
2203
0
          ZSTD_compressBlock_btopt_extDict,
2204
0
          ZSTD_compressBlock_btultra_extDict,
2205
0
          ZSTD_compressBlock_btultra_extDict },
2206
0
        { ZSTD_compressBlock_fast_dictMatchState  /* default for 0 */,
2207
0
          ZSTD_compressBlock_fast_dictMatchState,
2208
0
          ZSTD_compressBlock_doubleFast_dictMatchState,
2209
0
          ZSTD_compressBlock_greedy_dictMatchState,
2210
0
          ZSTD_compressBlock_lazy_dictMatchState,
2211
0
          ZSTD_compressBlock_lazy2_dictMatchState,
2212
0
          ZSTD_compressBlock_btlazy2_dictMatchState,
2213
0
          ZSTD_compressBlock_btopt_dictMatchState,
2214
0
          ZSTD_compressBlock_btultra_dictMatchState,
2215
0
          ZSTD_compressBlock_btultra_dictMatchState }
2216
0
    };
2217
0
    ZSTD_blockCompressor selectedCompressor;
2218
0
    ZSTD_STATIC_ASSERT((unsigned)ZSTD_fast == 1);
2219
2220
0
    assert(ZSTD_cParam_withinBounds(ZSTD_c_strategy, strat));
2221
0
    selectedCompressor = blockCompressor[(int)dictMode][(int)strat];
2222
0
    assert(selectedCompressor != NULL);
2223
0
    return selectedCompressor;
2224
0
}
2225
2226
static void ZSTD_storeLastLiterals(seqStore_t* seqStorePtr,
2227
                                   const BYTE* anchor, size_t lastLLSize)
2228
0
{
2229
0
    memcpy(seqStorePtr->lit, anchor, lastLLSize);
2230
0
    seqStorePtr->lit += lastLLSize;
2231
0
}
2232
2233
void ZSTD_resetSeqStore(seqStore_t* ssPtr)
2234
0
{
2235
0
    ssPtr->lit = ssPtr->litStart;
2236
0
    ssPtr->sequences = ssPtr->sequencesStart;
2237
0
    ssPtr->longLengthID = 0;
2238
0
}
2239
2240
typedef enum { ZSTDbss_compress, ZSTDbss_noCompress } ZSTD_buildSeqStore_e;
2241
2242
static size_t ZSTD_buildSeqStore(ZSTD_CCtx* zc, const void* src, size_t srcSize)
2243
0
{
2244
0
    ZSTD_matchState_t* const ms = &zc->blockState.matchState;
2245
0
    DEBUGLOG(5, "ZSTD_buildSeqStore (srcSize=%zu)", srcSize);
2246
0
    assert(srcSize <= ZSTD_BLOCKSIZE_MAX);
2247
    /* Assert that we have correctly flushed the ctx params into the ms's copy */
2248
0
    ZSTD_assertEqualCParams(zc->appliedParams.cParams, ms->cParams);
2249
0
    if (srcSize < MIN_CBLOCK_SIZE+ZSTDInternalConstants::ZSTD_blockHeaderSize+1) {
2250
0
        ZSTD_ldm_skipSequences(&zc->externSeqStore, srcSize, zc->appliedParams.cParams.minMatch);
2251
0
        return ZSTDbss_noCompress; /* don't even attempt compression below a certain srcSize */
2252
0
    }
2253
0
    ZSTD_resetSeqStore(&(zc->seqStore));
2254
    /* required for optimal parser to read stats from dictionary */
2255
0
    ms->opt.symbolCosts = &zc->blockState.prevCBlock->entropy;
2256
    /* tell the optimal parser how we expect to compress literals */
2257
0
    ms->opt.literalCompressionMode = zc->appliedParams.literalCompressionMode;
2258
    /* a gap between an attached dict and the current window is not safe,
2259
     * they must remain adjacent,
2260
     * and when that stops being the case, the dict must be unset */
2261
0
    assert(ms->dictMatchState == NULL || ms->loadedDictEnd == ms->window.dictLimit);
2262
2263
    /* limited update after a very long match */
2264
0
    {   const BYTE* const base = ms->window.base;
2265
0
        const BYTE* const istart = (const BYTE*)src;
2266
0
        const U32 current = (U32)(istart-base);
2267
0
        if (sizeof(ptrdiff_t)==8) assert(istart - base < (ptrdiff_t)(U32)(-1));   /* ensure no overflow */
2268
0
        if (current > ms->nextToUpdate + 384)
2269
0
            ms->nextToUpdate = current - MIN(192, (U32)(current - ms->nextToUpdate - 384));
2270
0
    }
2271
2272
    /* select and store sequences */
2273
0
    {   ZSTD_dictMode_e const dictMode = ZSTD_matchState_dictMode(ms);
2274
0
        size_t lastLLSize;
2275
0
        {   int i;
2276
0
            for (i = 0; i < ZSTD_REP_NUM; ++i)
2277
0
                zc->blockState.nextCBlock->rep[i] = zc->blockState.prevCBlock->rep[i];
2278
0
        }
2279
0
        if (zc->externSeqStore.pos < zc->externSeqStore.size) {
2280
0
            assert(!zc->appliedParams.ldmParams.enableLdm);
2281
            /* Updates ldmSeqStore.pos */
2282
0
            lastLLSize =
2283
0
                ZSTD_ldm_blockCompress(&zc->externSeqStore,
2284
0
                                       ms, &zc->seqStore,
2285
0
                                       zc->blockState.nextCBlock->rep,
2286
0
                                       src, srcSize);
2287
0
            assert(zc->externSeqStore.pos <= zc->externSeqStore.size);
2288
0
        } else if (zc->appliedParams.ldmParams.enableLdm) {
2289
0
            rawSeqStore_t ldmSeqStore = {NULL, 0, 0, 0};
2290
2291
0
            ldmSeqStore.seq = zc->ldmSequences;
2292
0
            ldmSeqStore.capacity = zc->maxNbLdmSequences;
2293
            /* Updates ldmSeqStore.size */
2294
0
            FORWARD_IF_ERROR(ZSTD_ldm_generateSequences(&zc->ldmState, &ldmSeqStore,
2295
0
                                               &zc->appliedParams.ldmParams,
2296
0
                                               src, srcSize), "");
2297
            /* Updates ldmSeqStore.pos */
2298
0
            lastLLSize =
2299
0
                ZSTD_ldm_blockCompress(&ldmSeqStore,
2300
0
                                       ms, &zc->seqStore,
2301
0
                                       zc->blockState.nextCBlock->rep,
2302
0
                                       src, srcSize);
2303
0
            assert(ldmSeqStore.pos == ldmSeqStore.size);
2304
0
        } else {   /* not long range mode */
2305
0
            ZSTD_blockCompressor const blockCompressor = ZSTD_selectBlockCompressor(zc->appliedParams.cParams.strategy, dictMode);
2306
0
            lastLLSize = blockCompressor(ms, &zc->seqStore, zc->blockState.nextCBlock->rep, src, srcSize);
2307
0
        }
2308
0
        {   const BYTE* const lastLiterals = (const BYTE*)src + srcSize - lastLLSize;
2309
0
            ZSTD_storeLastLiterals(&zc->seqStore, lastLiterals, lastLLSize);
2310
0
    }   }
2311
0
    return ZSTDbss_compress;
2312
0
}
2313
2314
static void ZSTD_copyBlockSequences(ZSTD_CCtx* zc)
2315
0
{
2316
0
    const seqStore_t* seqStore = ZSTD_getSeqStore(zc);
2317
0
    const seqDef* seqs = seqStore->sequencesStart;
2318
0
    size_t seqsSize = seqStore->sequences - seqs;
2319
2320
0
    ZSTD_Sequence* outSeqs = &zc->seqCollector.seqStart[zc->seqCollector.seqIndex];
2321
0
    size_t i; size_t position; int repIdx;
2322
2323
0
    assert(zc->seqCollector.seqIndex + 1 < zc->seqCollector.maxSequences);
2324
0
    for (i = 0, position = 0; i < seqsSize; ++i) {
2325
0
        outSeqs[i].offset = seqs[i].offset;
2326
0
        outSeqs[i].litLength = seqs[i].litLength;
2327
0
        outSeqs[i].matchLength = seqs[i].matchLength + MINMATCH;
2328
2329
0
        if (i == seqStore->longLengthPos) {
2330
0
            if (seqStore->longLengthID == 1) {
2331
0
                outSeqs[i].litLength += 0x10000;
2332
0
            } else if (seqStore->longLengthID == 2) {
2333
0
                outSeqs[i].matchLength += 0x10000;
2334
0
            }
2335
0
        }
2336
2337
0
        if (outSeqs[i].offset <= ZSTD_REP_NUM) {
2338
0
            outSeqs[i].rep = outSeqs[i].offset;
2339
0
            repIdx = (unsigned int)i - outSeqs[i].offset;
2340
2341
0
            if (outSeqs[i].litLength == 0) {
2342
0
                if (outSeqs[i].offset < 3) {
2343
0
                    --repIdx;
2344
0
                } else {
2345
0
                    repIdx = (unsigned int)i - 1;
2346
0
                }
2347
0
                ++outSeqs[i].rep;
2348
0
            }
2349
0
            assert(repIdx >= -3);
2350
0
            outSeqs[i].offset = repIdx >= 0 ? outSeqs[repIdx].offset : ZSTDInternalConstants::repStartValue[-repIdx - 1];
2351
0
            if (outSeqs[i].rep == 4) {
2352
0
                --outSeqs[i].offset;
2353
0
            }
2354
0
        } else {
2355
0
            outSeqs[i].offset -= ZSTD_REP_NUM;
2356
0
        }
2357
2358
0
        position += outSeqs[i].litLength;
2359
0
        outSeqs[i].matchPos = (unsigned int)position;
2360
0
        position += outSeqs[i].matchLength;
2361
0
    }
2362
0
    zc->seqCollector.seqIndex += seqsSize;
2363
0
}
2364
2365
size_t ZSTD_getSequences(ZSTD_CCtx* zc, ZSTD_Sequence* outSeqs,
2366
    size_t outSeqsSize, const void* src, size_t srcSize)
2367
0
{
2368
0
    const size_t dstCapacity = ZSTD_compressBound(srcSize);
2369
0
    void* dst = ZSTD_malloc(dstCapacity, ZSTDInternalConstants::ZSTD_defaultCMem);
2370
0
    SeqCollector seqCollector;
2371
2372
0
    RETURN_ERROR_IF(dst == NULL, memory_allocation, "NULL pointer!");
2373
2374
0
    seqCollector.collectSequences = 1;
2375
0
    seqCollector.seqStart = outSeqs;
2376
0
    seqCollector.seqIndex = 0;
2377
0
    seqCollector.maxSequences = outSeqsSize;
2378
0
    zc->seqCollector = seqCollector;
2379
2380
0
    ZSTD_compress2(zc, dst, dstCapacity, src, srcSize);
2381
0
    ZSTD_free(dst, ZSTDInternalConstants::ZSTD_defaultCMem);
2382
0
    return zc->seqCollector.seqIndex;
2383
0
}
2384
2385
/* Returns true if the given block is a RLE block */
2386
0
static int ZSTD_isRLE(const BYTE *ip, size_t length) {
2387
0
    size_t i;
2388
0
    if (length < 2) return 1;
2389
0
    for (i = 1; i < length; ++i) {
2390
0
        if (ip[0] != ip[i]) return 0;
2391
0
    }
2392
0
    return 1;
2393
0
}
2394
2395
/* Returns true if the given block may be RLE.
2396
 * This is just a heuristic based on the compressibility.
2397
 * It may return both false positives and false negatives.
2398
 */
2399
static int ZSTD_maybeRLE(seqStore_t const* seqStore)
2400
0
{
2401
0
    size_t const nbSeqs = (size_t)(seqStore->sequences - seqStore->sequencesStart);
2402
0
    size_t const nbLits = (size_t)(seqStore->lit - seqStore->litStart);
2403
2404
0
    return nbSeqs < 4 && nbLits < 10;
2405
0
}
2406
2407
static void ZSTD_confirmRepcodesAndEntropyTables(ZSTD_CCtx* zc)
2408
0
{
2409
0
    ZSTD_compressedBlockState_t* const tmp = zc->blockState.prevCBlock;
2410
0
    zc->blockState.prevCBlock = zc->blockState.nextCBlock;
2411
0
    zc->blockState.nextCBlock = tmp;
2412
0
}
2413
2414
static size_t ZSTD_compressBlock_internal(ZSTD_CCtx* zc,
2415
                                        void* dst, size_t dstCapacity,
2416
                                        const void* src, size_t srcSize, U32 frame)
2417
0
{
2418
    /* This the upper bound for the length of an rle block.
2419
     * This isn't the actual upper bound. Finding the real threshold
2420
     * needs further investigation.
2421
     */
2422
0
    const U32 rleMaxLength = 25;
2423
0
    size_t cSize;
2424
0
    const BYTE* ip = (const BYTE*)src;
2425
0
    BYTE* op = (BYTE*)dst;
2426
0
    DEBUGLOG(5, "ZSTD_compressBlock_internal (dstCapacity=%u, dictLimit=%u, nextToUpdate=%u)",
2427
0
                (unsigned)dstCapacity, (unsigned)zc->blockState.matchState.window.dictLimit,
2428
0
                (unsigned)zc->blockState.matchState.nextToUpdate);
2429
2430
0
    {   const size_t bss = ZSTD_buildSeqStore(zc, src, srcSize);
2431
0
        FORWARD_IF_ERROR(bss, "ZSTD_buildSeqStore failed");
2432
0
        if (bss == ZSTDbss_noCompress) { cSize = 0; goto out; }
2433
0
    }
2434
2435
0
    if (zc->seqCollector.collectSequences) {
2436
0
        ZSTD_copyBlockSequences(zc);
2437
0
        return 0;
2438
0
    }
2439
2440
    /* encode sequences and literals */
2441
0
    cSize = ZSTD_compressSequences(&zc->seqStore,
2442
0
            &zc->blockState.prevCBlock->entropy, &zc->blockState.nextCBlock->entropy,
2443
0
            &zc->appliedParams,
2444
0
            dst, dstCapacity,
2445
0
            srcSize,
2446
0
            zc->entropyWorkspace, HUF_WORKSPACE_SIZE /* statically allocated in resetCCtx */,
2447
0
            zc->bmi2);
2448
2449
0
    if (frame &&
2450
        /* We don't want to emit our first block as a RLE even if it qualifies because
2451
         * doing so will cause the decoder (cli only) to throw a "should consume all input error."
2452
         * This is only an issue for zstd <= v1.4.3
2453
         */
2454
0
        !zc->isFirstBlock &&
2455
0
        cSize < rleMaxLength &&
2456
0
        ZSTD_isRLE(ip, srcSize))
2457
0
    {
2458
0
        cSize = 1;
2459
0
        op[0] = ip[0];
2460
0
    }
2461
2462
0
out:
2463
0
    if (!ZSTD_isError(cSize) && cSize > 1) {
2464
0
        ZSTD_confirmRepcodesAndEntropyTables(zc);
2465
0
    }
2466
    /* We check that dictionaries have offset codes available for the first
2467
     * block. After the first block, the offcode table might not have large
2468
     * enough codes to represent the offsets in the data.
2469
     */
2470
0
    if (zc->blockState.prevCBlock->entropy.fse.offcode_repeatMode == FSE_repeat_valid)
2471
0
        zc->blockState.prevCBlock->entropy.fse.offcode_repeatMode = FSE_repeat_check;
2472
2473
0
    return cSize;
2474
0
}
2475
2476
static size_t ZSTD_compressBlock_targetCBlockSize_body(ZSTD_CCtx* zc,
2477
                               void* dst, size_t dstCapacity,
2478
                               const void* src, size_t srcSize,
2479
                               const size_t bss, U32 lastBlock)
2480
0
{
2481
0
    DEBUGLOG(6, "Attempting ZSTD_compressSuperBlock()");
2482
0
    if (bss == ZSTDbss_compress) {
2483
0
        if (/* We don't want to emit our first block as a RLE even if it qualifies because
2484
            * doing so will cause the decoder (cli only) to throw a "should consume all input error."
2485
            * This is only an issue for zstd <= v1.4.3
2486
            */
2487
0
            !zc->isFirstBlock &&
2488
0
            ZSTD_maybeRLE(&zc->seqStore) &&
2489
0
            ZSTD_isRLE((BYTE const*)src, srcSize))
2490
0
        {
2491
0
            return ZSTD_rleCompressBlock(dst, dstCapacity, *(BYTE const*)src, srcSize, lastBlock);
2492
0
        }
2493
        /* Attempt superblock compression.
2494
         *
2495
         * Note that compressed size of ZSTD_compressSuperBlock() is not bound by the
2496
         * standard ZSTD_compressBound(). This is a problem, because even if we have
2497
         * space now, taking an extra byte now could cause us to run out of space later
2498
         * and violate ZSTD_compressBound().
2499
         *
2500
         * Define blockBound(blockSize) = blockSize + ZSTD_blockHeaderSize.
2501
         *
2502
         * In order to respect ZSTD_compressBound() we must attempt to emit a raw
2503
         * uncompressed block in these cases:
2504
         *   * cSize == 0: Return code for an uncompressed block.
2505
         *   * cSize == dstSize_tooSmall: We may have expanded beyond blockBound(srcSize).
2506
         *     ZSTD_noCompressBlock() will return dstSize_tooSmall if we are really out of
2507
         *     output space.
2508
         *   * cSize >= blockBound(srcSize): We have expanded the block too much so
2509
         *     emit an uncompressed block.
2510
         */
2511
0
        {
2512
0
            size_t const cSize = ZSTD_compressSuperBlock(zc, dst, dstCapacity, src, srcSize, lastBlock);
2513
0
            if (cSize != ERROR(dstSize_tooSmall)) {
2514
0
                size_t const maxCSize = srcSize - ZSTD_minGain(srcSize, zc->appliedParams.cParams.strategy);
2515
0
                FORWARD_IF_ERROR(cSize, "ZSTD_compressSuperBlock failed");
2516
0
                if (cSize != 0 && cSize < maxCSize + ZSTDInternalConstants::ZSTD_blockHeaderSize) {
2517
0
                    ZSTD_confirmRepcodesAndEntropyTables(zc);
2518
0
                    return cSize;
2519
0
                }
2520
0
            }
2521
0
        }
2522
0
    }
2523
2524
0
    DEBUGLOG(6, "Resorting to ZSTD_noCompressBlock()");
2525
    /* Superblock compression failed, attempt to emit a single no compress block.
2526
     * The decoder will be able to stream this block since it is uncompressed.
2527
     */
2528
0
    return ZSTD_noCompressBlock(dst, dstCapacity, src, srcSize, lastBlock);
2529
0
}
2530
2531
static size_t ZSTD_compressBlock_targetCBlockSize(ZSTD_CCtx* zc,
2532
                               void* dst, size_t dstCapacity,
2533
                               const void* src, size_t srcSize,
2534
                               U32 lastBlock)
2535
0
{
2536
0
    size_t cSize = 0;
2537
0
    const size_t bss = ZSTD_buildSeqStore(zc, src, srcSize);
2538
0
    DEBUGLOG(5, "ZSTD_compressBlock_targetCBlockSize (dstCapacity=%u, dictLimit=%u, nextToUpdate=%u, srcSize=%zu)",
2539
0
                (unsigned)dstCapacity, (unsigned)zc->blockState.matchState.window.dictLimit, (unsigned)zc->blockState.matchState.nextToUpdate, srcSize);
2540
0
    FORWARD_IF_ERROR(bss, "ZSTD_buildSeqStore failed");
2541
2542
0
    cSize = ZSTD_compressBlock_targetCBlockSize_body(zc, dst, dstCapacity, src, srcSize, bss, lastBlock);
2543
0
    FORWARD_IF_ERROR(cSize, "ZSTD_compressBlock_targetCBlockSize_body failed");
2544
2545
0
    if (zc->blockState.prevCBlock->entropy.fse.offcode_repeatMode == FSE_repeat_valid)
2546
0
        zc->blockState.prevCBlock->entropy.fse.offcode_repeatMode = FSE_repeat_check;
2547
2548
0
    return cSize;
2549
0
}
2550
2551
static void ZSTD_overflowCorrectIfNeeded(ZSTD_matchState_t* ms,
2552
                                         ZSTD_cwksp* ws,
2553
                                         ZSTD_CCtx_params const* params,
2554
                                         void const* ip,
2555
                                         void const* iend)
2556
0
{
2557
0
    if (ZSTD_window_needOverflowCorrection(ms->window, iend)) {
2558
0
        U32 const maxDist = (U32)1 << params->cParams.windowLog;
2559
0
        U32 const cycleLog = ZSTD_cycleLog(params->cParams.chainLog, params->cParams.strategy);
2560
0
        U32 const correction = ZSTD_window_correctOverflow(&ms->window, cycleLog, maxDist, ip);
2561
0
        ZSTD_STATIC_ASSERT(ZSTD_CHAINLOG_MAX <= 30);
2562
0
        ZSTD_STATIC_ASSERT(ZSTD_WINDOWLOG_MAX_32 <= 30);
2563
0
        ZSTD_STATIC_ASSERT(ZSTD_WINDOWLOG_MAX <= 31);
2564
0
        ZSTD_cwksp_mark_tables_dirty(ws);
2565
0
        ZSTD_reduceIndex(ms, params, correction);
2566
0
        ZSTD_cwksp_mark_tables_clean(ws);
2567
0
        if (ms->nextToUpdate < correction) ms->nextToUpdate = 0;
2568
0
        else ms->nextToUpdate -= correction;
2569
        /* invalidate dictionaries on overflow correction */
2570
0
        ms->loadedDictEnd = 0;
2571
0
        ms->dictMatchState = NULL;
2572
0
    }
2573
0
}
2574
2575
/*! ZSTD_compress_frameChunk() :
2576
*   Compress a chunk of data into one or multiple blocks.
2577
*   All blocks will be terminated, all input will be consumed.
2578
*   Function will issue an error if there is not enough `dstCapacity` to hold the compressed content.
2579
*   Frame is supposed already started (header already produced)
2580
*   @return : compressed size, or an error code
2581
*/
2582
static size_t ZSTD_compress_frameChunk (ZSTD_CCtx* cctx,
2583
                                     void* dst, size_t dstCapacity,
2584
                               const void* src, size_t srcSize,
2585
                                     U32 lastFrameChunk)
2586
0
{
2587
0
    size_t blockSize = cctx->blockSize;
2588
0
    size_t remaining = srcSize;
2589
0
    const BYTE* ip = (const BYTE*)src;
2590
0
    BYTE* const ostart = (BYTE*)dst;
2591
0
    BYTE* op = ostart;
2592
0
    U32 const maxDist = (U32)1 << cctx->appliedParams.cParams.windowLog;
2593
2594
0
    assert(cctx->appliedParams.cParams.windowLog <= ZSTD_WINDOWLOG_MAX);
2595
2596
0
    DEBUGLOG(5, "ZSTD_compress_frameChunk (blockSize=%u)", (unsigned)blockSize);
2597
0
    if (cctx->appliedParams.fParams.checksumFlag && srcSize)
2598
0
        XXH64_update(&cctx->xxhState, src, srcSize);
2599
2600
0
    while (remaining) {
2601
0
        ZSTD_matchState_t* const ms = &cctx->blockState.matchState;
2602
0
        U32 const lastBlock = lastFrameChunk & (blockSize >= remaining);
2603
2604
0
        RETURN_ERROR_IF(dstCapacity < ZSTDInternalConstants::ZSTD_blockHeaderSize + MIN_CBLOCK_SIZE,
2605
0
                        dstSize_tooSmall,
2606
0
                        "not enough space to store compressed block");
2607
0
        if (remaining < blockSize) blockSize = remaining;
2608
2609
0
        ZSTD_overflowCorrectIfNeeded(
2610
0
            ms, &cctx->workspace, &cctx->appliedParams, ip, ip + blockSize);
2611
0
        ZSTD_checkDictValidity(&ms->window, ip + blockSize, maxDist, &ms->loadedDictEnd, &ms->dictMatchState);
2612
2613
        /* Ensure hash/chain table insertion resumes no sooner than lowlimit */
2614
0
        if (ms->nextToUpdate < ms->window.lowLimit) ms->nextToUpdate = ms->window.lowLimit;
2615
2616
0
        {   size_t cSize;
2617
0
            if (ZSTD_useTargetCBlockSize(&cctx->appliedParams)) {
2618
0
                cSize = ZSTD_compressBlock_targetCBlockSize(cctx, op, dstCapacity, ip, blockSize, lastBlock);
2619
0
                FORWARD_IF_ERROR(cSize, "ZSTD_compressBlock_targetCBlockSize failed");
2620
0
                assert(cSize > 0);
2621
0
                assert(cSize <= blockSize + ZSTDInternalConstants::ZSTD_blockHeaderSize);
2622
0
            } else {
2623
0
                cSize = ZSTD_compressBlock_internal(cctx,
2624
0
                                        op+ZSTDInternalConstants::ZSTD_blockHeaderSize, dstCapacity-ZSTDInternalConstants::ZSTD_blockHeaderSize,
2625
0
                                        ip, blockSize, 1 /* frame */);
2626
0
                FORWARD_IF_ERROR(cSize, "ZSTD_compressBlock_internal failed");
2627
2628
0
                if (cSize == 0) {  /* block is not compressible */
2629
0
                    cSize = ZSTD_noCompressBlock(op, dstCapacity, ip, blockSize, lastBlock);
2630
0
                    FORWARD_IF_ERROR(cSize, "ZSTD_noCompressBlock failed");
2631
0
                } else {
2632
0
                    U32 const cBlockHeader = cSize == 1 ?
2633
0
                        lastBlock + (((U32)bt_rle)<<1) + (U32)(blockSize << 3) :
2634
0
                        lastBlock + (((U32)bt_compressed)<<1) + (U32)(cSize << 3);
2635
0
                    MEM_writeLE24(op, cBlockHeader);
2636
0
                    cSize += ZSTDInternalConstants::ZSTD_blockHeaderSize;
2637
0
                }
2638
0
            }
2639
2640
2641
0
            ip += blockSize;
2642
0
            assert(remaining >= blockSize);
2643
0
            remaining -= blockSize;
2644
0
            op += cSize;
2645
0
            assert(dstCapacity >= cSize);
2646
0
            dstCapacity -= cSize;
2647
0
            cctx->isFirstBlock = 0;
2648
0
            DEBUGLOG(5, "ZSTD_compress_frameChunk: adding a block of size %u",
2649
0
                        (unsigned)cSize);
2650
0
    }   }
2651
2652
0
    if (lastFrameChunk && (op>ostart)) cctx->stage = ZSTDcs_ending;
2653
0
    return (size_t)(op-ostart);
2654
0
}
2655
2656
2657
static size_t ZSTD_writeFrameHeader(void* dst, size_t dstCapacity,
2658
                                    const ZSTD_CCtx_params* params, U64 pledgedSrcSize, U32 dictID)
2659
0
{   BYTE* const op = (BYTE*)dst;
2660
0
    U32   const dictIDSizeCodeLength = (dictID>0) + (dictID>=256) + (dictID>=65536);   /* 0-3 */
2661
0
    U32   const dictIDSizeCode = params->fParams.noDictIDFlag ? 0 : dictIDSizeCodeLength;   /* 0-3 */
2662
0
    U32   const checksumFlag = params->fParams.checksumFlag>0;
2663
0
    U32   const windowSize = (U32)1 << params->cParams.windowLog;
2664
0
    U32   const singleSegment = params->fParams.contentSizeFlag && (windowSize >= pledgedSrcSize);
2665
0
    BYTE  const windowLogByte = (BYTE)((params->cParams.windowLog - ZSTD_WINDOWLOG_ABSOLUTEMIN) << 3);
2666
0
    U32   const fcsCode = params->fParams.contentSizeFlag ?
2667
0
                     (pledgedSrcSize>=256) + (pledgedSrcSize>=65536+256) + (pledgedSrcSize>=0xFFFFFFFFU) : 0;  /* 0-3 */
2668
0
    BYTE  const frameHeaderDescriptionByte = (BYTE)(dictIDSizeCode + (checksumFlag<<2) + (singleSegment<<5) + (fcsCode<<6) );
2669
0
    size_t pos=0;
2670
2671
0
    assert(!(params->fParams.contentSizeFlag && pledgedSrcSize == ZSTD_CONTENTSIZE_UNKNOWN));
2672
0
    RETURN_ERROR_IF(dstCapacity < ZSTD_FRAMEHEADERSIZE_MAX, dstSize_tooSmall,
2673
0
                    "dst buf is too small to fit worst-case frame header size.");
2674
0
    DEBUGLOG(4, "ZSTD_writeFrameHeader : dictIDFlag : %u ; dictID : %u ; dictIDSizeCode : %u",
2675
0
                !params->fParams.noDictIDFlag, (unsigned)dictID, (unsigned)dictIDSizeCode);
2676
2677
0
    if (params->format == ZSTD_f_zstd1) {
2678
0
        MEM_writeLE32(dst, ZSTD_MAGICNUMBER);
2679
0
        pos = 4;
2680
0
    }
2681
0
    op[pos++] = frameHeaderDescriptionByte;
2682
0
    if (!singleSegment) op[pos++] = windowLogByte;
2683
0
    switch(dictIDSizeCode)
2684
0
    {
2685
0
        default:  assert(0); /* impossible */
2686
0
        case 0 : break;
2687
0
        case 1 : op[pos] = (BYTE)(dictID); pos++; break;
2688
0
        case 2 : MEM_writeLE16(op+pos, (U16)dictID); pos+=2; break;
2689
0
        case 3 : MEM_writeLE32(op+pos, dictID); pos+=4; break;
2690
0
    }
2691
0
    switch(fcsCode)
2692
0
    {
2693
0
        default:  assert(0); /* impossible */
2694
0
        case 0 : if (singleSegment) op[pos++] = (BYTE)(pledgedSrcSize); break;
2695
0
        case 1 : MEM_writeLE16(op+pos, (U16)(pledgedSrcSize-256)); pos+=2; break;
2696
0
        case 2 : MEM_writeLE32(op+pos, (U32)(pledgedSrcSize)); pos+=4; break;
2697
0
        case 3 : MEM_writeLE64(op+pos, (U64)(pledgedSrcSize)); pos+=8; break;
2698
0
    }
2699
0
    return pos;
2700
0
}
2701
2702
/* ZSTD_writeLastEmptyBlock() :
2703
 * output an empty Block with end-of-frame mark to complete a frame
2704
 * @return : size of data written into `dst` (== ZSTD_blockHeaderSize (defined in zstd_internal.h))
2705
 *           or an error code if `dstCapacity` is too small (<ZSTD_blockHeaderSize)
2706
 */
2707
size_t ZSTD_writeLastEmptyBlock(void* dst, size_t dstCapacity)
2708
0
{
2709
0
    RETURN_ERROR_IF(dstCapacity < ZSTDInternalConstants::ZSTD_blockHeaderSize, dstSize_tooSmall,
2710
0
                    "dst buf is too small to write frame trailer empty block.");
2711
0
    {   U32 const cBlockHeader24 = 1 /*lastBlock*/ + (((U32)bt_raw)<<1);  /* 0 size */
2712
0
        MEM_writeLE24(dst, cBlockHeader24);
2713
0
        return ZSTDInternalConstants::ZSTD_blockHeaderSize;
2714
0
    }
2715
0
}
2716
2717
size_t ZSTD_referenceExternalSequences(ZSTD_CCtx* cctx, rawSeq* seq, size_t nbSeq)
2718
0
{
2719
0
    RETURN_ERROR_IF(cctx->stage != ZSTDcs_init, stage_wrong,
2720
0
                    "wrong cctx stage");
2721
0
    RETURN_ERROR_IF(cctx->appliedParams.ldmParams.enableLdm,
2722
0
                    parameter_unsupported,
2723
0
                    "incompatible with ldm");
2724
0
    cctx->externSeqStore.seq = seq;
2725
0
    cctx->externSeqStore.size = nbSeq;
2726
0
    cctx->externSeqStore.capacity = nbSeq;
2727
0
    cctx->externSeqStore.pos = 0;
2728
0
    return 0;
2729
0
}
2730
2731
2732
static size_t ZSTD_compressContinue_internal (ZSTD_CCtx* cctx,
2733
                              void* dst, size_t dstCapacity,
2734
                        const void* src, size_t srcSize,
2735
                               U32 frame, U32 lastFrameChunk)
2736
0
{
2737
0
    ZSTD_matchState_t* const ms = &cctx->blockState.matchState;
2738
0
    size_t fhSize = 0;
2739
2740
0
    DEBUGLOG(5, "ZSTD_compressContinue_internal, stage: %u, srcSize: %u",
2741
0
                cctx->stage, (unsigned)srcSize);
2742
0
    RETURN_ERROR_IF(cctx->stage==ZSTDcs_created, stage_wrong,
2743
0
                    "missing init (ZSTD_compressBegin)");
2744
2745
0
    if (frame && (cctx->stage==ZSTDcs_init)) {
2746
0
        fhSize = ZSTD_writeFrameHeader(dst, dstCapacity, &cctx->appliedParams,
2747
0
                                       cctx->pledgedSrcSizePlusOne-1, cctx->dictID);
2748
0
        FORWARD_IF_ERROR(fhSize, "ZSTD_writeFrameHeader failed");
2749
0
        assert(fhSize <= dstCapacity);
2750
0
        dstCapacity -= fhSize;
2751
0
        dst = (char*)dst + fhSize;
2752
0
        cctx->stage = ZSTDcs_ongoing;
2753
0
    }
2754
2755
0
    if (!srcSize) return fhSize;  /* do not generate an empty block if no input */
2756
2757
0
    if (!ZSTD_window_update(&ms->window, src, srcSize)) {
2758
0
        ms->nextToUpdate = ms->window.dictLimit;
2759
0
    }
2760
0
    if (cctx->appliedParams.ldmParams.enableLdm) {
2761
0
        ZSTD_window_update(&cctx->ldmState.window, src, srcSize);
2762
0
    }
2763
2764
0
    if (!frame) {
2765
        /* overflow check and correction for block mode */
2766
0
        ZSTD_overflowCorrectIfNeeded(
2767
0
            ms, &cctx->workspace, &cctx->appliedParams,
2768
0
            src, (BYTE const*)src + srcSize);
2769
0
    }
2770
2771
0
    DEBUGLOG(5, "ZSTD_compressContinue_internal (blockSize=%u)", (unsigned)cctx->blockSize);
2772
0
    {   size_t const cSize = frame ?
2773
0
                             ZSTD_compress_frameChunk (cctx, dst, dstCapacity, src, srcSize, lastFrameChunk) :
2774
0
                             ZSTD_compressBlock_internal (cctx, dst, dstCapacity, src, srcSize, 0 /* frame */);
2775
0
        FORWARD_IF_ERROR(cSize, "%s", frame ? "ZSTD_compress_frameChunk failed" : "ZSTD_compressBlock_internal failed");
2776
0
        cctx->consumedSrcSize += srcSize;
2777
0
        cctx->producedCSize += (cSize + fhSize);
2778
0
        assert(!(cctx->appliedParams.fParams.contentSizeFlag && cctx->pledgedSrcSizePlusOne == 0));
2779
0
        if (cctx->pledgedSrcSizePlusOne != 0) {  /* control src size */
2780
0
            ZSTD_STATIC_ASSERT(ZSTD_CONTENTSIZE_UNKNOWN == (unsigned long long)-1);
2781
0
            RETURN_ERROR_IF(
2782
0
                cctx->consumedSrcSize+1 > cctx->pledgedSrcSizePlusOne,
2783
0
                srcSize_wrong,
2784
0
                "error : pledgedSrcSize = %u, while realSrcSize >= %u",
2785
0
                (unsigned)cctx->pledgedSrcSizePlusOne-1,
2786
0
                (unsigned)cctx->consumedSrcSize);
2787
0
        }
2788
0
        return cSize + fhSize;
2789
0
    }
2790
0
}
2791
2792
size_t ZSTD_compressContinue (ZSTD_CCtx* cctx,
2793
                              void* dst, size_t dstCapacity,
2794
                        const void* src, size_t srcSize)
2795
0
{
2796
0
    DEBUGLOG(5, "ZSTD_compressContinue (srcSize=%u)", (unsigned)srcSize);
2797
0
    return ZSTD_compressContinue_internal(cctx, dst, dstCapacity, src, srcSize, 1 /* frame mode */, 0 /* last chunk */);
2798
0
}
2799
2800
2801
size_t ZSTD_getBlockSize(const ZSTD_CCtx* cctx)
2802
0
{
2803
0
    ZSTD_compressionParameters const cParams = cctx->appliedParams.cParams;
2804
0
    assert(!ZSTD_checkCParams(cParams));
2805
0
    return MIN (ZSTD_BLOCKSIZE_MAX, (U32)1 << cParams.windowLog);
2806
0
}
2807
2808
size_t ZSTD_compressBlock(ZSTD_CCtx* cctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize)
2809
0
{
2810
0
    DEBUGLOG(5, "ZSTD_compressBlock: srcSize = %u", (unsigned)srcSize);
2811
0
    { size_t const blockSizeMax = ZSTD_getBlockSize(cctx);
2812
0
      RETURN_ERROR_IF(srcSize > blockSizeMax, srcSize_wrong, "input is larger than a block"); }
2813
2814
0
    return ZSTD_compressContinue_internal(cctx, dst, dstCapacity, src, srcSize, 0 /* frame mode */, 0 /* last chunk */);
2815
0
}
2816
2817
/*! ZSTD_loadDictionaryContent() :
2818
 *  @return : 0, or an error code
2819
 */
2820
static size_t ZSTD_loadDictionaryContent(ZSTD_matchState_t* ms,
2821
                                         ldmState_t* ls,
2822
                                         ZSTD_cwksp* ws,
2823
                                         ZSTD_CCtx_params const* params,
2824
                                         const void* src, size_t srcSize,
2825
                                         ZSTD_dictTableLoadMethod_e dtlm)
2826
0
{
2827
0
    const BYTE* ip = (const BYTE*) src;
2828
0
    const BYTE* const iend = ip + srcSize;
2829
2830
0
    ZSTD_window_update(&ms->window, src, srcSize);
2831
0
    ms->loadedDictEnd = params->forceWindow ? 0 : (U32)(iend - ms->window.base);
2832
2833
0
    if (params->ldmParams.enableLdm && ls != NULL) {
2834
0
        ZSTD_window_update(&ls->window, src, srcSize);
2835
0
        ls->loadedDictEnd = params->forceWindow ? 0 : (U32)(iend - ls->window.base);
2836
0
    }
2837
2838
    /* Assert that we the ms params match the params we're being given */
2839
0
    ZSTD_assertEqualCParams(params->cParams, ms->cParams);
2840
2841
0
    if (srcSize <= HASH_READ_SIZE) return 0;
2842
2843
0
    while (iend - ip > HASH_READ_SIZE) {
2844
0
        size_t const remaining = (size_t)(iend - ip);
2845
0
        size_t const chunk = MIN(remaining, ZSTD_CHUNKSIZE_MAX);
2846
0
        const BYTE* const ichunk = ip + chunk;
2847
2848
0
        ZSTD_overflowCorrectIfNeeded(ms, ws, params, ip, ichunk);
2849
2850
0
        if (params->ldmParams.enableLdm && ls != NULL)
2851
0
            ZSTD_ldm_fillHashTable(ls, (const BYTE*)src, (const BYTE*)src + srcSize, &params->ldmParams);
2852
2853
0
        switch(params->cParams.strategy)
2854
0
        {
2855
0
        case ZSTD_fast:
2856
0
            ZSTD_fillHashTable(ms, ichunk, dtlm);
2857
0
            break;
2858
0
        case ZSTD_dfast:
2859
0
            ZSTD_fillDoubleHashTable(ms, ichunk, dtlm);
2860
0
            break;
2861
2862
0
        case ZSTD_greedy:
2863
0
        case ZSTD_lazy:
2864
0
        case ZSTD_lazy2:
2865
0
            if (chunk >= HASH_READ_SIZE)
2866
0
                ZSTD_insertAndFindFirstIndex(ms, ichunk-HASH_READ_SIZE);
2867
0
            break;
2868
2869
0
        case ZSTD_btlazy2:   /* we want the dictionary table fully sorted */
2870
0
        case ZSTD_btopt:
2871
0
        case ZSTD_btultra:
2872
0
        case ZSTD_btultra2:
2873
0
            if (chunk >= HASH_READ_SIZE)
2874
0
                ZSTD_updateTree(ms, ichunk-HASH_READ_SIZE, ichunk);
2875
0
            break;
2876
2877
0
        default:
2878
0
            assert(0);  /* not possible : not a valid strategy id */
2879
0
        }
2880
2881
0
        ip = ichunk;
2882
0
    }
2883
2884
0
    ms->nextToUpdate = (U32)(iend - ms->window.base);
2885
0
    return 0;
2886
0
}
2887
2888
2889
/* Dictionaries that assign zero probability to symbols that show up causes problems
2890
   when FSE encoding.  Refuse dictionaries that assign zero probability to symbols
2891
   that we may encounter during compression.
2892
   NOTE: This behavior is not standard and could be improved in the future. */
2893
0
static size_t ZSTD_checkDictNCount(short* normalizedCounter, unsigned dictMaxSymbolValue, unsigned maxSymbolValue) {
2894
0
    U32 s;
2895
0
    RETURN_ERROR_IF(dictMaxSymbolValue < maxSymbolValue, dictionary_corrupted, "dict fse tables don't have all symbols");
2896
0
    for (s = 0; s <= maxSymbolValue; ++s) {
2897
0
        RETURN_ERROR_IF(normalizedCounter[s] == 0, dictionary_corrupted, "dict fse tables don't have all symbols");
2898
0
    }
2899
0
    return 0;
2900
0
}
2901
2902
size_t ZSTD_loadCEntropy(ZSTD_compressedBlockState_t* bs, void* workspace,
2903
                         short* offcodeNCount, unsigned* offcodeMaxValue,
2904
                         const void* const dict, size_t dictSize)
2905
0
{
2906
0
    const BYTE* dictPtr = (const BYTE*)dict;    /* skip magic num and dict ID */
2907
0
    const BYTE* const dictEnd = dictPtr + dictSize;
2908
0
    dictPtr += 8;
2909
0
    bs->entropy.huf.repeatMode = HUF_repeat_check;
2910
2911
0
    {   unsigned maxSymbolValue = 255;
2912
0
        unsigned hasZeroWeights = 1;
2913
0
        size_t const hufHeaderSize = HUF_readCTable((HUF_CElt*)bs->entropy.huf.CTable, &maxSymbolValue, dictPtr,
2914
0
            dictEnd-dictPtr, &hasZeroWeights);
2915
2916
        /* We only set the loaded table as valid if it contains all non-zero
2917
         * weights. Otherwise, we set it to check */
2918
0
        if (!hasZeroWeights)
2919
0
            bs->entropy.huf.repeatMode = HUF_repeat_valid;
2920
2921
0
        RETURN_ERROR_IF(HUF_isError(hufHeaderSize), dictionary_corrupted, "");
2922
0
        RETURN_ERROR_IF(maxSymbolValue < 255, dictionary_corrupted, "");
2923
0
        dictPtr += hufHeaderSize;
2924
0
    }
2925
2926
0
    {   unsigned offcodeLog;
2927
0
        size_t const offcodeHeaderSize = FSE_readNCount(offcodeNCount, offcodeMaxValue, &offcodeLog, dictPtr, dictEnd-dictPtr);
2928
0
        RETURN_ERROR_IF(FSE_isError(offcodeHeaderSize), dictionary_corrupted, "");
2929
0
        RETURN_ERROR_IF(offcodeLog > OffFSELog, dictionary_corrupted, "");
2930
        /* Defer checking offcodeMaxValue because we need to know the size of the dictionary content */
2931
        /* fill all offset symbols to avoid garbage at end of table */
2932
0
        RETURN_ERROR_IF(FSE_isError(FSE_buildCTable_wksp(
2933
0
                bs->entropy.fse.offcodeCTable,
2934
0
                offcodeNCount, MaxOff, offcodeLog,
2935
0
                workspace, HUF_WORKSPACE_SIZE)),
2936
0
            dictionary_corrupted, "");
2937
0
        dictPtr += offcodeHeaderSize;
2938
0
    }
2939
2940
0
    {   short matchlengthNCount[MaxML+1];
2941
0
        unsigned matchlengthMaxValue = MaxML, matchlengthLog;
2942
0
        size_t const matchlengthHeaderSize = FSE_readNCount(matchlengthNCount, &matchlengthMaxValue, &matchlengthLog, dictPtr, dictEnd-dictPtr);
2943
0
        RETURN_ERROR_IF(FSE_isError(matchlengthHeaderSize), dictionary_corrupted, "");
2944
0
        RETURN_ERROR_IF(matchlengthLog > MLFSELog, dictionary_corrupted, "");
2945
        /* Every match length code must have non-zero probability */
2946
0
        FORWARD_IF_ERROR( ZSTD_checkDictNCount(matchlengthNCount, matchlengthMaxValue, MaxML), "");
2947
0
        RETURN_ERROR_IF(FSE_isError(FSE_buildCTable_wksp(
2948
0
                bs->entropy.fse.matchlengthCTable,
2949
0
                matchlengthNCount, matchlengthMaxValue, matchlengthLog,
2950
0
                workspace, HUF_WORKSPACE_SIZE)),
2951
0
            dictionary_corrupted, "");
2952
0
        dictPtr += matchlengthHeaderSize;
2953
0
    }
2954
2955
0
    {   short litlengthNCount[MaxLL+1];
2956
0
        unsigned litlengthMaxValue = MaxLL, litlengthLog;
2957
0
        size_t const litlengthHeaderSize = FSE_readNCount(litlengthNCount, &litlengthMaxValue, &litlengthLog, dictPtr, dictEnd-dictPtr);
2958
0
        RETURN_ERROR_IF(FSE_isError(litlengthHeaderSize), dictionary_corrupted, "");
2959
0
        RETURN_ERROR_IF(litlengthLog > LLFSELog, dictionary_corrupted, "");
2960
        /* Every literal length code must have non-zero probability */
2961
0
        FORWARD_IF_ERROR( ZSTD_checkDictNCount(litlengthNCount, litlengthMaxValue, MaxLL), "");
2962
0
        RETURN_ERROR_IF(FSE_isError(FSE_buildCTable_wksp(
2963
0
                bs->entropy.fse.litlengthCTable,
2964
0
                litlengthNCount, litlengthMaxValue, litlengthLog,
2965
0
                workspace, HUF_WORKSPACE_SIZE)),
2966
0
            dictionary_corrupted, "");
2967
0
        dictPtr += litlengthHeaderSize;
2968
0
    }
2969
2970
0
    RETURN_ERROR_IF(dictPtr+12 > dictEnd, dictionary_corrupted, "");
2971
0
    bs->rep[0] = MEM_readLE32(dictPtr+0);
2972
0
    bs->rep[1] = MEM_readLE32(dictPtr+4);
2973
0
    bs->rep[2] = MEM_readLE32(dictPtr+8);
2974
0
    dictPtr += 12;
2975
2976
0
    return dictPtr - (const BYTE*)dict;
2977
0
}
2978
2979
/* Dictionary format :
2980
 * See :
2981
 * https://github.com/facebook/zstd/blob/master/doc/zstd_compression_format.md#dictionary-format
2982
 */
2983
/*! ZSTD_loadZstdDictionary() :
2984
 * @return : dictID, or an error code
2985
 *  assumptions : magic number supposed already checked
2986
 *                dictSize supposed >= 8
2987
 */
2988
static size_t ZSTD_loadZstdDictionary(ZSTD_compressedBlockState_t* bs,
2989
                                      ZSTD_matchState_t* ms,
2990
                                      ZSTD_cwksp* ws,
2991
                                      ZSTD_CCtx_params const* params,
2992
                                      const void* dict, size_t dictSize,
2993
                                      ZSTD_dictTableLoadMethod_e dtlm,
2994
                                      void* workspace)
2995
0
{
2996
0
    const BYTE* dictPtr = (const BYTE*)dict;
2997
0
    const BYTE* const dictEnd = dictPtr + dictSize;
2998
0
    short offcodeNCount[MaxOff+1];
2999
0
    unsigned offcodeMaxValue = MaxOff;
3000
0
    size_t dictID;
3001
0
    size_t eSize;
3002
3003
0
    ZSTD_STATIC_ASSERT(HUF_WORKSPACE_SIZE >= (1<<MAX(MLFSELog,LLFSELog)));
3004
0
    assert(dictSize >= 8);
3005
0
    assert(MEM_readLE32(dictPtr) == ZSTD_MAGIC_DICTIONARY);
3006
3007
0
    dictID = params->fParams.noDictIDFlag ? 0 :  MEM_readLE32(dictPtr + 4 /* skip magic number */ );
3008
0
    eSize = ZSTD_loadCEntropy(bs, workspace, offcodeNCount, &offcodeMaxValue, dict, dictSize);
3009
0
    FORWARD_IF_ERROR(eSize, "ZSTD_loadCEntropy failed");
3010
0
    dictPtr += eSize;
3011
3012
0
    {   size_t const dictContentSize = (size_t)(dictEnd - dictPtr);
3013
0
        U32 offcodeMax = MaxOff;
3014
0
        if (dictContentSize <= ((U32)-1) - 128 KB) {
3015
0
            U32 const maxOffset = (U32)dictContentSize + 128 KB; /* The maximum offset that must be supported */
3016
0
            offcodeMax = ZSTD_highbit32(maxOffset); /* Calculate minimum offset code required to represent maxOffset */
3017
0
        }
3018
        /* All offset values <= dictContentSize + 128 KB must be representable */
3019
0
        FORWARD_IF_ERROR(ZSTD_checkDictNCount(offcodeNCount, offcodeMaxValue, MIN(offcodeMax, MaxOff)), "");
3020
        /* All repCodes must be <= dictContentSize and != 0*/
3021
0
        {   U32 u;
3022
0
            for (u=0; u<3; u++) {
3023
0
                RETURN_ERROR_IF(bs->rep[u] == 0, dictionary_corrupted, "");
3024
0
                RETURN_ERROR_IF(bs->rep[u] > dictContentSize, dictionary_corrupted, "");
3025
0
        }   }
3026
3027
0
        bs->entropy.fse.offcode_repeatMode = FSE_repeat_valid;
3028
0
        bs->entropy.fse.matchlength_repeatMode = FSE_repeat_valid;
3029
0
        bs->entropy.fse.litlength_repeatMode = FSE_repeat_valid;
3030
0
        FORWARD_IF_ERROR(ZSTD_loadDictionaryContent(
3031
0
            ms, NULL, ws, params, dictPtr, dictContentSize, dtlm), "");
3032
0
        return dictID;
3033
0
    }
3034
0
}
3035
3036
/** ZSTD_compress_insertDictionary() :
3037
*   @return : dictID, or an error code */
3038
static size_t
3039
ZSTD_compress_insertDictionary(ZSTD_compressedBlockState_t* bs,
3040
                               ZSTD_matchState_t* ms,
3041
                               ldmState_t* ls,
3042
                               ZSTD_cwksp* ws,
3043
                         const ZSTD_CCtx_params* params,
3044
                         const void* dict, size_t dictSize,
3045
                               ZSTD_dictContentType_e dictContentType,
3046
                               ZSTD_dictTableLoadMethod_e dtlm,
3047
                               void* workspace)
3048
0
{
3049
0
    DEBUGLOG(4, "ZSTD_compress_insertDictionary (dictSize=%u)", (U32)dictSize);
3050
0
    if ((dict==NULL) || (dictSize<8)) {
3051
0
        RETURN_ERROR_IF(dictContentType == ZSTD_dct_fullDict, dictionary_wrong, "");
3052
0
        return 0;
3053
0
    }
3054
3055
0
    ZSTD_reset_compressedBlockState(bs);
3056
3057
    /* dict restricted modes */
3058
0
    if (dictContentType == ZSTD_dct_rawContent)
3059
0
        return ZSTD_loadDictionaryContent(ms, ls, ws, params, dict, dictSize, dtlm);
3060
3061
0
    if (MEM_readLE32(dict) != ZSTD_MAGIC_DICTIONARY) {
3062
0
        if (dictContentType == ZSTD_dct_auto) {
3063
0
            DEBUGLOG(4, "raw content dictionary detected");
3064
0
            return ZSTD_loadDictionaryContent(
3065
0
                ms, ls, ws, params, dict, dictSize, dtlm);
3066
0
        }
3067
0
        RETURN_ERROR_IF(dictContentType == ZSTD_dct_fullDict, dictionary_wrong, "");
3068
0
        assert(0);   /* impossible */
3069
0
    }
3070
3071
    /* dict as full zstd dictionary */
3072
0
    return ZSTD_loadZstdDictionary(
3073
0
        bs, ms, ws, params, dict, dictSize, dtlm, workspace);
3074
0
}
3075
3076
0
#define ZSTD_USE_CDICT_PARAMS_SRCSIZE_CUTOFF (128 KB)
3077
0
#define ZSTD_USE_CDICT_PARAMS_DICTSIZE_MULTIPLIER (6)
3078
3079
/*! ZSTD_compressBegin_internal() :
3080
 * @return : 0, or an error code */
3081
static size_t ZSTD_compressBegin_internal(ZSTD_CCtx* cctx,
3082
                                    const void* dict, size_t dictSize,
3083
                                    ZSTD_dictContentType_e dictContentType,
3084
                                    ZSTD_dictTableLoadMethod_e dtlm,
3085
                                    const ZSTD_CDict* cdict,
3086
                                    const ZSTD_CCtx_params* params, U64 pledgedSrcSize,
3087
                                    ZSTD_buffered_policy_e zbuff)
3088
0
{
3089
0
    DEBUGLOG(4, "ZSTD_compressBegin_internal: wlog=%u", params->cParams.windowLog);
3090
    /* params are supposed to be fully validated at this point */
3091
0
    assert(!ZSTD_isError(ZSTD_checkCParams(params->cParams)));
3092
0
    assert(!((dict) && (cdict)));  /* either dict or cdict, not both */
3093
0
    if ( (cdict)
3094
0
      && (cdict->dictContentSize > 0)
3095
0
      && ( pledgedSrcSize < ZSTD_USE_CDICT_PARAMS_SRCSIZE_CUTOFF
3096
0
        || pledgedSrcSize < cdict->dictContentSize * ZSTD_USE_CDICT_PARAMS_DICTSIZE_MULTIPLIER
3097
0
        || pledgedSrcSize == ZSTD_CONTENTSIZE_UNKNOWN
3098
0
        || cdict->compressionLevel == 0)
3099
0
      && (params->attachDictPref != ZSTD_dictForceLoad) ) {
3100
0
        return ZSTD_resetCCtx_usingCDict(cctx, cdict, params, pledgedSrcSize, zbuff);
3101
0
    }
3102
3103
0
    FORWARD_IF_ERROR( ZSTD_resetCCtx_internal(cctx, *params, pledgedSrcSize,
3104
0
                                     ZSTDcrp_makeClean, zbuff) , "");
3105
0
    {   size_t const dictID = cdict ?
3106
0
                ZSTD_compress_insertDictionary(
3107
0
                        cctx->blockState.prevCBlock, &cctx->blockState.matchState,
3108
0
                        &cctx->ldmState, &cctx->workspace, &cctx->appliedParams, cdict->dictContent,
3109
0
                        cdict->dictContentSize, dictContentType, dtlm,
3110
0
                        cctx->entropyWorkspace)
3111
0
              : ZSTD_compress_insertDictionary(
3112
0
                        cctx->blockState.prevCBlock, &cctx->blockState.matchState,
3113
0
                        &cctx->ldmState, &cctx->workspace, &cctx->appliedParams, dict, dictSize,
3114
0
                        dictContentType, dtlm, cctx->entropyWorkspace);
3115
0
        FORWARD_IF_ERROR(dictID, "ZSTD_compress_insertDictionary failed");
3116
0
        assert(dictID <= UINT_MAX);
3117
0
        cctx->dictID = (U32)dictID;
3118
0
    }
3119
0
    return 0;
3120
0
}
3121
3122
size_t ZSTD_compressBegin_advanced_internal(ZSTD_CCtx* cctx,
3123
                                    const void* dict, size_t dictSize,
3124
                                    ZSTD_dictContentType_e dictContentType,
3125
                                    ZSTD_dictTableLoadMethod_e dtlm,
3126
                                    const ZSTD_CDict* cdict,
3127
                                    const ZSTD_CCtx_params* params,
3128
                                    unsigned long long pledgedSrcSize)
3129
0
{
3130
0
    DEBUGLOG(4, "ZSTD_compressBegin_advanced_internal: wlog=%u", params->cParams.windowLog);
3131
    /* compression parameters verification and optimization */
3132
0
    FORWARD_IF_ERROR( ZSTD_checkCParams(params->cParams) , "");
3133
0
    return ZSTD_compressBegin_internal(cctx,
3134
0
                                       dict, dictSize, dictContentType, dtlm,
3135
0
                                       cdict,
3136
0
                                       params, pledgedSrcSize,
3137
0
                                       ZSTDb_not_buffered);
3138
0
}
3139
3140
/*! ZSTD_compressBegin_advanced() :
3141
*   @return : 0, or an error code */
3142
size_t ZSTD_compressBegin_advanced(ZSTD_CCtx* cctx,
3143
                             const void* dict, size_t dictSize,
3144
                                   ZSTD_parameters params, unsigned long long pledgedSrcSize)
3145
0
{
3146
0
    ZSTD_CCtx_params const cctxParams =
3147
0
            ZSTD_assignParamsToCCtxParams(&cctx->requestedParams, &params);
3148
0
    return ZSTD_compressBegin_advanced_internal(cctx,
3149
0
                                            dict, dictSize, ZSTD_dct_auto, ZSTD_dtlm_fast,
3150
0
                                            NULL /*cdict*/,
3151
0
                                            &cctxParams, pledgedSrcSize);
3152
0
}
3153
3154
size_t ZSTD_compressBegin_usingDict(ZSTD_CCtx* cctx, const void* dict, size_t dictSize, int compressionLevel)
3155
0
{
3156
0
    ZSTD_parameters const params = ZSTD_getParams_internal(compressionLevel, ZSTD_CONTENTSIZE_UNKNOWN, dictSize);
3157
0
    ZSTD_CCtx_params const cctxParams =
3158
0
            ZSTD_assignParamsToCCtxParams(&cctx->requestedParams, &params);
3159
0
    DEBUGLOG(4, "ZSTD_compressBegin_usingDict (dictSize=%u)", (unsigned)dictSize);
3160
0
    return ZSTD_compressBegin_internal(cctx, dict, dictSize, ZSTD_dct_auto, ZSTD_dtlm_fast, NULL,
3161
0
                                       &cctxParams, ZSTD_CONTENTSIZE_UNKNOWN, ZSTDb_not_buffered);
3162
0
}
3163
3164
size_t ZSTD_compressBegin(ZSTD_CCtx* cctx, int compressionLevel)
3165
0
{
3166
0
    return ZSTD_compressBegin_usingDict(cctx, NULL, 0, compressionLevel);
3167
0
}
3168
3169
3170
/*! ZSTD_writeEpilogue() :
3171
*   Ends a frame.
3172
*   @return : nb of bytes written into dst (or an error code) */
3173
static size_t ZSTD_writeEpilogue(ZSTD_CCtx* cctx, void* dst, size_t dstCapacity)
3174
0
{
3175
0
    BYTE* const ostart = (BYTE*)dst;
3176
0
    BYTE* op = ostart;
3177
0
    size_t fhSize = 0;
3178
3179
0
    DEBUGLOG(4, "ZSTD_writeEpilogue");
3180
0
    RETURN_ERROR_IF(cctx->stage == ZSTDcs_created, stage_wrong, "init missing");
3181
3182
    /* special case : empty frame */
3183
0
    if (cctx->stage == ZSTDcs_init) {
3184
0
        fhSize = ZSTD_writeFrameHeader(dst, dstCapacity, &cctx->appliedParams, 0, 0);
3185
0
        FORWARD_IF_ERROR(fhSize, "ZSTD_writeFrameHeader failed");
3186
0
        dstCapacity -= fhSize;
3187
0
        op += fhSize;
3188
0
        cctx->stage = ZSTDcs_ongoing;
3189
0
    }
3190
3191
0
    if (cctx->stage != ZSTDcs_ending) {
3192
        /* write one last empty block, make it the "last" block */
3193
0
        U32 const cBlockHeader24 = 1 /* last block */ + (((U32)bt_raw)<<1) + 0;
3194
0
        RETURN_ERROR_IF(dstCapacity<4, dstSize_tooSmall, "no room for epilogue");
3195
0
        MEM_writeLE32(op, cBlockHeader24);
3196
0
        op += ZSTDInternalConstants::ZSTD_blockHeaderSize;
3197
0
        dstCapacity -= ZSTDInternalConstants::ZSTD_blockHeaderSize;
3198
0
    }
3199
3200
0
    if (cctx->appliedParams.fParams.checksumFlag) {
3201
0
        U32 const checksum = (U32) XXH64_digest(&cctx->xxhState);
3202
0
        RETURN_ERROR_IF(dstCapacity<4, dstSize_tooSmall, "no room for checksum");
3203
0
        DEBUGLOG(4, "ZSTD_writeEpilogue: write checksum : %08X", (unsigned)checksum);
3204
0
        MEM_writeLE32(op, checksum);
3205
0
        op += 4;
3206
0
    }
3207
3208
0
    cctx->stage = ZSTDcs_created;  /* return to "created but no init" status */
3209
0
    return op-ostart;
3210
0
}
3211
3212
size_t ZSTD_compressEnd (ZSTD_CCtx* cctx,
3213
                         void* dst, size_t dstCapacity,
3214
                   const void* src, size_t srcSize)
3215
0
{
3216
0
    size_t endResult;
3217
0
    size_t const cSize = ZSTD_compressContinue_internal(cctx,
3218
0
                                dst, dstCapacity, src, srcSize,
3219
0
                                1 /* frame mode */, 1 /* last chunk */);
3220
0
    FORWARD_IF_ERROR(cSize, "ZSTD_compressContinue_internal failed");
3221
0
    endResult = ZSTD_writeEpilogue(cctx, (char*)dst + cSize, dstCapacity-cSize);
3222
0
    FORWARD_IF_ERROR(endResult, "ZSTD_writeEpilogue failed");
3223
0
    assert(!(cctx->appliedParams.fParams.contentSizeFlag && cctx->pledgedSrcSizePlusOne == 0));
3224
0
    if (cctx->pledgedSrcSizePlusOne != 0) {  /* control src size */
3225
0
        ZSTD_STATIC_ASSERT(ZSTD_CONTENTSIZE_UNKNOWN == (unsigned long long)-1);
3226
0
        DEBUGLOG(4, "end of frame : controlling src size");
3227
0
        RETURN_ERROR_IF(
3228
0
            cctx->pledgedSrcSizePlusOne != cctx->consumedSrcSize+1,
3229
0
            srcSize_wrong,
3230
0
             "error : pledgedSrcSize = %u, while realSrcSize = %u",
3231
0
            (unsigned)cctx->pledgedSrcSizePlusOne-1,
3232
0
            (unsigned)cctx->consumedSrcSize);
3233
0
    }
3234
0
    return cSize + endResult;
3235
0
}
3236
3237
3238
static size_t ZSTD_compress_internal (ZSTD_CCtx* cctx,
3239
                                      void* dst, size_t dstCapacity,
3240
                                const void* src, size_t srcSize,
3241
                                const void* dict,size_t dictSize,
3242
                                const ZSTD_parameters* params)
3243
0
{
3244
0
    ZSTD_CCtx_params const cctxParams =
3245
0
            ZSTD_assignParamsToCCtxParams(&cctx->requestedParams, params);
3246
0
    DEBUGLOG(4, "ZSTD_compress_internal");
3247
0
    return ZSTD_compress_advanced_internal(cctx,
3248
0
                                           dst, dstCapacity,
3249
0
                                           src, srcSize,
3250
0
                                           dict, dictSize,
3251
0
                                           &cctxParams);
3252
0
}
3253
3254
size_t ZSTD_compress_advanced (ZSTD_CCtx* cctx,
3255
                               void* dst, size_t dstCapacity,
3256
                         const void* src, size_t srcSize,
3257
                         const void* dict,size_t dictSize,
3258
                               ZSTD_parameters params)
3259
0
{
3260
0
    DEBUGLOG(4, "ZSTD_compress_advanced");
3261
0
    FORWARD_IF_ERROR(ZSTD_checkCParams(params.cParams), "");
3262
0
    return ZSTD_compress_internal(cctx,
3263
0
                                  dst, dstCapacity,
3264
0
                                  src, srcSize,
3265
0
                                  dict, dictSize,
3266
0
                                  &params);
3267
0
}
3268
3269
/* Internal */
3270
size_t ZSTD_compress_advanced_internal(
3271
        ZSTD_CCtx* cctx,
3272
        void* dst, size_t dstCapacity,
3273
        const void* src, size_t srcSize,
3274
        const void* dict,size_t dictSize,
3275
        const ZSTD_CCtx_params* params)
3276
0
{
3277
0
    DEBUGLOG(4, "ZSTD_compress_advanced_internal (srcSize:%u)", (unsigned)srcSize);
3278
0
    FORWARD_IF_ERROR( ZSTD_compressBegin_internal(cctx,
3279
0
                         dict, dictSize, ZSTD_dct_auto, ZSTD_dtlm_fast, NULL,
3280
0
                         params, srcSize, ZSTDb_not_buffered) , "");
3281
0
    return ZSTD_compressEnd(cctx, dst, dstCapacity, src, srcSize);
3282
0
}
3283
3284
size_t ZSTD_compress_usingDict(ZSTD_CCtx* cctx,
3285
                               void* dst, size_t dstCapacity,
3286
                         const void* src, size_t srcSize,
3287
                         const void* dict, size_t dictSize,
3288
                               int compressionLevel)
3289
0
{
3290
0
    ZSTD_parameters const params = ZSTD_getParams_internal(compressionLevel, srcSize, dict ? dictSize : 0);
3291
0
    ZSTD_CCtx_params cctxParams = ZSTD_assignParamsToCCtxParams(&cctx->requestedParams, &params);
3292
0
    DEBUGLOG(4, "ZSTD_compress_usingDict (srcSize=%u)", (unsigned)srcSize);
3293
0
    assert(params.fParams.contentSizeFlag == 1);
3294
0
    return ZSTD_compress_advanced_internal(cctx, dst, dstCapacity, src, srcSize, dict, dictSize, &cctxParams);
3295
0
}
3296
3297
size_t ZSTD_compressCCtx(ZSTD_CCtx* cctx,
3298
                         void* dst, size_t dstCapacity,
3299
                   const void* src, size_t srcSize,
3300
                         int compressionLevel)
3301
0
{
3302
0
    DEBUGLOG(4, "ZSTD_compressCCtx (srcSize=%u)", (unsigned)srcSize);
3303
0
    assert(cctx != NULL);
3304
0
    return ZSTD_compress_usingDict(cctx, dst, dstCapacity, src, srcSize, NULL, 0, compressionLevel);
3305
0
}
3306
3307
size_t ZSTD_compress(void* dst, size_t dstCapacity,
3308
               const void* src, size_t srcSize,
3309
                     int compressionLevel)
3310
0
{
3311
0
    size_t result;
3312
0
    ZSTD_CCtx ctxBody;
3313
0
    ZSTD_initCCtx(&ctxBody, ZSTDInternalConstants::ZSTD_defaultCMem);
3314
0
    result = ZSTD_compressCCtx(&ctxBody, dst, dstCapacity, src, srcSize, compressionLevel);
3315
0
    ZSTD_freeCCtxContent(&ctxBody);   /* can't free ctxBody itself, as it's on stack; free only heap content */
3316
0
    return result;
3317
0
}
3318
3319
3320
/* =====  Dictionary API  ===== */
3321
3322
/*! ZSTD_estimateCDictSize_advanced() :
3323
 *  Estimate amount of memory that will be needed to create a dictionary with following arguments */
3324
size_t ZSTD_estimateCDictSize_advanced(
3325
        size_t dictSize, ZSTD_compressionParameters cParams,
3326
        ZSTD_dictLoadMethod_e dictLoadMethod)
3327
0
{
3328
0
    DEBUGLOG(5, "sizeof(ZSTD_CDict) : %u", (unsigned)sizeof(ZSTD_CDict));
3329
0
    return ZSTD_cwksp_alloc_size(sizeof(ZSTD_CDict))
3330
0
         + ZSTD_cwksp_alloc_size(HUF_WORKSPACE_SIZE)
3331
0
         + ZSTD_sizeof_matchState(&cParams, /* forCCtx */ 0)
3332
0
         + (dictLoadMethod == ZSTD_dlm_byRef ? 0
3333
0
            : ZSTD_cwksp_alloc_size(ZSTD_cwksp_align(dictSize, sizeof(void *))));
3334
0
}
3335
3336
size_t ZSTD_estimateCDictSize(size_t dictSize, int compressionLevel)
3337
0
{
3338
0
    ZSTD_compressionParameters const cParams = ZSTD_getCParams_internal(compressionLevel, ZSTD_CONTENTSIZE_UNKNOWN, dictSize);
3339
0
    return ZSTD_estimateCDictSize_advanced(dictSize, cParams, ZSTD_dlm_byCopy);
3340
0
}
3341
3342
size_t ZSTD_sizeof_CDict(const ZSTD_CDict* cdict)
3343
0
{
3344
0
    if (cdict==NULL) return 0;   /* support sizeof on NULL */
3345
0
    DEBUGLOG(5, "sizeof(*cdict) : %u", (unsigned)sizeof(*cdict));
3346
    /* cdict may be in the workspace */
3347
0
    return (cdict->workspace.workspace == cdict ? 0 : sizeof(*cdict))
3348
0
        + ZSTD_cwksp_sizeof(&cdict->workspace);
3349
0
}
3350
3351
static size_t ZSTD_initCDict_internal(
3352
                    ZSTD_CDict* cdict,
3353
              const void* dictBuffer, size_t dictSize,
3354
                    ZSTD_dictLoadMethod_e dictLoadMethod,
3355
                    ZSTD_dictContentType_e dictContentType,
3356
                    ZSTD_compressionParameters cParams)
3357
0
{
3358
0
    DEBUGLOG(3, "ZSTD_initCDict_internal (dictContentType:%u)", (unsigned)dictContentType);
3359
0
    assert(!ZSTD_checkCParams(cParams));
3360
0
    cdict->matchState.cParams = cParams;
3361
0
    if ((dictLoadMethod == ZSTD_dlm_byRef) || (!dictBuffer) || (!dictSize)) {
3362
0
        cdict->dictContent = dictBuffer;
3363
0
    } else {
3364
0
         void *internalBuffer = ZSTD_cwksp_reserve_object(&cdict->workspace, ZSTD_cwksp_align(dictSize, sizeof(void*)));
3365
0
        RETURN_ERROR_IF(!internalBuffer, memory_allocation, "NULL pointer!");
3366
0
        cdict->dictContent = internalBuffer;
3367
0
        memcpy(internalBuffer, dictBuffer, dictSize);
3368
0
    }
3369
0
    cdict->dictContentSize = dictSize;
3370
3371
0
    cdict->entropyWorkspace = (U32*)ZSTD_cwksp_reserve_object(&cdict->workspace, HUF_WORKSPACE_SIZE);
3372
3373
3374
    /* Reset the state to no dictionary */
3375
0
    ZSTD_reset_compressedBlockState(&cdict->cBlockState);
3376
0
    FORWARD_IF_ERROR(ZSTD_reset_matchState(
3377
0
        &cdict->matchState,
3378
0
        &cdict->workspace,
3379
0
        &cParams,
3380
0
        ZSTDcrp_makeClean,
3381
0
        ZSTDirp_reset,
3382
0
        ZSTD_resetTarget_CDict), "");
3383
    /* (Maybe) load the dictionary
3384
     * Skips loading the dictionary if it is < 8 bytes.
3385
     */
3386
0
    {   ZSTD_CCtx_params params;
3387
0
        memset(&params, 0, sizeof(params));
3388
0
        params.compressionLevel = ZSTD_CLEVEL_DEFAULT;
3389
0
        params.fParams.contentSizeFlag = 1;
3390
0
        params.cParams = cParams;
3391
0
        {   size_t const dictID = ZSTD_compress_insertDictionary(
3392
0
                    &cdict->cBlockState, &cdict->matchState, NULL, &cdict->workspace,
3393
0
                    &params, cdict->dictContent, cdict->dictContentSize,
3394
0
                    dictContentType, ZSTD_dtlm_full, cdict->entropyWorkspace);
3395
0
            FORWARD_IF_ERROR(dictID, "ZSTD_compress_insertDictionary failed");
3396
0
            assert(dictID <= (size_t)(U32)-1);
3397
0
            cdict->dictID = (U32)dictID;
3398
0
        }
3399
0
    }
3400
3401
0
    return 0;
3402
0
}
3403
3404
ZSTD_CDict* ZSTD_createCDict_advanced(const void* dictBuffer, size_t dictSize,
3405
                                      ZSTD_dictLoadMethod_e dictLoadMethod,
3406
                                      ZSTD_dictContentType_e dictContentType,
3407
                                      ZSTD_compressionParameters cParams, ZSTD_customMem customMem)
3408
0
{
3409
0
    DEBUGLOG(3, "ZSTD_createCDict_advanced, mode %u", (unsigned)dictContentType);
3410
0
    if (!customMem.customAlloc ^ !customMem.customFree) return NULL;
3411
3412
0
    {   size_t const workspaceSize =
3413
0
            ZSTD_cwksp_alloc_size(sizeof(ZSTD_CDict)) +
3414
0
            ZSTD_cwksp_alloc_size(HUF_WORKSPACE_SIZE) +
3415
0
            ZSTD_sizeof_matchState(&cParams, /* forCCtx */ 0) +
3416
0
            (dictLoadMethod == ZSTD_dlm_byRef ? 0
3417
0
             : ZSTD_cwksp_alloc_size(ZSTD_cwksp_align(dictSize, sizeof(void*))));
3418
0
        void* const workspace = ZSTD_malloc(workspaceSize, customMem);
3419
0
        ZSTD_cwksp ws;
3420
0
        ZSTD_CDict* cdict;
3421
3422
0
        if (!workspace) {
3423
0
            ZSTD_free(workspace, customMem);
3424
0
            return NULL;
3425
0
        }
3426
3427
0
        ZSTD_cwksp_init(&ws, workspace, workspaceSize);
3428
3429
0
        cdict = (ZSTD_CDict*)ZSTD_cwksp_reserve_object(&ws, sizeof(ZSTD_CDict));
3430
0
        assert(cdict != NULL);
3431
0
        ZSTD_cwksp_move(&cdict->workspace, &ws);
3432
0
        cdict->customMem = customMem;
3433
0
        cdict->compressionLevel = 0; /* signals advanced API usage */
3434
3435
0
        if (ZSTD_isError( ZSTD_initCDict_internal(cdict,
3436
0
                                        dictBuffer, dictSize,
3437
0
                                        dictLoadMethod, dictContentType,
3438
0
                                        cParams) )) {
3439
0
            ZSTD_freeCDict(cdict);
3440
0
            return NULL;
3441
0
        }
3442
3443
0
        return cdict;
3444
0
    }
3445
0
}
3446
3447
ZSTD_CDict* ZSTD_createCDict(const void* dict, size_t dictSize, int compressionLevel)
3448
0
{
3449
0
    ZSTD_compressionParameters cParams = ZSTD_getCParams_internal(compressionLevel, ZSTD_CONTENTSIZE_UNKNOWN, dictSize);
3450
0
    ZSTD_CDict* cdict = ZSTD_createCDict_advanced(dict, dictSize,
3451
0
                                                  ZSTD_dlm_byCopy, ZSTD_dct_auto,
3452
0
                                                  cParams, ZSTDInternalConstants::ZSTD_defaultCMem);
3453
0
    if (cdict)
3454
0
        cdict->compressionLevel = compressionLevel == 0 ? ZSTD_CLEVEL_DEFAULT : compressionLevel;
3455
0
    return cdict;
3456
0
}
3457
3458
ZSTD_CDict* ZSTD_createCDict_byReference(const void* dict, size_t dictSize, int compressionLevel)
3459
0
{
3460
0
    ZSTD_compressionParameters cParams = ZSTD_getCParams_internal(compressionLevel, ZSTD_CONTENTSIZE_UNKNOWN, dictSize);
3461
0
    return ZSTD_createCDict_advanced(dict, dictSize,
3462
0
                                     ZSTD_dlm_byRef, ZSTD_dct_auto,
3463
0
                                     cParams, ZSTDInternalConstants::ZSTD_defaultCMem);
3464
0
}
3465
3466
size_t ZSTD_freeCDict(ZSTD_CDict* cdict)
3467
0
{
3468
0
    if (cdict==NULL) return 0;   /* support free on NULL */
3469
0
    {   ZSTD_customMem const cMem = cdict->customMem;
3470
0
        int cdictInWorkspace = ZSTD_cwksp_owns_buffer(&cdict->workspace, cdict);
3471
0
        ZSTD_cwksp_free(&cdict->workspace, cMem);
3472
0
        if (!cdictInWorkspace) {
3473
0
            ZSTD_free(cdict, cMem);
3474
0
        }
3475
0
        return 0;
3476
0
    }
3477
0
}
3478
3479
/*! ZSTD_initStaticCDict_advanced() :
3480
 *  Generate a digested dictionary in provided memory area.
3481
 *  workspace: The memory area to emplace the dictionary into.
3482
 *             Provided pointer must 8-bytes aligned.
3483
 *             It must outlive dictionary usage.
3484
 *  workspaceSize: Use ZSTD_estimateCDictSize()
3485
 *                 to determine how large workspace must be.
3486
 *  cParams : use ZSTD_getCParams() to transform a compression level
3487
 *            into its relevants cParams.
3488
 * @return : pointer to ZSTD_CDict*, or NULL if error (size too small)
3489
 *  Note : there is no corresponding "free" function.
3490
 *         Since workspace was allocated externally, it must be freed externally.
3491
 */
3492
const ZSTD_CDict* ZSTD_initStaticCDict(
3493
                                 void* workspace, size_t workspaceSize,
3494
                           const void* dict, size_t dictSize,
3495
                                 ZSTD_dictLoadMethod_e dictLoadMethod,
3496
                                 ZSTD_dictContentType_e dictContentType,
3497
                                 ZSTD_compressionParameters cParams)
3498
0
{
3499
0
    size_t const matchStateSize = ZSTD_sizeof_matchState(&cParams, /* forCCtx */ 0);
3500
0
    size_t const neededSize = ZSTD_cwksp_alloc_size(sizeof(ZSTD_CDict))
3501
0
                            + (dictLoadMethod == ZSTD_dlm_byRef ? 0
3502
0
                               : ZSTD_cwksp_alloc_size(ZSTD_cwksp_align(dictSize, sizeof(void*))))
3503
0
                            + ZSTD_cwksp_alloc_size(HUF_WORKSPACE_SIZE)
3504
0
                            + matchStateSize;
3505
0
    ZSTD_CDict* cdict;
3506
3507
0
    if ((size_t)workspace & 7) return NULL;  /* 8-aligned */
3508
3509
0
    {
3510
0
        ZSTD_cwksp ws;
3511
0
        ZSTD_cwksp_init(&ws, workspace, workspaceSize);
3512
0
        cdict = (ZSTD_CDict*)ZSTD_cwksp_reserve_object(&ws, sizeof(ZSTD_CDict));
3513
0
        if (cdict == NULL) return NULL;
3514
0
        ZSTD_cwksp_move(&cdict->workspace, &ws);
3515
0
    }
3516
3517
0
    DEBUGLOG(4, "(workspaceSize < neededSize) : (%u < %u) => %u",
3518
0
        (unsigned)workspaceSize, (unsigned)neededSize, (unsigned)(workspaceSize < neededSize));
3519
0
    if (workspaceSize < neededSize) return NULL;
3520
3521
0
    if (ZSTD_isError( ZSTD_initCDict_internal(cdict,
3522
0
                                              dict, dictSize,
3523
0
                                              dictLoadMethod, dictContentType,
3524
0
                                              cParams) ))
3525
0
        return NULL;
3526
3527
0
    return cdict;
3528
0
}
3529
3530
ZSTD_compressionParameters ZSTD_getCParamsFromCDict(const ZSTD_CDict* cdict)
3531
0
{
3532
0
    assert(cdict != NULL);
3533
0
    return cdict->matchState.cParams;
3534
0
}
3535
3536
/* ZSTD_compressBegin_usingCDict_advanced() :
3537
 * cdict must be != NULL */
3538
size_t ZSTD_compressBegin_usingCDict_advanced(
3539
    ZSTD_CCtx* const cctx, const ZSTD_CDict* const cdict,
3540
    ZSTD_frameParameters const fParams, unsigned long long const pledgedSrcSize)
3541
0
{
3542
0
    DEBUGLOG(4, "ZSTD_compressBegin_usingCDict_advanced");
3543
0
    RETURN_ERROR_IF(cdict==NULL, dictionary_wrong, "NULL pointer!");
3544
0
    {   ZSTD_CCtx_params params = cctx->requestedParams;
3545
0
        params.cParams = ( pledgedSrcSize < ZSTD_USE_CDICT_PARAMS_SRCSIZE_CUTOFF
3546
0
                        || pledgedSrcSize < cdict->dictContentSize * ZSTD_USE_CDICT_PARAMS_DICTSIZE_MULTIPLIER
3547
0
                        || pledgedSrcSize == ZSTD_CONTENTSIZE_UNKNOWN
3548
0
                        || cdict->compressionLevel == 0 )
3549
0
                      && (params.attachDictPref != ZSTD_dictForceLoad) ?
3550
0
                ZSTD_getCParamsFromCDict(cdict)
3551
0
              : ZSTD_getCParams(cdict->compressionLevel,
3552
0
                                pledgedSrcSize,
3553
0
                                cdict->dictContentSize);
3554
        /* Increase window log to fit the entire dictionary and source if the
3555
         * source size is known. Limit the increase to 19, which is the
3556
         * window log for compression level 1 with the largest source size.
3557
         */
3558
0
        if (pledgedSrcSize != ZSTD_CONTENTSIZE_UNKNOWN) {
3559
0
            U32 const limitedSrcSize = (U32)MIN(pledgedSrcSize, 1U << 19);
3560
0
            U32 const limitedSrcLog = limitedSrcSize > 1 ? ZSTD_highbit32(limitedSrcSize - 1) + 1 : 1;
3561
0
            params.cParams.windowLog = MAX(params.cParams.windowLog, limitedSrcLog);
3562
0
        }
3563
0
        params.fParams = fParams;
3564
0
        return ZSTD_compressBegin_internal(cctx,
3565
0
                                           NULL, 0, ZSTD_dct_auto, ZSTD_dtlm_fast,
3566
0
                                           cdict,
3567
0
                                           &params, pledgedSrcSize,
3568
0
                                           ZSTDb_not_buffered);
3569
0
    }
3570
0
}
3571
3572
/* ZSTD_compressBegin_usingCDict() :
3573
 * pledgedSrcSize=0 means "unknown"
3574
 * if pledgedSrcSize>0, it will enable contentSizeFlag */
3575
size_t ZSTD_compressBegin_usingCDict(ZSTD_CCtx* cctx, const ZSTD_CDict* cdict)
3576
0
{
3577
0
    ZSTD_frameParameters const fParams = { 0 /*content*/, 0 /*checksum*/, 0 /*noDictID*/ };
3578
0
    DEBUGLOG(4, "ZSTD_compressBegin_usingCDict : dictIDFlag == %u", !fParams.noDictIDFlag);
3579
0
    return ZSTD_compressBegin_usingCDict_advanced(cctx, cdict, fParams, ZSTD_CONTENTSIZE_UNKNOWN);
3580
0
}
3581
3582
size_t ZSTD_compress_usingCDict_advanced(ZSTD_CCtx* cctx,
3583
                                void* dst, size_t dstCapacity,
3584
                                const void* src, size_t srcSize,
3585
                                const ZSTD_CDict* cdict, ZSTD_frameParameters fParams)
3586
0
{
3587
0
    FORWARD_IF_ERROR(ZSTD_compressBegin_usingCDict_advanced(cctx, cdict, fParams, srcSize), "");   /* will check if cdict != NULL */
3588
0
    return ZSTD_compressEnd(cctx, dst, dstCapacity, src, srcSize);
3589
0
}
3590
3591
/*! ZSTD_compress_usingCDict() :
3592
 *  Compression using a digested Dictionary.
3593
 *  Faster startup than ZSTD_compress_usingDict(), recommended when same dictionary is used multiple times.
3594
 *  Note that compression parameters are decided at CDict creation time
3595
 *  while frame parameters are hardcoded */
3596
size_t ZSTD_compress_usingCDict(ZSTD_CCtx* cctx,
3597
                                void* dst, size_t dstCapacity,
3598
                                const void* src, size_t srcSize,
3599
                                const ZSTD_CDict* cdict)
3600
0
{
3601
0
    ZSTD_frameParameters const fParams = { 1 /*content*/, 0 /*checksum*/, 0 /*noDictID*/ };
3602
0
    return ZSTD_compress_usingCDict_advanced(cctx, dst, dstCapacity, src, srcSize, cdict, fParams);
3603
0
}
3604
3605
3606
3607
/* ******************************************************************
3608
*  Streaming
3609
********************************************************************/
3610
3611
ZSTD_CStream* ZSTD_createCStream(void)
3612
0
{
3613
0
    DEBUGLOG(3, "ZSTD_createCStream");
3614
0
    return ZSTD_createCStream_advanced(ZSTDInternalConstants::ZSTD_defaultCMem);
3615
0
}
3616
3617
ZSTD_CStream* ZSTD_initStaticCStream(void *workspace, size_t workspaceSize)
3618
0
{
3619
0
    return ZSTD_initStaticCCtx(workspace, workspaceSize);
3620
0
}
3621
3622
ZSTD_CStream* ZSTD_createCStream_advanced(ZSTD_customMem customMem)
3623
0
{   /* CStream and CCtx are now same object */
3624
0
    return ZSTD_createCCtx_advanced(customMem);
3625
0
}
3626
3627
size_t ZSTD_freeCStream(ZSTD_CStream* zcs)
3628
0
{
3629
0
    return ZSTD_freeCCtx(zcs);   /* same object */
3630
0
}
3631
3632
3633
3634
/*======   Initialization   ======*/
3635
3636
0
size_t ZSTD_CStreamInSize(void)  { return ZSTD_BLOCKSIZE_MAX; }
3637
3638
size_t ZSTD_CStreamOutSize(void)
3639
0
{
3640
0
    return ZSTD_compressBound(ZSTD_BLOCKSIZE_MAX) + ZSTDInternalConstants::ZSTD_blockHeaderSize + 4 /* 32-bits hash */ ;
3641
0
}
3642
3643
static size_t ZSTD_resetCStream_internal(ZSTD_CStream* cctx,
3644
                    const void* const dict, size_t const dictSize, ZSTD_dictContentType_e const dictContentType,
3645
                    const ZSTD_CDict* const cdict,
3646
                    ZSTD_CCtx_params params, unsigned long long const pledgedSrcSize)
3647
0
{
3648
0
    DEBUGLOG(4, "ZSTD_resetCStream_internal");
3649
    /* Finalize the compression parameters */
3650
0
    params.cParams = ZSTD_getCParamsFromCCtxParams(&params, pledgedSrcSize, dictSize);
3651
    /* params are supposed to be fully validated at this point */
3652
0
    assert(!ZSTD_isError(ZSTD_checkCParams(params.cParams)));
3653
0
    assert(!((dict) && (cdict)));  /* either dict or cdict, not both */
3654
3655
0
    FORWARD_IF_ERROR( ZSTD_compressBegin_internal(cctx,
3656
0
                                         dict, dictSize, dictContentType, ZSTD_dtlm_fast,
3657
0
                                         cdict,
3658
0
                                         &params, pledgedSrcSize,
3659
0
                                         ZSTDb_buffered) , "");
3660
3661
0
    cctx->inToCompress = 0;
3662
0
    cctx->inBuffPos = 0;
3663
0
    cctx->inBuffTarget = cctx->blockSize
3664
0
                      + (cctx->blockSize == pledgedSrcSize);   /* for small input: avoid automatic flush on reaching end of block, since it would require to add a 3-bytes null block to end frame */
3665
0
    cctx->outBuffContentSize = cctx->outBuffFlushedSize = 0;
3666
0
    cctx->streamStage = zcss_load;
3667
0
    cctx->frameEnded = 0;
3668
0
    return 0;   /* ready to go */
3669
0
}
3670
3671
/* ZSTD_resetCStream():
3672
 * pledgedSrcSize == 0 means "unknown" */
3673
size_t ZSTD_resetCStream(ZSTD_CStream* zcs, unsigned long long pss)
3674
0
{
3675
    /* temporary : 0 interpreted as "unknown" during transition period.
3676
     * Users willing to specify "unknown" **must** use ZSTD_CONTENTSIZE_UNKNOWN.
3677
     * 0 will be interpreted as "empty" in the future.
3678
     */
3679
0
    U64 const pledgedSrcSize = (pss==0) ? ZSTD_CONTENTSIZE_UNKNOWN : pss;
3680
0
    DEBUGLOG(4, "ZSTD_resetCStream: pledgedSrcSize = %u", (unsigned)pledgedSrcSize);
3681
0
    FORWARD_IF_ERROR( ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only) , "");
3682
0
    FORWARD_IF_ERROR( ZSTD_CCtx_setPledgedSrcSize(zcs, pledgedSrcSize) , "");
3683
0
    return 0;
3684
0
}
3685
3686
/*! ZSTD_initCStream_internal() :
3687
 *  Note : for lib/compress only. Used by zstdmt_compress.c.
3688
 *  Assumption 1 : params are valid
3689
 *  Assumption 2 : either dict, or cdict, is defined, not both */
3690
size_t ZSTD_initCStream_internal(ZSTD_CStream* zcs,
3691
                    const void* dict, size_t dictSize, const ZSTD_CDict* cdict,
3692
                    const ZSTD_CCtx_params* params,
3693
                    unsigned long long pledgedSrcSize)
3694
0
{
3695
0
    DEBUGLOG(4, "ZSTD_initCStream_internal");
3696
0
    FORWARD_IF_ERROR( ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only) , "");
3697
0
    FORWARD_IF_ERROR( ZSTD_CCtx_setPledgedSrcSize(zcs, pledgedSrcSize) , "");
3698
0
    assert(!ZSTD_isError(ZSTD_checkCParams(params->cParams)));
3699
0
    zcs->requestedParams = *params;
3700
0
    assert(!((dict) && (cdict)));  /* either dict or cdict, not both */
3701
0
    if (dict) {
3702
0
        FORWARD_IF_ERROR( ZSTD_CCtx_loadDictionary(zcs, dict, dictSize) , "");
3703
0
    } else {
3704
        /* Dictionary is cleared if !cdict */
3705
0
        FORWARD_IF_ERROR( ZSTD_CCtx_refCDict(zcs, cdict) , "");
3706
0
    }
3707
0
    return 0;
3708
0
}
3709
3710
/* ZSTD_initCStream_usingCDict_advanced() :
3711
 * same as ZSTD_initCStream_usingCDict(), with control over frame parameters */
3712
size_t ZSTD_initCStream_usingCDict_advanced(ZSTD_CStream* zcs,
3713
                                            const ZSTD_CDict* cdict,
3714
                                            ZSTD_frameParameters fParams,
3715
                                            unsigned long long pledgedSrcSize)
3716
0
{
3717
0
    DEBUGLOG(4, "ZSTD_initCStream_usingCDict_advanced");
3718
0
    FORWARD_IF_ERROR( ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only) , "");
3719
0
    FORWARD_IF_ERROR( ZSTD_CCtx_setPledgedSrcSize(zcs, pledgedSrcSize) , "");
3720
0
    zcs->requestedParams.fParams = fParams;
3721
0
    FORWARD_IF_ERROR( ZSTD_CCtx_refCDict(zcs, cdict) , "");
3722
0
    return 0;
3723
0
}
3724
3725
/* note : cdict must outlive compression session */
3726
size_t ZSTD_initCStream_usingCDict(ZSTD_CStream* zcs, const ZSTD_CDict* cdict)
3727
0
{
3728
0
    DEBUGLOG(4, "ZSTD_initCStream_usingCDict");
3729
0
    FORWARD_IF_ERROR( ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only) , "");
3730
0
    FORWARD_IF_ERROR( ZSTD_CCtx_refCDict(zcs, cdict) , "");
3731
0
    return 0;
3732
0
}
3733
3734
3735
/* ZSTD_initCStream_advanced() :
3736
 * pledgedSrcSize must be exact.
3737
 * if srcSize is not known at init time, use value ZSTD_CONTENTSIZE_UNKNOWN.
3738
 * dict is loaded with default parameters ZSTD_dct_auto and ZSTD_dlm_byCopy. */
3739
size_t ZSTD_initCStream_advanced(ZSTD_CStream* zcs,
3740
                                 const void* dict, size_t dictSize,
3741
                                 ZSTD_parameters params, unsigned long long pss)
3742
0
{
3743
    /* for compatibility with older programs relying on this behavior.
3744
     * Users should now specify ZSTD_CONTENTSIZE_UNKNOWN.
3745
     * This line will be removed in the future.
3746
     */
3747
0
    U64 const pledgedSrcSize = (pss==0 && params.fParams.contentSizeFlag==0) ? ZSTD_CONTENTSIZE_UNKNOWN : pss;
3748
0
    DEBUGLOG(4, "ZSTD_initCStream_advanced");
3749
0
    FORWARD_IF_ERROR( ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only) , "");
3750
0
    FORWARD_IF_ERROR( ZSTD_CCtx_setPledgedSrcSize(zcs, pledgedSrcSize) , "");
3751
0
    FORWARD_IF_ERROR( ZSTD_checkCParams(params.cParams) , "");
3752
0
    zcs->requestedParams = ZSTD_assignParamsToCCtxParams(&zcs->requestedParams, &params);
3753
0
    FORWARD_IF_ERROR( ZSTD_CCtx_loadDictionary(zcs, dict, dictSize) , "");
3754
0
    return 0;
3755
0
}
3756
3757
size_t ZSTD_initCStream_usingDict(ZSTD_CStream* zcs, const void* dict, size_t dictSize, int compressionLevel)
3758
0
{
3759
0
    DEBUGLOG(4, "ZSTD_initCStream_usingDict");
3760
0
    FORWARD_IF_ERROR( ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only) , "");
3761
0
    FORWARD_IF_ERROR( ZSTD_CCtx_setParameter(zcs, ZSTD_c_compressionLevel, compressionLevel) , "");
3762
0
    FORWARD_IF_ERROR( ZSTD_CCtx_loadDictionary(zcs, dict, dictSize) , "");
3763
0
    return 0;
3764
0
}
3765
3766
size_t ZSTD_initCStream_srcSize(ZSTD_CStream* zcs, int compressionLevel, unsigned long long pss)
3767
0
{
3768
    /* temporary : 0 interpreted as "unknown" during transition period.
3769
     * Users willing to specify "unknown" **must** use ZSTD_CONTENTSIZE_UNKNOWN.
3770
     * 0 will be interpreted as "empty" in the future.
3771
     */
3772
0
    U64 const pledgedSrcSize = (pss==0) ? ZSTD_CONTENTSIZE_UNKNOWN : pss;
3773
0
    DEBUGLOG(4, "ZSTD_initCStream_srcSize");
3774
0
    FORWARD_IF_ERROR( ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only) , "");
3775
0
    FORWARD_IF_ERROR( ZSTD_CCtx_refCDict(zcs, NULL) , "");
3776
0
    FORWARD_IF_ERROR( ZSTD_CCtx_setParameter(zcs, ZSTD_c_compressionLevel, compressionLevel) , "");
3777
0
    FORWARD_IF_ERROR( ZSTD_CCtx_setPledgedSrcSize(zcs, pledgedSrcSize) , "");
3778
0
    return 0;
3779
0
}
3780
3781
size_t ZSTD_initCStream(ZSTD_CStream* zcs, int compressionLevel)
3782
0
{
3783
0
    DEBUGLOG(4, "ZSTD_initCStream");
3784
0
    FORWARD_IF_ERROR( ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only) , "");
3785
0
    FORWARD_IF_ERROR( ZSTD_CCtx_refCDict(zcs, NULL) , "");
3786
0
    FORWARD_IF_ERROR( ZSTD_CCtx_setParameter(zcs, ZSTD_c_compressionLevel, compressionLevel) , "");
3787
0
    return 0;
3788
0
}
3789
3790
/*======   Compression   ======*/
3791
3792
static size_t ZSTD_nextInputSizeHint(const ZSTD_CCtx* cctx)
3793
0
{
3794
0
    size_t hintInSize = cctx->inBuffTarget - cctx->inBuffPos;
3795
0
    if (hintInSize==0) hintInSize = cctx->blockSize;
3796
0
    return hintInSize;
3797
0
}
3798
3799
/** ZSTD_compressStream_generic():
3800
 *  internal function for all *compressStream*() variants
3801
 *  non-static, because can be called from zstdmt_compress.c
3802
 * @return : hint size for next input */
3803
static size_t ZSTD_compressStream_generic(ZSTD_CStream* zcs,
3804
                                          ZSTD_outBuffer* output,
3805
                                          ZSTD_inBuffer* input,
3806
                                          ZSTD_EndDirective const flushMode)
3807
0
{
3808
0
    const char* const istart = (const char*)input->src;
3809
0
    const char* const iend = input->size != 0 ? istart + input->size : istart;
3810
0
    const char* ip = input->pos != 0 ? istart + input->pos : istart;
3811
0
    char* const ostart = (char*)output->dst;
3812
0
    char* const oend = output->size != 0 ? ostart + output->size : ostart;
3813
0
    char* op = output->pos != 0 ? ostart + output->pos : ostart;
3814
0
    U32 someMoreWork = 1;
3815
3816
    /* check expectations */
3817
0
    DEBUGLOG(5, "ZSTD_compressStream_generic, flush=%u", (unsigned)flushMode);
3818
0
    assert(zcs->inBuff != NULL);
3819
0
    assert(zcs->inBuffSize > 0);
3820
0
    assert(zcs->outBuff !=  NULL);
3821
0
    assert(zcs->outBuffSize > 0);
3822
0
    assert(output->pos <= output->size);
3823
0
    assert(input->pos <= input->size);
3824
3825
0
    while (someMoreWork) {
3826
0
        switch(zcs->streamStage)
3827
0
        {
3828
0
        case zcss_init:
3829
0
            RETURN_ERROR(init_missing, "call ZSTD_initCStream() first!");
3830
3831
0
        case zcss_load:
3832
0
            if ( (flushMode == ZSTD_e_end)
3833
0
              && ((size_t)(oend-op) >= ZSTD_compressBound(iend-ip))  /* enough dstCapacity */
3834
0
              && (zcs->inBuffPos == 0) ) {
3835
                /* shortcut to compression pass directly into output buffer */
3836
0
                size_t const cSize = ZSTD_compressEnd(zcs,
3837
0
                                                op, oend-op, ip, iend-ip);
3838
0
                DEBUGLOG(4, "ZSTD_compressEnd : cSize=%u", (unsigned)cSize);
3839
0
                FORWARD_IF_ERROR(cSize, "ZSTD_compressEnd failed");
3840
0
                ip = iend;
3841
0
                op += cSize;
3842
0
                zcs->frameEnded = 1;
3843
0
                ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only);
3844
0
                someMoreWork = 0; break;
3845
0
            }
3846
            /* complete loading into inBuffer */
3847
0
            {   size_t const toLoad = zcs->inBuffTarget - zcs->inBuffPos;
3848
0
                size_t const loaded = ZSTD_limitCopy(
3849
0
                                        zcs->inBuff + zcs->inBuffPos, toLoad,
3850
0
                                        ip, iend-ip);
3851
0
                zcs->inBuffPos += loaded;
3852
0
                if (loaded != 0)
3853
0
                    ip += loaded;
3854
0
                if ( (flushMode == ZSTD_e_continue)
3855
0
                  && (zcs->inBuffPos < zcs->inBuffTarget) ) {
3856
                    /* not enough input to fill full block : stop here */
3857
0
                    someMoreWork = 0; break;
3858
0
                }
3859
0
                if ( (flushMode == ZSTD_e_flush)
3860
0
                  && (zcs->inBuffPos == zcs->inToCompress) ) {
3861
                    /* empty */
3862
0
                    someMoreWork = 0; break;
3863
0
                }
3864
0
            }
3865
            /* compress current block (note : this stage cannot be stopped in the middle) */
3866
0
            DEBUGLOG(5, "stream compression stage (flushMode==%u)", flushMode);
3867
0
            {   void* cDst;
3868
0
                size_t cSize;
3869
0
                size_t const iSize = zcs->inBuffPos - zcs->inToCompress;
3870
0
                size_t oSize = oend-op;
3871
0
                unsigned const lastBlock = (flushMode == ZSTD_e_end) && (ip==iend);
3872
0
                if (oSize >= ZSTD_compressBound(iSize))
3873
0
                    cDst = op;   /* compress into output buffer, to skip flush stage */
3874
0
                else
3875
0
                    cDst = zcs->outBuff, oSize = zcs->outBuffSize;
3876
0
                cSize = lastBlock ?
3877
0
                        ZSTD_compressEnd(zcs, cDst, oSize,
3878
0
                                    zcs->inBuff + zcs->inToCompress, iSize) :
3879
0
                        ZSTD_compressContinue(zcs, cDst, oSize,
3880
0
                                    zcs->inBuff + zcs->inToCompress, iSize);
3881
0
                FORWARD_IF_ERROR(cSize, "%s", lastBlock ? "ZSTD_compressEnd failed" : "ZSTD_compressContinue failed");
3882
0
                zcs->frameEnded = lastBlock;
3883
                /* prepare next block */
3884
0
                zcs->inBuffTarget = zcs->inBuffPos + zcs->blockSize;
3885
0
                if (zcs->inBuffTarget > zcs->inBuffSize)
3886
0
                    zcs->inBuffPos = 0, zcs->inBuffTarget = zcs->blockSize;
3887
0
                DEBUGLOG(5, "inBuffTarget:%u / inBuffSize:%u",
3888
0
                         (unsigned)zcs->inBuffTarget, (unsigned)zcs->inBuffSize);
3889
0
                if (!lastBlock)
3890
0
                    assert(zcs->inBuffTarget <= zcs->inBuffSize);
3891
0
                zcs->inToCompress = zcs->inBuffPos;
3892
0
                if (cDst == op) {  /* no need to flush */
3893
0
                    op += cSize;
3894
0
                    if (zcs->frameEnded) {
3895
0
                        DEBUGLOG(5, "Frame completed directly in outBuffer");
3896
0
                        someMoreWork = 0;
3897
0
                        ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only);
3898
0
                    }
3899
0
                    break;
3900
0
                }
3901
0
                zcs->outBuffContentSize = cSize;
3902
0
                zcs->outBuffFlushedSize = 0;
3903
0
                zcs->streamStage = zcss_flush; /* pass-through to flush stage */
3904
0
            }
3905
      /* fall-through */
3906
0
        case zcss_flush:
3907
0
            DEBUGLOG(5, "flush stage");
3908
0
            {   size_t const toFlush = zcs->outBuffContentSize - zcs->outBuffFlushedSize;
3909
0
                size_t const flushed = ZSTD_limitCopy(op, (size_t)(oend-op),
3910
0
                            zcs->outBuff + zcs->outBuffFlushedSize, toFlush);
3911
0
                DEBUGLOG(5, "toFlush: %u into %u ==> flushed: %u",
3912
0
                            (unsigned)toFlush, (unsigned)(oend-op), (unsigned)flushed);
3913
0
                if (flushed)
3914
0
                    op += flushed;
3915
0
                zcs->outBuffFlushedSize += flushed;
3916
0
                if (toFlush!=flushed) {
3917
                    /* flush not fully completed, presumably because dst is too small */
3918
0
                    assert(op==oend);
3919
0
                    someMoreWork = 0;
3920
0
                    break;
3921
0
                }
3922
0
                zcs->outBuffContentSize = zcs->outBuffFlushedSize = 0;
3923
0
                if (zcs->frameEnded) {
3924
0
                    DEBUGLOG(5, "Frame completed on flush");
3925
0
                    someMoreWork = 0;
3926
0
                    ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only);
3927
0
                    break;
3928
0
                }
3929
0
                zcs->streamStage = zcss_load;
3930
0
                break;
3931
0
            }
3932
3933
0
        default: /* impossible */
3934
0
            assert(0);
3935
0
        }
3936
0
    }
3937
3938
0
    input->pos = ip - istart;
3939
0
    output->pos = op - ostart;
3940
0
    if (zcs->frameEnded) return 0;
3941
0
    return ZSTD_nextInputSizeHint(zcs);
3942
0
}
3943
3944
static size_t ZSTD_nextInputSizeHint_MTorST(const ZSTD_CCtx* cctx)
3945
0
{
3946
#ifdef ZSTD_MULTITHREAD
3947
    if (cctx->appliedParams.nbWorkers >= 1) {
3948
        assert(cctx->mtctx != NULL);
3949
        return ZSTDMT_nextInputSizeHint(cctx->mtctx);
3950
    }
3951
#endif
3952
0
    return ZSTD_nextInputSizeHint(cctx);
3953
3954
0
}
3955
3956
size_t ZSTD_compressStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output, ZSTD_inBuffer* input)
3957
0
{
3958
0
    FORWARD_IF_ERROR( ZSTD_compressStream2(zcs, output, input, ZSTD_e_continue) , "");
3959
0
    return ZSTD_nextInputSizeHint_MTorST(zcs);
3960
0
}
3961
3962
3963
size_t ZSTD_compressStream2( ZSTD_CCtx* cctx,
3964
                             ZSTD_outBuffer* output,
3965
                             ZSTD_inBuffer* input,
3966
                             ZSTD_EndDirective endOp)
3967
0
{
3968
0
    DEBUGLOG(5, "ZSTD_compressStream2, endOp=%u ", (unsigned)endOp);
3969
    /* check conditions */
3970
0
    RETURN_ERROR_IF(output->pos > output->size, GENERIC, "invalid buffer");
3971
0
    RETURN_ERROR_IF(input->pos  > input->size, GENERIC, "invalid buffer");
3972
0
    assert(cctx!=NULL);
3973
3974
    /* transparent initialization stage */
3975
0
    if (cctx->streamStage == zcss_init) {
3976
0
        ZSTD_CCtx_params params = cctx->requestedParams;
3977
0
        ZSTD_prefixDict const prefixDict = cctx->prefixDict;
3978
0
        FORWARD_IF_ERROR( ZSTD_initLocalDict(cctx) , ""); /* Init the local dict if present. */
3979
0
        memset(&cctx->prefixDict, 0, sizeof(cctx->prefixDict));   /* single usage */
3980
0
        assert(prefixDict.dict==NULL || cctx->cdict==NULL);    /* only one can be set */
3981
0
        DEBUGLOG(4, "ZSTD_compressStream2 : transparent init stage");
3982
0
        if (endOp == ZSTD_e_end) cctx->pledgedSrcSizePlusOne = input->size + 1;  /* auto-fix pledgedSrcSize */
3983
0
        params.cParams = ZSTD_getCParamsFromCCtxParams(
3984
0
                &cctx->requestedParams, cctx->pledgedSrcSizePlusOne-1, 0 /*dictSize*/);
3985
3986
3987
#ifdef ZSTD_MULTITHREAD
3988
        if ((cctx->pledgedSrcSizePlusOne-1) <= ZSTDMT_JOBSIZE_MIN) {
3989
            params.nbWorkers = 0; /* do not invoke multi-threading when src size is too small */
3990
        }
3991
        if (params.nbWorkers > 0) {
3992
            /* mt context creation */
3993
            if (cctx->mtctx == NULL) {
3994
                DEBUGLOG(4, "ZSTD_compressStream2: creating new mtctx for nbWorkers=%u",
3995
                            params.nbWorkers);
3996
                cctx->mtctx = ZSTDMT_createCCtx_advanced((U32)params.nbWorkers, cctx->customMem);
3997
                RETURN_ERROR_IF(cctx->mtctx == NULL, memory_allocation, "NULL pointer!");
3998
            }
3999
            /* mt compression */
4000
            DEBUGLOG(4, "call ZSTDMT_initCStream_internal as nbWorkers=%u", params.nbWorkers);
4001
            FORWARD_IF_ERROR( ZSTDMT_initCStream_internal(
4002
                        cctx->mtctx,
4003
                        prefixDict.dict, prefixDict.dictSize, prefixDict.dictContentType,
4004
                        cctx->cdict, params, cctx->pledgedSrcSizePlusOne-1) , "");
4005
            cctx->streamStage = zcss_load;
4006
            cctx->appliedParams.nbWorkers = params.nbWorkers;
4007
        } else
4008
#endif
4009
0
        {   FORWARD_IF_ERROR( ZSTD_resetCStream_internal(cctx,
4010
0
                            prefixDict.dict, prefixDict.dictSize, prefixDict.dictContentType,
4011
0
                            cctx->cdict,
4012
0
                            params, cctx->pledgedSrcSizePlusOne-1) , "");
4013
0
            assert(cctx->streamStage == zcss_load);
4014
0
            assert(cctx->appliedParams.nbWorkers == 0);
4015
0
    }   }
4016
    /* end of transparent initialization stage */
4017
4018
    /* compression stage */
4019
#ifdef ZSTD_MULTITHREAD
4020
    if (cctx->appliedParams.nbWorkers > 0) {
4021
        int const forceMaxProgress = (endOp == ZSTD_e_flush || endOp == ZSTD_e_end);
4022
        size_t flushMin;
4023
        assert(forceMaxProgress || endOp == ZSTD_e_continue /* Protection for a new flush type */);
4024
        if (cctx->cParamsChanged) {
4025
            ZSTDMT_updateCParams_whileCompressing(cctx->mtctx, &cctx->requestedParams);
4026
            cctx->cParamsChanged = 0;
4027
        }
4028
        do {
4029
            flushMin = ZSTDMT_compressStream_generic(cctx->mtctx, output, input, endOp);
4030
            if ( ZSTD_isError(flushMin)
4031
              || (endOp == ZSTD_e_end && flushMin == 0) ) { /* compression completed */
4032
                ZSTD_CCtx_reset(cctx, ZSTD_reset_session_only);
4033
            }
4034
            FORWARD_IF_ERROR(flushMin, "ZSTDMT_compressStream_generic failed");
4035
        } while (forceMaxProgress && flushMin != 0 && output->pos < output->size);
4036
        DEBUGLOG(5, "completed ZSTD_compressStream2 delegating to ZSTDMT_compressStream_generic");
4037
        /* Either we don't require maximum forward progress, we've finished the
4038
         * flush, or we are out of output space.
4039
         */
4040
        assert(!forceMaxProgress || flushMin == 0 || output->pos == output->size);
4041
        return flushMin;
4042
    }
4043
#endif
4044
0
    FORWARD_IF_ERROR( ZSTD_compressStream_generic(cctx, output, input, endOp) , "");
4045
0
    DEBUGLOG(5, "completed ZSTD_compressStream2");
4046
0
    return cctx->outBuffContentSize - cctx->outBuffFlushedSize; /* remaining to flush */
4047
0
}
4048
4049
size_t ZSTD_compressStream2_simpleArgs (
4050
                            ZSTD_CCtx* cctx,
4051
                            void* dst, size_t dstCapacity, size_t* dstPos,
4052
                      const void* src, size_t srcSize, size_t* srcPos,
4053
                            ZSTD_EndDirective endOp)
4054
0
{
4055
0
    ZSTD_outBuffer output = { dst, dstCapacity, *dstPos };
4056
0
    ZSTD_inBuffer  input  = { src, srcSize, *srcPos };
4057
    /* ZSTD_compressStream2() will check validity of dstPos and srcPos */
4058
0
    size_t const cErr = ZSTD_compressStream2(cctx, &output, &input, endOp);
4059
0
    *dstPos = output.pos;
4060
0
    *srcPos = input.pos;
4061
0
    return cErr;
4062
0
}
4063
4064
size_t ZSTD_compress2(ZSTD_CCtx* cctx,
4065
                      void* dst, size_t dstCapacity,
4066
                      const void* src, size_t srcSize)
4067
0
{
4068
0
    DEBUGLOG(4, "ZSTD_compress2 (srcSize=%u)", (unsigned)srcSize);
4069
0
    ZSTD_CCtx_reset(cctx, ZSTD_reset_session_only);
4070
0
    {   size_t oPos = 0;
4071
0
        size_t iPos = 0;
4072
0
        size_t const result = ZSTD_compressStream2_simpleArgs(cctx,
4073
0
                                        dst, dstCapacity, &oPos,
4074
0
                                        src, srcSize, &iPos,
4075
0
                                        ZSTD_e_end);
4076
0
        FORWARD_IF_ERROR(result, "ZSTD_compressStream2_simpleArgs failed");
4077
0
        if (result != 0) {  /* compression not completed, due to lack of output space */
4078
0
            assert(oPos == dstCapacity);
4079
0
            RETURN_ERROR(dstSize_tooSmall, "");
4080
0
        }
4081
0
        assert(iPos == srcSize);   /* all input is expected consumed */
4082
0
        return oPos;
4083
0
    }
4084
0
}
4085
4086
/*======   Finalize   ======*/
4087
4088
/*! ZSTD_flushStream() :
4089
 * @return : amount of data remaining to flush */
4090
size_t ZSTD_flushStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output)
4091
0
{
4092
0
    ZSTD_inBuffer input = { NULL, 0, 0 };
4093
0
    return ZSTD_compressStream2(zcs, output, &input, ZSTD_e_flush);
4094
0
}
4095
4096
4097
size_t ZSTD_endStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output)
4098
0
{
4099
0
    ZSTD_inBuffer input = { NULL, 0, 0 };
4100
0
    size_t const remainingToFlush = ZSTD_compressStream2(zcs, output, &input, ZSTD_e_end);
4101
0
    FORWARD_IF_ERROR( remainingToFlush , "ZSTD_compressStream2 failed");
4102
0
    if (zcs->appliedParams.nbWorkers > 0) return remainingToFlush;   /* minimal estimation */
4103
    /* single thread mode : attempt to calculate remaining to flush more precisely */
4104
0
    {   size_t const lastBlockSize = zcs->frameEnded ? 0 : ZSTD_BLOCKHEADERSIZE;
4105
0
        size_t const checksumSize = (size_t)(zcs->frameEnded ? 0 : zcs->appliedParams.fParams.checksumFlag * 4);
4106
0
        size_t const toFlush = remainingToFlush + lastBlockSize + checksumSize;
4107
0
        DEBUGLOG(4, "ZSTD_endStream : remaining to flush : %u", (unsigned)toFlush);
4108
0
        return toFlush;
4109
0
    }
4110
0
}
4111
4112
4113
/*-=====  Pre-defined compression levels  =====-*/
4114
4115
0
#define ZSTD_MAX_CLEVEL     22
4116
0
int ZSTD_maxCLevel(void) { return ZSTD_MAX_CLEVEL; }
4117
0
int ZSTD_minCLevel(void) { return (int)-ZSTD_TARGETLENGTH_MAX; }
4118
4119
static const ZSTD_compressionParameters ZSTD_defaultCParameters[4][ZSTD_MAX_CLEVEL+1] = {
4120
{   /* "default" - for any srcSize > 256 KB */
4121
    /* W,  C,  H,  S,  L, TL, strat */
4122
    { 19, 12, 13,  1,  6,  1, ZSTD_fast    },  /* base for negative levels */
4123
    { 19, 13, 14,  1,  7,  0, ZSTD_fast    },  /* level  1 */
4124
    { 20, 15, 16,  1,  6,  0, ZSTD_fast    },  /* level  2 */
4125
    { 21, 16, 17,  1,  5,  0, ZSTD_dfast   },  /* level  3 */
4126
    { 21, 18, 18,  1,  5,  0, ZSTD_dfast   },  /* level  4 */
4127
    { 21, 18, 19,  2,  5,  2, ZSTD_greedy  },  /* level  5 */
4128
    { 21, 19, 19,  3,  5,  4, ZSTD_greedy  },  /* level  6 */
4129
    { 21, 19, 19,  3,  5,  8, ZSTD_lazy    },  /* level  7 */
4130
    { 21, 19, 19,  3,  5, 16, ZSTD_lazy2   },  /* level  8 */
4131
    { 21, 19, 20,  4,  5, 16, ZSTD_lazy2   },  /* level  9 */
4132
    { 22, 20, 21,  4,  5, 16, ZSTD_lazy2   },  /* level 10 */
4133
    { 22, 21, 22,  4,  5, 16, ZSTD_lazy2   },  /* level 11 */
4134
    { 22, 21, 22,  5,  5, 16, ZSTD_lazy2   },  /* level 12 */
4135
    { 22, 21, 22,  5,  5, 32, ZSTD_btlazy2 },  /* level 13 */
4136
    { 22, 22, 23,  5,  5, 32, ZSTD_btlazy2 },  /* level 14 */
4137
    { 22, 23, 23,  6,  5, 32, ZSTD_btlazy2 },  /* level 15 */
4138
    { 22, 22, 22,  5,  5, 48, ZSTD_btopt   },  /* level 16 */
4139
    { 23, 23, 22,  5,  4, 64, ZSTD_btopt   },  /* level 17 */
4140
    { 23, 23, 22,  6,  3, 64, ZSTD_btultra },  /* level 18 */
4141
    { 23, 24, 22,  7,  3,256, ZSTD_btultra2},  /* level 19 */
4142
    { 25, 25, 23,  7,  3,256, ZSTD_btultra2},  /* level 20 */
4143
    { 26, 26, 24,  7,  3,512, ZSTD_btultra2},  /* level 21 */
4144
    { 27, 27, 25,  9,  3,999, ZSTD_btultra2},  /* level 22 */
4145
},
4146
{   /* for srcSize <= 256 KB */
4147
    /* W,  C,  H,  S,  L,  T, strat */
4148
    { 18, 12, 13,  1,  5,  1, ZSTD_fast    },  /* base for negative levels */
4149
    { 18, 13, 14,  1,  6,  0, ZSTD_fast    },  /* level  1 */
4150
    { 18, 14, 14,  1,  5,  0, ZSTD_dfast   },  /* level  2 */
4151
    { 18, 16, 16,  1,  4,  0, ZSTD_dfast   },  /* level  3 */
4152
    { 18, 16, 17,  2,  5,  2, ZSTD_greedy  },  /* level  4.*/
4153
    { 18, 18, 18,  3,  5,  2, ZSTD_greedy  },  /* level  5.*/
4154
    { 18, 18, 19,  3,  5,  4, ZSTD_lazy    },  /* level  6.*/
4155
    { 18, 18, 19,  4,  4,  4, ZSTD_lazy    },  /* level  7 */
4156
    { 18, 18, 19,  4,  4,  8, ZSTD_lazy2   },  /* level  8 */
4157
    { 18, 18, 19,  5,  4,  8, ZSTD_lazy2   },  /* level  9 */
4158
    { 18, 18, 19,  6,  4,  8, ZSTD_lazy2   },  /* level 10 */
4159
    { 18, 18, 19,  5,  4, 12, ZSTD_btlazy2 },  /* level 11.*/
4160
    { 18, 19, 19,  7,  4, 12, ZSTD_btlazy2 },  /* level 12.*/
4161
    { 18, 18, 19,  4,  4, 16, ZSTD_btopt   },  /* level 13 */
4162
    { 18, 18, 19,  4,  3, 32, ZSTD_btopt   },  /* level 14.*/
4163
    { 18, 18, 19,  6,  3,128, ZSTD_btopt   },  /* level 15.*/
4164
    { 18, 19, 19,  6,  3,128, ZSTD_btultra },  /* level 16.*/
4165
    { 18, 19, 19,  8,  3,256, ZSTD_btultra },  /* level 17.*/
4166
    { 18, 19, 19,  6,  3,128, ZSTD_btultra2},  /* level 18.*/
4167
    { 18, 19, 19,  8,  3,256, ZSTD_btultra2},  /* level 19.*/
4168
    { 18, 19, 19, 10,  3,512, ZSTD_btultra2},  /* level 20.*/
4169
    { 18, 19, 19, 12,  3,512, ZSTD_btultra2},  /* level 21.*/
4170
    { 18, 19, 19, 13,  3,999, ZSTD_btultra2},  /* level 22.*/
4171
},
4172
{   /* for srcSize <= 128 KB */
4173
    /* W,  C,  H,  S,  L,  T, strat */
4174
    { 17, 12, 12,  1,  5,  1, ZSTD_fast    },  /* base for negative levels */
4175
    { 17, 12, 13,  1,  6,  0, ZSTD_fast    },  /* level  1 */
4176
    { 17, 13, 15,  1,  5,  0, ZSTD_fast    },  /* level  2 */
4177
    { 17, 15, 16,  2,  5,  0, ZSTD_dfast   },  /* level  3 */
4178
    { 17, 17, 17,  2,  4,  0, ZSTD_dfast   },  /* level  4 */
4179
    { 17, 16, 17,  3,  4,  2, ZSTD_greedy  },  /* level  5 */
4180
    { 17, 17, 17,  3,  4,  4, ZSTD_lazy    },  /* level  6 */
4181
    { 17, 17, 17,  3,  4,  8, ZSTD_lazy2   },  /* level  7 */
4182
    { 17, 17, 17,  4,  4,  8, ZSTD_lazy2   },  /* level  8 */
4183
    { 17, 17, 17,  5,  4,  8, ZSTD_lazy2   },  /* level  9 */
4184
    { 17, 17, 17,  6,  4,  8, ZSTD_lazy2   },  /* level 10 */
4185
    { 17, 17, 17,  5,  4,  8, ZSTD_btlazy2 },  /* level 11 */
4186
    { 17, 18, 17,  7,  4, 12, ZSTD_btlazy2 },  /* level 12 */
4187
    { 17, 18, 17,  3,  4, 12, ZSTD_btopt   },  /* level 13.*/
4188
    { 17, 18, 17,  4,  3, 32, ZSTD_btopt   },  /* level 14.*/
4189
    { 17, 18, 17,  6,  3,256, ZSTD_btopt   },  /* level 15.*/
4190
    { 17, 18, 17,  6,  3,128, ZSTD_btultra },  /* level 16.*/
4191
    { 17, 18, 17,  8,  3,256, ZSTD_btultra },  /* level 17.*/
4192
    { 17, 18, 17, 10,  3,512, ZSTD_btultra },  /* level 18.*/
4193
    { 17, 18, 17,  5,  3,256, ZSTD_btultra2},  /* level 19.*/
4194
    { 17, 18, 17,  7,  3,512, ZSTD_btultra2},  /* level 20.*/
4195
    { 17, 18, 17,  9,  3,512, ZSTD_btultra2},  /* level 21.*/
4196
    { 17, 18, 17, 11,  3,999, ZSTD_btultra2},  /* level 22.*/
4197
},
4198
{   /* for srcSize <= 16 KB */
4199
    /* W,  C,  H,  S,  L,  T, strat */
4200
    { 14, 12, 13,  1,  5,  1, ZSTD_fast    },  /* base for negative levels */
4201
    { 14, 14, 15,  1,  5,  0, ZSTD_fast    },  /* level  1 */
4202
    { 14, 14, 15,  1,  4,  0, ZSTD_fast    },  /* level  2 */
4203
    { 14, 14, 15,  2,  4,  0, ZSTD_dfast   },  /* level  3 */
4204
    { 14, 14, 14,  4,  4,  2, ZSTD_greedy  },  /* level  4 */
4205
    { 14, 14, 14,  3,  4,  4, ZSTD_lazy    },  /* level  5.*/
4206
    { 14, 14, 14,  4,  4,  8, ZSTD_lazy2   },  /* level  6 */
4207
    { 14, 14, 14,  6,  4,  8, ZSTD_lazy2   },  /* level  7 */
4208
    { 14, 14, 14,  8,  4,  8, ZSTD_lazy2   },  /* level  8.*/
4209
    { 14, 15, 14,  5,  4,  8, ZSTD_btlazy2 },  /* level  9.*/
4210
    { 14, 15, 14,  9,  4,  8, ZSTD_btlazy2 },  /* level 10.*/
4211
    { 14, 15, 14,  3,  4, 12, ZSTD_btopt   },  /* level 11.*/
4212
    { 14, 15, 14,  4,  3, 24, ZSTD_btopt   },  /* level 12.*/
4213
    { 14, 15, 14,  5,  3, 32, ZSTD_btultra },  /* level 13.*/
4214
    { 14, 15, 15,  6,  3, 64, ZSTD_btultra },  /* level 14.*/
4215
    { 14, 15, 15,  7,  3,256, ZSTD_btultra },  /* level 15.*/
4216
    { 14, 15, 15,  5,  3, 48, ZSTD_btultra2},  /* level 16.*/
4217
    { 14, 15, 15,  6,  3,128, ZSTD_btultra2},  /* level 17.*/
4218
    { 14, 15, 15,  7,  3,256, ZSTD_btultra2},  /* level 18.*/
4219
    { 14, 15, 15,  8,  3,256, ZSTD_btultra2},  /* level 19.*/
4220
    { 14, 15, 15,  8,  3,512, ZSTD_btultra2},  /* level 20.*/
4221
    { 14, 15, 15,  9,  3,512, ZSTD_btultra2},  /* level 21.*/
4222
    { 14, 15, 15, 10,  3,999, ZSTD_btultra2},  /* level 22.*/
4223
},
4224
};
4225
4226
/*! ZSTD_getCParams_internal() :
4227
 * @return ZSTD_compressionParameters structure for a selected compression level, srcSize and dictSize.
4228
 *  Note: srcSizeHint 0 means 0, use ZSTD_CONTENTSIZE_UNKNOWN for unknown.
4229
 *        Use dictSize == 0 for unknown or unused. */
4230
static ZSTD_compressionParameters ZSTD_getCParams_internal(int compressionLevel, unsigned long long srcSizeHint, size_t dictSize)
4231
0
{
4232
0
    int const unknown = srcSizeHint == ZSTD_CONTENTSIZE_UNKNOWN;
4233
0
    size_t const addedSize = unknown && dictSize > 0 ? 500 : 0;
4234
0
    U64 const rSize = unknown && dictSize == 0 ? ZSTD_CONTENTSIZE_UNKNOWN : srcSizeHint+dictSize+addedSize;
4235
0
    U32 const tableID = (rSize <= 256 KB) + (rSize <= 128 KB) + (rSize <= 16 KB);
4236
0
    int row = compressionLevel;
4237
0
    DEBUGLOG(5, "ZSTD_getCParams_internal (cLevel=%i)", compressionLevel);
4238
0
    if (compressionLevel == 0) row = ZSTD_CLEVEL_DEFAULT;   /* 0 == default */
4239
0
    if (compressionLevel < 0) row = 0;   /* entry 0 is baseline for fast mode */
4240
0
    if (compressionLevel > ZSTD_MAX_CLEVEL) row = ZSTD_MAX_CLEVEL;
4241
0
    {   ZSTD_compressionParameters cp = ZSTD_defaultCParameters[tableID][row];
4242
0
        if (compressionLevel < 0) cp.targetLength = (unsigned)(-compressionLevel);   /* acceleration factor */
4243
        /* refine parameters based on srcSize & dictSize */
4244
0
        return ZSTD_adjustCParams_internal(cp, srcSizeHint, dictSize);
4245
0
    }
4246
0
}
4247
4248
/*! ZSTD_getCParams() :
4249
 * @return ZSTD_compressionParameters structure for a selected compression level, srcSize and dictSize.
4250
 *  Size values are optional, provide 0 if not known or unused */
4251
ZSTD_compressionParameters ZSTD_getCParams(int compressionLevel, unsigned long long srcSizeHint, size_t dictSize)
4252
0
{
4253
0
    if (srcSizeHint == 0) srcSizeHint = ZSTD_CONTENTSIZE_UNKNOWN;
4254
0
    return ZSTD_getCParams_internal(compressionLevel, srcSizeHint, dictSize);
4255
0
}
4256
4257
/*! ZSTD_getParams() :
4258
 *  same idea as ZSTD_getCParams()
4259
 * @return a `ZSTD_parameters` structure (instead of `ZSTD_compressionParameters`).
4260
 *  Fields of `ZSTD_frameParameters` are set to default values */
4261
0
static ZSTD_parameters ZSTD_getParams_internal(int compressionLevel, unsigned long long srcSizeHint, size_t dictSize) {
4262
0
    ZSTD_parameters params;
4263
0
    ZSTD_compressionParameters const cParams = ZSTD_getCParams_internal(compressionLevel, srcSizeHint, dictSize);
4264
0
    DEBUGLOG(5, "ZSTD_getParams (cLevel=%i)", compressionLevel);
4265
0
    memset(&params, 0, sizeof(params));
4266
0
    params.cParams = cParams;
4267
0
    params.fParams.contentSizeFlag = 1;
4268
0
    return params;
4269
0
}
4270
4271
/*! ZSTD_getParams() :
4272
 *  same idea as ZSTD_getCParams()
4273
 * @return a `ZSTD_parameters` structure (instead of `ZSTD_compressionParameters`).
4274
 *  Fields of `ZSTD_frameParameters` are set to default values */
4275
0
ZSTD_parameters ZSTD_getParams(int compressionLevel, unsigned long long srcSizeHint, size_t dictSize) {
4276
0
    if (srcSizeHint == 0) srcSizeHint = ZSTD_CONTENTSIZE_UNKNOWN;
4277
0
    return ZSTD_getParams_internal(compressionLevel, srcSizeHint, dictSize);
4278
0
}
4279
4280
}