zstd_compress_internal.h 48 KB

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