zstd_compress_internal.h 29 KB

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