Path: blob/main/sys/contrib/zstd/lib/compress/zstd_compress_internal.h
48378 views
/*1* Copyright (c) Yann Collet, Facebook, Inc.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#endif2526#if defined (__cplusplus)27extern "C" {28#endif2930/*-*************************************31* Constants32***************************************/33#define kSearchStrength 834#define HASH_READ_SIZE 835#define ZSTD_DUBT_UNSORTED_MARK 1 /* For btlazy2 strategy, index ZSTD_DUBT_UNSORTED_MARK==1 means "unsorted".36It could be confused for a real successor at index "1", if sorted as larger than its predecessor.37It's not a big deal though : candidate will just be sorted again.38Additionally, candidate position 1 will be lost.39But candidate 1 cannot hide a large tree of candidates, so it's a minimal loss.40The benefit is that ZSTD_DUBT_UNSORTED_MARK cannot be mishandled after table re-use with a different strategy.41This constant is required by ZSTD_compressBlock_btlazy2() and ZSTD_reduceTable_internal() */424344/*-*************************************45* Context memory management46***************************************/47typedef enum { ZSTDcs_created=0, ZSTDcs_init, ZSTDcs_ongoing, ZSTDcs_ending } ZSTD_compressionStage_e;48typedef enum { zcss_init=0, zcss_load, zcss_flush } ZSTD_cStreamStage;4950typedef struct ZSTD_prefixDict_s {51const void* dict;52size_t dictSize;53ZSTD_dictContentType_e dictContentType;54} ZSTD_prefixDict;5556typedef struct {57void* dictBuffer;58void const* dict;59size_t dictSize;60ZSTD_dictContentType_e dictContentType;61ZSTD_CDict* cdict;62} ZSTD_localDict;6364typedef struct {65HUF_CElt CTable[HUF_CTABLE_SIZE_ST(255)];66HUF_repeat repeatMode;67} ZSTD_hufCTables_t;6869typedef struct {70FSE_CTable offcodeCTable[FSE_CTABLE_SIZE_U32(OffFSELog, MaxOff)];71FSE_CTable matchlengthCTable[FSE_CTABLE_SIZE_U32(MLFSELog, MaxML)];72FSE_CTable litlengthCTable[FSE_CTABLE_SIZE_U32(LLFSELog, MaxLL)];73FSE_repeat offcode_repeatMode;74FSE_repeat matchlength_repeatMode;75FSE_repeat litlength_repeatMode;76} ZSTD_fseCTables_t;7778typedef struct {79ZSTD_hufCTables_t huf;80ZSTD_fseCTables_t fse;81} ZSTD_entropyCTables_t;8283/***********************************************84* Entropy buffer statistics structs and funcs *85***********************************************/86/** ZSTD_hufCTablesMetadata_t :87* Stores Literals Block Type for a super-block in hType, and88* huffman tree description in hufDesBuffer.89* hufDesSize refers to the size of huffman tree description in bytes.90* This metadata is populated in ZSTD_buildBlockEntropyStats_literals() */91typedef struct {92symbolEncodingType_e hType;93BYTE hufDesBuffer[ZSTD_MAX_HUF_HEADER_SIZE];94size_t hufDesSize;95} ZSTD_hufCTablesMetadata_t;9697/** ZSTD_fseCTablesMetadata_t :98* Stores symbol compression modes for a super-block in {ll, ol, ml}Type, and99* fse tables in fseTablesBuffer.100* fseTablesSize refers to the size of fse tables in bytes.101* This metadata is populated in ZSTD_buildBlockEntropyStats_sequences() */102typedef struct {103symbolEncodingType_e llType;104symbolEncodingType_e ofType;105symbolEncodingType_e mlType;106BYTE fseTablesBuffer[ZSTD_MAX_FSE_HEADERS_SIZE];107size_t fseTablesSize;108size_t lastCountSize; /* This is to account for bug in 1.3.4. More detail in ZSTD_entropyCompressSeqStore_internal() */109} ZSTD_fseCTablesMetadata_t;110111typedef struct {112ZSTD_hufCTablesMetadata_t hufMetadata;113ZSTD_fseCTablesMetadata_t fseMetadata;114} ZSTD_entropyCTablesMetadata_t;115116/** ZSTD_buildBlockEntropyStats() :117* Builds entropy for the block.118* @return : 0 on success or error code */119size_t ZSTD_buildBlockEntropyStats(seqStore_t* seqStorePtr,120const ZSTD_entropyCTables_t* prevEntropy,121ZSTD_entropyCTables_t* nextEntropy,122const ZSTD_CCtx_params* cctxParams,123ZSTD_entropyCTablesMetadata_t* entropyMetadata,124void* workspace, size_t wkspSize);125126/*********************************127* Compression internals structs *128*********************************/129130typedef struct {131U32 off; /* Offset sumtype code for the match, using ZSTD_storeSeq() format */132U32 len; /* Raw length of match */133} ZSTD_match_t;134135typedef struct {136U32 offset; /* Offset of sequence */137U32 litLength; /* Length of literals prior to match */138U32 matchLength; /* Raw length of match */139} rawSeq;140141typedef struct {142rawSeq* seq; /* The start of the sequences */143size_t pos; /* The index in seq where reading stopped. pos <= size. */144size_t posInSequence; /* The position within the sequence at seq[pos] where reading145stopped. posInSequence <= seq[pos].litLength + seq[pos].matchLength */146size_t size; /* The number of sequences. <= capacity. */147size_t capacity; /* The capacity starting from `seq` pointer */148} rawSeqStore_t;149150UNUSED_ATTR static const rawSeqStore_t kNullRawSeqStore = {NULL, 0, 0, 0, 0};151152typedef struct {153int price;154U32 off;155U32 mlen;156U32 litlen;157U32 rep[ZSTD_REP_NUM];158} ZSTD_optimal_t;159160typedef enum { zop_dynamic=0, zop_predef } ZSTD_OptPrice_e;161162typedef struct {163/* All tables are allocated inside cctx->workspace by ZSTD_resetCCtx_internal() */164unsigned* litFreq; /* table of literals statistics, of size 256 */165unsigned* litLengthFreq; /* table of litLength statistics, of size (MaxLL+1) */166unsigned* matchLengthFreq; /* table of matchLength statistics, of size (MaxML+1) */167unsigned* offCodeFreq; /* table of offCode statistics, of size (MaxOff+1) */168ZSTD_match_t* matchTable; /* list of found matches, of size ZSTD_OPT_NUM+1 */169ZSTD_optimal_t* priceTable; /* All positions tracked by optimal parser, of size ZSTD_OPT_NUM+1 */170171U32 litSum; /* nb of literals */172U32 litLengthSum; /* nb of litLength codes */173U32 matchLengthSum; /* nb of matchLength codes */174U32 offCodeSum; /* nb of offset codes */175U32 litSumBasePrice; /* to compare to log2(litfreq) */176U32 litLengthSumBasePrice; /* to compare to log2(llfreq) */177U32 matchLengthSumBasePrice;/* to compare to log2(mlfreq) */178U32 offCodeSumBasePrice; /* to compare to log2(offreq) */179ZSTD_OptPrice_e priceType; /* prices can be determined dynamically, or follow a pre-defined cost structure */180const ZSTD_entropyCTables_t* symbolCosts; /* pre-calculated dictionary statistics */181ZSTD_paramSwitch_e literalCompressionMode;182} optState_t;183184typedef struct {185ZSTD_entropyCTables_t entropy;186U32 rep[ZSTD_REP_NUM];187} ZSTD_compressedBlockState_t;188189typedef struct {190BYTE const* nextSrc; /* next block here to continue on current prefix */191BYTE const* base; /* All regular indexes relative to this position */192BYTE const* dictBase; /* extDict indexes relative to this position */193U32 dictLimit; /* below that point, need extDict */194U32 lowLimit; /* below that point, no more valid data */195U32 nbOverflowCorrections; /* Number of times overflow correction has run since196* ZSTD_window_init(). Useful for debugging coredumps197* and for ZSTD_WINDOW_OVERFLOW_CORRECT_FREQUENTLY.198*/199} ZSTD_window_t;200201#define ZSTD_WINDOW_START_INDEX 2202203typedef struct ZSTD_matchState_t ZSTD_matchState_t;204205#define ZSTD_ROW_HASH_CACHE_SIZE 8 /* Size of prefetching hash cache for row-based matchfinder */206207struct ZSTD_matchState_t {208ZSTD_window_t window; /* State for window round buffer management */209U32 loadedDictEnd; /* index of end of dictionary, within context's referential.210* When loadedDictEnd != 0, a dictionary is in use, and still valid.211* This relies on a mechanism to set loadedDictEnd=0 when dictionary is no longer within distance.212* Such mechanism is provided within ZSTD_window_enforceMaxDist() and ZSTD_checkDictValidity().213* When dict referential is copied into active context (i.e. not attached),214* loadedDictEnd == dictSize, since referential starts from zero.215*/216U32 nextToUpdate; /* index from which to continue table update */217U32 hashLog3; /* dispatch table for matches of len==3 : larger == faster, more memory */218219U32 rowHashLog; /* For row-based matchfinder: Hashlog based on nb of rows in the hashTable.*/220U16* tagTable; /* For row-based matchFinder: A row-based table containing the hashes and head index. */221U32 hashCache[ZSTD_ROW_HASH_CACHE_SIZE]; /* For row-based matchFinder: a cache of hashes to improve speed */222223U32* hashTable;224U32* hashTable3;225U32* chainTable;226227U32 forceNonContiguous; /* Non-zero if we should force non-contiguous load for the next window update. */228229int dedicatedDictSearch; /* Indicates whether this matchState is using the230* dedicated dictionary search structure.231*/232optState_t opt; /* optimal parser state */233const ZSTD_matchState_t* dictMatchState;234ZSTD_compressionParameters cParams;235const rawSeqStore_t* ldmSeqStore;236};237238typedef struct {239ZSTD_compressedBlockState_t* prevCBlock;240ZSTD_compressedBlockState_t* nextCBlock;241ZSTD_matchState_t matchState;242} ZSTD_blockState_t;243244typedef struct {245U32 offset;246U32 checksum;247} ldmEntry_t;248249typedef struct {250BYTE const* split;251U32 hash;252U32 checksum;253ldmEntry_t* bucket;254} ldmMatchCandidate_t;255256#define LDM_BATCH_SIZE 64257258typedef struct {259ZSTD_window_t window; /* State for the window round buffer management */260ldmEntry_t* hashTable;261U32 loadedDictEnd;262BYTE* bucketOffsets; /* Next position in bucket to insert entry */263size_t splitIndices[LDM_BATCH_SIZE];264ldmMatchCandidate_t matchCandidates[LDM_BATCH_SIZE];265} ldmState_t;266267typedef struct {268ZSTD_paramSwitch_e enableLdm; /* ZSTD_ps_enable to enable LDM. ZSTD_ps_auto by default */269U32 hashLog; /* Log size of hashTable */270U32 bucketSizeLog; /* Log bucket size for collision resolution, at most 8 */271U32 minMatchLength; /* Minimum match length */272U32 hashRateLog; /* Log number of entries to skip */273U32 windowLog; /* Window log for the LDM */274} ldmParams_t;275276typedef struct {277int collectSequences;278ZSTD_Sequence* seqStart;279size_t seqIndex;280size_t maxSequences;281} SeqCollector;282283struct ZSTD_CCtx_params_s {284ZSTD_format_e format;285ZSTD_compressionParameters cParams;286ZSTD_frameParameters fParams;287288int compressionLevel;289int forceWindow; /* force back-references to respect limit of290* 1<<wLog, even for dictionary */291size_t targetCBlockSize; /* Tries to fit compressed block size to be around targetCBlockSize.292* No target when targetCBlockSize == 0.293* There is no guarantee on compressed block size */294int srcSizeHint; /* User's best guess of source size.295* Hint is not valid when srcSizeHint == 0.296* There is no guarantee that hint is close to actual source size */297298ZSTD_dictAttachPref_e attachDictPref;299ZSTD_paramSwitch_e literalCompressionMode;300301/* Multithreading: used to pass parameters to mtctx */302int nbWorkers;303size_t jobSize;304int overlapLog;305int rsyncable;306307/* Long distance matching parameters */308ldmParams_t ldmParams;309310/* Dedicated dict search algorithm trigger */311int enableDedicatedDictSearch;312313/* Input/output buffer modes */314ZSTD_bufferMode_e inBufferMode;315ZSTD_bufferMode_e outBufferMode;316317/* Sequence compression API */318ZSTD_sequenceFormat_e blockDelimiters;319int validateSequences;320321/* Block splitting */322ZSTD_paramSwitch_e useBlockSplitter;323324/* Param for deciding whether to use row-based matchfinder */325ZSTD_paramSwitch_e useRowMatchFinder;326327/* Always load a dictionary in ext-dict mode (not prefix mode)? */328int deterministicRefPrefix;329330/* Internal use, for createCCtxParams() and freeCCtxParams() only */331ZSTD_customMem customMem;332}; /* typedef'd to ZSTD_CCtx_params within "zstd.h" */333334#define COMPRESS_SEQUENCES_WORKSPACE_SIZE (sizeof(unsigned) * (MaxSeq + 2))335#define ENTROPY_WORKSPACE_SIZE (HUF_WORKSPACE_SIZE + COMPRESS_SEQUENCES_WORKSPACE_SIZE)336337/**338* Indicates whether this compression proceeds directly from user-provided339* source buffer to user-provided destination buffer (ZSTDb_not_buffered), or340* whether the context needs to buffer the input/output (ZSTDb_buffered).341*/342typedef enum {343ZSTDb_not_buffered,344ZSTDb_buffered345} ZSTD_buffered_policy_e;346347/**348* Struct that contains all elements of block splitter that should be allocated349* in a wksp.350*/351#define ZSTD_MAX_NB_BLOCK_SPLITS 196352typedef struct {353seqStore_t fullSeqStoreChunk;354seqStore_t firstHalfSeqStore;355seqStore_t secondHalfSeqStore;356seqStore_t currSeqStore;357seqStore_t nextSeqStore;358359U32 partitions[ZSTD_MAX_NB_BLOCK_SPLITS];360ZSTD_entropyCTablesMetadata_t entropyMetadata;361} ZSTD_blockSplitCtx;362363struct ZSTD_CCtx_s {364ZSTD_compressionStage_e stage;365int 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. */366int bmi2; /* == 1 if the CPU supports BMI2 and 0 otherwise. CPU support is determined dynamically once per context lifetime. */367ZSTD_CCtx_params requestedParams;368ZSTD_CCtx_params appliedParams;369ZSTD_CCtx_params simpleApiParams; /* Param storage used by the simple API - not sticky. Must only be used in top-level simple API functions for storage. */370U32 dictID;371size_t dictContentSize;372373ZSTD_cwksp workspace; /* manages buffer for dynamic allocations */374size_t blockSize;375unsigned long long pledgedSrcSizePlusOne; /* this way, 0 (default) == unknown */376unsigned long long consumedSrcSize;377unsigned long long producedCSize;378XXH64_state_t xxhState;379ZSTD_customMem customMem;380ZSTD_threadPool* pool;381size_t staticSize;382SeqCollector seqCollector;383int isFirstBlock;384int initialized;385386seqStore_t seqStore; /* sequences storage ptrs */387ldmState_t ldmState; /* long distance matching state */388rawSeq* ldmSequences; /* Storage for the ldm output sequences */389size_t maxNbLdmSequences;390rawSeqStore_t externSeqStore; /* Mutable reference to external sequences */391ZSTD_blockState_t blockState;392U32* entropyWorkspace; /* entropy workspace of ENTROPY_WORKSPACE_SIZE bytes */393394/* Whether we are streaming or not */395ZSTD_buffered_policy_e bufferedPolicy;396397/* streaming */398char* inBuff;399size_t inBuffSize;400size_t inToCompress;401size_t inBuffPos;402size_t inBuffTarget;403char* outBuff;404size_t outBuffSize;405size_t outBuffContentSize;406size_t outBuffFlushedSize;407ZSTD_cStreamStage streamStage;408U32 frameEnded;409410/* Stable in/out buffer verification */411ZSTD_inBuffer expectedInBuffer;412size_t expectedOutBufferSize;413414/* Dictionary */415ZSTD_localDict localDict;416const ZSTD_CDict* cdict;417ZSTD_prefixDict prefixDict; /* single-usage dictionary */418419/* Multi-threading */420#ifdef ZSTD_MULTITHREAD421ZSTDMT_CCtx* mtctx;422#endif423424/* Tracing */425#if ZSTD_TRACE426ZSTD_TraceCtx traceCtx;427#endif428429/* Workspace for block splitter */430ZSTD_blockSplitCtx blockSplitCtx;431};432433typedef enum { ZSTD_dtlm_fast, ZSTD_dtlm_full } ZSTD_dictTableLoadMethod_e;434435typedef enum {436ZSTD_noDict = 0,437ZSTD_extDict = 1,438ZSTD_dictMatchState = 2,439ZSTD_dedicatedDictSearch = 3440} ZSTD_dictMode_e;441442typedef enum {443ZSTD_cpm_noAttachDict = 0, /* Compression with ZSTD_noDict or ZSTD_extDict.444* In this mode we use both the srcSize and the dictSize445* when selecting and adjusting parameters.446*/447ZSTD_cpm_attachDict = 1, /* Compression with ZSTD_dictMatchState or ZSTD_dedicatedDictSearch.448* In this mode we only take the srcSize into account when selecting449* and adjusting parameters.450*/451ZSTD_cpm_createCDict = 2, /* Creating a CDict.452* In this mode we take both the source size and the dictionary size453* into account when selecting and adjusting the parameters.454*/455ZSTD_cpm_unknown = 3, /* ZSTD_getCParams, ZSTD_getParams, ZSTD_adjustParams.456* We don't know what these parameters are for. We default to the legacy457* behavior of taking both the source size and the dict size into account458* when selecting and adjusting parameters.459*/460} ZSTD_cParamMode_e;461462typedef size_t (*ZSTD_blockCompressor) (463ZSTD_matchState_t* bs, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],464void const* src, size_t srcSize);465ZSTD_blockCompressor ZSTD_selectBlockCompressor(ZSTD_strategy strat, ZSTD_paramSwitch_e rowMatchfinderMode, ZSTD_dictMode_e dictMode);466467468MEM_STATIC U32 ZSTD_LLcode(U32 litLength)469{470static const BYTE LL_Code[64] = { 0, 1, 2, 3, 4, 5, 6, 7,4718, 9, 10, 11, 12, 13, 14, 15,47216, 16, 17, 17, 18, 18, 19, 19,47320, 20, 20, 20, 21, 21, 21, 21,47422, 22, 22, 22, 22, 22, 22, 22,47523, 23, 23, 23, 23, 23, 23, 23,47624, 24, 24, 24, 24, 24, 24, 24,47724, 24, 24, 24, 24, 24, 24, 24 };478static const U32 LL_deltaCode = 19;479return (litLength > 63) ? ZSTD_highbit32(litLength) + LL_deltaCode : LL_Code[litLength];480}481482/* ZSTD_MLcode() :483* note : mlBase = matchLength - MINMATCH;484* because it's the format it's stored in seqStore->sequences */485MEM_STATIC U32 ZSTD_MLcode(U32 mlBase)486{487static const BYTE ML_Code[128] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,48816, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,48932, 32, 33, 33, 34, 34, 35, 35, 36, 36, 36, 36, 37, 37, 37, 37,49038, 38, 38, 38, 38, 38, 38, 38, 39, 39, 39, 39, 39, 39, 39, 39,49140, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40,49241, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41,49342, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42,49442, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42 };495static const U32 ML_deltaCode = 36;496return (mlBase > 127) ? ZSTD_highbit32(mlBase) + ML_deltaCode : ML_Code[mlBase];497}498499/* ZSTD_cParam_withinBounds:500* @return 1 if value is within cParam bounds,501* 0 otherwise */502MEM_STATIC int ZSTD_cParam_withinBounds(ZSTD_cParameter cParam, int value)503{504ZSTD_bounds const bounds = ZSTD_cParam_getBounds(cParam);505if (ZSTD_isError(bounds.error)) return 0;506if (value < bounds.lowerBound) return 0;507if (value > bounds.upperBound) return 0;508return 1;509}510511/* ZSTD_noCompressBlock() :512* Writes uncompressed block to dst buffer from given src.513* Returns the size of the block */514MEM_STATIC size_t ZSTD_noCompressBlock (void* dst, size_t dstCapacity, const void* src, size_t srcSize, U32 lastBlock)515{516U32 const cBlockHeader24 = lastBlock + (((U32)bt_raw)<<1) + (U32)(srcSize << 3);517RETURN_ERROR_IF(srcSize + ZSTD_blockHeaderSize > dstCapacity,518dstSize_tooSmall, "dst buf too small for uncompressed block");519MEM_writeLE24(dst, cBlockHeader24);520ZSTD_memcpy((BYTE*)dst + ZSTD_blockHeaderSize, src, srcSize);521return ZSTD_blockHeaderSize + srcSize;522}523524MEM_STATIC size_t ZSTD_rleCompressBlock (void* dst, size_t dstCapacity, BYTE src, size_t srcSize, U32 lastBlock)525{526BYTE* const op = (BYTE*)dst;527U32 const cBlockHeader = lastBlock + (((U32)bt_rle)<<1) + (U32)(srcSize << 3);528RETURN_ERROR_IF(dstCapacity < 4, dstSize_tooSmall, "");529MEM_writeLE24(op, cBlockHeader);530op[3] = src;531return 4;532}533534535/* ZSTD_minGain() :536* minimum compression required537* to generate a compress block or a compressed literals section.538* note : use same formula for both situations */539MEM_STATIC size_t ZSTD_minGain(size_t srcSize, ZSTD_strategy strat)540{541U32 const minlog = (strat>=ZSTD_btultra) ? (U32)(strat) - 1 : 6;542ZSTD_STATIC_ASSERT(ZSTD_btultra == 8);543assert(ZSTD_cParam_withinBounds(ZSTD_c_strategy, strat));544return (srcSize >> minlog) + 2;545}546547MEM_STATIC int ZSTD_literalsCompressionIsDisabled(const ZSTD_CCtx_params* cctxParams)548{549switch (cctxParams->literalCompressionMode) {550case ZSTD_ps_enable:551return 0;552case ZSTD_ps_disable:553return 1;554default:555assert(0 /* impossible: pre-validated */);556ZSTD_FALLTHROUGH;557case ZSTD_ps_auto:558return (cctxParams->cParams.strategy == ZSTD_fast) && (cctxParams->cParams.targetLength > 0);559}560}561562/*! ZSTD_safecopyLiterals() :563* memcpy() function that won't read beyond more than WILDCOPY_OVERLENGTH bytes past ilimit_w.564* Only called when the sequence ends past ilimit_w, so it only needs to be optimized for single565* large copies.566*/567static void568ZSTD_safecopyLiterals(BYTE* op, BYTE const* ip, BYTE const* const iend, BYTE const* ilimit_w)569{570assert(iend > ilimit_w);571if (ip <= ilimit_w) {572ZSTD_wildcopy(op, ip, ilimit_w - ip, ZSTD_no_overlap);573op += ilimit_w - ip;574ip = ilimit_w;575}576while (ip < iend) *op++ = *ip++;577}578579#define ZSTD_REP_MOVE (ZSTD_REP_NUM-1)580#define STORE_REPCODE_1 STORE_REPCODE(1)581#define STORE_REPCODE_2 STORE_REPCODE(2)582#define STORE_REPCODE_3 STORE_REPCODE(3)583#define STORE_REPCODE(r) (assert((r)>=1), assert((r)<=3), (r)-1)584#define STORE_OFFSET(o) (assert((o)>0), o + ZSTD_REP_MOVE)585#define STORED_IS_OFFSET(o) ((o) > ZSTD_REP_MOVE)586#define STORED_IS_REPCODE(o) ((o) <= ZSTD_REP_MOVE)587#define STORED_OFFSET(o) (assert(STORED_IS_OFFSET(o)), (o)-ZSTD_REP_MOVE)588#define STORED_REPCODE(o) (assert(STORED_IS_REPCODE(o)), (o)+1) /* returns ID 1,2,3 */589#define STORED_TO_OFFBASE(o) ((o)+1)590#define OFFBASE_TO_STORED(o) ((o)-1)591592/*! ZSTD_storeSeq() :593* Store a sequence (litlen, litPtr, offCode and matchLength) into seqStore_t.594* @offBase_minus1 : Users should use employ macros STORE_REPCODE_X and STORE_OFFSET().595* @matchLength : must be >= MINMATCH596* Allowed to overread literals up to litLimit.597*/598HINT_INLINE UNUSED_ATTR void599ZSTD_storeSeq(seqStore_t* seqStorePtr,600size_t litLength, const BYTE* literals, const BYTE* litLimit,601U32 offBase_minus1,602size_t matchLength)603{604BYTE const* const litLimit_w = litLimit - WILDCOPY_OVERLENGTH;605BYTE const* const litEnd = literals + litLength;606#if defined(DEBUGLEVEL) && (DEBUGLEVEL >= 6)607static const BYTE* g_start = NULL;608if (g_start==NULL) g_start = (const BYTE*)literals; /* note : index only works for compression within a single segment */609{ U32 const pos = (U32)((const BYTE*)literals - g_start);610DEBUGLOG(6, "Cpos%7u :%3u literals, match%4u bytes at offCode%7u",611pos, (U32)litLength, (U32)matchLength, (U32)offBase_minus1);612}613#endif614assert((size_t)(seqStorePtr->sequences - seqStorePtr->sequencesStart) < seqStorePtr->maxNbSeq);615/* copy Literals */616assert(seqStorePtr->maxNbLit <= 128 KB);617assert(seqStorePtr->lit + litLength <= seqStorePtr->litStart + seqStorePtr->maxNbLit);618assert(literals + litLength <= litLimit);619if (litEnd <= litLimit_w) {620/* Common case we can use wildcopy.621* First copy 16 bytes, because literals are likely short.622*/623assert(WILDCOPY_OVERLENGTH >= 16);624ZSTD_copy16(seqStorePtr->lit, literals);625if (litLength > 16) {626ZSTD_wildcopy(seqStorePtr->lit+16, literals+16, (ptrdiff_t)litLength-16, ZSTD_no_overlap);627}628} else {629ZSTD_safecopyLiterals(seqStorePtr->lit, literals, litEnd, litLimit_w);630}631seqStorePtr->lit += litLength;632633/* literal Length */634if (litLength>0xFFFF) {635assert(seqStorePtr->longLengthType == ZSTD_llt_none); /* there can only be a single long length */636seqStorePtr->longLengthType = ZSTD_llt_literalLength;637seqStorePtr->longLengthPos = (U32)(seqStorePtr->sequences - seqStorePtr->sequencesStart);638}639seqStorePtr->sequences[0].litLength = (U16)litLength;640641/* match offset */642seqStorePtr->sequences[0].offBase = STORED_TO_OFFBASE(offBase_minus1);643644/* match Length */645assert(matchLength >= MINMATCH);646{ size_t const mlBase = matchLength - MINMATCH;647if (mlBase>0xFFFF) {648assert(seqStorePtr->longLengthType == ZSTD_llt_none); /* there can only be a single long length */649seqStorePtr->longLengthType = ZSTD_llt_matchLength;650seqStorePtr->longLengthPos = (U32)(seqStorePtr->sequences - seqStorePtr->sequencesStart);651}652seqStorePtr->sequences[0].mlBase = (U16)mlBase;653}654655seqStorePtr->sequences++;656}657658/* ZSTD_updateRep() :659* updates in-place @rep (array of repeat offsets)660* @offBase_minus1 : sum-type, with same numeric representation as ZSTD_storeSeq()661*/662MEM_STATIC void663ZSTD_updateRep(U32 rep[ZSTD_REP_NUM], U32 const offBase_minus1, U32 const ll0)664{665if (STORED_IS_OFFSET(offBase_minus1)) { /* full offset */666rep[2] = rep[1];667rep[1] = rep[0];668rep[0] = STORED_OFFSET(offBase_minus1);669} else { /* repcode */670U32 const repCode = STORED_REPCODE(offBase_minus1) - 1 + ll0;671if (repCode > 0) { /* note : if repCode==0, no change */672U32 const currentOffset = (repCode==ZSTD_REP_NUM) ? (rep[0] - 1) : rep[repCode];673rep[2] = (repCode >= 2) ? rep[1] : rep[2];674rep[1] = rep[0];675rep[0] = currentOffset;676} else { /* repCode == 0 */677/* nothing to do */678}679}680}681682typedef struct repcodes_s {683U32 rep[3];684} repcodes_t;685686MEM_STATIC repcodes_t687ZSTD_newRep(U32 const rep[ZSTD_REP_NUM], U32 const offBase_minus1, U32 const ll0)688{689repcodes_t newReps;690ZSTD_memcpy(&newReps, rep, sizeof(newReps));691ZSTD_updateRep(newReps.rep, offBase_minus1, ll0);692return newReps;693}694695696/*-*************************************697* Match length counter698***************************************/699static unsigned ZSTD_NbCommonBytes (size_t val)700{701if (MEM_isLittleEndian()) {702if (MEM_64bits()) {703# if defined(_MSC_VER) && defined(_WIN64)704# if STATIC_BMI2705return _tzcnt_u64(val) >> 3;706# else707if (val != 0) {708unsigned long r;709_BitScanForward64(&r, (U64)val);710return (unsigned)(r >> 3);711} else {712/* Should not reach this code path */713__assume(0);714}715# endif716# elif defined(__GNUC__) && (__GNUC__ >= 4)717return (__builtin_ctzll((U64)val) >> 3);718# else719static const int DeBruijnBytePos[64] = { 0, 0, 0, 0, 0, 1, 1, 2,7200, 3, 1, 3, 1, 4, 2, 7,7210, 2, 3, 6, 1, 5, 3, 5,7221, 3, 4, 4, 2, 5, 6, 7,7237, 0, 1, 2, 3, 3, 4, 6,7242, 6, 5, 5, 3, 4, 5, 6,7257, 1, 2, 4, 6, 4, 4, 5,7267, 2, 6, 5, 7, 6, 7, 7 };727return DeBruijnBytePos[((U64)((val & -(long long)val) * 0x0218A392CDABBD3FULL)) >> 58];728# endif729} else { /* 32 bits */730# if defined(_MSC_VER)731if (val != 0) {732unsigned long r;733_BitScanForward(&r, (U32)val);734return (unsigned)(r >> 3);735} else {736/* Should not reach this code path */737__assume(0);738}739# elif defined(__GNUC__) && (__GNUC__ >= 3)740return (__builtin_ctz((U32)val) >> 3);741# else742static const int DeBruijnBytePos[32] = { 0, 0, 3, 0, 3, 1, 3, 0,7433, 2, 2, 1, 3, 2, 0, 1,7443, 3, 1, 2, 2, 2, 2, 0,7453, 1, 2, 0, 1, 0, 1, 1 };746return DeBruijnBytePos[((U32)((val & -(S32)val) * 0x077CB531U)) >> 27];747# endif748}749} else { /* Big Endian CPU */750if (MEM_64bits()) {751# if defined(_MSC_VER) && defined(_WIN64)752# if STATIC_BMI2753return _lzcnt_u64(val) >> 3;754# else755if (val != 0) {756unsigned long r;757_BitScanReverse64(&r, (U64)val);758return (unsigned)(r >> 3);759} else {760/* Should not reach this code path */761__assume(0);762}763# endif764# elif defined(__GNUC__) && (__GNUC__ >= 4)765return (__builtin_clzll(val) >> 3);766# else767unsigned r;768const unsigned n32 = sizeof(size_t)*4; /* calculate this way due to compiler complaining in 32-bits mode */769if (!(val>>n32)) { r=4; } else { r=0; val>>=n32; }770if (!(val>>16)) { r+=2; val>>=8; } else { val>>=24; }771r += (!val);772return r;773# endif774} else { /* 32 bits */775# if defined(_MSC_VER)776if (val != 0) {777unsigned long r;778_BitScanReverse(&r, (unsigned long)val);779return (unsigned)(r >> 3);780} else {781/* Should not reach this code path */782__assume(0);783}784# elif defined(__GNUC__) && (__GNUC__ >= 3)785return (__builtin_clz((U32)val) >> 3);786# else787unsigned r;788if (!(val>>16)) { r=2; val>>=8; } else { r=0; val>>=24; }789r += (!val);790return r;791# endif792} }793}794795796MEM_STATIC size_t ZSTD_count(const BYTE* pIn, const BYTE* pMatch, const BYTE* const pInLimit)797{798const BYTE* const pStart = pIn;799const BYTE* const pInLoopLimit = pInLimit - (sizeof(size_t)-1);800801if (pIn < pInLoopLimit) {802{ size_t const diff = MEM_readST(pMatch) ^ MEM_readST(pIn);803if (diff) return ZSTD_NbCommonBytes(diff); }804pIn+=sizeof(size_t); pMatch+=sizeof(size_t);805while (pIn < pInLoopLimit) {806size_t const diff = MEM_readST(pMatch) ^ MEM_readST(pIn);807if (!diff) { pIn+=sizeof(size_t); pMatch+=sizeof(size_t); continue; }808pIn += ZSTD_NbCommonBytes(diff);809return (size_t)(pIn - pStart);810} }811if (MEM_64bits() && (pIn<(pInLimit-3)) && (MEM_read32(pMatch) == MEM_read32(pIn))) { pIn+=4; pMatch+=4; }812if ((pIn<(pInLimit-1)) && (MEM_read16(pMatch) == MEM_read16(pIn))) { pIn+=2; pMatch+=2; }813if ((pIn<pInLimit) && (*pMatch == *pIn)) pIn++;814return (size_t)(pIn - pStart);815}816817/** ZSTD_count_2segments() :818* can count match length with `ip` & `match` in 2 different segments.819* convention : on reaching mEnd, match count continue starting from iStart820*/821MEM_STATIC size_t822ZSTD_count_2segments(const BYTE* ip, const BYTE* match,823const BYTE* iEnd, const BYTE* mEnd, const BYTE* iStart)824{825const BYTE* const vEnd = MIN( ip + (mEnd - match), iEnd);826size_t const matchLength = ZSTD_count(ip, match, vEnd);827if (match + matchLength != mEnd) return matchLength;828DEBUGLOG(7, "ZSTD_count_2segments: found a 2-parts match (current length==%zu)", matchLength);829DEBUGLOG(7, "distance from match beginning to end dictionary = %zi", mEnd - match);830DEBUGLOG(7, "distance from current pos to end buffer = %zi", iEnd - ip);831DEBUGLOG(7, "next byte : ip==%02X, istart==%02X", ip[matchLength], *iStart);832DEBUGLOG(7, "final match length = %zu", matchLength + ZSTD_count(ip+matchLength, iStart, iEnd));833return matchLength + ZSTD_count(ip+matchLength, iStart, iEnd);834}835836837/*-*************************************838* Hashes839***************************************/840static const U32 prime3bytes = 506832829U;841static U32 ZSTD_hash3(U32 u, U32 h) { return ((u << (32-24)) * prime3bytes) >> (32-h) ; }842MEM_STATIC size_t ZSTD_hash3Ptr(const void* ptr, U32 h) { return ZSTD_hash3(MEM_readLE32(ptr), h); } /* only in zstd_opt.h */843844static const U32 prime4bytes = 2654435761U;845static U32 ZSTD_hash4(U32 u, U32 h) { return (u * prime4bytes) >> (32-h) ; }846static size_t ZSTD_hash4Ptr(const void* ptr, U32 h) { return ZSTD_hash4(MEM_read32(ptr), h); }847848static const U64 prime5bytes = 889523592379ULL;849static size_t ZSTD_hash5(U64 u, U32 h) { return (size_t)(((u << (64-40)) * prime5bytes) >> (64-h)) ; }850static size_t ZSTD_hash5Ptr(const void* p, U32 h) { return ZSTD_hash5(MEM_readLE64(p), h); }851852static const U64 prime6bytes = 227718039650203ULL;853static size_t ZSTD_hash6(U64 u, U32 h) { return (size_t)(((u << (64-48)) * prime6bytes) >> (64-h)) ; }854static size_t ZSTD_hash6Ptr(const void* p, U32 h) { return ZSTD_hash6(MEM_readLE64(p), h); }855856static const U64 prime7bytes = 58295818150454627ULL;857static size_t ZSTD_hash7(U64 u, U32 h) { return (size_t)(((u << (64-56)) * prime7bytes) >> (64-h)) ; }858static size_t ZSTD_hash7Ptr(const void* p, U32 h) { return ZSTD_hash7(MEM_readLE64(p), h); }859860static const U64 prime8bytes = 0xCF1BBCDCB7A56463ULL;861static size_t ZSTD_hash8(U64 u, U32 h) { return (size_t)(((u) * prime8bytes) >> (64-h)) ; }862static size_t ZSTD_hash8Ptr(const void* p, U32 h) { return ZSTD_hash8(MEM_readLE64(p), h); }863864MEM_STATIC FORCE_INLINE_ATTR865size_t ZSTD_hashPtr(const void* p, U32 hBits, U32 mls)866{867switch(mls)868{869default:870case 4: return ZSTD_hash4Ptr(p, hBits);871case 5: return ZSTD_hash5Ptr(p, hBits);872case 6: return ZSTD_hash6Ptr(p, hBits);873case 7: return ZSTD_hash7Ptr(p, hBits);874case 8: return ZSTD_hash8Ptr(p, hBits);875}876}877878/** ZSTD_ipow() :879* Return base^exponent.880*/881static U64 ZSTD_ipow(U64 base, U64 exponent)882{883U64 power = 1;884while (exponent) {885if (exponent & 1) power *= base;886exponent >>= 1;887base *= base;888}889return power;890}891892#define ZSTD_ROLL_HASH_CHAR_OFFSET 10893894/** ZSTD_rollingHash_append() :895* Add the buffer to the hash value.896*/897static U64 ZSTD_rollingHash_append(U64 hash, void const* buf, size_t size)898{899BYTE const* istart = (BYTE const*)buf;900size_t pos;901for (pos = 0; pos < size; ++pos) {902hash *= prime8bytes;903hash += istart[pos] + ZSTD_ROLL_HASH_CHAR_OFFSET;904}905return hash;906}907908/** ZSTD_rollingHash_compute() :909* Compute the rolling hash value of the buffer.910*/911MEM_STATIC U64 ZSTD_rollingHash_compute(void const* buf, size_t size)912{913return ZSTD_rollingHash_append(0, buf, size);914}915916/** ZSTD_rollingHash_primePower() :917* Compute the primePower to be passed to ZSTD_rollingHash_rotate() for a hash918* over a window of length bytes.919*/920MEM_STATIC U64 ZSTD_rollingHash_primePower(U32 length)921{922return ZSTD_ipow(prime8bytes, length - 1);923}924925/** ZSTD_rollingHash_rotate() :926* Rotate the rolling hash by one byte.927*/928MEM_STATIC U64 ZSTD_rollingHash_rotate(U64 hash, BYTE toRemove, BYTE toAdd, U64 primePower)929{930hash -= (toRemove + ZSTD_ROLL_HASH_CHAR_OFFSET) * primePower;931hash *= prime8bytes;932hash += toAdd + ZSTD_ROLL_HASH_CHAR_OFFSET;933return hash;934}935936/*-*************************************937* Round buffer management938***************************************/939#if (ZSTD_WINDOWLOG_MAX_64 > 31)940# error "ZSTD_WINDOWLOG_MAX is too large : would overflow ZSTD_CURRENT_MAX"941#endif942/* Max current allowed */943#define ZSTD_CURRENT_MAX ((3U << 29) + (1U << ZSTD_WINDOWLOG_MAX))944/* Maximum chunk size before overflow correction needs to be called again */945#define ZSTD_CHUNKSIZE_MAX \946( ((U32)-1) /* Maximum ending current index */ \947- ZSTD_CURRENT_MAX) /* Maximum beginning lowLimit */948949/**950* ZSTD_window_clear():951* Clears the window containing the history by simply setting it to empty.952*/953MEM_STATIC void ZSTD_window_clear(ZSTD_window_t* window)954{955size_t const endT = (size_t)(window->nextSrc - window->base);956U32 const end = (U32)endT;957958window->lowLimit = end;959window->dictLimit = end;960}961962MEM_STATIC U32 ZSTD_window_isEmpty(ZSTD_window_t const window)963{964return window.dictLimit == ZSTD_WINDOW_START_INDEX &&965window.lowLimit == ZSTD_WINDOW_START_INDEX &&966(window.nextSrc - window.base) == ZSTD_WINDOW_START_INDEX;967}968969/**970* ZSTD_window_hasExtDict():971* Returns non-zero if the window has a non-empty extDict.972*/973MEM_STATIC U32 ZSTD_window_hasExtDict(ZSTD_window_t const window)974{975return window.lowLimit < window.dictLimit;976}977978/**979* ZSTD_matchState_dictMode():980* Inspects the provided matchState and figures out what dictMode should be981* passed to the compressor.982*/983MEM_STATIC ZSTD_dictMode_e ZSTD_matchState_dictMode(const ZSTD_matchState_t *ms)984{985return ZSTD_window_hasExtDict(ms->window) ?986ZSTD_extDict :987ms->dictMatchState != NULL ?988(ms->dictMatchState->dedicatedDictSearch ? ZSTD_dedicatedDictSearch : ZSTD_dictMatchState) :989ZSTD_noDict;990}991992/* Defining this macro to non-zero tells zstd to run the overflow correction993* code much more frequently. This is very inefficient, and should only be994* used for tests and fuzzers.995*/996#ifndef ZSTD_WINDOW_OVERFLOW_CORRECT_FREQUENTLY997# ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION998# define ZSTD_WINDOW_OVERFLOW_CORRECT_FREQUENTLY 1999# else1000# define ZSTD_WINDOW_OVERFLOW_CORRECT_FREQUENTLY 01001# endif1002#endif10031004/**1005* ZSTD_window_canOverflowCorrect():1006* Returns non-zero if the indices are large enough for overflow correction1007* to work correctly without impacting compression ratio.1008*/1009MEM_STATIC U32 ZSTD_window_canOverflowCorrect(ZSTD_window_t const window,1010U32 cycleLog,1011U32 maxDist,1012U32 loadedDictEnd,1013void const* src)1014{1015U32 const cycleSize = 1u << cycleLog;1016U32 const curr = (U32)((BYTE const*)src - window.base);1017U32 const minIndexToOverflowCorrect = cycleSize1018+ MAX(maxDist, cycleSize)1019+ ZSTD_WINDOW_START_INDEX;10201021/* Adjust the min index to backoff the overflow correction frequency,1022* so we don't waste too much CPU in overflow correction. If this1023* computation overflows we don't really care, we just need to make1024* sure it is at least minIndexToOverflowCorrect.1025*/1026U32 const adjustment = window.nbOverflowCorrections + 1;1027U32 const adjustedIndex = MAX(minIndexToOverflowCorrect * adjustment,1028minIndexToOverflowCorrect);1029U32 const indexLargeEnough = curr > adjustedIndex;10301031/* Only overflow correct early if the dictionary is invalidated already,1032* so we don't hurt compression ratio.1033*/1034U32 const dictionaryInvalidated = curr > maxDist + loadedDictEnd;10351036return indexLargeEnough && dictionaryInvalidated;1037}10381039/**1040* ZSTD_window_needOverflowCorrection():1041* Returns non-zero if the indices are getting too large and need overflow1042* protection.1043*/1044MEM_STATIC U32 ZSTD_window_needOverflowCorrection(ZSTD_window_t const window,1045U32 cycleLog,1046U32 maxDist,1047U32 loadedDictEnd,1048void const* src,1049void const* srcEnd)1050{1051U32 const curr = (U32)((BYTE const*)srcEnd - window.base);1052if (ZSTD_WINDOW_OVERFLOW_CORRECT_FREQUENTLY) {1053if (ZSTD_window_canOverflowCorrect(window, cycleLog, maxDist, loadedDictEnd, src)) {1054return 1;1055}1056}1057return curr > ZSTD_CURRENT_MAX;1058}10591060/**1061* ZSTD_window_correctOverflow():1062* Reduces the indices to protect from index overflow.1063* Returns the correction made to the indices, which must be applied to every1064* stored index.1065*1066* The least significant cycleLog bits of the indices must remain the same,1067* which may be 0. Every index up to maxDist in the past must be valid.1068*/1069MEM_STATIC U32 ZSTD_window_correctOverflow(ZSTD_window_t* window, U32 cycleLog,1070U32 maxDist, void const* src)1071{1072/* preemptive overflow correction:1073* 1. correction is large enough:1074* lowLimit > (3<<29) ==> current > 3<<29 + 1<<windowLog1075* 1<<windowLog <= newCurrent < 1<<chainLog + 1<<windowLog1076*1077* current - newCurrent1078* > (3<<29 + 1<<windowLog) - (1<<windowLog + 1<<chainLog)1079* > (3<<29) - (1<<chainLog)1080* > (3<<29) - (1<<30) (NOTE: chainLog <= 30)1081* > 1<<291082*1083* 2. (ip+ZSTD_CHUNKSIZE_MAX - cctx->base) doesn't overflow:1084* After correction, current is less than (1<<chainLog + 1<<windowLog).1085* In 64-bit mode we are safe, because we have 64-bit ptrdiff_t.1086* In 32-bit mode we are safe, because (chainLog <= 29), so1087* ip+ZSTD_CHUNKSIZE_MAX - cctx->base < 1<<32.1088* 3. (cctx->lowLimit + 1<<windowLog) < 1<<32:1089* windowLog <= 31 ==> 3<<29 + 1<<windowLog < 7<<29 < 1<<32.1090*/1091U32 const cycleSize = 1u << cycleLog;1092U32 const cycleMask = cycleSize - 1;1093U32 const curr = (U32)((BYTE const*)src - window->base);1094U32 const currentCycle = curr & cycleMask;1095/* Ensure newCurrent - maxDist >= ZSTD_WINDOW_START_INDEX. */1096U32 const currentCycleCorrection = currentCycle < ZSTD_WINDOW_START_INDEX1097? MAX(cycleSize, ZSTD_WINDOW_START_INDEX)1098: 0;1099U32 const newCurrent = currentCycle1100+ currentCycleCorrection1101+ MAX(maxDist, cycleSize);1102U32 const correction = curr - newCurrent;1103/* maxDist must be a power of two so that:1104* (newCurrent & cycleMask) == (curr & cycleMask)1105* This is required to not corrupt the chains / binary tree.1106*/1107assert((maxDist & (maxDist - 1)) == 0);1108assert((curr & cycleMask) == (newCurrent & cycleMask));1109assert(curr > newCurrent);1110if (!ZSTD_WINDOW_OVERFLOW_CORRECT_FREQUENTLY) {1111/* Loose bound, should be around 1<<29 (see above) */1112assert(correction > 1<<28);1113}11141115window->base += correction;1116window->dictBase += correction;1117if (window->lowLimit < correction + ZSTD_WINDOW_START_INDEX) {1118window->lowLimit = ZSTD_WINDOW_START_INDEX;1119} else {1120window->lowLimit -= correction;1121}1122if (window->dictLimit < correction + ZSTD_WINDOW_START_INDEX) {1123window->dictLimit = ZSTD_WINDOW_START_INDEX;1124} else {1125window->dictLimit -= correction;1126}11271128/* Ensure we can still reference the full window. */1129assert(newCurrent >= maxDist);1130assert(newCurrent - maxDist >= ZSTD_WINDOW_START_INDEX);1131/* Ensure that lowLimit and dictLimit didn't underflow. */1132assert(window->lowLimit <= newCurrent);1133assert(window->dictLimit <= newCurrent);11341135++window->nbOverflowCorrections;11361137DEBUGLOG(4, "Correction of 0x%x bytes to lowLimit=0x%x", correction,1138window->lowLimit);1139return correction;1140}11411142/**1143* ZSTD_window_enforceMaxDist():1144* Updates lowLimit so that:1145* (srcEnd - base) - lowLimit == maxDist + loadedDictEnd1146*1147* It ensures index is valid as long as index >= lowLimit.1148* This must be called before a block compression call.1149*1150* loadedDictEnd is only defined if a dictionary is in use for current compression.1151* As the name implies, loadedDictEnd represents the index at end of dictionary.1152* The value lies within context's referential, it can be directly compared to blockEndIdx.1153*1154* If loadedDictEndPtr is NULL, no dictionary is in use, and we use loadedDictEnd == 0.1155* If loadedDictEndPtr is not NULL, we set it to zero after updating lowLimit.1156* This is because dictionaries are allowed to be referenced fully1157* as long as the last byte of the dictionary is in the window.1158* Once input has progressed beyond window size, dictionary cannot be referenced anymore.1159*1160* In normal dict mode, the dictionary lies between lowLimit and dictLimit.1161* In dictMatchState mode, lowLimit and dictLimit are the same,1162* and the dictionary is below them.1163* forceWindow and dictMatchState are therefore incompatible.1164*/1165MEM_STATIC void1166ZSTD_window_enforceMaxDist(ZSTD_window_t* window,1167const void* blockEnd,1168U32 maxDist,1169U32* loadedDictEndPtr,1170const ZSTD_matchState_t** dictMatchStatePtr)1171{1172U32 const blockEndIdx = (U32)((BYTE const*)blockEnd - window->base);1173U32 const loadedDictEnd = (loadedDictEndPtr != NULL) ? *loadedDictEndPtr : 0;1174DEBUGLOG(5, "ZSTD_window_enforceMaxDist: blockEndIdx=%u, maxDist=%u, loadedDictEnd=%u",1175(unsigned)blockEndIdx, (unsigned)maxDist, (unsigned)loadedDictEnd);11761177/* - When there is no dictionary : loadedDictEnd == 0.1178In which case, the test (blockEndIdx > maxDist) is merely to avoid1179overflowing next operation `newLowLimit = blockEndIdx - maxDist`.1180- When there is a standard dictionary :1181Index referential is copied from the dictionary,1182which means it starts from 0.1183In which case, loadedDictEnd == dictSize,1184and it makes sense to compare `blockEndIdx > maxDist + dictSize`1185since `blockEndIdx` also starts from zero.1186- When there is an attached dictionary :1187loadedDictEnd is expressed within the referential of the context,1188so it can be directly compared against blockEndIdx.1189*/1190if (blockEndIdx > maxDist + loadedDictEnd) {1191U32 const newLowLimit = blockEndIdx - maxDist;1192if (window->lowLimit < newLowLimit) window->lowLimit = newLowLimit;1193if (window->dictLimit < window->lowLimit) {1194DEBUGLOG(5, "Update dictLimit to match lowLimit, from %u to %u",1195(unsigned)window->dictLimit, (unsigned)window->lowLimit);1196window->dictLimit = window->lowLimit;1197}1198/* On reaching window size, dictionaries are invalidated */1199if (loadedDictEndPtr) *loadedDictEndPtr = 0;1200if (dictMatchStatePtr) *dictMatchStatePtr = NULL;1201}1202}12031204/* Similar to ZSTD_window_enforceMaxDist(),1205* but only invalidates dictionary1206* when input progresses beyond window size.1207* assumption : loadedDictEndPtr and dictMatchStatePtr are valid (non NULL)1208* loadedDictEnd uses same referential as window->base1209* maxDist is the window size */1210MEM_STATIC void1211ZSTD_checkDictValidity(const ZSTD_window_t* window,1212const void* blockEnd,1213U32 maxDist,1214U32* loadedDictEndPtr,1215const ZSTD_matchState_t** dictMatchStatePtr)1216{1217assert(loadedDictEndPtr != NULL);1218assert(dictMatchStatePtr != NULL);1219{ U32 const blockEndIdx = (U32)((BYTE const*)blockEnd - window->base);1220U32 const loadedDictEnd = *loadedDictEndPtr;1221DEBUGLOG(5, "ZSTD_checkDictValidity: blockEndIdx=%u, maxDist=%u, loadedDictEnd=%u",1222(unsigned)blockEndIdx, (unsigned)maxDist, (unsigned)loadedDictEnd);1223assert(blockEndIdx >= loadedDictEnd);12241225if (blockEndIdx > loadedDictEnd + maxDist) {1226/* On reaching window size, dictionaries are invalidated.1227* For simplification, if window size is reached anywhere within next block,1228* the dictionary is invalidated for the full block.1229*/1230DEBUGLOG(6, "invalidating dictionary for current block (distance > windowSize)");1231*loadedDictEndPtr = 0;1232*dictMatchStatePtr = NULL;1233} else {1234if (*loadedDictEndPtr != 0) {1235DEBUGLOG(6, "dictionary considered valid for current block");1236} } }1237}12381239MEM_STATIC void ZSTD_window_init(ZSTD_window_t* window) {1240ZSTD_memset(window, 0, sizeof(*window));1241window->base = (BYTE const*)" ";1242window->dictBase = (BYTE const*)" ";1243ZSTD_STATIC_ASSERT(ZSTD_DUBT_UNSORTED_MARK < ZSTD_WINDOW_START_INDEX); /* Start above ZSTD_DUBT_UNSORTED_MARK */1244window->dictLimit = ZSTD_WINDOW_START_INDEX; /* start from >0, so that 1st position is valid */1245window->lowLimit = ZSTD_WINDOW_START_INDEX; /* it ensures first and later CCtx usages compress the same */1246window->nextSrc = window->base + ZSTD_WINDOW_START_INDEX; /* see issue #1241 */1247window->nbOverflowCorrections = 0;1248}12491250/**1251* ZSTD_window_update():1252* Updates the window by appending [src, src + srcSize) to the window.1253* If it is not contiguous, the current prefix becomes the extDict, and we1254* forget about the extDict. Handles overlap of the prefix and extDict.1255* Returns non-zero if the segment is contiguous.1256*/1257MEM_STATIC U32 ZSTD_window_update(ZSTD_window_t* window,1258void const* src, size_t srcSize,1259int forceNonContiguous)1260{1261BYTE const* const ip = (BYTE const*)src;1262U32 contiguous = 1;1263DEBUGLOG(5, "ZSTD_window_update");1264if (srcSize == 0)1265return contiguous;1266assert(window->base != NULL);1267assert(window->dictBase != NULL);1268/* Check if blocks follow each other */1269if (src != window->nextSrc || forceNonContiguous) {1270/* not contiguous */1271size_t const distanceFromBase = (size_t)(window->nextSrc - window->base);1272DEBUGLOG(5, "Non contiguous blocks, new segment starts at %u", window->dictLimit);1273window->lowLimit = window->dictLimit;1274assert(distanceFromBase == (size_t)(U32)distanceFromBase); /* should never overflow */1275window->dictLimit = (U32)distanceFromBase;1276window->dictBase = window->base;1277window->base = ip - distanceFromBase;1278/* ms->nextToUpdate = window->dictLimit; */1279if (window->dictLimit - window->lowLimit < HASH_READ_SIZE) window->lowLimit = window->dictLimit; /* too small extDict */1280contiguous = 0;1281}1282window->nextSrc = ip + srcSize;1283/* if input and dictionary overlap : reduce dictionary (area presumed modified by input) */1284if ( (ip+srcSize > window->dictBase + window->lowLimit)1285& (ip < window->dictBase + window->dictLimit)) {1286ptrdiff_t const highInputIdx = (ip + srcSize) - window->dictBase;1287U32 const lowLimitMax = (highInputIdx > (ptrdiff_t)window->dictLimit) ? window->dictLimit : (U32)highInputIdx;1288window->lowLimit = lowLimitMax;1289DEBUGLOG(5, "Overlapping extDict and input : new lowLimit = %u", window->lowLimit);1290}1291return contiguous;1292}12931294/**1295* Returns the lowest allowed match index. It may either be in the ext-dict or the prefix.1296*/1297MEM_STATIC U32 ZSTD_getLowestMatchIndex(const ZSTD_matchState_t* ms, U32 curr, unsigned windowLog)1298{1299U32 const maxDistance = 1U << windowLog;1300U32 const lowestValid = ms->window.lowLimit;1301U32 const withinWindow = (curr - lowestValid > maxDistance) ? curr - maxDistance : lowestValid;1302U32 const isDictionary = (ms->loadedDictEnd != 0);1303/* When using a dictionary the entire dictionary is valid if a single byte of the dictionary1304* is within the window. We invalidate the dictionary (and set loadedDictEnd to 0) when it isn't1305* valid for the entire block. So this check is sufficient to find the lowest valid match index.1306*/1307U32 const matchLowest = isDictionary ? lowestValid : withinWindow;1308return matchLowest;1309}13101311/**1312* Returns the lowest allowed match index in the prefix.1313*/1314MEM_STATIC U32 ZSTD_getLowestPrefixIndex(const ZSTD_matchState_t* ms, U32 curr, unsigned windowLog)1315{1316U32 const maxDistance = 1U << windowLog;1317U32 const lowestValid = ms->window.dictLimit;1318U32 const withinWindow = (curr - lowestValid > maxDistance) ? curr - maxDistance : lowestValid;1319U32 const isDictionary = (ms->loadedDictEnd != 0);1320/* When computing the lowest prefix index we need to take the dictionary into account to handle1321* the edge case where the dictionary and the source are contiguous in memory.1322*/1323U32 const matchLowest = isDictionary ? lowestValid : withinWindow;1324return matchLowest;1325}1326132713281329/* debug functions */1330#if (DEBUGLEVEL>=2)13311332MEM_STATIC double ZSTD_fWeight(U32 rawStat)1333{1334U32 const fp_accuracy = 8;1335U32 const fp_multiplier = (1 << fp_accuracy);1336U32 const newStat = rawStat + 1;1337U32 const hb = ZSTD_highbit32(newStat);1338U32 const BWeight = hb * fp_multiplier;1339U32 const FWeight = (newStat << fp_accuracy) >> hb;1340U32 const weight = BWeight + FWeight;1341assert(hb + fp_accuracy < 31);1342return (double)weight / fp_multiplier;1343}13441345/* display a table content,1346* listing each element, its frequency, and its predicted bit cost */1347MEM_STATIC void ZSTD_debugTable(const U32* table, U32 max)1348{1349unsigned u, sum;1350for (u=0, sum=0; u<=max; u++) sum += table[u];1351DEBUGLOG(2, "total nb elts: %u", sum);1352for (u=0; u<=max; u++) {1353DEBUGLOG(2, "%2u: %5u (%.2f)",1354u, table[u], ZSTD_fWeight(sum) - ZSTD_fWeight(table[u]) );1355}1356}13571358#endif135913601361#if defined (__cplusplus)1362}1363#endif13641365/* ===============================================================1366* Shared internal declarations1367* These prototypes may be called from sources not in lib/compress1368* =============================================================== */13691370/* ZSTD_loadCEntropy() :1371* dict : must point at beginning of a valid zstd dictionary.1372* return : size of dictionary header (size of magic number + dict ID + entropy tables)1373* assumptions : magic number supposed already checked1374* and dictSize >= 8 */1375size_t ZSTD_loadCEntropy(ZSTD_compressedBlockState_t* bs, void* workspace,1376const void* const dict, size_t dictSize);13771378void ZSTD_reset_compressedBlockState(ZSTD_compressedBlockState_t* bs);13791380/* ==============================================================1381* Private declarations1382* These prototypes shall only be called from within lib/compress1383* ============================================================== */13841385/* ZSTD_getCParamsFromCCtxParams() :1386* cParams are built depending on compressionLevel, src size hints,1387* LDM and manually set compression parameters.1388* Note: srcSizeHint == 0 means 0!1389*/1390ZSTD_compressionParameters ZSTD_getCParamsFromCCtxParams(1391const ZSTD_CCtx_params* CCtxParams, U64 srcSizeHint, size_t dictSize, ZSTD_cParamMode_e mode);13921393/*! ZSTD_initCStream_internal() :1394* Private use only. Init streaming operation.1395* expects params to be valid.1396* must receive dict, or cdict, or none, but not both.1397* @return : 0, or an error code */1398size_t ZSTD_initCStream_internal(ZSTD_CStream* zcs,1399const void* dict, size_t dictSize,1400const ZSTD_CDict* cdict,1401const ZSTD_CCtx_params* params, unsigned long long pledgedSrcSize);14021403void ZSTD_resetSeqStore(seqStore_t* ssPtr);14041405/*! ZSTD_getCParamsFromCDict() :1406* as the name implies */1407ZSTD_compressionParameters ZSTD_getCParamsFromCDict(const ZSTD_CDict* cdict);14081409/* ZSTD_compressBegin_advanced_internal() :1410* Private use only. To be called from zstdmt_compress.c. */1411size_t ZSTD_compressBegin_advanced_internal(ZSTD_CCtx* cctx,1412const void* dict, size_t dictSize,1413ZSTD_dictContentType_e dictContentType,1414ZSTD_dictTableLoadMethod_e dtlm,1415const ZSTD_CDict* cdict,1416const ZSTD_CCtx_params* params,1417unsigned long long pledgedSrcSize);14181419/* ZSTD_compress_advanced_internal() :1420* Private use only. To be called from zstdmt_compress.c. */1421size_t ZSTD_compress_advanced_internal(ZSTD_CCtx* cctx,1422void* dst, size_t dstCapacity,1423const void* src, size_t srcSize,1424const void* dict,size_t dictSize,1425const ZSTD_CCtx_params* params);142614271428/* ZSTD_writeLastEmptyBlock() :1429* output an empty Block with end-of-frame mark to complete a frame1430* @return : size of data written into `dst` (== ZSTD_blockHeaderSize (defined in zstd_internal.h))1431* or an error code if `dstCapacity` is too small (<ZSTD_blockHeaderSize)1432*/1433size_t ZSTD_writeLastEmptyBlock(void* dst, size_t dstCapacity);143414351436/* ZSTD_referenceExternalSequences() :1437* Must be called before starting a compression operation.1438* seqs must parse a prefix of the source.1439* This cannot be used when long range matching is enabled.1440* Zstd will use these sequences, and pass the literals to a secondary block1441* compressor.1442* @return : An error code on failure.1443* NOTE: seqs are not verified! Invalid sequences can cause out-of-bounds memory1444* access and data corruption.1445*/1446size_t ZSTD_referenceExternalSequences(ZSTD_CCtx* cctx, rawSeq* seq, size_t nbSeq);14471448/** ZSTD_cycleLog() :1449* condition for correct operation : hashLog > 1 */1450/* Begin FreeBSD - This symbol is needed by dll-linked CLI zstd(1). */1451ZSTDLIB_API1452/* End FreeBSD */1453U32 ZSTD_cycleLog(U32 hashLog, ZSTD_strategy strat);14541455/** ZSTD_CCtx_trace() :1456* Trace the end of a compression call.1457*/1458void ZSTD_CCtx_trace(ZSTD_CCtx* cctx, size_t extraCSize);14591460#endif /* ZSTD_COMPRESS_H */146114621463