zstd_compress_internal.h 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532
  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 re-use 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;
  140. U32 off;
  141. U32 mlen;
  142. U32 litlen;
  143. U32 rep[ZSTD_REP_NUM];
  144. } ZSTD_optimal_t;
  145. typedef enum { zop_dynamic=0, zop_predef } ZSTD_OptPrice_e;
  146. typedef struct {
  147. /* All tables are allocated inside cctx->workspace by ZSTD_resetCCtx_internal() */
  148. unsigned* litFreq; /* table of literals statistics, of size 256 */
  149. unsigned* litLengthFreq; /* table of litLength statistics, of size (MaxLL+1) */
  150. unsigned* matchLengthFreq; /* table of matchLength statistics, of size (MaxML+1) */
  151. unsigned* offCodeFreq; /* table of offCode statistics, of size (MaxOff+1) */
  152. ZSTD_match_t* matchTable; /* list of found matches, of size ZSTD_OPT_NUM+1 */
  153. ZSTD_optimal_t* priceTable; /* All positions tracked by optimal parser, of size ZSTD_OPT_NUM+1 */
  154. U32 litSum; /* nb of literals */
  155. U32 litLengthSum; /* nb of litLength codes */
  156. U32 matchLengthSum; /* nb of matchLength codes */
  157. U32 offCodeSum; /* nb of offset codes */
  158. U32 litSumBasePrice; /* to compare to log2(litfreq) */
  159. U32 litLengthSumBasePrice; /* to compare to log2(llfreq) */
  160. U32 matchLengthSumBasePrice;/* to compare to log2(mlfreq) */
  161. U32 offCodeSumBasePrice; /* to compare to log2(offreq) */
  162. ZSTD_OptPrice_e priceType; /* prices can be determined dynamically, or follow a pre-defined cost structure */
  163. const ZSTD_entropyCTables_t* symbolCosts; /* pre-calculated dictionary statistics */
  164. ZSTD_paramSwitch_e literalCompressionMode;
  165. } optState_t;
  166. typedef struct {
  167. ZSTD_entropyCTables_t entropy;
  168. U32 rep[ZSTD_REP_NUM];
  169. } ZSTD_compressedBlockState_t;
  170. typedef struct {
  171. BYTE const* nextSrc; /* next block here to continue on current prefix */
  172. BYTE const* base; /* All regular indexes relative to this position */
  173. BYTE const* dictBase; /* extDict indexes relative to this position */
  174. U32 dictLimit; /* below that point, need extDict */
  175. U32 lowLimit; /* below that point, no more valid data */
  176. U32 nbOverflowCorrections; /* Number of times overflow correction has run since
  177. * ZSTD_window_init(). Useful for debugging coredumps
  178. * and for ZSTD_WINDOW_OVERFLOW_CORRECT_FREQUENTLY.
  179. */
  180. } ZSTD_window_t;
  181. #define ZSTD_WINDOW_START_INDEX 2
  182. typedef struct ZSTD_matchState_t ZSTD_matchState_t;
  183. #define ZSTD_ROW_HASH_CACHE_SIZE 8 /* Size of prefetching hash cache for row-based matchfinder */
  184. struct ZSTD_matchState_t {
  185. ZSTD_window_t window; /* State for window round buffer management */
  186. U32 loadedDictEnd; /* index of end of dictionary, within context's referential.
  187. * When loadedDictEnd != 0, a dictionary is in use, and still valid.
  188. * This relies on a mechanism to set loadedDictEnd=0 when dictionary is no longer within distance.
  189. * Such mechanism is provided within ZSTD_window_enforceMaxDist() and ZSTD_checkDictValidity().
  190. * When dict referential is copied into active context (i.e. not attached),
  191. * loadedDictEnd == dictSize, since referential starts from zero.
  192. */
  193. U32 nextToUpdate; /* index from which to continue table update */
  194. U32 hashLog3; /* dispatch table for matches of len==3 : larger == faster, more memory */
  195. U32 rowHashLog; /* For row-based matchfinder: Hashlog based on nb of rows in the hashTable.*/
  196. BYTE* tagTable; /* For row-based matchFinder: A row-based table containing the hashes and head index. */
  197. U32 hashCache[ZSTD_ROW_HASH_CACHE_SIZE]; /* For row-based matchFinder: a cache of hashes to improve speed */
  198. U64 hashSalt; /* For row-based matchFinder: salts the hash for re-use of tag table */
  199. U32 hashSaltEntropy; /* For row-based matchFinder: collects entropy for salt generation */
  200. U32* hashTable;
  201. U32* hashTable3;
  202. U32* chainTable;
  203. U32 forceNonContiguous; /* Non-zero if we should force non-contiguous load for the next window update. */
  204. int dedicatedDictSearch; /* Indicates whether this matchState is using the
  205. * dedicated dictionary search structure.
  206. */
  207. optState_t opt; /* optimal parser state */
  208. const ZSTD_matchState_t* dictMatchState;
  209. ZSTD_compressionParameters cParams;
  210. const rawSeqStore_t* ldmSeqStore;
  211. /* Controls prefetching in some dictMatchState matchfinders.
  212. * This behavior is controlled from the cctx ms.
  213. * This parameter has no effect in the cdict ms. */
  214. int prefetchCDictTables;
  215. /* When == 0, lazy match finders insert every position.
  216. * When != 0, lazy match finders only insert positions they search.
  217. * This allows them to skip much faster over incompressible data,
  218. * at a small cost to compression ratio.
  219. */
  220. int lazySkipping;
  221. };
  222. typedef struct {
  223. ZSTD_compressedBlockState_t* prevCBlock;
  224. ZSTD_compressedBlockState_t* nextCBlock;
  225. ZSTD_matchState_t matchState;
  226. } ZSTD_blockState_t;
  227. typedef struct {
  228. U32 offset;
  229. U32 checksum;
  230. } ldmEntry_t;
  231. typedef struct {
  232. BYTE const* split;
  233. U32 hash;
  234. U32 checksum;
  235. ldmEntry_t* bucket;
  236. } ldmMatchCandidate_t;
  237. #define LDM_BATCH_SIZE 64
  238. typedef struct {
  239. ZSTD_window_t window; /* State for the window round buffer management */
  240. ldmEntry_t* hashTable;
  241. U32 loadedDictEnd;
  242. BYTE* bucketOffsets; /* Next position in bucket to insert entry */
  243. size_t splitIndices[LDM_BATCH_SIZE];
  244. ldmMatchCandidate_t matchCandidates[LDM_BATCH_SIZE];
  245. } ldmState_t;
  246. typedef struct {
  247. ZSTD_paramSwitch_e enableLdm; /* ZSTD_ps_enable to enable LDM. ZSTD_ps_auto by default */
  248. U32 hashLog; /* Log size of hashTable */
  249. U32 bucketSizeLog; /* Log bucket size for collision resolution, at most 8 */
  250. U32 minMatchLength; /* Minimum match length */
  251. U32 hashRateLog; /* Log number of entries to skip */
  252. U32 windowLog; /* Window log for the LDM */
  253. } ldmParams_t;
  254. typedef struct {
  255. int collectSequences;
  256. ZSTD_Sequence* seqStart;
  257. size_t seqIndex;
  258. size_t maxSequences;
  259. } SeqCollector;
  260. struct ZSTD_CCtx_params_s {
  261. ZSTD_format_e format;
  262. ZSTD_compressionParameters cParams;
  263. ZSTD_frameParameters fParams;
  264. int compressionLevel;
  265. int forceWindow; /* force back-references to respect limit of
  266. * 1<<wLog, even for dictionary */
  267. size_t targetCBlockSize; /* Tries to fit compressed block size to be around targetCBlockSize.
  268. * No target when targetCBlockSize == 0.
  269. * There is no guarantee on compressed block size */
  270. int srcSizeHint; /* User's best guess of source size.
  271. * Hint is not valid when srcSizeHint == 0.
  272. * There is no guarantee that hint is close to actual source size */
  273. ZSTD_dictAttachPref_e attachDictPref;
  274. ZSTD_paramSwitch_e literalCompressionMode;
  275. /* Multithreading: used to pass parameters to mtctx */
  276. int nbWorkers;
  277. size_t jobSize;
  278. int overlapLog;
  279. int rsyncable;
  280. /* Long distance matching parameters */
  281. ldmParams_t ldmParams;
  282. /* Dedicated dict search algorithm trigger */
  283. int enableDedicatedDictSearch;
  284. /* Input/output buffer modes */
  285. ZSTD_bufferMode_e inBufferMode;
  286. ZSTD_bufferMode_e outBufferMode;
  287. /* Sequence compression API */
  288. ZSTD_sequenceFormat_e blockDelimiters;
  289. int validateSequences;
  290. /* Block splitting */
  291. ZSTD_paramSwitch_e useBlockSplitter;
  292. /* Param for deciding whether to use row-based matchfinder */
  293. ZSTD_paramSwitch_e useRowMatchFinder;
  294. /* Always load a dictionary in ext-dict mode (not prefix mode)? */
  295. int deterministicRefPrefix;
  296. /* Internal use, for createCCtxParams() and freeCCtxParams() only */
  297. ZSTD_customMem customMem;
  298. /* Controls prefetching in some dictMatchState matchfinders */
  299. ZSTD_paramSwitch_e prefetchCDictTables;
  300. /* Controls whether zstd will fall back to an internal matchfinder
  301. * if the external matchfinder returns an error code. */
  302. int enableMatchFinderFallback;
  303. /* Indicates whether an external matchfinder has been referenced.
  304. * Users can't set this externally.
  305. * It is set internally in ZSTD_registerSequenceProducer(). */
  306. int useSequenceProducer;
  307. /* Adjust the max block size*/
  308. size_t maxBlockSize;
  309. /* Controls repcode search in external sequence parsing */
  310. ZSTD_paramSwitch_e searchForExternalRepcodes;
  311. }; /* typedef'd to ZSTD_CCtx_params within "zstd.h" */
  312. #define COMPRESS_SEQUENCES_WORKSPACE_SIZE (sizeof(unsigned) * (MaxSeq + 2))
  313. #define ENTROPY_WORKSPACE_SIZE (HUF_WORKSPACE_SIZE + COMPRESS_SEQUENCES_WORKSPACE_SIZE)
  314. /**
  315. * Indicates whether this compression proceeds directly from user-provided
  316. * source buffer to user-provided destination buffer (ZSTDb_not_buffered), or
  317. * whether the context needs to buffer the input/output (ZSTDb_buffered).
  318. */
  319. typedef enum {
  320. ZSTDb_not_buffered,
  321. ZSTDb_buffered
  322. } ZSTD_buffered_policy_e;
  323. /**
  324. * Struct that contains all elements of block splitter that should be allocated
  325. * in a wksp.
  326. */
  327. #define ZSTD_MAX_NB_BLOCK_SPLITS 196
  328. typedef struct {
  329. seqStore_t fullSeqStoreChunk;
  330. seqStore_t firstHalfSeqStore;
  331. seqStore_t secondHalfSeqStore;
  332. seqStore_t currSeqStore;
  333. seqStore_t nextSeqStore;
  334. U32 partitions[ZSTD_MAX_NB_BLOCK_SPLITS];
  335. ZSTD_entropyCTablesMetadata_t entropyMetadata;
  336. } ZSTD_blockSplitCtx;
  337. /* Context for block-level external matchfinder API */
  338. typedef struct {
  339. void* mState;
  340. ZSTD_sequenceProducer_F* mFinder;
  341. ZSTD_Sequence* seqBuffer;
  342. size_t seqBufferCapacity;
  343. } ZSTD_externalMatchCtx;
  344. struct ZSTD_CCtx_s {
  345. ZSTD_compressionStage_e stage;
  346. 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. */
  347. int bmi2; /* == 1 if the CPU supports BMI2 and 0 otherwise. CPU support is determined dynamically once per context lifetime. */
  348. ZSTD_CCtx_params requestedParams;
  349. ZSTD_CCtx_params appliedParams;
  350. 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. */
  351. U32 dictID;
  352. size_t dictContentSize;
  353. ZSTD_cwksp workspace; /* manages buffer for dynamic allocations */
  354. size_t blockSize;
  355. unsigned long long pledgedSrcSizePlusOne; /* this way, 0 (default) == unknown */
  356. unsigned long long consumedSrcSize;
  357. unsigned long long producedCSize;
  358. XXH64_state_t xxhState;
  359. ZSTD_customMem customMem;
  360. ZSTD_threadPool* pool;
  361. size_t staticSize;
  362. SeqCollector seqCollector;
  363. int isFirstBlock;
  364. int initialized;
  365. seqStore_t seqStore; /* sequences storage ptrs */
  366. ldmState_t ldmState; /* long distance matching state */
  367. rawSeq* ldmSequences; /* Storage for the ldm output sequences */
  368. size_t maxNbLdmSequences;
  369. rawSeqStore_t externSeqStore; /* Mutable reference to external sequences */
  370. ZSTD_blockState_t blockState;
  371. U32* entropyWorkspace; /* entropy workspace of ENTROPY_WORKSPACE_SIZE bytes */
  372. /* Whether we are streaming or not */
  373. ZSTD_buffered_policy_e bufferedPolicy;
  374. /* streaming */
  375. char* inBuff;
  376. size_t inBuffSize;
  377. size_t inToCompress;
  378. size_t inBuffPos;
  379. size_t inBuffTarget;
  380. char* outBuff;
  381. size_t outBuffSize;
  382. size_t outBuffContentSize;
  383. size_t outBuffFlushedSize;
  384. ZSTD_cStreamStage streamStage;
  385. U32 frameEnded;
  386. /* Stable in/out buffer verification */
  387. ZSTD_inBuffer expectedInBuffer;
  388. size_t stableIn_notConsumed; /* nb bytes within stable input buffer that are said to be consumed but are not */
  389. size_t expectedOutBufferSize;
  390. /* Dictionary */
  391. ZSTD_localDict localDict;
  392. const ZSTD_CDict* cdict;
  393. ZSTD_prefixDict prefixDict; /* single-usage dictionary */
  394. /* Multi-threading */
  395. #ifdef ZSTD_MULTITHREAD
  396. ZSTDMT_CCtx* mtctx;
  397. #endif
  398. /* Tracing */
  399. #if ZSTD_TRACE
  400. ZSTD_TraceCtx traceCtx;
  401. #endif
  402. /* Workspace for block splitter */
  403. ZSTD_blockSplitCtx blockSplitCtx;
  404. /* Workspace for external matchfinder */
  405. ZSTD_externalMatchCtx externalMatchCtx;
  406. };
  407. typedef enum { ZSTD_dtlm_fast, ZSTD_dtlm_full } ZSTD_dictTableLoadMethod_e;
  408. typedef enum { ZSTD_tfp_forCCtx, ZSTD_tfp_forCDict } ZSTD_tableFillPurpose_e;
  409. typedef enum {
  410. ZSTD_noDict = 0,
  411. ZSTD_extDict = 1,
  412. ZSTD_dictMatchState = 2,
  413. ZSTD_dedicatedDictSearch = 3
  414. } ZSTD_dictMode_e;
  415. typedef enum {
  416. ZSTD_cpm_noAttachDict = 0, /* Compression with ZSTD_noDict or ZSTD_extDict.
  417. * In this mode we use both the srcSize and the dictSize
  418. * when selecting and adjusting parameters.
  419. */
  420. ZSTD_cpm_attachDict = 1, /* Compression with ZSTD_dictMatchState or ZSTD_dedicatedDictSearch.
  421. * In this mode we only take the srcSize into account when selecting
  422. * and adjusting parameters.
  423. */
  424. ZSTD_cpm_createCDict = 2, /* Creating a CDict.
  425. * In this mode we take both the source size and the dictionary size
  426. * into account when selecting and adjusting the parameters.
  427. */
  428. ZSTD_cpm_unknown = 3 /* ZSTD_getCParams, ZSTD_getParams, ZSTD_adjustParams.
  429. * We don't know what these parameters are for. We default to the legacy
  430. * behavior of taking both the source size and the dict size into account
  431. * when selecting and adjusting parameters.
  432. */
  433. } ZSTD_cParamMode_e;
  434. typedef size_t (*ZSTD_blockCompressor) (
  435. ZSTD_matchState_t* bs, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
  436. void const* src, size_t srcSize);
  437. ZSTD_blockCompressor ZSTD_selectBlockCompressor(ZSTD_strategy strat, ZSTD_paramSwitch_e rowMatchfinderMode, ZSTD_dictMode_e dictMode);
  438. MEM_STATIC U32 ZSTD_LLcode(U32 litLength)
  439. {
  440. static const BYTE LL_Code[64] = { 0, 1, 2, 3, 4, 5, 6, 7,
  441. 8, 9, 10, 11, 12, 13, 14, 15,
  442. 16, 16, 17, 17, 18, 18, 19, 19,
  443. 20, 20, 20, 20, 21, 21, 21, 21,
  444. 22, 22, 22, 22, 22, 22, 22, 22,
  445. 23, 23, 23, 23, 23, 23, 23, 23,
  446. 24, 24, 24, 24, 24, 24, 24, 24,
  447. 24, 24, 24, 24, 24, 24, 24, 24 };
  448. static const U32 LL_deltaCode = 19;
  449. return (litLength > 63) ? ZSTD_highbit32(litLength) + LL_deltaCode : LL_Code[litLength];
  450. }
  451. /* ZSTD_MLcode() :
  452. * note : mlBase = matchLength - MINMATCH;
  453. * because it's the format it's stored in seqStore->sequences */
  454. MEM_STATIC U32 ZSTD_MLcode(U32 mlBase)
  455. {
  456. static const BYTE ML_Code[128] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
  457. 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
  458. 32, 32, 33, 33, 34, 34, 35, 35, 36, 36, 36, 36, 37, 37, 37, 37,
  459. 38, 38, 38, 38, 38, 38, 38, 38, 39, 39, 39, 39, 39, 39, 39, 39,
  460. 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40,
  461. 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41,
  462. 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42,
  463. 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42 };
  464. static const U32 ML_deltaCode = 36;
  465. return (mlBase > 127) ? ZSTD_highbit32(mlBase) + ML_deltaCode : ML_Code[mlBase];
  466. }
  467. /* ZSTD_cParam_withinBounds:
  468. * @return 1 if value is within cParam bounds,
  469. * 0 otherwise */
  470. MEM_STATIC int ZSTD_cParam_withinBounds(ZSTD_cParameter cParam, int value)
  471. {
  472. ZSTD_bounds const bounds = ZSTD_cParam_getBounds(cParam);
  473. if (ZSTD_isError(bounds.error)) return 0;
  474. if (value < bounds.lowerBound) return 0;
  475. if (value > bounds.upperBound) return 0;
  476. return 1;
  477. }
  478. /* ZSTD_noCompressBlock() :
  479. * Writes uncompressed block to dst buffer from given src.
  480. * Returns the size of the block */
  481. MEM_STATIC size_t
  482. ZSTD_noCompressBlock(void* dst, size_t dstCapacity, const void* src, size_t srcSize, U32 lastBlock)
  483. {
  484. U32 const cBlockHeader24 = lastBlock + (((U32)bt_raw)<<1) + (U32)(srcSize << 3);
  485. DEBUGLOG(5, "ZSTD_noCompressBlock (srcSize=%zu, dstCapacity=%zu)", srcSize, dstCapacity);
  486. RETURN_ERROR_IF(srcSize + ZSTD_blockHeaderSize > dstCapacity,
  487. dstSize_tooSmall, "dst buf too small for uncompressed block");
  488. MEM_writeLE24(dst, cBlockHeader24);
  489. ZSTD_memcpy((BYTE*)dst + ZSTD_blockHeaderSize, src, srcSize);
  490. return ZSTD_blockHeaderSize + srcSize;
  491. }
  492. MEM_STATIC size_t
  493. ZSTD_rleCompressBlock(void* dst, size_t dstCapacity, BYTE src, size_t srcSize, U32 lastBlock)
  494. {
  495. BYTE* const op = (BYTE*)dst;
  496. U32 const cBlockHeader = lastBlock + (((U32)bt_rle)<<1) + (U32)(srcSize << 3);
  497. RETURN_ERROR_IF(dstCapacity < 4, dstSize_tooSmall, "");
  498. MEM_writeLE24(op, cBlockHeader);
  499. op[3] = src;
  500. return 4;
  501. }
  502. /* ZSTD_minGain() :
  503. * minimum compression required
  504. * to generate a compress block or a compressed literals section.
  505. * note : use same formula for both situations */
  506. MEM_STATIC size_t ZSTD_minGain(size_t srcSize, ZSTD_strategy strat)
  507. {
  508. U32 const minlog = (strat>=ZSTD_btultra) ? (U32)(strat) - 1 : 6;
  509. ZSTD_STATIC_ASSERT(ZSTD_btultra == 8);
  510. assert(ZSTD_cParam_withinBounds(ZSTD_c_strategy, (int)strat));
  511. return (srcSize >> minlog) + 2;
  512. }
  513. MEM_STATIC int ZSTD_literalsCompressionIsDisabled(const ZSTD_CCtx_params* cctxParams)
  514. {
  515. switch (cctxParams->literalCompressionMode) {
  516. case ZSTD_ps_enable:
  517. return 0;
  518. case ZSTD_ps_disable:
  519. return 1;
  520. default:
  521. assert(0 /* impossible: pre-validated */);
  522. ZSTD_FALLTHROUGH;
  523. case ZSTD_ps_auto:
  524. return (cctxParams->cParams.strategy == ZSTD_fast) && (cctxParams->cParams.targetLength > 0);
  525. }
  526. }
  527. /*! ZSTD_safecopyLiterals() :
  528. * memcpy() function that won't read beyond more than WILDCOPY_OVERLENGTH bytes past ilimit_w.
  529. * Only called when the sequence ends past ilimit_w, so it only needs to be optimized for single
  530. * large copies.
  531. */
  532. static void
  533. ZSTD_safecopyLiterals(BYTE* op, BYTE const* ip, BYTE const* const iend, BYTE const* ilimit_w)
  534. {
  535. assert(iend > ilimit_w);
  536. if (ip <= ilimit_w) {
  537. ZSTD_wildcopy(op, ip, ilimit_w - ip, ZSTD_no_overlap);
  538. op += ilimit_w - ip;
  539. ip = ilimit_w;
  540. }
  541. while (ip < iend) *op++ = *ip++;
  542. }
  543. #define REPCODE1_TO_OFFBASE REPCODE_TO_OFFBASE(1)
  544. #define REPCODE2_TO_OFFBASE REPCODE_TO_OFFBASE(2)
  545. #define REPCODE3_TO_OFFBASE REPCODE_TO_OFFBASE(3)
  546. #define REPCODE_TO_OFFBASE(r) (assert((r)>=1), assert((r)<=ZSTD_REP_NUM), (r)) /* accepts IDs 1,2,3 */
  547. #define OFFSET_TO_OFFBASE(o) (assert((o)>0), o + ZSTD_REP_NUM)
  548. #define OFFBASE_IS_OFFSET(o) ((o) > ZSTD_REP_NUM)
  549. #define OFFBASE_IS_REPCODE(o) ( 1 <= (o) && (o) <= ZSTD_REP_NUM)
  550. #define OFFBASE_TO_OFFSET(o) (assert(OFFBASE_IS_OFFSET(o)), (o) - ZSTD_REP_NUM)
  551. #define OFFBASE_TO_REPCODE(o) (assert(OFFBASE_IS_REPCODE(o)), (o)) /* returns ID 1,2,3 */
  552. /*! ZSTD_storeSeq() :
  553. * Store a sequence (litlen, litPtr, offBase and matchLength) into seqStore_t.
  554. * @offBase : Users should employ macros REPCODE_TO_OFFBASE() and OFFSET_TO_OFFBASE().
  555. * @matchLength : must be >= MINMATCH
  556. * Allowed to over-read literals up to litLimit.
  557. */
  558. HINT_INLINE UNUSED_ATTR void
  559. ZSTD_storeSeq(seqStore_t* seqStorePtr,
  560. size_t litLength, const BYTE* literals, const BYTE* litLimit,
  561. U32 offBase,
  562. size_t matchLength)
  563. {
  564. BYTE const* const litLimit_w = litLimit - WILDCOPY_OVERLENGTH;
  565. BYTE const* const litEnd = literals + litLength;
  566. #if defined(DEBUGLEVEL) && (DEBUGLEVEL >= 6)
  567. static const BYTE* g_start = NULL;
  568. if (g_start==NULL) g_start = (const BYTE*)literals; /* note : index only works for compression within a single segment */
  569. { U32 const pos = (U32)((const BYTE*)literals - g_start);
  570. DEBUGLOG(6, "Cpos%7u :%3u literals, match%4u bytes at offBase%7u",
  571. pos, (U32)litLength, (U32)matchLength, (U32)offBase);
  572. }
  573. #endif
  574. assert((size_t)(seqStorePtr->sequences - seqStorePtr->sequencesStart) < seqStorePtr->maxNbSeq);
  575. /* copy Literals */
  576. assert(seqStorePtr->maxNbLit <= 128 KB);
  577. assert(seqStorePtr->lit + litLength <= seqStorePtr->litStart + seqStorePtr->maxNbLit);
  578. assert(literals + litLength <= litLimit);
  579. if (litEnd <= litLimit_w) {
  580. /* Common case we can use wildcopy.
  581. * First copy 16 bytes, because literals are likely short.
  582. */
  583. ZSTD_STATIC_ASSERT(WILDCOPY_OVERLENGTH >= 16);
  584. ZSTD_copy16(seqStorePtr->lit, literals);
  585. if (litLength > 16) {
  586. ZSTD_wildcopy(seqStorePtr->lit+16, literals+16, (ptrdiff_t)litLength-16, ZSTD_no_overlap);
  587. }
  588. } else {
  589. ZSTD_safecopyLiterals(seqStorePtr->lit, literals, litEnd, litLimit_w);
  590. }
  591. seqStorePtr->lit += litLength;
  592. /* literal Length */
  593. if (litLength>0xFFFF) {
  594. assert(seqStorePtr->longLengthType == ZSTD_llt_none); /* there can only be a single long length */
  595. seqStorePtr->longLengthType = ZSTD_llt_literalLength;
  596. seqStorePtr->longLengthPos = (U32)(seqStorePtr->sequences - seqStorePtr->sequencesStart);
  597. }
  598. seqStorePtr->sequences[0].litLength = (U16)litLength;
  599. /* match offset */
  600. seqStorePtr->sequences[0].offBase = offBase;
  601. /* match Length */
  602. assert(matchLength >= MINMATCH);
  603. { size_t const mlBase = matchLength - MINMATCH;
  604. if (mlBase>0xFFFF) {
  605. assert(seqStorePtr->longLengthType == ZSTD_llt_none); /* there can only be a single long length */
  606. seqStorePtr->longLengthType = ZSTD_llt_matchLength;
  607. seqStorePtr->longLengthPos = (U32)(seqStorePtr->sequences - seqStorePtr->sequencesStart);
  608. }
  609. seqStorePtr->sequences[0].mlBase = (U16)mlBase;
  610. }
  611. seqStorePtr->sequences++;
  612. }
  613. /* ZSTD_updateRep() :
  614. * updates in-place @rep (array of repeat offsets)
  615. * @offBase : sum-type, using numeric representation of ZSTD_storeSeq()
  616. */
  617. MEM_STATIC void
  618. ZSTD_updateRep(U32 rep[ZSTD_REP_NUM], U32 const offBase, U32 const ll0)
  619. {
  620. if (OFFBASE_IS_OFFSET(offBase)) { /* full offset */
  621. rep[2] = rep[1];
  622. rep[1] = rep[0];
  623. rep[0] = OFFBASE_TO_OFFSET(offBase);
  624. } else { /* repcode */
  625. U32 const repCode = OFFBASE_TO_REPCODE(offBase) - 1 + ll0;
  626. if (repCode > 0) { /* note : if repCode==0, no change */
  627. U32 const currentOffset = (repCode==ZSTD_REP_NUM) ? (rep[0] - 1) : rep[repCode];
  628. rep[2] = (repCode >= 2) ? rep[1] : rep[2];
  629. rep[1] = rep[0];
  630. rep[0] = currentOffset;
  631. } else { /* repCode == 0 */
  632. /* nothing to do */
  633. }
  634. }
  635. }
  636. typedef struct repcodes_s {
  637. U32 rep[3];
  638. } repcodes_t;
  639. MEM_STATIC repcodes_t
  640. ZSTD_newRep(U32 const rep[ZSTD_REP_NUM], U32 const offBase, U32 const ll0)
  641. {
  642. repcodes_t newReps;
  643. ZSTD_memcpy(&newReps, rep, sizeof(newReps));
  644. ZSTD_updateRep(newReps.rep, offBase, ll0);
  645. return newReps;
  646. }
  647. /*-*************************************
  648. * Match length counter
  649. ***************************************/
  650. MEM_STATIC size_t ZSTD_count(const BYTE* pIn, const BYTE* pMatch, const BYTE* const pInLimit)
  651. {
  652. const BYTE* const pStart = pIn;
  653. const BYTE* const pInLoopLimit = pInLimit - (sizeof(size_t)-1);
  654. if (pIn < pInLoopLimit) {
  655. { size_t const diff = MEM_readST(pMatch) ^ MEM_readST(pIn);
  656. if (diff) return ZSTD_NbCommonBytes(diff); }
  657. pIn+=sizeof(size_t); pMatch+=sizeof(size_t);
  658. while (pIn < pInLoopLimit) {
  659. size_t const diff = MEM_readST(pMatch) ^ MEM_readST(pIn);
  660. if (!diff) { pIn+=sizeof(size_t); pMatch+=sizeof(size_t); continue; }
  661. pIn += ZSTD_NbCommonBytes(diff);
  662. return (size_t)(pIn - pStart);
  663. } }
  664. if (MEM_64bits() && (pIn<(pInLimit-3)) && (MEM_read32(pMatch) == MEM_read32(pIn))) { pIn+=4; pMatch+=4; }
  665. if ((pIn<(pInLimit-1)) && (MEM_read16(pMatch) == MEM_read16(pIn))) { pIn+=2; pMatch+=2; }
  666. if ((pIn<pInLimit) && (*pMatch == *pIn)) pIn++;
  667. return (size_t)(pIn - pStart);
  668. }
  669. /** ZSTD_count_2segments() :
  670. * can count match length with `ip` & `match` in 2 different segments.
  671. * convention : on reaching mEnd, match count continue starting from iStart
  672. */
  673. MEM_STATIC size_t
  674. ZSTD_count_2segments(const BYTE* ip, const BYTE* match,
  675. const BYTE* iEnd, const BYTE* mEnd, const BYTE* iStart)
  676. {
  677. const BYTE* const vEnd = MIN( ip + (mEnd - match), iEnd);
  678. size_t const matchLength = ZSTD_count(ip, match, vEnd);
  679. if (match + matchLength != mEnd) return matchLength;
  680. DEBUGLOG(7, "ZSTD_count_2segments: found a 2-parts match (current length==%zu)", matchLength);
  681. DEBUGLOG(7, "distance from match beginning to end dictionary = %zi", mEnd - match);
  682. DEBUGLOG(7, "distance from current pos to end buffer = %zi", iEnd - ip);
  683. DEBUGLOG(7, "next byte : ip==%02X, istart==%02X", ip[matchLength], *iStart);
  684. DEBUGLOG(7, "final match length = %zu", matchLength + ZSTD_count(ip+matchLength, iStart, iEnd));
  685. return matchLength + ZSTD_count(ip+matchLength, iStart, iEnd);
  686. }
  687. /*-*************************************
  688. * Hashes
  689. ***************************************/
  690. static const U32 prime3bytes = 506832829U;
  691. static U32 ZSTD_hash3(U32 u, U32 h, U32 s) { assert(h <= 32); return (((u << (32-24)) * prime3bytes) ^ s) >> (32-h) ; }
  692. MEM_STATIC size_t ZSTD_hash3Ptr(const void* ptr, U32 h) { return ZSTD_hash3(MEM_readLE32(ptr), h, 0); } /* only in zstd_opt.h */
  693. MEM_STATIC size_t ZSTD_hash3PtrS(const void* ptr, U32 h, U32 s) { return ZSTD_hash3(MEM_readLE32(ptr), h, s); }
  694. static const U32 prime4bytes = 2654435761U;
  695. static U32 ZSTD_hash4(U32 u, U32 h, U32 s) { assert(h <= 32); return ((u * prime4bytes) ^ s) >> (32-h) ; }
  696. static size_t ZSTD_hash4Ptr(const void* ptr, U32 h) { return ZSTD_hash4(MEM_readLE32(ptr), h, 0); }
  697. static size_t ZSTD_hash4PtrS(const void* ptr, U32 h, U32 s) { return ZSTD_hash4(MEM_readLE32(ptr), h, s); }
  698. static const U64 prime5bytes = 889523592379ULL;
  699. static size_t ZSTD_hash5(U64 u, U32 h, U64 s) { assert(h <= 64); return (size_t)((((u << (64-40)) * prime5bytes) ^ s) >> (64-h)) ; }
  700. static size_t ZSTD_hash5Ptr(const void* p, U32 h) { return ZSTD_hash5(MEM_readLE64(p), h, 0); }
  701. static size_t ZSTD_hash5PtrS(const void* p, U32 h, U64 s) { return ZSTD_hash5(MEM_readLE64(p), h, s); }
  702. static const U64 prime6bytes = 227718039650203ULL;
  703. static size_t ZSTD_hash6(U64 u, U32 h, U64 s) { assert(h <= 64); return (size_t)((((u << (64-48)) * prime6bytes) ^ s) >> (64-h)) ; }
  704. static size_t ZSTD_hash6Ptr(const void* p, U32 h) { return ZSTD_hash6(MEM_readLE64(p), h, 0); }
  705. static size_t ZSTD_hash6PtrS(const void* p, U32 h, U64 s) { return ZSTD_hash6(MEM_readLE64(p), h, s); }
  706. static const U64 prime7bytes = 58295818150454627ULL;
  707. static size_t ZSTD_hash7(U64 u, U32 h, U64 s) { assert(h <= 64); return (size_t)((((u << (64-56)) * prime7bytes) ^ s) >> (64-h)) ; }
  708. static size_t ZSTD_hash7Ptr(const void* p, U32 h) { return ZSTD_hash7(MEM_readLE64(p), h, 0); }
  709. static size_t ZSTD_hash7PtrS(const void* p, U32 h, U64 s) { return ZSTD_hash7(MEM_readLE64(p), h, s); }
  710. static const U64 prime8bytes = 0xCF1BBCDCB7A56463ULL;
  711. static size_t ZSTD_hash8(U64 u, U32 h, U64 s) { assert(h <= 64); return (size_t)((((u) * prime8bytes) ^ s) >> (64-h)) ; }
  712. static size_t ZSTD_hash8Ptr(const void* p, U32 h) { return ZSTD_hash8(MEM_readLE64(p), h, 0); }
  713. static size_t ZSTD_hash8PtrS(const void* p, U32 h, U64 s) { return ZSTD_hash8(MEM_readLE64(p), h, s); }
  714. MEM_STATIC FORCE_INLINE_ATTR
  715. size_t ZSTD_hashPtr(const void* p, U32 hBits, U32 mls)
  716. {
  717. /* Although some of these hashes do support hBits up to 64, some do not.
  718. * To be on the safe side, always avoid hBits > 32. */
  719. assert(hBits <= 32);
  720. switch(mls)
  721. {
  722. default:
  723. case 4: return ZSTD_hash4Ptr(p, hBits);
  724. case 5: return ZSTD_hash5Ptr(p, hBits);
  725. case 6: return ZSTD_hash6Ptr(p, hBits);
  726. case 7: return ZSTD_hash7Ptr(p, hBits);
  727. case 8: return ZSTD_hash8Ptr(p, hBits);
  728. }
  729. }
  730. MEM_STATIC FORCE_INLINE_ATTR
  731. size_t ZSTD_hashPtrSalted(const void* p, U32 hBits, U32 mls, const U64 hashSalt) {
  732. /* Although some of these hashes do support hBits up to 64, some do not.
  733. * To be on the safe side, always avoid hBits > 32. */
  734. assert(hBits <= 32);
  735. switch(mls)
  736. {
  737. default:
  738. case 4: return ZSTD_hash4PtrS(p, hBits, (U32)hashSalt);
  739. case 5: return ZSTD_hash5PtrS(p, hBits, hashSalt);
  740. case 6: return ZSTD_hash6PtrS(p, hBits, hashSalt);
  741. case 7: return ZSTD_hash7PtrS(p, hBits, hashSalt);
  742. case 8: return ZSTD_hash8PtrS(p, hBits, hashSalt);
  743. }
  744. }
  745. /** ZSTD_ipow() :
  746. * Return base^exponent.
  747. */
  748. static U64 ZSTD_ipow(U64 base, U64 exponent)
  749. {
  750. U64 power = 1;
  751. while (exponent) {
  752. if (exponent & 1) power *= base;
  753. exponent >>= 1;
  754. base *= base;
  755. }
  756. return power;
  757. }
  758. #define ZSTD_ROLL_HASH_CHAR_OFFSET 10
  759. /** ZSTD_rollingHash_append() :
  760. * Add the buffer to the hash value.
  761. */
  762. static U64 ZSTD_rollingHash_append(U64 hash, void const* buf, size_t size)
  763. {
  764. BYTE const* istart = (BYTE const*)buf;
  765. size_t pos;
  766. for (pos = 0; pos < size; ++pos) {
  767. hash *= prime8bytes;
  768. hash += istart[pos] + ZSTD_ROLL_HASH_CHAR_OFFSET;
  769. }
  770. return hash;
  771. }
  772. /** ZSTD_rollingHash_compute() :
  773. * Compute the rolling hash value of the buffer.
  774. */
  775. MEM_STATIC U64 ZSTD_rollingHash_compute(void const* buf, size_t size)
  776. {
  777. return ZSTD_rollingHash_append(0, buf, size);
  778. }
  779. /** ZSTD_rollingHash_primePower() :
  780. * Compute the primePower to be passed to ZSTD_rollingHash_rotate() for a hash
  781. * over a window of length bytes.
  782. */
  783. MEM_STATIC U64 ZSTD_rollingHash_primePower(U32 length)
  784. {
  785. return ZSTD_ipow(prime8bytes, length - 1);
  786. }
  787. /** ZSTD_rollingHash_rotate() :
  788. * Rotate the rolling hash by one byte.
  789. */
  790. MEM_STATIC U64 ZSTD_rollingHash_rotate(U64 hash, BYTE toRemove, BYTE toAdd, U64 primePower)
  791. {
  792. hash -= (toRemove + ZSTD_ROLL_HASH_CHAR_OFFSET) * primePower;
  793. hash *= prime8bytes;
  794. hash += toAdd + ZSTD_ROLL_HASH_CHAR_OFFSET;
  795. return hash;
  796. }
  797. /*-*************************************
  798. * Round buffer management
  799. ***************************************/
  800. #if (ZSTD_WINDOWLOG_MAX_64 > 31)
  801. # error "ZSTD_WINDOWLOG_MAX is too large : would overflow ZSTD_CURRENT_MAX"
  802. #endif
  803. /* Max current allowed */
  804. #define ZSTD_CURRENT_MAX ((3U << 29) + (1U << ZSTD_WINDOWLOG_MAX))
  805. /* Maximum chunk size before overflow correction needs to be called again */
  806. #define ZSTD_CHUNKSIZE_MAX \
  807. ( ((U32)-1) /* Maximum ending current index */ \
  808. - ZSTD_CURRENT_MAX) /* Maximum beginning lowLimit */
  809. /**
  810. * ZSTD_window_clear():
  811. * Clears the window containing the history by simply setting it to empty.
  812. */
  813. MEM_STATIC void ZSTD_window_clear(ZSTD_window_t* window)
  814. {
  815. size_t const endT = (size_t)(window->nextSrc - window->base);
  816. U32 const end = (U32)endT;
  817. window->lowLimit = end;
  818. window->dictLimit = end;
  819. }
  820. MEM_STATIC U32 ZSTD_window_isEmpty(ZSTD_window_t const window)
  821. {
  822. return window.dictLimit == ZSTD_WINDOW_START_INDEX &&
  823. window.lowLimit == ZSTD_WINDOW_START_INDEX &&
  824. (window.nextSrc - window.base) == ZSTD_WINDOW_START_INDEX;
  825. }
  826. /**
  827. * ZSTD_window_hasExtDict():
  828. * Returns non-zero if the window has a non-empty extDict.
  829. */
  830. MEM_STATIC U32 ZSTD_window_hasExtDict(ZSTD_window_t const window)
  831. {
  832. return window.lowLimit < window.dictLimit;
  833. }
  834. /**
  835. * ZSTD_matchState_dictMode():
  836. * Inspects the provided matchState and figures out what dictMode should be
  837. * passed to the compressor.
  838. */
  839. MEM_STATIC ZSTD_dictMode_e ZSTD_matchState_dictMode(const ZSTD_matchState_t *ms)
  840. {
  841. return ZSTD_window_hasExtDict(ms->window) ?
  842. ZSTD_extDict :
  843. ms->dictMatchState != NULL ?
  844. (ms->dictMatchState->dedicatedDictSearch ? ZSTD_dedicatedDictSearch : ZSTD_dictMatchState) :
  845. ZSTD_noDict;
  846. }
  847. /* Defining this macro to non-zero tells zstd to run the overflow correction
  848. * code much more frequently. This is very inefficient, and should only be
  849. * used for tests and fuzzers.
  850. */
  851. #ifndef ZSTD_WINDOW_OVERFLOW_CORRECT_FREQUENTLY
  852. # ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
  853. # define ZSTD_WINDOW_OVERFLOW_CORRECT_FREQUENTLY 1
  854. # else
  855. # define ZSTD_WINDOW_OVERFLOW_CORRECT_FREQUENTLY 0
  856. # endif
  857. #endif
  858. /**
  859. * ZSTD_window_canOverflowCorrect():
  860. * Returns non-zero if the indices are large enough for overflow correction
  861. * to work correctly without impacting compression ratio.
  862. */
  863. MEM_STATIC U32 ZSTD_window_canOverflowCorrect(ZSTD_window_t const window,
  864. U32 cycleLog,
  865. U32 maxDist,
  866. U32 loadedDictEnd,
  867. void const* src)
  868. {
  869. U32 const cycleSize = 1u << cycleLog;
  870. U32 const curr = (U32)((BYTE const*)src - window.base);
  871. U32 const minIndexToOverflowCorrect = cycleSize
  872. + MAX(maxDist, cycleSize)
  873. + ZSTD_WINDOW_START_INDEX;
  874. /* Adjust the min index to backoff the overflow correction frequency,
  875. * so we don't waste too much CPU in overflow correction. If this
  876. * computation overflows we don't really care, we just need to make
  877. * sure it is at least minIndexToOverflowCorrect.
  878. */
  879. U32 const adjustment = window.nbOverflowCorrections + 1;
  880. U32 const adjustedIndex = MAX(minIndexToOverflowCorrect * adjustment,
  881. minIndexToOverflowCorrect);
  882. U32 const indexLargeEnough = curr > adjustedIndex;
  883. /* Only overflow correct early if the dictionary is invalidated already,
  884. * so we don't hurt compression ratio.
  885. */
  886. U32 const dictionaryInvalidated = curr > maxDist + loadedDictEnd;
  887. return indexLargeEnough && dictionaryInvalidated;
  888. }
  889. /**
  890. * ZSTD_window_needOverflowCorrection():
  891. * Returns non-zero if the indices are getting too large and need overflow
  892. * protection.
  893. */
  894. MEM_STATIC U32 ZSTD_window_needOverflowCorrection(ZSTD_window_t const window,
  895. U32 cycleLog,
  896. U32 maxDist,
  897. U32 loadedDictEnd,
  898. void const* src,
  899. void const* srcEnd)
  900. {
  901. U32 const curr = (U32)((BYTE const*)srcEnd - window.base);
  902. if (ZSTD_WINDOW_OVERFLOW_CORRECT_FREQUENTLY) {
  903. if (ZSTD_window_canOverflowCorrect(window, cycleLog, maxDist, loadedDictEnd, src)) {
  904. return 1;
  905. }
  906. }
  907. return curr > ZSTD_CURRENT_MAX;
  908. }
  909. /**
  910. * ZSTD_window_correctOverflow():
  911. * Reduces the indices to protect from index overflow.
  912. * Returns the correction made to the indices, which must be applied to every
  913. * stored index.
  914. *
  915. * The least significant cycleLog bits of the indices must remain the same,
  916. * which may be 0. Every index up to maxDist in the past must be valid.
  917. */
  918. MEM_STATIC U32 ZSTD_window_correctOverflow(ZSTD_window_t* window, U32 cycleLog,
  919. U32 maxDist, void const* src)
  920. {
  921. /* preemptive overflow correction:
  922. * 1. correction is large enough:
  923. * lowLimit > (3<<29) ==> current > 3<<29 + 1<<windowLog
  924. * 1<<windowLog <= newCurrent < 1<<chainLog + 1<<windowLog
  925. *
  926. * current - newCurrent
  927. * > (3<<29 + 1<<windowLog) - (1<<windowLog + 1<<chainLog)
  928. * > (3<<29) - (1<<chainLog)
  929. * > (3<<29) - (1<<30) (NOTE: chainLog <= 30)
  930. * > 1<<29
  931. *
  932. * 2. (ip+ZSTD_CHUNKSIZE_MAX - cctx->base) doesn't overflow:
  933. * After correction, current is less than (1<<chainLog + 1<<windowLog).
  934. * In 64-bit mode we are safe, because we have 64-bit ptrdiff_t.
  935. * In 32-bit mode we are safe, because (chainLog <= 29), so
  936. * ip+ZSTD_CHUNKSIZE_MAX - cctx->base < 1<<32.
  937. * 3. (cctx->lowLimit + 1<<windowLog) < 1<<32:
  938. * windowLog <= 31 ==> 3<<29 + 1<<windowLog < 7<<29 < 1<<32.
  939. */
  940. U32 const cycleSize = 1u << cycleLog;
  941. U32 const cycleMask = cycleSize - 1;
  942. U32 const curr = (U32)((BYTE const*)src - window->base);
  943. U32 const currentCycle = curr & cycleMask;
  944. /* Ensure newCurrent - maxDist >= ZSTD_WINDOW_START_INDEX. */
  945. U32 const currentCycleCorrection = currentCycle < ZSTD_WINDOW_START_INDEX
  946. ? MAX(cycleSize, ZSTD_WINDOW_START_INDEX)
  947. : 0;
  948. U32 const newCurrent = currentCycle
  949. + currentCycleCorrection
  950. + MAX(maxDist, cycleSize);
  951. U32 const correction = curr - newCurrent;
  952. /* maxDist must be a power of two so that:
  953. * (newCurrent & cycleMask) == (curr & cycleMask)
  954. * This is required to not corrupt the chains / binary tree.
  955. */
  956. assert((maxDist & (maxDist - 1)) == 0);
  957. assert((curr & cycleMask) == (newCurrent & cycleMask));
  958. assert(curr > newCurrent);
  959. if (!ZSTD_WINDOW_OVERFLOW_CORRECT_FREQUENTLY) {
  960. /* Loose bound, should be around 1<<29 (see above) */
  961. assert(correction > 1<<28);
  962. }
  963. window->base += correction;
  964. window->dictBase += correction;
  965. if (window->lowLimit < correction + ZSTD_WINDOW_START_INDEX) {
  966. window->lowLimit = ZSTD_WINDOW_START_INDEX;
  967. } else {
  968. window->lowLimit -= correction;
  969. }
  970. if (window->dictLimit < correction + ZSTD_WINDOW_START_INDEX) {
  971. window->dictLimit = ZSTD_WINDOW_START_INDEX;
  972. } else {
  973. window->dictLimit -= correction;
  974. }
  975. /* Ensure we can still reference the full window. */
  976. assert(newCurrent >= maxDist);
  977. assert(newCurrent - maxDist >= ZSTD_WINDOW_START_INDEX);
  978. /* Ensure that lowLimit and dictLimit didn't underflow. */
  979. assert(window->lowLimit <= newCurrent);
  980. assert(window->dictLimit <= newCurrent);
  981. ++window->nbOverflowCorrections;
  982. DEBUGLOG(4, "Correction of 0x%x bytes to lowLimit=0x%x", correction,
  983. window->lowLimit);
  984. return correction;
  985. }
  986. /**
  987. * ZSTD_window_enforceMaxDist():
  988. * Updates lowLimit so that:
  989. * (srcEnd - base) - lowLimit == maxDist + loadedDictEnd
  990. *
  991. * It ensures index is valid as long as index >= lowLimit.
  992. * This must be called before a block compression call.
  993. *
  994. * loadedDictEnd is only defined if a dictionary is in use for current compression.
  995. * As the name implies, loadedDictEnd represents the index at end of dictionary.
  996. * The value lies within context's referential, it can be directly compared to blockEndIdx.
  997. *
  998. * If loadedDictEndPtr is NULL, no dictionary is in use, and we use loadedDictEnd == 0.
  999. * If loadedDictEndPtr is not NULL, we set it to zero after updating lowLimit.
  1000. * This is because dictionaries are allowed to be referenced fully
  1001. * as long as the last byte of the dictionary is in the window.
  1002. * Once input has progressed beyond window size, dictionary cannot be referenced anymore.
  1003. *
  1004. * In normal dict mode, the dictionary lies between lowLimit and dictLimit.
  1005. * In dictMatchState mode, lowLimit and dictLimit are the same,
  1006. * and the dictionary is below them.
  1007. * forceWindow and dictMatchState are therefore incompatible.
  1008. */
  1009. MEM_STATIC void
  1010. ZSTD_window_enforceMaxDist(ZSTD_window_t* window,
  1011. const void* blockEnd,
  1012. U32 maxDist,
  1013. U32* loadedDictEndPtr,
  1014. const ZSTD_matchState_t** dictMatchStatePtr)
  1015. {
  1016. U32 const blockEndIdx = (U32)((BYTE const*)blockEnd - window->base);
  1017. U32 const loadedDictEnd = (loadedDictEndPtr != NULL) ? *loadedDictEndPtr : 0;
  1018. DEBUGLOG(5, "ZSTD_window_enforceMaxDist: blockEndIdx=%u, maxDist=%u, loadedDictEnd=%u",
  1019. (unsigned)blockEndIdx, (unsigned)maxDist, (unsigned)loadedDictEnd);
  1020. /* - When there is no dictionary : loadedDictEnd == 0.
  1021. In which case, the test (blockEndIdx > maxDist) is merely to avoid
  1022. overflowing next operation `newLowLimit = blockEndIdx - maxDist`.
  1023. - When there is a standard dictionary :
  1024. Index referential is copied from the dictionary,
  1025. which means it starts from 0.
  1026. In which case, loadedDictEnd == dictSize,
  1027. and it makes sense to compare `blockEndIdx > maxDist + dictSize`
  1028. since `blockEndIdx` also starts from zero.
  1029. - When there is an attached dictionary :
  1030. loadedDictEnd is expressed within the referential of the context,
  1031. so it can be directly compared against blockEndIdx.
  1032. */
  1033. if (blockEndIdx > maxDist + loadedDictEnd) {
  1034. U32 const newLowLimit = blockEndIdx - maxDist;
  1035. if (window->lowLimit < newLowLimit) window->lowLimit = newLowLimit;
  1036. if (window->dictLimit < window->lowLimit) {
  1037. DEBUGLOG(5, "Update dictLimit to match lowLimit, from %u to %u",
  1038. (unsigned)window->dictLimit, (unsigned)window->lowLimit);
  1039. window->dictLimit = window->lowLimit;
  1040. }
  1041. /* On reaching window size, dictionaries are invalidated */
  1042. if (loadedDictEndPtr) *loadedDictEndPtr = 0;
  1043. if (dictMatchStatePtr) *dictMatchStatePtr = NULL;
  1044. }
  1045. }
  1046. /* Similar to ZSTD_window_enforceMaxDist(),
  1047. * but only invalidates dictionary
  1048. * when input progresses beyond window size.
  1049. * assumption : loadedDictEndPtr and dictMatchStatePtr are valid (non NULL)
  1050. * loadedDictEnd uses same referential as window->base
  1051. * maxDist is the window size */
  1052. MEM_STATIC void
  1053. ZSTD_checkDictValidity(const ZSTD_window_t* window,
  1054. const void* blockEnd,
  1055. U32 maxDist,
  1056. U32* loadedDictEndPtr,
  1057. const ZSTD_matchState_t** dictMatchStatePtr)
  1058. {
  1059. assert(loadedDictEndPtr != NULL);
  1060. assert(dictMatchStatePtr != NULL);
  1061. { U32 const blockEndIdx = (U32)((BYTE const*)blockEnd - window->base);
  1062. U32 const loadedDictEnd = *loadedDictEndPtr;
  1063. DEBUGLOG(5, "ZSTD_checkDictValidity: blockEndIdx=%u, maxDist=%u, loadedDictEnd=%u",
  1064. (unsigned)blockEndIdx, (unsigned)maxDist, (unsigned)loadedDictEnd);
  1065. assert(blockEndIdx >= loadedDictEnd);
  1066. if (blockEndIdx > loadedDictEnd + maxDist || loadedDictEnd != window->dictLimit) {
  1067. /* On reaching window size, dictionaries are invalidated.
  1068. * For simplification, if window size is reached anywhere within next block,
  1069. * the dictionary is invalidated for the full block.
  1070. *
  1071. * We also have to invalidate the dictionary if ZSTD_window_update() has detected
  1072. * non-contiguous segments, which means that loadedDictEnd != window->dictLimit.
  1073. * loadedDictEnd may be 0, if forceWindow is true, but in that case we never use
  1074. * dictMatchState, so setting it to NULL is not a problem.
  1075. */
  1076. DEBUGLOG(6, "invalidating dictionary for current block (distance > windowSize)");
  1077. *loadedDictEndPtr = 0;
  1078. *dictMatchStatePtr = NULL;
  1079. } else {
  1080. if (*loadedDictEndPtr != 0) {
  1081. DEBUGLOG(6, "dictionary considered valid for current block");
  1082. } } }
  1083. }
  1084. MEM_STATIC void ZSTD_window_init(ZSTD_window_t* window) {
  1085. ZSTD_memset(window, 0, sizeof(*window));
  1086. window->base = (BYTE const*)" ";
  1087. window->dictBase = (BYTE const*)" ";
  1088. ZSTD_STATIC_ASSERT(ZSTD_DUBT_UNSORTED_MARK < ZSTD_WINDOW_START_INDEX); /* Start above ZSTD_DUBT_UNSORTED_MARK */
  1089. window->dictLimit = ZSTD_WINDOW_START_INDEX; /* start from >0, so that 1st position is valid */
  1090. window->lowLimit = ZSTD_WINDOW_START_INDEX; /* it ensures first and later CCtx usages compress the same */
  1091. window->nextSrc = window->base + ZSTD_WINDOW_START_INDEX; /* see issue #1241 */
  1092. window->nbOverflowCorrections = 0;
  1093. }
  1094. /**
  1095. * ZSTD_window_update():
  1096. * Updates the window by appending [src, src + srcSize) to the window.
  1097. * If it is not contiguous, the current prefix becomes the extDict, and we
  1098. * forget about the extDict. Handles overlap of the prefix and extDict.
  1099. * Returns non-zero if the segment is contiguous.
  1100. */
  1101. MEM_STATIC 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. * @return : An error code on failure.
  1296. * NOTE: seqs are not verified! Invalid sequences can cause out-of-bounds memory
  1297. * access and data corruption.
  1298. */
  1299. size_t ZSTD_referenceExternalSequences(ZSTD_CCtx* cctx, rawSeq* seq, size_t nbSeq);
  1300. /** ZSTD_cycleLog() :
  1301. * condition for correct operation : hashLog > 1 */
  1302. U32 ZSTD_cycleLog(U32 hashLog, ZSTD_strategy strat);
  1303. /** ZSTD_CCtx_trace() :
  1304. * Trace the end of a compression call.
  1305. */
  1306. void ZSTD_CCtx_trace(ZSTD_CCtx* cctx, size_t extraCSize);
  1307. /* Returns 0 on success, and a ZSTD_error otherwise. This function scans through an array of
  1308. * ZSTD_Sequence, storing the sequences it finds, until it reaches a block delimiter.
  1309. * Note that the block delimiter must include the last literals of the block.
  1310. */
  1311. size_t
  1312. ZSTD_copySequencesToSeqStoreExplicitBlockDelim(ZSTD_CCtx* cctx,
  1313. ZSTD_sequencePosition* seqPos,
  1314. const ZSTD_Sequence* const inSeqs, size_t inSeqsSize,
  1315. const void* src, size_t blockSize, ZSTD_paramSwitch_e externalRepSearch);
  1316. /* Returns the number of bytes to move the current read position back by.
  1317. * Only non-zero if we ended up splitting a sequence.
  1318. * Otherwise, it may return a ZSTD error if something went wrong.
  1319. *
  1320. * This function will attempt to scan through blockSize bytes
  1321. * represented by the sequences in @inSeqs,
  1322. * storing any (partial) sequences.
  1323. *
  1324. * Occasionally, we may want to change the actual number of bytes we consumed from inSeqs to
  1325. * avoid splitting a match, or to avoid splitting a match such that it would produce a match
  1326. * smaller than MINMATCH. In this case, we return the number of bytes that we didn't read from this block.
  1327. */
  1328. size_t
  1329. ZSTD_copySequencesToSeqStoreNoBlockDelim(ZSTD_CCtx* cctx, ZSTD_sequencePosition* seqPos,
  1330. const ZSTD_Sequence* const inSeqs, size_t inSeqsSize,
  1331. const void* src, size_t blockSize, ZSTD_paramSwitch_e externalRepSearch);
  1332. /* ===============================================================
  1333. * Deprecated definitions that are still used internally to avoid
  1334. * deprecation warnings. These functions are exactly equivalent to
  1335. * their public variants, but avoid the deprecation warnings.
  1336. * =============================================================== */
  1337. size_t ZSTD_compressBegin_usingCDict_deprecated(ZSTD_CCtx* cctx, const ZSTD_CDict* cdict);
  1338. size_t ZSTD_compressContinue_public(ZSTD_CCtx* cctx,
  1339. void* dst, size_t dstCapacity,
  1340. const void* src, size_t srcSize);
  1341. size_t ZSTD_compressEnd_public(ZSTD_CCtx* cctx,
  1342. void* dst, size_t dstCapacity,
  1343. const void* src, size_t srcSize);
  1344. size_t ZSTD_compressBlock_deprecated(ZSTD_CCtx* cctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize);
  1345. #endif /* ZSTD_COMPRESS_H */