zstd_compress_internal.h 49 KB

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