zstd_compress_internal.h 67 KB

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