xref: /aosp_15_r20/external/zstd/lib/compress/zstd_compress_internal.h (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 /* This header contains definitions
12*01826a49SYabin Cui  * that shall **only** be used by modules within lib/compress.
13*01826a49SYabin Cui  */
14*01826a49SYabin Cui 
15*01826a49SYabin Cui #ifndef ZSTD_COMPRESS_H
16*01826a49SYabin Cui #define ZSTD_COMPRESS_H
17*01826a49SYabin Cui 
18*01826a49SYabin Cui /*-*************************************
19*01826a49SYabin Cui *  Dependencies
20*01826a49SYabin Cui ***************************************/
21*01826a49SYabin Cui #include "../common/zstd_internal.h"
22*01826a49SYabin Cui #include "zstd_cwksp.h"
23*01826a49SYabin Cui #ifdef ZSTD_MULTITHREAD
24*01826a49SYabin Cui #  include "zstdmt_compress.h"
25*01826a49SYabin Cui #endif
26*01826a49SYabin Cui #include "../common/bits.h" /* ZSTD_highbit32, ZSTD_NbCommonBytes */
27*01826a49SYabin Cui 
28*01826a49SYabin Cui #if defined (__cplusplus)
29*01826a49SYabin Cui extern "C" {
30*01826a49SYabin Cui #endif
31*01826a49SYabin Cui 
32*01826a49SYabin Cui /*-*************************************
33*01826a49SYabin Cui *  Constants
34*01826a49SYabin Cui ***************************************/
35*01826a49SYabin Cui #define kSearchStrength      8
36*01826a49SYabin Cui #define HASH_READ_SIZE       8
37*01826a49SYabin Cui #define ZSTD_DUBT_UNSORTED_MARK 1   /* For btlazy2 strategy, index ZSTD_DUBT_UNSORTED_MARK==1 means "unsorted".
38*01826a49SYabin Cui                                        It could be confused for a real successor at index "1", if sorted as larger than its predecessor.
39*01826a49SYabin Cui                                        It's not a big deal though : candidate will just be sorted again.
40*01826a49SYabin Cui                                        Additionally, candidate position 1 will be lost.
41*01826a49SYabin Cui                                        But candidate 1 cannot hide a large tree of candidates, so it's a minimal loss.
42*01826a49SYabin Cui                                        The benefit is that ZSTD_DUBT_UNSORTED_MARK cannot be mishandled after table reuse with a different strategy.
43*01826a49SYabin Cui                                        This constant is required by ZSTD_compressBlock_btlazy2() and ZSTD_reduceTable_internal() */
44*01826a49SYabin Cui 
45*01826a49SYabin Cui 
46*01826a49SYabin Cui /*-*************************************
47*01826a49SYabin Cui *  Context memory management
48*01826a49SYabin Cui ***************************************/
49*01826a49SYabin Cui typedef enum { ZSTDcs_created=0, ZSTDcs_init, ZSTDcs_ongoing, ZSTDcs_ending } ZSTD_compressionStage_e;
50*01826a49SYabin Cui typedef enum { zcss_init=0, zcss_load, zcss_flush } ZSTD_cStreamStage;
51*01826a49SYabin Cui 
52*01826a49SYabin Cui typedef struct ZSTD_prefixDict_s {
53*01826a49SYabin Cui     const void* dict;
54*01826a49SYabin Cui     size_t dictSize;
55*01826a49SYabin Cui     ZSTD_dictContentType_e dictContentType;
56*01826a49SYabin Cui } ZSTD_prefixDict;
57*01826a49SYabin Cui 
58*01826a49SYabin Cui typedef struct {
59*01826a49SYabin Cui     void* dictBuffer;
60*01826a49SYabin Cui     void const* dict;
61*01826a49SYabin Cui     size_t dictSize;
62*01826a49SYabin Cui     ZSTD_dictContentType_e dictContentType;
63*01826a49SYabin Cui     ZSTD_CDict* cdict;
64*01826a49SYabin Cui } ZSTD_localDict;
65*01826a49SYabin Cui 
66*01826a49SYabin Cui typedef struct {
67*01826a49SYabin Cui     HUF_CElt CTable[HUF_CTABLE_SIZE_ST(255)];
68*01826a49SYabin Cui     HUF_repeat repeatMode;
69*01826a49SYabin Cui } ZSTD_hufCTables_t;
70*01826a49SYabin Cui 
71*01826a49SYabin Cui typedef struct {
72*01826a49SYabin Cui     FSE_CTable offcodeCTable[FSE_CTABLE_SIZE_U32(OffFSELog, MaxOff)];
73*01826a49SYabin Cui     FSE_CTable matchlengthCTable[FSE_CTABLE_SIZE_U32(MLFSELog, MaxML)];
74*01826a49SYabin Cui     FSE_CTable litlengthCTable[FSE_CTABLE_SIZE_U32(LLFSELog, MaxLL)];
75*01826a49SYabin Cui     FSE_repeat offcode_repeatMode;
76*01826a49SYabin Cui     FSE_repeat matchlength_repeatMode;
77*01826a49SYabin Cui     FSE_repeat litlength_repeatMode;
78*01826a49SYabin Cui } ZSTD_fseCTables_t;
79*01826a49SYabin Cui 
80*01826a49SYabin Cui typedef struct {
81*01826a49SYabin Cui     ZSTD_hufCTables_t huf;
82*01826a49SYabin Cui     ZSTD_fseCTables_t fse;
83*01826a49SYabin Cui } ZSTD_entropyCTables_t;
84*01826a49SYabin Cui 
85*01826a49SYabin Cui /***********************************************
86*01826a49SYabin Cui *  Entropy buffer statistics structs and funcs *
87*01826a49SYabin Cui ***********************************************/
88*01826a49SYabin Cui /** ZSTD_hufCTablesMetadata_t :
89*01826a49SYabin Cui  *  Stores Literals Block Type for a super-block in hType, and
90*01826a49SYabin Cui  *  huffman tree description in hufDesBuffer.
91*01826a49SYabin Cui  *  hufDesSize refers to the size of huffman tree description in bytes.
92*01826a49SYabin Cui  *  This metadata is populated in ZSTD_buildBlockEntropyStats_literals() */
93*01826a49SYabin Cui typedef struct {
94*01826a49SYabin Cui     symbolEncodingType_e hType;
95*01826a49SYabin Cui     BYTE hufDesBuffer[ZSTD_MAX_HUF_HEADER_SIZE];
96*01826a49SYabin Cui     size_t hufDesSize;
97*01826a49SYabin Cui } ZSTD_hufCTablesMetadata_t;
98*01826a49SYabin Cui 
99*01826a49SYabin Cui /** ZSTD_fseCTablesMetadata_t :
100*01826a49SYabin Cui  *  Stores symbol compression modes for a super-block in {ll, ol, ml}Type, and
101*01826a49SYabin Cui  *  fse tables in fseTablesBuffer.
102*01826a49SYabin Cui  *  fseTablesSize refers to the size of fse tables in bytes.
103*01826a49SYabin Cui  *  This metadata is populated in ZSTD_buildBlockEntropyStats_sequences() */
104*01826a49SYabin Cui typedef struct {
105*01826a49SYabin Cui     symbolEncodingType_e llType;
106*01826a49SYabin Cui     symbolEncodingType_e ofType;
107*01826a49SYabin Cui     symbolEncodingType_e mlType;
108*01826a49SYabin Cui     BYTE fseTablesBuffer[ZSTD_MAX_FSE_HEADERS_SIZE];
109*01826a49SYabin Cui     size_t fseTablesSize;
110*01826a49SYabin Cui     size_t lastCountSize; /* This is to account for bug in 1.3.4. More detail in ZSTD_entropyCompressSeqStore_internal() */
111*01826a49SYabin Cui } ZSTD_fseCTablesMetadata_t;
112*01826a49SYabin Cui 
113*01826a49SYabin Cui typedef struct {
114*01826a49SYabin Cui     ZSTD_hufCTablesMetadata_t hufMetadata;
115*01826a49SYabin Cui     ZSTD_fseCTablesMetadata_t fseMetadata;
116*01826a49SYabin Cui } ZSTD_entropyCTablesMetadata_t;
117*01826a49SYabin Cui 
118*01826a49SYabin Cui /** ZSTD_buildBlockEntropyStats() :
119*01826a49SYabin Cui  *  Builds entropy for the block.
120*01826a49SYabin Cui  *  @return : 0 on success or error code */
121*01826a49SYabin Cui size_t ZSTD_buildBlockEntropyStats(
122*01826a49SYabin Cui                     const seqStore_t* seqStorePtr,
123*01826a49SYabin Cui                     const ZSTD_entropyCTables_t* prevEntropy,
124*01826a49SYabin Cui                           ZSTD_entropyCTables_t* nextEntropy,
125*01826a49SYabin Cui                     const ZSTD_CCtx_params* cctxParams,
126*01826a49SYabin Cui                           ZSTD_entropyCTablesMetadata_t* entropyMetadata,
127*01826a49SYabin Cui                           void* workspace, size_t wkspSize);
128*01826a49SYabin Cui 
129*01826a49SYabin Cui /*********************************
130*01826a49SYabin Cui *  Compression internals structs *
131*01826a49SYabin Cui *********************************/
132*01826a49SYabin Cui 
133*01826a49SYabin Cui typedef struct {
134*01826a49SYabin Cui     U32 off;            /* Offset sumtype code for the match, using ZSTD_storeSeq() format */
135*01826a49SYabin Cui     U32 len;            /* Raw length of match */
136*01826a49SYabin Cui } ZSTD_match_t;
137*01826a49SYabin Cui 
138*01826a49SYabin Cui typedef struct {
139*01826a49SYabin Cui     U32 offset;         /* Offset of sequence */
140*01826a49SYabin Cui     U32 litLength;      /* Length of literals prior to match */
141*01826a49SYabin Cui     U32 matchLength;    /* Raw length of match */
142*01826a49SYabin Cui } rawSeq;
143*01826a49SYabin Cui 
144*01826a49SYabin Cui typedef struct {
145*01826a49SYabin Cui   rawSeq* seq;          /* The start of the sequences */
146*01826a49SYabin Cui   size_t pos;           /* The index in seq where reading stopped. pos <= size. */
147*01826a49SYabin Cui   size_t posInSequence; /* The position within the sequence at seq[pos] where reading
148*01826a49SYabin Cui                            stopped. posInSequence <= seq[pos].litLength + seq[pos].matchLength */
149*01826a49SYabin Cui   size_t size;          /* The number of sequences. <= capacity. */
150*01826a49SYabin Cui   size_t capacity;      /* The capacity starting from `seq` pointer */
151*01826a49SYabin Cui } rawSeqStore_t;
152*01826a49SYabin Cui 
153*01826a49SYabin Cui typedef struct {
154*01826a49SYabin Cui     U32 idx;            /* Index in array of ZSTD_Sequence */
155*01826a49SYabin Cui     U32 posInSequence;  /* Position within sequence at idx */
156*01826a49SYabin Cui     size_t posInSrc;    /* Number of bytes given by sequences provided so far */
157*01826a49SYabin Cui } ZSTD_sequencePosition;
158*01826a49SYabin Cui 
159*01826a49SYabin Cui UNUSED_ATTR static const rawSeqStore_t kNullRawSeqStore = {NULL, 0, 0, 0, 0};
160*01826a49SYabin Cui 
161*01826a49SYabin Cui typedef struct {
162*01826a49SYabin Cui     int price;  /* price from beginning of segment to this position */
163*01826a49SYabin Cui     U32 off;    /* offset of previous match */
164*01826a49SYabin Cui     U32 mlen;   /* length of previous match */
165*01826a49SYabin Cui     U32 litlen; /* nb of literals since previous match */
166*01826a49SYabin Cui     U32 rep[ZSTD_REP_NUM];  /* offset history after previous match */
167*01826a49SYabin Cui } ZSTD_optimal_t;
168*01826a49SYabin Cui 
169*01826a49SYabin Cui typedef enum { zop_dynamic=0, zop_predef } ZSTD_OptPrice_e;
170*01826a49SYabin Cui 
171*01826a49SYabin Cui #define ZSTD_OPT_SIZE (ZSTD_OPT_NUM+3)
172*01826a49SYabin Cui typedef struct {
173*01826a49SYabin Cui     /* All tables are allocated inside cctx->workspace by ZSTD_resetCCtx_internal() */
174*01826a49SYabin Cui     unsigned* litFreq;           /* table of literals statistics, of size 256 */
175*01826a49SYabin Cui     unsigned* litLengthFreq;     /* table of litLength statistics, of size (MaxLL+1) */
176*01826a49SYabin Cui     unsigned* matchLengthFreq;   /* table of matchLength statistics, of size (MaxML+1) */
177*01826a49SYabin Cui     unsigned* offCodeFreq;       /* table of offCode statistics, of size (MaxOff+1) */
178*01826a49SYabin Cui     ZSTD_match_t* matchTable;    /* list of found matches, of size ZSTD_OPT_SIZE */
179*01826a49SYabin Cui     ZSTD_optimal_t* priceTable;  /* All positions tracked by optimal parser, of size ZSTD_OPT_SIZE */
180*01826a49SYabin Cui 
181*01826a49SYabin Cui     U32  litSum;                 /* nb of literals */
182*01826a49SYabin Cui     U32  litLengthSum;           /* nb of litLength codes */
183*01826a49SYabin Cui     U32  matchLengthSum;         /* nb of matchLength codes */
184*01826a49SYabin Cui     U32  offCodeSum;             /* nb of offset codes */
185*01826a49SYabin Cui     U32  litSumBasePrice;        /* to compare to log2(litfreq) */
186*01826a49SYabin Cui     U32  litLengthSumBasePrice;  /* to compare to log2(llfreq)  */
187*01826a49SYabin Cui     U32  matchLengthSumBasePrice;/* to compare to log2(mlfreq)  */
188*01826a49SYabin Cui     U32  offCodeSumBasePrice;    /* to compare to log2(offreq)  */
189*01826a49SYabin Cui     ZSTD_OptPrice_e priceType;   /* prices can be determined dynamically, or follow a pre-defined cost structure */
190*01826a49SYabin Cui     const ZSTD_entropyCTables_t* symbolCosts;  /* pre-calculated dictionary statistics */
191*01826a49SYabin Cui     ZSTD_paramSwitch_e literalCompressionMode;
192*01826a49SYabin Cui } optState_t;
193*01826a49SYabin Cui 
194*01826a49SYabin Cui typedef struct {
195*01826a49SYabin Cui   ZSTD_entropyCTables_t entropy;
196*01826a49SYabin Cui   U32 rep[ZSTD_REP_NUM];
197*01826a49SYabin Cui } ZSTD_compressedBlockState_t;
198*01826a49SYabin Cui 
199*01826a49SYabin Cui typedef struct {
200*01826a49SYabin Cui     BYTE const* nextSrc;       /* next block here to continue on current prefix */
201*01826a49SYabin Cui     BYTE const* base;          /* All regular indexes relative to this position */
202*01826a49SYabin Cui     BYTE const* dictBase;      /* extDict indexes relative to this position */
203*01826a49SYabin Cui     U32 dictLimit;             /* below that point, need extDict */
204*01826a49SYabin Cui     U32 lowLimit;              /* below that point, no more valid data */
205*01826a49SYabin Cui     U32 nbOverflowCorrections; /* Number of times overflow correction has run since
206*01826a49SYabin Cui                                 * ZSTD_window_init(). Useful for debugging coredumps
207*01826a49SYabin Cui                                 * and for ZSTD_WINDOW_OVERFLOW_CORRECT_FREQUENTLY.
208*01826a49SYabin Cui                                 */
209*01826a49SYabin Cui } ZSTD_window_t;
210*01826a49SYabin Cui 
211*01826a49SYabin Cui #define ZSTD_WINDOW_START_INDEX 2
212*01826a49SYabin Cui 
213*01826a49SYabin Cui typedef struct ZSTD_matchState_t ZSTD_matchState_t;
214*01826a49SYabin Cui 
215*01826a49SYabin Cui #define ZSTD_ROW_HASH_CACHE_SIZE 8       /* Size of prefetching hash cache for row-based matchfinder */
216*01826a49SYabin Cui 
217*01826a49SYabin Cui struct ZSTD_matchState_t {
218*01826a49SYabin Cui     ZSTD_window_t window;   /* State for window round buffer management */
219*01826a49SYabin Cui     U32 loadedDictEnd;      /* index of end of dictionary, within context's referential.
220*01826a49SYabin Cui                              * When loadedDictEnd != 0, a dictionary is in use, and still valid.
221*01826a49SYabin Cui                              * This relies on a mechanism to set loadedDictEnd=0 when dictionary is no longer within distance.
222*01826a49SYabin Cui                              * Such mechanism is provided within ZSTD_window_enforceMaxDist() and ZSTD_checkDictValidity().
223*01826a49SYabin Cui                              * When dict referential is copied into active context (i.e. not attached),
224*01826a49SYabin Cui                              * loadedDictEnd == dictSize, since referential starts from zero.
225*01826a49SYabin Cui                              */
226*01826a49SYabin Cui     U32 nextToUpdate;       /* index from which to continue table update */
227*01826a49SYabin Cui     U32 hashLog3;           /* dispatch table for matches of len==3 : larger == faster, more memory */
228*01826a49SYabin Cui 
229*01826a49SYabin Cui     U32 rowHashLog;                          /* For row-based matchfinder: Hashlog based on nb of rows in the hashTable.*/
230*01826a49SYabin Cui     BYTE* tagTable;                          /* For row-based matchFinder: A row-based table containing the hashes and head index. */
231*01826a49SYabin Cui     U32 hashCache[ZSTD_ROW_HASH_CACHE_SIZE]; /* For row-based matchFinder: a cache of hashes to improve speed */
232*01826a49SYabin Cui     U64 hashSalt;                            /* For row-based matchFinder: salts the hash for reuse of tag table */
233*01826a49SYabin Cui     U32 hashSaltEntropy;                     /* For row-based matchFinder: collects entropy for salt generation */
234*01826a49SYabin Cui 
235*01826a49SYabin Cui     U32* hashTable;
236*01826a49SYabin Cui     U32* hashTable3;
237*01826a49SYabin Cui     U32* chainTable;
238*01826a49SYabin Cui 
239*01826a49SYabin Cui     U32 forceNonContiguous; /* Non-zero if we should force non-contiguous load for the next window update. */
240*01826a49SYabin Cui 
241*01826a49SYabin Cui     int dedicatedDictSearch;  /* Indicates whether this matchState is using the
242*01826a49SYabin Cui                                * dedicated dictionary search structure.
243*01826a49SYabin Cui                                */
244*01826a49SYabin Cui     optState_t opt;         /* optimal parser state */
245*01826a49SYabin Cui     const ZSTD_matchState_t* dictMatchState;
246*01826a49SYabin Cui     ZSTD_compressionParameters cParams;
247*01826a49SYabin Cui     const rawSeqStore_t* ldmSeqStore;
248*01826a49SYabin Cui 
249*01826a49SYabin Cui     /* Controls prefetching in some dictMatchState matchfinders.
250*01826a49SYabin Cui      * This behavior is controlled from the cctx ms.
251*01826a49SYabin Cui      * This parameter has no effect in the cdict ms. */
252*01826a49SYabin Cui     int prefetchCDictTables;
253*01826a49SYabin Cui 
254*01826a49SYabin Cui     /* When == 0, lazy match finders insert every position.
255*01826a49SYabin Cui      * When != 0, lazy match finders only insert positions they search.
256*01826a49SYabin Cui      * This allows them to skip much faster over incompressible data,
257*01826a49SYabin Cui      * at a small cost to compression ratio.
258*01826a49SYabin Cui      */
259*01826a49SYabin Cui     int lazySkipping;
260*01826a49SYabin Cui };
261*01826a49SYabin Cui 
262*01826a49SYabin Cui typedef struct {
263*01826a49SYabin Cui     ZSTD_compressedBlockState_t* prevCBlock;
264*01826a49SYabin Cui     ZSTD_compressedBlockState_t* nextCBlock;
265*01826a49SYabin Cui     ZSTD_matchState_t matchState;
266*01826a49SYabin Cui } ZSTD_blockState_t;
267*01826a49SYabin Cui 
268*01826a49SYabin Cui typedef struct {
269*01826a49SYabin Cui     U32 offset;
270*01826a49SYabin Cui     U32 checksum;
271*01826a49SYabin Cui } ldmEntry_t;
272*01826a49SYabin Cui 
273*01826a49SYabin Cui typedef struct {
274*01826a49SYabin Cui     BYTE const* split;
275*01826a49SYabin Cui     U32 hash;
276*01826a49SYabin Cui     U32 checksum;
277*01826a49SYabin Cui     ldmEntry_t* bucket;
278*01826a49SYabin Cui } ldmMatchCandidate_t;
279*01826a49SYabin Cui 
280*01826a49SYabin Cui #define LDM_BATCH_SIZE 64
281*01826a49SYabin Cui 
282*01826a49SYabin Cui typedef struct {
283*01826a49SYabin Cui     ZSTD_window_t window;   /* State for the window round buffer management */
284*01826a49SYabin Cui     ldmEntry_t* hashTable;
285*01826a49SYabin Cui     U32 loadedDictEnd;
286*01826a49SYabin Cui     BYTE* bucketOffsets;    /* Next position in bucket to insert entry */
287*01826a49SYabin Cui     size_t splitIndices[LDM_BATCH_SIZE];
288*01826a49SYabin Cui     ldmMatchCandidate_t matchCandidates[LDM_BATCH_SIZE];
289*01826a49SYabin Cui } ldmState_t;
290*01826a49SYabin Cui 
291*01826a49SYabin Cui typedef struct {
292*01826a49SYabin Cui     ZSTD_paramSwitch_e enableLdm; /* ZSTD_ps_enable to enable LDM. ZSTD_ps_auto by default */
293*01826a49SYabin Cui     U32 hashLog;            /* Log size of hashTable */
294*01826a49SYabin Cui     U32 bucketSizeLog;      /* Log bucket size for collision resolution, at most 8 */
295*01826a49SYabin Cui     U32 minMatchLength;     /* Minimum match length */
296*01826a49SYabin Cui     U32 hashRateLog;       /* Log number of entries to skip */
297*01826a49SYabin Cui     U32 windowLog;          /* Window log for the LDM */
298*01826a49SYabin Cui } ldmParams_t;
299*01826a49SYabin Cui 
300*01826a49SYabin Cui typedef struct {
301*01826a49SYabin Cui     int collectSequences;
302*01826a49SYabin Cui     ZSTD_Sequence* seqStart;
303*01826a49SYabin Cui     size_t seqIndex;
304*01826a49SYabin Cui     size_t maxSequences;
305*01826a49SYabin Cui } SeqCollector;
306*01826a49SYabin Cui 
307*01826a49SYabin Cui struct ZSTD_CCtx_params_s {
308*01826a49SYabin Cui     ZSTD_format_e format;
309*01826a49SYabin Cui     ZSTD_compressionParameters cParams;
310*01826a49SYabin Cui     ZSTD_frameParameters fParams;
311*01826a49SYabin Cui 
312*01826a49SYabin Cui     int compressionLevel;
313*01826a49SYabin Cui     int forceWindow;           /* force back-references to respect limit of
314*01826a49SYabin Cui                                 * 1<<wLog, even for dictionary */
315*01826a49SYabin Cui     size_t targetCBlockSize;   /* Tries to fit compressed block size to be around targetCBlockSize.
316*01826a49SYabin Cui                                 * No target when targetCBlockSize == 0.
317*01826a49SYabin Cui                                 * There is no guarantee on compressed block size */
318*01826a49SYabin Cui     int srcSizeHint;           /* User's best guess of source size.
319*01826a49SYabin Cui                                 * Hint is not valid when srcSizeHint == 0.
320*01826a49SYabin Cui                                 * There is no guarantee that hint is close to actual source size */
321*01826a49SYabin Cui 
322*01826a49SYabin Cui     ZSTD_dictAttachPref_e attachDictPref;
323*01826a49SYabin Cui     ZSTD_paramSwitch_e literalCompressionMode;
324*01826a49SYabin Cui 
325*01826a49SYabin Cui     /* Multithreading: used to pass parameters to mtctx */
326*01826a49SYabin Cui     int nbWorkers;
327*01826a49SYabin Cui     size_t jobSize;
328*01826a49SYabin Cui     int overlapLog;
329*01826a49SYabin Cui     int rsyncable;
330*01826a49SYabin Cui 
331*01826a49SYabin Cui     /* Long distance matching parameters */
332*01826a49SYabin Cui     ldmParams_t ldmParams;
333*01826a49SYabin Cui 
334*01826a49SYabin Cui     /* Dedicated dict search algorithm trigger */
335*01826a49SYabin Cui     int enableDedicatedDictSearch;
336*01826a49SYabin Cui 
337*01826a49SYabin Cui     /* Input/output buffer modes */
338*01826a49SYabin Cui     ZSTD_bufferMode_e inBufferMode;
339*01826a49SYabin Cui     ZSTD_bufferMode_e outBufferMode;
340*01826a49SYabin Cui 
341*01826a49SYabin Cui     /* Sequence compression API */
342*01826a49SYabin Cui     ZSTD_sequenceFormat_e blockDelimiters;
343*01826a49SYabin Cui     int validateSequences;
344*01826a49SYabin Cui 
345*01826a49SYabin Cui     /* Block splitting */
346*01826a49SYabin Cui     ZSTD_paramSwitch_e useBlockSplitter;
347*01826a49SYabin Cui 
348*01826a49SYabin Cui     /* Param for deciding whether to use row-based matchfinder */
349*01826a49SYabin Cui     ZSTD_paramSwitch_e useRowMatchFinder;
350*01826a49SYabin Cui 
351*01826a49SYabin Cui     /* Always load a dictionary in ext-dict mode (not prefix mode)? */
352*01826a49SYabin Cui     int deterministicRefPrefix;
353*01826a49SYabin Cui 
354*01826a49SYabin Cui     /* Internal use, for createCCtxParams() and freeCCtxParams() only */
355*01826a49SYabin Cui     ZSTD_customMem customMem;
356*01826a49SYabin Cui 
357*01826a49SYabin Cui     /* Controls prefetching in some dictMatchState matchfinders */
358*01826a49SYabin Cui     ZSTD_paramSwitch_e prefetchCDictTables;
359*01826a49SYabin Cui 
360*01826a49SYabin Cui     /* Controls whether zstd will fall back to an internal matchfinder
361*01826a49SYabin Cui      * if the external matchfinder returns an error code. */
362*01826a49SYabin Cui     int enableMatchFinderFallback;
363*01826a49SYabin Cui 
364*01826a49SYabin Cui     /* Parameters for the external sequence producer API.
365*01826a49SYabin Cui      * Users set these parameters through ZSTD_registerSequenceProducer().
366*01826a49SYabin Cui      * It is not possible to set these parameters individually through the public API. */
367*01826a49SYabin Cui     void* extSeqProdState;
368*01826a49SYabin Cui     ZSTD_sequenceProducer_F extSeqProdFunc;
369*01826a49SYabin Cui 
370*01826a49SYabin Cui     /* Adjust the max block size*/
371*01826a49SYabin Cui     size_t maxBlockSize;
372*01826a49SYabin Cui 
373*01826a49SYabin Cui     /* Controls repcode search in external sequence parsing */
374*01826a49SYabin Cui     ZSTD_paramSwitch_e searchForExternalRepcodes;
375*01826a49SYabin Cui };  /* typedef'd to ZSTD_CCtx_params within "zstd.h" */
376*01826a49SYabin Cui 
377*01826a49SYabin Cui #define COMPRESS_SEQUENCES_WORKSPACE_SIZE (sizeof(unsigned) * (MaxSeq + 2))
378*01826a49SYabin Cui #define ENTROPY_WORKSPACE_SIZE (HUF_WORKSPACE_SIZE + COMPRESS_SEQUENCES_WORKSPACE_SIZE)
379*01826a49SYabin Cui 
380*01826a49SYabin Cui /**
381*01826a49SYabin Cui  * Indicates whether this compression proceeds directly from user-provided
382*01826a49SYabin Cui  * source buffer to user-provided destination buffer (ZSTDb_not_buffered), or
383*01826a49SYabin Cui  * whether the context needs to buffer the input/output (ZSTDb_buffered).
384*01826a49SYabin Cui  */
385*01826a49SYabin Cui typedef enum {
386*01826a49SYabin Cui     ZSTDb_not_buffered,
387*01826a49SYabin Cui     ZSTDb_buffered
388*01826a49SYabin Cui } ZSTD_buffered_policy_e;
389*01826a49SYabin Cui 
390*01826a49SYabin Cui /**
391*01826a49SYabin Cui  * Struct that contains all elements of block splitter that should be allocated
392*01826a49SYabin Cui  * in a wksp.
393*01826a49SYabin Cui  */
394*01826a49SYabin Cui #define ZSTD_MAX_NB_BLOCK_SPLITS 196
395*01826a49SYabin Cui typedef struct {
396*01826a49SYabin Cui     seqStore_t fullSeqStoreChunk;
397*01826a49SYabin Cui     seqStore_t firstHalfSeqStore;
398*01826a49SYabin Cui     seqStore_t secondHalfSeqStore;
399*01826a49SYabin Cui     seqStore_t currSeqStore;
400*01826a49SYabin Cui     seqStore_t nextSeqStore;
401*01826a49SYabin Cui 
402*01826a49SYabin Cui     U32 partitions[ZSTD_MAX_NB_BLOCK_SPLITS];
403*01826a49SYabin Cui     ZSTD_entropyCTablesMetadata_t entropyMetadata;
404*01826a49SYabin Cui } ZSTD_blockSplitCtx;
405*01826a49SYabin Cui 
406*01826a49SYabin Cui struct ZSTD_CCtx_s {
407*01826a49SYabin Cui     ZSTD_compressionStage_e stage;
408*01826a49SYabin Cui     int cParamsChanged;                  /* == 1 if cParams(except wlog) or compression level are changed in requestedParams. Triggers transmission of new params to ZSTDMT (if available) then reset to 0. */
409*01826a49SYabin Cui     int bmi2;                            /* == 1 if the CPU supports BMI2 and 0 otherwise. CPU support is determined dynamically once per context lifetime. */
410*01826a49SYabin Cui     ZSTD_CCtx_params requestedParams;
411*01826a49SYabin Cui     ZSTD_CCtx_params appliedParams;
412*01826a49SYabin Cui     ZSTD_CCtx_params simpleApiParams;    /* Param storage used by the simple API - not sticky. Must only be used in top-level simple API functions for storage. */
413*01826a49SYabin Cui     U32   dictID;
414*01826a49SYabin Cui     size_t dictContentSize;
415*01826a49SYabin Cui 
416*01826a49SYabin Cui     ZSTD_cwksp workspace; /* manages buffer for dynamic allocations */
417*01826a49SYabin Cui     size_t blockSize;
418*01826a49SYabin Cui     unsigned long long pledgedSrcSizePlusOne;  /* this way, 0 (default) == unknown */
419*01826a49SYabin Cui     unsigned long long consumedSrcSize;
420*01826a49SYabin Cui     unsigned long long producedCSize;
421*01826a49SYabin Cui     XXH64_state_t xxhState;
422*01826a49SYabin Cui     ZSTD_customMem customMem;
423*01826a49SYabin Cui     ZSTD_threadPool* pool;
424*01826a49SYabin Cui     size_t staticSize;
425*01826a49SYabin Cui     SeqCollector seqCollector;
426*01826a49SYabin Cui     int isFirstBlock;
427*01826a49SYabin Cui     int initialized;
428*01826a49SYabin Cui 
429*01826a49SYabin Cui     seqStore_t seqStore;      /* sequences storage ptrs */
430*01826a49SYabin Cui     ldmState_t ldmState;      /* long distance matching state */
431*01826a49SYabin Cui     rawSeq* ldmSequences;     /* Storage for the ldm output sequences */
432*01826a49SYabin Cui     size_t maxNbLdmSequences;
433*01826a49SYabin Cui     rawSeqStore_t externSeqStore; /* Mutable reference to external sequences */
434*01826a49SYabin Cui     ZSTD_blockState_t blockState;
435*01826a49SYabin Cui     U32* entropyWorkspace;  /* entropy workspace of ENTROPY_WORKSPACE_SIZE bytes */
436*01826a49SYabin Cui 
437*01826a49SYabin Cui     /* Whether we are streaming or not */
438*01826a49SYabin Cui     ZSTD_buffered_policy_e bufferedPolicy;
439*01826a49SYabin Cui 
440*01826a49SYabin Cui     /* streaming */
441*01826a49SYabin Cui     char*  inBuff;
442*01826a49SYabin Cui     size_t inBuffSize;
443*01826a49SYabin Cui     size_t inToCompress;
444*01826a49SYabin Cui     size_t inBuffPos;
445*01826a49SYabin Cui     size_t inBuffTarget;
446*01826a49SYabin Cui     char*  outBuff;
447*01826a49SYabin Cui     size_t outBuffSize;
448*01826a49SYabin Cui     size_t outBuffContentSize;
449*01826a49SYabin Cui     size_t outBuffFlushedSize;
450*01826a49SYabin Cui     ZSTD_cStreamStage streamStage;
451*01826a49SYabin Cui     U32    frameEnded;
452*01826a49SYabin Cui 
453*01826a49SYabin Cui     /* Stable in/out buffer verification */
454*01826a49SYabin Cui     ZSTD_inBuffer expectedInBuffer;
455*01826a49SYabin Cui     size_t stableIn_notConsumed; /* nb bytes within stable input buffer that are said to be consumed but are not */
456*01826a49SYabin Cui     size_t expectedOutBufferSize;
457*01826a49SYabin Cui 
458*01826a49SYabin Cui     /* Dictionary */
459*01826a49SYabin Cui     ZSTD_localDict localDict;
460*01826a49SYabin Cui     const ZSTD_CDict* cdict;
461*01826a49SYabin Cui     ZSTD_prefixDict prefixDict;   /* single-usage dictionary */
462*01826a49SYabin Cui 
463*01826a49SYabin Cui     /* Multi-threading */
464*01826a49SYabin Cui #ifdef ZSTD_MULTITHREAD
465*01826a49SYabin Cui     ZSTDMT_CCtx* mtctx;
466*01826a49SYabin Cui #endif
467*01826a49SYabin Cui 
468*01826a49SYabin Cui     /* Tracing */
469*01826a49SYabin Cui #if ZSTD_TRACE
470*01826a49SYabin Cui     ZSTD_TraceCtx traceCtx;
471*01826a49SYabin Cui #endif
472*01826a49SYabin Cui 
473*01826a49SYabin Cui     /* Workspace for block splitter */
474*01826a49SYabin Cui     ZSTD_blockSplitCtx blockSplitCtx;
475*01826a49SYabin Cui 
476*01826a49SYabin Cui     /* Buffer for output from external sequence producer */
477*01826a49SYabin Cui     ZSTD_Sequence* extSeqBuf;
478*01826a49SYabin Cui     size_t extSeqBufCapacity;
479*01826a49SYabin Cui };
480*01826a49SYabin Cui 
481*01826a49SYabin Cui typedef enum { ZSTD_dtlm_fast, ZSTD_dtlm_full } ZSTD_dictTableLoadMethod_e;
482*01826a49SYabin Cui typedef enum { ZSTD_tfp_forCCtx, ZSTD_tfp_forCDict } ZSTD_tableFillPurpose_e;
483*01826a49SYabin Cui 
484*01826a49SYabin Cui typedef enum {
485*01826a49SYabin Cui     ZSTD_noDict = 0,
486*01826a49SYabin Cui     ZSTD_extDict = 1,
487*01826a49SYabin Cui     ZSTD_dictMatchState = 2,
488*01826a49SYabin Cui     ZSTD_dedicatedDictSearch = 3
489*01826a49SYabin Cui } ZSTD_dictMode_e;
490*01826a49SYabin Cui 
491*01826a49SYabin Cui typedef enum {
492*01826a49SYabin Cui     ZSTD_cpm_noAttachDict = 0,  /* Compression with ZSTD_noDict or ZSTD_extDict.
493*01826a49SYabin Cui                                  * In this mode we use both the srcSize and the dictSize
494*01826a49SYabin Cui                                  * when selecting and adjusting parameters.
495*01826a49SYabin Cui                                  */
496*01826a49SYabin Cui     ZSTD_cpm_attachDict = 1,    /* Compression with ZSTD_dictMatchState or ZSTD_dedicatedDictSearch.
497*01826a49SYabin Cui                                  * In this mode we only take the srcSize into account when selecting
498*01826a49SYabin Cui                                  * and adjusting parameters.
499*01826a49SYabin Cui                                  */
500*01826a49SYabin Cui     ZSTD_cpm_createCDict = 2,   /* Creating a CDict.
501*01826a49SYabin Cui                                  * In this mode we take both the source size and the dictionary size
502*01826a49SYabin Cui                                  * into account when selecting and adjusting the parameters.
503*01826a49SYabin Cui                                  */
504*01826a49SYabin Cui     ZSTD_cpm_unknown = 3        /* ZSTD_getCParams, ZSTD_getParams, ZSTD_adjustParams.
505*01826a49SYabin Cui                                  * We don't know what these parameters are for. We default to the legacy
506*01826a49SYabin Cui                                  * behavior of taking both the source size and the dict size into account
507*01826a49SYabin Cui                                  * when selecting and adjusting parameters.
508*01826a49SYabin Cui                                  */
509*01826a49SYabin Cui } ZSTD_cParamMode_e;
510*01826a49SYabin Cui 
511*01826a49SYabin Cui typedef size_t (*ZSTD_blockCompressor) (
512*01826a49SYabin Cui         ZSTD_matchState_t* bs, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
513*01826a49SYabin Cui         void const* src, size_t srcSize);
514*01826a49SYabin Cui ZSTD_blockCompressor ZSTD_selectBlockCompressor(ZSTD_strategy strat, ZSTD_paramSwitch_e rowMatchfinderMode, ZSTD_dictMode_e dictMode);
515*01826a49SYabin Cui 
516*01826a49SYabin Cui 
ZSTD_LLcode(U32 litLength)517*01826a49SYabin Cui MEM_STATIC U32 ZSTD_LLcode(U32 litLength)
518*01826a49SYabin Cui {
519*01826a49SYabin Cui     static const BYTE LL_Code[64] = {  0,  1,  2,  3,  4,  5,  6,  7,
520*01826a49SYabin Cui                                        8,  9, 10, 11, 12, 13, 14, 15,
521*01826a49SYabin Cui                                       16, 16, 17, 17, 18, 18, 19, 19,
522*01826a49SYabin Cui                                       20, 20, 20, 20, 21, 21, 21, 21,
523*01826a49SYabin Cui                                       22, 22, 22, 22, 22, 22, 22, 22,
524*01826a49SYabin Cui                                       23, 23, 23, 23, 23, 23, 23, 23,
525*01826a49SYabin Cui                                       24, 24, 24, 24, 24, 24, 24, 24,
526*01826a49SYabin Cui                                       24, 24, 24, 24, 24, 24, 24, 24 };
527*01826a49SYabin Cui     static const U32 LL_deltaCode = 19;
528*01826a49SYabin Cui     return (litLength > 63) ? ZSTD_highbit32(litLength) + LL_deltaCode : LL_Code[litLength];
529*01826a49SYabin Cui }
530*01826a49SYabin Cui 
531*01826a49SYabin Cui /* ZSTD_MLcode() :
532*01826a49SYabin Cui  * note : mlBase = matchLength - MINMATCH;
533*01826a49SYabin Cui  *        because it's the format it's stored in seqStore->sequences */
ZSTD_MLcode(U32 mlBase)534*01826a49SYabin Cui MEM_STATIC U32 ZSTD_MLcode(U32 mlBase)
535*01826a49SYabin Cui {
536*01826a49SYabin Cui     static const BYTE ML_Code[128] = { 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15,
537*01826a49SYabin Cui                                       16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
538*01826a49SYabin Cui                                       32, 32, 33, 33, 34, 34, 35, 35, 36, 36, 36, 36, 37, 37, 37, 37,
539*01826a49SYabin Cui                                       38, 38, 38, 38, 38, 38, 38, 38, 39, 39, 39, 39, 39, 39, 39, 39,
540*01826a49SYabin Cui                                       40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40,
541*01826a49SYabin Cui                                       41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41,
542*01826a49SYabin Cui                                       42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42,
543*01826a49SYabin Cui                                       42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42 };
544*01826a49SYabin Cui     static const U32 ML_deltaCode = 36;
545*01826a49SYabin Cui     return (mlBase > 127) ? ZSTD_highbit32(mlBase) + ML_deltaCode : ML_Code[mlBase];
546*01826a49SYabin Cui }
547*01826a49SYabin Cui 
548*01826a49SYabin Cui /* ZSTD_cParam_withinBounds:
549*01826a49SYabin Cui  * @return 1 if value is within cParam bounds,
550*01826a49SYabin Cui  * 0 otherwise */
ZSTD_cParam_withinBounds(ZSTD_cParameter cParam,int value)551*01826a49SYabin Cui MEM_STATIC int ZSTD_cParam_withinBounds(ZSTD_cParameter cParam, int value)
552*01826a49SYabin Cui {
553*01826a49SYabin Cui     ZSTD_bounds const bounds = ZSTD_cParam_getBounds(cParam);
554*01826a49SYabin Cui     if (ZSTD_isError(bounds.error)) return 0;
555*01826a49SYabin Cui     if (value < bounds.lowerBound) return 0;
556*01826a49SYabin Cui     if (value > bounds.upperBound) return 0;
557*01826a49SYabin Cui     return 1;
558*01826a49SYabin Cui }
559*01826a49SYabin Cui 
560*01826a49SYabin Cui /* ZSTD_noCompressBlock() :
561*01826a49SYabin Cui  * Writes uncompressed block to dst buffer from given src.
562*01826a49SYabin Cui  * Returns the size of the block */
563*01826a49SYabin Cui MEM_STATIC size_t
ZSTD_noCompressBlock(void * dst,size_t dstCapacity,const void * src,size_t srcSize,U32 lastBlock)564*01826a49SYabin Cui ZSTD_noCompressBlock(void* dst, size_t dstCapacity, const void* src, size_t srcSize, U32 lastBlock)
565*01826a49SYabin Cui {
566*01826a49SYabin Cui     U32 const cBlockHeader24 = lastBlock + (((U32)bt_raw)<<1) + (U32)(srcSize << 3);
567*01826a49SYabin Cui     DEBUGLOG(5, "ZSTD_noCompressBlock (srcSize=%zu, dstCapacity=%zu)", srcSize, dstCapacity);
568*01826a49SYabin Cui     RETURN_ERROR_IF(srcSize + ZSTD_blockHeaderSize > dstCapacity,
569*01826a49SYabin Cui                     dstSize_tooSmall, "dst buf too small for uncompressed block");
570*01826a49SYabin Cui     MEM_writeLE24(dst, cBlockHeader24);
571*01826a49SYabin Cui     ZSTD_memcpy((BYTE*)dst + ZSTD_blockHeaderSize, src, srcSize);
572*01826a49SYabin Cui     return ZSTD_blockHeaderSize + srcSize;
573*01826a49SYabin Cui }
574*01826a49SYabin Cui 
575*01826a49SYabin Cui MEM_STATIC size_t
ZSTD_rleCompressBlock(void * dst,size_t dstCapacity,BYTE src,size_t srcSize,U32 lastBlock)576*01826a49SYabin Cui ZSTD_rleCompressBlock(void* dst, size_t dstCapacity, BYTE src, size_t srcSize, U32 lastBlock)
577*01826a49SYabin Cui {
578*01826a49SYabin Cui     BYTE* const op = (BYTE*)dst;
579*01826a49SYabin Cui     U32 const cBlockHeader = lastBlock + (((U32)bt_rle)<<1) + (U32)(srcSize << 3);
580*01826a49SYabin Cui     RETURN_ERROR_IF(dstCapacity < 4, dstSize_tooSmall, "");
581*01826a49SYabin Cui     MEM_writeLE24(op, cBlockHeader);
582*01826a49SYabin Cui     op[3] = src;
583*01826a49SYabin Cui     return 4;
584*01826a49SYabin Cui }
585*01826a49SYabin Cui 
586*01826a49SYabin Cui 
587*01826a49SYabin Cui /* ZSTD_minGain() :
588*01826a49SYabin Cui  * minimum compression required
589*01826a49SYabin Cui  * to generate a compress block or a compressed literals section.
590*01826a49SYabin Cui  * note : use same formula for both situations */
ZSTD_minGain(size_t srcSize,ZSTD_strategy strat)591*01826a49SYabin Cui MEM_STATIC size_t ZSTD_minGain(size_t srcSize, ZSTD_strategy strat)
592*01826a49SYabin Cui {
593*01826a49SYabin Cui     U32 const minlog = (strat>=ZSTD_btultra) ? (U32)(strat) - 1 : 6;
594*01826a49SYabin Cui     ZSTD_STATIC_ASSERT(ZSTD_btultra == 8);
595*01826a49SYabin Cui     assert(ZSTD_cParam_withinBounds(ZSTD_c_strategy, (int)strat));
596*01826a49SYabin Cui     return (srcSize >> minlog) + 2;
597*01826a49SYabin Cui }
598*01826a49SYabin Cui 
ZSTD_literalsCompressionIsDisabled(const ZSTD_CCtx_params * cctxParams)599*01826a49SYabin Cui MEM_STATIC int ZSTD_literalsCompressionIsDisabled(const ZSTD_CCtx_params* cctxParams)
600*01826a49SYabin Cui {
601*01826a49SYabin Cui     switch (cctxParams->literalCompressionMode) {
602*01826a49SYabin Cui     case ZSTD_ps_enable:
603*01826a49SYabin Cui         return 0;
604*01826a49SYabin Cui     case ZSTD_ps_disable:
605*01826a49SYabin Cui         return 1;
606*01826a49SYabin Cui     default:
607*01826a49SYabin Cui         assert(0 /* impossible: pre-validated */);
608*01826a49SYabin Cui         ZSTD_FALLTHROUGH;
609*01826a49SYabin Cui     case ZSTD_ps_auto:
610*01826a49SYabin Cui         return (cctxParams->cParams.strategy == ZSTD_fast) && (cctxParams->cParams.targetLength > 0);
611*01826a49SYabin Cui     }
612*01826a49SYabin Cui }
613*01826a49SYabin Cui 
614*01826a49SYabin Cui /*! ZSTD_safecopyLiterals() :
615*01826a49SYabin Cui  *  memcpy() function that won't read beyond more than WILDCOPY_OVERLENGTH bytes past ilimit_w.
616*01826a49SYabin Cui  *  Only called when the sequence ends past ilimit_w, so it only needs to be optimized for single
617*01826a49SYabin Cui  *  large copies.
618*01826a49SYabin Cui  */
619*01826a49SYabin Cui static void
ZSTD_safecopyLiterals(BYTE * op,BYTE const * ip,BYTE const * const iend,BYTE const * ilimit_w)620*01826a49SYabin Cui ZSTD_safecopyLiterals(BYTE* op, BYTE const* ip, BYTE const* const iend, BYTE const* ilimit_w)
621*01826a49SYabin Cui {
622*01826a49SYabin Cui     assert(iend > ilimit_w);
623*01826a49SYabin Cui     if (ip <= ilimit_w) {
624*01826a49SYabin Cui         ZSTD_wildcopy(op, ip, ilimit_w - ip, ZSTD_no_overlap);
625*01826a49SYabin Cui         op += ilimit_w - ip;
626*01826a49SYabin Cui         ip = ilimit_w;
627*01826a49SYabin Cui     }
628*01826a49SYabin Cui     while (ip < iend) *op++ = *ip++;
629*01826a49SYabin Cui }
630*01826a49SYabin Cui 
631*01826a49SYabin Cui 
632*01826a49SYabin Cui #define REPCODE1_TO_OFFBASE REPCODE_TO_OFFBASE(1)
633*01826a49SYabin Cui #define REPCODE2_TO_OFFBASE REPCODE_TO_OFFBASE(2)
634*01826a49SYabin Cui #define REPCODE3_TO_OFFBASE REPCODE_TO_OFFBASE(3)
635*01826a49SYabin Cui #define REPCODE_TO_OFFBASE(r) (assert((r)>=1), assert((r)<=ZSTD_REP_NUM), (r)) /* accepts IDs 1,2,3 */
636*01826a49SYabin Cui #define OFFSET_TO_OFFBASE(o)  (assert((o)>0), o + ZSTD_REP_NUM)
637*01826a49SYabin Cui #define OFFBASE_IS_OFFSET(o)  ((o) > ZSTD_REP_NUM)
638*01826a49SYabin Cui #define OFFBASE_IS_REPCODE(o) ( 1 <= (o) && (o) <= ZSTD_REP_NUM)
639*01826a49SYabin Cui #define OFFBASE_TO_OFFSET(o)  (assert(OFFBASE_IS_OFFSET(o)), (o) - ZSTD_REP_NUM)
640*01826a49SYabin Cui #define OFFBASE_TO_REPCODE(o) (assert(OFFBASE_IS_REPCODE(o)), (o))  /* returns ID 1,2,3 */
641*01826a49SYabin Cui 
642*01826a49SYabin Cui /*! ZSTD_storeSeq() :
643*01826a49SYabin Cui  *  Store a sequence (litlen, litPtr, offBase and matchLength) into seqStore_t.
644*01826a49SYabin Cui  *  @offBase : Users should employ macros REPCODE_TO_OFFBASE() and OFFSET_TO_OFFBASE().
645*01826a49SYabin Cui  *  @matchLength : must be >= MINMATCH
646*01826a49SYabin Cui  *  Allowed to over-read literals up to litLimit.
647*01826a49SYabin Cui */
648*01826a49SYabin Cui HINT_INLINE UNUSED_ATTR void
ZSTD_storeSeq(seqStore_t * seqStorePtr,size_t litLength,const BYTE * literals,const BYTE * litLimit,U32 offBase,size_t matchLength)649*01826a49SYabin Cui ZSTD_storeSeq(seqStore_t* seqStorePtr,
650*01826a49SYabin Cui               size_t litLength, const BYTE* literals, const BYTE* litLimit,
651*01826a49SYabin Cui               U32 offBase,
652*01826a49SYabin Cui               size_t matchLength)
653*01826a49SYabin Cui {
654*01826a49SYabin Cui     BYTE const* const litLimit_w = litLimit - WILDCOPY_OVERLENGTH;
655*01826a49SYabin Cui     BYTE const* const litEnd = literals + litLength;
656*01826a49SYabin Cui #if defined(DEBUGLEVEL) && (DEBUGLEVEL >= 6)
657*01826a49SYabin Cui     static const BYTE* g_start = NULL;
658*01826a49SYabin Cui     if (g_start==NULL) g_start = (const BYTE*)literals;  /* note : index only works for compression within a single segment */
659*01826a49SYabin Cui     {   U32 const pos = (U32)((const BYTE*)literals - g_start);
660*01826a49SYabin Cui         DEBUGLOG(6, "Cpos%7u :%3u literals, match%4u bytes at offBase%7u",
661*01826a49SYabin Cui                pos, (U32)litLength, (U32)matchLength, (U32)offBase);
662*01826a49SYabin Cui     }
663*01826a49SYabin Cui #endif
664*01826a49SYabin Cui     assert((size_t)(seqStorePtr->sequences - seqStorePtr->sequencesStart) < seqStorePtr->maxNbSeq);
665*01826a49SYabin Cui     /* copy Literals */
666*01826a49SYabin Cui     assert(seqStorePtr->maxNbLit <= 128 KB);
667*01826a49SYabin Cui     assert(seqStorePtr->lit + litLength <= seqStorePtr->litStart + seqStorePtr->maxNbLit);
668*01826a49SYabin Cui     assert(literals + litLength <= litLimit);
669*01826a49SYabin Cui     if (litEnd <= litLimit_w) {
670*01826a49SYabin Cui         /* Common case we can use wildcopy.
671*01826a49SYabin Cui          * First copy 16 bytes, because literals are likely short.
672*01826a49SYabin Cui          */
673*01826a49SYabin Cui         ZSTD_STATIC_ASSERT(WILDCOPY_OVERLENGTH >= 16);
674*01826a49SYabin Cui         ZSTD_copy16(seqStorePtr->lit, literals);
675*01826a49SYabin Cui         if (litLength > 16) {
676*01826a49SYabin Cui             ZSTD_wildcopy(seqStorePtr->lit+16, literals+16, (ptrdiff_t)litLength-16, ZSTD_no_overlap);
677*01826a49SYabin Cui         }
678*01826a49SYabin Cui     } else {
679*01826a49SYabin Cui         ZSTD_safecopyLiterals(seqStorePtr->lit, literals, litEnd, litLimit_w);
680*01826a49SYabin Cui     }
681*01826a49SYabin Cui     seqStorePtr->lit += litLength;
682*01826a49SYabin Cui 
683*01826a49SYabin Cui     /* literal Length */
684*01826a49SYabin Cui     if (litLength>0xFFFF) {
685*01826a49SYabin Cui         assert(seqStorePtr->longLengthType == ZSTD_llt_none); /* there can only be a single long length */
686*01826a49SYabin Cui         seqStorePtr->longLengthType = ZSTD_llt_literalLength;
687*01826a49SYabin Cui         seqStorePtr->longLengthPos = (U32)(seqStorePtr->sequences - seqStorePtr->sequencesStart);
688*01826a49SYabin Cui     }
689*01826a49SYabin Cui     seqStorePtr->sequences[0].litLength = (U16)litLength;
690*01826a49SYabin Cui 
691*01826a49SYabin Cui     /* match offset */
692*01826a49SYabin Cui     seqStorePtr->sequences[0].offBase = offBase;
693*01826a49SYabin Cui 
694*01826a49SYabin Cui     /* match Length */
695*01826a49SYabin Cui     assert(matchLength >= MINMATCH);
696*01826a49SYabin Cui     {   size_t const mlBase = matchLength - MINMATCH;
697*01826a49SYabin Cui         if (mlBase>0xFFFF) {
698*01826a49SYabin Cui             assert(seqStorePtr->longLengthType == ZSTD_llt_none); /* there can only be a single long length */
699*01826a49SYabin Cui             seqStorePtr->longLengthType = ZSTD_llt_matchLength;
700*01826a49SYabin Cui             seqStorePtr->longLengthPos = (U32)(seqStorePtr->sequences - seqStorePtr->sequencesStart);
701*01826a49SYabin Cui         }
702*01826a49SYabin Cui         seqStorePtr->sequences[0].mlBase = (U16)mlBase;
703*01826a49SYabin Cui     }
704*01826a49SYabin Cui 
705*01826a49SYabin Cui     seqStorePtr->sequences++;
706*01826a49SYabin Cui }
707*01826a49SYabin Cui 
708*01826a49SYabin Cui /* ZSTD_updateRep() :
709*01826a49SYabin Cui  * updates in-place @rep (array of repeat offsets)
710*01826a49SYabin Cui  * @offBase : sum-type, using numeric representation of ZSTD_storeSeq()
711*01826a49SYabin Cui  */
712*01826a49SYabin Cui MEM_STATIC void
ZSTD_updateRep(U32 rep[ZSTD_REP_NUM],U32 const offBase,U32 const ll0)713*01826a49SYabin Cui ZSTD_updateRep(U32 rep[ZSTD_REP_NUM], U32 const offBase, U32 const ll0)
714*01826a49SYabin Cui {
715*01826a49SYabin Cui     if (OFFBASE_IS_OFFSET(offBase)) {  /* full offset */
716*01826a49SYabin Cui         rep[2] = rep[1];
717*01826a49SYabin Cui         rep[1] = rep[0];
718*01826a49SYabin Cui         rep[0] = OFFBASE_TO_OFFSET(offBase);
719*01826a49SYabin Cui     } else {   /* repcode */
720*01826a49SYabin Cui         U32 const repCode = OFFBASE_TO_REPCODE(offBase) - 1 + ll0;
721*01826a49SYabin Cui         if (repCode > 0) {  /* note : if repCode==0, no change */
722*01826a49SYabin Cui             U32 const currentOffset = (repCode==ZSTD_REP_NUM) ? (rep[0] - 1) : rep[repCode];
723*01826a49SYabin Cui             rep[2] = (repCode >= 2) ? rep[1] : rep[2];
724*01826a49SYabin Cui             rep[1] = rep[0];
725*01826a49SYabin Cui             rep[0] = currentOffset;
726*01826a49SYabin Cui         } else {   /* repCode == 0 */
727*01826a49SYabin Cui             /* nothing to do */
728*01826a49SYabin Cui         }
729*01826a49SYabin Cui     }
730*01826a49SYabin Cui }
731*01826a49SYabin Cui 
732*01826a49SYabin Cui typedef struct repcodes_s {
733*01826a49SYabin Cui     U32 rep[3];
734*01826a49SYabin Cui } repcodes_t;
735*01826a49SYabin Cui 
736*01826a49SYabin Cui MEM_STATIC repcodes_t
ZSTD_newRep(U32 const rep[ZSTD_REP_NUM],U32 const offBase,U32 const ll0)737*01826a49SYabin Cui ZSTD_newRep(U32 const rep[ZSTD_REP_NUM], U32 const offBase, U32 const ll0)
738*01826a49SYabin Cui {
739*01826a49SYabin Cui     repcodes_t newReps;
740*01826a49SYabin Cui     ZSTD_memcpy(&newReps, rep, sizeof(newReps));
741*01826a49SYabin Cui     ZSTD_updateRep(newReps.rep, offBase, ll0);
742*01826a49SYabin Cui     return newReps;
743*01826a49SYabin Cui }
744*01826a49SYabin Cui 
745*01826a49SYabin Cui 
746*01826a49SYabin Cui /*-*************************************
747*01826a49SYabin Cui *  Match length counter
748*01826a49SYabin Cui ***************************************/
ZSTD_count(const BYTE * pIn,const BYTE * pMatch,const BYTE * const pInLimit)749*01826a49SYabin Cui MEM_STATIC size_t ZSTD_count(const BYTE* pIn, const BYTE* pMatch, const BYTE* const pInLimit)
750*01826a49SYabin Cui {
751*01826a49SYabin Cui     const BYTE* const pStart = pIn;
752*01826a49SYabin Cui     const BYTE* const pInLoopLimit = pInLimit - (sizeof(size_t)-1);
753*01826a49SYabin Cui 
754*01826a49SYabin Cui     if (pIn < pInLoopLimit) {
755*01826a49SYabin Cui         { size_t const diff = MEM_readST(pMatch) ^ MEM_readST(pIn);
756*01826a49SYabin Cui           if (diff) return ZSTD_NbCommonBytes(diff); }
757*01826a49SYabin Cui         pIn+=sizeof(size_t); pMatch+=sizeof(size_t);
758*01826a49SYabin Cui         while (pIn < pInLoopLimit) {
759*01826a49SYabin Cui             size_t const diff = MEM_readST(pMatch) ^ MEM_readST(pIn);
760*01826a49SYabin Cui             if (!diff) { pIn+=sizeof(size_t); pMatch+=sizeof(size_t); continue; }
761*01826a49SYabin Cui             pIn += ZSTD_NbCommonBytes(diff);
762*01826a49SYabin Cui             return (size_t)(pIn - pStart);
763*01826a49SYabin Cui     }   }
764*01826a49SYabin Cui     if (MEM_64bits() && (pIn<(pInLimit-3)) && (MEM_read32(pMatch) == MEM_read32(pIn))) { pIn+=4; pMatch+=4; }
765*01826a49SYabin Cui     if ((pIn<(pInLimit-1)) && (MEM_read16(pMatch) == MEM_read16(pIn))) { pIn+=2; pMatch+=2; }
766*01826a49SYabin Cui     if ((pIn<pInLimit) && (*pMatch == *pIn)) pIn++;
767*01826a49SYabin Cui     return (size_t)(pIn - pStart);
768*01826a49SYabin Cui }
769*01826a49SYabin Cui 
770*01826a49SYabin Cui /** ZSTD_count_2segments() :
771*01826a49SYabin Cui  *  can count match length with `ip` & `match` in 2 different segments.
772*01826a49SYabin Cui  *  convention : on reaching mEnd, match count continue starting from iStart
773*01826a49SYabin Cui  */
774*01826a49SYabin Cui MEM_STATIC size_t
ZSTD_count_2segments(const BYTE * ip,const BYTE * match,const BYTE * iEnd,const BYTE * mEnd,const BYTE * iStart)775*01826a49SYabin Cui ZSTD_count_2segments(const BYTE* ip, const BYTE* match,
776*01826a49SYabin Cui                      const BYTE* iEnd, const BYTE* mEnd, const BYTE* iStart)
777*01826a49SYabin Cui {
778*01826a49SYabin Cui     const BYTE* const vEnd = MIN( ip + (mEnd - match), iEnd);
779*01826a49SYabin Cui     size_t const matchLength = ZSTD_count(ip, match, vEnd);
780*01826a49SYabin Cui     if (match + matchLength != mEnd) return matchLength;
781*01826a49SYabin Cui     DEBUGLOG(7, "ZSTD_count_2segments: found a 2-parts match (current length==%zu)", matchLength);
782*01826a49SYabin Cui     DEBUGLOG(7, "distance from match beginning to end dictionary = %zi", mEnd - match);
783*01826a49SYabin Cui     DEBUGLOG(7, "distance from current pos to end buffer = %zi", iEnd - ip);
784*01826a49SYabin Cui     DEBUGLOG(7, "next byte : ip==%02X, istart==%02X", ip[matchLength], *iStart);
785*01826a49SYabin Cui     DEBUGLOG(7, "final match length = %zu", matchLength + ZSTD_count(ip+matchLength, iStart, iEnd));
786*01826a49SYabin Cui     return matchLength + ZSTD_count(ip+matchLength, iStart, iEnd);
787*01826a49SYabin Cui }
788*01826a49SYabin Cui 
789*01826a49SYabin Cui 
790*01826a49SYabin Cui /*-*************************************
791*01826a49SYabin Cui  *  Hashes
792*01826a49SYabin Cui  ***************************************/
793*01826a49SYabin Cui static const U32 prime3bytes = 506832829U;
ZSTD_hash3(U32 u,U32 h,U32 s)794*01826a49SYabin Cui static U32    ZSTD_hash3(U32 u, U32 h, U32 s) { assert(h <= 32); return (((u << (32-24)) * prime3bytes) ^ s)  >> (32-h) ; }
ZSTD_hash3Ptr(const void * ptr,U32 h)795*01826a49SYabin Cui MEM_STATIC size_t ZSTD_hash3Ptr(const void* ptr, U32 h) { return ZSTD_hash3(MEM_readLE32(ptr), h, 0); } /* only in zstd_opt.h */
ZSTD_hash3PtrS(const void * ptr,U32 h,U32 s)796*01826a49SYabin Cui MEM_STATIC size_t ZSTD_hash3PtrS(const void* ptr, U32 h, U32 s) { return ZSTD_hash3(MEM_readLE32(ptr), h, s); }
797*01826a49SYabin Cui 
798*01826a49SYabin Cui static const U32 prime4bytes = 2654435761U;
ZSTD_hash4(U32 u,U32 h,U32 s)799*01826a49SYabin Cui static U32    ZSTD_hash4(U32 u, U32 h, U32 s) { assert(h <= 32); return ((u * prime4bytes) ^ s) >> (32-h) ; }
ZSTD_hash4Ptr(const void * ptr,U32 h)800*01826a49SYabin Cui static size_t ZSTD_hash4Ptr(const void* ptr, U32 h) { return ZSTD_hash4(MEM_readLE32(ptr), h, 0); }
ZSTD_hash4PtrS(const void * ptr,U32 h,U32 s)801*01826a49SYabin Cui static size_t ZSTD_hash4PtrS(const void* ptr, U32 h, U32 s) { return ZSTD_hash4(MEM_readLE32(ptr), h, s); }
802*01826a49SYabin Cui 
803*01826a49SYabin Cui static const U64 prime5bytes = 889523592379ULL;
ZSTD_hash5(U64 u,U32 h,U64 s)804*01826a49SYabin Cui static size_t ZSTD_hash5(U64 u, U32 h, U64 s) { assert(h <= 64); return (size_t)((((u  << (64-40)) * prime5bytes) ^ s) >> (64-h)) ; }
ZSTD_hash5Ptr(const void * p,U32 h)805*01826a49SYabin Cui static size_t ZSTD_hash5Ptr(const void* p, U32 h) { return ZSTD_hash5(MEM_readLE64(p), h, 0); }
ZSTD_hash5PtrS(const void * p,U32 h,U64 s)806*01826a49SYabin Cui static size_t ZSTD_hash5PtrS(const void* p, U32 h, U64 s) { return ZSTD_hash5(MEM_readLE64(p), h, s); }
807*01826a49SYabin Cui 
808*01826a49SYabin Cui static const U64 prime6bytes = 227718039650203ULL;
ZSTD_hash6(U64 u,U32 h,U64 s)809*01826a49SYabin Cui static size_t ZSTD_hash6(U64 u, U32 h, U64 s) { assert(h <= 64); return (size_t)((((u  << (64-48)) * prime6bytes) ^ s) >> (64-h)) ; }
ZSTD_hash6Ptr(const void * p,U32 h)810*01826a49SYabin Cui static size_t ZSTD_hash6Ptr(const void* p, U32 h) { return ZSTD_hash6(MEM_readLE64(p), h, 0); }
ZSTD_hash6PtrS(const void * p,U32 h,U64 s)811*01826a49SYabin Cui static size_t ZSTD_hash6PtrS(const void* p, U32 h, U64 s) { return ZSTD_hash6(MEM_readLE64(p), h, s); }
812*01826a49SYabin Cui 
813*01826a49SYabin Cui static const U64 prime7bytes = 58295818150454627ULL;
ZSTD_hash7(U64 u,U32 h,U64 s)814*01826a49SYabin Cui static size_t ZSTD_hash7(U64 u, U32 h, U64 s) { assert(h <= 64); return (size_t)((((u  << (64-56)) * prime7bytes) ^ s) >> (64-h)) ; }
ZSTD_hash7Ptr(const void * p,U32 h)815*01826a49SYabin Cui static size_t ZSTD_hash7Ptr(const void* p, U32 h) { return ZSTD_hash7(MEM_readLE64(p), h, 0); }
ZSTD_hash7PtrS(const void * p,U32 h,U64 s)816*01826a49SYabin Cui static size_t ZSTD_hash7PtrS(const void* p, U32 h, U64 s) { return ZSTD_hash7(MEM_readLE64(p), h, s); }
817*01826a49SYabin Cui 
818*01826a49SYabin Cui static const U64 prime8bytes = 0xCF1BBCDCB7A56463ULL;
ZSTD_hash8(U64 u,U32 h,U64 s)819*01826a49SYabin Cui static size_t ZSTD_hash8(U64 u, U32 h, U64 s) { assert(h <= 64); return (size_t)((((u) * prime8bytes)  ^ s) >> (64-h)) ; }
ZSTD_hash8Ptr(const void * p,U32 h)820*01826a49SYabin Cui static size_t ZSTD_hash8Ptr(const void* p, U32 h) { return ZSTD_hash8(MEM_readLE64(p), h, 0); }
ZSTD_hash8PtrS(const void * p,U32 h,U64 s)821*01826a49SYabin Cui static size_t ZSTD_hash8PtrS(const void* p, U32 h, U64 s) { return ZSTD_hash8(MEM_readLE64(p), h, s); }
822*01826a49SYabin Cui 
823*01826a49SYabin Cui 
824*01826a49SYabin Cui MEM_STATIC FORCE_INLINE_ATTR
ZSTD_hashPtr(const void * p,U32 hBits,U32 mls)825*01826a49SYabin Cui size_t ZSTD_hashPtr(const void* p, U32 hBits, U32 mls)
826*01826a49SYabin Cui {
827*01826a49SYabin Cui     /* Although some of these hashes do support hBits up to 64, some do not.
828*01826a49SYabin Cui      * To be on the safe side, always avoid hBits > 32. */
829*01826a49SYabin Cui     assert(hBits <= 32);
830*01826a49SYabin Cui 
831*01826a49SYabin Cui     switch(mls)
832*01826a49SYabin Cui     {
833*01826a49SYabin Cui     default:
834*01826a49SYabin Cui     case 4: return ZSTD_hash4Ptr(p, hBits);
835*01826a49SYabin Cui     case 5: return ZSTD_hash5Ptr(p, hBits);
836*01826a49SYabin Cui     case 6: return ZSTD_hash6Ptr(p, hBits);
837*01826a49SYabin Cui     case 7: return ZSTD_hash7Ptr(p, hBits);
838*01826a49SYabin Cui     case 8: return ZSTD_hash8Ptr(p, hBits);
839*01826a49SYabin Cui     }
840*01826a49SYabin Cui }
841*01826a49SYabin Cui 
842*01826a49SYabin Cui MEM_STATIC FORCE_INLINE_ATTR
ZSTD_hashPtrSalted(const void * p,U32 hBits,U32 mls,const U64 hashSalt)843*01826a49SYabin Cui size_t ZSTD_hashPtrSalted(const void* p, U32 hBits, U32 mls, const U64 hashSalt) {
844*01826a49SYabin Cui     /* Although some of these hashes do support hBits up to 64, some do not.
845*01826a49SYabin Cui      * To be on the safe side, always avoid hBits > 32. */
846*01826a49SYabin Cui     assert(hBits <= 32);
847*01826a49SYabin Cui 
848*01826a49SYabin Cui     switch(mls)
849*01826a49SYabin Cui     {
850*01826a49SYabin Cui         default:
851*01826a49SYabin Cui         case 4: return ZSTD_hash4PtrS(p, hBits, (U32)hashSalt);
852*01826a49SYabin Cui         case 5: return ZSTD_hash5PtrS(p, hBits, hashSalt);
853*01826a49SYabin Cui         case 6: return ZSTD_hash6PtrS(p, hBits, hashSalt);
854*01826a49SYabin Cui         case 7: return ZSTD_hash7PtrS(p, hBits, hashSalt);
855*01826a49SYabin Cui         case 8: return ZSTD_hash8PtrS(p, hBits, hashSalt);
856*01826a49SYabin Cui     }
857*01826a49SYabin Cui }
858*01826a49SYabin Cui 
859*01826a49SYabin Cui 
860*01826a49SYabin Cui /** ZSTD_ipow() :
861*01826a49SYabin Cui  * Return base^exponent.
862*01826a49SYabin Cui  */
ZSTD_ipow(U64 base,U64 exponent)863*01826a49SYabin Cui static U64 ZSTD_ipow(U64 base, U64 exponent)
864*01826a49SYabin Cui {
865*01826a49SYabin Cui     U64 power = 1;
866*01826a49SYabin Cui     while (exponent) {
867*01826a49SYabin Cui       if (exponent & 1) power *= base;
868*01826a49SYabin Cui       exponent >>= 1;
869*01826a49SYabin Cui       base *= base;
870*01826a49SYabin Cui     }
871*01826a49SYabin Cui     return power;
872*01826a49SYabin Cui }
873*01826a49SYabin Cui 
874*01826a49SYabin Cui #define ZSTD_ROLL_HASH_CHAR_OFFSET 10
875*01826a49SYabin Cui 
876*01826a49SYabin Cui /** ZSTD_rollingHash_append() :
877*01826a49SYabin Cui  * Add the buffer to the hash value.
878*01826a49SYabin Cui  */
ZSTD_rollingHash_append(U64 hash,void const * buf,size_t size)879*01826a49SYabin Cui static U64 ZSTD_rollingHash_append(U64 hash, void const* buf, size_t size)
880*01826a49SYabin Cui {
881*01826a49SYabin Cui     BYTE const* istart = (BYTE const*)buf;
882*01826a49SYabin Cui     size_t pos;
883*01826a49SYabin Cui     for (pos = 0; pos < size; ++pos) {
884*01826a49SYabin Cui         hash *= prime8bytes;
885*01826a49SYabin Cui         hash += istart[pos] + ZSTD_ROLL_HASH_CHAR_OFFSET;
886*01826a49SYabin Cui     }
887*01826a49SYabin Cui     return hash;
888*01826a49SYabin Cui }
889*01826a49SYabin Cui 
890*01826a49SYabin Cui /** ZSTD_rollingHash_compute() :
891*01826a49SYabin Cui  * Compute the rolling hash value of the buffer.
892*01826a49SYabin Cui  */
ZSTD_rollingHash_compute(void const * buf,size_t size)893*01826a49SYabin Cui MEM_STATIC U64 ZSTD_rollingHash_compute(void const* buf, size_t size)
894*01826a49SYabin Cui {
895*01826a49SYabin Cui     return ZSTD_rollingHash_append(0, buf, size);
896*01826a49SYabin Cui }
897*01826a49SYabin Cui 
898*01826a49SYabin Cui /** ZSTD_rollingHash_primePower() :
899*01826a49SYabin Cui  * Compute the primePower to be passed to ZSTD_rollingHash_rotate() for a hash
900*01826a49SYabin Cui  * over a window of length bytes.
901*01826a49SYabin Cui  */
ZSTD_rollingHash_primePower(U32 length)902*01826a49SYabin Cui MEM_STATIC U64 ZSTD_rollingHash_primePower(U32 length)
903*01826a49SYabin Cui {
904*01826a49SYabin Cui     return ZSTD_ipow(prime8bytes, length - 1);
905*01826a49SYabin Cui }
906*01826a49SYabin Cui 
907*01826a49SYabin Cui /** ZSTD_rollingHash_rotate() :
908*01826a49SYabin Cui  * Rotate the rolling hash by one byte.
909*01826a49SYabin Cui  */
ZSTD_rollingHash_rotate(U64 hash,BYTE toRemove,BYTE toAdd,U64 primePower)910*01826a49SYabin Cui MEM_STATIC U64 ZSTD_rollingHash_rotate(U64 hash, BYTE toRemove, BYTE toAdd, U64 primePower)
911*01826a49SYabin Cui {
912*01826a49SYabin Cui     hash -= (toRemove + ZSTD_ROLL_HASH_CHAR_OFFSET) * primePower;
913*01826a49SYabin Cui     hash *= prime8bytes;
914*01826a49SYabin Cui     hash += toAdd + ZSTD_ROLL_HASH_CHAR_OFFSET;
915*01826a49SYabin Cui     return hash;
916*01826a49SYabin Cui }
917*01826a49SYabin Cui 
918*01826a49SYabin Cui /*-*************************************
919*01826a49SYabin Cui *  Round buffer management
920*01826a49SYabin Cui ***************************************/
921*01826a49SYabin Cui #if (ZSTD_WINDOWLOG_MAX_64 > 31)
922*01826a49SYabin Cui # error "ZSTD_WINDOWLOG_MAX is too large : would overflow ZSTD_CURRENT_MAX"
923*01826a49SYabin Cui #endif
924*01826a49SYabin Cui /* Max current allowed */
925*01826a49SYabin Cui #define ZSTD_CURRENT_MAX ((3U << 29) + (1U << ZSTD_WINDOWLOG_MAX))
926*01826a49SYabin Cui /* Maximum chunk size before overflow correction needs to be called again */
927*01826a49SYabin Cui #define ZSTD_CHUNKSIZE_MAX                                                     \
928*01826a49SYabin Cui     ( ((U32)-1)                  /* Maximum ending current index */            \
929*01826a49SYabin Cui     - ZSTD_CURRENT_MAX)          /* Maximum beginning lowLimit */
930*01826a49SYabin Cui 
931*01826a49SYabin Cui /**
932*01826a49SYabin Cui  * ZSTD_window_clear():
933*01826a49SYabin Cui  * Clears the window containing the history by simply setting it to empty.
934*01826a49SYabin Cui  */
ZSTD_window_clear(ZSTD_window_t * window)935*01826a49SYabin Cui MEM_STATIC void ZSTD_window_clear(ZSTD_window_t* window)
936*01826a49SYabin Cui {
937*01826a49SYabin Cui     size_t const endT = (size_t)(window->nextSrc - window->base);
938*01826a49SYabin Cui     U32 const end = (U32)endT;
939*01826a49SYabin Cui 
940*01826a49SYabin Cui     window->lowLimit = end;
941*01826a49SYabin Cui     window->dictLimit = end;
942*01826a49SYabin Cui }
943*01826a49SYabin Cui 
ZSTD_window_isEmpty(ZSTD_window_t const window)944*01826a49SYabin Cui MEM_STATIC U32 ZSTD_window_isEmpty(ZSTD_window_t const window)
945*01826a49SYabin Cui {
946*01826a49SYabin Cui     return window.dictLimit == ZSTD_WINDOW_START_INDEX &&
947*01826a49SYabin Cui            window.lowLimit == ZSTD_WINDOW_START_INDEX &&
948*01826a49SYabin Cui            (window.nextSrc - window.base) == ZSTD_WINDOW_START_INDEX;
949*01826a49SYabin Cui }
950*01826a49SYabin Cui 
951*01826a49SYabin Cui /**
952*01826a49SYabin Cui  * ZSTD_window_hasExtDict():
953*01826a49SYabin Cui  * Returns non-zero if the window has a non-empty extDict.
954*01826a49SYabin Cui  */
ZSTD_window_hasExtDict(ZSTD_window_t const window)955*01826a49SYabin Cui MEM_STATIC U32 ZSTD_window_hasExtDict(ZSTD_window_t const window)
956*01826a49SYabin Cui {
957*01826a49SYabin Cui     return window.lowLimit < window.dictLimit;
958*01826a49SYabin Cui }
959*01826a49SYabin Cui 
960*01826a49SYabin Cui /**
961*01826a49SYabin Cui  * ZSTD_matchState_dictMode():
962*01826a49SYabin Cui  * Inspects the provided matchState and figures out what dictMode should be
963*01826a49SYabin Cui  * passed to the compressor.
964*01826a49SYabin Cui  */
ZSTD_matchState_dictMode(const ZSTD_matchState_t * ms)965*01826a49SYabin Cui MEM_STATIC ZSTD_dictMode_e ZSTD_matchState_dictMode(const ZSTD_matchState_t *ms)
966*01826a49SYabin Cui {
967*01826a49SYabin Cui     return ZSTD_window_hasExtDict(ms->window) ?
968*01826a49SYabin Cui         ZSTD_extDict :
969*01826a49SYabin Cui         ms->dictMatchState != NULL ?
970*01826a49SYabin Cui             (ms->dictMatchState->dedicatedDictSearch ? ZSTD_dedicatedDictSearch : ZSTD_dictMatchState) :
971*01826a49SYabin Cui             ZSTD_noDict;
972*01826a49SYabin Cui }
973*01826a49SYabin Cui 
974*01826a49SYabin Cui /* Defining this macro to non-zero tells zstd to run the overflow correction
975*01826a49SYabin Cui  * code much more frequently. This is very inefficient, and should only be
976*01826a49SYabin Cui  * used for tests and fuzzers.
977*01826a49SYabin Cui  */
978*01826a49SYabin Cui #ifndef ZSTD_WINDOW_OVERFLOW_CORRECT_FREQUENTLY
979*01826a49SYabin Cui #  ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
980*01826a49SYabin Cui #    define ZSTD_WINDOW_OVERFLOW_CORRECT_FREQUENTLY 1
981*01826a49SYabin Cui #  else
982*01826a49SYabin Cui #    define ZSTD_WINDOW_OVERFLOW_CORRECT_FREQUENTLY 0
983*01826a49SYabin Cui #  endif
984*01826a49SYabin Cui #endif
985*01826a49SYabin Cui 
986*01826a49SYabin Cui /**
987*01826a49SYabin Cui  * ZSTD_window_canOverflowCorrect():
988*01826a49SYabin Cui  * Returns non-zero if the indices are large enough for overflow correction
989*01826a49SYabin Cui  * to work correctly without impacting compression ratio.
990*01826a49SYabin Cui  */
ZSTD_window_canOverflowCorrect(ZSTD_window_t const window,U32 cycleLog,U32 maxDist,U32 loadedDictEnd,void const * src)991*01826a49SYabin Cui MEM_STATIC U32 ZSTD_window_canOverflowCorrect(ZSTD_window_t const window,
992*01826a49SYabin Cui                                               U32 cycleLog,
993*01826a49SYabin Cui                                               U32 maxDist,
994*01826a49SYabin Cui                                               U32 loadedDictEnd,
995*01826a49SYabin Cui                                               void const* src)
996*01826a49SYabin Cui {
997*01826a49SYabin Cui     U32 const cycleSize = 1u << cycleLog;
998*01826a49SYabin Cui     U32 const curr = (U32)((BYTE const*)src - window.base);
999*01826a49SYabin Cui     U32 const minIndexToOverflowCorrect = cycleSize
1000*01826a49SYabin Cui                                         + MAX(maxDist, cycleSize)
1001*01826a49SYabin Cui                                         + ZSTD_WINDOW_START_INDEX;
1002*01826a49SYabin Cui 
1003*01826a49SYabin Cui     /* Adjust the min index to backoff the overflow correction frequency,
1004*01826a49SYabin Cui      * so we don't waste too much CPU in overflow correction. If this
1005*01826a49SYabin Cui      * computation overflows we don't really care, we just need to make
1006*01826a49SYabin Cui      * sure it is at least minIndexToOverflowCorrect.
1007*01826a49SYabin Cui      */
1008*01826a49SYabin Cui     U32 const adjustment = window.nbOverflowCorrections + 1;
1009*01826a49SYabin Cui     U32 const adjustedIndex = MAX(minIndexToOverflowCorrect * adjustment,
1010*01826a49SYabin Cui                                   minIndexToOverflowCorrect);
1011*01826a49SYabin Cui     U32 const indexLargeEnough = curr > adjustedIndex;
1012*01826a49SYabin Cui 
1013*01826a49SYabin Cui     /* Only overflow correct early if the dictionary is invalidated already,
1014*01826a49SYabin Cui      * so we don't hurt compression ratio.
1015*01826a49SYabin Cui      */
1016*01826a49SYabin Cui     U32 const dictionaryInvalidated = curr > maxDist + loadedDictEnd;
1017*01826a49SYabin Cui 
1018*01826a49SYabin Cui     return indexLargeEnough && dictionaryInvalidated;
1019*01826a49SYabin Cui }
1020*01826a49SYabin Cui 
1021*01826a49SYabin Cui /**
1022*01826a49SYabin Cui  * ZSTD_window_needOverflowCorrection():
1023*01826a49SYabin Cui  * Returns non-zero if the indices are getting too large and need overflow
1024*01826a49SYabin Cui  * protection.
1025*01826a49SYabin Cui  */
ZSTD_window_needOverflowCorrection(ZSTD_window_t const window,U32 cycleLog,U32 maxDist,U32 loadedDictEnd,void const * src,void const * srcEnd)1026*01826a49SYabin Cui MEM_STATIC U32 ZSTD_window_needOverflowCorrection(ZSTD_window_t const window,
1027*01826a49SYabin Cui                                                   U32 cycleLog,
1028*01826a49SYabin Cui                                                   U32 maxDist,
1029*01826a49SYabin Cui                                                   U32 loadedDictEnd,
1030*01826a49SYabin Cui                                                   void const* src,
1031*01826a49SYabin Cui                                                   void const* srcEnd)
1032*01826a49SYabin Cui {
1033*01826a49SYabin Cui     U32 const curr = (U32)((BYTE const*)srcEnd - window.base);
1034*01826a49SYabin Cui     if (ZSTD_WINDOW_OVERFLOW_CORRECT_FREQUENTLY) {
1035*01826a49SYabin Cui         if (ZSTD_window_canOverflowCorrect(window, cycleLog, maxDist, loadedDictEnd, src)) {
1036*01826a49SYabin Cui             return 1;
1037*01826a49SYabin Cui         }
1038*01826a49SYabin Cui     }
1039*01826a49SYabin Cui     return curr > ZSTD_CURRENT_MAX;
1040*01826a49SYabin Cui }
1041*01826a49SYabin Cui 
1042*01826a49SYabin Cui /**
1043*01826a49SYabin Cui  * ZSTD_window_correctOverflow():
1044*01826a49SYabin Cui  * Reduces the indices to protect from index overflow.
1045*01826a49SYabin Cui  * Returns the correction made to the indices, which must be applied to every
1046*01826a49SYabin Cui  * stored index.
1047*01826a49SYabin Cui  *
1048*01826a49SYabin Cui  * The least significant cycleLog bits of the indices must remain the same,
1049*01826a49SYabin Cui  * which may be 0. Every index up to maxDist in the past must be valid.
1050*01826a49SYabin Cui  */
1051*01826a49SYabin Cui MEM_STATIC
1052*01826a49SYabin Cui ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
ZSTD_window_correctOverflow(ZSTD_window_t * window,U32 cycleLog,U32 maxDist,void const * src)1053*01826a49SYabin Cui U32 ZSTD_window_correctOverflow(ZSTD_window_t* window, U32 cycleLog,
1054*01826a49SYabin Cui                                            U32 maxDist, void const* src)
1055*01826a49SYabin Cui {
1056*01826a49SYabin Cui     /* preemptive overflow correction:
1057*01826a49SYabin Cui      * 1. correction is large enough:
1058*01826a49SYabin Cui      *    lowLimit > (3<<29) ==> current > 3<<29 + 1<<windowLog
1059*01826a49SYabin Cui      *    1<<windowLog <= newCurrent < 1<<chainLog + 1<<windowLog
1060*01826a49SYabin Cui      *
1061*01826a49SYabin Cui      *    current - newCurrent
1062*01826a49SYabin Cui      *    > (3<<29 + 1<<windowLog) - (1<<windowLog + 1<<chainLog)
1063*01826a49SYabin Cui      *    > (3<<29) - (1<<chainLog)
1064*01826a49SYabin Cui      *    > (3<<29) - (1<<30)             (NOTE: chainLog <= 30)
1065*01826a49SYabin Cui      *    > 1<<29
1066*01826a49SYabin Cui      *
1067*01826a49SYabin Cui      * 2. (ip+ZSTD_CHUNKSIZE_MAX - cctx->base) doesn't overflow:
1068*01826a49SYabin Cui      *    After correction, current is less than (1<<chainLog + 1<<windowLog).
1069*01826a49SYabin Cui      *    In 64-bit mode we are safe, because we have 64-bit ptrdiff_t.
1070*01826a49SYabin Cui      *    In 32-bit mode we are safe, because (chainLog <= 29), so
1071*01826a49SYabin Cui      *    ip+ZSTD_CHUNKSIZE_MAX - cctx->base < 1<<32.
1072*01826a49SYabin Cui      * 3. (cctx->lowLimit + 1<<windowLog) < 1<<32:
1073*01826a49SYabin Cui      *    windowLog <= 31 ==> 3<<29 + 1<<windowLog < 7<<29 < 1<<32.
1074*01826a49SYabin Cui      */
1075*01826a49SYabin Cui     U32 const cycleSize = 1u << cycleLog;
1076*01826a49SYabin Cui     U32 const cycleMask = cycleSize - 1;
1077*01826a49SYabin Cui     U32 const curr = (U32)((BYTE const*)src - window->base);
1078*01826a49SYabin Cui     U32 const currentCycle = curr & cycleMask;
1079*01826a49SYabin Cui     /* Ensure newCurrent - maxDist >= ZSTD_WINDOW_START_INDEX. */
1080*01826a49SYabin Cui     U32 const currentCycleCorrection = currentCycle < ZSTD_WINDOW_START_INDEX
1081*01826a49SYabin Cui                                      ? MAX(cycleSize, ZSTD_WINDOW_START_INDEX)
1082*01826a49SYabin Cui                                      : 0;
1083*01826a49SYabin Cui     U32 const newCurrent = currentCycle
1084*01826a49SYabin Cui                          + currentCycleCorrection
1085*01826a49SYabin Cui                          + MAX(maxDist, cycleSize);
1086*01826a49SYabin Cui     U32 const correction = curr - newCurrent;
1087*01826a49SYabin Cui     /* maxDist must be a power of two so that:
1088*01826a49SYabin Cui      *   (newCurrent & cycleMask) == (curr & cycleMask)
1089*01826a49SYabin Cui      * This is required to not corrupt the chains / binary tree.
1090*01826a49SYabin Cui      */
1091*01826a49SYabin Cui     assert((maxDist & (maxDist - 1)) == 0);
1092*01826a49SYabin Cui     assert((curr & cycleMask) == (newCurrent & cycleMask));
1093*01826a49SYabin Cui     assert(curr > newCurrent);
1094*01826a49SYabin Cui     if (!ZSTD_WINDOW_OVERFLOW_CORRECT_FREQUENTLY) {
1095*01826a49SYabin Cui         /* Loose bound, should be around 1<<29 (see above) */
1096*01826a49SYabin Cui         assert(correction > 1<<28);
1097*01826a49SYabin Cui     }
1098*01826a49SYabin Cui 
1099*01826a49SYabin Cui     window->base += correction;
1100*01826a49SYabin Cui     window->dictBase += correction;
1101*01826a49SYabin Cui     if (window->lowLimit < correction + ZSTD_WINDOW_START_INDEX) {
1102*01826a49SYabin Cui         window->lowLimit = ZSTD_WINDOW_START_INDEX;
1103*01826a49SYabin Cui     } else {
1104*01826a49SYabin Cui         window->lowLimit -= correction;
1105*01826a49SYabin Cui     }
1106*01826a49SYabin Cui     if (window->dictLimit < correction + ZSTD_WINDOW_START_INDEX) {
1107*01826a49SYabin Cui         window->dictLimit = ZSTD_WINDOW_START_INDEX;
1108*01826a49SYabin Cui     } else {
1109*01826a49SYabin Cui         window->dictLimit -= correction;
1110*01826a49SYabin Cui     }
1111*01826a49SYabin Cui 
1112*01826a49SYabin Cui     /* Ensure we can still reference the full window. */
1113*01826a49SYabin Cui     assert(newCurrent >= maxDist);
1114*01826a49SYabin Cui     assert(newCurrent - maxDist >= ZSTD_WINDOW_START_INDEX);
1115*01826a49SYabin Cui     /* Ensure that lowLimit and dictLimit didn't underflow. */
1116*01826a49SYabin Cui     assert(window->lowLimit <= newCurrent);
1117*01826a49SYabin Cui     assert(window->dictLimit <= newCurrent);
1118*01826a49SYabin Cui 
1119*01826a49SYabin Cui     ++window->nbOverflowCorrections;
1120*01826a49SYabin Cui 
1121*01826a49SYabin Cui     DEBUGLOG(4, "Correction of 0x%x bytes to lowLimit=0x%x", correction,
1122*01826a49SYabin Cui              window->lowLimit);
1123*01826a49SYabin Cui     return correction;
1124*01826a49SYabin Cui }
1125*01826a49SYabin Cui 
1126*01826a49SYabin Cui /**
1127*01826a49SYabin Cui  * ZSTD_window_enforceMaxDist():
1128*01826a49SYabin Cui  * Updates lowLimit so that:
1129*01826a49SYabin Cui  *    (srcEnd - base) - lowLimit == maxDist + loadedDictEnd
1130*01826a49SYabin Cui  *
1131*01826a49SYabin Cui  * It ensures index is valid as long as index >= lowLimit.
1132*01826a49SYabin Cui  * This must be called before a block compression call.
1133*01826a49SYabin Cui  *
1134*01826a49SYabin Cui  * loadedDictEnd is only defined if a dictionary is in use for current compression.
1135*01826a49SYabin Cui  * As the name implies, loadedDictEnd represents the index at end of dictionary.
1136*01826a49SYabin Cui  * The value lies within context's referential, it can be directly compared to blockEndIdx.
1137*01826a49SYabin Cui  *
1138*01826a49SYabin Cui  * If loadedDictEndPtr is NULL, no dictionary is in use, and we use loadedDictEnd == 0.
1139*01826a49SYabin Cui  * If loadedDictEndPtr is not NULL, we set it to zero after updating lowLimit.
1140*01826a49SYabin Cui  * This is because dictionaries are allowed to be referenced fully
1141*01826a49SYabin Cui  * as long as the last byte of the dictionary is in the window.
1142*01826a49SYabin Cui  * Once input has progressed beyond window size, dictionary cannot be referenced anymore.
1143*01826a49SYabin Cui  *
1144*01826a49SYabin Cui  * In normal dict mode, the dictionary lies between lowLimit and dictLimit.
1145*01826a49SYabin Cui  * In dictMatchState mode, lowLimit and dictLimit are the same,
1146*01826a49SYabin Cui  * and the dictionary is below them.
1147*01826a49SYabin Cui  * forceWindow and dictMatchState are therefore incompatible.
1148*01826a49SYabin Cui  */
1149*01826a49SYabin Cui MEM_STATIC void
ZSTD_window_enforceMaxDist(ZSTD_window_t * window,const void * blockEnd,U32 maxDist,U32 * loadedDictEndPtr,const ZSTD_matchState_t ** dictMatchStatePtr)1150*01826a49SYabin Cui ZSTD_window_enforceMaxDist(ZSTD_window_t* window,
1151*01826a49SYabin Cui                      const void* blockEnd,
1152*01826a49SYabin Cui                            U32   maxDist,
1153*01826a49SYabin Cui                            U32*  loadedDictEndPtr,
1154*01826a49SYabin Cui                      const ZSTD_matchState_t** dictMatchStatePtr)
1155*01826a49SYabin Cui {
1156*01826a49SYabin Cui     U32 const blockEndIdx = (U32)((BYTE const*)blockEnd - window->base);
1157*01826a49SYabin Cui     U32 const loadedDictEnd = (loadedDictEndPtr != NULL) ? *loadedDictEndPtr : 0;
1158*01826a49SYabin Cui     DEBUGLOG(5, "ZSTD_window_enforceMaxDist: blockEndIdx=%u, maxDist=%u, loadedDictEnd=%u",
1159*01826a49SYabin Cui                 (unsigned)blockEndIdx, (unsigned)maxDist, (unsigned)loadedDictEnd);
1160*01826a49SYabin Cui 
1161*01826a49SYabin Cui     /* - When there is no dictionary : loadedDictEnd == 0.
1162*01826a49SYabin Cui          In which case, the test (blockEndIdx > maxDist) is merely to avoid
1163*01826a49SYabin Cui          overflowing next operation `newLowLimit = blockEndIdx - maxDist`.
1164*01826a49SYabin Cui        - When there is a standard dictionary :
1165*01826a49SYabin Cui          Index referential is copied from the dictionary,
1166*01826a49SYabin Cui          which means it starts from 0.
1167*01826a49SYabin Cui          In which case, loadedDictEnd == dictSize,
1168*01826a49SYabin Cui          and it makes sense to compare `blockEndIdx > maxDist + dictSize`
1169*01826a49SYabin Cui          since `blockEndIdx` also starts from zero.
1170*01826a49SYabin Cui        - When there is an attached dictionary :
1171*01826a49SYabin Cui          loadedDictEnd is expressed within the referential of the context,
1172*01826a49SYabin Cui          so it can be directly compared against blockEndIdx.
1173*01826a49SYabin Cui     */
1174*01826a49SYabin Cui     if (blockEndIdx > maxDist + loadedDictEnd) {
1175*01826a49SYabin Cui         U32 const newLowLimit = blockEndIdx - maxDist;
1176*01826a49SYabin Cui         if (window->lowLimit < newLowLimit) window->lowLimit = newLowLimit;
1177*01826a49SYabin Cui         if (window->dictLimit < window->lowLimit) {
1178*01826a49SYabin Cui             DEBUGLOG(5, "Update dictLimit to match lowLimit, from %u to %u",
1179*01826a49SYabin Cui                         (unsigned)window->dictLimit, (unsigned)window->lowLimit);
1180*01826a49SYabin Cui             window->dictLimit = window->lowLimit;
1181*01826a49SYabin Cui         }
1182*01826a49SYabin Cui         /* On reaching window size, dictionaries are invalidated */
1183*01826a49SYabin Cui         if (loadedDictEndPtr) *loadedDictEndPtr = 0;
1184*01826a49SYabin Cui         if (dictMatchStatePtr) *dictMatchStatePtr = NULL;
1185*01826a49SYabin Cui     }
1186*01826a49SYabin Cui }
1187*01826a49SYabin Cui 
1188*01826a49SYabin Cui /* Similar to ZSTD_window_enforceMaxDist(),
1189*01826a49SYabin Cui  * but only invalidates dictionary
1190*01826a49SYabin Cui  * when input progresses beyond window size.
1191*01826a49SYabin Cui  * assumption : loadedDictEndPtr and dictMatchStatePtr are valid (non NULL)
1192*01826a49SYabin Cui  *              loadedDictEnd uses same referential as window->base
1193*01826a49SYabin Cui  *              maxDist is the window size */
1194*01826a49SYabin Cui MEM_STATIC void
ZSTD_checkDictValidity(const ZSTD_window_t * window,const void * blockEnd,U32 maxDist,U32 * loadedDictEndPtr,const ZSTD_matchState_t ** dictMatchStatePtr)1195*01826a49SYabin Cui ZSTD_checkDictValidity(const ZSTD_window_t* window,
1196*01826a49SYabin Cui                        const void* blockEnd,
1197*01826a49SYabin Cui                              U32   maxDist,
1198*01826a49SYabin Cui                              U32*  loadedDictEndPtr,
1199*01826a49SYabin Cui                        const ZSTD_matchState_t** dictMatchStatePtr)
1200*01826a49SYabin Cui {
1201*01826a49SYabin Cui     assert(loadedDictEndPtr != NULL);
1202*01826a49SYabin Cui     assert(dictMatchStatePtr != NULL);
1203*01826a49SYabin Cui     {   U32 const blockEndIdx = (U32)((BYTE const*)blockEnd - window->base);
1204*01826a49SYabin Cui         U32 const loadedDictEnd = *loadedDictEndPtr;
1205*01826a49SYabin Cui         DEBUGLOG(5, "ZSTD_checkDictValidity: blockEndIdx=%u, maxDist=%u, loadedDictEnd=%u",
1206*01826a49SYabin Cui                     (unsigned)blockEndIdx, (unsigned)maxDist, (unsigned)loadedDictEnd);
1207*01826a49SYabin Cui         assert(blockEndIdx >= loadedDictEnd);
1208*01826a49SYabin Cui 
1209*01826a49SYabin Cui         if (blockEndIdx > loadedDictEnd + maxDist || loadedDictEnd != window->dictLimit) {
1210*01826a49SYabin Cui             /* On reaching window size, dictionaries are invalidated.
1211*01826a49SYabin Cui              * For simplification, if window size is reached anywhere within next block,
1212*01826a49SYabin Cui              * the dictionary is invalidated for the full block.
1213*01826a49SYabin Cui              *
1214*01826a49SYabin Cui              * We also have to invalidate the dictionary if ZSTD_window_update() has detected
1215*01826a49SYabin Cui              * non-contiguous segments, which means that loadedDictEnd != window->dictLimit.
1216*01826a49SYabin Cui              * loadedDictEnd may be 0, if forceWindow is true, but in that case we never use
1217*01826a49SYabin Cui              * dictMatchState, so setting it to NULL is not a problem.
1218*01826a49SYabin Cui              */
1219*01826a49SYabin Cui             DEBUGLOG(6, "invalidating dictionary for current block (distance > windowSize)");
1220*01826a49SYabin Cui             *loadedDictEndPtr = 0;
1221*01826a49SYabin Cui             *dictMatchStatePtr = NULL;
1222*01826a49SYabin Cui         } else {
1223*01826a49SYabin Cui             if (*loadedDictEndPtr != 0) {
1224*01826a49SYabin Cui                 DEBUGLOG(6, "dictionary considered valid for current block");
1225*01826a49SYabin Cui     }   }   }
1226*01826a49SYabin Cui }
1227*01826a49SYabin Cui 
ZSTD_window_init(ZSTD_window_t * window)1228*01826a49SYabin Cui MEM_STATIC void ZSTD_window_init(ZSTD_window_t* window) {
1229*01826a49SYabin Cui     ZSTD_memset(window, 0, sizeof(*window));
1230*01826a49SYabin Cui     window->base = (BYTE const*)" ";
1231*01826a49SYabin Cui     window->dictBase = (BYTE const*)" ";
1232*01826a49SYabin Cui     ZSTD_STATIC_ASSERT(ZSTD_DUBT_UNSORTED_MARK < ZSTD_WINDOW_START_INDEX); /* Start above ZSTD_DUBT_UNSORTED_MARK */
1233*01826a49SYabin Cui     window->dictLimit = ZSTD_WINDOW_START_INDEX;    /* start from >0, so that 1st position is valid */
1234*01826a49SYabin Cui     window->lowLimit = ZSTD_WINDOW_START_INDEX;     /* it ensures first and later CCtx usages compress the same */
1235*01826a49SYabin Cui     window->nextSrc = window->base + ZSTD_WINDOW_START_INDEX;   /* see issue #1241 */
1236*01826a49SYabin Cui     window->nbOverflowCorrections = 0;
1237*01826a49SYabin Cui }
1238*01826a49SYabin Cui 
1239*01826a49SYabin Cui /**
1240*01826a49SYabin Cui  * ZSTD_window_update():
1241*01826a49SYabin Cui  * Updates the window by appending [src, src + srcSize) to the window.
1242*01826a49SYabin Cui  * If it is not contiguous, the current prefix becomes the extDict, and we
1243*01826a49SYabin Cui  * forget about the extDict. Handles overlap of the prefix and extDict.
1244*01826a49SYabin Cui  * Returns non-zero if the segment is contiguous.
1245*01826a49SYabin Cui  */
1246*01826a49SYabin Cui MEM_STATIC
1247*01826a49SYabin Cui ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
ZSTD_window_update(ZSTD_window_t * window,void const * src,size_t srcSize,int forceNonContiguous)1248*01826a49SYabin Cui U32 ZSTD_window_update(ZSTD_window_t* window,
1249*01826a49SYabin Cui                                   void const* src, size_t srcSize,
1250*01826a49SYabin Cui                                   int forceNonContiguous)
1251*01826a49SYabin Cui {
1252*01826a49SYabin Cui     BYTE const* const ip = (BYTE const*)src;
1253*01826a49SYabin Cui     U32 contiguous = 1;
1254*01826a49SYabin Cui     DEBUGLOG(5, "ZSTD_window_update");
1255*01826a49SYabin Cui     if (srcSize == 0)
1256*01826a49SYabin Cui         return contiguous;
1257*01826a49SYabin Cui     assert(window->base != NULL);
1258*01826a49SYabin Cui     assert(window->dictBase != NULL);
1259*01826a49SYabin Cui     /* Check if blocks follow each other */
1260*01826a49SYabin Cui     if (src != window->nextSrc || forceNonContiguous) {
1261*01826a49SYabin Cui         /* not contiguous */
1262*01826a49SYabin Cui         size_t const distanceFromBase = (size_t)(window->nextSrc - window->base);
1263*01826a49SYabin Cui         DEBUGLOG(5, "Non contiguous blocks, new segment starts at %u", window->dictLimit);
1264*01826a49SYabin Cui         window->lowLimit = window->dictLimit;
1265*01826a49SYabin Cui         assert(distanceFromBase == (size_t)(U32)distanceFromBase);  /* should never overflow */
1266*01826a49SYabin Cui         window->dictLimit = (U32)distanceFromBase;
1267*01826a49SYabin Cui         window->dictBase = window->base;
1268*01826a49SYabin Cui         window->base = ip - distanceFromBase;
1269*01826a49SYabin Cui         /* ms->nextToUpdate = window->dictLimit; */
1270*01826a49SYabin Cui         if (window->dictLimit - window->lowLimit < HASH_READ_SIZE) window->lowLimit = window->dictLimit;   /* too small extDict */
1271*01826a49SYabin Cui         contiguous = 0;
1272*01826a49SYabin Cui     }
1273*01826a49SYabin Cui     window->nextSrc = ip + srcSize;
1274*01826a49SYabin Cui     /* if input and dictionary overlap : reduce dictionary (area presumed modified by input) */
1275*01826a49SYabin Cui     if ( (ip+srcSize > window->dictBase + window->lowLimit)
1276*01826a49SYabin Cui        & (ip < window->dictBase + window->dictLimit)) {
1277*01826a49SYabin Cui         ptrdiff_t const highInputIdx = (ip + srcSize) - window->dictBase;
1278*01826a49SYabin Cui         U32 const lowLimitMax = (highInputIdx > (ptrdiff_t)window->dictLimit) ? window->dictLimit : (U32)highInputIdx;
1279*01826a49SYabin Cui         window->lowLimit = lowLimitMax;
1280*01826a49SYabin Cui         DEBUGLOG(5, "Overlapping extDict and input : new lowLimit = %u", window->lowLimit);
1281*01826a49SYabin Cui     }
1282*01826a49SYabin Cui     return contiguous;
1283*01826a49SYabin Cui }
1284*01826a49SYabin Cui 
1285*01826a49SYabin Cui /**
1286*01826a49SYabin Cui  * Returns the lowest allowed match index. It may either be in the ext-dict or the prefix.
1287*01826a49SYabin Cui  */
ZSTD_getLowestMatchIndex(const ZSTD_matchState_t * ms,U32 curr,unsigned windowLog)1288*01826a49SYabin Cui MEM_STATIC U32 ZSTD_getLowestMatchIndex(const ZSTD_matchState_t* ms, U32 curr, unsigned windowLog)
1289*01826a49SYabin Cui {
1290*01826a49SYabin Cui     U32 const maxDistance = 1U << windowLog;
1291*01826a49SYabin Cui     U32 const lowestValid = ms->window.lowLimit;
1292*01826a49SYabin Cui     U32 const withinWindow = (curr - lowestValid > maxDistance) ? curr - maxDistance : lowestValid;
1293*01826a49SYabin Cui     U32 const isDictionary = (ms->loadedDictEnd != 0);
1294*01826a49SYabin Cui     /* When using a dictionary the entire dictionary is valid if a single byte of the dictionary
1295*01826a49SYabin Cui      * is within the window. We invalidate the dictionary (and set loadedDictEnd to 0) when it isn't
1296*01826a49SYabin Cui      * valid for the entire block. So this check is sufficient to find the lowest valid match index.
1297*01826a49SYabin Cui      */
1298*01826a49SYabin Cui     U32 const matchLowest = isDictionary ? lowestValid : withinWindow;
1299*01826a49SYabin Cui     return matchLowest;
1300*01826a49SYabin Cui }
1301*01826a49SYabin Cui 
1302*01826a49SYabin Cui /**
1303*01826a49SYabin Cui  * Returns the lowest allowed match index in the prefix.
1304*01826a49SYabin Cui  */
ZSTD_getLowestPrefixIndex(const ZSTD_matchState_t * ms,U32 curr,unsigned windowLog)1305*01826a49SYabin Cui MEM_STATIC U32 ZSTD_getLowestPrefixIndex(const ZSTD_matchState_t* ms, U32 curr, unsigned windowLog)
1306*01826a49SYabin Cui {
1307*01826a49SYabin Cui     U32    const maxDistance = 1U << windowLog;
1308*01826a49SYabin Cui     U32    const lowestValid = ms->window.dictLimit;
1309*01826a49SYabin Cui     U32    const withinWindow = (curr - lowestValid > maxDistance) ? curr - maxDistance : lowestValid;
1310*01826a49SYabin Cui     U32    const isDictionary = (ms->loadedDictEnd != 0);
1311*01826a49SYabin Cui     /* When computing the lowest prefix index we need to take the dictionary into account to handle
1312*01826a49SYabin Cui      * the edge case where the dictionary and the source are contiguous in memory.
1313*01826a49SYabin Cui      */
1314*01826a49SYabin Cui     U32    const matchLowest = isDictionary ? lowestValid : withinWindow;
1315*01826a49SYabin Cui     return matchLowest;
1316*01826a49SYabin Cui }
1317*01826a49SYabin Cui 
1318*01826a49SYabin Cui 
1319*01826a49SYabin Cui 
1320*01826a49SYabin Cui /* debug functions */
1321*01826a49SYabin Cui #if (DEBUGLEVEL>=2)
1322*01826a49SYabin Cui 
ZSTD_fWeight(U32 rawStat)1323*01826a49SYabin Cui MEM_STATIC double ZSTD_fWeight(U32 rawStat)
1324*01826a49SYabin Cui {
1325*01826a49SYabin Cui     U32 const fp_accuracy = 8;
1326*01826a49SYabin Cui     U32 const fp_multiplier = (1 << fp_accuracy);
1327*01826a49SYabin Cui     U32 const newStat = rawStat + 1;
1328*01826a49SYabin Cui     U32 const hb = ZSTD_highbit32(newStat);
1329*01826a49SYabin Cui     U32 const BWeight = hb * fp_multiplier;
1330*01826a49SYabin Cui     U32 const FWeight = (newStat << fp_accuracy) >> hb;
1331*01826a49SYabin Cui     U32 const weight = BWeight + FWeight;
1332*01826a49SYabin Cui     assert(hb + fp_accuracy < 31);
1333*01826a49SYabin Cui     return (double)weight / fp_multiplier;
1334*01826a49SYabin Cui }
1335*01826a49SYabin Cui 
1336*01826a49SYabin Cui /* display a table content,
1337*01826a49SYabin Cui  * listing each element, its frequency, and its predicted bit cost */
ZSTD_debugTable(const U32 * table,U32 max)1338*01826a49SYabin Cui MEM_STATIC void ZSTD_debugTable(const U32* table, U32 max)
1339*01826a49SYabin Cui {
1340*01826a49SYabin Cui     unsigned u, sum;
1341*01826a49SYabin Cui     for (u=0, sum=0; u<=max; u++) sum += table[u];
1342*01826a49SYabin Cui     DEBUGLOG(2, "total nb elts: %u", sum);
1343*01826a49SYabin Cui     for (u=0; u<=max; u++) {
1344*01826a49SYabin Cui         DEBUGLOG(2, "%2u: %5u  (%.2f)",
1345*01826a49SYabin Cui                 u, table[u], ZSTD_fWeight(sum) - ZSTD_fWeight(table[u]) );
1346*01826a49SYabin Cui     }
1347*01826a49SYabin Cui }
1348*01826a49SYabin Cui 
1349*01826a49SYabin Cui #endif
1350*01826a49SYabin Cui 
1351*01826a49SYabin Cui /* Short Cache */
1352*01826a49SYabin Cui 
1353*01826a49SYabin Cui /* Normally, zstd matchfinders follow this flow:
1354*01826a49SYabin Cui  *     1. Compute hash at ip
1355*01826a49SYabin Cui  *     2. Load index from hashTable[hash]
1356*01826a49SYabin Cui  *     3. Check if *ip == *(base + index)
1357*01826a49SYabin Cui  * In dictionary compression, loading *(base + index) is often an L2 or even L3 miss.
1358*01826a49SYabin Cui  *
1359*01826a49SYabin Cui  * Short cache is an optimization which allows us to avoid step 3 most of the time
1360*01826a49SYabin Cui  * when the data doesn't actually match. With short cache, the flow becomes:
1361*01826a49SYabin Cui  *     1. Compute (hash, currentTag) at ip. currentTag is an 8-bit independent hash at ip.
1362*01826a49SYabin Cui  *     2. Load (index, matchTag) from hashTable[hash]. See ZSTD_writeTaggedIndex to understand how this works.
1363*01826a49SYabin Cui  *     3. Only if currentTag == matchTag, check *ip == *(base + index). Otherwise, continue.
1364*01826a49SYabin Cui  *
1365*01826a49SYabin Cui  * Currently, short cache is only implemented in CDict hashtables. Thus, its use is limited to
1366*01826a49SYabin Cui  * dictMatchState matchfinders.
1367*01826a49SYabin Cui  */
1368*01826a49SYabin Cui #define ZSTD_SHORT_CACHE_TAG_BITS 8
1369*01826a49SYabin Cui #define ZSTD_SHORT_CACHE_TAG_MASK ((1u << ZSTD_SHORT_CACHE_TAG_BITS) - 1)
1370*01826a49SYabin Cui 
1371*01826a49SYabin Cui /* Helper function for ZSTD_fillHashTable and ZSTD_fillDoubleHashTable.
1372*01826a49SYabin Cui  * Unpacks hashAndTag into (hash, tag), then packs (index, tag) into hashTable[hash]. */
ZSTD_writeTaggedIndex(U32 * const hashTable,size_t hashAndTag,U32 index)1373*01826a49SYabin Cui MEM_STATIC void ZSTD_writeTaggedIndex(U32* const hashTable, size_t hashAndTag, U32 index) {
1374*01826a49SYabin Cui     size_t const hash = hashAndTag >> ZSTD_SHORT_CACHE_TAG_BITS;
1375*01826a49SYabin Cui     U32 const tag = (U32)(hashAndTag & ZSTD_SHORT_CACHE_TAG_MASK);
1376*01826a49SYabin Cui     assert(index >> (32 - ZSTD_SHORT_CACHE_TAG_BITS) == 0);
1377*01826a49SYabin Cui     hashTable[hash] = (index << ZSTD_SHORT_CACHE_TAG_BITS) | tag;
1378*01826a49SYabin Cui }
1379*01826a49SYabin Cui 
1380*01826a49SYabin Cui /* Helper function for short cache matchfinders.
1381*01826a49SYabin Cui  * Unpacks tag1 and tag2 from lower bits of packedTag1 and packedTag2, then checks if the tags match. */
ZSTD_comparePackedTags(size_t packedTag1,size_t packedTag2)1382*01826a49SYabin Cui MEM_STATIC int ZSTD_comparePackedTags(size_t packedTag1, size_t packedTag2) {
1383*01826a49SYabin Cui     U32 const tag1 = packedTag1 & ZSTD_SHORT_CACHE_TAG_MASK;
1384*01826a49SYabin Cui     U32 const tag2 = packedTag2 & ZSTD_SHORT_CACHE_TAG_MASK;
1385*01826a49SYabin Cui     return tag1 == tag2;
1386*01826a49SYabin Cui }
1387*01826a49SYabin Cui 
1388*01826a49SYabin Cui #if defined (__cplusplus)
1389*01826a49SYabin Cui }
1390*01826a49SYabin Cui #endif
1391*01826a49SYabin Cui 
1392*01826a49SYabin Cui /* ===============================================================
1393*01826a49SYabin Cui  * Shared internal declarations
1394*01826a49SYabin Cui  * These prototypes may be called from sources not in lib/compress
1395*01826a49SYabin Cui  * =============================================================== */
1396*01826a49SYabin Cui 
1397*01826a49SYabin Cui /* ZSTD_loadCEntropy() :
1398*01826a49SYabin Cui  * dict : must point at beginning of a valid zstd dictionary.
1399*01826a49SYabin Cui  * return : size of dictionary header (size of magic number + dict ID + entropy tables)
1400*01826a49SYabin Cui  * assumptions : magic number supposed already checked
1401*01826a49SYabin Cui  *               and dictSize >= 8 */
1402*01826a49SYabin Cui size_t ZSTD_loadCEntropy(ZSTD_compressedBlockState_t* bs, void* workspace,
1403*01826a49SYabin Cui                          const void* const dict, size_t dictSize);
1404*01826a49SYabin Cui 
1405*01826a49SYabin Cui void ZSTD_reset_compressedBlockState(ZSTD_compressedBlockState_t* bs);
1406*01826a49SYabin Cui 
1407*01826a49SYabin Cui /* ==============================================================
1408*01826a49SYabin Cui  * Private declarations
1409*01826a49SYabin Cui  * These prototypes shall only be called from within lib/compress
1410*01826a49SYabin Cui  * ============================================================== */
1411*01826a49SYabin Cui 
1412*01826a49SYabin Cui /* ZSTD_getCParamsFromCCtxParams() :
1413*01826a49SYabin Cui  * cParams are built depending on compressionLevel, src size hints,
1414*01826a49SYabin Cui  * LDM and manually set compression parameters.
1415*01826a49SYabin Cui  * Note: srcSizeHint == 0 means 0!
1416*01826a49SYabin Cui  */
1417*01826a49SYabin Cui ZSTD_compressionParameters ZSTD_getCParamsFromCCtxParams(
1418*01826a49SYabin Cui         const ZSTD_CCtx_params* CCtxParams, U64 srcSizeHint, size_t dictSize, ZSTD_cParamMode_e mode);
1419*01826a49SYabin Cui 
1420*01826a49SYabin Cui /*! ZSTD_initCStream_internal() :
1421*01826a49SYabin Cui  *  Private use only. Init streaming operation.
1422*01826a49SYabin Cui  *  expects params to be valid.
1423*01826a49SYabin Cui  *  must receive dict, or cdict, or none, but not both.
1424*01826a49SYabin Cui  *  @return : 0, or an error code */
1425*01826a49SYabin Cui size_t ZSTD_initCStream_internal(ZSTD_CStream* zcs,
1426*01826a49SYabin Cui                      const void* dict, size_t dictSize,
1427*01826a49SYabin Cui                      const ZSTD_CDict* cdict,
1428*01826a49SYabin Cui                      const ZSTD_CCtx_params* params, unsigned long long pledgedSrcSize);
1429*01826a49SYabin Cui 
1430*01826a49SYabin Cui void ZSTD_resetSeqStore(seqStore_t* ssPtr);
1431*01826a49SYabin Cui 
1432*01826a49SYabin Cui /*! ZSTD_getCParamsFromCDict() :
1433*01826a49SYabin Cui  *  as the name implies */
1434*01826a49SYabin Cui ZSTD_compressionParameters ZSTD_getCParamsFromCDict(const ZSTD_CDict* cdict);
1435*01826a49SYabin Cui 
1436*01826a49SYabin Cui /* ZSTD_compressBegin_advanced_internal() :
1437*01826a49SYabin Cui  * Private use only. To be called from zstdmt_compress.c. */
1438*01826a49SYabin Cui size_t ZSTD_compressBegin_advanced_internal(ZSTD_CCtx* cctx,
1439*01826a49SYabin Cui                                     const void* dict, size_t dictSize,
1440*01826a49SYabin Cui                                     ZSTD_dictContentType_e dictContentType,
1441*01826a49SYabin Cui                                     ZSTD_dictTableLoadMethod_e dtlm,
1442*01826a49SYabin Cui                                     const ZSTD_CDict* cdict,
1443*01826a49SYabin Cui                                     const ZSTD_CCtx_params* params,
1444*01826a49SYabin Cui                                     unsigned long long pledgedSrcSize);
1445*01826a49SYabin Cui 
1446*01826a49SYabin Cui /* ZSTD_compress_advanced_internal() :
1447*01826a49SYabin Cui  * Private use only. To be called from zstdmt_compress.c. */
1448*01826a49SYabin Cui size_t ZSTD_compress_advanced_internal(ZSTD_CCtx* cctx,
1449*01826a49SYabin Cui                                        void* dst, size_t dstCapacity,
1450*01826a49SYabin Cui                                  const void* src, size_t srcSize,
1451*01826a49SYabin Cui                                  const void* dict,size_t dictSize,
1452*01826a49SYabin Cui                                  const ZSTD_CCtx_params* params);
1453*01826a49SYabin Cui 
1454*01826a49SYabin Cui 
1455*01826a49SYabin Cui /* ZSTD_writeLastEmptyBlock() :
1456*01826a49SYabin Cui  * output an empty Block with end-of-frame mark to complete a frame
1457*01826a49SYabin Cui  * @return : size of data written into `dst` (== ZSTD_blockHeaderSize (defined in zstd_internal.h))
1458*01826a49SYabin Cui  *           or an error code if `dstCapacity` is too small (<ZSTD_blockHeaderSize)
1459*01826a49SYabin Cui  */
1460*01826a49SYabin Cui size_t ZSTD_writeLastEmptyBlock(void* dst, size_t dstCapacity);
1461*01826a49SYabin Cui 
1462*01826a49SYabin Cui 
1463*01826a49SYabin Cui /* ZSTD_referenceExternalSequences() :
1464*01826a49SYabin Cui  * Must be called before starting a compression operation.
1465*01826a49SYabin Cui  * seqs must parse a prefix of the source.
1466*01826a49SYabin Cui  * This cannot be used when long range matching is enabled.
1467*01826a49SYabin Cui  * Zstd will use these sequences, and pass the literals to a secondary block
1468*01826a49SYabin Cui  * compressor.
1469*01826a49SYabin Cui  * NOTE: seqs are not verified! Invalid sequences can cause out-of-bounds memory
1470*01826a49SYabin Cui  * access and data corruption.
1471*01826a49SYabin Cui  */
1472*01826a49SYabin Cui void ZSTD_referenceExternalSequences(ZSTD_CCtx* cctx, rawSeq* seq, size_t nbSeq);
1473*01826a49SYabin Cui 
1474*01826a49SYabin Cui /** ZSTD_cycleLog() :
1475*01826a49SYabin Cui  *  condition for correct operation : hashLog > 1 */
1476*01826a49SYabin Cui U32 ZSTD_cycleLog(U32 hashLog, ZSTD_strategy strat);
1477*01826a49SYabin Cui 
1478*01826a49SYabin Cui /** ZSTD_CCtx_trace() :
1479*01826a49SYabin Cui  *  Trace the end of a compression call.
1480*01826a49SYabin Cui  */
1481*01826a49SYabin Cui void ZSTD_CCtx_trace(ZSTD_CCtx* cctx, size_t extraCSize);
1482*01826a49SYabin Cui 
1483*01826a49SYabin Cui /* Returns 0 on success, and a ZSTD_error otherwise. This function scans through an array of
1484*01826a49SYabin Cui  * ZSTD_Sequence, storing the sequences it finds, until it reaches a block delimiter.
1485*01826a49SYabin Cui  * Note that the block delimiter must include the last literals of the block.
1486*01826a49SYabin Cui  */
1487*01826a49SYabin Cui size_t
1488*01826a49SYabin Cui ZSTD_copySequencesToSeqStoreExplicitBlockDelim(ZSTD_CCtx* cctx,
1489*01826a49SYabin Cui                                               ZSTD_sequencePosition* seqPos,
1490*01826a49SYabin Cui                                         const ZSTD_Sequence* const inSeqs, size_t inSeqsSize,
1491*01826a49SYabin Cui                                         const void* src, size_t blockSize, ZSTD_paramSwitch_e externalRepSearch);
1492*01826a49SYabin Cui 
1493*01826a49SYabin Cui /* Returns the number of bytes to move the current read position back by.
1494*01826a49SYabin Cui  * Only non-zero if we ended up splitting a sequence.
1495*01826a49SYabin Cui  * Otherwise, it may return a ZSTD error if something went wrong.
1496*01826a49SYabin Cui  *
1497*01826a49SYabin Cui  * This function will attempt to scan through blockSize bytes
1498*01826a49SYabin Cui  * represented by the sequences in @inSeqs,
1499*01826a49SYabin Cui  * storing any (partial) sequences.
1500*01826a49SYabin Cui  *
1501*01826a49SYabin Cui  * Occasionally, we may want to change the actual number of bytes we consumed from inSeqs to
1502*01826a49SYabin Cui  * avoid splitting a match, or to avoid splitting a match such that it would produce a match
1503*01826a49SYabin Cui  * smaller than MINMATCH. In this case, we return the number of bytes that we didn't read from this block.
1504*01826a49SYabin Cui  */
1505*01826a49SYabin Cui size_t
1506*01826a49SYabin Cui ZSTD_copySequencesToSeqStoreNoBlockDelim(ZSTD_CCtx* cctx, ZSTD_sequencePosition* seqPos,
1507*01826a49SYabin Cui                                    const ZSTD_Sequence* const inSeqs, size_t inSeqsSize,
1508*01826a49SYabin Cui                                    const void* src, size_t blockSize, ZSTD_paramSwitch_e externalRepSearch);
1509*01826a49SYabin Cui 
1510*01826a49SYabin Cui /* Returns 1 if an external sequence producer is registered, otherwise returns 0. */
ZSTD_hasExtSeqProd(const ZSTD_CCtx_params * params)1511*01826a49SYabin Cui MEM_STATIC int ZSTD_hasExtSeqProd(const ZSTD_CCtx_params* params) {
1512*01826a49SYabin Cui     return params->extSeqProdFunc != NULL;
1513*01826a49SYabin Cui }
1514*01826a49SYabin Cui 
1515*01826a49SYabin Cui /* ===============================================================
1516*01826a49SYabin Cui  * Deprecated definitions that are still used internally to avoid
1517*01826a49SYabin Cui  * deprecation warnings. These functions are exactly equivalent to
1518*01826a49SYabin Cui  * their public variants, but avoid the deprecation warnings.
1519*01826a49SYabin Cui  * =============================================================== */
1520*01826a49SYabin Cui 
1521*01826a49SYabin Cui size_t ZSTD_compressBegin_usingCDict_deprecated(ZSTD_CCtx* cctx, const ZSTD_CDict* cdict);
1522*01826a49SYabin Cui 
1523*01826a49SYabin Cui size_t ZSTD_compressContinue_public(ZSTD_CCtx* cctx,
1524*01826a49SYabin Cui                                     void* dst, size_t dstCapacity,
1525*01826a49SYabin Cui                               const void* src, size_t srcSize);
1526*01826a49SYabin Cui 
1527*01826a49SYabin Cui size_t ZSTD_compressEnd_public(ZSTD_CCtx* cctx,
1528*01826a49SYabin Cui                                void* dst, size_t dstCapacity,
1529*01826a49SYabin Cui                          const void* src, size_t srcSize);
1530*01826a49SYabin Cui 
1531*01826a49SYabin Cui size_t ZSTD_compressBlock_deprecated(ZSTD_CCtx* cctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize);
1532*01826a49SYabin Cui 
1533*01826a49SYabin Cui 
1534*01826a49SYabin Cui #endif /* ZSTD_COMPRESS_H */
1535