zstd_ldm.c 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686
  1. /*
  2. * Copyright (c) Yann Collet, Facebook, Inc.
  3. * All rights reserved.
  4. *
  5. * This source code is licensed under both the BSD-style license (found in the
  6. * LICENSE file in the root directory of this source tree) and the GPLv2 (found
  7. * in the COPYING file in the root directory of this source tree).
  8. * You may select, at your option, one of the above-listed licenses.
  9. */
  10. #include "zstd_ldm.h"
  11. #include "../common/debug.h"
  12. #include <linux/xxhash.h>
  13. #include "zstd_fast.h" /* ZSTD_fillHashTable() */
  14. #include "zstd_double_fast.h" /* ZSTD_fillDoubleHashTable() */
  15. #include "zstd_ldm_geartab.h"
  16. #define LDM_BUCKET_SIZE_LOG 3
  17. #define LDM_MIN_MATCH_LENGTH 64
  18. #define LDM_HASH_RLOG 7
  19. typedef struct {
  20. U64 rolling;
  21. U64 stopMask;
  22. } ldmRollingHashState_t;
  23. /* ZSTD_ldm_gear_init():
  24. *
  25. * Initializes the rolling hash state such that it will honor the
  26. * settings in params. */
  27. static void ZSTD_ldm_gear_init(ldmRollingHashState_t* state, ldmParams_t const* params)
  28. {
  29. unsigned maxBitsInMask = MIN(params->minMatchLength, 64);
  30. unsigned hashRateLog = params->hashRateLog;
  31. state->rolling = ~(U32)0;
  32. /* The choice of the splitting criterion is subject to two conditions:
  33. * 1. it has to trigger on average every 2^(hashRateLog) bytes;
  34. * 2. ideally, it has to depend on a window of minMatchLength bytes.
  35. *
  36. * In the gear hash algorithm, bit n depends on the last n bytes;
  37. * so in order to obtain a good quality splitting criterion it is
  38. * preferable to use bits with high weight.
  39. *
  40. * To match condition 1 we use a mask with hashRateLog bits set
  41. * and, because of the previous remark, we make sure these bits
  42. * have the highest possible weight while still respecting
  43. * condition 2.
  44. */
  45. if (hashRateLog > 0 && hashRateLog <= maxBitsInMask) {
  46. state->stopMask = (((U64)1 << hashRateLog) - 1) << (maxBitsInMask - hashRateLog);
  47. } else {
  48. /* In this degenerate case we simply honor the hash rate. */
  49. state->stopMask = ((U64)1 << hashRateLog) - 1;
  50. }
  51. }
  52. /* ZSTD_ldm_gear_feed():
  53. *
  54. * Registers in the splits array all the split points found in the first
  55. * size bytes following the data pointer. This function terminates when
  56. * either all the data has been processed or LDM_BATCH_SIZE splits are
  57. * present in the splits array.
  58. *
  59. * Precondition: The splits array must not be full.
  60. * Returns: The number of bytes processed. */
  61. static size_t ZSTD_ldm_gear_feed(ldmRollingHashState_t* state,
  62. BYTE const* data, size_t size,
  63. size_t* splits, unsigned* numSplits)
  64. {
  65. size_t n;
  66. U64 hash, mask;
  67. hash = state->rolling;
  68. mask = state->stopMask;
  69. n = 0;
  70. #define GEAR_ITER_ONCE() do { \
  71. hash = (hash << 1) + ZSTD_ldm_gearTab[data[n] & 0xff]; \
  72. n += 1; \
  73. if (UNLIKELY((hash & mask) == 0)) { \
  74. splits[*numSplits] = n; \
  75. *numSplits += 1; \
  76. if (*numSplits == LDM_BATCH_SIZE) \
  77. goto done; \
  78. } \
  79. } while (0)
  80. while (n + 3 < size) {
  81. GEAR_ITER_ONCE();
  82. GEAR_ITER_ONCE();
  83. GEAR_ITER_ONCE();
  84. GEAR_ITER_ONCE();
  85. }
  86. while (n < size) {
  87. GEAR_ITER_ONCE();
  88. }
  89. #undef GEAR_ITER_ONCE
  90. done:
  91. state->rolling = hash;
  92. return n;
  93. }
  94. void ZSTD_ldm_adjustParameters(ldmParams_t* params,
  95. ZSTD_compressionParameters const* cParams)
  96. {
  97. params->windowLog = cParams->windowLog;
  98. ZSTD_STATIC_ASSERT(LDM_BUCKET_SIZE_LOG <= ZSTD_LDM_BUCKETSIZELOG_MAX);
  99. DEBUGLOG(4, "ZSTD_ldm_adjustParameters");
  100. if (!params->bucketSizeLog) params->bucketSizeLog = LDM_BUCKET_SIZE_LOG;
  101. if (!params->minMatchLength) params->minMatchLength = LDM_MIN_MATCH_LENGTH;
  102. if (params->hashLog == 0) {
  103. params->hashLog = MAX(ZSTD_HASHLOG_MIN, params->windowLog - LDM_HASH_RLOG);
  104. assert(params->hashLog <= ZSTD_HASHLOG_MAX);
  105. }
  106. if (params->hashRateLog == 0) {
  107. params->hashRateLog = params->windowLog < params->hashLog
  108. ? 0
  109. : params->windowLog - params->hashLog;
  110. }
  111. params->bucketSizeLog = MIN(params->bucketSizeLog, params->hashLog);
  112. }
  113. size_t ZSTD_ldm_getTableSize(ldmParams_t params)
  114. {
  115. size_t const ldmHSize = ((size_t)1) << params.hashLog;
  116. size_t const ldmBucketSizeLog = MIN(params.bucketSizeLog, params.hashLog);
  117. size_t const ldmBucketSize = ((size_t)1) << (params.hashLog - ldmBucketSizeLog);
  118. size_t const totalSize = ZSTD_cwksp_alloc_size(ldmBucketSize)
  119. + ZSTD_cwksp_alloc_size(ldmHSize * sizeof(ldmEntry_t));
  120. return params.enableLdm ? totalSize : 0;
  121. }
  122. size_t ZSTD_ldm_getMaxNbSeq(ldmParams_t params, size_t maxChunkSize)
  123. {
  124. return params.enableLdm ? (maxChunkSize / params.minMatchLength) : 0;
  125. }
  126. /* ZSTD_ldm_getBucket() :
  127. * Returns a pointer to the start of the bucket associated with hash. */
  128. static ldmEntry_t* ZSTD_ldm_getBucket(
  129. ldmState_t* ldmState, size_t hash, ldmParams_t const ldmParams)
  130. {
  131. return ldmState->hashTable + (hash << ldmParams.bucketSizeLog);
  132. }
  133. /* ZSTD_ldm_insertEntry() :
  134. * Insert the entry with corresponding hash into the hash table */
  135. static void ZSTD_ldm_insertEntry(ldmState_t* ldmState,
  136. size_t const hash, const ldmEntry_t entry,
  137. ldmParams_t const ldmParams)
  138. {
  139. BYTE* const pOffset = ldmState->bucketOffsets + hash;
  140. unsigned const offset = *pOffset;
  141. *(ZSTD_ldm_getBucket(ldmState, hash, ldmParams) + offset) = entry;
  142. *pOffset = (BYTE)((offset + 1) & ((1u << ldmParams.bucketSizeLog) - 1));
  143. }
  144. /* ZSTD_ldm_countBackwardsMatch() :
  145. * Returns the number of bytes that match backwards before pIn and pMatch.
  146. *
  147. * We count only bytes where pMatch >= pBase and pIn >= pAnchor. */
  148. static size_t ZSTD_ldm_countBackwardsMatch(
  149. const BYTE* pIn, const BYTE* pAnchor,
  150. const BYTE* pMatch, const BYTE* pMatchBase)
  151. {
  152. size_t matchLength = 0;
  153. while (pIn > pAnchor && pMatch > pMatchBase && pIn[-1] == pMatch[-1]) {
  154. pIn--;
  155. pMatch--;
  156. matchLength++;
  157. }
  158. return matchLength;
  159. }
  160. /* ZSTD_ldm_countBackwardsMatch_2segments() :
  161. * Returns the number of bytes that match backwards from pMatch,
  162. * even with the backwards match spanning 2 different segments.
  163. *
  164. * On reaching `pMatchBase`, start counting from mEnd */
  165. static size_t ZSTD_ldm_countBackwardsMatch_2segments(
  166. const BYTE* pIn, const BYTE* pAnchor,
  167. const BYTE* pMatch, const BYTE* pMatchBase,
  168. const BYTE* pExtDictStart, const BYTE* pExtDictEnd)
  169. {
  170. size_t matchLength = ZSTD_ldm_countBackwardsMatch(pIn, pAnchor, pMatch, pMatchBase);
  171. if (pMatch - matchLength != pMatchBase || pMatchBase == pExtDictStart) {
  172. /* If backwards match is entirely in the extDict or prefix, immediately return */
  173. return matchLength;
  174. }
  175. DEBUGLOG(7, "ZSTD_ldm_countBackwardsMatch_2segments: found 2-parts backwards match (length in prefix==%zu)", matchLength);
  176. matchLength += ZSTD_ldm_countBackwardsMatch(pIn - matchLength, pAnchor, pExtDictEnd, pExtDictStart);
  177. DEBUGLOG(7, "final backwards match length = %zu", matchLength);
  178. return matchLength;
  179. }
  180. /* ZSTD_ldm_fillFastTables() :
  181. *
  182. * Fills the relevant tables for the ZSTD_fast and ZSTD_dfast strategies.
  183. * This is similar to ZSTD_loadDictionaryContent.
  184. *
  185. * The tables for the other strategies are filled within their
  186. * block compressors. */
  187. static size_t ZSTD_ldm_fillFastTables(ZSTD_matchState_t* ms,
  188. void const* end)
  189. {
  190. const BYTE* const iend = (const BYTE*)end;
  191. switch(ms->cParams.strategy)
  192. {
  193. case ZSTD_fast:
  194. ZSTD_fillHashTable(ms, iend, ZSTD_dtlm_fast);
  195. break;
  196. case ZSTD_dfast:
  197. ZSTD_fillDoubleHashTable(ms, iend, ZSTD_dtlm_fast);
  198. break;
  199. case ZSTD_greedy:
  200. case ZSTD_lazy:
  201. case ZSTD_lazy2:
  202. case ZSTD_btlazy2:
  203. case ZSTD_btopt:
  204. case ZSTD_btultra:
  205. case ZSTD_btultra2:
  206. break;
  207. default:
  208. assert(0); /* not possible : not a valid strategy id */
  209. }
  210. return 0;
  211. }
  212. void ZSTD_ldm_fillHashTable(
  213. ldmState_t* ldmState, const BYTE* ip,
  214. const BYTE* iend, ldmParams_t const* params)
  215. {
  216. U32 const minMatchLength = params->minMatchLength;
  217. U32 const hBits = params->hashLog - params->bucketSizeLog;
  218. BYTE const* const base = ldmState->window.base;
  219. BYTE const* const istart = ip;
  220. ldmRollingHashState_t hashState;
  221. size_t* const splits = ldmState->splitIndices;
  222. unsigned numSplits;
  223. DEBUGLOG(5, "ZSTD_ldm_fillHashTable");
  224. ZSTD_ldm_gear_init(&hashState, params);
  225. while (ip < iend) {
  226. size_t hashed;
  227. unsigned n;
  228. numSplits = 0;
  229. hashed = ZSTD_ldm_gear_feed(&hashState, ip, iend - ip, splits, &numSplits);
  230. for (n = 0; n < numSplits; n++) {
  231. if (ip + splits[n] >= istart + minMatchLength) {
  232. BYTE const* const split = ip + splits[n] - minMatchLength;
  233. U64 const xxhash = xxh64(split, minMatchLength, 0);
  234. U32 const hash = (U32)(xxhash & (((U32)1 << hBits) - 1));
  235. ldmEntry_t entry;
  236. entry.offset = (U32)(split - base);
  237. entry.checksum = (U32)(xxhash >> 32);
  238. ZSTD_ldm_insertEntry(ldmState, hash, entry, *params);
  239. }
  240. }
  241. ip += hashed;
  242. }
  243. }
  244. /* ZSTD_ldm_limitTableUpdate() :
  245. *
  246. * Sets cctx->nextToUpdate to a position corresponding closer to anchor
  247. * if it is far way
  248. * (after a long match, only update tables a limited amount). */
  249. static void ZSTD_ldm_limitTableUpdate(ZSTD_matchState_t* ms, const BYTE* anchor)
  250. {
  251. U32 const curr = (U32)(anchor - ms->window.base);
  252. if (curr > ms->nextToUpdate + 1024) {
  253. ms->nextToUpdate =
  254. curr - MIN(512, curr - ms->nextToUpdate - 1024);
  255. }
  256. }
  257. static size_t ZSTD_ldm_generateSequences_internal(
  258. ldmState_t* ldmState, rawSeqStore_t* rawSeqStore,
  259. ldmParams_t const* params, void const* src, size_t srcSize)
  260. {
  261. /* LDM parameters */
  262. int const extDict = ZSTD_window_hasExtDict(ldmState->window);
  263. U32 const minMatchLength = params->minMatchLength;
  264. U32 const entsPerBucket = 1U << params->bucketSizeLog;
  265. U32 const hBits = params->hashLog - params->bucketSizeLog;
  266. /* Prefix and extDict parameters */
  267. U32 const dictLimit = ldmState->window.dictLimit;
  268. U32 const lowestIndex = extDict ? ldmState->window.lowLimit : dictLimit;
  269. BYTE const* const base = ldmState->window.base;
  270. BYTE const* const dictBase = extDict ? ldmState->window.dictBase : NULL;
  271. BYTE const* const dictStart = extDict ? dictBase + lowestIndex : NULL;
  272. BYTE const* const dictEnd = extDict ? dictBase + dictLimit : NULL;
  273. BYTE const* const lowPrefixPtr = base + dictLimit;
  274. /* Input bounds */
  275. BYTE const* const istart = (BYTE const*)src;
  276. BYTE const* const iend = istart + srcSize;
  277. BYTE const* const ilimit = iend - HASH_READ_SIZE;
  278. /* Input positions */
  279. BYTE const* anchor = istart;
  280. BYTE const* ip = istart;
  281. /* Rolling hash state */
  282. ldmRollingHashState_t hashState;
  283. /* Arrays for staged-processing */
  284. size_t* const splits = ldmState->splitIndices;
  285. ldmMatchCandidate_t* const candidates = ldmState->matchCandidates;
  286. unsigned numSplits;
  287. if (srcSize < minMatchLength)
  288. return iend - anchor;
  289. /* Initialize the rolling hash state with the first minMatchLength bytes */
  290. ZSTD_ldm_gear_init(&hashState, params);
  291. {
  292. size_t n = 0;
  293. while (n < minMatchLength) {
  294. numSplits = 0;
  295. n += ZSTD_ldm_gear_feed(&hashState, ip + n, minMatchLength - n,
  296. splits, &numSplits);
  297. }
  298. ip += minMatchLength;
  299. }
  300. while (ip < ilimit) {
  301. size_t hashed;
  302. unsigned n;
  303. numSplits = 0;
  304. hashed = ZSTD_ldm_gear_feed(&hashState, ip, ilimit - ip,
  305. splits, &numSplits);
  306. for (n = 0; n < numSplits; n++) {
  307. BYTE const* const split = ip + splits[n] - minMatchLength;
  308. U64 const xxhash = xxh64(split, minMatchLength, 0);
  309. U32 const hash = (U32)(xxhash & (((U32)1 << hBits) - 1));
  310. candidates[n].split = split;
  311. candidates[n].hash = hash;
  312. candidates[n].checksum = (U32)(xxhash >> 32);
  313. candidates[n].bucket = ZSTD_ldm_getBucket(ldmState, hash, *params);
  314. PREFETCH_L1(candidates[n].bucket);
  315. }
  316. for (n = 0; n < numSplits; n++) {
  317. size_t forwardMatchLength = 0, backwardMatchLength = 0,
  318. bestMatchLength = 0, mLength;
  319. BYTE const* const split = candidates[n].split;
  320. U32 const checksum = candidates[n].checksum;
  321. U32 const hash = candidates[n].hash;
  322. ldmEntry_t* const bucket = candidates[n].bucket;
  323. ldmEntry_t const* cur;
  324. ldmEntry_t const* bestEntry = NULL;
  325. ldmEntry_t newEntry;
  326. newEntry.offset = (U32)(split - base);
  327. newEntry.checksum = checksum;
  328. /* If a split point would generate a sequence overlapping with
  329. * the previous one, we merely register it in the hash table and
  330. * move on */
  331. if (split < anchor) {
  332. ZSTD_ldm_insertEntry(ldmState, hash, newEntry, *params);
  333. continue;
  334. }
  335. for (cur = bucket; cur < bucket + entsPerBucket; cur++) {
  336. size_t curForwardMatchLength, curBackwardMatchLength,
  337. curTotalMatchLength;
  338. if (cur->checksum != checksum || cur->offset <= lowestIndex) {
  339. continue;
  340. }
  341. if (extDict) {
  342. BYTE const* const curMatchBase =
  343. cur->offset < dictLimit ? dictBase : base;
  344. BYTE const* const pMatch = curMatchBase + cur->offset;
  345. BYTE const* const matchEnd =
  346. cur->offset < dictLimit ? dictEnd : iend;
  347. BYTE const* const lowMatchPtr =
  348. cur->offset < dictLimit ? dictStart : lowPrefixPtr;
  349. curForwardMatchLength =
  350. ZSTD_count_2segments(split, pMatch, iend, matchEnd, lowPrefixPtr);
  351. if (curForwardMatchLength < minMatchLength) {
  352. continue;
  353. }
  354. curBackwardMatchLength = ZSTD_ldm_countBackwardsMatch_2segments(
  355. split, anchor, pMatch, lowMatchPtr, dictStart, dictEnd);
  356. } else { /* !extDict */
  357. BYTE const* const pMatch = base + cur->offset;
  358. curForwardMatchLength = ZSTD_count(split, pMatch, iend);
  359. if (curForwardMatchLength < minMatchLength) {
  360. continue;
  361. }
  362. curBackwardMatchLength =
  363. ZSTD_ldm_countBackwardsMatch(split, anchor, pMatch, lowPrefixPtr);
  364. }
  365. curTotalMatchLength = curForwardMatchLength + curBackwardMatchLength;
  366. if (curTotalMatchLength > bestMatchLength) {
  367. bestMatchLength = curTotalMatchLength;
  368. forwardMatchLength = curForwardMatchLength;
  369. backwardMatchLength = curBackwardMatchLength;
  370. bestEntry = cur;
  371. }
  372. }
  373. /* No match found -- insert an entry into the hash table
  374. * and process the next candidate match */
  375. if (bestEntry == NULL) {
  376. ZSTD_ldm_insertEntry(ldmState, hash, newEntry, *params);
  377. continue;
  378. }
  379. /* Match found */
  380. mLength = forwardMatchLength + backwardMatchLength;
  381. {
  382. U32 const offset = (U32)(split - base) - bestEntry->offset;
  383. rawSeq* const seq = rawSeqStore->seq + rawSeqStore->size;
  384. /* Out of sequence storage */
  385. if (rawSeqStore->size == rawSeqStore->capacity)
  386. return ERROR(dstSize_tooSmall);
  387. seq->litLength = (U32)(split - backwardMatchLength - anchor);
  388. seq->matchLength = (U32)mLength;
  389. seq->offset = offset;
  390. rawSeqStore->size++;
  391. }
  392. /* Insert the current entry into the hash table --- it must be
  393. * done after the previous block to avoid clobbering bestEntry */
  394. ZSTD_ldm_insertEntry(ldmState, hash, newEntry, *params);
  395. anchor = split + forwardMatchLength;
  396. }
  397. ip += hashed;
  398. }
  399. return iend - anchor;
  400. }
  401. /*! ZSTD_ldm_reduceTable() :
  402. * reduce table indexes by `reducerValue` */
  403. static void ZSTD_ldm_reduceTable(ldmEntry_t* const table, U32 const size,
  404. U32 const reducerValue)
  405. {
  406. U32 u;
  407. for (u = 0; u < size; u++) {
  408. if (table[u].offset < reducerValue) table[u].offset = 0;
  409. else table[u].offset -= reducerValue;
  410. }
  411. }
  412. size_t ZSTD_ldm_generateSequences(
  413. ldmState_t* ldmState, rawSeqStore_t* sequences,
  414. ldmParams_t const* params, void const* src, size_t srcSize)
  415. {
  416. U32 const maxDist = 1U << params->windowLog;
  417. BYTE const* const istart = (BYTE const*)src;
  418. BYTE const* const iend = istart + srcSize;
  419. size_t const kMaxChunkSize = 1 << 20;
  420. size_t const nbChunks = (srcSize / kMaxChunkSize) + ((srcSize % kMaxChunkSize) != 0);
  421. size_t chunk;
  422. size_t leftoverSize = 0;
  423. assert(ZSTD_CHUNKSIZE_MAX >= kMaxChunkSize);
  424. /* Check that ZSTD_window_update() has been called for this chunk prior
  425. * to passing it to this function.
  426. */
  427. assert(ldmState->window.nextSrc >= (BYTE const*)src + srcSize);
  428. /* The input could be very large (in zstdmt), so it must be broken up into
  429. * chunks to enforce the maximum distance and handle overflow correction.
  430. */
  431. assert(sequences->pos <= sequences->size);
  432. assert(sequences->size <= sequences->capacity);
  433. for (chunk = 0; chunk < nbChunks && sequences->size < sequences->capacity; ++chunk) {
  434. BYTE const* const chunkStart = istart + chunk * kMaxChunkSize;
  435. size_t const remaining = (size_t)(iend - chunkStart);
  436. BYTE const *const chunkEnd =
  437. (remaining < kMaxChunkSize) ? iend : chunkStart + kMaxChunkSize;
  438. size_t const chunkSize = chunkEnd - chunkStart;
  439. size_t newLeftoverSize;
  440. size_t const prevSize = sequences->size;
  441. assert(chunkStart < iend);
  442. /* 1. Perform overflow correction if necessary. */
  443. if (ZSTD_window_needOverflowCorrection(ldmState->window, chunkEnd)) {
  444. U32 const ldmHSize = 1U << params->hashLog;
  445. U32 const correction = ZSTD_window_correctOverflow(
  446. &ldmState->window, /* cycleLog */ 0, maxDist, chunkStart);
  447. ZSTD_ldm_reduceTable(ldmState->hashTable, ldmHSize, correction);
  448. /* invalidate dictionaries on overflow correction */
  449. ldmState->loadedDictEnd = 0;
  450. }
  451. /* 2. We enforce the maximum offset allowed.
  452. *
  453. * kMaxChunkSize should be small enough that we don't lose too much of
  454. * the window through early invalidation.
  455. * TODO: * Test the chunk size.
  456. * * Try invalidation after the sequence generation and test the
  457. * the offset against maxDist directly.
  458. *
  459. * NOTE: Because of dictionaries + sequence splitting we MUST make sure
  460. * that any offset used is valid at the END of the sequence, since it may
  461. * be split into two sequences. This condition holds when using
  462. * ZSTD_window_enforceMaxDist(), but if we move to checking offsets
  463. * against maxDist directly, we'll have to carefully handle that case.
  464. */
  465. ZSTD_window_enforceMaxDist(&ldmState->window, chunkEnd, maxDist, &ldmState->loadedDictEnd, NULL);
  466. /* 3. Generate the sequences for the chunk, and get newLeftoverSize. */
  467. newLeftoverSize = ZSTD_ldm_generateSequences_internal(
  468. ldmState, sequences, params, chunkStart, chunkSize);
  469. if (ZSTD_isError(newLeftoverSize))
  470. return newLeftoverSize;
  471. /* 4. We add the leftover literals from previous iterations to the first
  472. * newly generated sequence, or add the `newLeftoverSize` if none are
  473. * generated.
  474. */
  475. /* Prepend the leftover literals from the last call */
  476. if (prevSize < sequences->size) {
  477. sequences->seq[prevSize].litLength += (U32)leftoverSize;
  478. leftoverSize = newLeftoverSize;
  479. } else {
  480. assert(newLeftoverSize == chunkSize);
  481. leftoverSize += chunkSize;
  482. }
  483. }
  484. return 0;
  485. }
  486. void ZSTD_ldm_skipSequences(rawSeqStore_t* rawSeqStore, size_t srcSize, U32 const minMatch) {
  487. while (srcSize > 0 && rawSeqStore->pos < rawSeqStore->size) {
  488. rawSeq* seq = rawSeqStore->seq + rawSeqStore->pos;
  489. if (srcSize <= seq->litLength) {
  490. /* Skip past srcSize literals */
  491. seq->litLength -= (U32)srcSize;
  492. return;
  493. }
  494. srcSize -= seq->litLength;
  495. seq->litLength = 0;
  496. if (srcSize < seq->matchLength) {
  497. /* Skip past the first srcSize of the match */
  498. seq->matchLength -= (U32)srcSize;
  499. if (seq->matchLength < minMatch) {
  500. /* The match is too short, omit it */
  501. if (rawSeqStore->pos + 1 < rawSeqStore->size) {
  502. seq[1].litLength += seq[0].matchLength;
  503. }
  504. rawSeqStore->pos++;
  505. }
  506. return;
  507. }
  508. srcSize -= seq->matchLength;
  509. seq->matchLength = 0;
  510. rawSeqStore->pos++;
  511. }
  512. }
  513. /*
  514. * If the sequence length is longer than remaining then the sequence is split
  515. * between this block and the next.
  516. *
  517. * Returns the current sequence to handle, or if the rest of the block should
  518. * be literals, it returns a sequence with offset == 0.
  519. */
  520. static rawSeq maybeSplitSequence(rawSeqStore_t* rawSeqStore,
  521. U32 const remaining, U32 const minMatch)
  522. {
  523. rawSeq sequence = rawSeqStore->seq[rawSeqStore->pos];
  524. assert(sequence.offset > 0);
  525. /* Likely: No partial sequence */
  526. if (remaining >= sequence.litLength + sequence.matchLength) {
  527. rawSeqStore->pos++;
  528. return sequence;
  529. }
  530. /* Cut the sequence short (offset == 0 ==> rest is literals). */
  531. if (remaining <= sequence.litLength) {
  532. sequence.offset = 0;
  533. } else if (remaining < sequence.litLength + sequence.matchLength) {
  534. sequence.matchLength = remaining - sequence.litLength;
  535. if (sequence.matchLength < minMatch) {
  536. sequence.offset = 0;
  537. }
  538. }
  539. /* Skip past `remaining` bytes for the future sequences. */
  540. ZSTD_ldm_skipSequences(rawSeqStore, remaining, minMatch);
  541. return sequence;
  542. }
  543. void ZSTD_ldm_skipRawSeqStoreBytes(rawSeqStore_t* rawSeqStore, size_t nbBytes) {
  544. U32 currPos = (U32)(rawSeqStore->posInSequence + nbBytes);
  545. while (currPos && rawSeqStore->pos < rawSeqStore->size) {
  546. rawSeq currSeq = rawSeqStore->seq[rawSeqStore->pos];
  547. if (currPos >= currSeq.litLength + currSeq.matchLength) {
  548. currPos -= currSeq.litLength + currSeq.matchLength;
  549. rawSeqStore->pos++;
  550. } else {
  551. rawSeqStore->posInSequence = currPos;
  552. break;
  553. }
  554. }
  555. if (currPos == 0 || rawSeqStore->pos == rawSeqStore->size) {
  556. rawSeqStore->posInSequence = 0;
  557. }
  558. }
  559. size_t ZSTD_ldm_blockCompress(rawSeqStore_t* rawSeqStore,
  560. ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
  561. void const* src, size_t srcSize)
  562. {
  563. const ZSTD_compressionParameters* const cParams = &ms->cParams;
  564. unsigned const minMatch = cParams->minMatch;
  565. ZSTD_blockCompressor const blockCompressor =
  566. ZSTD_selectBlockCompressor(cParams->strategy, ZSTD_matchState_dictMode(ms));
  567. /* Input bounds */
  568. BYTE const* const istart = (BYTE const*)src;
  569. BYTE const* const iend = istart + srcSize;
  570. /* Input positions */
  571. BYTE const* ip = istart;
  572. DEBUGLOG(5, "ZSTD_ldm_blockCompress: srcSize=%zu", srcSize);
  573. /* If using opt parser, use LDMs only as candidates rather than always accepting them */
  574. if (cParams->strategy >= ZSTD_btopt) {
  575. size_t lastLLSize;
  576. ms->ldmSeqStore = rawSeqStore;
  577. lastLLSize = blockCompressor(ms, seqStore, rep, src, srcSize);
  578. ZSTD_ldm_skipRawSeqStoreBytes(rawSeqStore, srcSize);
  579. return lastLLSize;
  580. }
  581. assert(rawSeqStore->pos <= rawSeqStore->size);
  582. assert(rawSeqStore->size <= rawSeqStore->capacity);
  583. /* Loop through each sequence and apply the block compressor to the literals */
  584. while (rawSeqStore->pos < rawSeqStore->size && ip < iend) {
  585. /* maybeSplitSequence updates rawSeqStore->pos */
  586. rawSeq const sequence = maybeSplitSequence(rawSeqStore,
  587. (U32)(iend - ip), minMatch);
  588. int i;
  589. /* End signal */
  590. if (sequence.offset == 0)
  591. break;
  592. assert(ip + sequence.litLength + sequence.matchLength <= iend);
  593. /* Fill tables for block compressor */
  594. ZSTD_ldm_limitTableUpdate(ms, ip);
  595. ZSTD_ldm_fillFastTables(ms, ip);
  596. /* Run the block compressor */
  597. DEBUGLOG(5, "pos %u : calling block compressor on segment of size %u", (unsigned)(ip-istart), sequence.litLength);
  598. {
  599. size_t const newLitLength =
  600. blockCompressor(ms, seqStore, rep, ip, sequence.litLength);
  601. ip += sequence.litLength;
  602. /* Update the repcodes */
  603. for (i = ZSTD_REP_NUM - 1; i > 0; i--)
  604. rep[i] = rep[i-1];
  605. rep[0] = sequence.offset;
  606. /* Store the sequence */
  607. ZSTD_storeSeq(seqStore, newLitLength, ip - newLitLength, iend,
  608. sequence.offset + ZSTD_REP_MOVE,
  609. sequence.matchLength - MINMATCH);
  610. ip += sequence.matchLength;
  611. }
  612. }
  613. /* Fill the tables for the block compressor */
  614. ZSTD_ldm_limitTableUpdate(ms, ip);
  615. ZSTD_ldm_fillFastTables(ms, ip);
  616. /* Compress the last literals */
  617. return blockCompressor(ms, seqStore, rep, ip, iend - ip);
  618. }