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