lz4hc.c 68 KB

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