lz4hc.c 65 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538
  1. /*
  2. LZ4 HC - High Compression Mode of LZ4
  3. Copyright (C) 2011-2017, Yann Collet.
  4. BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
  5. Redistribution and use in source and binary forms, with or without
  6. modification, are permitted provided that the following conditions are
  7. met:
  8. * Redistributions of source code must retain the above copyright
  9. notice, this list of conditions and the following disclaimer.
  10. * Redistributions in binary form must reproduce the above
  11. copyright notice, this list of conditions and the following disclaimer
  12. in the documentation and/or other materials provided with the
  13. distribution.
  14. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  15. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  16. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  17. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  18. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  19. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  20. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  21. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  22. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  23. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. You can contact the author at :
  26. - LZ4 source repository : https://github.com/lz4/lz4
  27. - LZ4 public forum : https://groups.google.com/forum/#!forum/lz4c
  28. */
  29. /* note : lz4hc is not an independent module, it requires lz4.h/lz4.c for proper compilation */
  30. /* *************************************
  31. * Tuning Parameter
  32. ***************************************/
  33. /*! HEAPMODE :
  34. * Select how default compression function will allocate workplace memory,
  35. * in stack (0:fastest), or in heap (1:requires malloc()).
  36. * Since workplace is rather large, heap mode is recommended.
  37. */
  38. #ifndef LZ4HC_HEAPMODE
  39. # define LZ4HC_HEAPMODE 1
  40. #endif
  41. /*=== Dependency ===*/
  42. #define LZ4_HC_STATIC_LINKING_ONLY
  43. #include "lz4hc.h"
  44. /*=== Common LZ4 definitions ===*/
  45. #if defined(__GNUC__)
  46. # pragma GCC diagnostic ignored "-Wunused-function"
  47. #endif
  48. #if defined (__clang__)
  49. # pragma clang diagnostic ignored "-Wunused-function"
  50. #endif
  51. /*=== Enums ===*/
  52. typedef enum { noDictCtx, usingDictCtxHc } dictCtx_directive;
  53. #define LZ4_COMMONDEFS_ONLY
  54. #ifndef LZ4_SRC_INCLUDED
  55. #include "lz4.c" /* LZ4_count, constants, mem */
  56. #endif
  57. /*=== Constants ===*/
  58. #define OPTIMAL_ML (int)((ML_MASK-1)+MINMATCH)
  59. #define LZ4_OPT_NUM (1<<12)
  60. /*=== Macros ===*/
  61. #define MIN(a,b) ( (a) < (b) ? (a) : (b) )
  62. #define MAX(a,b) ( (a) > (b) ? (a) : (b) )
  63. #define HASH_FUNCTION(i) (((i) * 2654435761U) >> ((MINMATCH*8)-LZ4HC_HASH_LOG))
  64. #define DELTANEXTMAXD(p) chainTable[(p) & LZ4HC_MAXD_MASK] /* flexible, LZ4HC_MAXD dependent */
  65. #define DELTANEXTU16(table, pos) table[(U16)(pos)] /* faster */
  66. /* Make fields passed to, and updated by LZ4HC_encodeSequence explicit */
  67. #define UPDATABLE(ip, op, anchor) &ip, &op, &anchor
  68. static U32 LZ4HC_hashPtr(const void* ptr) { return HASH_FUNCTION(LZ4_read32(ptr)); }
  69. /**************************************
  70. * HC Compression
  71. **************************************/
  72. static void LZ4HC_clearTables (LZ4HC_CCtx_internal* hc4)
  73. {
  74. MEM_INIT((void*)hc4->hashTable, 0, sizeof(hc4->hashTable));
  75. MEM_INIT(hc4->chainTable, 0xFF, sizeof(hc4->chainTable));
  76. }
  77. static void LZ4HC_init_internal (LZ4HC_CCtx_internal* hc4, const BYTE* start)
  78. {
  79. uptrval startingOffset = (uptrval)(hc4->end - hc4->base);
  80. if (startingOffset > 1 GB) {
  81. LZ4HC_clearTables(hc4);
  82. startingOffset = 0;
  83. }
  84. startingOffset += 64 KB;
  85. hc4->nextToUpdate = (U32) startingOffset;
  86. hc4->base = start - startingOffset;
  87. hc4->end = start;
  88. hc4->dictBase = start - startingOffset;
  89. hc4->dictLimit = (U32) startingOffset;
  90. hc4->lowLimit = (U32) startingOffset;
  91. }
  92. /* Update chains up to ip (excluded) */
  93. LZ4_FORCE_INLINE void LZ4HC_Insert (LZ4HC_CCtx_internal* hc4, const BYTE* ip)
  94. {
  95. U16* const chainTable = hc4->chainTable;
  96. U32* const hashTable = hc4->hashTable;
  97. const BYTE* const base = hc4->base;
  98. U32 const target = (U32)(ip - base);
  99. U32 idx = hc4->nextToUpdate;
  100. while (idx < target) {
  101. U32 const h = LZ4HC_hashPtr(base+idx);
  102. size_t delta = idx - hashTable[h];
  103. if (delta>LZ4_DISTANCE_MAX) delta = LZ4_DISTANCE_MAX;
  104. DELTANEXTU16(chainTable, idx) = (U16)delta;
  105. hashTable[h] = idx;
  106. idx++;
  107. }
  108. hc4->nextToUpdate = target;
  109. }
  110. /** LZ4HC_countBack() :
  111. * @return : negative value, nb of common bytes before ip/match */
  112. LZ4_FORCE_INLINE
  113. int LZ4HC_countBack(const BYTE* const ip, const BYTE* const match,
  114. const BYTE* const iMin, const BYTE* const mMin)
  115. {
  116. int back = 0;
  117. int const min = (int)MAX(iMin - ip, mMin - match);
  118. assert(min <= 0);
  119. assert(ip >= iMin); assert((size_t)(ip-iMin) < (1U<<31));
  120. assert(match >= mMin); assert((size_t)(match - mMin) < (1U<<31));
  121. while ( (back > min)
  122. && (ip[back-1] == match[back-1]) )
  123. back--;
  124. return back;
  125. }
  126. #if defined(_MSC_VER)
  127. # define LZ4HC_rotl32(x,r) _rotl(x,r)
  128. #else
  129. # define LZ4HC_rotl32(x,r) ((x << r) | (x >> (32 - r)))
  130. #endif
  131. static U32 LZ4HC_rotatePattern(size_t const rotate, U32 const pattern)
  132. {
  133. size_t const bitsToRotate = (rotate & (sizeof(pattern) - 1)) << 3;
  134. if (bitsToRotate == 0)
  135. return pattern;
  136. return LZ4HC_rotl32(pattern, (int)bitsToRotate);
  137. }
  138. /* LZ4HC_countPattern() :
  139. * pattern32 must be a sample of repetitive pattern of length 1, 2 or 4 (but not 3!) */
  140. static unsigned
  141. LZ4HC_countPattern(const BYTE* ip, const BYTE* const iEnd, U32 const pattern32)
  142. {
  143. const BYTE* const iStart = ip;
  144. reg_t const pattern = (sizeof(pattern)==8) ? (reg_t)pattern32 + (((reg_t)pattern32) << 32) : pattern32;
  145. while (likely(ip < iEnd-(sizeof(pattern)-1))) {
  146. reg_t const diff = LZ4_read_ARCH(ip) ^ pattern;
  147. if (!diff) { ip+=sizeof(pattern); continue; }
  148. ip += LZ4_NbCommonBytes(diff);
  149. return (unsigned)(ip - iStart);
  150. }
  151. if (LZ4_isLittleEndian()) {
  152. reg_t patternByte = pattern;
  153. while ((ip<iEnd) && (*ip == (BYTE)patternByte)) {
  154. ip++; patternByte >>= 8;
  155. }
  156. } else { /* big endian */
  157. U32 bitOffset = (sizeof(pattern)*8) - 8;
  158. while (ip < iEnd) {
  159. BYTE const byte = (BYTE)(pattern >> bitOffset);
  160. if (*ip != byte) break;
  161. ip ++; bitOffset -= 8;
  162. }
  163. }
  164. return (unsigned)(ip - iStart);
  165. }
  166. /* LZ4HC_reverseCountPattern() :
  167. * pattern must be a sample of repetitive pattern of length 1, 2 or 4 (but not 3!)
  168. * read using natural platform endianess */
  169. static unsigned
  170. LZ4HC_reverseCountPattern(const BYTE* ip, const BYTE* const iLow, U32 pattern)
  171. {
  172. const BYTE* const iStart = ip;
  173. while (likely(ip >= iLow+4)) {
  174. if (LZ4_read32(ip-4) != pattern) break;
  175. ip -= 4;
  176. }
  177. { const BYTE* bytePtr = (const BYTE*)(&pattern) + 3; /* works for any endianess */
  178. while (likely(ip>iLow)) {
  179. if (ip[-1] != *bytePtr) break;
  180. ip--; bytePtr--;
  181. } }
  182. return (unsigned)(iStart - ip);
  183. }
  184. /* LZ4HC_protectDictEnd() :
  185. * Checks if the match is in the last 3 bytes of the dictionary, so reading the
  186. * 4 byte MINMATCH would overflow.
  187. * @returns true if the match index is okay.
  188. */
  189. static int LZ4HC_protectDictEnd(U32 const dictLimit, U32 const matchIndex)
  190. {
  191. return ((U32)((dictLimit - 1) - matchIndex) >= 3);
  192. }
  193. typedef enum { rep_untested, rep_not, rep_confirmed } repeat_state_e;
  194. typedef enum { favorCompressionRatio=0, favorDecompressionSpeed } HCfavor_e;
  195. LZ4_FORCE_INLINE int
  196. LZ4HC_InsertAndGetWiderMatch (
  197. LZ4HC_CCtx_internal* hc4,
  198. const BYTE* const ip,
  199. const BYTE* const iLowLimit,
  200. const BYTE* const iHighLimit,
  201. int longest,
  202. const BYTE** matchpos,
  203. const BYTE** startpos,
  204. const int maxNbAttempts,
  205. const int patternAnalysis,
  206. const int chainSwap,
  207. const dictCtx_directive dict,
  208. const HCfavor_e favorDecSpeed)
  209. {
  210. U16* const chainTable = hc4->chainTable;
  211. U32* const HashTable = hc4->hashTable;
  212. const LZ4HC_CCtx_internal * const dictCtx = hc4->dictCtx;
  213. const BYTE* const base = hc4->base;
  214. const U32 dictLimit = hc4->dictLimit;
  215. const BYTE* const lowPrefixPtr = base + dictLimit;
  216. const U32 ipIndex = (U32)(ip - base);
  217. const U32 lowestMatchIndex = (hc4->lowLimit + (LZ4_DISTANCE_MAX + 1) > ipIndex) ? hc4->lowLimit : ipIndex - LZ4_DISTANCE_MAX;
  218. const BYTE* const dictBase = hc4->dictBase;
  219. int const lookBackLength = (int)(ip-iLowLimit);
  220. int nbAttempts = maxNbAttempts;
  221. U32 matchChainPos = 0;
  222. U32 const pattern = LZ4_read32(ip);
  223. U32 matchIndex;
  224. repeat_state_e repeat = rep_untested;
  225. size_t srcPatternLength = 0;
  226. DEBUGLOG(7, "LZ4HC_InsertAndGetWiderMatch");
  227. /* First Match */
  228. LZ4HC_Insert(hc4, ip);
  229. matchIndex = HashTable[LZ4HC_hashPtr(ip)];
  230. DEBUGLOG(7, "First match at index %u / %u (lowestMatchIndex)",
  231. matchIndex, lowestMatchIndex);
  232. while ((matchIndex>=lowestMatchIndex) && (nbAttempts)) {
  233. int matchLength=0;
  234. nbAttempts--;
  235. assert(matchIndex < ipIndex);
  236. if (favorDecSpeed && (ipIndex - matchIndex < 8)) {
  237. /* do nothing */
  238. } else if (matchIndex >= dictLimit) { /* within current Prefix */
  239. const BYTE* const matchPtr = base + matchIndex;
  240. assert(matchPtr >= lowPrefixPtr);
  241. assert(matchPtr < ip);
  242. assert(longest >= 1);
  243. if (LZ4_read16(iLowLimit + longest - 1) == LZ4_read16(matchPtr - lookBackLength + longest - 1)) {
  244. if (LZ4_read32(matchPtr) == pattern) {
  245. int const back = lookBackLength ? LZ4HC_countBack(ip, matchPtr, iLowLimit, lowPrefixPtr) : 0;
  246. matchLength = MINMATCH + (int)LZ4_count(ip+MINMATCH, matchPtr+MINMATCH, iHighLimit);
  247. matchLength -= back;
  248. if (matchLength > longest) {
  249. longest = matchLength;
  250. *matchpos = matchPtr + back;
  251. *startpos = ip + back;
  252. } } }
  253. } else { /* lowestMatchIndex <= matchIndex < dictLimit */
  254. const BYTE* const matchPtr = dictBase + matchIndex;
  255. if (LZ4_read32(matchPtr) == pattern) {
  256. const BYTE* const dictStart = dictBase + hc4->lowLimit;
  257. int back = 0;
  258. const BYTE* vLimit = ip + (dictLimit - matchIndex);
  259. if (vLimit > iHighLimit) vLimit = iHighLimit;
  260. matchLength = (int)LZ4_count(ip+MINMATCH, matchPtr+MINMATCH, vLimit) + MINMATCH;
  261. if ((ip+matchLength == vLimit) && (vLimit < iHighLimit))
  262. matchLength += LZ4_count(ip+matchLength, lowPrefixPtr, iHighLimit);
  263. back = lookBackLength ? LZ4HC_countBack(ip, matchPtr, iLowLimit, dictStart) : 0;
  264. matchLength -= back;
  265. if (matchLength > longest) {
  266. longest = matchLength;
  267. *matchpos = base + matchIndex + back; /* virtual pos, relative to ip, to retrieve offset */
  268. *startpos = ip + back;
  269. } } }
  270. if (chainSwap && matchLength==longest) { /* better match => select a better chain */
  271. assert(lookBackLength==0); /* search forward only */
  272. if (matchIndex + (U32)longest <= ipIndex) {
  273. int const kTrigger = 4;
  274. U32 distanceToNextMatch = 1;
  275. int const end = longest - MINMATCH + 1;
  276. int step = 1;
  277. int accel = 1 << kTrigger;
  278. int pos;
  279. for (pos = 0; pos < end; pos += step) {
  280. U32 const candidateDist = DELTANEXTU16(chainTable, matchIndex + (U32)pos);
  281. step = (accel++ >> kTrigger);
  282. if (candidateDist > distanceToNextMatch) {
  283. distanceToNextMatch = candidateDist;
  284. matchChainPos = (U32)pos;
  285. accel = 1 << kTrigger;
  286. }
  287. }
  288. if (distanceToNextMatch > 1) {
  289. if (distanceToNextMatch > matchIndex) break; /* avoid overflow */
  290. matchIndex -= distanceToNextMatch;
  291. continue;
  292. } } }
  293. { U32 const distNextMatch = DELTANEXTU16(chainTable, matchIndex);
  294. if (patternAnalysis && distNextMatch==1 && matchChainPos==0) {
  295. U32 const matchCandidateIdx = matchIndex-1;
  296. /* may be a repeated pattern */
  297. if (repeat == rep_untested) {
  298. if ( ((pattern & 0xFFFF) == (pattern >> 16))
  299. & ((pattern & 0xFF) == (pattern >> 24)) ) {
  300. repeat = rep_confirmed;
  301. srcPatternLength = LZ4HC_countPattern(ip+sizeof(pattern), iHighLimit, pattern) + sizeof(pattern);
  302. } else {
  303. repeat = rep_not;
  304. } }
  305. if ( (repeat == rep_confirmed) && (matchCandidateIdx >= lowestMatchIndex)
  306. && LZ4HC_protectDictEnd(dictLimit, matchCandidateIdx) ) {
  307. const int extDict = matchCandidateIdx < dictLimit;
  308. const BYTE* const matchPtr = (extDict ? dictBase : base) + matchCandidateIdx;
  309. if (LZ4_read32(matchPtr) == pattern) { /* good candidate */
  310. const BYTE* const dictStart = dictBase + hc4->lowLimit;
  311. const BYTE* const iLimit = extDict ? dictBase + dictLimit : iHighLimit;
  312. size_t forwardPatternLength = LZ4HC_countPattern(matchPtr+sizeof(pattern), iLimit, pattern) + sizeof(pattern);
  313. if (extDict && matchPtr + forwardPatternLength == iLimit) {
  314. U32 const rotatedPattern = LZ4HC_rotatePattern(forwardPatternLength, pattern);
  315. forwardPatternLength += LZ4HC_countPattern(lowPrefixPtr, iHighLimit, rotatedPattern);
  316. }
  317. { const BYTE* const lowestMatchPtr = extDict ? dictStart : lowPrefixPtr;
  318. size_t backLength = LZ4HC_reverseCountPattern(matchPtr, lowestMatchPtr, pattern);
  319. size_t currentSegmentLength;
  320. if (!extDict && matchPtr - backLength == lowPrefixPtr && hc4->lowLimit < dictLimit) {
  321. U32 const rotatedPattern = LZ4HC_rotatePattern((U32)(-(int)backLength), pattern);
  322. backLength += LZ4HC_reverseCountPattern(dictBase + dictLimit, dictStart, rotatedPattern);
  323. }
  324. /* Limit backLength not go further than lowestMatchIndex */
  325. backLength = matchCandidateIdx - MAX(matchCandidateIdx - (U32)backLength, lowestMatchIndex);
  326. assert(matchCandidateIdx - backLength >= lowestMatchIndex);
  327. currentSegmentLength = backLength + forwardPatternLength;
  328. /* Adjust to end of pattern if the source pattern fits, otherwise the beginning of the pattern */
  329. if ( (currentSegmentLength >= srcPatternLength) /* current pattern segment large enough to contain full srcPatternLength */
  330. && (forwardPatternLength <= srcPatternLength) ) { /* haven't reached this position yet */
  331. U32 const newMatchIndex = matchCandidateIdx + (U32)forwardPatternLength - (U32)srcPatternLength; /* best position, full pattern, might be followed by more match */
  332. if (LZ4HC_protectDictEnd(dictLimit, newMatchIndex))
  333. matchIndex = newMatchIndex;
  334. else {
  335. /* Can only happen if started in the prefix */
  336. assert(newMatchIndex >= dictLimit - 3 && newMatchIndex < dictLimit && !extDict);
  337. matchIndex = dictLimit;
  338. }
  339. } else {
  340. U32 const newMatchIndex = matchCandidateIdx - (U32)backLength; /* farthest position in current segment, will find a match of length currentSegmentLength + maybe some back */
  341. if (!LZ4HC_protectDictEnd(dictLimit, newMatchIndex)) {
  342. assert(newMatchIndex >= dictLimit - 3 && newMatchIndex < dictLimit && !extDict);
  343. matchIndex = dictLimit;
  344. } else {
  345. matchIndex = newMatchIndex;
  346. if (lookBackLength==0) { /* no back possible */
  347. size_t const maxML = MIN(currentSegmentLength, srcPatternLength);
  348. if ((size_t)longest < maxML) {
  349. assert(base + matchIndex < ip);
  350. if (ip - (base+matchIndex) > LZ4_DISTANCE_MAX) break;
  351. assert(maxML < 2 GB);
  352. longest = (int)maxML;
  353. *matchpos = base + matchIndex; /* virtual pos, relative to ip, to retrieve offset */
  354. *startpos = ip;
  355. }
  356. { U32 const distToNextPattern = DELTANEXTU16(chainTable, matchIndex);
  357. if (distToNextPattern > matchIndex) break; /* avoid overflow */
  358. matchIndex -= distToNextPattern;
  359. } } } } }
  360. continue;
  361. } }
  362. } } /* PA optimization */
  363. /* follow current chain */
  364. matchIndex -= DELTANEXTU16(chainTable, matchIndex + matchChainPos);
  365. } /* while ((matchIndex>=lowestMatchIndex) && (nbAttempts)) */
  366. if ( dict == usingDictCtxHc
  367. && nbAttempts
  368. && ipIndex - lowestMatchIndex < LZ4_DISTANCE_MAX) {
  369. size_t const dictEndOffset = (size_t)(dictCtx->end - dictCtx->base);
  370. U32 dictMatchIndex = dictCtx->hashTable[LZ4HC_hashPtr(ip)];
  371. assert(dictEndOffset <= 1 GB);
  372. matchIndex = dictMatchIndex + lowestMatchIndex - (U32)dictEndOffset;
  373. while (ipIndex - matchIndex <= LZ4_DISTANCE_MAX && nbAttempts--) {
  374. const BYTE* const matchPtr = dictCtx->base + dictMatchIndex;
  375. if (LZ4_read32(matchPtr) == pattern) {
  376. int mlt;
  377. int back = 0;
  378. const BYTE* vLimit = ip + (dictEndOffset - dictMatchIndex);
  379. if (vLimit > iHighLimit) vLimit = iHighLimit;
  380. mlt = (int)LZ4_count(ip+MINMATCH, matchPtr+MINMATCH, vLimit) + MINMATCH;
  381. back = lookBackLength ? LZ4HC_countBack(ip, matchPtr, iLowLimit, dictCtx->base + dictCtx->dictLimit) : 0;
  382. mlt -= back;
  383. if (mlt > longest) {
  384. longest = mlt;
  385. *matchpos = base + matchIndex + back;
  386. *startpos = ip + back;
  387. } }
  388. { U32 const nextOffset = DELTANEXTU16(dictCtx->chainTable, dictMatchIndex);
  389. dictMatchIndex -= nextOffset;
  390. matchIndex -= nextOffset;
  391. } } }
  392. return longest;
  393. }
  394. LZ4_FORCE_INLINE
  395. int LZ4HC_InsertAndFindBestMatch(LZ4HC_CCtx_internal* const hc4, /* Index table will be updated */
  396. const BYTE* const ip, const BYTE* const iLimit,
  397. const BYTE** matchpos,
  398. const int maxNbAttempts,
  399. const int patternAnalysis,
  400. const dictCtx_directive dict)
  401. {
  402. const BYTE* uselessPtr = ip;
  403. /* note : LZ4HC_InsertAndGetWiderMatch() is able to modify the starting position of a match (*startpos),
  404. * but this won't be the case here, as we define iLowLimit==ip,
  405. * so LZ4HC_InsertAndGetWiderMatch() won't be allowed to search past ip */
  406. return LZ4HC_InsertAndGetWiderMatch(hc4, ip, ip, iLimit, MINMATCH-1, matchpos, &uselessPtr, maxNbAttempts, patternAnalysis, 0 /*chainSwap*/, dict, favorCompressionRatio);
  407. }
  408. /* LZ4HC_encodeSequence() :
  409. * @return : 0 if ok,
  410. * 1 if buffer issue detected */
  411. LZ4_FORCE_INLINE int LZ4HC_encodeSequence (
  412. const BYTE** ip,
  413. BYTE** op,
  414. const BYTE** anchor,
  415. int matchLength,
  416. const BYTE* const match,
  417. limitedOutput_directive limit,
  418. BYTE* oend)
  419. {
  420. size_t length;
  421. BYTE* const token = (*op)++;
  422. #if defined(LZ4_DEBUG) && (LZ4_DEBUG >= 6)
  423. static const BYTE* start = NULL;
  424. static U32 totalCost = 0;
  425. U32 const pos = (start==NULL) ? 0 : (U32)(*anchor - start);
  426. U32 const ll = (U32)(*ip - *anchor);
  427. U32 const llAdd = (ll>=15) ? ((ll-15) / 255) + 1 : 0;
  428. U32 const mlAdd = (matchLength>=19) ? ((matchLength-19) / 255) + 1 : 0;
  429. U32 const cost = 1 + llAdd + ll + 2 + mlAdd;
  430. if (start==NULL) start = *anchor; /* only works for single segment */
  431. /* g_debuglog_enable = (pos >= 2228) & (pos <= 2262); */
  432. DEBUGLOG(6, "pos:%7u -- literals:%3u, match:%4i, offset:%5u, cost:%3u + %u",
  433. pos,
  434. (U32)(*ip - *anchor), matchLength, (U32)(*ip-match),
  435. cost, totalCost);
  436. totalCost += cost;
  437. #endif
  438. /* Encode Literal length */
  439. length = (size_t)(*ip - *anchor);
  440. if ((limit) && ((*op + (length / 255) + length + (2 + 1 + LASTLITERALS)) > oend)) return 1; /* Check output limit */
  441. if (length >= RUN_MASK) {
  442. size_t len = length - RUN_MASK;
  443. *token = (RUN_MASK << ML_BITS);
  444. for(; len >= 255 ; len -= 255) *(*op)++ = 255;
  445. *(*op)++ = (BYTE)len;
  446. } else {
  447. *token = (BYTE)(length << ML_BITS);
  448. }
  449. /* Copy Literals */
  450. LZ4_wildCopy8(*op, *anchor, (*op) + length);
  451. *op += length;
  452. /* Encode Offset */
  453. assert( (*ip - match) <= LZ4_DISTANCE_MAX ); /* note : consider providing offset as a value, rather than as a pointer difference */
  454. LZ4_writeLE16(*op, (U16)(*ip-match)); *op += 2;
  455. /* Encode MatchLength */
  456. assert(matchLength >= MINMATCH);
  457. length = (size_t)matchLength - MINMATCH;
  458. if ((limit) && (*op + (length / 255) + (1 + LASTLITERALS) > oend)) return 1; /* Check output limit */
  459. if (length >= ML_MASK) {
  460. *token += ML_MASK;
  461. length -= ML_MASK;
  462. for(; length >= 510 ; length -= 510) { *(*op)++ = 255; *(*op)++ = 255; }
  463. if (length >= 255) { length -= 255; *(*op)++ = 255; }
  464. *(*op)++ = (BYTE)length;
  465. } else {
  466. *token += (BYTE)(length);
  467. }
  468. /* Prepare next loop */
  469. *ip += matchLength;
  470. *anchor = *ip;
  471. return 0;
  472. }
  473. LZ4_FORCE_INLINE int LZ4HC_compress_hashChain (
  474. LZ4HC_CCtx_internal* const ctx,
  475. const char* const source,
  476. char* const dest,
  477. int* srcSizePtr,
  478. int const maxOutputSize,
  479. unsigned maxNbAttempts,
  480. const limitedOutput_directive limit,
  481. const dictCtx_directive dict
  482. )
  483. {
  484. const int inputSize = *srcSizePtr;
  485. const int patternAnalysis = (maxNbAttempts > 128); /* levels 9+ */
  486. const BYTE* ip = (const BYTE*) source;
  487. const BYTE* anchor = ip;
  488. const BYTE* const iend = ip + inputSize;
  489. const BYTE* const mflimit = iend - MFLIMIT;
  490. const BYTE* const matchlimit = (iend - LASTLITERALS);
  491. BYTE* optr = (BYTE*) dest;
  492. BYTE* op = (BYTE*) dest;
  493. BYTE* oend = op + maxOutputSize;
  494. int ml0, ml, ml2, ml3;
  495. const BYTE* start0;
  496. const BYTE* ref0;
  497. const BYTE* ref = NULL;
  498. const BYTE* start2 = NULL;
  499. const BYTE* ref2 = NULL;
  500. const BYTE* start3 = NULL;
  501. const BYTE* ref3 = NULL;
  502. /* init */
  503. *srcSizePtr = 0;
  504. if (limit == fillOutput) oend -= LASTLITERALS; /* Hack for support LZ4 format restriction */
  505. if (inputSize < LZ4_minLength) goto _last_literals; /* Input too small, no compression (all literals) */
  506. /* Main Loop */
  507. while (ip <= mflimit) {
  508. ml = LZ4HC_InsertAndFindBestMatch(ctx, ip, matchlimit, &ref, maxNbAttempts, patternAnalysis, dict);
  509. if (ml<MINMATCH) { ip++; continue; }
  510. /* saved, in case we would skip too much */
  511. start0 = ip; ref0 = ref; ml0 = ml;
  512. _Search2:
  513. if (ip+ml <= mflimit) {
  514. ml2 = LZ4HC_InsertAndGetWiderMatch(ctx,
  515. ip + ml - 2, ip + 0, matchlimit, ml, &ref2, &start2,
  516. maxNbAttempts, patternAnalysis, 0, dict, favorCompressionRatio);
  517. } else {
  518. ml2 = ml;
  519. }
  520. if (ml2 == ml) { /* No better match => encode ML1 */
  521. optr = op;
  522. if (LZ4HC_encodeSequence(UPDATABLE(ip, op, anchor), ml, ref, limit, oend)) goto _dest_overflow;
  523. continue;
  524. }
  525. if (start0 < ip) { /* first match was skipped at least once */
  526. if (start2 < ip + ml0) { /* squeezing ML1 between ML0(original ML1) and ML2 */
  527. ip = start0; ref = ref0; ml = ml0; /* restore initial ML1 */
  528. } }
  529. /* Here, start0==ip */
  530. if ((start2 - ip) < 3) { /* First Match too small : removed */
  531. ml = ml2;
  532. ip = start2;
  533. ref =ref2;
  534. goto _Search2;
  535. }
  536. _Search3:
  537. /* At this stage, we have :
  538. * ml2 > ml1, and
  539. * ip1+3 <= ip2 (usually < ip1+ml1) */
  540. if ((start2 - ip) < OPTIMAL_ML) {
  541. int correction;
  542. int new_ml = ml;
  543. if (new_ml > OPTIMAL_ML) new_ml = OPTIMAL_ML;
  544. if (ip+new_ml > start2 + ml2 - MINMATCH) new_ml = (int)(start2 - ip) + ml2 - MINMATCH;
  545. correction = new_ml - (int)(start2 - ip);
  546. if (correction > 0) {
  547. start2 += correction;
  548. ref2 += correction;
  549. ml2 -= correction;
  550. }
  551. }
  552. /* Now, we have start2 = ip+new_ml, with new_ml = min(ml, OPTIMAL_ML=18) */
  553. if (start2 + ml2 <= mflimit) {
  554. ml3 = LZ4HC_InsertAndGetWiderMatch(ctx,
  555. start2 + ml2 - 3, start2, matchlimit, ml2, &ref3, &start3,
  556. maxNbAttempts, patternAnalysis, 0, dict, favorCompressionRatio);
  557. } else {
  558. ml3 = ml2;
  559. }
  560. if (ml3 == ml2) { /* No better match => encode ML1 and ML2 */
  561. /* ip & ref are known; Now for ml */
  562. if (start2 < ip+ml) ml = (int)(start2 - ip);
  563. /* Now, encode 2 sequences */
  564. optr = op;
  565. if (LZ4HC_encodeSequence(UPDATABLE(ip, op, anchor), ml, ref, limit, oend)) goto _dest_overflow;
  566. ip = start2;
  567. optr = op;
  568. if (LZ4HC_encodeSequence(UPDATABLE(ip, op, anchor), ml2, ref2, limit, oend)) goto _dest_overflow;
  569. continue;
  570. }
  571. if (start3 < ip+ml+3) { /* Not enough space for match 2 : remove it */
  572. if (start3 >= (ip+ml)) { /* can write Seq1 immediately ==> Seq2 is removed, so Seq3 becomes Seq1 */
  573. if (start2 < ip+ml) {
  574. int correction = (int)(ip+ml - start2);
  575. start2 += correction;
  576. ref2 += correction;
  577. ml2 -= correction;
  578. if (ml2 < MINMATCH) {
  579. start2 = start3;
  580. ref2 = ref3;
  581. ml2 = ml3;
  582. }
  583. }
  584. optr = op;
  585. if (LZ4HC_encodeSequence(UPDATABLE(ip, op, anchor), ml, ref, limit, oend)) goto _dest_overflow;
  586. ip = start3;
  587. ref = ref3;
  588. ml = ml3;
  589. start0 = start2;
  590. ref0 = ref2;
  591. ml0 = ml2;
  592. goto _Search2;
  593. }
  594. start2 = start3;
  595. ref2 = ref3;
  596. ml2 = ml3;
  597. goto _Search3;
  598. }
  599. /*
  600. * OK, now we have 3 ascending matches;
  601. * let's write the first one ML1.
  602. * ip & ref are known; Now decide ml.
  603. */
  604. if (start2 < ip+ml) {
  605. if ((start2 - ip) < OPTIMAL_ML) {
  606. int correction;
  607. if (ml > OPTIMAL_ML) ml = OPTIMAL_ML;
  608. if (ip + ml > start2 + ml2 - MINMATCH) ml = (int)(start2 - ip) + ml2 - MINMATCH;
  609. correction = ml - (int)(start2 - ip);
  610. if (correction > 0) {
  611. start2 += correction;
  612. ref2 += correction;
  613. ml2 -= correction;
  614. }
  615. } else {
  616. ml = (int)(start2 - ip);
  617. }
  618. }
  619. optr = op;
  620. if (LZ4HC_encodeSequence(UPDATABLE(ip, op, anchor), ml, ref, limit, oend)) goto _dest_overflow;
  621. /* ML2 becomes ML1 */
  622. ip = start2; ref = ref2; ml = ml2;
  623. /* ML3 becomes ML2 */
  624. start2 = start3; ref2 = ref3; ml2 = ml3;
  625. /* let's find a new ML3 */
  626. goto _Search3;
  627. }
  628. _last_literals:
  629. /* Encode Last Literals */
  630. { size_t lastRunSize = (size_t)(iend - anchor); /* literals */
  631. size_t litLength = (lastRunSize + 255 - RUN_MASK) / 255;
  632. size_t const totalSize = 1 + litLength + lastRunSize;
  633. if (limit == fillOutput) oend += LASTLITERALS; /* restore correct value */
  634. if (limit && (op + totalSize > oend)) {
  635. if (limit == limitedOutput) return 0; /* Check output limit */
  636. /* adapt lastRunSize to fill 'dest' */
  637. lastRunSize = (size_t)(oend - op) - 1;
  638. litLength = (lastRunSize + 255 - RUN_MASK) / 255;
  639. lastRunSize -= litLength;
  640. }
  641. ip = anchor + lastRunSize;
  642. if (lastRunSize >= RUN_MASK) {
  643. size_t accumulator = lastRunSize - RUN_MASK;
  644. *op++ = (RUN_MASK << ML_BITS);
  645. for(; accumulator >= 255 ; accumulator -= 255) *op++ = 255;
  646. *op++ = (BYTE) accumulator;
  647. } else {
  648. *op++ = (BYTE)(lastRunSize << ML_BITS);
  649. }
  650. memcpy(op, anchor, lastRunSize);
  651. op += lastRunSize;
  652. }
  653. /* End */
  654. *srcSizePtr = (int) (((const char*)ip) - source);
  655. return (int) (((char*)op)-dest);
  656. _dest_overflow:
  657. if (limit == fillOutput) {
  658. op = optr; /* restore correct out pointer */
  659. goto _last_literals;
  660. }
  661. return 0;
  662. }
  663. static int LZ4HC_compress_optimal( LZ4HC_CCtx_internal* ctx,
  664. const char* const source, char* dst,
  665. int* srcSizePtr, int dstCapacity,
  666. int const nbSearches, size_t sufficient_len,
  667. const limitedOutput_directive limit, int const fullUpdate,
  668. const dictCtx_directive dict,
  669. HCfavor_e favorDecSpeed);
  670. LZ4_FORCE_INLINE int LZ4HC_compress_generic_internal (
  671. LZ4HC_CCtx_internal* const ctx,
  672. const char* const src,
  673. char* const dst,
  674. int* const srcSizePtr,
  675. int const dstCapacity,
  676. int cLevel,
  677. const limitedOutput_directive limit,
  678. const dictCtx_directive dict
  679. )
  680. {
  681. typedef enum { lz4hc, lz4opt } lz4hc_strat_e;
  682. typedef struct {
  683. lz4hc_strat_e strat;
  684. U32 nbSearches;
  685. U32 targetLength;
  686. } cParams_t;
  687. static const cParams_t clTable[LZ4HC_CLEVEL_MAX+1] = {
  688. { lz4hc, 2, 16 }, /* 0, unused */
  689. { lz4hc, 2, 16 }, /* 1, unused */
  690. { lz4hc, 2, 16 }, /* 2, unused */
  691. { lz4hc, 4, 16 }, /* 3 */
  692. { lz4hc, 8, 16 }, /* 4 */
  693. { lz4hc, 16, 16 }, /* 5 */
  694. { lz4hc, 32, 16 }, /* 6 */
  695. { lz4hc, 64, 16 }, /* 7 */
  696. { lz4hc, 128, 16 }, /* 8 */
  697. { lz4hc, 256, 16 }, /* 9 */
  698. { lz4opt, 96, 64 }, /*10==LZ4HC_CLEVEL_OPT_MIN*/
  699. { lz4opt, 512,128 }, /*11 */
  700. { lz4opt,16384,LZ4_OPT_NUM }, /* 12==LZ4HC_CLEVEL_MAX */
  701. };
  702. DEBUGLOG(4, "LZ4HC_compress_generic(ctx=%p, src=%p, srcSize=%d)", ctx, src, *srcSizePtr);
  703. if (limit == fillOutput && dstCapacity < 1) return 0; /* Impossible to store anything */
  704. if ((U32)*srcSizePtr > (U32)LZ4_MAX_INPUT_SIZE) return 0; /* Unsupported input size (too large or negative) */
  705. ctx->end += *srcSizePtr;
  706. if (cLevel < 1) cLevel = LZ4HC_CLEVEL_DEFAULT; /* note : convention is different from lz4frame, maybe something to review */
  707. cLevel = MIN(LZ4HC_CLEVEL_MAX, cLevel);
  708. { cParams_t const cParam = clTable[cLevel];
  709. HCfavor_e const favor = ctx->favorDecSpeed ? favorDecompressionSpeed : favorCompressionRatio;
  710. int result;
  711. if (cParam.strat == lz4hc) {
  712. result = LZ4HC_compress_hashChain(ctx,
  713. src, dst, srcSizePtr, dstCapacity,
  714. cParam.nbSearches, limit, dict);
  715. } else {
  716. assert(cParam.strat == lz4opt);
  717. result = LZ4HC_compress_optimal(ctx,
  718. src, dst, srcSizePtr, dstCapacity,
  719. (int)cParam.nbSearches, cParam.targetLength, limit,
  720. cLevel == LZ4HC_CLEVEL_MAX, /* ultra mode */
  721. dict, favor);
  722. }
  723. if (result <= 0) ctx->dirty = 1;
  724. return result;
  725. }
  726. }
  727. static void LZ4HC_setExternalDict(LZ4HC_CCtx_internal* ctxPtr, const BYTE* newBlock);
  728. static int
  729. LZ4HC_compress_generic_noDictCtx (
  730. LZ4HC_CCtx_internal* const ctx,
  731. const char* const src,
  732. char* const dst,
  733. int* const srcSizePtr,
  734. int const dstCapacity,
  735. int cLevel,
  736. limitedOutput_directive limit
  737. )
  738. {
  739. assert(ctx->dictCtx == NULL);
  740. return LZ4HC_compress_generic_internal(ctx, src, dst, srcSizePtr, dstCapacity, cLevel, limit, noDictCtx);
  741. }
  742. static int
  743. LZ4HC_compress_generic_dictCtx (
  744. LZ4HC_CCtx_internal* const ctx,
  745. const char* const src,
  746. char* const dst,
  747. int* const srcSizePtr,
  748. int const dstCapacity,
  749. int cLevel,
  750. limitedOutput_directive limit
  751. )
  752. {
  753. const size_t position = (size_t)(ctx->end - ctx->base) - ctx->lowLimit;
  754. assert(ctx->dictCtx != NULL);
  755. if (position >= 64 KB) {
  756. ctx->dictCtx = NULL;
  757. return LZ4HC_compress_generic_noDictCtx(ctx, src, dst, srcSizePtr, dstCapacity, cLevel, limit);
  758. } else if (position == 0 && *srcSizePtr > 4 KB) {
  759. memcpy(ctx, ctx->dictCtx, sizeof(LZ4HC_CCtx_internal));
  760. LZ4HC_setExternalDict(ctx, (const BYTE *)src);
  761. ctx->compressionLevel = (short)cLevel;
  762. return LZ4HC_compress_generic_noDictCtx(ctx, src, dst, srcSizePtr, dstCapacity, cLevel, limit);
  763. } else {
  764. return LZ4HC_compress_generic_internal(ctx, src, dst, srcSizePtr, dstCapacity, cLevel, limit, usingDictCtxHc);
  765. }
  766. }
  767. static int
  768. LZ4HC_compress_generic (
  769. LZ4HC_CCtx_internal* const ctx,
  770. const char* const src,
  771. char* const dst,
  772. int* const srcSizePtr,
  773. int const dstCapacity,
  774. int cLevel,
  775. limitedOutput_directive limit
  776. )
  777. {
  778. if (ctx->dictCtx == NULL) {
  779. return LZ4HC_compress_generic_noDictCtx(ctx, src, dst, srcSizePtr, dstCapacity, cLevel, limit);
  780. } else {
  781. return LZ4HC_compress_generic_dictCtx(ctx, src, dst, srcSizePtr, dstCapacity, cLevel, limit);
  782. }
  783. }
  784. int LZ4_sizeofStateHC(void) { return (int)sizeof(LZ4_streamHC_t); }
  785. #ifndef _MSC_VER /* for some reason, Visual fails the aligment test on 32-bit x86 :
  786. * it reports an aligment of 8-bytes,
  787. * while actually aligning LZ4_streamHC_t on 4 bytes. */
  788. static size_t LZ4_streamHC_t_alignment(void)
  789. {
  790. struct { char c; LZ4_streamHC_t t; } t_a;
  791. return sizeof(t_a) - sizeof(t_a.t);
  792. }
  793. #endif
  794. /* state is presumed correctly initialized,
  795. * in which case its size and alignment have already been validate */
  796. int LZ4_compress_HC_extStateHC_fastReset (void* state, const char* src, char* dst, int srcSize, int dstCapacity, int compressionLevel)
  797. {
  798. LZ4HC_CCtx_internal* const ctx = &((LZ4_streamHC_t*)state)->internal_donotuse;
  799. #ifndef _MSC_VER /* for some reason, Visual fails the aligment test on 32-bit x86 :
  800. * it reports an aligment of 8-bytes,
  801. * while actually aligning LZ4_streamHC_t on 4 bytes. */
  802. assert(((size_t)state & (LZ4_streamHC_t_alignment() - 1)) == 0); /* check alignment */
  803. #endif
  804. if (((size_t)(state)&(sizeof(void*)-1)) != 0) return 0; /* Error : state is not aligned for pointers (32 or 64 bits) */
  805. LZ4_resetStreamHC_fast((LZ4_streamHC_t*)state, compressionLevel);
  806. LZ4HC_init_internal (ctx, (const BYTE*)src);
  807. if (dstCapacity < LZ4_compressBound(srcSize))
  808. return LZ4HC_compress_generic (ctx, src, dst, &srcSize, dstCapacity, compressionLevel, limitedOutput);
  809. else
  810. return LZ4HC_compress_generic (ctx, src, dst, &srcSize, dstCapacity, compressionLevel, notLimited);
  811. }
  812. int LZ4_compress_HC_extStateHC (void* state, const char* src, char* dst, int srcSize, int dstCapacity, int compressionLevel)
  813. {
  814. LZ4_streamHC_t* const ctx = LZ4_initStreamHC(state, sizeof(*ctx));
  815. if (ctx==NULL) return 0; /* init failure */
  816. return LZ4_compress_HC_extStateHC_fastReset(state, src, dst, srcSize, dstCapacity, compressionLevel);
  817. }
  818. int LZ4_compress_HC(const char* src, char* dst, int srcSize, int dstCapacity, int compressionLevel)
  819. {
  820. #if defined(LZ4HC_HEAPMODE) && LZ4HC_HEAPMODE==1
  821. LZ4_streamHC_t* const statePtr = (LZ4_streamHC_t*)ALLOC(sizeof(LZ4_streamHC_t));
  822. #else
  823. LZ4_streamHC_t state;
  824. LZ4_streamHC_t* const statePtr = &state;
  825. #endif
  826. int const cSize = LZ4_compress_HC_extStateHC(statePtr, src, dst, srcSize, dstCapacity, compressionLevel);
  827. #if defined(LZ4HC_HEAPMODE) && LZ4HC_HEAPMODE==1
  828. FREEMEM(statePtr);
  829. #endif
  830. return cSize;
  831. }
  832. /* state is presumed sized correctly (>= sizeof(LZ4_streamHC_t)) */
  833. int LZ4_compress_HC_destSize(void* state, const char* source, char* dest, int* sourceSizePtr, int targetDestSize, int cLevel)
  834. {
  835. LZ4_streamHC_t* const ctx = LZ4_initStreamHC(state, sizeof(*ctx));
  836. if (ctx==NULL) return 0; /* init failure */
  837. LZ4HC_init_internal(&ctx->internal_donotuse, (const BYTE*) source);
  838. LZ4_setCompressionLevel(ctx, cLevel);
  839. return LZ4HC_compress_generic(&ctx->internal_donotuse, source, dest, sourceSizePtr, targetDestSize, cLevel, fillOutput);
  840. }
  841. /**************************************
  842. * Streaming Functions
  843. **************************************/
  844. /* allocation */
  845. LZ4_streamHC_t* LZ4_createStreamHC(void)
  846. {
  847. LZ4_streamHC_t* const LZ4_streamHCPtr = (LZ4_streamHC_t*)ALLOC(sizeof(LZ4_streamHC_t));
  848. if (LZ4_streamHCPtr==NULL) return NULL;
  849. LZ4_initStreamHC(LZ4_streamHCPtr, sizeof(*LZ4_streamHCPtr)); /* full initialization, malloc'ed buffer can be full of garbage */
  850. return LZ4_streamHCPtr;
  851. }
  852. int LZ4_freeStreamHC (LZ4_streamHC_t* LZ4_streamHCPtr)
  853. {
  854. DEBUGLOG(4, "LZ4_freeStreamHC(%p)", LZ4_streamHCPtr);
  855. if (!LZ4_streamHCPtr) return 0; /* support free on NULL */
  856. FREEMEM(LZ4_streamHCPtr);
  857. return 0;
  858. }
  859. LZ4_streamHC_t* LZ4_initStreamHC (void* buffer, size_t size)
  860. {
  861. LZ4_streamHC_t* const LZ4_streamHCPtr = (LZ4_streamHC_t*)buffer;
  862. if (buffer == NULL) return NULL;
  863. if (size < sizeof(LZ4_streamHC_t)) return NULL;
  864. #ifndef _MSC_VER /* for some reason, Visual fails the aligment test on 32-bit x86 :
  865. * it reports an aligment of 8-bytes,
  866. * while actually aligning LZ4_streamHC_t on 4 bytes. */
  867. if (((size_t)buffer) & (LZ4_streamHC_t_alignment() - 1)) return NULL; /* alignment check */
  868. #endif
  869. /* if compilation fails here, LZ4_STREAMHCSIZE must be increased */
  870. LZ4_STATIC_ASSERT(sizeof(LZ4HC_CCtx_internal) <= LZ4_STREAMHCSIZE);
  871. DEBUGLOG(4, "LZ4_initStreamHC(%p, %u)", LZ4_streamHCPtr, (unsigned)size);
  872. /* end-base will trigger a clearTable on starting compression */
  873. LZ4_streamHCPtr->internal_donotuse.end = (const BYTE *)(ptrdiff_t)-1;
  874. LZ4_streamHCPtr->internal_donotuse.base = NULL;
  875. LZ4_streamHCPtr->internal_donotuse.dictCtx = NULL;
  876. LZ4_streamHCPtr->internal_donotuse.favorDecSpeed = 0;
  877. LZ4_streamHCPtr->internal_donotuse.dirty = 0;
  878. LZ4_setCompressionLevel(LZ4_streamHCPtr, LZ4HC_CLEVEL_DEFAULT);
  879. return LZ4_streamHCPtr;
  880. }
  881. /* just a stub */
  882. void LZ4_resetStreamHC (LZ4_streamHC_t* LZ4_streamHCPtr, int compressionLevel)
  883. {
  884. LZ4_initStreamHC(LZ4_streamHCPtr, sizeof(*LZ4_streamHCPtr));
  885. LZ4_setCompressionLevel(LZ4_streamHCPtr, compressionLevel);
  886. }
  887. void LZ4_resetStreamHC_fast (LZ4_streamHC_t* LZ4_streamHCPtr, int compressionLevel)
  888. {
  889. DEBUGLOG(4, "LZ4_resetStreamHC_fast(%p, %d)", LZ4_streamHCPtr, compressionLevel);
  890. if (LZ4_streamHCPtr->internal_donotuse.dirty) {
  891. LZ4_initStreamHC(LZ4_streamHCPtr, sizeof(*LZ4_streamHCPtr));
  892. } else {
  893. /* preserve end - base : can trigger clearTable's threshold */
  894. LZ4_streamHCPtr->internal_donotuse.end -= (uptrval)LZ4_streamHCPtr->internal_donotuse.base;
  895. LZ4_streamHCPtr->internal_donotuse.base = NULL;
  896. LZ4_streamHCPtr->internal_donotuse.dictCtx = NULL;
  897. }
  898. LZ4_setCompressionLevel(LZ4_streamHCPtr, compressionLevel);
  899. }
  900. void LZ4_setCompressionLevel(LZ4_streamHC_t* LZ4_streamHCPtr, int compressionLevel)
  901. {
  902. DEBUGLOG(5, "LZ4_setCompressionLevel(%p, %d)", LZ4_streamHCPtr, compressionLevel);
  903. if (compressionLevel < 1) compressionLevel = LZ4HC_CLEVEL_DEFAULT;
  904. if (compressionLevel > LZ4HC_CLEVEL_MAX) compressionLevel = LZ4HC_CLEVEL_MAX;
  905. LZ4_streamHCPtr->internal_donotuse.compressionLevel = (short)compressionLevel;
  906. }
  907. void LZ4_favorDecompressionSpeed(LZ4_streamHC_t* LZ4_streamHCPtr, int favor)
  908. {
  909. LZ4_streamHCPtr->internal_donotuse.favorDecSpeed = (favor!=0);
  910. }
  911. /* LZ4_loadDictHC() :
  912. * LZ4_streamHCPtr is presumed properly initialized */
  913. int LZ4_loadDictHC (LZ4_streamHC_t* LZ4_streamHCPtr,
  914. const char* dictionary, int dictSize)
  915. {
  916. LZ4HC_CCtx_internal* const ctxPtr = &LZ4_streamHCPtr->internal_donotuse;
  917. DEBUGLOG(4, "LZ4_loadDictHC(%p, %p, %d)", LZ4_streamHCPtr, dictionary, dictSize);
  918. assert(LZ4_streamHCPtr != NULL);
  919. if (dictSize > 64 KB) {
  920. dictionary += (size_t)dictSize - 64 KB;
  921. dictSize = 64 KB;
  922. }
  923. /* need a full initialization, there are bad side-effects when using resetFast() */
  924. { int const cLevel = ctxPtr->compressionLevel;
  925. LZ4_initStreamHC(LZ4_streamHCPtr, sizeof(*LZ4_streamHCPtr));
  926. LZ4_setCompressionLevel(LZ4_streamHCPtr, cLevel);
  927. }
  928. LZ4HC_init_internal (ctxPtr, (const BYTE*)dictionary);
  929. ctxPtr->end = (const BYTE*)dictionary + dictSize;
  930. if (dictSize >= 4) LZ4HC_Insert (ctxPtr, ctxPtr->end-3);
  931. return dictSize;
  932. }
  933. void LZ4_attach_HC_dictionary(LZ4_streamHC_t *working_stream, const LZ4_streamHC_t *dictionary_stream) {
  934. working_stream->internal_donotuse.dictCtx = dictionary_stream != NULL ? &(dictionary_stream->internal_donotuse) : NULL;
  935. }
  936. /* compression */
  937. static void LZ4HC_setExternalDict(LZ4HC_CCtx_internal* ctxPtr, const BYTE* newBlock)
  938. {
  939. DEBUGLOG(4, "LZ4HC_setExternalDict(%p, %p)", ctxPtr, newBlock);
  940. if (ctxPtr->end >= ctxPtr->base + ctxPtr->dictLimit + 4)
  941. LZ4HC_Insert (ctxPtr, ctxPtr->end-3); /* Referencing remaining dictionary content */
  942. /* Only one memory segment for extDict, so any previous extDict is lost at this stage */
  943. ctxPtr->lowLimit = ctxPtr->dictLimit;
  944. ctxPtr->dictLimit = (U32)(ctxPtr->end - ctxPtr->base);
  945. ctxPtr->dictBase = ctxPtr->base;
  946. ctxPtr->base = newBlock - ctxPtr->dictLimit;
  947. ctxPtr->end = newBlock;
  948. ctxPtr->nextToUpdate = ctxPtr->dictLimit; /* match referencing will resume from there */
  949. /* cannot reference an extDict and a dictCtx at the same time */
  950. ctxPtr->dictCtx = NULL;
  951. }
  952. static int LZ4_compressHC_continue_generic (LZ4_streamHC_t* LZ4_streamHCPtr,
  953. const char* src, char* dst,
  954. int* srcSizePtr, int dstCapacity,
  955. limitedOutput_directive limit)
  956. {
  957. LZ4HC_CCtx_internal* const ctxPtr = &LZ4_streamHCPtr->internal_donotuse;
  958. DEBUGLOG(4, "LZ4_compressHC_continue_generic(ctx=%p, src=%p, srcSize=%d)",
  959. LZ4_streamHCPtr, src, *srcSizePtr);
  960. assert(ctxPtr != NULL);
  961. /* auto-init if forgotten */
  962. if (ctxPtr->base == NULL) LZ4HC_init_internal (ctxPtr, (const BYTE*) src);
  963. /* Check overflow */
  964. if ((size_t)(ctxPtr->end - ctxPtr->base) > 2 GB) {
  965. size_t dictSize = (size_t)(ctxPtr->end - ctxPtr->base) - ctxPtr->dictLimit;
  966. if (dictSize > 64 KB) dictSize = 64 KB;
  967. LZ4_loadDictHC(LZ4_streamHCPtr, (const char*)(ctxPtr->end) - dictSize, (int)dictSize);
  968. }
  969. /* Check if blocks follow each other */
  970. if ((const BYTE*)src != ctxPtr->end)
  971. LZ4HC_setExternalDict(ctxPtr, (const BYTE*)src);
  972. /* Check overlapping input/dictionary space */
  973. { const BYTE* sourceEnd = (const BYTE*) src + *srcSizePtr;
  974. const BYTE* const dictBegin = ctxPtr->dictBase + ctxPtr->lowLimit;
  975. const BYTE* const dictEnd = ctxPtr->dictBase + ctxPtr->dictLimit;
  976. if ((sourceEnd > dictBegin) && ((const BYTE*)src < dictEnd)) {
  977. if (sourceEnd > dictEnd) sourceEnd = dictEnd;
  978. ctxPtr->lowLimit = (U32)(sourceEnd - ctxPtr->dictBase);
  979. if (ctxPtr->dictLimit - ctxPtr->lowLimit < 4) ctxPtr->lowLimit = ctxPtr->dictLimit;
  980. }
  981. }
  982. return LZ4HC_compress_generic (ctxPtr, src, dst, srcSizePtr, dstCapacity, ctxPtr->compressionLevel, limit);
  983. }
  984. int LZ4_compress_HC_continue (LZ4_streamHC_t* LZ4_streamHCPtr, const char* src, char* dst, int srcSize, int dstCapacity)
  985. {
  986. if (dstCapacity < LZ4_compressBound(srcSize))
  987. return LZ4_compressHC_continue_generic (LZ4_streamHCPtr, src, dst, &srcSize, dstCapacity, limitedOutput);
  988. else
  989. return LZ4_compressHC_continue_generic (LZ4_streamHCPtr, src, dst, &srcSize, dstCapacity, notLimited);
  990. }
  991. int LZ4_compress_HC_continue_destSize (LZ4_streamHC_t* LZ4_streamHCPtr, const char* src, char* dst, int* srcSizePtr, int targetDestSize)
  992. {
  993. return LZ4_compressHC_continue_generic(LZ4_streamHCPtr, src, dst, srcSizePtr, targetDestSize, fillOutput);
  994. }
  995. /* dictionary saving */
  996. int LZ4_saveDictHC (LZ4_streamHC_t* LZ4_streamHCPtr, char* safeBuffer, int dictSize)
  997. {
  998. LZ4HC_CCtx_internal* const streamPtr = &LZ4_streamHCPtr->internal_donotuse;
  999. int const prefixSize = (int)(streamPtr->end - (streamPtr->base + streamPtr->dictLimit));
  1000. DEBUGLOG(4, "LZ4_saveDictHC(%p, %p, %d)", LZ4_streamHCPtr, safeBuffer, dictSize);
  1001. if (dictSize > 64 KB) dictSize = 64 KB;
  1002. if (dictSize < 4) dictSize = 0;
  1003. if (dictSize > prefixSize) dictSize = prefixSize;
  1004. memmove(safeBuffer, streamPtr->end - dictSize, dictSize);
  1005. { U32 const endIndex = (U32)(streamPtr->end - streamPtr->base);
  1006. streamPtr->end = (const BYTE*)safeBuffer + dictSize;
  1007. streamPtr->base = streamPtr->end - endIndex;
  1008. streamPtr->dictLimit = endIndex - (U32)dictSize;
  1009. streamPtr->lowLimit = endIndex - (U32)dictSize;
  1010. if (streamPtr->nextToUpdate < streamPtr->dictLimit) streamPtr->nextToUpdate = streamPtr->dictLimit;
  1011. }
  1012. return dictSize;
  1013. }
  1014. /***************************************************
  1015. * Deprecated Functions
  1016. ***************************************************/
  1017. /* These functions currently generate deprecation warnings */
  1018. /* Wrappers for deprecated compression functions */
  1019. int LZ4_compressHC(const char* src, char* dst, int srcSize) { return LZ4_compress_HC (src, dst, srcSize, LZ4_compressBound(srcSize), 0); }
  1020. int LZ4_compressHC_limitedOutput(const char* src, char* dst, int srcSize, int maxDstSize) { return LZ4_compress_HC(src, dst, srcSize, maxDstSize, 0); }
  1021. int LZ4_compressHC2(const char* src, char* dst, int srcSize, int cLevel) { return LZ4_compress_HC (src, dst, srcSize, LZ4_compressBound(srcSize), cLevel); }
  1022. int LZ4_compressHC2_limitedOutput(const char* src, char* dst, int srcSize, int maxDstSize, int cLevel) { return LZ4_compress_HC(src, dst, srcSize, maxDstSize, cLevel); }
  1023. int LZ4_compressHC_withStateHC (void* state, const char* src, char* dst, int srcSize) { return LZ4_compress_HC_extStateHC (state, src, dst, srcSize, LZ4_compressBound(srcSize), 0); }
  1024. int LZ4_compressHC_limitedOutput_withStateHC (void* state, const char* src, char* dst, int srcSize, int maxDstSize) { return LZ4_compress_HC_extStateHC (state, src, dst, srcSize, maxDstSize, 0); }
  1025. int LZ4_compressHC2_withStateHC (void* state, const char* src, char* dst, int srcSize, int cLevel) { return LZ4_compress_HC_extStateHC(state, src, dst, srcSize, LZ4_compressBound(srcSize), cLevel); }
  1026. int LZ4_compressHC2_limitedOutput_withStateHC (void* state, const char* src, char* dst, int srcSize, int maxDstSize, int cLevel) { return LZ4_compress_HC_extStateHC(state, src, dst, srcSize, maxDstSize, cLevel); }
  1027. int LZ4_compressHC_continue (LZ4_streamHC_t* ctx, const char* src, char* dst, int srcSize) { return LZ4_compress_HC_continue (ctx, src, dst, srcSize, LZ4_compressBound(srcSize)); }
  1028. int LZ4_compressHC_limitedOutput_continue (LZ4_streamHC_t* ctx, const char* src, char* dst, int srcSize, int maxDstSize) { return LZ4_compress_HC_continue (ctx, src, dst, srcSize, maxDstSize); }
  1029. /* Deprecated streaming functions */
  1030. int LZ4_sizeofStreamStateHC(void) { return LZ4_STREAMHCSIZE; }
  1031. /* state is presumed correctly sized, aka >= sizeof(LZ4_streamHC_t)
  1032. * @return : 0 on success, !=0 if error */
  1033. int LZ4_resetStreamStateHC(void* state, char* inputBuffer)
  1034. {
  1035. LZ4_streamHC_t* const hc4 = LZ4_initStreamHC(state, sizeof(*hc4));
  1036. if (hc4 == NULL) return 1; /* init failed */
  1037. LZ4HC_init_internal (&hc4->internal_donotuse, (const BYTE*)inputBuffer);
  1038. return 0;
  1039. }
  1040. void* LZ4_createHC (const char* inputBuffer)
  1041. {
  1042. LZ4_streamHC_t* const hc4 = LZ4_createStreamHC();
  1043. if (hc4 == NULL) return NULL; /* not enough memory */
  1044. LZ4HC_init_internal (&hc4->internal_donotuse, (const BYTE*)inputBuffer);
  1045. return hc4;
  1046. }
  1047. int LZ4_freeHC (void* LZ4HC_Data)
  1048. {
  1049. if (!LZ4HC_Data) return 0; /* support free on NULL */
  1050. FREEMEM(LZ4HC_Data);
  1051. return 0;
  1052. }
  1053. int LZ4_compressHC2_continue (void* LZ4HC_Data, const char* src, char* dst, int srcSize, int cLevel)
  1054. {
  1055. return LZ4HC_compress_generic (&((LZ4_streamHC_t*)LZ4HC_Data)->internal_donotuse, src, dst, &srcSize, 0, cLevel, notLimited);
  1056. }
  1057. int LZ4_compressHC2_limitedOutput_continue (void* LZ4HC_Data, const char* src, char* dst, int srcSize, int dstCapacity, int cLevel)
  1058. {
  1059. return LZ4HC_compress_generic (&((LZ4_streamHC_t*)LZ4HC_Data)->internal_donotuse, src, dst, &srcSize, dstCapacity, cLevel, limitedOutput);
  1060. }
  1061. char* LZ4_slideInputBufferHC(void* LZ4HC_Data)
  1062. {
  1063. LZ4_streamHC_t *ctx = (LZ4_streamHC_t*)LZ4HC_Data;
  1064. const BYTE *bufferStart = ctx->internal_donotuse.base + ctx->internal_donotuse.lowLimit;
  1065. LZ4_resetStreamHC_fast(ctx, ctx->internal_donotuse.compressionLevel);
  1066. /* avoid const char * -> char * conversion warning :( */
  1067. return (char *)(uptrval)bufferStart;
  1068. }
  1069. /* ================================================
  1070. * LZ4 Optimal parser (levels [LZ4HC_CLEVEL_OPT_MIN - LZ4HC_CLEVEL_MAX])
  1071. * ===============================================*/
  1072. typedef struct {
  1073. int price;
  1074. int off;
  1075. int mlen;
  1076. int litlen;
  1077. } LZ4HC_optimal_t;
  1078. /* price in bytes */
  1079. LZ4_FORCE_INLINE int LZ4HC_literalsPrice(int const litlen)
  1080. {
  1081. int price = litlen;
  1082. assert(litlen >= 0);
  1083. if (litlen >= (int)RUN_MASK)
  1084. price += 1 + ((litlen-(int)RUN_MASK) / 255);
  1085. return price;
  1086. }
  1087. /* requires mlen >= MINMATCH */
  1088. LZ4_FORCE_INLINE int LZ4HC_sequencePrice(int litlen, int mlen)
  1089. {
  1090. int price = 1 + 2 ; /* token + 16-bit offset */
  1091. assert(litlen >= 0);
  1092. assert(mlen >= MINMATCH);
  1093. price += LZ4HC_literalsPrice(litlen);
  1094. if (mlen >= (int)(ML_MASK+MINMATCH))
  1095. price += 1 + ((mlen-(int)(ML_MASK+MINMATCH)) / 255);
  1096. return price;
  1097. }
  1098. typedef struct {
  1099. int off;
  1100. int len;
  1101. } LZ4HC_match_t;
  1102. LZ4_FORCE_INLINE LZ4HC_match_t
  1103. LZ4HC_FindLongerMatch(LZ4HC_CCtx_internal* const ctx,
  1104. const BYTE* ip, const BYTE* const iHighLimit,
  1105. int minLen, int nbSearches,
  1106. const dictCtx_directive dict,
  1107. const HCfavor_e favorDecSpeed)
  1108. {
  1109. LZ4HC_match_t match = { 0 , 0 };
  1110. const BYTE* matchPtr = NULL;
  1111. /* note : LZ4HC_InsertAndGetWiderMatch() is able to modify the starting position of a match (*startpos),
  1112. * but this won't be the case here, as we define iLowLimit==ip,
  1113. * so LZ4HC_InsertAndGetWiderMatch() won't be allowed to search past ip */
  1114. int matchLength = LZ4HC_InsertAndGetWiderMatch(ctx, ip, ip, iHighLimit, minLen, &matchPtr, &ip, nbSearches, 1 /*patternAnalysis*/, 1 /*chainSwap*/, dict, favorDecSpeed);
  1115. if (matchLength <= minLen) return match;
  1116. if (favorDecSpeed) {
  1117. if ((matchLength>18) & (matchLength<=36)) matchLength=18; /* favor shortcut */
  1118. }
  1119. match.len = matchLength;
  1120. match.off = (int)(ip-matchPtr);
  1121. return match;
  1122. }
  1123. static int LZ4HC_compress_optimal ( LZ4HC_CCtx_internal* ctx,
  1124. const char* const source,
  1125. char* dst,
  1126. int* srcSizePtr,
  1127. int dstCapacity,
  1128. int const nbSearches,
  1129. size_t sufficient_len,
  1130. const limitedOutput_directive limit,
  1131. int const fullUpdate,
  1132. const dictCtx_directive dict,
  1133. const HCfavor_e favorDecSpeed)
  1134. {
  1135. #define TRAILING_LITERALS 3
  1136. LZ4HC_optimal_t opt[LZ4_OPT_NUM + TRAILING_LITERALS]; /* ~64 KB, which is a bit large for stack... */
  1137. const BYTE* ip = (const BYTE*) source;
  1138. const BYTE* anchor = ip;
  1139. const BYTE* const iend = ip + *srcSizePtr;
  1140. const BYTE* const mflimit = iend - MFLIMIT;
  1141. const BYTE* const matchlimit = iend - LASTLITERALS;
  1142. BYTE* op = (BYTE*) dst;
  1143. BYTE* opSaved = (BYTE*) dst;
  1144. BYTE* oend = op + dstCapacity;
  1145. /* init */
  1146. DEBUGLOG(5, "LZ4HC_compress_optimal(dst=%p, dstCapa=%u)", dst, (unsigned)dstCapacity);
  1147. *srcSizePtr = 0;
  1148. if (limit == fillOutput) oend -= LASTLITERALS; /* Hack for support LZ4 format restriction */
  1149. if (sufficient_len >= LZ4_OPT_NUM) sufficient_len = LZ4_OPT_NUM-1;
  1150. /* Main Loop */
  1151. assert(ip - anchor < LZ4_MAX_INPUT_SIZE);
  1152. while (ip <= mflimit) {
  1153. int const llen = (int)(ip - anchor);
  1154. int best_mlen, best_off;
  1155. int cur, last_match_pos = 0;
  1156. LZ4HC_match_t const firstMatch = LZ4HC_FindLongerMatch(ctx, ip, matchlimit, MINMATCH-1, nbSearches, dict, favorDecSpeed);
  1157. if (firstMatch.len==0) { ip++; continue; }
  1158. if ((size_t)firstMatch.len > sufficient_len) {
  1159. /* good enough solution : immediate encoding */
  1160. int const firstML = firstMatch.len;
  1161. const BYTE* const matchPos = ip - firstMatch.off;
  1162. opSaved = op;
  1163. if ( LZ4HC_encodeSequence(UPDATABLE(ip, op, anchor), firstML, matchPos, limit, oend) ) /* updates ip, op and anchor */
  1164. goto _dest_overflow;
  1165. continue;
  1166. }
  1167. /* set prices for first positions (literals) */
  1168. { int rPos;
  1169. for (rPos = 0 ; rPos < MINMATCH ; rPos++) {
  1170. int const cost = LZ4HC_literalsPrice(llen + rPos);
  1171. opt[rPos].mlen = 1;
  1172. opt[rPos].off = 0;
  1173. opt[rPos].litlen = llen + rPos;
  1174. opt[rPos].price = cost;
  1175. DEBUGLOG(7, "rPos:%3i => price:%3i (litlen=%i) -- initial setup",
  1176. rPos, cost, opt[rPos].litlen);
  1177. } }
  1178. /* set prices using initial match */
  1179. { int mlen = MINMATCH;
  1180. int const matchML = firstMatch.len; /* necessarily < sufficient_len < LZ4_OPT_NUM */
  1181. int const offset = firstMatch.off;
  1182. assert(matchML < LZ4_OPT_NUM);
  1183. for ( ; mlen <= matchML ; mlen++) {
  1184. int const cost = LZ4HC_sequencePrice(llen, mlen);
  1185. opt[mlen].mlen = mlen;
  1186. opt[mlen].off = offset;
  1187. opt[mlen].litlen = llen;
  1188. opt[mlen].price = cost;
  1189. DEBUGLOG(7, "rPos:%3i => price:%3i (matchlen=%i) -- initial setup",
  1190. mlen, cost, mlen);
  1191. } }
  1192. last_match_pos = firstMatch.len;
  1193. { int addLit;
  1194. for (addLit = 1; addLit <= TRAILING_LITERALS; addLit ++) {
  1195. opt[last_match_pos+addLit].mlen = 1; /* literal */
  1196. opt[last_match_pos+addLit].off = 0;
  1197. opt[last_match_pos+addLit].litlen = addLit;
  1198. opt[last_match_pos+addLit].price = opt[last_match_pos].price + LZ4HC_literalsPrice(addLit);
  1199. DEBUGLOG(7, "rPos:%3i => price:%3i (litlen=%i) -- initial setup",
  1200. last_match_pos+addLit, opt[last_match_pos+addLit].price, addLit);
  1201. } }
  1202. /* check further positions */
  1203. for (cur = 1; cur < last_match_pos; cur++) {
  1204. const BYTE* const curPtr = ip + cur;
  1205. LZ4HC_match_t newMatch;
  1206. if (curPtr > mflimit) break;
  1207. DEBUGLOG(7, "rPos:%u[%u] vs [%u]%u",
  1208. cur, opt[cur].price, opt[cur+1].price, cur+1);
  1209. if (fullUpdate) {
  1210. /* not useful to search here if next position has same (or lower) cost */
  1211. if ( (opt[cur+1].price <= opt[cur].price)
  1212. /* in some cases, next position has same cost, but cost rises sharply after, so a small match would still be beneficial */
  1213. && (opt[cur+MINMATCH].price < opt[cur].price + 3/*min seq price*/) )
  1214. continue;
  1215. } else {
  1216. /* not useful to search here if next position has same (or lower) cost */
  1217. if (opt[cur+1].price <= opt[cur].price) continue;
  1218. }
  1219. DEBUGLOG(7, "search at rPos:%u", cur);
  1220. if (fullUpdate)
  1221. newMatch = LZ4HC_FindLongerMatch(ctx, curPtr, matchlimit, MINMATCH-1, nbSearches, dict, favorDecSpeed);
  1222. else
  1223. /* only test matches of minimum length; slightly faster, but misses a few bytes */
  1224. newMatch = LZ4HC_FindLongerMatch(ctx, curPtr, matchlimit, last_match_pos - cur, nbSearches, dict, favorDecSpeed);
  1225. if (!newMatch.len) continue;
  1226. if ( ((size_t)newMatch.len > sufficient_len)
  1227. || (newMatch.len + cur >= LZ4_OPT_NUM) ) {
  1228. /* immediate encoding */
  1229. best_mlen = newMatch.len;
  1230. best_off = newMatch.off;
  1231. last_match_pos = cur + 1;
  1232. goto encode;
  1233. }
  1234. /* before match : set price with literals at beginning */
  1235. { int const baseLitlen = opt[cur].litlen;
  1236. int litlen;
  1237. for (litlen = 1; litlen < MINMATCH; litlen++) {
  1238. int const price = opt[cur].price - LZ4HC_literalsPrice(baseLitlen) + LZ4HC_literalsPrice(baseLitlen+litlen);
  1239. int const pos = cur + litlen;
  1240. if (price < opt[pos].price) {
  1241. opt[pos].mlen = 1; /* literal */
  1242. opt[pos].off = 0;
  1243. opt[pos].litlen = baseLitlen+litlen;
  1244. opt[pos].price = price;
  1245. DEBUGLOG(7, "rPos:%3i => price:%3i (litlen=%i)",
  1246. pos, price, opt[pos].litlen);
  1247. } } }
  1248. /* set prices using match at position = cur */
  1249. { int const matchML = newMatch.len;
  1250. int ml = MINMATCH;
  1251. assert(cur + newMatch.len < LZ4_OPT_NUM);
  1252. for ( ; ml <= matchML ; ml++) {
  1253. int const pos = cur + ml;
  1254. int const offset = newMatch.off;
  1255. int price;
  1256. int ll;
  1257. DEBUGLOG(7, "testing price rPos %i (last_match_pos=%i)",
  1258. pos, last_match_pos);
  1259. if (opt[cur].mlen == 1) {
  1260. ll = opt[cur].litlen;
  1261. price = ((cur > ll) ? opt[cur - ll].price : 0)
  1262. + LZ4HC_sequencePrice(ll, ml);
  1263. } else {
  1264. ll = 0;
  1265. price = opt[cur].price + LZ4HC_sequencePrice(0, ml);
  1266. }
  1267. assert((U32)favorDecSpeed <= 1);
  1268. if (pos > last_match_pos+TRAILING_LITERALS
  1269. || price <= opt[pos].price - (int)favorDecSpeed) {
  1270. DEBUGLOG(7, "rPos:%3i => price:%3i (matchlen=%i)",
  1271. pos, price, ml);
  1272. assert(pos < LZ4_OPT_NUM);
  1273. if ( (ml == matchML) /* last pos of last match */
  1274. && (last_match_pos < pos) )
  1275. last_match_pos = pos;
  1276. opt[pos].mlen = ml;
  1277. opt[pos].off = offset;
  1278. opt[pos].litlen = ll;
  1279. opt[pos].price = price;
  1280. } } }
  1281. /* complete following positions with literals */
  1282. { int addLit;
  1283. for (addLit = 1; addLit <= TRAILING_LITERALS; addLit ++) {
  1284. opt[last_match_pos+addLit].mlen = 1; /* literal */
  1285. opt[last_match_pos+addLit].off = 0;
  1286. opt[last_match_pos+addLit].litlen = addLit;
  1287. opt[last_match_pos+addLit].price = opt[last_match_pos].price + LZ4HC_literalsPrice(addLit);
  1288. DEBUGLOG(7, "rPos:%3i => price:%3i (litlen=%i)", last_match_pos+addLit, opt[last_match_pos+addLit].price, addLit);
  1289. } }
  1290. } /* for (cur = 1; cur <= last_match_pos; cur++) */
  1291. assert(last_match_pos < LZ4_OPT_NUM + TRAILING_LITERALS);
  1292. best_mlen = opt[last_match_pos].mlen;
  1293. best_off = opt[last_match_pos].off;
  1294. cur = last_match_pos - best_mlen;
  1295. encode: /* cur, last_match_pos, best_mlen, best_off must be set */
  1296. assert(cur < LZ4_OPT_NUM);
  1297. assert(last_match_pos >= 1); /* == 1 when only one candidate */
  1298. DEBUGLOG(6, "reverse traversal, looking for shortest path (last_match_pos=%i)", last_match_pos);
  1299. { int candidate_pos = cur;
  1300. int selected_matchLength = best_mlen;
  1301. int selected_offset = best_off;
  1302. while (1) { /* from end to beginning */
  1303. int const next_matchLength = opt[candidate_pos].mlen; /* can be 1, means literal */
  1304. int const next_offset = opt[candidate_pos].off;
  1305. DEBUGLOG(7, "pos %i: sequence length %i", candidate_pos, selected_matchLength);
  1306. opt[candidate_pos].mlen = selected_matchLength;
  1307. opt[candidate_pos].off = selected_offset;
  1308. selected_matchLength = next_matchLength;
  1309. selected_offset = next_offset;
  1310. if (next_matchLength > candidate_pos) break; /* last match elected, first match to encode */
  1311. assert(next_matchLength > 0); /* can be 1, means literal */
  1312. candidate_pos -= next_matchLength;
  1313. } }
  1314. /* encode all recorded sequences in order */
  1315. { int rPos = 0; /* relative position (to ip) */
  1316. while (rPos < last_match_pos) {
  1317. int const ml = opt[rPos].mlen;
  1318. int const offset = opt[rPos].off;
  1319. if (ml == 1) { ip++; rPos++; continue; } /* literal; note: can end up with several literals, in which case, skip them */
  1320. rPos += ml;
  1321. assert(ml >= MINMATCH);
  1322. assert((offset >= 1) && (offset <= LZ4_DISTANCE_MAX));
  1323. opSaved = op;
  1324. if ( LZ4HC_encodeSequence(UPDATABLE(ip, op, anchor), ml, ip - offset, limit, oend) ) /* updates ip, op and anchor */
  1325. goto _dest_overflow;
  1326. } }
  1327. } /* while (ip <= mflimit) */
  1328. _last_literals:
  1329. /* Encode Last Literals */
  1330. { size_t lastRunSize = (size_t)(iend - anchor); /* literals */
  1331. size_t litLength = (lastRunSize + 255 - RUN_MASK) / 255;
  1332. size_t const totalSize = 1 + litLength + lastRunSize;
  1333. if (limit == fillOutput) oend += LASTLITERALS; /* restore correct value */
  1334. if (limit && (op + totalSize > oend)) {
  1335. if (limit == limitedOutput) return 0; /* Check output limit */
  1336. /* adapt lastRunSize to fill 'dst' */
  1337. lastRunSize = (size_t)(oend - op) - 1;
  1338. litLength = (lastRunSize + 255 - RUN_MASK) / 255;
  1339. lastRunSize -= litLength;
  1340. }
  1341. ip = anchor + lastRunSize;
  1342. if (lastRunSize >= RUN_MASK) {
  1343. size_t accumulator = lastRunSize - RUN_MASK;
  1344. *op++ = (RUN_MASK << ML_BITS);
  1345. for(; accumulator >= 255 ; accumulator -= 255) *op++ = 255;
  1346. *op++ = (BYTE) accumulator;
  1347. } else {
  1348. *op++ = (BYTE)(lastRunSize << ML_BITS);
  1349. }
  1350. memcpy(op, anchor, lastRunSize);
  1351. op += lastRunSize;
  1352. }
  1353. /* End */
  1354. *srcSizePtr = (int) (((const char*)ip) - source);
  1355. return (int) ((char*)op-dst);
  1356. _dest_overflow:
  1357. if (limit == fillOutput) {
  1358. op = opSaved; /* restore correct out pointer */
  1359. goto _last_literals;
  1360. }
  1361. return 0;
  1362. }