zstd_compress_internal.h 58 KB

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