Path: blob/master/Utilities/cmzstd/lib/compress/zstd_compress_internal.h
5016 views
/*1* Copyright (c) Meta Platforms, Inc. and affiliates.2* All rights reserved.3*4* This source code is licensed under both the BSD-style license (found in the5* LICENSE file in the root directory of this source tree) and the GPLv2 (found6* in the COPYING file in the root directory of this source tree).7* You may select, at your option, one of the above-listed licenses.8*/910/* This header contains definitions11* that shall **only** be used by modules within lib/compress.12*/1314#ifndef ZSTD_COMPRESS_H15#define ZSTD_COMPRESS_H1617/*-*************************************18* Dependencies19***************************************/20#include "../common/zstd_internal.h"21#include "zstd_cwksp.h"22#ifdef ZSTD_MULTITHREAD23# include "zstdmt_compress.h"24#endif25#include "../common/bits.h" /* ZSTD_highbit32, ZSTD_NbCommonBytes */26#include "zstd_preSplit.h" /* ZSTD_SLIPBLOCK_WORKSPACESIZE */2728/*-*************************************29* Constants30***************************************/31#define kSearchStrength 832#define HASH_READ_SIZE 833#define ZSTD_DUBT_UNSORTED_MARK 1 /* For btlazy2 strategy, index ZSTD_DUBT_UNSORTED_MARK==1 means "unsorted".34It could be confused for a real successor at index "1", if sorted as larger than its predecessor.35It's not a big deal though : candidate will just be sorted again.36Additionally, candidate position 1 will be lost.37But candidate 1 cannot hide a large tree of candidates, so it's a minimal loss.38The benefit is that ZSTD_DUBT_UNSORTED_MARK cannot be mishandled after table reuse with a different strategy.39This constant is required by ZSTD_compressBlock_btlazy2() and ZSTD_reduceTable_internal() */404142/*-*************************************43* Context memory management44***************************************/45typedef enum { ZSTDcs_created=0, ZSTDcs_init, ZSTDcs_ongoing, ZSTDcs_ending } ZSTD_compressionStage_e;46typedef enum { zcss_init=0, zcss_load, zcss_flush } ZSTD_cStreamStage;4748typedef struct ZSTD_prefixDict_s {49const void* dict;50size_t dictSize;51ZSTD_dictContentType_e dictContentType;52} ZSTD_prefixDict;5354typedef struct {55void* dictBuffer;56void const* dict;57size_t dictSize;58ZSTD_dictContentType_e dictContentType;59ZSTD_CDict* cdict;60} ZSTD_localDict;6162typedef struct {63HUF_CElt CTable[HUF_CTABLE_SIZE_ST(255)];64HUF_repeat repeatMode;65} ZSTD_hufCTables_t;6667typedef struct {68FSE_CTable offcodeCTable[FSE_CTABLE_SIZE_U32(OffFSELog, MaxOff)];69FSE_CTable matchlengthCTable[FSE_CTABLE_SIZE_U32(MLFSELog, MaxML)];70FSE_CTable litlengthCTable[FSE_CTABLE_SIZE_U32(LLFSELog, MaxLL)];71FSE_repeat offcode_repeatMode;72FSE_repeat matchlength_repeatMode;73FSE_repeat litlength_repeatMode;74} ZSTD_fseCTables_t;7576typedef struct {77ZSTD_hufCTables_t huf;78ZSTD_fseCTables_t fse;79} ZSTD_entropyCTables_t;8081/***********************************************82* Sequences *83***********************************************/84typedef struct SeqDef_s {85U32 offBase; /* offBase == Offset + ZSTD_REP_NUM, or repcode 1,2,3 */86U16 litLength;87U16 mlBase; /* mlBase == matchLength - MINMATCH */88} SeqDef;8990/* Controls whether seqStore has a single "long" litLength or matchLength. See SeqStore_t. */91typedef enum {92ZSTD_llt_none = 0, /* no longLengthType */93ZSTD_llt_literalLength = 1, /* represents a long literal */94ZSTD_llt_matchLength = 2 /* represents a long match */95} ZSTD_longLengthType_e;9697typedef struct {98SeqDef* sequencesStart;99SeqDef* sequences; /* ptr to end of sequences */100BYTE* litStart;101BYTE* lit; /* ptr to end of literals */102BYTE* llCode;103BYTE* mlCode;104BYTE* ofCode;105size_t maxNbSeq;106size_t maxNbLit;107108/* longLengthPos and longLengthType to allow us to represent either a single litLength or matchLength109* in the seqStore that has a value larger than U16 (if it exists). To do so, we increment110* the existing value of the litLength or matchLength by 0x10000.111*/112ZSTD_longLengthType_e longLengthType;113U32 longLengthPos; /* Index of the sequence to apply long length modification to */114} SeqStore_t;115116typedef struct {117U32 litLength;118U32 matchLength;119} ZSTD_SequenceLength;120121/**122* Returns the ZSTD_SequenceLength for the given sequences. It handles the decoding of long sequences123* indicated by longLengthPos and longLengthType, and adds MINMATCH back to matchLength.124*/125MEM_STATIC ZSTD_SequenceLength ZSTD_getSequenceLength(SeqStore_t const* seqStore, SeqDef const* seq)126{127ZSTD_SequenceLength seqLen;128seqLen.litLength = seq->litLength;129seqLen.matchLength = seq->mlBase + MINMATCH;130if (seqStore->longLengthPos == (U32)(seq - seqStore->sequencesStart)) {131if (seqStore->longLengthType == ZSTD_llt_literalLength) {132seqLen.litLength += 0x10000;133}134if (seqStore->longLengthType == ZSTD_llt_matchLength) {135seqLen.matchLength += 0x10000;136}137}138return seqLen;139}140141const SeqStore_t* ZSTD_getSeqStore(const ZSTD_CCtx* ctx); /* compress & dictBuilder */142int ZSTD_seqToCodes(const SeqStore_t* seqStorePtr); /* compress, dictBuilder, decodeCorpus (shouldn't get its definition from here) */143144145/***********************************************146* Entropy buffer statistics structs and funcs *147***********************************************/148/** ZSTD_hufCTablesMetadata_t :149* Stores Literals Block Type for a super-block in hType, and150* huffman tree description in hufDesBuffer.151* hufDesSize refers to the size of huffman tree description in bytes.152* This metadata is populated in ZSTD_buildBlockEntropyStats_literals() */153typedef struct {154SymbolEncodingType_e hType;155BYTE hufDesBuffer[ZSTD_MAX_HUF_HEADER_SIZE];156size_t hufDesSize;157} ZSTD_hufCTablesMetadata_t;158159/** ZSTD_fseCTablesMetadata_t :160* Stores symbol compression modes for a super-block in {ll, ol, ml}Type, and161* fse tables in fseTablesBuffer.162* fseTablesSize refers to the size of fse tables in bytes.163* This metadata is populated in ZSTD_buildBlockEntropyStats_sequences() */164typedef struct {165SymbolEncodingType_e llType;166SymbolEncodingType_e ofType;167SymbolEncodingType_e mlType;168BYTE fseTablesBuffer[ZSTD_MAX_FSE_HEADERS_SIZE];169size_t fseTablesSize;170size_t lastCountSize; /* This is to account for bug in 1.3.4. More detail in ZSTD_entropyCompressSeqStore_internal() */171} ZSTD_fseCTablesMetadata_t;172173typedef struct {174ZSTD_hufCTablesMetadata_t hufMetadata;175ZSTD_fseCTablesMetadata_t fseMetadata;176} ZSTD_entropyCTablesMetadata_t;177178/** ZSTD_buildBlockEntropyStats() :179* Builds entropy for the block.180* @return : 0 on success or error code */181size_t ZSTD_buildBlockEntropyStats(182const SeqStore_t* seqStorePtr,183const ZSTD_entropyCTables_t* prevEntropy,184ZSTD_entropyCTables_t* nextEntropy,185const ZSTD_CCtx_params* cctxParams,186ZSTD_entropyCTablesMetadata_t* entropyMetadata,187void* workspace, size_t wkspSize);188189/*********************************190* Compression internals structs *191*********************************/192193typedef struct {194U32 off; /* Offset sumtype code for the match, using ZSTD_storeSeq() format */195U32 len; /* Raw length of match */196} ZSTD_match_t;197198typedef struct {199U32 offset; /* Offset of sequence */200U32 litLength; /* Length of literals prior to match */201U32 matchLength; /* Raw length of match */202} rawSeq;203204typedef struct {205rawSeq* seq; /* The start of the sequences */206size_t pos; /* The index in seq where reading stopped. pos <= size. */207size_t posInSequence; /* The position within the sequence at seq[pos] where reading208stopped. posInSequence <= seq[pos].litLength + seq[pos].matchLength */209size_t size; /* The number of sequences. <= capacity. */210size_t capacity; /* The capacity starting from `seq` pointer */211} RawSeqStore_t;212213UNUSED_ATTR static const RawSeqStore_t kNullRawSeqStore = {NULL, 0, 0, 0, 0};214215typedef struct {216int price; /* price from beginning of segment to this position */217U32 off; /* offset of previous match */218U32 mlen; /* length of previous match */219U32 litlen; /* nb of literals since previous match */220U32 rep[ZSTD_REP_NUM]; /* offset history after previous match */221} ZSTD_optimal_t;222223typedef enum { zop_dynamic=0, zop_predef } ZSTD_OptPrice_e;224225#define ZSTD_OPT_SIZE (ZSTD_OPT_NUM+3)226typedef struct {227/* All tables are allocated inside cctx->workspace by ZSTD_resetCCtx_internal() */228unsigned* litFreq; /* table of literals statistics, of size 256 */229unsigned* litLengthFreq; /* table of litLength statistics, of size (MaxLL+1) */230unsigned* matchLengthFreq; /* table of matchLength statistics, of size (MaxML+1) */231unsigned* offCodeFreq; /* table of offCode statistics, of size (MaxOff+1) */232ZSTD_match_t* matchTable; /* list of found matches, of size ZSTD_OPT_SIZE */233ZSTD_optimal_t* priceTable; /* All positions tracked by optimal parser, of size ZSTD_OPT_SIZE */234235U32 litSum; /* nb of literals */236U32 litLengthSum; /* nb of litLength codes */237U32 matchLengthSum; /* nb of matchLength codes */238U32 offCodeSum; /* nb of offset codes */239U32 litSumBasePrice; /* to compare to log2(litfreq) */240U32 litLengthSumBasePrice; /* to compare to log2(llfreq) */241U32 matchLengthSumBasePrice;/* to compare to log2(mlfreq) */242U32 offCodeSumBasePrice; /* to compare to log2(offreq) */243ZSTD_OptPrice_e priceType; /* prices can be determined dynamically, or follow a pre-defined cost structure */244const ZSTD_entropyCTables_t* symbolCosts; /* pre-calculated dictionary statistics */245ZSTD_ParamSwitch_e literalCompressionMode;246} optState_t;247248typedef struct {249ZSTD_entropyCTables_t entropy;250U32 rep[ZSTD_REP_NUM];251} ZSTD_compressedBlockState_t;252253typedef struct {254BYTE const* nextSrc; /* next block here to continue on current prefix */255BYTE const* base; /* All regular indexes relative to this position */256BYTE const* dictBase; /* extDict indexes relative to this position */257U32 dictLimit; /* below that point, need extDict */258U32 lowLimit; /* below that point, no more valid data */259U32 nbOverflowCorrections; /* Number of times overflow correction has run since260* ZSTD_window_init(). Useful for debugging coredumps261* and for ZSTD_WINDOW_OVERFLOW_CORRECT_FREQUENTLY.262*/263} ZSTD_window_t;264265#define ZSTD_WINDOW_START_INDEX 2266267typedef struct ZSTD_MatchState_t ZSTD_MatchState_t;268269#define ZSTD_ROW_HASH_CACHE_SIZE 8 /* Size of prefetching hash cache for row-based matchfinder */270271struct ZSTD_MatchState_t {272ZSTD_window_t window; /* State for window round buffer management */273U32 loadedDictEnd; /* index of end of dictionary, within context's referential.274* When loadedDictEnd != 0, a dictionary is in use, and still valid.275* This relies on a mechanism to set loadedDictEnd=0 when dictionary is no longer within distance.276* Such mechanism is provided within ZSTD_window_enforceMaxDist() and ZSTD_checkDictValidity().277* When dict referential is copied into active context (i.e. not attached),278* loadedDictEnd == dictSize, since referential starts from zero.279*/280U32 nextToUpdate; /* index from which to continue table update */281U32 hashLog3; /* dispatch table for matches of len==3 : larger == faster, more memory */282283U32 rowHashLog; /* For row-based matchfinder: Hashlog based on nb of rows in the hashTable.*/284BYTE* tagTable; /* For row-based matchFinder: A row-based table containing the hashes and head index. */285U32 hashCache[ZSTD_ROW_HASH_CACHE_SIZE]; /* For row-based matchFinder: a cache of hashes to improve speed */286U64 hashSalt; /* For row-based matchFinder: salts the hash for reuse of tag table */287U32 hashSaltEntropy; /* For row-based matchFinder: collects entropy for salt generation */288289U32* hashTable;290U32* hashTable3;291U32* chainTable;292293int forceNonContiguous; /* Non-zero if we should force non-contiguous load for the next window update. */294295int dedicatedDictSearch; /* Indicates whether this matchState is using the296* dedicated dictionary search structure.297*/298optState_t opt; /* optimal parser state */299const ZSTD_MatchState_t* dictMatchState;300ZSTD_compressionParameters cParams;301const RawSeqStore_t* ldmSeqStore;302303/* Controls prefetching in some dictMatchState matchfinders.304* This behavior is controlled from the cctx ms.305* This parameter has no effect in the cdict ms. */306int prefetchCDictTables;307308/* When == 0, lazy match finders insert every position.309* When != 0, lazy match finders only insert positions they search.310* This allows them to skip much faster over incompressible data,311* at a small cost to compression ratio.312*/313int lazySkipping;314};315316typedef struct {317ZSTD_compressedBlockState_t* prevCBlock;318ZSTD_compressedBlockState_t* nextCBlock;319ZSTD_MatchState_t matchState;320} ZSTD_blockState_t;321322typedef struct {323U32 offset;324U32 checksum;325} ldmEntry_t;326327typedef struct {328BYTE const* split;329U32 hash;330U32 checksum;331ldmEntry_t* bucket;332} ldmMatchCandidate_t;333334#define LDM_BATCH_SIZE 64335336typedef struct {337ZSTD_window_t window; /* State for the window round buffer management */338ldmEntry_t* hashTable;339U32 loadedDictEnd;340BYTE* bucketOffsets; /* Next position in bucket to insert entry */341size_t splitIndices[LDM_BATCH_SIZE];342ldmMatchCandidate_t matchCandidates[LDM_BATCH_SIZE];343} ldmState_t;344345typedef struct {346ZSTD_ParamSwitch_e enableLdm; /* ZSTD_ps_enable to enable LDM. ZSTD_ps_auto by default */347U32 hashLog; /* Log size of hashTable */348U32 bucketSizeLog; /* Log bucket size for collision resolution, at most 8 */349U32 minMatchLength; /* Minimum match length */350U32 hashRateLog; /* Log number of entries to skip */351U32 windowLog; /* Window log for the LDM */352} ldmParams_t;353354typedef struct {355int collectSequences;356ZSTD_Sequence* seqStart;357size_t seqIndex;358size_t maxSequences;359} SeqCollector;360361struct ZSTD_CCtx_params_s {362ZSTD_format_e format;363ZSTD_compressionParameters cParams;364ZSTD_frameParameters fParams;365366int compressionLevel;367int forceWindow; /* force back-references to respect limit of368* 1<<wLog, even for dictionary */369size_t targetCBlockSize; /* Tries to fit compressed block size to be around targetCBlockSize.370* No target when targetCBlockSize == 0.371* There is no guarantee on compressed block size */372int srcSizeHint; /* User's best guess of source size.373* Hint is not valid when srcSizeHint == 0.374* There is no guarantee that hint is close to actual source size */375376ZSTD_dictAttachPref_e attachDictPref;377ZSTD_ParamSwitch_e literalCompressionMode;378379/* Multithreading: used to pass parameters to mtctx */380int nbWorkers;381size_t jobSize;382int overlapLog;383int rsyncable;384385/* Long distance matching parameters */386ldmParams_t ldmParams;387388/* Dedicated dict search algorithm trigger */389int enableDedicatedDictSearch;390391/* Input/output buffer modes */392ZSTD_bufferMode_e inBufferMode;393ZSTD_bufferMode_e outBufferMode;394395/* Sequence compression API */396ZSTD_SequenceFormat_e blockDelimiters;397int validateSequences;398399/* Block splitting400* @postBlockSplitter executes split analysis after sequences are produced,401* it's more accurate but consumes more resources.402* @preBlockSplitter_level splits before knowing sequences,403* it's more approximative but also cheaper.404* Valid @preBlockSplitter_level values range from 0 to 6 (included).405* 0 means auto, 1 means do not split,406* then levels are sorted in increasing cpu budget, from 2 (fastest) to 6 (slowest).407* Highest @preBlockSplitter_level combines well with @postBlockSplitter.408*/409ZSTD_ParamSwitch_e postBlockSplitter;410int preBlockSplitter_level;411412/* Adjust the max block size*/413size_t maxBlockSize;414415/* Param for deciding whether to use row-based matchfinder */416ZSTD_ParamSwitch_e useRowMatchFinder;417418/* Always load a dictionary in ext-dict mode (not prefix mode)? */419int deterministicRefPrefix;420421/* Internal use, for createCCtxParams() and freeCCtxParams() only */422ZSTD_customMem customMem;423424/* Controls prefetching in some dictMatchState matchfinders */425ZSTD_ParamSwitch_e prefetchCDictTables;426427/* Controls whether zstd will fall back to an internal matchfinder428* if the external matchfinder returns an error code. */429int enableMatchFinderFallback;430431/* Parameters for the external sequence producer API.432* Users set these parameters through ZSTD_registerSequenceProducer().433* It is not possible to set these parameters individually through the public API. */434void* extSeqProdState;435ZSTD_sequenceProducer_F extSeqProdFunc;436437/* Controls repcode search in external sequence parsing */438ZSTD_ParamSwitch_e searchForExternalRepcodes;439}; /* typedef'd to ZSTD_CCtx_params within "zstd.h" */440441#define COMPRESS_SEQUENCES_WORKSPACE_SIZE (sizeof(unsigned) * (MaxSeq + 2))442#define ENTROPY_WORKSPACE_SIZE (HUF_WORKSPACE_SIZE + COMPRESS_SEQUENCES_WORKSPACE_SIZE)443#define TMP_WORKSPACE_SIZE (MAX(ENTROPY_WORKSPACE_SIZE, ZSTD_SLIPBLOCK_WORKSPACESIZE))444445/**446* Indicates whether this compression proceeds directly from user-provided447* source buffer to user-provided destination buffer (ZSTDb_not_buffered), or448* whether the context needs to buffer the input/output (ZSTDb_buffered).449*/450typedef enum {451ZSTDb_not_buffered,452ZSTDb_buffered453} ZSTD_buffered_policy_e;454455/**456* Struct that contains all elements of block splitter that should be allocated457* in a wksp.458*/459#define ZSTD_MAX_NB_BLOCK_SPLITS 196460typedef struct {461SeqStore_t fullSeqStoreChunk;462SeqStore_t firstHalfSeqStore;463SeqStore_t secondHalfSeqStore;464SeqStore_t currSeqStore;465SeqStore_t nextSeqStore;466467U32 partitions[ZSTD_MAX_NB_BLOCK_SPLITS];468ZSTD_entropyCTablesMetadata_t entropyMetadata;469} ZSTD_blockSplitCtx;470471struct ZSTD_CCtx_s {472ZSTD_compressionStage_e stage;473int 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. */474int bmi2; /* == 1 if the CPU supports BMI2 and 0 otherwise. CPU support is determined dynamically once per context lifetime. */475ZSTD_CCtx_params requestedParams;476ZSTD_CCtx_params appliedParams;477ZSTD_CCtx_params simpleApiParams; /* Param storage used by the simple API - not sticky. Must only be used in top-level simple API functions for storage. */478U32 dictID;479size_t dictContentSize;480481ZSTD_cwksp workspace; /* manages buffer for dynamic allocations */482size_t blockSizeMax;483unsigned long long pledgedSrcSizePlusOne; /* this way, 0 (default) == unknown */484unsigned long long consumedSrcSize;485unsigned long long producedCSize;486XXH64_state_t xxhState;487ZSTD_customMem customMem;488ZSTD_threadPool* pool;489size_t staticSize;490SeqCollector seqCollector;491int isFirstBlock;492int initialized;493494SeqStore_t seqStore; /* sequences storage ptrs */495ldmState_t ldmState; /* long distance matching state */496rawSeq* ldmSequences; /* Storage for the ldm output sequences */497size_t maxNbLdmSequences;498RawSeqStore_t externSeqStore; /* Mutable reference to external sequences */499ZSTD_blockState_t blockState;500void* tmpWorkspace; /* used as substitute of stack space - must be aligned for S64 type */501size_t tmpWkspSize;502503/* Whether we are streaming or not */504ZSTD_buffered_policy_e bufferedPolicy;505506/* streaming */507char* inBuff;508size_t inBuffSize;509size_t inToCompress;510size_t inBuffPos;511size_t inBuffTarget;512char* outBuff;513size_t outBuffSize;514size_t outBuffContentSize;515size_t outBuffFlushedSize;516ZSTD_cStreamStage streamStage;517U32 frameEnded;518519/* Stable in/out buffer verification */520ZSTD_inBuffer expectedInBuffer;521size_t stableIn_notConsumed; /* nb bytes within stable input buffer that are said to be consumed but are not */522size_t expectedOutBufferSize;523524/* Dictionary */525ZSTD_localDict localDict;526const ZSTD_CDict* cdict;527ZSTD_prefixDict prefixDict; /* single-usage dictionary */528529/* Multi-threading */530#ifdef ZSTD_MULTITHREAD531ZSTDMT_CCtx* mtctx;532#endif533534/* Tracing */535#if ZSTD_TRACE536ZSTD_TraceCtx traceCtx;537#endif538539/* Workspace for block splitter */540ZSTD_blockSplitCtx blockSplitCtx;541542/* Buffer for output from external sequence producer */543ZSTD_Sequence* extSeqBuf;544size_t extSeqBufCapacity;545};546547typedef enum { ZSTD_dtlm_fast, ZSTD_dtlm_full } ZSTD_dictTableLoadMethod_e;548typedef enum { ZSTD_tfp_forCCtx, ZSTD_tfp_forCDict } ZSTD_tableFillPurpose_e;549550typedef enum {551ZSTD_noDict = 0,552ZSTD_extDict = 1,553ZSTD_dictMatchState = 2,554ZSTD_dedicatedDictSearch = 3555} ZSTD_dictMode_e;556557typedef enum {558ZSTD_cpm_noAttachDict = 0, /* Compression with ZSTD_noDict or ZSTD_extDict.559* In this mode we use both the srcSize and the dictSize560* when selecting and adjusting parameters.561*/562ZSTD_cpm_attachDict = 1, /* Compression with ZSTD_dictMatchState or ZSTD_dedicatedDictSearch.563* In this mode we only take the srcSize into account when selecting564* and adjusting parameters.565*/566ZSTD_cpm_createCDict = 2, /* Creating a CDict.567* In this mode we take both the source size and the dictionary size568* into account when selecting and adjusting the parameters.569*/570ZSTD_cpm_unknown = 3 /* ZSTD_getCParams, ZSTD_getParams, ZSTD_adjustParams.571* We don't know what these parameters are for. We default to the legacy572* behavior of taking both the source size and the dict size into account573* when selecting and adjusting parameters.574*/575} ZSTD_CParamMode_e;576577typedef size_t (*ZSTD_BlockCompressor_f) (578ZSTD_MatchState_t* bs, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],579void const* src, size_t srcSize);580ZSTD_BlockCompressor_f ZSTD_selectBlockCompressor(ZSTD_strategy strat, ZSTD_ParamSwitch_e rowMatchfinderMode, ZSTD_dictMode_e dictMode);581582583MEM_STATIC U32 ZSTD_LLcode(U32 litLength)584{585static const BYTE LL_Code[64] = { 0, 1, 2, 3, 4, 5, 6, 7,5868, 9, 10, 11, 12, 13, 14, 15,58716, 16, 17, 17, 18, 18, 19, 19,58820, 20, 20, 20, 21, 21, 21, 21,58922, 22, 22, 22, 22, 22, 22, 22,59023, 23, 23, 23, 23, 23, 23, 23,59124, 24, 24, 24, 24, 24, 24, 24,59224, 24, 24, 24, 24, 24, 24, 24 };593static const U32 LL_deltaCode = 19;594return (litLength > 63) ? ZSTD_highbit32(litLength) + LL_deltaCode : LL_Code[litLength];595}596597/* ZSTD_MLcode() :598* note : mlBase = matchLength - MINMATCH;599* because it's the format it's stored in seqStore->sequences */600MEM_STATIC U32 ZSTD_MLcode(U32 mlBase)601{602static const BYTE ML_Code[128] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,60316, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,60432, 32, 33, 33, 34, 34, 35, 35, 36, 36, 36, 36, 37, 37, 37, 37,60538, 38, 38, 38, 38, 38, 38, 38, 39, 39, 39, 39, 39, 39, 39, 39,60640, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40,60741, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41,60842, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42,60942, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42 };610static const U32 ML_deltaCode = 36;611return (mlBase > 127) ? ZSTD_highbit32(mlBase) + ML_deltaCode : ML_Code[mlBase];612}613614/* ZSTD_cParam_withinBounds:615* @return 1 if value is within cParam bounds,616* 0 otherwise */617MEM_STATIC int ZSTD_cParam_withinBounds(ZSTD_cParameter cParam, int value)618{619ZSTD_bounds const bounds = ZSTD_cParam_getBounds(cParam);620if (ZSTD_isError(bounds.error)) return 0;621if (value < bounds.lowerBound) return 0;622if (value > bounds.upperBound) return 0;623return 1;624}625626/* ZSTD_selectAddr:627* @return index >= lowLimit ? candidate : backup,628* tries to force branchless codegen. */629MEM_STATIC const BYTE*630ZSTD_selectAddr(U32 index, U32 lowLimit, const BYTE* candidate, const BYTE* backup)631{632#if defined(__GNUC__) && defined(__x86_64__)633__asm__ (634"cmp %1, %2\n"635"cmova %3, %0\n"636: "+r"(candidate)637: "r"(index), "r"(lowLimit), "r"(backup)638);639return candidate;640#else641return index >= lowLimit ? candidate : backup;642#endif643}644645/* ZSTD_noCompressBlock() :646* Writes uncompressed block to dst buffer from given src.647* Returns the size of the block */648MEM_STATIC size_t649ZSTD_noCompressBlock(void* dst, size_t dstCapacity, const void* src, size_t srcSize, U32 lastBlock)650{651U32 const cBlockHeader24 = lastBlock + (((U32)bt_raw)<<1) + (U32)(srcSize << 3);652DEBUGLOG(5, "ZSTD_noCompressBlock (srcSize=%zu, dstCapacity=%zu)", srcSize, dstCapacity);653RETURN_ERROR_IF(srcSize + ZSTD_blockHeaderSize > dstCapacity,654dstSize_tooSmall, "dst buf too small for uncompressed block");655MEM_writeLE24(dst, cBlockHeader24);656ZSTD_memcpy((BYTE*)dst + ZSTD_blockHeaderSize, src, srcSize);657return ZSTD_blockHeaderSize + srcSize;658}659660MEM_STATIC size_t661ZSTD_rleCompressBlock(void* dst, size_t dstCapacity, BYTE src, size_t srcSize, U32 lastBlock)662{663BYTE* const op = (BYTE*)dst;664U32 const cBlockHeader = lastBlock + (((U32)bt_rle)<<1) + (U32)(srcSize << 3);665RETURN_ERROR_IF(dstCapacity < 4, dstSize_tooSmall, "");666MEM_writeLE24(op, cBlockHeader);667op[3] = src;668return 4;669}670671672/* ZSTD_minGain() :673* minimum compression required674* to generate a compress block or a compressed literals section.675* note : use same formula for both situations */676MEM_STATIC size_t ZSTD_minGain(size_t srcSize, ZSTD_strategy strat)677{678U32 const minlog = (strat>=ZSTD_btultra) ? (U32)(strat) - 1 : 6;679ZSTD_STATIC_ASSERT(ZSTD_btultra == 8);680assert(ZSTD_cParam_withinBounds(ZSTD_c_strategy, (int)strat));681return (srcSize >> minlog) + 2;682}683684MEM_STATIC int ZSTD_literalsCompressionIsDisabled(const ZSTD_CCtx_params* cctxParams)685{686switch (cctxParams->literalCompressionMode) {687case ZSTD_ps_enable:688return 0;689case ZSTD_ps_disable:690return 1;691default:692assert(0 /* impossible: pre-validated */);693ZSTD_FALLTHROUGH;694case ZSTD_ps_auto:695return (cctxParams->cParams.strategy == ZSTD_fast) && (cctxParams->cParams.targetLength > 0);696}697}698699/*! ZSTD_safecopyLiterals() :700* memcpy() function that won't read beyond more than WILDCOPY_OVERLENGTH bytes past ilimit_w.701* Only called when the sequence ends past ilimit_w, so it only needs to be optimized for single702* large copies.703*/704static void705ZSTD_safecopyLiterals(BYTE* op, BYTE const* ip, BYTE const* const iend, BYTE const* ilimit_w)706{707assert(iend > ilimit_w);708if (ip <= ilimit_w) {709ZSTD_wildcopy(op, ip, ilimit_w - ip, ZSTD_no_overlap);710op += ilimit_w - ip;711ip = ilimit_w;712}713while (ip < iend) *op++ = *ip++;714}715716717#define REPCODE1_TO_OFFBASE REPCODE_TO_OFFBASE(1)718#define REPCODE2_TO_OFFBASE REPCODE_TO_OFFBASE(2)719#define REPCODE3_TO_OFFBASE REPCODE_TO_OFFBASE(3)720#define REPCODE_TO_OFFBASE(r) (assert((r)>=1), assert((r)<=ZSTD_REP_NUM), (r)) /* accepts IDs 1,2,3 */721#define OFFSET_TO_OFFBASE(o) (assert((o)>0), o + ZSTD_REP_NUM)722#define OFFBASE_IS_OFFSET(o) ((o) > ZSTD_REP_NUM)723#define OFFBASE_IS_REPCODE(o) ( 1 <= (o) && (o) <= ZSTD_REP_NUM)724#define OFFBASE_TO_OFFSET(o) (assert(OFFBASE_IS_OFFSET(o)), (o) - ZSTD_REP_NUM)725#define OFFBASE_TO_REPCODE(o) (assert(OFFBASE_IS_REPCODE(o)), (o)) /* returns ID 1,2,3 */726727/*! ZSTD_storeSeqOnly() :728* Store a sequence (litlen, litPtr, offBase and matchLength) into SeqStore_t.729* Literals themselves are not copied, but @litPtr is updated.730* @offBase : Users should employ macros REPCODE_TO_OFFBASE() and OFFSET_TO_OFFBASE().731* @matchLength : must be >= MINMATCH732*/733HINT_INLINE UNUSED_ATTR void734ZSTD_storeSeqOnly(SeqStore_t* seqStorePtr,735size_t litLength,736U32 offBase,737size_t matchLength)738{739assert((size_t)(seqStorePtr->sequences - seqStorePtr->sequencesStart) < seqStorePtr->maxNbSeq);740741/* literal Length */742assert(litLength <= ZSTD_BLOCKSIZE_MAX);743if (UNLIKELY(litLength>0xFFFF)) {744assert(seqStorePtr->longLengthType == ZSTD_llt_none); /* there can only be a single long length */745seqStorePtr->longLengthType = ZSTD_llt_literalLength;746seqStorePtr->longLengthPos = (U32)(seqStorePtr->sequences - seqStorePtr->sequencesStart);747}748seqStorePtr->sequences[0].litLength = (U16)litLength;749750/* match offset */751seqStorePtr->sequences[0].offBase = offBase;752753/* match Length */754assert(matchLength <= ZSTD_BLOCKSIZE_MAX);755assert(matchLength >= MINMATCH);756{ size_t const mlBase = matchLength - MINMATCH;757if (UNLIKELY(mlBase>0xFFFF)) {758assert(seqStorePtr->longLengthType == ZSTD_llt_none); /* there can only be a single long length */759seqStorePtr->longLengthType = ZSTD_llt_matchLength;760seqStorePtr->longLengthPos = (U32)(seqStorePtr->sequences - seqStorePtr->sequencesStart);761}762seqStorePtr->sequences[0].mlBase = (U16)mlBase;763}764765seqStorePtr->sequences++;766}767768/*! ZSTD_storeSeq() :769* Store a sequence (litlen, litPtr, offBase and matchLength) into SeqStore_t.770* @offBase : Users should employ macros REPCODE_TO_OFFBASE() and OFFSET_TO_OFFBASE().771* @matchLength : must be >= MINMATCH772* Allowed to over-read literals up to litLimit.773*/774HINT_INLINE UNUSED_ATTR void775ZSTD_storeSeq(SeqStore_t* seqStorePtr,776size_t litLength, const BYTE* literals, const BYTE* litLimit,777U32 offBase,778size_t matchLength)779{780BYTE const* const litLimit_w = litLimit - WILDCOPY_OVERLENGTH;781BYTE const* const litEnd = literals + litLength;782#if defined(DEBUGLEVEL) && (DEBUGLEVEL >= 6)783static const BYTE* g_start = NULL;784if (g_start==NULL) g_start = (const BYTE*)literals; /* note : index only works for compression within a single segment */785{ U32 const pos = (U32)((const BYTE*)literals - g_start);786DEBUGLOG(6, "Cpos%7u :%3u literals, match%4u bytes at offBase%7u",787pos, (U32)litLength, (U32)matchLength, (U32)offBase);788}789#endif790assert((size_t)(seqStorePtr->sequences - seqStorePtr->sequencesStart) < seqStorePtr->maxNbSeq);791/* copy Literals */792assert(seqStorePtr->maxNbLit <= 128 KB);793assert(seqStorePtr->lit + litLength <= seqStorePtr->litStart + seqStorePtr->maxNbLit);794assert(literals + litLength <= litLimit);795if (litEnd <= litLimit_w) {796/* Common case we can use wildcopy.797* First copy 16 bytes, because literals are likely short.798*/799ZSTD_STATIC_ASSERT(WILDCOPY_OVERLENGTH >= 16);800ZSTD_copy16(seqStorePtr->lit, literals);801if (litLength > 16) {802ZSTD_wildcopy(seqStorePtr->lit+16, literals+16, (ptrdiff_t)litLength-16, ZSTD_no_overlap);803}804} else {805ZSTD_safecopyLiterals(seqStorePtr->lit, literals, litEnd, litLimit_w);806}807seqStorePtr->lit += litLength;808809ZSTD_storeSeqOnly(seqStorePtr, litLength, offBase, matchLength);810}811812/* ZSTD_updateRep() :813* updates in-place @rep (array of repeat offsets)814* @offBase : sum-type, using numeric representation of ZSTD_storeSeq()815*/816MEM_STATIC void817ZSTD_updateRep(U32 rep[ZSTD_REP_NUM], U32 const offBase, U32 const ll0)818{819if (OFFBASE_IS_OFFSET(offBase)) { /* full offset */820rep[2] = rep[1];821rep[1] = rep[0];822rep[0] = OFFBASE_TO_OFFSET(offBase);823} else { /* repcode */824U32 const repCode = OFFBASE_TO_REPCODE(offBase) - 1 + ll0;825if (repCode > 0) { /* note : if repCode==0, no change */826U32 const currentOffset = (repCode==ZSTD_REP_NUM) ? (rep[0] - 1) : rep[repCode];827rep[2] = (repCode >= 2) ? rep[1] : rep[2];828rep[1] = rep[0];829rep[0] = currentOffset;830} else { /* repCode == 0 */831/* nothing to do */832}833}834}835836typedef struct repcodes_s {837U32 rep[3];838} Repcodes_t;839840MEM_STATIC Repcodes_t841ZSTD_newRep(U32 const rep[ZSTD_REP_NUM], U32 const offBase, U32 const ll0)842{843Repcodes_t newReps;844ZSTD_memcpy(&newReps, rep, sizeof(newReps));845ZSTD_updateRep(newReps.rep, offBase, ll0);846return newReps;847}848849850/*-*************************************851* Match length counter852***************************************/853MEM_STATIC size_t ZSTD_count(const BYTE* pIn, const BYTE* pMatch, const BYTE* const pInLimit)854{855const BYTE* const pStart = pIn;856const BYTE* const pInLoopLimit = pInLimit - (sizeof(size_t)-1);857858if (pIn < pInLoopLimit) {859{ size_t const diff = MEM_readST(pMatch) ^ MEM_readST(pIn);860if (diff) return ZSTD_NbCommonBytes(diff); }861pIn+=sizeof(size_t); pMatch+=sizeof(size_t);862while (pIn < pInLoopLimit) {863size_t const diff = MEM_readST(pMatch) ^ MEM_readST(pIn);864if (!diff) { pIn+=sizeof(size_t); pMatch+=sizeof(size_t); continue; }865pIn += ZSTD_NbCommonBytes(diff);866return (size_t)(pIn - pStart);867} }868if (MEM_64bits() && (pIn<(pInLimit-3)) && (MEM_read32(pMatch) == MEM_read32(pIn))) { pIn+=4; pMatch+=4; }869if ((pIn<(pInLimit-1)) && (MEM_read16(pMatch) == MEM_read16(pIn))) { pIn+=2; pMatch+=2; }870if ((pIn<pInLimit) && (*pMatch == *pIn)) pIn++;871return (size_t)(pIn - pStart);872}873874/** ZSTD_count_2segments() :875* can count match length with `ip` & `match` in 2 different segments.876* convention : on reaching mEnd, match count continue starting from iStart877*/878MEM_STATIC size_t879ZSTD_count_2segments(const BYTE* ip, const BYTE* match,880const BYTE* iEnd, const BYTE* mEnd, const BYTE* iStart)881{882const BYTE* const vEnd = MIN( ip + (mEnd - match), iEnd);883size_t const matchLength = ZSTD_count(ip, match, vEnd);884if (match + matchLength != mEnd) return matchLength;885DEBUGLOG(7, "ZSTD_count_2segments: found a 2-parts match (current length==%zu)", matchLength);886DEBUGLOG(7, "distance from match beginning to end dictionary = %i", (int)(mEnd - match));887DEBUGLOG(7, "distance from current pos to end buffer = %i", (int)(iEnd - ip));888DEBUGLOG(7, "next byte : ip==%02X, istart==%02X", ip[matchLength], *iStart);889DEBUGLOG(7, "final match length = %zu", matchLength + ZSTD_count(ip+matchLength, iStart, iEnd));890return matchLength + ZSTD_count(ip+matchLength, iStart, iEnd);891}892893894/*-*************************************895* Hashes896***************************************/897static const U32 prime3bytes = 506832829U;898static U32 ZSTD_hash3(U32 u, U32 h, U32 s) { assert(h <= 32); return (((u << (32-24)) * prime3bytes) ^ s) >> (32-h) ; }899MEM_STATIC size_t ZSTD_hash3Ptr(const void* ptr, U32 h) { return ZSTD_hash3(MEM_readLE32(ptr), h, 0); } /* only in zstd_opt.h */900MEM_STATIC size_t ZSTD_hash3PtrS(const void* ptr, U32 h, U32 s) { return ZSTD_hash3(MEM_readLE32(ptr), h, s); }901902static const U32 prime4bytes = 2654435761U;903static U32 ZSTD_hash4(U32 u, U32 h, U32 s) { assert(h <= 32); return ((u * prime4bytes) ^ s) >> (32-h) ; }904static size_t ZSTD_hash4Ptr(const void* ptr, U32 h) { return ZSTD_hash4(MEM_readLE32(ptr), h, 0); }905static size_t ZSTD_hash4PtrS(const void* ptr, U32 h, U32 s) { return ZSTD_hash4(MEM_readLE32(ptr), h, s); }906907static const U64 prime5bytes = 889523592379ULL;908static size_t ZSTD_hash5(U64 u, U32 h, U64 s) { assert(h <= 64); return (size_t)((((u << (64-40)) * prime5bytes) ^ s) >> (64-h)) ; }909static size_t ZSTD_hash5Ptr(const void* p, U32 h) { return ZSTD_hash5(MEM_readLE64(p), h, 0); }910static size_t ZSTD_hash5PtrS(const void* p, U32 h, U64 s) { return ZSTD_hash5(MEM_readLE64(p), h, s); }911912static const U64 prime6bytes = 227718039650203ULL;913static size_t ZSTD_hash6(U64 u, U32 h, U64 s) { assert(h <= 64); return (size_t)((((u << (64-48)) * prime6bytes) ^ s) >> (64-h)) ; }914static size_t ZSTD_hash6Ptr(const void* p, U32 h) { return ZSTD_hash6(MEM_readLE64(p), h, 0); }915static size_t ZSTD_hash6PtrS(const void* p, U32 h, U64 s) { return ZSTD_hash6(MEM_readLE64(p), h, s); }916917static const U64 prime7bytes = 58295818150454627ULL;918static size_t ZSTD_hash7(U64 u, U32 h, U64 s) { assert(h <= 64); return (size_t)((((u << (64-56)) * prime7bytes) ^ s) >> (64-h)) ; }919static size_t ZSTD_hash7Ptr(const void* p, U32 h) { return ZSTD_hash7(MEM_readLE64(p), h, 0); }920static size_t ZSTD_hash7PtrS(const void* p, U32 h, U64 s) { return ZSTD_hash7(MEM_readLE64(p), h, s); }921922static const U64 prime8bytes = 0xCF1BBCDCB7A56463ULL;923static size_t ZSTD_hash8(U64 u, U32 h, U64 s) { assert(h <= 64); return (size_t)((((u) * prime8bytes) ^ s) >> (64-h)) ; }924static size_t ZSTD_hash8Ptr(const void* p, U32 h) { return ZSTD_hash8(MEM_readLE64(p), h, 0); }925static size_t ZSTD_hash8PtrS(const void* p, U32 h, U64 s) { return ZSTD_hash8(MEM_readLE64(p), h, s); }926927928MEM_STATIC FORCE_INLINE_ATTR929size_t ZSTD_hashPtr(const void* p, U32 hBits, U32 mls)930{931/* Although some of these hashes do support hBits up to 64, some do not.932* To be on the safe side, always avoid hBits > 32. */933assert(hBits <= 32);934935switch(mls)936{937default:938case 4: return ZSTD_hash4Ptr(p, hBits);939case 5: return ZSTD_hash5Ptr(p, hBits);940case 6: return ZSTD_hash6Ptr(p, hBits);941case 7: return ZSTD_hash7Ptr(p, hBits);942case 8: return ZSTD_hash8Ptr(p, hBits);943}944}945946MEM_STATIC FORCE_INLINE_ATTR947size_t ZSTD_hashPtrSalted(const void* p, U32 hBits, U32 mls, const U64 hashSalt) {948/* Although some of these hashes do support hBits up to 64, some do not.949* To be on the safe side, always avoid hBits > 32. */950assert(hBits <= 32);951952switch(mls)953{954default:955case 4: return ZSTD_hash4PtrS(p, hBits, (U32)hashSalt);956case 5: return ZSTD_hash5PtrS(p, hBits, hashSalt);957case 6: return ZSTD_hash6PtrS(p, hBits, hashSalt);958case 7: return ZSTD_hash7PtrS(p, hBits, hashSalt);959case 8: return ZSTD_hash8PtrS(p, hBits, hashSalt);960}961}962963964/** ZSTD_ipow() :965* Return base^exponent.966*/967static U64 ZSTD_ipow(U64 base, U64 exponent)968{969U64 power = 1;970while (exponent) {971if (exponent & 1) power *= base;972exponent >>= 1;973base *= base;974}975return power;976}977978#define ZSTD_ROLL_HASH_CHAR_OFFSET 10979980/** ZSTD_rollingHash_append() :981* Add the buffer to the hash value.982*/983static U64 ZSTD_rollingHash_append(U64 hash, void const* buf, size_t size)984{985BYTE const* istart = (BYTE const*)buf;986size_t pos;987for (pos = 0; pos < size; ++pos) {988hash *= prime8bytes;989hash += istart[pos] + ZSTD_ROLL_HASH_CHAR_OFFSET;990}991return hash;992}993994/** ZSTD_rollingHash_compute() :995* Compute the rolling hash value of the buffer.996*/997MEM_STATIC U64 ZSTD_rollingHash_compute(void const* buf, size_t size)998{999return ZSTD_rollingHash_append(0, buf, size);1000}10011002/** ZSTD_rollingHash_primePower() :1003* Compute the primePower to be passed to ZSTD_rollingHash_rotate() for a hash1004* over a window of length bytes.1005*/1006MEM_STATIC U64 ZSTD_rollingHash_primePower(U32 length)1007{1008return ZSTD_ipow(prime8bytes, length - 1);1009}10101011/** ZSTD_rollingHash_rotate() :1012* Rotate the rolling hash by one byte.1013*/1014MEM_STATIC U64 ZSTD_rollingHash_rotate(U64 hash, BYTE toRemove, BYTE toAdd, U64 primePower)1015{1016hash -= (toRemove + ZSTD_ROLL_HASH_CHAR_OFFSET) * primePower;1017hash *= prime8bytes;1018hash += toAdd + ZSTD_ROLL_HASH_CHAR_OFFSET;1019return hash;1020}10211022/*-*************************************1023* Round buffer management1024***************************************/1025/* Max @current value allowed:1026* In 32-bit mode: we want to avoid crossing the 2 GB limit,1027* reducing risks of side effects in case of signed operations on indexes.1028* In 64-bit mode: we want to ensure that adding the maximum job size (512 MB)1029* doesn't overflow U32 index capacity (4 GB) */1030#define ZSTD_CURRENT_MAX (MEM_64bits() ? 3500U MB : 2000U MB)1031/* Maximum chunk size before overflow correction needs to be called again */1032#define ZSTD_CHUNKSIZE_MAX \1033( ((U32)-1) /* Maximum ending current index */ \1034- ZSTD_CURRENT_MAX) /* Maximum beginning lowLimit */10351036/**1037* ZSTD_window_clear():1038* Clears the window containing the history by simply setting it to empty.1039*/1040MEM_STATIC void ZSTD_window_clear(ZSTD_window_t* window)1041{1042size_t const endT = (size_t)(window->nextSrc - window->base);1043U32 const end = (U32)endT;10441045window->lowLimit = end;1046window->dictLimit = end;1047}10481049MEM_STATIC U32 ZSTD_window_isEmpty(ZSTD_window_t const window)1050{1051return window.dictLimit == ZSTD_WINDOW_START_INDEX &&1052window.lowLimit == ZSTD_WINDOW_START_INDEX &&1053(window.nextSrc - window.base) == ZSTD_WINDOW_START_INDEX;1054}10551056/**1057* ZSTD_window_hasExtDict():1058* Returns non-zero if the window has a non-empty extDict.1059*/1060MEM_STATIC U32 ZSTD_window_hasExtDict(ZSTD_window_t const window)1061{1062return window.lowLimit < window.dictLimit;1063}10641065/**1066* ZSTD_matchState_dictMode():1067* Inspects the provided matchState and figures out what dictMode should be1068* passed to the compressor.1069*/1070MEM_STATIC ZSTD_dictMode_e ZSTD_matchState_dictMode(const ZSTD_MatchState_t *ms)1071{1072return ZSTD_window_hasExtDict(ms->window) ?1073ZSTD_extDict :1074ms->dictMatchState != NULL ?1075(ms->dictMatchState->dedicatedDictSearch ? ZSTD_dedicatedDictSearch : ZSTD_dictMatchState) :1076ZSTD_noDict;1077}10781079/* Defining this macro to non-zero tells zstd to run the overflow correction1080* code much more frequently. This is very inefficient, and should only be1081* used for tests and fuzzers.1082*/1083#ifndef ZSTD_WINDOW_OVERFLOW_CORRECT_FREQUENTLY1084# ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION1085# define ZSTD_WINDOW_OVERFLOW_CORRECT_FREQUENTLY 11086# else1087# define ZSTD_WINDOW_OVERFLOW_CORRECT_FREQUENTLY 01088# endif1089#endif10901091/**1092* ZSTD_window_canOverflowCorrect():1093* Returns non-zero if the indices are large enough for overflow correction1094* to work correctly without impacting compression ratio.1095*/1096MEM_STATIC U32 ZSTD_window_canOverflowCorrect(ZSTD_window_t const window,1097U32 cycleLog,1098U32 maxDist,1099U32 loadedDictEnd,1100void const* src)1101{1102U32 const cycleSize = 1u << cycleLog;1103U32 const curr = (U32)((BYTE const*)src - window.base);1104U32 const minIndexToOverflowCorrect = cycleSize1105+ MAX(maxDist, cycleSize)1106+ ZSTD_WINDOW_START_INDEX;11071108/* Adjust the min index to backoff the overflow correction frequency,1109* so we don't waste too much CPU in overflow correction. If this1110* computation overflows we don't really care, we just need to make1111* sure it is at least minIndexToOverflowCorrect.1112*/1113U32 const adjustment = window.nbOverflowCorrections + 1;1114U32 const adjustedIndex = MAX(minIndexToOverflowCorrect * adjustment,1115minIndexToOverflowCorrect);1116U32 const indexLargeEnough = curr > adjustedIndex;11171118/* Only overflow correct early if the dictionary is invalidated already,1119* so we don't hurt compression ratio.1120*/1121U32 const dictionaryInvalidated = curr > maxDist + loadedDictEnd;11221123return indexLargeEnough && dictionaryInvalidated;1124}11251126/**1127* ZSTD_window_needOverflowCorrection():1128* Returns non-zero if the indices are getting too large and need overflow1129* protection.1130*/1131MEM_STATIC U32 ZSTD_window_needOverflowCorrection(ZSTD_window_t const window,1132U32 cycleLog,1133U32 maxDist,1134U32 loadedDictEnd,1135void const* src,1136void const* srcEnd)1137{1138U32 const curr = (U32)((BYTE const*)srcEnd - window.base);1139if (ZSTD_WINDOW_OVERFLOW_CORRECT_FREQUENTLY) {1140if (ZSTD_window_canOverflowCorrect(window, cycleLog, maxDist, loadedDictEnd, src)) {1141return 1;1142}1143}1144return curr > ZSTD_CURRENT_MAX;1145}11461147/**1148* ZSTD_window_correctOverflow():1149* Reduces the indices to protect from index overflow.1150* Returns the correction made to the indices, which must be applied to every1151* stored index.1152*1153* The least significant cycleLog bits of the indices must remain the same,1154* which may be 0. Every index up to maxDist in the past must be valid.1155*/1156MEM_STATIC1157ZSTD_ALLOW_POINTER_OVERFLOW_ATTR1158U32 ZSTD_window_correctOverflow(ZSTD_window_t* window, U32 cycleLog,1159U32 maxDist, void const* src)1160{1161/* preemptive overflow correction:1162* 1. correction is large enough:1163* lowLimit > (3<<29) ==> current > 3<<29 + 1<<windowLog1164* 1<<windowLog <= newCurrent < 1<<chainLog + 1<<windowLog1165*1166* current - newCurrent1167* > (3<<29 + 1<<windowLog) - (1<<windowLog + 1<<chainLog)1168* > (3<<29) - (1<<chainLog)1169* > (3<<29) - (1<<30) (NOTE: chainLog <= 30)1170* > 1<<291171*1172* 2. (ip+ZSTD_CHUNKSIZE_MAX - cctx->base) doesn't overflow:1173* After correction, current is less than (1<<chainLog + 1<<windowLog).1174* In 64-bit mode we are safe, because we have 64-bit ptrdiff_t.1175* In 32-bit mode we are safe, because (chainLog <= 29), so1176* ip+ZSTD_CHUNKSIZE_MAX - cctx->base < 1<<32.1177* 3. (cctx->lowLimit + 1<<windowLog) < 1<<32:1178* windowLog <= 31 ==> 3<<29 + 1<<windowLog < 7<<29 < 1<<32.1179*/1180U32 const cycleSize = 1u << cycleLog;1181U32 const cycleMask = cycleSize - 1;1182U32 const curr = (U32)((BYTE const*)src - window->base);1183U32 const currentCycle = curr & cycleMask;1184/* Ensure newCurrent - maxDist >= ZSTD_WINDOW_START_INDEX. */1185U32 const currentCycleCorrection = currentCycle < ZSTD_WINDOW_START_INDEX1186? MAX(cycleSize, ZSTD_WINDOW_START_INDEX)1187: 0;1188U32 const newCurrent = currentCycle1189+ currentCycleCorrection1190+ MAX(maxDist, cycleSize);1191U32 const correction = curr - newCurrent;1192/* maxDist must be a power of two so that:1193* (newCurrent & cycleMask) == (curr & cycleMask)1194* This is required to not corrupt the chains / binary tree.1195*/1196assert((maxDist & (maxDist - 1)) == 0);1197assert((curr & cycleMask) == (newCurrent & cycleMask));1198assert(curr > newCurrent);1199if (!ZSTD_WINDOW_OVERFLOW_CORRECT_FREQUENTLY) {1200/* Loose bound, should be around 1<<29 (see above) */1201assert(correction > 1<<28);1202}12031204window->base += correction;1205window->dictBase += correction;1206if (window->lowLimit < correction + ZSTD_WINDOW_START_INDEX) {1207window->lowLimit = ZSTD_WINDOW_START_INDEX;1208} else {1209window->lowLimit -= correction;1210}1211if (window->dictLimit < correction + ZSTD_WINDOW_START_INDEX) {1212window->dictLimit = ZSTD_WINDOW_START_INDEX;1213} else {1214window->dictLimit -= correction;1215}12161217/* Ensure we can still reference the full window. */1218assert(newCurrent >= maxDist);1219assert(newCurrent - maxDist >= ZSTD_WINDOW_START_INDEX);1220/* Ensure that lowLimit and dictLimit didn't underflow. */1221assert(window->lowLimit <= newCurrent);1222assert(window->dictLimit <= newCurrent);12231224++window->nbOverflowCorrections;12251226DEBUGLOG(4, "Correction of 0x%x bytes to lowLimit=0x%x", correction,1227window->lowLimit);1228return correction;1229}12301231/**1232* ZSTD_window_enforceMaxDist():1233* Updates lowLimit so that:1234* (srcEnd - base) - lowLimit == maxDist + loadedDictEnd1235*1236* It ensures index is valid as long as index >= lowLimit.1237* This must be called before a block compression call.1238*1239* loadedDictEnd is only defined if a dictionary is in use for current compression.1240* As the name implies, loadedDictEnd represents the index at end of dictionary.1241* The value lies within context's referential, it can be directly compared to blockEndIdx.1242*1243* If loadedDictEndPtr is NULL, no dictionary is in use, and we use loadedDictEnd == 0.1244* If loadedDictEndPtr is not NULL, we set it to zero after updating lowLimit.1245* This is because dictionaries are allowed to be referenced fully1246* as long as the last byte of the dictionary is in the window.1247* Once input has progressed beyond window size, dictionary cannot be referenced anymore.1248*1249* In normal dict mode, the dictionary lies between lowLimit and dictLimit.1250* In dictMatchState mode, lowLimit and dictLimit are the same,1251* and the dictionary is below them.1252* forceWindow and dictMatchState are therefore incompatible.1253*/1254MEM_STATIC void1255ZSTD_window_enforceMaxDist(ZSTD_window_t* window,1256const void* blockEnd,1257U32 maxDist,1258U32* loadedDictEndPtr,1259const ZSTD_MatchState_t** dictMatchStatePtr)1260{1261U32 const blockEndIdx = (U32)((BYTE const*)blockEnd - window->base);1262U32 const loadedDictEnd = (loadedDictEndPtr != NULL) ? *loadedDictEndPtr : 0;1263DEBUGLOG(5, "ZSTD_window_enforceMaxDist: blockEndIdx=%u, maxDist=%u, loadedDictEnd=%u",1264(unsigned)blockEndIdx, (unsigned)maxDist, (unsigned)loadedDictEnd);12651266/* - When there is no dictionary : loadedDictEnd == 0.1267In which case, the test (blockEndIdx > maxDist) is merely to avoid1268overflowing next operation `newLowLimit = blockEndIdx - maxDist`.1269- When there is a standard dictionary :1270Index referential is copied from the dictionary,1271which means it starts from 0.1272In which case, loadedDictEnd == dictSize,1273and it makes sense to compare `blockEndIdx > maxDist + dictSize`1274since `blockEndIdx` also starts from zero.1275- When there is an attached dictionary :1276loadedDictEnd is expressed within the referential of the context,1277so it can be directly compared against blockEndIdx.1278*/1279if (blockEndIdx > maxDist + loadedDictEnd) {1280U32 const newLowLimit = blockEndIdx - maxDist;1281if (window->lowLimit < newLowLimit) window->lowLimit = newLowLimit;1282if (window->dictLimit < window->lowLimit) {1283DEBUGLOG(5, "Update dictLimit to match lowLimit, from %u to %u",1284(unsigned)window->dictLimit, (unsigned)window->lowLimit);1285window->dictLimit = window->lowLimit;1286}1287/* On reaching window size, dictionaries are invalidated */1288if (loadedDictEndPtr) *loadedDictEndPtr = 0;1289if (dictMatchStatePtr) *dictMatchStatePtr = NULL;1290}1291}12921293/* Similar to ZSTD_window_enforceMaxDist(),1294* but only invalidates dictionary1295* when input progresses beyond window size.1296* assumption : loadedDictEndPtr and dictMatchStatePtr are valid (non NULL)1297* loadedDictEnd uses same referential as window->base1298* maxDist is the window size */1299MEM_STATIC void1300ZSTD_checkDictValidity(const ZSTD_window_t* window,1301const void* blockEnd,1302U32 maxDist,1303U32* loadedDictEndPtr,1304const ZSTD_MatchState_t** dictMatchStatePtr)1305{1306assert(loadedDictEndPtr != NULL);1307assert(dictMatchStatePtr != NULL);1308{ U32 const blockEndIdx = (U32)((BYTE const*)blockEnd - window->base);1309U32 const loadedDictEnd = *loadedDictEndPtr;1310DEBUGLOG(5, "ZSTD_checkDictValidity: blockEndIdx=%u, maxDist=%u, loadedDictEnd=%u",1311(unsigned)blockEndIdx, (unsigned)maxDist, (unsigned)loadedDictEnd);1312assert(blockEndIdx >= loadedDictEnd);13131314if (blockEndIdx > loadedDictEnd + maxDist || loadedDictEnd != window->dictLimit) {1315/* On reaching window size, dictionaries are invalidated.1316* For simplification, if window size is reached anywhere within next block,1317* the dictionary is invalidated for the full block.1318*1319* We also have to invalidate the dictionary if ZSTD_window_update() has detected1320* non-contiguous segments, which means that loadedDictEnd != window->dictLimit.1321* loadedDictEnd may be 0, if forceWindow is true, but in that case we never use1322* dictMatchState, so setting it to NULL is not a problem.1323*/1324DEBUGLOG(6, "invalidating dictionary for current block (distance > windowSize)");1325*loadedDictEndPtr = 0;1326*dictMatchStatePtr = NULL;1327} else {1328if (*loadedDictEndPtr != 0) {1329DEBUGLOG(6, "dictionary considered valid for current block");1330} } }1331}13321333MEM_STATIC void ZSTD_window_init(ZSTD_window_t* window) {1334ZSTD_memset(window, 0, sizeof(*window));1335window->base = (BYTE const*)" ";1336window->dictBase = (BYTE const*)" ";1337ZSTD_STATIC_ASSERT(ZSTD_DUBT_UNSORTED_MARK < ZSTD_WINDOW_START_INDEX); /* Start above ZSTD_DUBT_UNSORTED_MARK */1338window->dictLimit = ZSTD_WINDOW_START_INDEX; /* start from >0, so that 1st position is valid */1339window->lowLimit = ZSTD_WINDOW_START_INDEX; /* it ensures first and later CCtx usages compress the same */1340window->nextSrc = window->base + ZSTD_WINDOW_START_INDEX; /* see issue #1241 */1341window->nbOverflowCorrections = 0;1342}13431344/**1345* ZSTD_window_update():1346* Updates the window by appending [src, src + srcSize) to the window.1347* If it is not contiguous, the current prefix becomes the extDict, and we1348* forget about the extDict. Handles overlap of the prefix and extDict.1349* Returns non-zero if the segment is contiguous.1350*/1351MEM_STATIC1352ZSTD_ALLOW_POINTER_OVERFLOW_ATTR1353U32 ZSTD_window_update(ZSTD_window_t* window,1354const void* src, size_t srcSize,1355int forceNonContiguous)1356{1357BYTE const* const ip = (BYTE const*)src;1358U32 contiguous = 1;1359DEBUGLOG(5, "ZSTD_window_update");1360if (srcSize == 0)1361return contiguous;1362assert(window->base != NULL);1363assert(window->dictBase != NULL);1364/* Check if blocks follow each other */1365if (src != window->nextSrc || forceNonContiguous) {1366/* not contiguous */1367size_t const distanceFromBase = (size_t)(window->nextSrc - window->base);1368DEBUGLOG(5, "Non contiguous blocks, new segment starts at %u", window->dictLimit);1369window->lowLimit = window->dictLimit;1370assert(distanceFromBase == (size_t)(U32)distanceFromBase); /* should never overflow */1371window->dictLimit = (U32)distanceFromBase;1372window->dictBase = window->base;1373window->base = ip - distanceFromBase;1374/* ms->nextToUpdate = window->dictLimit; */1375if (window->dictLimit - window->lowLimit < HASH_READ_SIZE) window->lowLimit = window->dictLimit; /* too small extDict */1376contiguous = 0;1377}1378window->nextSrc = ip + srcSize;1379/* if input and dictionary overlap : reduce dictionary (area presumed modified by input) */1380if ( (ip+srcSize > window->dictBase + window->lowLimit)1381& (ip < window->dictBase + window->dictLimit)) {1382size_t const highInputIdx = (size_t)((ip + srcSize) - window->dictBase);1383U32 const lowLimitMax = (highInputIdx > (size_t)window->dictLimit) ? window->dictLimit : (U32)highInputIdx;1384assert(highInputIdx < UINT_MAX);1385window->lowLimit = lowLimitMax;1386DEBUGLOG(5, "Overlapping extDict and input : new lowLimit = %u", window->lowLimit);1387}1388return contiguous;1389}13901391/**1392* Returns the lowest allowed match index. It may either be in the ext-dict or the prefix.1393*/1394MEM_STATIC U32 ZSTD_getLowestMatchIndex(const ZSTD_MatchState_t* ms, U32 curr, unsigned windowLog)1395{1396U32 const maxDistance = 1U << windowLog;1397U32 const lowestValid = ms->window.lowLimit;1398U32 const withinWindow = (curr - lowestValid > maxDistance) ? curr - maxDistance : lowestValid;1399U32 const isDictionary = (ms->loadedDictEnd != 0);1400/* When using a dictionary the entire dictionary is valid if a single byte of the dictionary1401* is within the window. We invalidate the dictionary (and set loadedDictEnd to 0) when it isn't1402* valid for the entire block. So this check is sufficient to find the lowest valid match index.1403*/1404U32 const matchLowest = isDictionary ? lowestValid : withinWindow;1405return matchLowest;1406}14071408/**1409* Returns the lowest allowed match index in the prefix.1410*/1411MEM_STATIC U32 ZSTD_getLowestPrefixIndex(const ZSTD_MatchState_t* ms, U32 curr, unsigned windowLog)1412{1413U32 const maxDistance = 1U << windowLog;1414U32 const lowestValid = ms->window.dictLimit;1415U32 const withinWindow = (curr - lowestValid > maxDistance) ? curr - maxDistance : lowestValid;1416U32 const isDictionary = (ms->loadedDictEnd != 0);1417/* When computing the lowest prefix index we need to take the dictionary into account to handle1418* the edge case where the dictionary and the source are contiguous in memory.1419*/1420U32 const matchLowest = isDictionary ? lowestValid : withinWindow;1421return matchLowest;1422}14231424/* index_safety_check:1425* intentional underflow : ensure repIndex isn't overlapping dict + prefix1426* @return 1 if values are not overlapping,1427* 0 otherwise */1428MEM_STATIC int ZSTD_index_overlap_check(const U32 prefixLowestIndex, const U32 repIndex) {1429return ((U32)((prefixLowestIndex-1) - repIndex) >= 3);1430}143114321433/* debug functions */1434#if (DEBUGLEVEL>=2)14351436MEM_STATIC double ZSTD_fWeight(U32 rawStat)1437{1438U32 const fp_accuracy = 8;1439U32 const fp_multiplier = (1 << fp_accuracy);1440U32 const newStat = rawStat + 1;1441U32 const hb = ZSTD_highbit32(newStat);1442U32 const BWeight = hb * fp_multiplier;1443U32 const FWeight = (newStat << fp_accuracy) >> hb;1444U32 const weight = BWeight + FWeight;1445assert(hb + fp_accuracy < 31);1446return (double)weight / fp_multiplier;1447}14481449/* display a table content,1450* listing each element, its frequency, and its predicted bit cost */1451MEM_STATIC void ZSTD_debugTable(const U32* table, U32 max)1452{1453unsigned u, sum;1454for (u=0, sum=0; u<=max; u++) sum += table[u];1455DEBUGLOG(2, "total nb elts: %u", sum);1456for (u=0; u<=max; u++) {1457DEBUGLOG(2, "%2u: %5u (%.2f)",1458u, table[u], ZSTD_fWeight(sum) - ZSTD_fWeight(table[u]) );1459}1460}14611462#endif14631464/* Short Cache */14651466/* Normally, zstd matchfinders follow this flow:1467* 1. Compute hash at ip1468* 2. Load index from hashTable[hash]1469* 3. Check if *ip == *(base + index)1470* In dictionary compression, loading *(base + index) is often an L2 or even L3 miss.1471*1472* Short cache is an optimization which allows us to avoid step 3 most of the time1473* when the data doesn't actually match. With short cache, the flow becomes:1474* 1. Compute (hash, currentTag) at ip. currentTag is an 8-bit independent hash at ip.1475* 2. Load (index, matchTag) from hashTable[hash]. See ZSTD_writeTaggedIndex to understand how this works.1476* 3. Only if currentTag == matchTag, check *ip == *(base + index). Otherwise, continue.1477*1478* Currently, short cache is only implemented in CDict hashtables. Thus, its use is limited to1479* dictMatchState matchfinders.1480*/1481#define ZSTD_SHORT_CACHE_TAG_BITS 81482#define ZSTD_SHORT_CACHE_TAG_MASK ((1u << ZSTD_SHORT_CACHE_TAG_BITS) - 1)14831484/* Helper function for ZSTD_fillHashTable and ZSTD_fillDoubleHashTable.1485* Unpacks hashAndTag into (hash, tag), then packs (index, tag) into hashTable[hash]. */1486MEM_STATIC void ZSTD_writeTaggedIndex(U32* const hashTable, size_t hashAndTag, U32 index) {1487size_t const hash = hashAndTag >> ZSTD_SHORT_CACHE_TAG_BITS;1488U32 const tag = (U32)(hashAndTag & ZSTD_SHORT_CACHE_TAG_MASK);1489assert(index >> (32 - ZSTD_SHORT_CACHE_TAG_BITS) == 0);1490hashTable[hash] = (index << ZSTD_SHORT_CACHE_TAG_BITS) | tag;1491}14921493/* Helper function for short cache matchfinders.1494* Unpacks tag1 and tag2 from lower bits of packedTag1 and packedTag2, then checks if the tags match. */1495MEM_STATIC int ZSTD_comparePackedTags(size_t packedTag1, size_t packedTag2) {1496U32 const tag1 = packedTag1 & ZSTD_SHORT_CACHE_TAG_MASK;1497U32 const tag2 = packedTag2 & ZSTD_SHORT_CACHE_TAG_MASK;1498return tag1 == tag2;1499}15001501/* ===============================================================1502* Shared internal declarations1503* These prototypes may be called from sources not in lib/compress1504* =============================================================== */15051506/* ZSTD_loadCEntropy() :1507* dict : must point at beginning of a valid zstd dictionary.1508* return : size of dictionary header (size of magic number + dict ID + entropy tables)1509* assumptions : magic number supposed already checked1510* and dictSize >= 8 */1511size_t ZSTD_loadCEntropy(ZSTD_compressedBlockState_t* bs, void* workspace,1512const void* const dict, size_t dictSize);15131514void ZSTD_reset_compressedBlockState(ZSTD_compressedBlockState_t* bs);15151516typedef struct {1517U32 idx; /* Index in array of ZSTD_Sequence */1518U32 posInSequence; /* Position within sequence at idx */1519size_t posInSrc; /* Number of bytes given by sequences provided so far */1520} ZSTD_SequencePosition;15211522/* for benchmark */1523size_t ZSTD_convertBlockSequences(ZSTD_CCtx* cctx,1524const ZSTD_Sequence* const inSeqs, size_t nbSequences,1525int const repcodeResolution);15261527typedef struct {1528size_t nbSequences;1529size_t blockSize;1530size_t litSize;1531} BlockSummary;15321533BlockSummary ZSTD_get1BlockSummary(const ZSTD_Sequence* seqs, size_t nbSeqs);15341535/* ==============================================================1536* Private declarations1537* These prototypes shall only be called from within lib/compress1538* ============================================================== */15391540/* ZSTD_getCParamsFromCCtxParams() :1541* cParams are built depending on compressionLevel, src size hints,1542* LDM and manually set compression parameters.1543* Note: srcSizeHint == 0 means 0!1544*/1545ZSTD_compressionParameters ZSTD_getCParamsFromCCtxParams(1546const ZSTD_CCtx_params* CCtxParams, U64 srcSizeHint, size_t dictSize, ZSTD_CParamMode_e mode);15471548/*! ZSTD_initCStream_internal() :1549* Private use only. Init streaming operation.1550* expects params to be valid.1551* must receive dict, or cdict, or none, but not both.1552* @return : 0, or an error code */1553size_t ZSTD_initCStream_internal(ZSTD_CStream* zcs,1554const void* dict, size_t dictSize,1555const ZSTD_CDict* cdict,1556const ZSTD_CCtx_params* params, unsigned long long pledgedSrcSize);15571558void ZSTD_resetSeqStore(SeqStore_t* ssPtr);15591560/*! ZSTD_getCParamsFromCDict() :1561* as the name implies */1562ZSTD_compressionParameters ZSTD_getCParamsFromCDict(const ZSTD_CDict* cdict);15631564/* ZSTD_compressBegin_advanced_internal() :1565* Private use only. To be called from zstdmt_compress.c. */1566size_t ZSTD_compressBegin_advanced_internal(ZSTD_CCtx* cctx,1567const void* dict, size_t dictSize,1568ZSTD_dictContentType_e dictContentType,1569ZSTD_dictTableLoadMethod_e dtlm,1570const ZSTD_CDict* cdict,1571const ZSTD_CCtx_params* params,1572unsigned long long pledgedSrcSize);15731574/* ZSTD_compress_advanced_internal() :1575* Private use only. To be called from zstdmt_compress.c. */1576size_t ZSTD_compress_advanced_internal(ZSTD_CCtx* cctx,1577void* dst, size_t dstCapacity,1578const void* src, size_t srcSize,1579const void* dict,size_t dictSize,1580const ZSTD_CCtx_params* params);158115821583/* ZSTD_writeLastEmptyBlock() :1584* output an empty Block with end-of-frame mark to complete a frame1585* @return : size of data written into `dst` (== ZSTD_blockHeaderSize (defined in zstd_internal.h))1586* or an error code if `dstCapacity` is too small (<ZSTD_blockHeaderSize)1587*/1588size_t ZSTD_writeLastEmptyBlock(void* dst, size_t dstCapacity);158915901591/* ZSTD_referenceExternalSequences() :1592* Must be called before starting a compression operation.1593* seqs must parse a prefix of the source.1594* This cannot be used when long range matching is enabled.1595* Zstd will use these sequences, and pass the literals to a secondary block1596* compressor.1597* NOTE: seqs are not verified! Invalid sequences can cause out-of-bounds memory1598* access and data corruption.1599*/1600void ZSTD_referenceExternalSequences(ZSTD_CCtx* cctx, rawSeq* seq, size_t nbSeq);16011602/** ZSTD_cycleLog() :1603* condition for correct operation : hashLog > 1 */1604U32 ZSTD_cycleLog(U32 hashLog, ZSTD_strategy strat);16051606/** ZSTD_CCtx_trace() :1607* Trace the end of a compression call.1608*/1609void ZSTD_CCtx_trace(ZSTD_CCtx* cctx, size_t extraCSize);16101611/* Returns 1 if an external sequence producer is registered, otherwise returns 0. */1612MEM_STATIC int ZSTD_hasExtSeqProd(const ZSTD_CCtx_params* params) {1613return params->extSeqProdFunc != NULL;1614}16151616/* ===============================================================1617* Deprecated definitions that are still used internally to avoid1618* deprecation warnings. These functions are exactly equivalent to1619* their public variants, but avoid the deprecation warnings.1620* =============================================================== */16211622size_t ZSTD_compressBegin_usingCDict_deprecated(ZSTD_CCtx* cctx, const ZSTD_CDict* cdict);16231624size_t ZSTD_compressContinue_public(ZSTD_CCtx* cctx,1625void* dst, size_t dstCapacity,1626const void* src, size_t srcSize);16271628size_t ZSTD_compressEnd_public(ZSTD_CCtx* cctx,1629void* dst, size_t dstCapacity,1630const void* src, size_t srcSize);16311632size_t ZSTD_compressBlock_deprecated(ZSTD_CCtx* cctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize);163316341635#endif /* ZSTD_COMPRESS_H */163616371638