zstd_ldm.c 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619
  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. #include "zstd_ldm.h"
  11. #include "../common/debug.h"
  12. #include "zstd_fast.h" /* ZSTD_fillHashTable() */
  13. #include "zstd_double_fast.h" /* ZSTD_fillDoubleHashTable() */
  14. #define LDM_BUCKET_SIZE_LOG 3
  15. #define LDM_MIN_MATCH_LENGTH 64
  16. #define LDM_HASH_RLOG 7
  17. #define LDM_HASH_CHAR_OFFSET 10
  18. void ZSTD_ldm_adjustParameters(ldmParams_t* params,
  19. ZSTD_compressionParameters const* cParams)
  20. {
  21. params->windowLog = cParams->windowLog;
  22. ZSTD_STATIC_ASSERT(LDM_BUCKET_SIZE_LOG <= ZSTD_LDM_BUCKETSIZELOG_MAX);
  23. DEBUGLOG(4, "ZSTD_ldm_adjustParameters");
  24. if (!params->bucketSizeLog) params->bucketSizeLog = LDM_BUCKET_SIZE_LOG;
  25. if (!params->minMatchLength) params->minMatchLength = LDM_MIN_MATCH_LENGTH;
  26. if (cParams->strategy >= ZSTD_btopt) {
  27. /* Get out of the way of the optimal parser */
  28. U32 const minMatch = MAX(cParams->targetLength, params->minMatchLength);
  29. assert(minMatch >= ZSTD_LDM_MINMATCH_MIN);
  30. assert(minMatch <= ZSTD_LDM_MINMATCH_MAX);
  31. params->minMatchLength = minMatch;
  32. }
  33. if (params->hashLog == 0) {
  34. params->hashLog = MAX(ZSTD_HASHLOG_MIN, params->windowLog - LDM_HASH_RLOG);
  35. assert(params->hashLog <= ZSTD_HASHLOG_MAX);
  36. }
  37. if (params->hashRateLog == 0) {
  38. params->hashRateLog = params->windowLog < params->hashLog
  39. ? 0
  40. : params->windowLog - params->hashLog;
  41. }
  42. params->bucketSizeLog = MIN(params->bucketSizeLog, params->hashLog);
  43. }
  44. size_t ZSTD_ldm_getTableSize(ldmParams_t params)
  45. {
  46. size_t const ldmHSize = ((size_t)1) << params.hashLog;
  47. size_t const ldmBucketSizeLog = MIN(params.bucketSizeLog, params.hashLog);
  48. size_t const ldmBucketSize = ((size_t)1) << (params.hashLog - ldmBucketSizeLog);
  49. size_t const totalSize = ZSTD_cwksp_alloc_size(ldmBucketSize)
  50. + ZSTD_cwksp_alloc_size(ldmHSize * sizeof(ldmEntry_t));
  51. return params.enableLdm ? totalSize : 0;
  52. }
  53. size_t ZSTD_ldm_getMaxNbSeq(ldmParams_t params, size_t maxChunkSize)
  54. {
  55. return params.enableLdm ? (maxChunkSize / params.minMatchLength) : 0;
  56. }
  57. /** ZSTD_ldm_getSmallHash() :
  58. * numBits should be <= 32
  59. * If numBits==0, returns 0.
  60. * @return : the most significant numBits of value. */
  61. static U32 ZSTD_ldm_getSmallHash(U64 value, U32 numBits)
  62. {
  63. assert(numBits <= 32);
  64. return numBits == 0 ? 0 : (U32)(value >> (64 - numBits));
  65. }
  66. /** ZSTD_ldm_getChecksum() :
  67. * numBitsToDiscard should be <= 32
  68. * @return : the next most significant 32 bits after numBitsToDiscard */
  69. static U32 ZSTD_ldm_getChecksum(U64 hash, U32 numBitsToDiscard)
  70. {
  71. assert(numBitsToDiscard <= 32);
  72. return (hash >> (64 - 32 - numBitsToDiscard)) & 0xFFFFFFFF;
  73. }
  74. /** ZSTD_ldm_getTag() ;
  75. * Given the hash, returns the most significant numTagBits bits
  76. * after (32 + hbits) bits.
  77. *
  78. * If there are not enough bits remaining, return the last
  79. * numTagBits bits. */
  80. static U32 ZSTD_ldm_getTag(U64 hash, U32 hbits, U32 numTagBits)
  81. {
  82. assert(numTagBits < 32 && hbits <= 32);
  83. if (32 - hbits < numTagBits) {
  84. return hash & (((U32)1 << numTagBits) - 1);
  85. } else {
  86. return (hash >> (32 - hbits - numTagBits)) & (((U32)1 << numTagBits) - 1);
  87. }
  88. }
  89. /** ZSTD_ldm_getBucket() :
  90. * Returns a pointer to the start of the bucket associated with hash. */
  91. static ldmEntry_t* ZSTD_ldm_getBucket(
  92. ldmState_t* ldmState, size_t hash, ldmParams_t const ldmParams)
  93. {
  94. return ldmState->hashTable + (hash << ldmParams.bucketSizeLog);
  95. }
  96. /** ZSTD_ldm_insertEntry() :
  97. * Insert the entry with corresponding hash into the hash table */
  98. static void ZSTD_ldm_insertEntry(ldmState_t* ldmState,
  99. size_t const hash, const ldmEntry_t entry,
  100. ldmParams_t const ldmParams)
  101. {
  102. BYTE* const bucketOffsets = ldmState->bucketOffsets;
  103. *(ZSTD_ldm_getBucket(ldmState, hash, ldmParams) + bucketOffsets[hash]) = entry;
  104. bucketOffsets[hash]++;
  105. bucketOffsets[hash] &= ((U32)1 << ldmParams.bucketSizeLog) - 1;
  106. }
  107. /** ZSTD_ldm_makeEntryAndInsertByTag() :
  108. *
  109. * Gets the small hash, checksum, and tag from the rollingHash.
  110. *
  111. * If the tag matches (1 << ldmParams.hashRateLog)-1, then
  112. * creates an ldmEntry from the offset, and inserts it into the hash table.
  113. *
  114. * hBits is the length of the small hash, which is the most significant hBits
  115. * of rollingHash. The checksum is the next 32 most significant bits, followed
  116. * by ldmParams.hashRateLog bits that make up the tag. */
  117. static void ZSTD_ldm_makeEntryAndInsertByTag(ldmState_t* ldmState,
  118. U64 const rollingHash,
  119. U32 const hBits,
  120. U32 const offset,
  121. ldmParams_t const ldmParams)
  122. {
  123. U32 const tag = ZSTD_ldm_getTag(rollingHash, hBits, ldmParams.hashRateLog);
  124. U32 const tagMask = ((U32)1 << ldmParams.hashRateLog) - 1;
  125. if (tag == tagMask) {
  126. U32 const hash = ZSTD_ldm_getSmallHash(rollingHash, hBits);
  127. U32 const checksum = ZSTD_ldm_getChecksum(rollingHash, hBits);
  128. ldmEntry_t entry;
  129. entry.offset = offset;
  130. entry.checksum = checksum;
  131. ZSTD_ldm_insertEntry(ldmState, hash, entry, ldmParams);
  132. }
  133. }
  134. /** ZSTD_ldm_countBackwardsMatch() :
  135. * Returns the number of bytes that match backwards before pIn and pMatch.
  136. *
  137. * We count only bytes where pMatch >= pBase and pIn >= pAnchor. */
  138. static size_t ZSTD_ldm_countBackwardsMatch(
  139. const BYTE* pIn, const BYTE* pAnchor,
  140. const BYTE* pMatch, const BYTE* pBase)
  141. {
  142. size_t matchLength = 0;
  143. while (pIn > pAnchor && pMatch > pBase && pIn[-1] == pMatch[-1]) {
  144. pIn--;
  145. pMatch--;
  146. matchLength++;
  147. }
  148. return matchLength;
  149. }
  150. /** ZSTD_ldm_fillFastTables() :
  151. *
  152. * Fills the relevant tables for the ZSTD_fast and ZSTD_dfast strategies.
  153. * This is similar to ZSTD_loadDictionaryContent.
  154. *
  155. * The tables for the other strategies are filled within their
  156. * block compressors. */
  157. static size_t ZSTD_ldm_fillFastTables(ZSTD_matchState_t* ms,
  158. void const* end)
  159. {
  160. const BYTE* const iend = (const BYTE*)end;
  161. switch(ms->cParams.strategy)
  162. {
  163. case ZSTD_fast:
  164. ZSTD_fillHashTable(ms, iend, ZSTD_dtlm_fast);
  165. break;
  166. case ZSTD_dfast:
  167. ZSTD_fillDoubleHashTable(ms, iend, ZSTD_dtlm_fast);
  168. break;
  169. case ZSTD_greedy:
  170. case ZSTD_lazy:
  171. case ZSTD_lazy2:
  172. case ZSTD_btlazy2:
  173. case ZSTD_btopt:
  174. case ZSTD_btultra:
  175. case ZSTD_btultra2:
  176. break;
  177. default:
  178. assert(0); /* not possible : not a valid strategy id */
  179. }
  180. return 0;
  181. }
  182. /** ZSTD_ldm_fillLdmHashTable() :
  183. *
  184. * Fills hashTable from (lastHashed + 1) to iend (non-inclusive).
  185. * lastHash is the rolling hash that corresponds to lastHashed.
  186. *
  187. * Returns the rolling hash corresponding to position iend-1. */
  188. static U64 ZSTD_ldm_fillLdmHashTable(ldmState_t* state,
  189. U64 lastHash, const BYTE* lastHashed,
  190. const BYTE* iend, const BYTE* base,
  191. U32 hBits, ldmParams_t const ldmParams)
  192. {
  193. U64 rollingHash = lastHash;
  194. const BYTE* cur = lastHashed + 1;
  195. while (cur < iend) {
  196. rollingHash = ZSTD_rollingHash_rotate(rollingHash, cur[-1],
  197. cur[ldmParams.minMatchLength-1],
  198. state->hashPower);
  199. ZSTD_ldm_makeEntryAndInsertByTag(state,
  200. rollingHash, hBits,
  201. (U32)(cur - base), ldmParams);
  202. ++cur;
  203. }
  204. return rollingHash;
  205. }
  206. void ZSTD_ldm_fillHashTable(
  207. ldmState_t* state, const BYTE* ip,
  208. const BYTE* iend, ldmParams_t const* params)
  209. {
  210. DEBUGLOG(5, "ZSTD_ldm_fillHashTable");
  211. if ((size_t)(iend - ip) >= params->minMatchLength) {
  212. U64 startingHash = ZSTD_rollingHash_compute(ip, params->minMatchLength);
  213. ZSTD_ldm_fillLdmHashTable(
  214. state, startingHash, ip, iend - params->minMatchLength, state->window.base,
  215. params->hashLog - params->bucketSizeLog,
  216. *params);
  217. }
  218. }
  219. /** ZSTD_ldm_limitTableUpdate() :
  220. *
  221. * Sets cctx->nextToUpdate to a position corresponding closer to anchor
  222. * if it is far way
  223. * (after a long match, only update tables a limited amount). */
  224. static void ZSTD_ldm_limitTableUpdate(ZSTD_matchState_t* ms, const BYTE* anchor)
  225. {
  226. U32 const current = (U32)(anchor - ms->window.base);
  227. if (current > ms->nextToUpdate + 1024) {
  228. ms->nextToUpdate =
  229. current - MIN(512, current - ms->nextToUpdate - 1024);
  230. }
  231. }
  232. static size_t ZSTD_ldm_generateSequences_internal(
  233. ldmState_t* ldmState, rawSeqStore_t* rawSeqStore,
  234. ldmParams_t const* params, void const* src, size_t srcSize)
  235. {
  236. /* LDM parameters */
  237. int const extDict = ZSTD_window_hasExtDict(ldmState->window);
  238. U32 const minMatchLength = params->minMatchLength;
  239. U64 const hashPower = ldmState->hashPower;
  240. U32 const hBits = params->hashLog - params->bucketSizeLog;
  241. U32 const ldmBucketSize = 1U << params->bucketSizeLog;
  242. U32 const hashRateLog = params->hashRateLog;
  243. U32 const ldmTagMask = (1U << params->hashRateLog) - 1;
  244. /* Prefix and extDict parameters */
  245. U32 const dictLimit = ldmState->window.dictLimit;
  246. U32 const lowestIndex = extDict ? ldmState->window.lowLimit : dictLimit;
  247. BYTE const* const base = ldmState->window.base;
  248. BYTE const* const dictBase = extDict ? ldmState->window.dictBase : NULL;
  249. BYTE const* const dictStart = extDict ? dictBase + lowestIndex : NULL;
  250. BYTE const* const dictEnd = extDict ? dictBase + dictLimit : NULL;
  251. BYTE const* const lowPrefixPtr = base + dictLimit;
  252. /* Input bounds */
  253. BYTE const* const istart = (BYTE const*)src;
  254. BYTE const* const iend = istart + srcSize;
  255. BYTE const* const ilimit = iend - MAX(minMatchLength, HASH_READ_SIZE);
  256. /* Input positions */
  257. BYTE const* anchor = istart;
  258. BYTE const* ip = istart;
  259. /* Rolling hash */
  260. BYTE const* lastHashed = NULL;
  261. U64 rollingHash = 0;
  262. while (ip <= ilimit) {
  263. size_t mLength;
  264. U32 const current = (U32)(ip - base);
  265. size_t forwardMatchLength = 0, backwardMatchLength = 0;
  266. ldmEntry_t* bestEntry = NULL;
  267. if (ip != istart) {
  268. rollingHash = ZSTD_rollingHash_rotate(rollingHash, lastHashed[0],
  269. lastHashed[minMatchLength],
  270. hashPower);
  271. } else {
  272. rollingHash = ZSTD_rollingHash_compute(ip, minMatchLength);
  273. }
  274. lastHashed = ip;
  275. /* Do not insert and do not look for a match */
  276. if (ZSTD_ldm_getTag(rollingHash, hBits, hashRateLog) != ldmTagMask) {
  277. ip++;
  278. continue;
  279. }
  280. /* Get the best entry and compute the match lengths */
  281. {
  282. ldmEntry_t* const bucket =
  283. ZSTD_ldm_getBucket(ldmState,
  284. ZSTD_ldm_getSmallHash(rollingHash, hBits),
  285. *params);
  286. ldmEntry_t* cur;
  287. size_t bestMatchLength = 0;
  288. U32 const checksum = ZSTD_ldm_getChecksum(rollingHash, hBits);
  289. for (cur = bucket; cur < bucket + ldmBucketSize; ++cur) {
  290. size_t curForwardMatchLength, curBackwardMatchLength,
  291. curTotalMatchLength;
  292. if (cur->checksum != checksum || cur->offset <= lowestIndex) {
  293. continue;
  294. }
  295. if (extDict) {
  296. BYTE const* const curMatchBase =
  297. cur->offset < dictLimit ? dictBase : base;
  298. BYTE const* const pMatch = curMatchBase + cur->offset;
  299. BYTE const* const matchEnd =
  300. cur->offset < dictLimit ? dictEnd : iend;
  301. BYTE const* const lowMatchPtr =
  302. cur->offset < dictLimit ? dictStart : lowPrefixPtr;
  303. curForwardMatchLength = ZSTD_count_2segments(
  304. ip, pMatch, iend,
  305. matchEnd, lowPrefixPtr);
  306. if (curForwardMatchLength < minMatchLength) {
  307. continue;
  308. }
  309. curBackwardMatchLength =
  310. ZSTD_ldm_countBackwardsMatch(ip, anchor, pMatch,
  311. lowMatchPtr);
  312. curTotalMatchLength = curForwardMatchLength +
  313. curBackwardMatchLength;
  314. } else { /* !extDict */
  315. BYTE const* const pMatch = base + cur->offset;
  316. curForwardMatchLength = ZSTD_count(ip, pMatch, iend);
  317. if (curForwardMatchLength < minMatchLength) {
  318. continue;
  319. }
  320. curBackwardMatchLength =
  321. ZSTD_ldm_countBackwardsMatch(ip, anchor, pMatch,
  322. lowPrefixPtr);
  323. curTotalMatchLength = curForwardMatchLength +
  324. curBackwardMatchLength;
  325. }
  326. if (curTotalMatchLength > bestMatchLength) {
  327. bestMatchLength = curTotalMatchLength;
  328. forwardMatchLength = curForwardMatchLength;
  329. backwardMatchLength = curBackwardMatchLength;
  330. bestEntry = cur;
  331. }
  332. }
  333. }
  334. /* No match found -- continue searching */
  335. if (bestEntry == NULL) {
  336. ZSTD_ldm_makeEntryAndInsertByTag(ldmState, rollingHash,
  337. hBits, current,
  338. *params);
  339. ip++;
  340. continue;
  341. }
  342. /* Match found */
  343. mLength = forwardMatchLength + backwardMatchLength;
  344. ip -= backwardMatchLength;
  345. {
  346. /* Store the sequence:
  347. * ip = current - backwardMatchLength
  348. * The match is at (bestEntry->offset - backwardMatchLength)
  349. */
  350. U32 const matchIndex = bestEntry->offset;
  351. U32 const offset = current - matchIndex;
  352. rawSeq* const seq = rawSeqStore->seq + rawSeqStore->size;
  353. /* Out of sequence storage */
  354. if (rawSeqStore->size == rawSeqStore->capacity)
  355. return ERROR(dstSize_tooSmall);
  356. seq->litLength = (U32)(ip - anchor);
  357. seq->matchLength = (U32)mLength;
  358. seq->offset = offset;
  359. rawSeqStore->size++;
  360. }
  361. /* Insert the current entry into the hash table */
  362. ZSTD_ldm_makeEntryAndInsertByTag(ldmState, rollingHash, hBits,
  363. (U32)(lastHashed - base),
  364. *params);
  365. assert(ip + backwardMatchLength == lastHashed);
  366. /* Fill the hash table from lastHashed+1 to ip+mLength*/
  367. /* Heuristic: don't need to fill the entire table at end of block */
  368. if (ip + mLength <= ilimit) {
  369. rollingHash = ZSTD_ldm_fillLdmHashTable(
  370. ldmState, rollingHash, lastHashed,
  371. ip + mLength, base, hBits, *params);
  372. lastHashed = ip + mLength - 1;
  373. }
  374. ip += mLength;
  375. anchor = ip;
  376. }
  377. return iend - anchor;
  378. }
  379. /*! ZSTD_ldm_reduceTable() :
  380. * reduce table indexes by `reducerValue` */
  381. static void ZSTD_ldm_reduceTable(ldmEntry_t* const table, U32 const size,
  382. U32 const reducerValue)
  383. {
  384. U32 u;
  385. for (u = 0; u < size; u++) {
  386. if (table[u].offset < reducerValue) table[u].offset = 0;
  387. else table[u].offset -= reducerValue;
  388. }
  389. }
  390. size_t ZSTD_ldm_generateSequences(
  391. ldmState_t* ldmState, rawSeqStore_t* sequences,
  392. ldmParams_t const* params, void const* src, size_t srcSize)
  393. {
  394. U32 const maxDist = 1U << params->windowLog;
  395. BYTE const* const istart = (BYTE const*)src;
  396. BYTE const* const iend = istart + srcSize;
  397. size_t const kMaxChunkSize = 1 << 20;
  398. size_t const nbChunks = (srcSize / kMaxChunkSize) + ((srcSize % kMaxChunkSize) != 0);
  399. size_t chunk;
  400. size_t leftoverSize = 0;
  401. assert(ZSTD_CHUNKSIZE_MAX >= kMaxChunkSize);
  402. /* Check that ZSTD_window_update() has been called for this chunk prior
  403. * to passing it to this function.
  404. */
  405. assert(ldmState->window.nextSrc >= (BYTE const*)src + srcSize);
  406. /* The input could be very large (in zstdmt), so it must be broken up into
  407. * chunks to enforce the maximum distance and handle overflow correction.
  408. */
  409. assert(sequences->pos <= sequences->size);
  410. assert(sequences->size <= sequences->capacity);
  411. for (chunk = 0; chunk < nbChunks && sequences->size < sequences->capacity; ++chunk) {
  412. BYTE const* const chunkStart = istart + chunk * kMaxChunkSize;
  413. size_t const remaining = (size_t)(iend - chunkStart);
  414. BYTE const *const chunkEnd =
  415. (remaining < kMaxChunkSize) ? iend : chunkStart + kMaxChunkSize;
  416. size_t const chunkSize = chunkEnd - chunkStart;
  417. size_t newLeftoverSize;
  418. size_t const prevSize = sequences->size;
  419. assert(chunkStart < iend);
  420. /* 1. Perform overflow correction if necessary. */
  421. if (ZSTD_window_needOverflowCorrection(ldmState->window, chunkEnd)) {
  422. U32 const ldmHSize = 1U << params->hashLog;
  423. U32 const correction = ZSTD_window_correctOverflow(
  424. &ldmState->window, /* cycleLog */ 0, maxDist, chunkStart);
  425. ZSTD_ldm_reduceTable(ldmState->hashTable, ldmHSize, correction);
  426. /* invalidate dictionaries on overflow correction */
  427. ldmState->loadedDictEnd = 0;
  428. }
  429. /* 2. We enforce the maximum offset allowed.
  430. *
  431. * kMaxChunkSize should be small enough that we don't lose too much of
  432. * the window through early invalidation.
  433. * TODO: * Test the chunk size.
  434. * * Try invalidation after the sequence generation and test the
  435. * the offset against maxDist directly.
  436. *
  437. * NOTE: Because of dictionaries + sequence splitting we MUST make sure
  438. * that any offset used is valid at the END of the sequence, since it may
  439. * be split into two sequences. This condition holds when using
  440. * ZSTD_window_enforceMaxDist(), but if we move to checking offsets
  441. * against maxDist directly, we'll have to carefully handle that case.
  442. */
  443. ZSTD_window_enforceMaxDist(&ldmState->window, chunkEnd, maxDist, &ldmState->loadedDictEnd, NULL);
  444. /* 3. Generate the sequences for the chunk, and get newLeftoverSize. */
  445. newLeftoverSize = ZSTD_ldm_generateSequences_internal(
  446. ldmState, sequences, params, chunkStart, chunkSize);
  447. if (ZSTD_isError(newLeftoverSize))
  448. return newLeftoverSize;
  449. /* 4. We add the leftover literals from previous iterations to the first
  450. * newly generated sequence, or add the `newLeftoverSize` if none are
  451. * generated.
  452. */
  453. /* Prepend the leftover literals from the last call */
  454. if (prevSize < sequences->size) {
  455. sequences->seq[prevSize].litLength += (U32)leftoverSize;
  456. leftoverSize = newLeftoverSize;
  457. } else {
  458. assert(newLeftoverSize == chunkSize);
  459. leftoverSize += chunkSize;
  460. }
  461. }
  462. return 0;
  463. }
  464. void ZSTD_ldm_skipSequences(rawSeqStore_t* rawSeqStore, size_t srcSize, U32 const minMatch) {
  465. while (srcSize > 0 && rawSeqStore->pos < rawSeqStore->size) {
  466. rawSeq* seq = rawSeqStore->seq + rawSeqStore->pos;
  467. if (srcSize <= seq->litLength) {
  468. /* Skip past srcSize literals */
  469. seq->litLength -= (U32)srcSize;
  470. return;
  471. }
  472. srcSize -= seq->litLength;
  473. seq->litLength = 0;
  474. if (srcSize < seq->matchLength) {
  475. /* Skip past the first srcSize of the match */
  476. seq->matchLength -= (U32)srcSize;
  477. if (seq->matchLength < minMatch) {
  478. /* The match is too short, omit it */
  479. if (rawSeqStore->pos + 1 < rawSeqStore->size) {
  480. seq[1].litLength += seq[0].matchLength;
  481. }
  482. rawSeqStore->pos++;
  483. }
  484. return;
  485. }
  486. srcSize -= seq->matchLength;
  487. seq->matchLength = 0;
  488. rawSeqStore->pos++;
  489. }
  490. }
  491. /**
  492. * If the sequence length is longer than remaining then the sequence is split
  493. * between this block and the next.
  494. *
  495. * Returns the current sequence to handle, or if the rest of the block should
  496. * be literals, it returns a sequence with offset == 0.
  497. */
  498. static rawSeq maybeSplitSequence(rawSeqStore_t* rawSeqStore,
  499. U32 const remaining, U32 const minMatch)
  500. {
  501. rawSeq sequence = rawSeqStore->seq[rawSeqStore->pos];
  502. assert(sequence.offset > 0);
  503. /* Likely: No partial sequence */
  504. if (remaining >= sequence.litLength + sequence.matchLength) {
  505. rawSeqStore->pos++;
  506. return sequence;
  507. }
  508. /* Cut the sequence short (offset == 0 ==> rest is literals). */
  509. if (remaining <= sequence.litLength) {
  510. sequence.offset = 0;
  511. } else if (remaining < sequence.litLength + sequence.matchLength) {
  512. sequence.matchLength = remaining - sequence.litLength;
  513. if (sequence.matchLength < minMatch) {
  514. sequence.offset = 0;
  515. }
  516. }
  517. /* Skip past `remaining` bytes for the future sequences. */
  518. ZSTD_ldm_skipSequences(rawSeqStore, remaining, minMatch);
  519. return sequence;
  520. }
  521. size_t ZSTD_ldm_blockCompress(rawSeqStore_t* rawSeqStore,
  522. ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
  523. void const* src, size_t srcSize)
  524. {
  525. const ZSTD_compressionParameters* const cParams = &ms->cParams;
  526. unsigned const minMatch = cParams->minMatch;
  527. ZSTD_blockCompressor const blockCompressor =
  528. ZSTD_selectBlockCompressor(cParams->strategy, ZSTD_matchState_dictMode(ms));
  529. /* Input bounds */
  530. BYTE const* const istart = (BYTE const*)src;
  531. BYTE const* const iend = istart + srcSize;
  532. /* Input positions */
  533. BYTE const* ip = istart;
  534. DEBUGLOG(5, "ZSTD_ldm_blockCompress: srcSize=%zu", srcSize);
  535. assert(rawSeqStore->pos <= rawSeqStore->size);
  536. assert(rawSeqStore->size <= rawSeqStore->capacity);
  537. /* Loop through each sequence and apply the block compressor to the lits */
  538. while (rawSeqStore->pos < rawSeqStore->size && ip < iend) {
  539. /* maybeSplitSequence updates rawSeqStore->pos */
  540. rawSeq const sequence = maybeSplitSequence(rawSeqStore,
  541. (U32)(iend - ip), minMatch);
  542. int i;
  543. /* End signal */
  544. if (sequence.offset == 0)
  545. break;
  546. assert(ip + sequence.litLength + sequence.matchLength <= iend);
  547. /* Fill tables for block compressor */
  548. ZSTD_ldm_limitTableUpdate(ms, ip);
  549. ZSTD_ldm_fillFastTables(ms, ip);
  550. /* Run the block compressor */
  551. DEBUGLOG(5, "pos %u : calling block compressor on segment of size %u", (unsigned)(ip-istart), sequence.litLength);
  552. {
  553. size_t const newLitLength =
  554. blockCompressor(ms, seqStore, rep, ip, sequence.litLength);
  555. ip += sequence.litLength;
  556. /* Update the repcodes */
  557. for (i = ZSTD_REP_NUM - 1; i > 0; i--)
  558. rep[i] = rep[i-1];
  559. rep[0] = sequence.offset;
  560. /* Store the sequence */
  561. ZSTD_storeSeq(seqStore, newLitLength, ip - newLitLength, iend,
  562. sequence.offset + ZSTD_REP_MOVE,
  563. sequence.matchLength - MINMATCH);
  564. ip += sequence.matchLength;
  565. }
  566. }
  567. /* Fill the tables for the block compressor */
  568. ZSTD_ldm_limitTableUpdate(ms, ip);
  569. ZSTD_ldm_fillFastTables(ms, ip);
  570. /* Compress the last literals */
  571. return blockCompressor(ms, seqStore, rep, ip, iend - ip);
  572. }