zstd_compress_internal.h 63 KB

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