zstd_compress_internal.h 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861
  1. /*
  2. * Copyright (c) 2016-present, 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. #ifdef ZSTD_MULTITHREAD
  20. # include "zstdmt_compress.h"
  21. #endif
  22. #if defined (__cplusplus)
  23. extern "C" {
  24. #endif
  25. /*-*************************************
  26. * Constants
  27. ***************************************/
  28. #define kSearchStrength 8
  29. #define HASH_READ_SIZE 8
  30. #define ZSTD_DUBT_UNSORTED_MARK 1 /* For btlazy2 strategy, index 1 now means "unsorted".
  31. It could be confused for a real successor at index "1", if sorted as larger than its predecessor.
  32. It's not a big deal though : candidate will just be sorted again.
  33. Additionnally, candidate position 1 will be lost.
  34. But candidate 1 cannot hide a large tree of candidates, so it's a minimal loss.
  35. The benefit is that ZSTD_DUBT_UNSORTED_MARK cannot be misdhandled after table re-use with a different strategy
  36. Constant required by ZSTD_compressBlock_btlazy2() and ZSTD_reduceTable_internal() */
  37. /*-*************************************
  38. * Context memory management
  39. ***************************************/
  40. typedef enum { ZSTDcs_created=0, ZSTDcs_init, ZSTDcs_ongoing, ZSTDcs_ending } ZSTD_compressionStage_e;
  41. typedef enum { zcss_init=0, zcss_load, zcss_flush } ZSTD_cStreamStage;
  42. typedef struct ZSTD_prefixDict_s {
  43. const void* dict;
  44. size_t dictSize;
  45. ZSTD_dictContentType_e dictContentType;
  46. } ZSTD_prefixDict;
  47. typedef struct {
  48. U32 CTable[HUF_CTABLE_SIZE_U32(255)];
  49. HUF_repeat repeatMode;
  50. } ZSTD_hufCTables_t;
  51. typedef struct {
  52. FSE_CTable offcodeCTable[FSE_CTABLE_SIZE_U32(OffFSELog, MaxOff)];
  53. FSE_CTable matchlengthCTable[FSE_CTABLE_SIZE_U32(MLFSELog, MaxML)];
  54. FSE_CTable litlengthCTable[FSE_CTABLE_SIZE_U32(LLFSELog, MaxLL)];
  55. FSE_repeat offcode_repeatMode;
  56. FSE_repeat matchlength_repeatMode;
  57. FSE_repeat litlength_repeatMode;
  58. } ZSTD_fseCTables_t;
  59. typedef struct {
  60. ZSTD_hufCTables_t huf;
  61. ZSTD_fseCTables_t fse;
  62. } ZSTD_entropyCTables_t;
  63. typedef struct {
  64. U32 off;
  65. U32 len;
  66. } ZSTD_match_t;
  67. typedef struct {
  68. int price;
  69. U32 off;
  70. U32 mlen;
  71. U32 litlen;
  72. U32 rep[ZSTD_REP_NUM];
  73. } ZSTD_optimal_t;
  74. typedef enum { zop_dynamic=0, zop_predef } ZSTD_OptPrice_e;
  75. typedef struct {
  76. /* All tables are allocated inside cctx->workspace by ZSTD_resetCCtx_internal() */
  77. unsigned* litFreq; /* table of literals statistics, of size 256 */
  78. unsigned* litLengthFreq; /* table of litLength statistics, of size (MaxLL+1) */
  79. unsigned* matchLengthFreq; /* table of matchLength statistics, of size (MaxML+1) */
  80. unsigned* offCodeFreq; /* table of offCode statistics, of size (MaxOff+1) */
  81. ZSTD_match_t* matchTable; /* list of found matches, of size ZSTD_OPT_NUM+1 */
  82. ZSTD_optimal_t* priceTable; /* All positions tracked by optimal parser, of size ZSTD_OPT_NUM+1 */
  83. U32 litSum; /* nb of literals */
  84. U32 litLengthSum; /* nb of litLength codes */
  85. U32 matchLengthSum; /* nb of matchLength codes */
  86. U32 offCodeSum; /* nb of offset codes */
  87. U32 litSumBasePrice; /* to compare to log2(litfreq) */
  88. U32 litLengthSumBasePrice; /* to compare to log2(llfreq) */
  89. U32 matchLengthSumBasePrice;/* to compare to log2(mlfreq) */
  90. U32 offCodeSumBasePrice; /* to compare to log2(offreq) */
  91. ZSTD_OptPrice_e priceType; /* prices can be determined dynamically, or follow a pre-defined cost structure */
  92. const ZSTD_entropyCTables_t* symbolCosts; /* pre-calculated dictionary statistics */
  93. } optState_t;
  94. typedef struct {
  95. ZSTD_entropyCTables_t entropy;
  96. U32 rep[ZSTD_REP_NUM];
  97. } ZSTD_compressedBlockState_t;
  98. typedef struct {
  99. BYTE const* nextSrc; /* next block here to continue on current prefix */
  100. BYTE const* base; /* All regular indexes relative to this position */
  101. BYTE const* dictBase; /* extDict indexes relative to this position */
  102. U32 dictLimit; /* below that point, need extDict */
  103. U32 lowLimit; /* below that point, no more data */
  104. } ZSTD_window_t;
  105. typedef struct ZSTD_matchState_t ZSTD_matchState_t;
  106. struct ZSTD_matchState_t {
  107. ZSTD_window_t window; /* State for window round buffer management */
  108. U32 loadedDictEnd; /* index of end of dictionary */
  109. U32 nextToUpdate; /* index from which to continue table update */
  110. U32 nextToUpdate3; /* index from which to continue table update */
  111. U32 hashLog3; /* dispatch table : larger == faster, more memory */
  112. U32* hashTable;
  113. U32* hashTable3;
  114. U32* chainTable;
  115. optState_t opt; /* optimal parser state */
  116. const ZSTD_matchState_t * dictMatchState;
  117. ZSTD_compressionParameters cParams;
  118. };
  119. typedef struct {
  120. ZSTD_compressedBlockState_t* prevCBlock;
  121. ZSTD_compressedBlockState_t* nextCBlock;
  122. ZSTD_matchState_t matchState;
  123. } ZSTD_blockState_t;
  124. typedef struct {
  125. U32 offset;
  126. U32 checksum;
  127. } ldmEntry_t;
  128. typedef struct {
  129. ZSTD_window_t window; /* State for the window round buffer management */
  130. ldmEntry_t* hashTable;
  131. BYTE* bucketOffsets; /* Next position in bucket to insert entry */
  132. U64 hashPower; /* Used to compute the rolling hash.
  133. * Depends on ldmParams.minMatchLength */
  134. } ldmState_t;
  135. typedef struct {
  136. U32 enableLdm; /* 1 if enable long distance matching */
  137. U32 hashLog; /* Log size of hashTable */
  138. U32 bucketSizeLog; /* Log bucket size for collision resolution, at most 8 */
  139. U32 minMatchLength; /* Minimum match length */
  140. U32 hashRateLog; /* Log number of entries to skip */
  141. U32 windowLog; /* Window log for the LDM */
  142. } ldmParams_t;
  143. typedef struct {
  144. U32 offset;
  145. U32 litLength;
  146. U32 matchLength;
  147. } rawSeq;
  148. typedef struct {
  149. rawSeq* seq; /* The start of the sequences */
  150. size_t pos; /* The position where reading stopped. <= size. */
  151. size_t size; /* The number of sequences. <= capacity. */
  152. size_t capacity; /* The capacity starting from `seq` pointer */
  153. } rawSeqStore_t;
  154. struct ZSTD_CCtx_params_s {
  155. ZSTD_format_e format;
  156. ZSTD_compressionParameters cParams;
  157. ZSTD_frameParameters fParams;
  158. int compressionLevel;
  159. int forceWindow; /* force back-references to respect limit of
  160. * 1<<wLog, even for dictionary */
  161. ZSTD_dictAttachPref_e attachDictPref;
  162. /* Multithreading: used to pass parameters to mtctx */
  163. int nbWorkers;
  164. size_t jobSize;
  165. int overlapLog;
  166. int rsyncable;
  167. /* Long distance matching parameters */
  168. ldmParams_t ldmParams;
  169. /* Internal use, for createCCtxParams() and freeCCtxParams() only */
  170. ZSTD_customMem customMem;
  171. }; /* typedef'd to ZSTD_CCtx_params within "zstd.h" */
  172. struct ZSTD_CCtx_s {
  173. ZSTD_compressionStage_e stage;
  174. 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. */
  175. int bmi2; /* == 1 if the CPU supports BMI2 and 0 otherwise. CPU support is determined dynamically once per context lifetime. */
  176. ZSTD_CCtx_params requestedParams;
  177. ZSTD_CCtx_params appliedParams;
  178. U32 dictID;
  179. int workSpaceOversizedDuration;
  180. void* workSpace;
  181. size_t workSpaceSize;
  182. size_t blockSize;
  183. unsigned long long pledgedSrcSizePlusOne; /* this way, 0 (default) == unknown */
  184. unsigned long long consumedSrcSize;
  185. unsigned long long producedCSize;
  186. XXH64_state_t xxhState;
  187. ZSTD_customMem customMem;
  188. size_t staticSize;
  189. seqStore_t seqStore; /* sequences storage ptrs */
  190. ldmState_t ldmState; /* long distance matching state */
  191. rawSeq* ldmSequences; /* Storage for the ldm output sequences */
  192. size_t maxNbLdmSequences;
  193. rawSeqStore_t externSeqStore; /* Mutable reference to external sequences */
  194. ZSTD_blockState_t blockState;
  195. U32* entropyWorkspace; /* entropy workspace of HUF_WORKSPACE_SIZE bytes */
  196. /* streaming */
  197. char* inBuff;
  198. size_t inBuffSize;
  199. size_t inToCompress;
  200. size_t inBuffPos;
  201. size_t inBuffTarget;
  202. char* outBuff;
  203. size_t outBuffSize;
  204. size_t outBuffContentSize;
  205. size_t outBuffFlushedSize;
  206. ZSTD_cStreamStage streamStage;
  207. U32 frameEnded;
  208. /* Dictionary */
  209. ZSTD_CDict* cdictLocal;
  210. const ZSTD_CDict* cdict;
  211. ZSTD_prefixDict prefixDict; /* single-usage dictionary */
  212. /* Multi-threading */
  213. #ifdef ZSTD_MULTITHREAD
  214. ZSTDMT_CCtx* mtctx;
  215. #endif
  216. };
  217. typedef enum { ZSTD_dtlm_fast, ZSTD_dtlm_full } ZSTD_dictTableLoadMethod_e;
  218. typedef enum { ZSTD_noDict = 0, ZSTD_extDict = 1, ZSTD_dictMatchState = 2 } ZSTD_dictMode_e;
  219. typedef size_t (*ZSTD_blockCompressor) (
  220. ZSTD_matchState_t* bs, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
  221. void const* src, size_t srcSize);
  222. ZSTD_blockCompressor ZSTD_selectBlockCompressor(ZSTD_strategy strat, ZSTD_dictMode_e dictMode);
  223. MEM_STATIC U32 ZSTD_LLcode(U32 litLength)
  224. {
  225. static const BYTE LL_Code[64] = { 0, 1, 2, 3, 4, 5, 6, 7,
  226. 8, 9, 10, 11, 12, 13, 14, 15,
  227. 16, 16, 17, 17, 18, 18, 19, 19,
  228. 20, 20, 20, 20, 21, 21, 21, 21,
  229. 22, 22, 22, 22, 22, 22, 22, 22,
  230. 23, 23, 23, 23, 23, 23, 23, 23,
  231. 24, 24, 24, 24, 24, 24, 24, 24,
  232. 24, 24, 24, 24, 24, 24, 24, 24 };
  233. static const U32 LL_deltaCode = 19;
  234. return (litLength > 63) ? ZSTD_highbit32(litLength) + LL_deltaCode : LL_Code[litLength];
  235. }
  236. /* ZSTD_MLcode() :
  237. * note : mlBase = matchLength - MINMATCH;
  238. * because it's the format it's stored in seqStore->sequences */
  239. MEM_STATIC U32 ZSTD_MLcode(U32 mlBase)
  240. {
  241. static const BYTE ML_Code[128] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
  242. 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
  243. 32, 32, 33, 33, 34, 34, 35, 35, 36, 36, 36, 36, 37, 37, 37, 37,
  244. 38, 38, 38, 38, 38, 38, 38, 38, 39, 39, 39, 39, 39, 39, 39, 39,
  245. 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40,
  246. 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41,
  247. 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42,
  248. 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42 };
  249. static const U32 ML_deltaCode = 36;
  250. return (mlBase > 127) ? ZSTD_highbit32(mlBase) + ML_deltaCode : ML_Code[mlBase];
  251. }
  252. /*! ZSTD_storeSeq() :
  253. * Store a sequence (literal length, literals, offset code and match length code) into seqStore_t.
  254. * `offsetCode` : distance to match + 3 (values 1-3 are repCodes).
  255. * `mlBase` : matchLength - MINMATCH
  256. */
  257. MEM_STATIC void ZSTD_storeSeq(seqStore_t* seqStorePtr, size_t litLength, const void* literals, U32 offsetCode, size_t mlBase)
  258. {
  259. #if defined(DEBUGLEVEL) && (DEBUGLEVEL >= 6)
  260. static const BYTE* g_start = NULL;
  261. if (g_start==NULL) g_start = (const BYTE*)literals; /* note : index only works for compression within a single segment */
  262. { U32 const pos = (U32)((const BYTE*)literals - g_start);
  263. DEBUGLOG(6, "Cpos%7u :%3u literals, match%4u bytes at offCode%7u",
  264. pos, (U32)litLength, (U32)mlBase+MINMATCH, (U32)offsetCode);
  265. }
  266. #endif
  267. assert((size_t)(seqStorePtr->sequences - seqStorePtr->sequencesStart) < seqStorePtr->maxNbSeq);
  268. /* copy Literals */
  269. assert(seqStorePtr->maxNbLit <= 128 KB);
  270. assert(seqStorePtr->lit + litLength <= seqStorePtr->litStart + seqStorePtr->maxNbLit);
  271. ZSTD_wildcopy(seqStorePtr->lit, literals, litLength);
  272. seqStorePtr->lit += litLength;
  273. /* literal Length */
  274. if (litLength>0xFFFF) {
  275. assert(seqStorePtr->longLengthID == 0); /* there can only be a single long length */
  276. seqStorePtr->longLengthID = 1;
  277. seqStorePtr->longLengthPos = (U32)(seqStorePtr->sequences - seqStorePtr->sequencesStart);
  278. }
  279. seqStorePtr->sequences[0].litLength = (U16)litLength;
  280. /* match offset */
  281. seqStorePtr->sequences[0].offset = offsetCode + 1;
  282. /* match Length */
  283. if (mlBase>0xFFFF) {
  284. assert(seqStorePtr->longLengthID == 0); /* there can only be a single long length */
  285. seqStorePtr->longLengthID = 2;
  286. seqStorePtr->longLengthPos = (U32)(seqStorePtr->sequences - seqStorePtr->sequencesStart);
  287. }
  288. seqStorePtr->sequences[0].matchLength = (U16)mlBase;
  289. seqStorePtr->sequences++;
  290. }
  291. /*-*************************************
  292. * Match length counter
  293. ***************************************/
  294. static unsigned ZSTD_NbCommonBytes (size_t val)
  295. {
  296. if (MEM_isLittleEndian()) {
  297. if (MEM_64bits()) {
  298. # if defined(_MSC_VER) && defined(_WIN64)
  299. unsigned long r = 0;
  300. _BitScanForward64( &r, (U64)val );
  301. return (unsigned)(r>>3);
  302. # elif defined(__GNUC__) && (__GNUC__ >= 4)
  303. return (__builtin_ctzll((U64)val) >> 3);
  304. # else
  305. static const int DeBruijnBytePos[64] = { 0, 0, 0, 0, 0, 1, 1, 2,
  306. 0, 3, 1, 3, 1, 4, 2, 7,
  307. 0, 2, 3, 6, 1, 5, 3, 5,
  308. 1, 3, 4, 4, 2, 5, 6, 7,
  309. 7, 0, 1, 2, 3, 3, 4, 6,
  310. 2, 6, 5, 5, 3, 4, 5, 6,
  311. 7, 1, 2, 4, 6, 4, 4, 5,
  312. 7, 2, 6, 5, 7, 6, 7, 7 };
  313. return DeBruijnBytePos[((U64)((val & -(long long)val) * 0x0218A392CDABBD3FULL)) >> 58];
  314. # endif
  315. } else { /* 32 bits */
  316. # if defined(_MSC_VER)
  317. unsigned long r=0;
  318. _BitScanForward( &r, (U32)val );
  319. return (unsigned)(r>>3);
  320. # elif defined(__GNUC__) && (__GNUC__ >= 3)
  321. return (__builtin_ctz((U32)val) >> 3);
  322. # else
  323. static const int DeBruijnBytePos[32] = { 0, 0, 3, 0, 3, 1, 3, 0,
  324. 3, 2, 2, 1, 3, 2, 0, 1,
  325. 3, 3, 1, 2, 2, 2, 2, 0,
  326. 3, 1, 2, 0, 1, 0, 1, 1 };
  327. return DeBruijnBytePos[((U32)((val & -(S32)val) * 0x077CB531U)) >> 27];
  328. # endif
  329. }
  330. } else { /* Big Endian CPU */
  331. if (MEM_64bits()) {
  332. # if defined(_MSC_VER) && defined(_WIN64)
  333. unsigned long r = 0;
  334. _BitScanReverse64( &r, val );
  335. return (unsigned)(r>>3);
  336. # elif defined(__GNUC__) && (__GNUC__ >= 4)
  337. return (__builtin_clzll(val) >> 3);
  338. # else
  339. unsigned r;
  340. const unsigned n32 = sizeof(size_t)*4; /* calculate this way due to compiler complaining in 32-bits mode */
  341. if (!(val>>n32)) { r=4; } else { r=0; val>>=n32; }
  342. if (!(val>>16)) { r+=2; val>>=8; } else { val>>=24; }
  343. r += (!val);
  344. return r;
  345. # endif
  346. } else { /* 32 bits */
  347. # if defined(_MSC_VER)
  348. unsigned long r = 0;
  349. _BitScanReverse( &r, (unsigned long)val );
  350. return (unsigned)(r>>3);
  351. # elif defined(__GNUC__) && (__GNUC__ >= 3)
  352. return (__builtin_clz((U32)val) >> 3);
  353. # else
  354. unsigned r;
  355. if (!(val>>16)) { r=2; val>>=8; } else { r=0; val>>=24; }
  356. r += (!val);
  357. return r;
  358. # endif
  359. } }
  360. }
  361. MEM_STATIC size_t ZSTD_count(const BYTE* pIn, const BYTE* pMatch, const BYTE* const pInLimit)
  362. {
  363. const BYTE* const pStart = pIn;
  364. const BYTE* const pInLoopLimit = pInLimit - (sizeof(size_t)-1);
  365. if (pIn < pInLoopLimit) {
  366. { size_t const diff = MEM_readST(pMatch) ^ MEM_readST(pIn);
  367. if (diff) return ZSTD_NbCommonBytes(diff); }
  368. pIn+=sizeof(size_t); pMatch+=sizeof(size_t);
  369. while (pIn < pInLoopLimit) {
  370. size_t const diff = MEM_readST(pMatch) ^ MEM_readST(pIn);
  371. if (!diff) { pIn+=sizeof(size_t); pMatch+=sizeof(size_t); continue; }
  372. pIn += ZSTD_NbCommonBytes(diff);
  373. return (size_t)(pIn - pStart);
  374. } }
  375. if (MEM_64bits() && (pIn<(pInLimit-3)) && (MEM_read32(pMatch) == MEM_read32(pIn))) { pIn+=4; pMatch+=4; }
  376. if ((pIn<(pInLimit-1)) && (MEM_read16(pMatch) == MEM_read16(pIn))) { pIn+=2; pMatch+=2; }
  377. if ((pIn<pInLimit) && (*pMatch == *pIn)) pIn++;
  378. return (size_t)(pIn - pStart);
  379. }
  380. /** ZSTD_count_2segments() :
  381. * can count match length with `ip` & `match` in 2 different segments.
  382. * convention : on reaching mEnd, match count continue starting from iStart
  383. */
  384. MEM_STATIC size_t
  385. ZSTD_count_2segments(const BYTE* ip, const BYTE* match,
  386. const BYTE* iEnd, const BYTE* mEnd, const BYTE* iStart)
  387. {
  388. const BYTE* const vEnd = MIN( ip + (mEnd - match), iEnd);
  389. size_t const matchLength = ZSTD_count(ip, match, vEnd);
  390. if (match + matchLength != mEnd) return matchLength;
  391. DEBUGLOG(7, "ZSTD_count_2segments: found a 2-parts match (current length==%zu)", matchLength);
  392. DEBUGLOG(7, "distance from match beginning to end dictionary = %zi", mEnd - match);
  393. DEBUGLOG(7, "distance from current pos to end buffer = %zi", iEnd - ip);
  394. DEBUGLOG(7, "next byte : ip==%02X, istart==%02X", ip[matchLength], *iStart);
  395. DEBUGLOG(7, "final match length = %zu", matchLength + ZSTD_count(ip+matchLength, iStart, iEnd));
  396. return matchLength + ZSTD_count(ip+matchLength, iStart, iEnd);
  397. }
  398. /*-*************************************
  399. * Hashes
  400. ***************************************/
  401. static const U32 prime3bytes = 506832829U;
  402. static U32 ZSTD_hash3(U32 u, U32 h) { return ((u << (32-24)) * prime3bytes) >> (32-h) ; }
  403. MEM_STATIC size_t ZSTD_hash3Ptr(const void* ptr, U32 h) { return ZSTD_hash3(MEM_readLE32(ptr), h); } /* only in zstd_opt.h */
  404. static const U32 prime4bytes = 2654435761U;
  405. static U32 ZSTD_hash4(U32 u, U32 h) { return (u * prime4bytes) >> (32-h) ; }
  406. static size_t ZSTD_hash4Ptr(const void* ptr, U32 h) { return ZSTD_hash4(MEM_read32(ptr), h); }
  407. static const U64 prime5bytes = 889523592379ULL;
  408. static size_t ZSTD_hash5(U64 u, U32 h) { return (size_t)(((u << (64-40)) * prime5bytes) >> (64-h)) ; }
  409. static size_t ZSTD_hash5Ptr(const void* p, U32 h) { return ZSTD_hash5(MEM_readLE64(p), h); }
  410. static const U64 prime6bytes = 227718039650203ULL;
  411. static size_t ZSTD_hash6(U64 u, U32 h) { return (size_t)(((u << (64-48)) * prime6bytes) >> (64-h)) ; }
  412. static size_t ZSTD_hash6Ptr(const void* p, U32 h) { return ZSTD_hash6(MEM_readLE64(p), h); }
  413. static const U64 prime7bytes = 58295818150454627ULL;
  414. static size_t ZSTD_hash7(U64 u, U32 h) { return (size_t)(((u << (64-56)) * prime7bytes) >> (64-h)) ; }
  415. static size_t ZSTD_hash7Ptr(const void* p, U32 h) { return ZSTD_hash7(MEM_readLE64(p), h); }
  416. static const U64 prime8bytes = 0xCF1BBCDCB7A56463ULL;
  417. static size_t ZSTD_hash8(U64 u, U32 h) { return (size_t)(((u) * prime8bytes) >> (64-h)) ; }
  418. static size_t ZSTD_hash8Ptr(const void* p, U32 h) { return ZSTD_hash8(MEM_readLE64(p), h); }
  419. MEM_STATIC size_t ZSTD_hashPtr(const void* p, U32 hBits, U32 mls)
  420. {
  421. switch(mls)
  422. {
  423. default:
  424. case 4: return ZSTD_hash4Ptr(p, hBits);
  425. case 5: return ZSTD_hash5Ptr(p, hBits);
  426. case 6: return ZSTD_hash6Ptr(p, hBits);
  427. case 7: return ZSTD_hash7Ptr(p, hBits);
  428. case 8: return ZSTD_hash8Ptr(p, hBits);
  429. }
  430. }
  431. /** ZSTD_ipow() :
  432. * Return base^exponent.
  433. */
  434. static U64 ZSTD_ipow(U64 base, U64 exponent)
  435. {
  436. U64 power = 1;
  437. while (exponent) {
  438. if (exponent & 1) power *= base;
  439. exponent >>= 1;
  440. base *= base;
  441. }
  442. return power;
  443. }
  444. #define ZSTD_ROLL_HASH_CHAR_OFFSET 10
  445. /** ZSTD_rollingHash_append() :
  446. * Add the buffer to the hash value.
  447. */
  448. static U64 ZSTD_rollingHash_append(U64 hash, void const* buf, size_t size)
  449. {
  450. BYTE const* istart = (BYTE const*)buf;
  451. size_t pos;
  452. for (pos = 0; pos < size; ++pos) {
  453. hash *= prime8bytes;
  454. hash += istart[pos] + ZSTD_ROLL_HASH_CHAR_OFFSET;
  455. }
  456. return hash;
  457. }
  458. /** ZSTD_rollingHash_compute() :
  459. * Compute the rolling hash value of the buffer.
  460. */
  461. MEM_STATIC U64 ZSTD_rollingHash_compute(void const* buf, size_t size)
  462. {
  463. return ZSTD_rollingHash_append(0, buf, size);
  464. }
  465. /** ZSTD_rollingHash_primePower() :
  466. * Compute the primePower to be passed to ZSTD_rollingHash_rotate() for a hash
  467. * over a window of length bytes.
  468. */
  469. MEM_STATIC U64 ZSTD_rollingHash_primePower(U32 length)
  470. {
  471. return ZSTD_ipow(prime8bytes, length - 1);
  472. }
  473. /** ZSTD_rollingHash_rotate() :
  474. * Rotate the rolling hash by one byte.
  475. */
  476. MEM_STATIC U64 ZSTD_rollingHash_rotate(U64 hash, BYTE toRemove, BYTE toAdd, U64 primePower)
  477. {
  478. hash -= (toRemove + ZSTD_ROLL_HASH_CHAR_OFFSET) * primePower;
  479. hash *= prime8bytes;
  480. hash += toAdd + ZSTD_ROLL_HASH_CHAR_OFFSET;
  481. return hash;
  482. }
  483. /*-*************************************
  484. * Round buffer management
  485. ***************************************/
  486. /* Max current allowed */
  487. #define ZSTD_CURRENT_MAX ((3U << 29) + (1U << ZSTD_WINDOWLOG_MAX))
  488. /* Maximum chunk size before overflow correction needs to be called again */
  489. #define ZSTD_CHUNKSIZE_MAX \
  490. ( ((U32)-1) /* Maximum ending current index */ \
  491. - ZSTD_CURRENT_MAX) /* Maximum beginning lowLimit */
  492. /**
  493. * ZSTD_window_clear():
  494. * Clears the window containing the history by simply setting it to empty.
  495. */
  496. MEM_STATIC void ZSTD_window_clear(ZSTD_window_t* window)
  497. {
  498. size_t const endT = (size_t)(window->nextSrc - window->base);
  499. U32 const end = (U32)endT;
  500. window->lowLimit = end;
  501. window->dictLimit = end;
  502. }
  503. /**
  504. * ZSTD_window_hasExtDict():
  505. * Returns non-zero if the window has a non-empty extDict.
  506. */
  507. MEM_STATIC U32 ZSTD_window_hasExtDict(ZSTD_window_t const window)
  508. {
  509. return window.lowLimit < window.dictLimit;
  510. }
  511. /**
  512. * ZSTD_matchState_dictMode():
  513. * Inspects the provided matchState and figures out what dictMode should be
  514. * passed to the compressor.
  515. */
  516. MEM_STATIC ZSTD_dictMode_e ZSTD_matchState_dictMode(const ZSTD_matchState_t *ms)
  517. {
  518. return ZSTD_window_hasExtDict(ms->window) ?
  519. ZSTD_extDict :
  520. ms->dictMatchState != NULL ?
  521. ZSTD_dictMatchState :
  522. ZSTD_noDict;
  523. }
  524. /**
  525. * ZSTD_window_needOverflowCorrection():
  526. * Returns non-zero if the indices are getting too large and need overflow
  527. * protection.
  528. */
  529. MEM_STATIC U32 ZSTD_window_needOverflowCorrection(ZSTD_window_t const window,
  530. void const* srcEnd)
  531. {
  532. U32 const current = (U32)((BYTE const*)srcEnd - window.base);
  533. return current > ZSTD_CURRENT_MAX;
  534. }
  535. /**
  536. * ZSTD_window_correctOverflow():
  537. * Reduces the indices to protect from index overflow.
  538. * Returns the correction made to the indices, which must be applied to every
  539. * stored index.
  540. *
  541. * The least significant cycleLog bits of the indices must remain the same,
  542. * which may be 0. Every index up to maxDist in the past must be valid.
  543. * NOTE: (maxDist & cycleMask) must be zero.
  544. */
  545. MEM_STATIC U32 ZSTD_window_correctOverflow(ZSTD_window_t* window, U32 cycleLog,
  546. U32 maxDist, void const* src)
  547. {
  548. /* preemptive overflow correction:
  549. * 1. correction is large enough:
  550. * lowLimit > (3<<29) ==> current > 3<<29 + 1<<windowLog
  551. * 1<<windowLog <= newCurrent < 1<<chainLog + 1<<windowLog
  552. *
  553. * current - newCurrent
  554. * > (3<<29 + 1<<windowLog) - (1<<windowLog + 1<<chainLog)
  555. * > (3<<29) - (1<<chainLog)
  556. * > (3<<29) - (1<<30) (NOTE: chainLog <= 30)
  557. * > 1<<29
  558. *
  559. * 2. (ip+ZSTD_CHUNKSIZE_MAX - cctx->base) doesn't overflow:
  560. * After correction, current is less than (1<<chainLog + 1<<windowLog).
  561. * In 64-bit mode we are safe, because we have 64-bit ptrdiff_t.
  562. * In 32-bit mode we are safe, because (chainLog <= 29), so
  563. * ip+ZSTD_CHUNKSIZE_MAX - cctx->base < 1<<32.
  564. * 3. (cctx->lowLimit + 1<<windowLog) < 1<<32:
  565. * windowLog <= 31 ==> 3<<29 + 1<<windowLog < 7<<29 < 1<<32.
  566. */
  567. U32 const cycleMask = (1U << cycleLog) - 1;
  568. U32 const current = (U32)((BYTE const*)src - window->base);
  569. U32 const newCurrent = (current & cycleMask) + maxDist;
  570. U32 const correction = current - newCurrent;
  571. assert((maxDist & cycleMask) == 0);
  572. assert(current > newCurrent);
  573. /* Loose bound, should be around 1<<29 (see above) */
  574. assert(correction > 1<<28);
  575. window->base += correction;
  576. window->dictBase += correction;
  577. window->lowLimit -= correction;
  578. window->dictLimit -= correction;
  579. DEBUGLOG(4, "Correction of 0x%x bytes to lowLimit=0x%x", correction,
  580. window->lowLimit);
  581. return correction;
  582. }
  583. /**
  584. * ZSTD_window_enforceMaxDist():
  585. * Updates lowLimit so that:
  586. * (srcEnd - base) - lowLimit == maxDist + loadedDictEnd
  587. *
  588. * This allows a simple check that index >= lowLimit to see if index is valid.
  589. * This must be called before a block compression call, with srcEnd as the block
  590. * source end.
  591. *
  592. * If loadedDictEndPtr is not NULL, we set it to zero once we update lowLimit.
  593. * This is because dictionaries are allowed to be referenced as long as the last
  594. * byte of the dictionary is in the window, but once they are out of range,
  595. * they cannot be referenced. If loadedDictEndPtr is NULL, we use
  596. * loadedDictEnd == 0.
  597. *
  598. * In normal dict mode, the dict is between lowLimit and dictLimit. In
  599. * dictMatchState mode, lowLimit and dictLimit are the same, and the dictionary
  600. * is below them. forceWindow and dictMatchState are therefore incompatible.
  601. */
  602. MEM_STATIC void
  603. ZSTD_window_enforceMaxDist(ZSTD_window_t* window,
  604. void const* srcEnd,
  605. U32 maxDist,
  606. U32* loadedDictEndPtr,
  607. const ZSTD_matchState_t** dictMatchStatePtr)
  608. {
  609. U32 const blockEndIdx = (U32)((BYTE const*)srcEnd - window->base);
  610. U32 loadedDictEnd = (loadedDictEndPtr != NULL) ? *loadedDictEndPtr : 0;
  611. DEBUGLOG(5, "ZSTD_window_enforceMaxDist: blockEndIdx=%u, maxDist=%u",
  612. (unsigned)blockEndIdx, (unsigned)maxDist);
  613. if (blockEndIdx > maxDist + loadedDictEnd) {
  614. U32 const newLowLimit = blockEndIdx - maxDist;
  615. if (window->lowLimit < newLowLimit) window->lowLimit = newLowLimit;
  616. if (window->dictLimit < window->lowLimit) {
  617. DEBUGLOG(5, "Update dictLimit to match lowLimit, from %u to %u",
  618. (unsigned)window->dictLimit, (unsigned)window->lowLimit);
  619. window->dictLimit = window->lowLimit;
  620. }
  621. if (loadedDictEndPtr)
  622. *loadedDictEndPtr = 0;
  623. if (dictMatchStatePtr)
  624. *dictMatchStatePtr = NULL;
  625. }
  626. }
  627. /**
  628. * ZSTD_window_update():
  629. * Updates the window by appending [src, src + srcSize) to the window.
  630. * If it is not contiguous, the current prefix becomes the extDict, and we
  631. * forget about the extDict. Handles overlap of the prefix and extDict.
  632. * Returns non-zero if the segment is contiguous.
  633. */
  634. MEM_STATIC U32 ZSTD_window_update(ZSTD_window_t* window,
  635. void const* src, size_t srcSize)
  636. {
  637. BYTE const* const ip = (BYTE const*)src;
  638. U32 contiguous = 1;
  639. DEBUGLOG(5, "ZSTD_window_update");
  640. /* Check if blocks follow each other */
  641. if (src != window->nextSrc) {
  642. /* not contiguous */
  643. size_t const distanceFromBase = (size_t)(window->nextSrc - window->base);
  644. DEBUGLOG(5, "Non contiguous blocks, new segment starts at %u", window->dictLimit);
  645. window->lowLimit = window->dictLimit;
  646. assert(distanceFromBase == (size_t)(U32)distanceFromBase); /* should never overflow */
  647. window->dictLimit = (U32)distanceFromBase;
  648. window->dictBase = window->base;
  649. window->base = ip - distanceFromBase;
  650. // ms->nextToUpdate = window->dictLimit;
  651. if (window->dictLimit - window->lowLimit < HASH_READ_SIZE) window->lowLimit = window->dictLimit; /* too small extDict */
  652. contiguous = 0;
  653. }
  654. window->nextSrc = ip + srcSize;
  655. /* if input and dictionary overlap : reduce dictionary (area presumed modified by input) */
  656. if ( (ip+srcSize > window->dictBase + window->lowLimit)
  657. & (ip < window->dictBase + window->dictLimit)) {
  658. ptrdiff_t const highInputIdx = (ip + srcSize) - window->dictBase;
  659. U32 const lowLimitMax = (highInputIdx > (ptrdiff_t)window->dictLimit) ? window->dictLimit : (U32)highInputIdx;
  660. window->lowLimit = lowLimitMax;
  661. DEBUGLOG(5, "Overlapping extDict and input : new lowLimit = %u", window->lowLimit);
  662. }
  663. return contiguous;
  664. }
  665. /* debug functions */
  666. #if (DEBUGLEVEL>=2)
  667. MEM_STATIC double ZSTD_fWeight(U32 rawStat)
  668. {
  669. U32 const fp_accuracy = 8;
  670. U32 const fp_multiplier = (1 << fp_accuracy);
  671. U32 const newStat = rawStat + 1;
  672. U32 const hb = ZSTD_highbit32(newStat);
  673. U32 const BWeight = hb * fp_multiplier;
  674. U32 const FWeight = (newStat << fp_accuracy) >> hb;
  675. U32 const weight = BWeight + FWeight;
  676. assert(hb + fp_accuracy < 31);
  677. return (double)weight / fp_multiplier;
  678. }
  679. /* display a table content,
  680. * listing each element, its frequency, and its predicted bit cost */
  681. MEM_STATIC void ZSTD_debugTable(const U32* table, U32 max)
  682. {
  683. unsigned u, sum;
  684. for (u=0, sum=0; u<=max; u++) sum += table[u];
  685. DEBUGLOG(2, "total nb elts: %u", sum);
  686. for (u=0; u<=max; u++) {
  687. DEBUGLOG(2, "%2u: %5u (%.2f)",
  688. u, table[u], ZSTD_fWeight(sum) - ZSTD_fWeight(table[u]) );
  689. }
  690. }
  691. #endif
  692. #if defined (__cplusplus)
  693. }
  694. #endif
  695. /* ==============================================================
  696. * Private declarations
  697. * These prototypes shall only be called from within lib/compress
  698. * ============================================================== */
  699. /* ZSTD_getCParamsFromCCtxParams() :
  700. * cParams are built depending on compressionLevel, src size hints,
  701. * LDM and manually set compression parameters.
  702. */
  703. ZSTD_compressionParameters ZSTD_getCParamsFromCCtxParams(
  704. const ZSTD_CCtx_params* CCtxParams, U64 srcSizeHint, size_t dictSize);
  705. /*! ZSTD_initCStream_internal() :
  706. * Private use only. Init streaming operation.
  707. * expects params to be valid.
  708. * must receive dict, or cdict, or none, but not both.
  709. * @return : 0, or an error code */
  710. size_t ZSTD_initCStream_internal(ZSTD_CStream* zcs,
  711. const void* dict, size_t dictSize,
  712. const ZSTD_CDict* cdict,
  713. ZSTD_CCtx_params params, unsigned long long pledgedSrcSize);
  714. void ZSTD_resetSeqStore(seqStore_t* ssPtr);
  715. /*! ZSTD_compressStream_generic() :
  716. * Private use only. To be called from zstdmt_compress.c in single-thread mode. */
  717. size_t ZSTD_compressStream_generic(ZSTD_CStream* zcs,
  718. ZSTD_outBuffer* output,
  719. ZSTD_inBuffer* input,
  720. ZSTD_EndDirective const flushMode);
  721. /*! ZSTD_getCParamsFromCDict() :
  722. * as the name implies */
  723. ZSTD_compressionParameters ZSTD_getCParamsFromCDict(const ZSTD_CDict* cdict);
  724. /* ZSTD_compressBegin_advanced_internal() :
  725. * Private use only. To be called from zstdmt_compress.c. */
  726. size_t ZSTD_compressBegin_advanced_internal(ZSTD_CCtx* cctx,
  727. const void* dict, size_t dictSize,
  728. ZSTD_dictContentType_e dictContentType,
  729. ZSTD_dictTableLoadMethod_e dtlm,
  730. const ZSTD_CDict* cdict,
  731. ZSTD_CCtx_params params,
  732. unsigned long long pledgedSrcSize);
  733. /* ZSTD_compress_advanced_internal() :
  734. * Private use only. To be called from zstdmt_compress.c. */
  735. size_t ZSTD_compress_advanced_internal(ZSTD_CCtx* cctx,
  736. void* dst, size_t dstCapacity,
  737. const void* src, size_t srcSize,
  738. const void* dict,size_t dictSize,
  739. ZSTD_CCtx_params params);
  740. /* ZSTD_writeLastEmptyBlock() :
  741. * output an empty Block with end-of-frame mark to complete a frame
  742. * @return : size of data written into `dst` (== ZSTD_blockHeaderSize (defined in zstd_internal.h))
  743. * or an error code if `dstCapcity` is too small (<ZSTD_blockHeaderSize)
  744. */
  745. size_t ZSTD_writeLastEmptyBlock(void* dst, size_t dstCapacity);
  746. /* ZSTD_referenceExternalSequences() :
  747. * Must be called before starting a compression operation.
  748. * seqs must parse a prefix of the source.
  749. * This cannot be used when long range matching is enabled.
  750. * Zstd will use these sequences, and pass the literals to a secondary block
  751. * compressor.
  752. * @return : An error code on failure.
  753. * NOTE: seqs are not verified! Invalid sequences can cause out-of-bounds memory
  754. * access and data corruption.
  755. */
  756. size_t ZSTD_referenceExternalSequences(ZSTD_CCtx* cctx, rawSeq* seq, size_t nbSeq);
  757. #endif /* ZSTD_COMPRESS_H */