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