Path: blob/master/Utilities/cmzstd/lib/compress/zstd_compress_internal.h
3158 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 */2627#if defined (__cplusplus)28extern "C" {29#endif3031/*-*************************************32* Constants33***************************************/34#define kSearchStrength 835#define HASH_READ_SIZE 836#define ZSTD_DUBT_UNSORTED_MARK 1 /* For btlazy2 strategy, index ZSTD_DUBT_UNSORTED_MARK==1 means "unsorted".37It could be confused for a real successor at index "1", if sorted as larger than its predecessor.38It's not a big deal though : candidate will just be sorted again.39Additionally, candidate position 1 will be lost.40But candidate 1 cannot hide a large tree of candidates, so it's a minimal loss.41The benefit is that ZSTD_DUBT_UNSORTED_MARK cannot be mishandled after table re-use with a different strategy.42This constant is required by ZSTD_compressBlock_btlazy2() and ZSTD_reduceTable_internal() */434445/*-*************************************46* Context memory management47***************************************/48typedef enum { ZSTDcs_created=0, ZSTDcs_init, ZSTDcs_ongoing, ZSTDcs_ending } ZSTD_compressionStage_e;49typedef enum { zcss_init=0, zcss_load, zcss_flush } ZSTD_cStreamStage;5051typedef struct ZSTD_prefixDict_s {52const void* dict;53size_t dictSize;54ZSTD_dictContentType_e dictContentType;55} ZSTD_prefixDict;5657typedef struct {58void* dictBuffer;59void const* dict;60size_t dictSize;61ZSTD_dictContentType_e dictContentType;62ZSTD_CDict* cdict;63} ZSTD_localDict;6465typedef struct {66HUF_CElt CTable[HUF_CTABLE_SIZE_ST(255)];67HUF_repeat repeatMode;68} ZSTD_hufCTables_t;6970typedef struct {71FSE_CTable offcodeCTable[FSE_CTABLE_SIZE_U32(OffFSELog, MaxOff)];72FSE_CTable matchlengthCTable[FSE_CTABLE_SIZE_U32(MLFSELog, MaxML)];73FSE_CTable litlengthCTable[FSE_CTABLE_SIZE_U32(LLFSELog, MaxLL)];74FSE_repeat offcode_repeatMode;75FSE_repeat matchlength_repeatMode;76FSE_repeat litlength_repeatMode;77} ZSTD_fseCTables_t;7879typedef struct {80ZSTD_hufCTables_t huf;81ZSTD_fseCTables_t fse;82} ZSTD_entropyCTables_t;8384/***********************************************85* Entropy buffer statistics structs and funcs *86***********************************************/87/** ZSTD_hufCTablesMetadata_t :88* Stores Literals Block Type for a super-block in hType, and89* huffman tree description in hufDesBuffer.90* hufDesSize refers to the size of huffman tree description in bytes.91* This metadata is populated in ZSTD_buildBlockEntropyStats_literals() */92typedef struct {93symbolEncodingType_e hType;94BYTE hufDesBuffer[ZSTD_MAX_HUF_HEADER_SIZE];95size_t hufDesSize;96} ZSTD_hufCTablesMetadata_t;9798/** ZSTD_fseCTablesMetadata_t :99* Stores symbol compression modes for a super-block in {ll, ol, ml}Type, and100* fse tables in fseTablesBuffer.101* fseTablesSize refers to the size of fse tables in bytes.102* This metadata is populated in ZSTD_buildBlockEntropyStats_sequences() */103typedef struct {104symbolEncodingType_e llType;105symbolEncodingType_e ofType;106symbolEncodingType_e mlType;107BYTE fseTablesBuffer[ZSTD_MAX_FSE_HEADERS_SIZE];108size_t fseTablesSize;109size_t lastCountSize; /* This is to account for bug in 1.3.4. More detail in ZSTD_entropyCompressSeqStore_internal() */110} ZSTD_fseCTablesMetadata_t;111112typedef struct {113ZSTD_hufCTablesMetadata_t hufMetadata;114ZSTD_fseCTablesMetadata_t fseMetadata;115} ZSTD_entropyCTablesMetadata_t;116117/** ZSTD_buildBlockEntropyStats() :118* Builds entropy for the block.119* @return : 0 on success or error code */120size_t ZSTD_buildBlockEntropyStats(121const seqStore_t* seqStorePtr,122const ZSTD_entropyCTables_t* prevEntropy,123ZSTD_entropyCTables_t* nextEntropy,124const ZSTD_CCtx_params* cctxParams,125ZSTD_entropyCTablesMetadata_t* entropyMetadata,126void* workspace, size_t wkspSize);127128/*********************************129* Compression internals structs *130*********************************/131132typedef struct {133U32 off; /* Offset sumtype code for the match, using ZSTD_storeSeq() format */134U32 len; /* Raw length of match */135} ZSTD_match_t;136137typedef struct {138U32 offset; /* Offset of sequence */139U32 litLength; /* Length of literals prior to match */140U32 matchLength; /* Raw length of match */141} rawSeq;142143typedef struct {144rawSeq* seq; /* The start of the sequences */145size_t pos; /* The index in seq where reading stopped. pos <= size. */146size_t posInSequence; /* The position within the sequence at seq[pos] where reading147stopped. posInSequence <= seq[pos].litLength + seq[pos].matchLength */148size_t size; /* The number of sequences. <= capacity. */149size_t capacity; /* The capacity starting from `seq` pointer */150} rawSeqStore_t;151152typedef struct {153U32 idx; /* Index in array of ZSTD_Sequence */154U32 posInSequence; /* Position within sequence at idx */155size_t posInSrc; /* Number of bytes given by sequences provided so far */156} ZSTD_sequencePosition;157158UNUSED_ATTR static const rawSeqStore_t kNullRawSeqStore = {NULL, 0, 0, 0, 0};159160typedef struct {161int price;162U32 off;163U32 mlen;164U32 litlen;165U32 rep[ZSTD_REP_NUM];166} ZSTD_optimal_t;167168typedef enum { zop_dynamic=0, zop_predef } ZSTD_OptPrice_e;169170typedef struct {171/* All tables are allocated inside cctx->workspace by ZSTD_resetCCtx_internal() */172unsigned* litFreq; /* table of literals statistics, of size 256 */173unsigned* litLengthFreq; /* table of litLength statistics, of size (MaxLL+1) */174unsigned* matchLengthFreq; /* table of matchLength statistics, of size (MaxML+1) */175unsigned* offCodeFreq; /* table of offCode statistics, of size (MaxOff+1) */176ZSTD_match_t* matchTable; /* list of found matches, of size ZSTD_OPT_NUM+1 */177ZSTD_optimal_t* priceTable; /* All positions tracked by optimal parser, of size ZSTD_OPT_NUM+1 */178179U32 litSum; /* nb of literals */180U32 litLengthSum; /* nb of litLength codes */181U32 matchLengthSum; /* nb of matchLength codes */182U32 offCodeSum; /* nb of offset codes */183U32 litSumBasePrice; /* to compare to log2(litfreq) */184U32 litLengthSumBasePrice; /* to compare to log2(llfreq) */185U32 matchLengthSumBasePrice;/* to compare to log2(mlfreq) */186U32 offCodeSumBasePrice; /* to compare to log2(offreq) */187ZSTD_OptPrice_e priceType; /* prices can be determined dynamically, or follow a pre-defined cost structure */188const ZSTD_entropyCTables_t* symbolCosts; /* pre-calculated dictionary statistics */189ZSTD_paramSwitch_e literalCompressionMode;190} optState_t;191192typedef struct {193ZSTD_entropyCTables_t entropy;194U32 rep[ZSTD_REP_NUM];195} ZSTD_compressedBlockState_t;196197typedef struct {198BYTE const* nextSrc; /* next block here to continue on current prefix */199BYTE const* base; /* All regular indexes relative to this position */200BYTE const* dictBase; /* extDict indexes relative to this position */201U32 dictLimit; /* below that point, need extDict */202U32 lowLimit; /* below that point, no more valid data */203U32 nbOverflowCorrections; /* Number of times overflow correction has run since204* ZSTD_window_init(). Useful for debugging coredumps205* and for ZSTD_WINDOW_OVERFLOW_CORRECT_FREQUENTLY.206*/207} ZSTD_window_t;208209#define ZSTD_WINDOW_START_INDEX 2210211typedef struct ZSTD_matchState_t ZSTD_matchState_t;212213#define ZSTD_ROW_HASH_CACHE_SIZE 8 /* Size of prefetching hash cache for row-based matchfinder */214215struct ZSTD_matchState_t {216ZSTD_window_t window; /* State for window round buffer management */217U32 loadedDictEnd; /* index of end of dictionary, within context's referential.218* When loadedDictEnd != 0, a dictionary is in use, and still valid.219* This relies on a mechanism to set loadedDictEnd=0 when dictionary is no longer within distance.220* Such mechanism is provided within ZSTD_window_enforceMaxDist() and ZSTD_checkDictValidity().221* When dict referential is copied into active context (i.e. not attached),222* loadedDictEnd == dictSize, since referential starts from zero.223*/224U32 nextToUpdate; /* index from which to continue table update */225U32 hashLog3; /* dispatch table for matches of len==3 : larger == faster, more memory */226227U32 rowHashLog; /* For row-based matchfinder: Hashlog based on nb of rows in the hashTable.*/228BYTE* tagTable; /* For row-based matchFinder: A row-based table containing the hashes and head index. */229U32 hashCache[ZSTD_ROW_HASH_CACHE_SIZE]; /* For row-based matchFinder: a cache of hashes to improve speed */230U64 hashSalt; /* For row-based matchFinder: salts the hash for re-use of tag table */231U32 hashSaltEntropy; /* For row-based matchFinder: collects entropy for salt generation */232233U32* hashTable;234U32* hashTable3;235U32* chainTable;236237U32 forceNonContiguous; /* Non-zero if we should force non-contiguous load for the next window update. */238239int dedicatedDictSearch; /* Indicates whether this matchState is using the240* dedicated dictionary search structure.241*/242optState_t opt; /* optimal parser state */243const ZSTD_matchState_t* dictMatchState;244ZSTD_compressionParameters cParams;245const rawSeqStore_t* ldmSeqStore;246247/* Controls prefetching in some dictMatchState matchfinders.248* This behavior is controlled from the cctx ms.249* This parameter has no effect in the cdict ms. */250int prefetchCDictTables;251252/* When == 0, lazy match finders insert every position.253* When != 0, lazy match finders only insert positions they search.254* This allows them to skip much faster over incompressible data,255* at a small cost to compression ratio.256*/257int lazySkipping;258};259260typedef struct {261ZSTD_compressedBlockState_t* prevCBlock;262ZSTD_compressedBlockState_t* nextCBlock;263ZSTD_matchState_t matchState;264} ZSTD_blockState_t;265266typedef struct {267U32 offset;268U32 checksum;269} ldmEntry_t;270271typedef struct {272BYTE const* split;273U32 hash;274U32 checksum;275ldmEntry_t* bucket;276} ldmMatchCandidate_t;277278#define LDM_BATCH_SIZE 64279280typedef struct {281ZSTD_window_t window; /* State for the window round buffer management */282ldmEntry_t* hashTable;283U32 loadedDictEnd;284BYTE* bucketOffsets; /* Next position in bucket to insert entry */285size_t splitIndices[LDM_BATCH_SIZE];286ldmMatchCandidate_t matchCandidates[LDM_BATCH_SIZE];287} ldmState_t;288289typedef struct {290ZSTD_paramSwitch_e enableLdm; /* ZSTD_ps_enable to enable LDM. ZSTD_ps_auto by default */291U32 hashLog; /* Log size of hashTable */292U32 bucketSizeLog; /* Log bucket size for collision resolution, at most 8 */293U32 minMatchLength; /* Minimum match length */294U32 hashRateLog; /* Log number of entries to skip */295U32 windowLog; /* Window log for the LDM */296} ldmParams_t;297298typedef struct {299int collectSequences;300ZSTD_Sequence* seqStart;301size_t seqIndex;302size_t maxSequences;303} SeqCollector;304305struct ZSTD_CCtx_params_s {306ZSTD_format_e format;307ZSTD_compressionParameters cParams;308ZSTD_frameParameters fParams;309310int compressionLevel;311int forceWindow; /* force back-references to respect limit of312* 1<<wLog, even for dictionary */313size_t targetCBlockSize; /* Tries to fit compressed block size to be around targetCBlockSize.314* No target when targetCBlockSize == 0.315* There is no guarantee on compressed block size */316int srcSizeHint; /* User's best guess of source size.317* Hint is not valid when srcSizeHint == 0.318* There is no guarantee that hint is close to actual source size */319320ZSTD_dictAttachPref_e attachDictPref;321ZSTD_paramSwitch_e literalCompressionMode;322323/* Multithreading: used to pass parameters to mtctx */324int nbWorkers;325size_t jobSize;326int overlapLog;327int rsyncable;328329/* Long distance matching parameters */330ldmParams_t ldmParams;331332/* Dedicated dict search algorithm trigger */333int enableDedicatedDictSearch;334335/* Input/output buffer modes */336ZSTD_bufferMode_e inBufferMode;337ZSTD_bufferMode_e outBufferMode;338339/* Sequence compression API */340ZSTD_sequenceFormat_e blockDelimiters;341int validateSequences;342343/* Block splitting */344ZSTD_paramSwitch_e useBlockSplitter;345346/* Param for deciding whether to use row-based matchfinder */347ZSTD_paramSwitch_e useRowMatchFinder;348349/* Always load a dictionary in ext-dict mode (not prefix mode)? */350int deterministicRefPrefix;351352/* Internal use, for createCCtxParams() and freeCCtxParams() only */353ZSTD_customMem customMem;354355/* Controls prefetching in some dictMatchState matchfinders */356ZSTD_paramSwitch_e prefetchCDictTables;357358/* Controls whether zstd will fall back to an internal matchfinder359* if the external matchfinder returns an error code. */360int enableMatchFinderFallback;361362/* Indicates whether an external matchfinder has been referenced.363* Users can't set this externally.364* It is set internally in ZSTD_registerSequenceProducer(). */365int useSequenceProducer;366367/* Adjust the max block size*/368size_t maxBlockSize;369370/* Controls repcode search in external sequence parsing */371ZSTD_paramSwitch_e searchForExternalRepcodes;372}; /* typedef'd to ZSTD_CCtx_params within "zstd.h" */373374#define COMPRESS_SEQUENCES_WORKSPACE_SIZE (sizeof(unsigned) * (MaxSeq + 2))375#define ENTROPY_WORKSPACE_SIZE (HUF_WORKSPACE_SIZE + COMPRESS_SEQUENCES_WORKSPACE_SIZE)376377/**378* Indicates whether this compression proceeds directly from user-provided379* source buffer to user-provided destination buffer (ZSTDb_not_buffered), or380* whether the context needs to buffer the input/output (ZSTDb_buffered).381*/382typedef enum {383ZSTDb_not_buffered,384ZSTDb_buffered385} ZSTD_buffered_policy_e;386387/**388* Struct that contains all elements of block splitter that should be allocated389* in a wksp.390*/391#define ZSTD_MAX_NB_BLOCK_SPLITS 196392typedef struct {393seqStore_t fullSeqStoreChunk;394seqStore_t firstHalfSeqStore;395seqStore_t secondHalfSeqStore;396seqStore_t currSeqStore;397seqStore_t nextSeqStore;398399U32 partitions[ZSTD_MAX_NB_BLOCK_SPLITS];400ZSTD_entropyCTablesMetadata_t entropyMetadata;401} ZSTD_blockSplitCtx;402403/* Context for block-level external matchfinder API */404typedef struct {405void* mState;406ZSTD_sequenceProducer_F* mFinder;407ZSTD_Sequence* seqBuffer;408size_t seqBufferCapacity;409} ZSTD_externalMatchCtx;410411struct ZSTD_CCtx_s {412ZSTD_compressionStage_e stage;413int 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. */414int bmi2; /* == 1 if the CPU supports BMI2 and 0 otherwise. CPU support is determined dynamically once per context lifetime. */415ZSTD_CCtx_params requestedParams;416ZSTD_CCtx_params appliedParams;417ZSTD_CCtx_params simpleApiParams; /* Param storage used by the simple API - not sticky. Must only be used in top-level simple API functions for storage. */418U32 dictID;419size_t dictContentSize;420421ZSTD_cwksp workspace; /* manages buffer for dynamic allocations */422size_t blockSize;423unsigned long long pledgedSrcSizePlusOne; /* this way, 0 (default) == unknown */424unsigned long long consumedSrcSize;425unsigned long long producedCSize;426XXH64_state_t xxhState;427ZSTD_customMem customMem;428ZSTD_threadPool* pool;429size_t staticSize;430SeqCollector seqCollector;431int isFirstBlock;432int initialized;433434seqStore_t seqStore; /* sequences storage ptrs */435ldmState_t ldmState; /* long distance matching state */436rawSeq* ldmSequences; /* Storage for the ldm output sequences */437size_t maxNbLdmSequences;438rawSeqStore_t externSeqStore; /* Mutable reference to external sequences */439ZSTD_blockState_t blockState;440U32* entropyWorkspace; /* entropy workspace of ENTROPY_WORKSPACE_SIZE bytes */441442/* Whether we are streaming or not */443ZSTD_buffered_policy_e bufferedPolicy;444445/* streaming */446char* inBuff;447size_t inBuffSize;448size_t inToCompress;449size_t inBuffPos;450size_t inBuffTarget;451char* outBuff;452size_t outBuffSize;453size_t outBuffContentSize;454size_t outBuffFlushedSize;455ZSTD_cStreamStage streamStage;456U32 frameEnded;457458/* Stable in/out buffer verification */459ZSTD_inBuffer expectedInBuffer;460size_t stableIn_notConsumed; /* nb bytes within stable input buffer that are said to be consumed but are not */461size_t expectedOutBufferSize;462463/* Dictionary */464ZSTD_localDict localDict;465const ZSTD_CDict* cdict;466ZSTD_prefixDict prefixDict; /* single-usage dictionary */467468/* Multi-threading */469#ifdef ZSTD_MULTITHREAD470ZSTDMT_CCtx* mtctx;471#endif472473/* Tracing */474#if ZSTD_TRACE475ZSTD_TraceCtx traceCtx;476#endif477478/* Workspace for block splitter */479ZSTD_blockSplitCtx blockSplitCtx;480481/* Workspace for external matchfinder */482ZSTD_externalMatchCtx externalMatchCtx;483};484485typedef enum { ZSTD_dtlm_fast, ZSTD_dtlm_full } ZSTD_dictTableLoadMethod_e;486typedef enum { ZSTD_tfp_forCCtx, ZSTD_tfp_forCDict } ZSTD_tableFillPurpose_e;487488typedef enum {489ZSTD_noDict = 0,490ZSTD_extDict = 1,491ZSTD_dictMatchState = 2,492ZSTD_dedicatedDictSearch = 3493} ZSTD_dictMode_e;494495typedef enum {496ZSTD_cpm_noAttachDict = 0, /* Compression with ZSTD_noDict or ZSTD_extDict.497* In this mode we use both the srcSize and the dictSize498* when selecting and adjusting parameters.499*/500ZSTD_cpm_attachDict = 1, /* Compression with ZSTD_dictMatchState or ZSTD_dedicatedDictSearch.501* In this mode we only take the srcSize into account when selecting502* and adjusting parameters.503*/504ZSTD_cpm_createCDict = 2, /* Creating a CDict.505* In this mode we take both the source size and the dictionary size506* into account when selecting and adjusting the parameters.507*/508ZSTD_cpm_unknown = 3 /* ZSTD_getCParams, ZSTD_getParams, ZSTD_adjustParams.509* We don't know what these parameters are for. We default to the legacy510* behavior of taking both the source size and the dict size into account511* when selecting and adjusting parameters.512*/513} ZSTD_cParamMode_e;514515typedef size_t (*ZSTD_blockCompressor) (516ZSTD_matchState_t* bs, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],517void const* src, size_t srcSize);518ZSTD_blockCompressor ZSTD_selectBlockCompressor(ZSTD_strategy strat, ZSTD_paramSwitch_e rowMatchfinderMode, ZSTD_dictMode_e dictMode);519520521MEM_STATIC U32 ZSTD_LLcode(U32 litLength)522{523static const BYTE LL_Code[64] = { 0, 1, 2, 3, 4, 5, 6, 7,5248, 9, 10, 11, 12, 13, 14, 15,52516, 16, 17, 17, 18, 18, 19, 19,52620, 20, 20, 20, 21, 21, 21, 21,52722, 22, 22, 22, 22, 22, 22, 22,52823, 23, 23, 23, 23, 23, 23, 23,52924, 24, 24, 24, 24, 24, 24, 24,53024, 24, 24, 24, 24, 24, 24, 24 };531static const U32 LL_deltaCode = 19;532return (litLength > 63) ? ZSTD_highbit32(litLength) + LL_deltaCode : LL_Code[litLength];533}534535/* ZSTD_MLcode() :536* note : mlBase = matchLength - MINMATCH;537* because it's the format it's stored in seqStore->sequences */538MEM_STATIC U32 ZSTD_MLcode(U32 mlBase)539{540static const BYTE ML_Code[128] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,54116, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,54232, 32, 33, 33, 34, 34, 35, 35, 36, 36, 36, 36, 37, 37, 37, 37,54338, 38, 38, 38, 38, 38, 38, 38, 39, 39, 39, 39, 39, 39, 39, 39,54440, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40,54541, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41,54642, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42,54742, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42 };548static const U32 ML_deltaCode = 36;549return (mlBase > 127) ? ZSTD_highbit32(mlBase) + ML_deltaCode : ML_Code[mlBase];550}551552/* ZSTD_cParam_withinBounds:553* @return 1 if value is within cParam bounds,554* 0 otherwise */555MEM_STATIC int ZSTD_cParam_withinBounds(ZSTD_cParameter cParam, int value)556{557ZSTD_bounds const bounds = ZSTD_cParam_getBounds(cParam);558if (ZSTD_isError(bounds.error)) return 0;559if (value < bounds.lowerBound) return 0;560if (value > bounds.upperBound) return 0;561return 1;562}563564/* ZSTD_noCompressBlock() :565* Writes uncompressed block to dst buffer from given src.566* Returns the size of the block */567MEM_STATIC size_t568ZSTD_noCompressBlock(void* dst, size_t dstCapacity, const void* src, size_t srcSize, U32 lastBlock)569{570U32 const cBlockHeader24 = lastBlock + (((U32)bt_raw)<<1) + (U32)(srcSize << 3);571DEBUGLOG(5, "ZSTD_noCompressBlock (srcSize=%zu, dstCapacity=%zu)", srcSize, dstCapacity);572RETURN_ERROR_IF(srcSize + ZSTD_blockHeaderSize > dstCapacity,573dstSize_tooSmall, "dst buf too small for uncompressed block");574MEM_writeLE24(dst, cBlockHeader24);575ZSTD_memcpy((BYTE*)dst + ZSTD_blockHeaderSize, src, srcSize);576return ZSTD_blockHeaderSize + srcSize;577}578579MEM_STATIC size_t580ZSTD_rleCompressBlock(void* dst, size_t dstCapacity, BYTE src, size_t srcSize, U32 lastBlock)581{582BYTE* const op = (BYTE*)dst;583U32 const cBlockHeader = lastBlock + (((U32)bt_rle)<<1) + (U32)(srcSize << 3);584RETURN_ERROR_IF(dstCapacity < 4, dstSize_tooSmall, "");585MEM_writeLE24(op, cBlockHeader);586op[3] = src;587return 4;588}589590591/* ZSTD_minGain() :592* minimum compression required593* to generate a compress block or a compressed literals section.594* note : use same formula for both situations */595MEM_STATIC size_t ZSTD_minGain(size_t srcSize, ZSTD_strategy strat)596{597U32 const minlog = (strat>=ZSTD_btultra) ? (U32)(strat) - 1 : 6;598ZSTD_STATIC_ASSERT(ZSTD_btultra == 8);599assert(ZSTD_cParam_withinBounds(ZSTD_c_strategy, (int)strat));600return (srcSize >> minlog) + 2;601}602603MEM_STATIC int ZSTD_literalsCompressionIsDisabled(const ZSTD_CCtx_params* cctxParams)604{605switch (cctxParams->literalCompressionMode) {606case ZSTD_ps_enable:607return 0;608case ZSTD_ps_disable:609return 1;610default:611assert(0 /* impossible: pre-validated */);612ZSTD_FALLTHROUGH;613case ZSTD_ps_auto:614return (cctxParams->cParams.strategy == ZSTD_fast) && (cctxParams->cParams.targetLength > 0);615}616}617618/*! ZSTD_safecopyLiterals() :619* memcpy() function that won't read beyond more than WILDCOPY_OVERLENGTH bytes past ilimit_w.620* Only called when the sequence ends past ilimit_w, so it only needs to be optimized for single621* large copies.622*/623static void624ZSTD_safecopyLiterals(BYTE* op, BYTE const* ip, BYTE const* const iend, BYTE const* ilimit_w)625{626assert(iend > ilimit_w);627if (ip <= ilimit_w) {628ZSTD_wildcopy(op, ip, ilimit_w - ip, ZSTD_no_overlap);629op += ilimit_w - ip;630ip = ilimit_w;631}632while (ip < iend) *op++ = *ip++;633}634635636#define REPCODE1_TO_OFFBASE REPCODE_TO_OFFBASE(1)637#define REPCODE2_TO_OFFBASE REPCODE_TO_OFFBASE(2)638#define REPCODE3_TO_OFFBASE REPCODE_TO_OFFBASE(3)639#define REPCODE_TO_OFFBASE(r) (assert((r)>=1), assert((r)<=ZSTD_REP_NUM), (r)) /* accepts IDs 1,2,3 */640#define OFFSET_TO_OFFBASE(o) (assert((o)>0), o + ZSTD_REP_NUM)641#define OFFBASE_IS_OFFSET(o) ((o) > ZSTD_REP_NUM)642#define OFFBASE_IS_REPCODE(o) ( 1 <= (o) && (o) <= ZSTD_REP_NUM)643#define OFFBASE_TO_OFFSET(o) (assert(OFFBASE_IS_OFFSET(o)), (o) - ZSTD_REP_NUM)644#define OFFBASE_TO_REPCODE(o) (assert(OFFBASE_IS_REPCODE(o)), (o)) /* returns ID 1,2,3 */645646/*! ZSTD_storeSeq() :647* Store a sequence (litlen, litPtr, offBase and matchLength) into seqStore_t.648* @offBase : Users should employ macros REPCODE_TO_OFFBASE() and OFFSET_TO_OFFBASE().649* @matchLength : must be >= MINMATCH650* Allowed to over-read literals up to litLimit.651*/652HINT_INLINE UNUSED_ATTR void653ZSTD_storeSeq(seqStore_t* seqStorePtr,654size_t litLength, const BYTE* literals, const BYTE* litLimit,655U32 offBase,656size_t matchLength)657{658BYTE const* const litLimit_w = litLimit - WILDCOPY_OVERLENGTH;659BYTE const* const litEnd = literals + litLength;660#if defined(DEBUGLEVEL) && (DEBUGLEVEL >= 6)661static const BYTE* g_start = NULL;662if (g_start==NULL) g_start = (const BYTE*)literals; /* note : index only works for compression within a single segment */663{ U32 const pos = (U32)((const BYTE*)literals - g_start);664DEBUGLOG(6, "Cpos%7u :%3u literals, match%4u bytes at offBase%7u",665pos, (U32)litLength, (U32)matchLength, (U32)offBase);666}667#endif668assert((size_t)(seqStorePtr->sequences - seqStorePtr->sequencesStart) < seqStorePtr->maxNbSeq);669/* copy Literals */670assert(seqStorePtr->maxNbLit <= 128 KB);671assert(seqStorePtr->lit + litLength <= seqStorePtr->litStart + seqStorePtr->maxNbLit);672assert(literals + litLength <= litLimit);673if (litEnd <= litLimit_w) {674/* Common case we can use wildcopy.675* First copy 16 bytes, because literals are likely short.676*/677ZSTD_STATIC_ASSERT(WILDCOPY_OVERLENGTH >= 16);678ZSTD_copy16(seqStorePtr->lit, literals);679if (litLength > 16) {680ZSTD_wildcopy(seqStorePtr->lit+16, literals+16, (ptrdiff_t)litLength-16, ZSTD_no_overlap);681}682} else {683ZSTD_safecopyLiterals(seqStorePtr->lit, literals, litEnd, litLimit_w);684}685seqStorePtr->lit += litLength;686687/* literal Length */688if (litLength>0xFFFF) {689assert(seqStorePtr->longLengthType == ZSTD_llt_none); /* there can only be a single long length */690seqStorePtr->longLengthType = ZSTD_llt_literalLength;691seqStorePtr->longLengthPos = (U32)(seqStorePtr->sequences - seqStorePtr->sequencesStart);692}693seqStorePtr->sequences[0].litLength = (U16)litLength;694695/* match offset */696seqStorePtr->sequences[0].offBase = offBase;697698/* match Length */699assert(matchLength >= MINMATCH);700{ size_t const mlBase = matchLength - MINMATCH;701if (mlBase>0xFFFF) {702assert(seqStorePtr->longLengthType == ZSTD_llt_none); /* there can only be a single long length */703seqStorePtr->longLengthType = ZSTD_llt_matchLength;704seqStorePtr->longLengthPos = (U32)(seqStorePtr->sequences - seqStorePtr->sequencesStart);705}706seqStorePtr->sequences[0].mlBase = (U16)mlBase;707}708709seqStorePtr->sequences++;710}711712/* ZSTD_updateRep() :713* updates in-place @rep (array of repeat offsets)714* @offBase : sum-type, using numeric representation of ZSTD_storeSeq()715*/716MEM_STATIC void717ZSTD_updateRep(U32 rep[ZSTD_REP_NUM], U32 const offBase, U32 const ll0)718{719if (OFFBASE_IS_OFFSET(offBase)) { /* full offset */720rep[2] = rep[1];721rep[1] = rep[0];722rep[0] = OFFBASE_TO_OFFSET(offBase);723} else { /* repcode */724U32 const repCode = OFFBASE_TO_REPCODE(offBase) - 1 + ll0;725if (repCode > 0) { /* note : if repCode==0, no change */726U32 const currentOffset = (repCode==ZSTD_REP_NUM) ? (rep[0] - 1) : rep[repCode];727rep[2] = (repCode >= 2) ? rep[1] : rep[2];728rep[1] = rep[0];729rep[0] = currentOffset;730} else { /* repCode == 0 */731/* nothing to do */732}733}734}735736typedef struct repcodes_s {737U32 rep[3];738} repcodes_t;739740MEM_STATIC repcodes_t741ZSTD_newRep(U32 const rep[ZSTD_REP_NUM], U32 const offBase, U32 const ll0)742{743repcodes_t newReps;744ZSTD_memcpy(&newReps, rep, sizeof(newReps));745ZSTD_updateRep(newReps.rep, offBase, ll0);746return newReps;747}748749750/*-*************************************751* Match length counter752***************************************/753MEM_STATIC size_t ZSTD_count(const BYTE* pIn, const BYTE* pMatch, const BYTE* const pInLimit)754{755const BYTE* const pStart = pIn;756const BYTE* const pInLoopLimit = pInLimit - (sizeof(size_t)-1);757758if (pIn < pInLoopLimit) {759{ size_t const diff = MEM_readST(pMatch) ^ MEM_readST(pIn);760if (diff) return ZSTD_NbCommonBytes(diff); }761pIn+=sizeof(size_t); pMatch+=sizeof(size_t);762while (pIn < pInLoopLimit) {763size_t const diff = MEM_readST(pMatch) ^ MEM_readST(pIn);764if (!diff) { pIn+=sizeof(size_t); pMatch+=sizeof(size_t); continue; }765pIn += ZSTD_NbCommonBytes(diff);766return (size_t)(pIn - pStart);767} }768if (MEM_64bits() && (pIn<(pInLimit-3)) && (MEM_read32(pMatch) == MEM_read32(pIn))) { pIn+=4; pMatch+=4; }769if ((pIn<(pInLimit-1)) && (MEM_read16(pMatch) == MEM_read16(pIn))) { pIn+=2; pMatch+=2; }770if ((pIn<pInLimit) && (*pMatch == *pIn)) pIn++;771return (size_t)(pIn - pStart);772}773774/** ZSTD_count_2segments() :775* can count match length with `ip` & `match` in 2 different segments.776* convention : on reaching mEnd, match count continue starting from iStart777*/778MEM_STATIC size_t779ZSTD_count_2segments(const BYTE* ip, const BYTE* match,780const BYTE* iEnd, const BYTE* mEnd, const BYTE* iStart)781{782const BYTE* const vEnd = MIN( ip + (mEnd - match), iEnd);783size_t const matchLength = ZSTD_count(ip, match, vEnd);784if (match + matchLength != mEnd) return matchLength;785DEBUGLOG(7, "ZSTD_count_2segments: found a 2-parts match (current length==%zu)", matchLength);786DEBUGLOG(7, "distance from match beginning to end dictionary = %zi", mEnd - match);787DEBUGLOG(7, "distance from current pos to end buffer = %zi", iEnd - ip);788DEBUGLOG(7, "next byte : ip==%02X, istart==%02X", ip[matchLength], *iStart);789DEBUGLOG(7, "final match length = %zu", matchLength + ZSTD_count(ip+matchLength, iStart, iEnd));790return matchLength + ZSTD_count(ip+matchLength, iStart, iEnd);791}792793794/*-*************************************795* Hashes796***************************************/797static const U32 prime3bytes = 506832829U;798static U32 ZSTD_hash3(U32 u, U32 h, U32 s) { assert(h <= 32); return (((u << (32-24)) * prime3bytes) ^ s) >> (32-h) ; }799MEM_STATIC size_t ZSTD_hash3Ptr(const void* ptr, U32 h) { return ZSTD_hash3(MEM_readLE32(ptr), h, 0); } /* only in zstd_opt.h */800MEM_STATIC size_t ZSTD_hash3PtrS(const void* ptr, U32 h, U32 s) { return ZSTD_hash3(MEM_readLE32(ptr), h, s); }801802static const U32 prime4bytes = 2654435761U;803static U32 ZSTD_hash4(U32 u, U32 h, U32 s) { assert(h <= 32); return ((u * prime4bytes) ^ s) >> (32-h) ; }804static size_t ZSTD_hash4Ptr(const void* ptr, U32 h) { return ZSTD_hash4(MEM_readLE32(ptr), h, 0); }805static size_t ZSTD_hash4PtrS(const void* ptr, U32 h, U32 s) { return ZSTD_hash4(MEM_readLE32(ptr), h, s); }806807static const U64 prime5bytes = 889523592379ULL;808static size_t ZSTD_hash5(U64 u, U32 h, U64 s) { assert(h <= 64); return (size_t)((((u << (64-40)) * prime5bytes) ^ s) >> (64-h)) ; }809static size_t ZSTD_hash5Ptr(const void* p, U32 h) { return ZSTD_hash5(MEM_readLE64(p), h, 0); }810static size_t ZSTD_hash5PtrS(const void* p, U32 h, U64 s) { return ZSTD_hash5(MEM_readLE64(p), h, s); }811812static const U64 prime6bytes = 227718039650203ULL;813static size_t ZSTD_hash6(U64 u, U32 h, U64 s) { assert(h <= 64); return (size_t)((((u << (64-48)) * prime6bytes) ^ s) >> (64-h)) ; }814static size_t ZSTD_hash6Ptr(const void* p, U32 h) { return ZSTD_hash6(MEM_readLE64(p), h, 0); }815static size_t ZSTD_hash6PtrS(const void* p, U32 h, U64 s) { return ZSTD_hash6(MEM_readLE64(p), h, s); }816817static const U64 prime7bytes = 58295818150454627ULL;818static size_t ZSTD_hash7(U64 u, U32 h, U64 s) { assert(h <= 64); return (size_t)((((u << (64-56)) * prime7bytes) ^ s) >> (64-h)) ; }819static size_t ZSTD_hash7Ptr(const void* p, U32 h) { return ZSTD_hash7(MEM_readLE64(p), h, 0); }820static size_t ZSTD_hash7PtrS(const void* p, U32 h, U64 s) { return ZSTD_hash7(MEM_readLE64(p), h, s); }821822static const U64 prime8bytes = 0xCF1BBCDCB7A56463ULL;823static size_t ZSTD_hash8(U64 u, U32 h, U64 s) { assert(h <= 64); return (size_t)((((u) * prime8bytes) ^ s) >> (64-h)) ; }824static size_t ZSTD_hash8Ptr(const void* p, U32 h) { return ZSTD_hash8(MEM_readLE64(p), h, 0); }825static size_t ZSTD_hash8PtrS(const void* p, U32 h, U64 s) { return ZSTD_hash8(MEM_readLE64(p), h, s); }826827828MEM_STATIC FORCE_INLINE_ATTR829size_t ZSTD_hashPtr(const void* p, U32 hBits, U32 mls)830{831/* Although some of these hashes do support hBits up to 64, some do not.832* To be on the safe side, always avoid hBits > 32. */833assert(hBits <= 32);834835switch(mls)836{837default:838case 4: return ZSTD_hash4Ptr(p, hBits);839case 5: return ZSTD_hash5Ptr(p, hBits);840case 6: return ZSTD_hash6Ptr(p, hBits);841case 7: return ZSTD_hash7Ptr(p, hBits);842case 8: return ZSTD_hash8Ptr(p, hBits);843}844}845846MEM_STATIC FORCE_INLINE_ATTR847size_t ZSTD_hashPtrSalted(const void* p, U32 hBits, U32 mls, const U64 hashSalt) {848/* Although some of these hashes do support hBits up to 64, some do not.849* To be on the safe side, always avoid hBits > 32. */850assert(hBits <= 32);851852switch(mls)853{854default:855case 4: return ZSTD_hash4PtrS(p, hBits, (U32)hashSalt);856case 5: return ZSTD_hash5PtrS(p, hBits, hashSalt);857case 6: return ZSTD_hash6PtrS(p, hBits, hashSalt);858case 7: return ZSTD_hash7PtrS(p, hBits, hashSalt);859case 8: return ZSTD_hash8PtrS(p, hBits, hashSalt);860}861}862863864/** ZSTD_ipow() :865* Return base^exponent.866*/867static U64 ZSTD_ipow(U64 base, U64 exponent)868{869U64 power = 1;870while (exponent) {871if (exponent & 1) power *= base;872exponent >>= 1;873base *= base;874}875return power;876}877878#define ZSTD_ROLL_HASH_CHAR_OFFSET 10879880/** ZSTD_rollingHash_append() :881* Add the buffer to the hash value.882*/883static U64 ZSTD_rollingHash_append(U64 hash, void const* buf, size_t size)884{885BYTE const* istart = (BYTE const*)buf;886size_t pos;887for (pos = 0; pos < size; ++pos) {888hash *= prime8bytes;889hash += istart[pos] + ZSTD_ROLL_HASH_CHAR_OFFSET;890}891return hash;892}893894/** ZSTD_rollingHash_compute() :895* Compute the rolling hash value of the buffer.896*/897MEM_STATIC U64 ZSTD_rollingHash_compute(void const* buf, size_t size)898{899return ZSTD_rollingHash_append(0, buf, size);900}901902/** ZSTD_rollingHash_primePower() :903* Compute the primePower to be passed to ZSTD_rollingHash_rotate() for a hash904* over a window of length bytes.905*/906MEM_STATIC U64 ZSTD_rollingHash_primePower(U32 length)907{908return ZSTD_ipow(prime8bytes, length - 1);909}910911/** ZSTD_rollingHash_rotate() :912* Rotate the rolling hash by one byte.913*/914MEM_STATIC U64 ZSTD_rollingHash_rotate(U64 hash, BYTE toRemove, BYTE toAdd, U64 primePower)915{916hash -= (toRemove + ZSTD_ROLL_HASH_CHAR_OFFSET) * primePower;917hash *= prime8bytes;918hash += toAdd + ZSTD_ROLL_HASH_CHAR_OFFSET;919return hash;920}921922/*-*************************************923* Round buffer management924***************************************/925#if (ZSTD_WINDOWLOG_MAX_64 > 31)926# error "ZSTD_WINDOWLOG_MAX is too large : would overflow ZSTD_CURRENT_MAX"927#endif928/* Max current allowed */929#define ZSTD_CURRENT_MAX ((3U << 29) + (1U << ZSTD_WINDOWLOG_MAX))930/* Maximum chunk size before overflow correction needs to be called again */931#define ZSTD_CHUNKSIZE_MAX \932( ((U32)-1) /* Maximum ending current index */ \933- ZSTD_CURRENT_MAX) /* Maximum beginning lowLimit */934935/**936* ZSTD_window_clear():937* Clears the window containing the history by simply setting it to empty.938*/939MEM_STATIC void ZSTD_window_clear(ZSTD_window_t* window)940{941size_t const endT = (size_t)(window->nextSrc - window->base);942U32 const end = (U32)endT;943944window->lowLimit = end;945window->dictLimit = end;946}947948MEM_STATIC U32 ZSTD_window_isEmpty(ZSTD_window_t const window)949{950return window.dictLimit == ZSTD_WINDOW_START_INDEX &&951window.lowLimit == ZSTD_WINDOW_START_INDEX &&952(window.nextSrc - window.base) == ZSTD_WINDOW_START_INDEX;953}954955/**956* ZSTD_window_hasExtDict():957* Returns non-zero if the window has a non-empty extDict.958*/959MEM_STATIC U32 ZSTD_window_hasExtDict(ZSTD_window_t const window)960{961return window.lowLimit < window.dictLimit;962}963964/**965* ZSTD_matchState_dictMode():966* Inspects the provided matchState and figures out what dictMode should be967* passed to the compressor.968*/969MEM_STATIC ZSTD_dictMode_e ZSTD_matchState_dictMode(const ZSTD_matchState_t *ms)970{971return ZSTD_window_hasExtDict(ms->window) ?972ZSTD_extDict :973ms->dictMatchState != NULL ?974(ms->dictMatchState->dedicatedDictSearch ? ZSTD_dedicatedDictSearch : ZSTD_dictMatchState) :975ZSTD_noDict;976}977978/* Defining this macro to non-zero tells zstd to run the overflow correction979* code much more frequently. This is very inefficient, and should only be980* used for tests and fuzzers.981*/982#ifndef ZSTD_WINDOW_OVERFLOW_CORRECT_FREQUENTLY983# ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION984# define ZSTD_WINDOW_OVERFLOW_CORRECT_FREQUENTLY 1985# else986# define ZSTD_WINDOW_OVERFLOW_CORRECT_FREQUENTLY 0987# endif988#endif989990/**991* ZSTD_window_canOverflowCorrect():992* Returns non-zero if the indices are large enough for overflow correction993* to work correctly without impacting compression ratio.994*/995MEM_STATIC U32 ZSTD_window_canOverflowCorrect(ZSTD_window_t const window,996U32 cycleLog,997U32 maxDist,998U32 loadedDictEnd,999void const* src)1000{1001U32 const cycleSize = 1u << cycleLog;1002U32 const curr = (U32)((BYTE const*)src - window.base);1003U32 const minIndexToOverflowCorrect = cycleSize1004+ MAX(maxDist, cycleSize)1005+ ZSTD_WINDOW_START_INDEX;10061007/* Adjust the min index to backoff the overflow correction frequency,1008* so we don't waste too much CPU in overflow correction. If this1009* computation overflows we don't really care, we just need to make1010* sure it is at least minIndexToOverflowCorrect.1011*/1012U32 const adjustment = window.nbOverflowCorrections + 1;1013U32 const adjustedIndex = MAX(minIndexToOverflowCorrect * adjustment,1014minIndexToOverflowCorrect);1015U32 const indexLargeEnough = curr > adjustedIndex;10161017/* Only overflow correct early if the dictionary is invalidated already,1018* so we don't hurt compression ratio.1019*/1020U32 const dictionaryInvalidated = curr > maxDist + loadedDictEnd;10211022return indexLargeEnough && dictionaryInvalidated;1023}10241025/**1026* ZSTD_window_needOverflowCorrection():1027* Returns non-zero if the indices are getting too large and need overflow1028* protection.1029*/1030MEM_STATIC U32 ZSTD_window_needOverflowCorrection(ZSTD_window_t const window,1031U32 cycleLog,1032U32 maxDist,1033U32 loadedDictEnd,1034void const* src,1035void const* srcEnd)1036{1037U32 const curr = (U32)((BYTE const*)srcEnd - window.base);1038if (ZSTD_WINDOW_OVERFLOW_CORRECT_FREQUENTLY) {1039if (ZSTD_window_canOverflowCorrect(window, cycleLog, maxDist, loadedDictEnd, src)) {1040return 1;1041}1042}1043return curr > ZSTD_CURRENT_MAX;1044}10451046/**1047* ZSTD_window_correctOverflow():1048* Reduces the indices to protect from index overflow.1049* Returns the correction made to the indices, which must be applied to every1050* stored index.1051*1052* The least significant cycleLog bits of the indices must remain the same,1053* which may be 0. Every index up to maxDist in the past must be valid.1054*/1055MEM_STATIC U32 ZSTD_window_correctOverflow(ZSTD_window_t* window, U32 cycleLog,1056U32 maxDist, void const* src)1057{1058/* preemptive overflow correction:1059* 1. correction is large enough:1060* lowLimit > (3<<29) ==> current > 3<<29 + 1<<windowLog1061* 1<<windowLog <= newCurrent < 1<<chainLog + 1<<windowLog1062*1063* current - newCurrent1064* > (3<<29 + 1<<windowLog) - (1<<windowLog + 1<<chainLog)1065* > (3<<29) - (1<<chainLog)1066* > (3<<29) - (1<<30) (NOTE: chainLog <= 30)1067* > 1<<291068*1069* 2. (ip+ZSTD_CHUNKSIZE_MAX - cctx->base) doesn't overflow:1070* After correction, current is less than (1<<chainLog + 1<<windowLog).1071* In 64-bit mode we are safe, because we have 64-bit ptrdiff_t.1072* In 32-bit mode we are safe, because (chainLog <= 29), so1073* ip+ZSTD_CHUNKSIZE_MAX - cctx->base < 1<<32.1074* 3. (cctx->lowLimit + 1<<windowLog) < 1<<32:1075* windowLog <= 31 ==> 3<<29 + 1<<windowLog < 7<<29 < 1<<32.1076*/1077U32 const cycleSize = 1u << cycleLog;1078U32 const cycleMask = cycleSize - 1;1079U32 const curr = (U32)((BYTE const*)src - window->base);1080U32 const currentCycle = curr & cycleMask;1081/* Ensure newCurrent - maxDist >= ZSTD_WINDOW_START_INDEX. */1082U32 const currentCycleCorrection = currentCycle < ZSTD_WINDOW_START_INDEX1083? MAX(cycleSize, ZSTD_WINDOW_START_INDEX)1084: 0;1085U32 const newCurrent = currentCycle1086+ currentCycleCorrection1087+ MAX(maxDist, cycleSize);1088U32 const correction = curr - newCurrent;1089/* maxDist must be a power of two so that:1090* (newCurrent & cycleMask) == (curr & cycleMask)1091* This is required to not corrupt the chains / binary tree.1092*/1093assert((maxDist & (maxDist - 1)) == 0);1094assert((curr & cycleMask) == (newCurrent & cycleMask));1095assert(curr > newCurrent);1096if (!ZSTD_WINDOW_OVERFLOW_CORRECT_FREQUENTLY) {1097/* Loose bound, should be around 1<<29 (see above) */1098assert(correction > 1<<28);1099}11001101window->base += correction;1102window->dictBase += correction;1103if (window->lowLimit < correction + ZSTD_WINDOW_START_INDEX) {1104window->lowLimit = ZSTD_WINDOW_START_INDEX;1105} else {1106window->lowLimit -= correction;1107}1108if (window->dictLimit < correction + ZSTD_WINDOW_START_INDEX) {1109window->dictLimit = ZSTD_WINDOW_START_INDEX;1110} else {1111window->dictLimit -= correction;1112}11131114/* Ensure we can still reference the full window. */1115assert(newCurrent >= maxDist);1116assert(newCurrent - maxDist >= ZSTD_WINDOW_START_INDEX);1117/* Ensure that lowLimit and dictLimit didn't underflow. */1118assert(window->lowLimit <= newCurrent);1119assert(window->dictLimit <= newCurrent);11201121++window->nbOverflowCorrections;11221123DEBUGLOG(4, "Correction of 0x%x bytes to lowLimit=0x%x", correction,1124window->lowLimit);1125return correction;1126}11271128/**1129* ZSTD_window_enforceMaxDist():1130* Updates lowLimit so that:1131* (srcEnd - base) - lowLimit == maxDist + loadedDictEnd1132*1133* It ensures index is valid as long as index >= lowLimit.1134* This must be called before a block compression call.1135*1136* loadedDictEnd is only defined if a dictionary is in use for current compression.1137* As the name implies, loadedDictEnd represents the index at end of dictionary.1138* The value lies within context's referential, it can be directly compared to blockEndIdx.1139*1140* If loadedDictEndPtr is NULL, no dictionary is in use, and we use loadedDictEnd == 0.1141* If loadedDictEndPtr is not NULL, we set it to zero after updating lowLimit.1142* This is because dictionaries are allowed to be referenced fully1143* as long as the last byte of the dictionary is in the window.1144* Once input has progressed beyond window size, dictionary cannot be referenced anymore.1145*1146* In normal dict mode, the dictionary lies between lowLimit and dictLimit.1147* In dictMatchState mode, lowLimit and dictLimit are the same,1148* and the dictionary is below them.1149* forceWindow and dictMatchState are therefore incompatible.1150*/1151MEM_STATIC void1152ZSTD_window_enforceMaxDist(ZSTD_window_t* window,1153const void* blockEnd,1154U32 maxDist,1155U32* loadedDictEndPtr,1156const ZSTD_matchState_t** dictMatchStatePtr)1157{1158U32 const blockEndIdx = (U32)((BYTE const*)blockEnd - window->base);1159U32 const loadedDictEnd = (loadedDictEndPtr != NULL) ? *loadedDictEndPtr : 0;1160DEBUGLOG(5, "ZSTD_window_enforceMaxDist: blockEndIdx=%u, maxDist=%u, loadedDictEnd=%u",1161(unsigned)blockEndIdx, (unsigned)maxDist, (unsigned)loadedDictEnd);11621163/* - When there is no dictionary : loadedDictEnd == 0.1164In which case, the test (blockEndIdx > maxDist) is merely to avoid1165overflowing next operation `newLowLimit = blockEndIdx - maxDist`.1166- When there is a standard dictionary :1167Index referential is copied from the dictionary,1168which means it starts from 0.1169In which case, loadedDictEnd == dictSize,1170and it makes sense to compare `blockEndIdx > maxDist + dictSize`1171since `blockEndIdx` also starts from zero.1172- When there is an attached dictionary :1173loadedDictEnd is expressed within the referential of the context,1174so it can be directly compared against blockEndIdx.1175*/1176if (blockEndIdx > maxDist + loadedDictEnd) {1177U32 const newLowLimit = blockEndIdx - maxDist;1178if (window->lowLimit < newLowLimit) window->lowLimit = newLowLimit;1179if (window->dictLimit < window->lowLimit) {1180DEBUGLOG(5, "Update dictLimit to match lowLimit, from %u to %u",1181(unsigned)window->dictLimit, (unsigned)window->lowLimit);1182window->dictLimit = window->lowLimit;1183}1184/* On reaching window size, dictionaries are invalidated */1185if (loadedDictEndPtr) *loadedDictEndPtr = 0;1186if (dictMatchStatePtr) *dictMatchStatePtr = NULL;1187}1188}11891190/* Similar to ZSTD_window_enforceMaxDist(),1191* but only invalidates dictionary1192* when input progresses beyond window size.1193* assumption : loadedDictEndPtr and dictMatchStatePtr are valid (non NULL)1194* loadedDictEnd uses same referential as window->base1195* maxDist is the window size */1196MEM_STATIC void1197ZSTD_checkDictValidity(const ZSTD_window_t* window,1198const void* blockEnd,1199U32 maxDist,1200U32* loadedDictEndPtr,1201const ZSTD_matchState_t** dictMatchStatePtr)1202{1203assert(loadedDictEndPtr != NULL);1204assert(dictMatchStatePtr != NULL);1205{ U32 const blockEndIdx = (U32)((BYTE const*)blockEnd - window->base);1206U32 const loadedDictEnd = *loadedDictEndPtr;1207DEBUGLOG(5, "ZSTD_checkDictValidity: blockEndIdx=%u, maxDist=%u, loadedDictEnd=%u",1208(unsigned)blockEndIdx, (unsigned)maxDist, (unsigned)loadedDictEnd);1209assert(blockEndIdx >= loadedDictEnd);12101211if (blockEndIdx > loadedDictEnd + maxDist || loadedDictEnd != window->dictLimit) {1212/* On reaching window size, dictionaries are invalidated.1213* For simplification, if window size is reached anywhere within next block,1214* the dictionary is invalidated for the full block.1215*1216* We also have to invalidate the dictionary if ZSTD_window_update() has detected1217* non-contiguous segments, which means that loadedDictEnd != window->dictLimit.1218* loadedDictEnd may be 0, if forceWindow is true, but in that case we never use1219* dictMatchState, so setting it to NULL is not a problem.1220*/1221DEBUGLOG(6, "invalidating dictionary for current block (distance > windowSize)");1222*loadedDictEndPtr = 0;1223*dictMatchStatePtr = NULL;1224} else {1225if (*loadedDictEndPtr != 0) {1226DEBUGLOG(6, "dictionary considered valid for current block");1227} } }1228}12291230MEM_STATIC void ZSTD_window_init(ZSTD_window_t* window) {1231ZSTD_memset(window, 0, sizeof(*window));1232window->base = (BYTE const*)" ";1233window->dictBase = (BYTE const*)" ";1234ZSTD_STATIC_ASSERT(ZSTD_DUBT_UNSORTED_MARK < ZSTD_WINDOW_START_INDEX); /* Start above ZSTD_DUBT_UNSORTED_MARK */1235window->dictLimit = ZSTD_WINDOW_START_INDEX; /* start from >0, so that 1st position is valid */1236window->lowLimit = ZSTD_WINDOW_START_INDEX; /* it ensures first and later CCtx usages compress the same */1237window->nextSrc = window->base + ZSTD_WINDOW_START_INDEX; /* see issue #1241 */1238window->nbOverflowCorrections = 0;1239}12401241/**1242* ZSTD_window_update():1243* Updates the window by appending [src, src + srcSize) to the window.1244* If it is not contiguous, the current prefix becomes the extDict, and we1245* forget about the extDict. Handles overlap of the prefix and extDict.1246* Returns non-zero if the segment is contiguous.1247*/1248MEM_STATIC U32 ZSTD_window_update(ZSTD_window_t* window,1249void const* src, size_t srcSize,1250int forceNonContiguous)1251{1252BYTE const* const ip = (BYTE const*)src;1253U32 contiguous = 1;1254DEBUGLOG(5, "ZSTD_window_update");1255if (srcSize == 0)1256return contiguous;1257assert(window->base != NULL);1258assert(window->dictBase != NULL);1259/* Check if blocks follow each other */1260if (src != window->nextSrc || forceNonContiguous) {1261/* not contiguous */1262size_t const distanceFromBase = (size_t)(window->nextSrc - window->base);1263DEBUGLOG(5, "Non contiguous blocks, new segment starts at %u", window->dictLimit);1264window->lowLimit = window->dictLimit;1265assert(distanceFromBase == (size_t)(U32)distanceFromBase); /* should never overflow */1266window->dictLimit = (U32)distanceFromBase;1267window->dictBase = window->base;1268window->base = ip - distanceFromBase;1269/* ms->nextToUpdate = window->dictLimit; */1270if (window->dictLimit - window->lowLimit < HASH_READ_SIZE) window->lowLimit = window->dictLimit; /* too small extDict */1271contiguous = 0;1272}1273window->nextSrc = ip + srcSize;1274/* if input and dictionary overlap : reduce dictionary (area presumed modified by input) */1275if ( (ip+srcSize > window->dictBase + window->lowLimit)1276& (ip < window->dictBase + window->dictLimit)) {1277ptrdiff_t const highInputIdx = (ip + srcSize) - window->dictBase;1278U32 const lowLimitMax = (highInputIdx > (ptrdiff_t)window->dictLimit) ? window->dictLimit : (U32)highInputIdx;1279window->lowLimit = lowLimitMax;1280DEBUGLOG(5, "Overlapping extDict and input : new lowLimit = %u", window->lowLimit);1281}1282return contiguous;1283}12841285/**1286* Returns the lowest allowed match index. It may either be in the ext-dict or the prefix.1287*/1288MEM_STATIC U32 ZSTD_getLowestMatchIndex(const ZSTD_matchState_t* ms, U32 curr, unsigned windowLog)1289{1290U32 const maxDistance = 1U << windowLog;1291U32 const lowestValid = ms->window.lowLimit;1292U32 const withinWindow = (curr - lowestValid > maxDistance) ? curr - maxDistance : lowestValid;1293U32 const isDictionary = (ms->loadedDictEnd != 0);1294/* When using a dictionary the entire dictionary is valid if a single byte of the dictionary1295* is within the window. We invalidate the dictionary (and set loadedDictEnd to 0) when it isn't1296* valid for the entire block. So this check is sufficient to find the lowest valid match index.1297*/1298U32 const matchLowest = isDictionary ? lowestValid : withinWindow;1299return matchLowest;1300}13011302/**1303* Returns the lowest allowed match index in the prefix.1304*/1305MEM_STATIC U32 ZSTD_getLowestPrefixIndex(const ZSTD_matchState_t* ms, U32 curr, unsigned windowLog)1306{1307U32 const maxDistance = 1U << windowLog;1308U32 const lowestValid = ms->window.dictLimit;1309U32 const withinWindow = (curr - lowestValid > maxDistance) ? curr - maxDistance : lowestValid;1310U32 const isDictionary = (ms->loadedDictEnd != 0);1311/* When computing the lowest prefix index we need to take the dictionary into account to handle1312* the edge case where the dictionary and the source are contiguous in memory.1313*/1314U32 const matchLowest = isDictionary ? lowestValid : withinWindow;1315return matchLowest;1316}1317131813191320/* debug functions */1321#if (DEBUGLEVEL>=2)13221323MEM_STATIC double ZSTD_fWeight(U32 rawStat)1324{1325U32 const fp_accuracy = 8;1326U32 const fp_multiplier = (1 << fp_accuracy);1327U32 const newStat = rawStat + 1;1328U32 const hb = ZSTD_highbit32(newStat);1329U32 const BWeight = hb * fp_multiplier;1330U32 const FWeight = (newStat << fp_accuracy) >> hb;1331U32 const weight = BWeight + FWeight;1332assert(hb + fp_accuracy < 31);1333return (double)weight / fp_multiplier;1334}13351336/* display a table content,1337* listing each element, its frequency, and its predicted bit cost */1338MEM_STATIC void ZSTD_debugTable(const U32* table, U32 max)1339{1340unsigned u, sum;1341for (u=0, sum=0; u<=max; u++) sum += table[u];1342DEBUGLOG(2, "total nb elts: %u", sum);1343for (u=0; u<=max; u++) {1344DEBUGLOG(2, "%2u: %5u (%.2f)",1345u, table[u], ZSTD_fWeight(sum) - ZSTD_fWeight(table[u]) );1346}1347}13481349#endif13501351/* Short Cache */13521353/* Normally, zstd matchfinders follow this flow:1354* 1. Compute hash at ip1355* 2. Load index from hashTable[hash]1356* 3. Check if *ip == *(base + index)1357* In dictionary compression, loading *(base + index) is often an L2 or even L3 miss.1358*1359* Short cache is an optimization which allows us to avoid step 3 most of the time1360* when the data doesn't actually match. With short cache, the flow becomes:1361* 1. Compute (hash, currentTag) at ip. currentTag is an 8-bit independent hash at ip.1362* 2. Load (index, matchTag) from hashTable[hash]. See ZSTD_writeTaggedIndex to understand how this works.1363* 3. Only if currentTag == matchTag, check *ip == *(base + index). Otherwise, continue.1364*1365* Currently, short cache is only implemented in CDict hashtables. Thus, its use is limited to1366* dictMatchState matchfinders.1367*/1368#define ZSTD_SHORT_CACHE_TAG_BITS 81369#define ZSTD_SHORT_CACHE_TAG_MASK ((1u << ZSTD_SHORT_CACHE_TAG_BITS) - 1)13701371/* Helper function for ZSTD_fillHashTable and ZSTD_fillDoubleHashTable.1372* Unpacks hashAndTag into (hash, tag), then packs (index, tag) into hashTable[hash]. */1373MEM_STATIC void ZSTD_writeTaggedIndex(U32* const hashTable, size_t hashAndTag, U32 index) {1374size_t const hash = hashAndTag >> ZSTD_SHORT_CACHE_TAG_BITS;1375U32 const tag = (U32)(hashAndTag & ZSTD_SHORT_CACHE_TAG_MASK);1376assert(index >> (32 - ZSTD_SHORT_CACHE_TAG_BITS) == 0);1377hashTable[hash] = (index << ZSTD_SHORT_CACHE_TAG_BITS) | tag;1378}13791380/* Helper function for short cache matchfinders.1381* Unpacks tag1 and tag2 from lower bits of packedTag1 and packedTag2, then checks if the tags match. */1382MEM_STATIC int ZSTD_comparePackedTags(size_t packedTag1, size_t packedTag2) {1383U32 const tag1 = packedTag1 & ZSTD_SHORT_CACHE_TAG_MASK;1384U32 const tag2 = packedTag2 & ZSTD_SHORT_CACHE_TAG_MASK;1385return tag1 == tag2;1386}13871388#if defined (__cplusplus)1389}1390#endif13911392/* ===============================================================1393* Shared internal declarations1394* These prototypes may be called from sources not in lib/compress1395* =============================================================== */13961397/* ZSTD_loadCEntropy() :1398* dict : must point at beginning of a valid zstd dictionary.1399* return : size of dictionary header (size of magic number + dict ID + entropy tables)1400* assumptions : magic number supposed already checked1401* and dictSize >= 8 */1402size_t ZSTD_loadCEntropy(ZSTD_compressedBlockState_t* bs, void* workspace,1403const void* const dict, size_t dictSize);14041405void ZSTD_reset_compressedBlockState(ZSTD_compressedBlockState_t* bs);14061407/* ==============================================================1408* Private declarations1409* These prototypes shall only be called from within lib/compress1410* ============================================================== */14111412/* ZSTD_getCParamsFromCCtxParams() :1413* cParams are built depending on compressionLevel, src size hints,1414* LDM and manually set compression parameters.1415* Note: srcSizeHint == 0 means 0!1416*/1417ZSTD_compressionParameters ZSTD_getCParamsFromCCtxParams(1418const ZSTD_CCtx_params* CCtxParams, U64 srcSizeHint, size_t dictSize, ZSTD_cParamMode_e mode);14191420/*! ZSTD_initCStream_internal() :1421* Private use only. Init streaming operation.1422* expects params to be valid.1423* must receive dict, or cdict, or none, but not both.1424* @return : 0, or an error code */1425size_t ZSTD_initCStream_internal(ZSTD_CStream* zcs,1426const void* dict, size_t dictSize,1427const ZSTD_CDict* cdict,1428const ZSTD_CCtx_params* params, unsigned long long pledgedSrcSize);14291430void ZSTD_resetSeqStore(seqStore_t* ssPtr);14311432/*! ZSTD_getCParamsFromCDict() :1433* as the name implies */1434ZSTD_compressionParameters ZSTD_getCParamsFromCDict(const ZSTD_CDict* cdict);14351436/* ZSTD_compressBegin_advanced_internal() :1437* Private use only. To be called from zstdmt_compress.c. */1438size_t ZSTD_compressBegin_advanced_internal(ZSTD_CCtx* cctx,1439const void* dict, size_t dictSize,1440ZSTD_dictContentType_e dictContentType,1441ZSTD_dictTableLoadMethod_e dtlm,1442const ZSTD_CDict* cdict,1443const ZSTD_CCtx_params* params,1444unsigned long long pledgedSrcSize);14451446/* ZSTD_compress_advanced_internal() :1447* Private use only. To be called from zstdmt_compress.c. */1448size_t ZSTD_compress_advanced_internal(ZSTD_CCtx* cctx,1449void* dst, size_t dstCapacity,1450const void* src, size_t srcSize,1451const void* dict,size_t dictSize,1452const ZSTD_CCtx_params* params);145314541455/* ZSTD_writeLastEmptyBlock() :1456* output an empty Block with end-of-frame mark to complete a frame1457* @return : size of data written into `dst` (== ZSTD_blockHeaderSize (defined in zstd_internal.h))1458* or an error code if `dstCapacity` is too small (<ZSTD_blockHeaderSize)1459*/1460size_t ZSTD_writeLastEmptyBlock(void* dst, size_t dstCapacity);146114621463/* ZSTD_referenceExternalSequences() :1464* Must be called before starting a compression operation.1465* seqs must parse a prefix of the source.1466* This cannot be used when long range matching is enabled.1467* Zstd will use these sequences, and pass the literals to a secondary block1468* compressor.1469* @return : An error code on failure.1470* NOTE: seqs are not verified! Invalid sequences can cause out-of-bounds memory1471* access and data corruption.1472*/1473size_t ZSTD_referenceExternalSequences(ZSTD_CCtx* cctx, rawSeq* seq, size_t nbSeq);14741475/** ZSTD_cycleLog() :1476* condition for correct operation : hashLog > 1 */1477U32 ZSTD_cycleLog(U32 hashLog, ZSTD_strategy strat);14781479/** ZSTD_CCtx_trace() :1480* Trace the end of a compression call.1481*/1482void ZSTD_CCtx_trace(ZSTD_CCtx* cctx, size_t extraCSize);14831484/* Returns 0 on success, and a ZSTD_error otherwise. This function scans through an array of1485* ZSTD_Sequence, storing the sequences it finds, until it reaches a block delimiter.1486* Note that the block delimiter must include the last literals of the block.1487*/1488size_t1489ZSTD_copySequencesToSeqStoreExplicitBlockDelim(ZSTD_CCtx* cctx,1490ZSTD_sequencePosition* seqPos,1491const ZSTD_Sequence* const inSeqs, size_t inSeqsSize,1492const void* src, size_t blockSize, ZSTD_paramSwitch_e externalRepSearch);14931494/* Returns the number of bytes to move the current read position back by.1495* Only non-zero if we ended up splitting a sequence.1496* Otherwise, it may return a ZSTD error if something went wrong.1497*1498* This function will attempt to scan through blockSize bytes1499* represented by the sequences in @inSeqs,1500* storing any (partial) sequences.1501*1502* Occasionally, we may want to change the actual number of bytes we consumed from inSeqs to1503* avoid splitting a match, or to avoid splitting a match such that it would produce a match1504* smaller than MINMATCH. In this case, we return the number of bytes that we didn't read from this block.1505*/1506size_t1507ZSTD_copySequencesToSeqStoreNoBlockDelim(ZSTD_CCtx* cctx, ZSTD_sequencePosition* seqPos,1508const ZSTD_Sequence* const inSeqs, size_t inSeqsSize,1509const void* src, size_t blockSize, ZSTD_paramSwitch_e externalRepSearch);151015111512/* ===============================================================1513* Deprecated definitions that are still used internally to avoid1514* deprecation warnings. These functions are exactly equivalent to1515* their public variants, but avoid the deprecation warnings.1516* =============================================================== */15171518size_t ZSTD_compressBegin_usingCDict_deprecated(ZSTD_CCtx* cctx, const ZSTD_CDict* cdict);15191520size_t ZSTD_compressContinue_public(ZSTD_CCtx* cctx,1521void* dst, size_t dstCapacity,1522const void* src, size_t srcSize);15231524size_t ZSTD_compressEnd_public(ZSTD_CCtx* cctx,1525void* dst, size_t dstCapacity,1526const void* src, size_t srcSize);15271528size_t ZSTD_compressBlock_deprecated(ZSTD_CCtx* cctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize);152915301531#endif /* ZSTD_COMPRESS_H */153215331534