You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

zstd_compress_internal.h 60KB

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