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

zstd_compress_internal.h 45KB

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