lz4hc.c 75 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829
  1. /*
  2. LZ4 HC - High Compression Mode of LZ4
  3. Copyright (C) 2011-2017, Yann Collet.
  4. Adapted to CGo by Vadim Markovtsev, source{d} - 2018.
  5. BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
  6. Redistribution and use in source and binary forms, with or without
  7. modification, are permitted provided that the following conditions are
  8. met:
  9. * Redistributions of source code must retain the above copyright
  10. notice, this list of conditions and the following disclaimer.
  11. * Redistributions in binary form must reproduce the above
  12. copyright notice, this list of conditions and the following disclaimer
  13. in the documentation and/or other materials provided with the
  14. distribution.
  15. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  16. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  17. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  18. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  19. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  20. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  21. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  22. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  23. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  25. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. /*-************************************
  28. * Block Compression
  29. **************************************/
  30. /*! LZ4_compress_HC() :
  31. * Compress data from `src` into `dst`, using the more powerful but slower "HC" algorithm.
  32. * `dst` must be already allocated.
  33. * Compression is guaranteed to succeed if `dstCapacity >= LZ4_compressBound(srcSize)` (see "lz4.h")
  34. * Max supported `srcSize` value is LZ4_MAX_INPUT_SIZE (see "lz4.h")
  35. * @return : the number of bytes written into 'dst'
  36. * or 0 if compression fails.
  37. */
  38. int LZ4_compress_HC(const void* src, void* dst, int srcSize, int dstCapacity, int compressionLevel);
  39. /*! LZ4_decompress_fast() : **unsafe!**
  40. * This function used to be a bit faster than LZ4_decompress_safe(),
  41. * though situation has changed in recent versions,
  42. * and now `LZ4_decompress_safe()` can be as fast and sometimes faster than `LZ4_decompress_fast()`.
  43. * Moreover, LZ4_decompress_fast() is not protected vs malformed input, as it doesn't perform full validation of compressed data.
  44. * As a consequence, this function is no longer recommended, and may be deprecated in future versions.
  45. * It's only remaining specificity is that it can decompress data without knowing its compressed size.
  46. *
  47. * originalSize : is the uncompressed size to regenerate.
  48. * `dst` must be already allocated, its size must be >= 'originalSize' bytes.
  49. * @return : number of bytes read from source buffer (== compressed size).
  50. * If the source stream is detected malformed, the function stops decoding and returns a negative result.
  51. * note : This function requires uncompressed originalSize to be known in advance.
  52. * The function never writes past the output buffer.
  53. * However, since it doesn't know its 'src' size, it may read past the intended input.
  54. * Also, because match offsets are not validated during decoding,
  55. * reads from 'src' may underflow.
  56. * Use this function in trusted environment **only**.
  57. */
  58. int LZ4_decompress_fast(const void* source, void* dest, int originalSize);
  59. #define LZ4HC_HEAPMODE 1
  60. // Modern Intel CPUs have 32KB of L1
  61. #define LZ4_MEMORY_USAGE 15
  62. #ifdef __GNUC__
  63. #define LZ4_FORCE_INLINE static inline __attribute__((always_inline))
  64. #else
  65. #define LZ4_FORCE_INLINE static inline
  66. #endif
  67. /*-************************************
  68. * Memory routines
  69. **************************************/
  70. #include <stddef.h>
  71. #include <stdlib.h> /* malloc, calloc, free */
  72. #define ALLOC(s) malloc(s)
  73. #define ALLOC_AND_ZERO(s) calloc(1,s)
  74. #define FREEMEM(p) free(p)
  75. #include <string.h> /* memset, memcpy */
  76. #define MEM_INIT(p,v,s) memset((p),(v),(s))
  77. /*-************************************
  78. * Basic Types
  79. **************************************/
  80. #include <stdint.h>
  81. typedef uint8_t BYTE;
  82. typedef uint16_t U16;
  83. typedef uint32_t U32;
  84. typedef int32_t S32;
  85. typedef uint64_t U64;
  86. typedef uintptr_t uptrval;
  87. #if defined(__x86_64__)
  88. typedef U64 reg_t; /* 64-bits in x32 mode */
  89. #else
  90. typedef size_t reg_t; /* 32-bits in x32 mode */
  91. #endif
  92. /*-************************************
  93. * CPU Feature Detection
  94. **************************************/
  95. #define expect(expr,value) (__builtin_expect ((expr),(value)) )
  96. #ifndef likely
  97. #define likely(expr) expect((expr) != 0, 1)
  98. #endif
  99. #ifndef unlikely
  100. #define unlikely(expr) expect((expr) != 0, 0)
  101. #endif
  102. /* LZ4_FORCE_MEMORY_ACCESS
  103. * By default, access to unaligned memory is controlled by `memcpy()`, which is safe and portable.
  104. * Unfortunately, on some target/compiler combinations, the generated assembly is sub-optimal.
  105. * The below switch allow to select different access method for improved performance.
  106. * Method 0 (default) : use `memcpy()`. Safe and portable.
  107. * Method 1 : `__packed` statement. It depends on compiler extension (ie, not portable).
  108. * This method is safe if your compiler supports it, and *generally* as fast or faster than `memcpy`.
  109. * Method 2 : direct access. This method is portable but violate C standard.
  110. * It can generate buggy code on targets which assembly generation depends on alignment.
  111. * But in some circumstances, it's the only known way to get the most performance (ie GCC + ARMv6)
  112. * See https://fastcompression.blogspot.fr/2015/08/accessing-unaligned-memory.html for details.
  113. * Prefer these methods in priority order (0 > 1 > 2)
  114. */
  115. #ifndef LZ4_FORCE_MEMORY_ACCESS /* can be defined externally */
  116. # if defined(__GNUC__) && \
  117. ( defined(__ARM_ARCH_6__) || defined(__ARM_ARCH_6J__) || defined(__ARM_ARCH_6K__) \
  118. || defined(__ARM_ARCH_6Z__) || defined(__ARM_ARCH_6ZK__) || defined(__ARM_ARCH_6T2__) )
  119. # define LZ4_FORCE_MEMORY_ACCESS 2
  120. # elif (defined(__INTEL_COMPILER) && !defined(_WIN32)) || defined(__GNUC__)
  121. # define LZ4_FORCE_MEMORY_ACCESS 1
  122. # endif
  123. #endif
  124. /*-************************************
  125. * Reading and writing into memory
  126. **************************************/
  127. static unsigned LZ4_isLittleEndian(void)
  128. {
  129. const union { U32 u; BYTE c[4]; } one = { 1 }; /* don't use static : performance detrimental */
  130. return one.c[0];
  131. }
  132. #if defined(LZ4_FORCE_MEMORY_ACCESS) && (LZ4_FORCE_MEMORY_ACCESS==2)
  133. /* lie to the compiler about data alignment; use with caution */
  134. static U16 LZ4_read16(const void* memPtr) { return *(const U16*) memPtr; }
  135. static U32 LZ4_read32(const void* memPtr) { return *(const U32*) memPtr; }
  136. static reg_t LZ4_read_ARCH(const void* memPtr) { return *(const reg_t*) memPtr; }
  137. static void LZ4_write16(void* memPtr, U16 value) { *(U16*)memPtr = value; }
  138. static void LZ4_write32(void* memPtr, U32 value) { *(U32*)memPtr = value; }
  139. #elif defined(LZ4_FORCE_MEMORY_ACCESS) && (LZ4_FORCE_MEMORY_ACCESS==1)
  140. /* __pack instructions are safer, but compiler specific, hence potentially problematic for some compilers */
  141. /* currently only defined for gcc and icc */
  142. typedef union { U16 u16; U32 u32; reg_t uArch; } __attribute__((packed)) unalign;
  143. static U16 LZ4_read16(const void* ptr) { return ((const unalign*)ptr)->u16; }
  144. static U32 LZ4_read32(const void* ptr) { return ((const unalign*)ptr)->u32; }
  145. static reg_t LZ4_read_ARCH(const void* ptr) { return ((const unalign*)ptr)->uArch; }
  146. static void LZ4_write16(void* memPtr, U16 value) { ((unalign*)memPtr)->u16 = value; }
  147. static void LZ4_write32(void* memPtr, U32 value) { ((unalign*)memPtr)->u32 = value; }
  148. #else /* safe and portable access through memcpy() */
  149. static U16 LZ4_read16(const void* memPtr)
  150. {
  151. U16 val; memcpy(&val, memPtr, sizeof(val)); return val;
  152. }
  153. static U32 LZ4_read32(const void* memPtr)
  154. {
  155. U32 val; memcpy(&val, memPtr, sizeof(val)); return val;
  156. }
  157. static reg_t LZ4_read_ARCH(const void* memPtr)
  158. {
  159. reg_t val; memcpy(&val, memPtr, sizeof(val)); return val;
  160. }
  161. static void LZ4_write16(void* memPtr, U16 value)
  162. {
  163. memcpy(memPtr, &value, sizeof(value));
  164. }
  165. static void LZ4_write32(void* memPtr, U32 value)
  166. {
  167. memcpy(memPtr, &value, sizeof(value));
  168. }
  169. #endif /* LZ4_FORCE_MEMORY_ACCESS */
  170. static U16 LZ4_readLE16(const void* memPtr)
  171. {
  172. if (LZ4_isLittleEndian()) {
  173. return LZ4_read16(memPtr);
  174. } else {
  175. const BYTE* p = (const BYTE*)memPtr;
  176. return (U16)((U16)p[0] + (p[1]<<8));
  177. }
  178. }
  179. static void LZ4_writeLE16(void* memPtr, U16 value)
  180. {
  181. if (LZ4_isLittleEndian()) {
  182. LZ4_write16(memPtr, value);
  183. } else {
  184. BYTE* p = (BYTE*)memPtr;
  185. p[0] = (BYTE) value;
  186. p[1] = (BYTE)(value>>8);
  187. }
  188. }
  189. /* customized variant of memcpy, which can overwrite up to 8 bytes beyond dstEnd */
  190. LZ4_FORCE_INLINE
  191. void LZ4_wildCopy(void* dstPtr, const void* srcPtr, void* dstEnd)
  192. {
  193. BYTE* d = (BYTE*)dstPtr;
  194. const BYTE* s = (const BYTE*)srcPtr;
  195. BYTE* const e = (BYTE*)dstEnd;
  196. do { memcpy(d,s,8); d+=8; s+=8; } while (d<e);
  197. }
  198. #define assert(condition) ((void)0)
  199. #define DEBUGLOG(...) ((void)0)
  200. #define LZ4_STATIC_ASSERT(c) { enum { LZ4_static_assert = 1/(int)(!!(c)) }; } /* use after variable declarations */
  201. /*=== Constants ===*/
  202. #define OPTIMAL_ML (int)((ML_MASK-1)+MINMATCH)
  203. #define LZ4_OPT_NUM (1<<12)
  204. #define MINMATCH 4
  205. #define LZ4_MAX_INPUT_SIZE 0x7E000000 /* 2 113 929 216 bytes */
  206. #define LZ4_COMPRESSBOUND(isize) ((unsigned)(isize) > (unsigned)LZ4_MAX_INPUT_SIZE ? 0 : (isize) + ((isize)/255) + 16)
  207. #define WILDCOPYLENGTH 8
  208. #define LASTLITERALS 5 /* see ../doc/lz4_Block_format.md#parsing-restrictions */
  209. #define MFLIMIT 12 /* see ../doc/lz4_Block_format.md#parsing-restrictions */
  210. #define MATCH_SAFEGUARD_DISTANCE ((2*WILDCOPYLENGTH) - MINMATCH) /* ensure it's possible to write 2 x wildcopyLength without overflowing output buffer */
  211. static const int LZ4_minLength = (MFLIMIT+1);
  212. #define KB *(1 <<10)
  213. #define MB *(1 <<20)
  214. #define GB *(1U<<30)
  215. #define MAXD_LOG 16
  216. #define MAX_DISTANCE ((1 << MAXD_LOG) - 1)
  217. #define ML_BITS 4
  218. #define ML_MASK ((1U<<ML_BITS)-1)
  219. #define RUN_BITS (8-ML_BITS)
  220. #define RUN_MASK ((1U<<RUN_BITS)-1)
  221. int LZ4_compressBound(int isize) { return LZ4_COMPRESSBOUND(isize); }
  222. /*=== Enums ===*/
  223. typedef enum { noDictCtx, usingDictCtx } dictCtx_directive;
  224. #define LZ4HC_CLEVEL_MIN 3
  225. #define LZ4HC_CLEVEL_DEFAULT 9
  226. #define LZ4HC_CLEVEL_OPT_MIN 10
  227. #define LZ4HC_CLEVEL_MAX 12
  228. #define LZ4HC_DICTIONARY_LOGSIZE 16
  229. #define LZ4HC_MAXD (1<<LZ4HC_DICTIONARY_LOGSIZE)
  230. #define LZ4HC_MAXD_MASK (LZ4HC_MAXD - 1)
  231. #define LZ4HC_HASH_LOG 15
  232. #define LZ4HC_HASHTABLESIZE (1 << LZ4HC_HASH_LOG)
  233. #define LZ4HC_HASH_MASK (LZ4HC_HASHTABLESIZE - 1)
  234. typedef struct LZ4HC_CCtx_internal LZ4HC_CCtx_internal;
  235. struct LZ4HC_CCtx_internal
  236. {
  237. uint32_t hashTable[LZ4HC_HASHTABLESIZE];
  238. uint16_t chainTable[LZ4HC_MAXD];
  239. const uint8_t* end; /* next block here to continue on current prefix */
  240. const uint8_t* base; /* All index relative to this position */
  241. const uint8_t* dictBase; /* alternate base for extDict */
  242. uint32_t dictLimit; /* below that point, need extDict */
  243. uint32_t lowLimit; /* below that point, no more dict */
  244. uint32_t nextToUpdate; /* index from which to continue dictionary update */
  245. short compressionLevel;
  246. int8_t favorDecSpeed; /* favor decompression speed if this flag set,
  247. otherwise, favor compression ratio */
  248. int8_t dirty; /* stream has to be fully reset if this flag is set */
  249. const LZ4HC_CCtx_internal* dictCtx;
  250. };
  251. #define LZ4_STREAMHCSIZE (4*LZ4HC_HASHTABLESIZE + 2*LZ4HC_MAXD + 56 + ((sizeof(void*)==16) ? 56 : 0) /* AS400*/ ) /* 262200 or 262256*/
  252. #define LZ4_STREAMHCSIZE_SIZET (LZ4_STREAMHCSIZE / sizeof(size_t))
  253. union LZ4_streamHC_u {
  254. size_t table[LZ4_STREAMHCSIZE_SIZET];
  255. LZ4HC_CCtx_internal internal_donotuse;
  256. };
  257. typedef union LZ4_streamHC_u LZ4_streamHC_t;
  258. /*=== Macros ===*/
  259. #define MIN(a,b) ( (a) < (b) ? (a) : (b) )
  260. #define MAX(a,b) ( (a) > (b) ? (a) : (b) )
  261. #define HASH_FUNCTION(i) (((i) * 2654435761U) >> ((MINMATCH*8)-LZ4HC_HASH_LOG))
  262. #define DELTANEXTMAXD(p) chainTable[(p) & LZ4HC_MAXD_MASK] /* flexible, LZ4HC_MAXD dependent */
  263. #define DELTANEXTU16(table, pos) table[(U16)(pos)] /* faster */
  264. static U32 LZ4HC_hashPtr(const void* ptr) { return HASH_FUNCTION(LZ4_read32(ptr)); }
  265. /*-************************************
  266. * Common functions
  267. **************************************/
  268. static unsigned LZ4_NbCommonBytes (reg_t val)
  269. {
  270. if (LZ4_isLittleEndian()) {
  271. if (sizeof(val)==8) {
  272. # if defined(_MSC_VER) && defined(_WIN64) && !defined(LZ4_FORCE_SW_BITCOUNT)
  273. unsigned long r = 0;
  274. _BitScanForward64( &r, (U64)val );
  275. return (int)(r>>3);
  276. # elif (defined(__clang__) || (defined(__GNUC__) && (__GNUC__>=3))) && !defined(LZ4_FORCE_SW_BITCOUNT)
  277. return (__builtin_ctzll((U64)val) >> 3);
  278. # else
  279. static const int DeBruijnBytePos[64] = { 0, 0, 0, 0, 0, 1, 1, 2,
  280. 0, 3, 1, 3, 1, 4, 2, 7,
  281. 0, 2, 3, 6, 1, 5, 3, 5,
  282. 1, 3, 4, 4, 2, 5, 6, 7,
  283. 7, 0, 1, 2, 3, 3, 4, 6,
  284. 2, 6, 5, 5, 3, 4, 5, 6,
  285. 7, 1, 2, 4, 6, 4, 4, 5,
  286. 7, 2, 6, 5, 7, 6, 7, 7 };
  287. return DeBruijnBytePos[((U64)((val & -(long long)val) * 0x0218A392CDABBD3FULL)) >> 58];
  288. # endif
  289. } else /* 32 bits */ {
  290. # if defined(_MSC_VER) && !defined(LZ4_FORCE_SW_BITCOUNT)
  291. unsigned long r;
  292. _BitScanForward( &r, (U32)val );
  293. return (int)(r>>3);
  294. # elif (defined(__clang__) || (defined(__GNUC__) && (__GNUC__>=3))) && !defined(LZ4_FORCE_SW_BITCOUNT)
  295. return (__builtin_ctz((U32)val) >> 3);
  296. # else
  297. static const int DeBruijnBytePos[32] = { 0, 0, 3, 0, 3, 1, 3, 0,
  298. 3, 2, 2, 1, 3, 2, 0, 1,
  299. 3, 3, 1, 2, 2, 2, 2, 0,
  300. 3, 1, 2, 0, 1, 0, 1, 1 };
  301. return DeBruijnBytePos[((U32)((val & -(S32)val) * 0x077CB531U)) >> 27];
  302. # endif
  303. }
  304. } else /* Big Endian CPU */ {
  305. if (sizeof(val)==8) { /* 64-bits */
  306. # if defined(_MSC_VER) && defined(_WIN64) && !defined(LZ4_FORCE_SW_BITCOUNT)
  307. unsigned long r = 0;
  308. _BitScanReverse64( &r, val );
  309. return (unsigned)(r>>3);
  310. # elif (defined(__clang__) || (defined(__GNUC__) && (__GNUC__>=3))) && !defined(LZ4_FORCE_SW_BITCOUNT)
  311. return (__builtin_clzll((U64)val) >> 3);
  312. # else
  313. static const U32 by32 = sizeof(val)*4; /* 32 on 64 bits (goal), 16 on 32 bits.
  314. Just to avoid some static analyzer complaining about shift by 32 on 32-bits target.
  315. Note that this code path is never triggered in 32-bits mode. */
  316. unsigned r;
  317. if (!(val>>by32)) { r=4; } else { r=0; val>>=by32; }
  318. if (!(val>>16)) { r+=2; val>>=8; } else { val>>=24; }
  319. r += (!val);
  320. return r;
  321. # endif
  322. } else /* 32 bits */ {
  323. # if defined(_MSC_VER) && !defined(LZ4_FORCE_SW_BITCOUNT)
  324. unsigned long r = 0;
  325. _BitScanReverse( &r, (unsigned long)val );
  326. return (unsigned)(r>>3);
  327. # elif (defined(__clang__) || (defined(__GNUC__) && (__GNUC__>=3))) && !defined(LZ4_FORCE_SW_BITCOUNT)
  328. return (__builtin_clz((U32)val) >> 3);
  329. # else
  330. unsigned r;
  331. if (!(val>>16)) { r=2; val>>=8; } else { r=0; val>>=24; }
  332. r += (!val);
  333. return r;
  334. # endif
  335. }
  336. }
  337. }
  338. #define STEPSIZE sizeof(reg_t)
  339. LZ4_FORCE_INLINE
  340. unsigned LZ4_count(const BYTE* pIn, const BYTE* pMatch, const BYTE* pInLimit)
  341. {
  342. const BYTE* const pStart = pIn;
  343. if (likely(pIn < pInLimit-(STEPSIZE-1))) {
  344. reg_t const diff = LZ4_read_ARCH(pMatch) ^ LZ4_read_ARCH(pIn);
  345. if (!diff) {
  346. pIn+=STEPSIZE; pMatch+=STEPSIZE;
  347. } else {
  348. return LZ4_NbCommonBytes(diff);
  349. } }
  350. while (likely(pIn < pInLimit-(STEPSIZE-1))) {
  351. reg_t const diff = LZ4_read_ARCH(pMatch) ^ LZ4_read_ARCH(pIn);
  352. if (!diff) { pIn+=STEPSIZE; pMatch+=STEPSIZE; continue; }
  353. pIn += LZ4_NbCommonBytes(diff);
  354. return (unsigned)(pIn - pStart);
  355. }
  356. if ((STEPSIZE==8) && (pIn<(pInLimit-3)) && (LZ4_read32(pMatch) == LZ4_read32(pIn))) { pIn+=4; pMatch+=4; }
  357. if ((pIn<(pInLimit-1)) && (LZ4_read16(pMatch) == LZ4_read16(pIn))) { pIn+=2; pMatch+=2; }
  358. if ((pIn<pInLimit) && (*pMatch == *pIn)) pIn++;
  359. return (unsigned)(pIn - pStart);
  360. }
  361. /**************************************
  362. * HC Compression
  363. **************************************/
  364. static void LZ4HC_clearTables (LZ4HC_CCtx_internal* hc4)
  365. {
  366. MEM_INIT((void*)hc4->hashTable, 0, sizeof(hc4->hashTable));
  367. MEM_INIT(hc4->chainTable, 0xFF, sizeof(hc4->chainTable));
  368. }
  369. static void LZ4HC_init (LZ4HC_CCtx_internal* hc4, const BYTE* start)
  370. {
  371. uptrval startingOffset = hc4->end - hc4->base;
  372. if (startingOffset > 1 GB) {
  373. LZ4HC_clearTables(hc4);
  374. startingOffset = 0;
  375. }
  376. startingOffset += 64 KB;
  377. hc4->nextToUpdate = (U32) startingOffset;
  378. hc4->base = start - startingOffset;
  379. hc4->end = start;
  380. hc4->dictBase = start - startingOffset;
  381. hc4->dictLimit = (U32) startingOffset;
  382. hc4->lowLimit = (U32) startingOffset;
  383. }
  384. /* Update chains up to ip (excluded) */
  385. LZ4_FORCE_INLINE void LZ4HC_Insert (LZ4HC_CCtx_internal* hc4, const BYTE* ip)
  386. {
  387. U16* const chainTable = hc4->chainTable;
  388. U32* const hashTable = hc4->hashTable;
  389. const BYTE* const base = hc4->base;
  390. U32 const target = (U32)(ip - base);
  391. U32 idx = hc4->nextToUpdate;
  392. while (idx < target) {
  393. U32 const h = LZ4HC_hashPtr(base+idx);
  394. size_t delta = idx - hashTable[h];
  395. if (delta>MAX_DISTANCE) delta = MAX_DISTANCE;
  396. DELTANEXTU16(chainTable, idx) = (U16)delta;
  397. hashTable[h] = idx;
  398. idx++;
  399. }
  400. hc4->nextToUpdate = target;
  401. }
  402. static void LZ4HC_setExternalDict(LZ4HC_CCtx_internal* ctxPtr, const BYTE* newBlock)
  403. {
  404. DEBUGLOG(4, "LZ4HC_setExternalDict(%p, %p)", ctxPtr, newBlock);
  405. if (ctxPtr->end >= ctxPtr->base + ctxPtr->dictLimit + 4)
  406. LZ4HC_Insert (ctxPtr, ctxPtr->end-3); /* Referencing remaining dictionary content */
  407. /* Only one memory segment for extDict, so any previous extDict is lost at this stage */
  408. ctxPtr->lowLimit = ctxPtr->dictLimit;
  409. ctxPtr->dictLimit = (U32)(ctxPtr->end - ctxPtr->base);
  410. ctxPtr->dictBase = ctxPtr->base;
  411. ctxPtr->base = newBlock - ctxPtr->dictLimit;
  412. ctxPtr->end = newBlock;
  413. ctxPtr->nextToUpdate = ctxPtr->dictLimit; /* match referencing will resume from there */
  414. }
  415. /** LZ4HC_countBack() :
  416. * @return : negative value, nb of common bytes before ip/match */
  417. LZ4_FORCE_INLINE
  418. int LZ4HC_countBack(const BYTE* const ip, const BYTE* const match,
  419. const BYTE* const iMin, const BYTE* const mMin)
  420. {
  421. int back = 0;
  422. int const min = (int)MAX(iMin - ip, mMin - match);
  423. assert(min <= 0);
  424. assert(ip >= iMin); assert((size_t)(ip-iMin) < (1U<<31));
  425. assert(match >= mMin); assert((size_t)(match - mMin) < (1U<<31));
  426. while ( (back > min)
  427. && (ip[back-1] == match[back-1]) )
  428. back--;
  429. return back;
  430. }
  431. /* LZ4HC_countPattern() :
  432. * pattern32 must be a sample of repetitive pattern of length 1, 2 or 4 (but not 3!) */
  433. static unsigned
  434. LZ4HC_countPattern(const BYTE* ip, const BYTE* const iEnd, U32 const pattern32)
  435. {
  436. const BYTE* const iStart = ip;
  437. reg_t const pattern = (sizeof(pattern)==8) ? (reg_t)pattern32 + (((reg_t)pattern32) << 32) : pattern32;
  438. while (likely(ip < iEnd-(sizeof(pattern)-1))) {
  439. reg_t const diff = LZ4_read_ARCH(ip) ^ pattern;
  440. if (!diff) { ip+=sizeof(pattern); continue; }
  441. ip += LZ4_NbCommonBytes(diff);
  442. return (unsigned)(ip - iStart);
  443. }
  444. if (LZ4_isLittleEndian()) {
  445. reg_t patternByte = pattern;
  446. while ((ip<iEnd) && (*ip == (BYTE)patternByte)) {
  447. ip++; patternByte >>= 8;
  448. }
  449. } else { /* big endian */
  450. U32 bitOffset = (sizeof(pattern)*8) - 8;
  451. while (ip < iEnd) {
  452. BYTE const byte = (BYTE)(pattern >> bitOffset);
  453. if (*ip != byte) break;
  454. ip ++; bitOffset -= 8;
  455. }
  456. }
  457. return (unsigned)(ip - iStart);
  458. }
  459. /* LZ4HC_reverseCountPattern() :
  460. * pattern must be a sample of repetitive pattern of length 1, 2 or 4 (but not 3!)
  461. * read using natural platform endianess */
  462. static unsigned
  463. LZ4HC_reverseCountPattern(const BYTE* ip, const BYTE* const iLow, U32 pattern)
  464. {
  465. const BYTE* const iStart = ip;
  466. while (likely(ip >= iLow+4)) {
  467. if (LZ4_read32(ip-4) != pattern) break;
  468. ip -= 4;
  469. }
  470. { const BYTE* bytePtr = (const BYTE*)(&pattern) + 3; /* works for any endianess */
  471. while (likely(ip>iLow)) {
  472. if (ip[-1] != *bytePtr) break;
  473. ip--; bytePtr--;
  474. } }
  475. return (unsigned)(iStart - ip);
  476. }
  477. typedef enum { rep_untested, rep_not, rep_confirmed } repeat_state_e;
  478. typedef enum { favorCompressionRatio=0, favorDecompressionSpeed } HCfavor_e;
  479. LZ4_FORCE_INLINE int
  480. LZ4HC_InsertAndGetWiderMatch (
  481. LZ4HC_CCtx_internal* hc4,
  482. const BYTE* const ip,
  483. const BYTE* const iLowLimit,
  484. const BYTE* const iHighLimit,
  485. int longest,
  486. const BYTE** matchpos,
  487. const BYTE** startpos,
  488. const int maxNbAttempts,
  489. const int patternAnalysis,
  490. const int chainSwap,
  491. const dictCtx_directive dict,
  492. const HCfavor_e favorDecSpeed)
  493. {
  494. U16* const chainTable = hc4->chainTable;
  495. U32* const HashTable = hc4->hashTable;
  496. const LZ4HC_CCtx_internal * const dictCtx = hc4->dictCtx;
  497. const BYTE* const base = hc4->base;
  498. const U32 dictLimit = hc4->dictLimit;
  499. const BYTE* const lowPrefixPtr = base + dictLimit;
  500. const U32 ipIndex = (U32)(ip - base);
  501. const U32 lowestMatchIndex = (hc4->lowLimit + 64 KB > ipIndex) ? hc4->lowLimit : ipIndex - MAX_DISTANCE;
  502. const BYTE* const dictBase = hc4->dictBase;
  503. int const lookBackLength = (int)(ip-iLowLimit);
  504. int nbAttempts = maxNbAttempts;
  505. int matchChainPos = 0;
  506. U32 const pattern = LZ4_read32(ip);
  507. U32 matchIndex;
  508. U32 dictMatchIndex;
  509. repeat_state_e repeat = rep_untested;
  510. size_t srcPatternLength = 0;
  511. DEBUGLOG(7, "LZ4HC_InsertAndGetWiderMatch");
  512. /* First Match */
  513. LZ4HC_Insert(hc4, ip);
  514. matchIndex = HashTable[LZ4HC_hashPtr(ip)];
  515. DEBUGLOG(7, "First match at index %u / %u (lowestMatchIndex)",
  516. matchIndex, lowestMatchIndex);
  517. while ((matchIndex>=lowestMatchIndex) && (nbAttempts)) {
  518. int matchLength=0;
  519. nbAttempts--;
  520. assert(matchIndex < ipIndex);
  521. if (favorDecSpeed && (ipIndex - matchIndex < 8)) {
  522. /* do nothing */
  523. } else if (matchIndex >= dictLimit) { /* within current Prefix */
  524. const BYTE* const matchPtr = base + matchIndex;
  525. assert(matchPtr >= lowPrefixPtr);
  526. assert(matchPtr < ip);
  527. assert(longest >= 1);
  528. if (LZ4_read16(iLowLimit + longest - 1) == LZ4_read16(matchPtr - lookBackLength + longest - 1)) {
  529. if (LZ4_read32(matchPtr) == pattern) {
  530. int const back = lookBackLength ? LZ4HC_countBack(ip, matchPtr, iLowLimit, lowPrefixPtr) : 0;
  531. matchLength = MINMATCH + LZ4_count(ip+MINMATCH, matchPtr+MINMATCH, iHighLimit);
  532. matchLength -= back;
  533. if (matchLength > longest) {
  534. longest = matchLength;
  535. *matchpos = matchPtr + back;
  536. *startpos = ip + back;
  537. } } }
  538. } else { /* lowestMatchIndex <= matchIndex < dictLimit */
  539. const BYTE* const matchPtr = dictBase + matchIndex;
  540. if (LZ4_read32(matchPtr) == pattern) {
  541. const BYTE* const dictStart = dictBase + hc4->lowLimit;
  542. int back = 0;
  543. const BYTE* vLimit = ip + (dictLimit - matchIndex);
  544. if (vLimit > iHighLimit) vLimit = iHighLimit;
  545. matchLength = LZ4_count(ip+MINMATCH, matchPtr+MINMATCH, vLimit) + MINMATCH;
  546. if ((ip+matchLength == vLimit) && (vLimit < iHighLimit))
  547. matchLength += LZ4_count(ip+matchLength, lowPrefixPtr, iHighLimit);
  548. back = lookBackLength ? LZ4HC_countBack(ip, matchPtr, iLowLimit, dictStart) : 0;
  549. matchLength -= back;
  550. if (matchLength > longest) {
  551. longest = matchLength;
  552. *matchpos = base + matchIndex + back; /* virtual pos, relative to ip, to retrieve offset */
  553. *startpos = ip + back;
  554. } } }
  555. if (chainSwap && matchLength==longest) { /* better match => select a better chain */
  556. assert(lookBackLength==0); /* search forward only */
  557. if (matchIndex + longest <= ipIndex) {
  558. U32 distanceToNextMatch = 1;
  559. int pos;
  560. for (pos = 0; pos <= longest - MINMATCH; pos++) {
  561. U32 const candidateDist = DELTANEXTU16(chainTable, matchIndex + pos);
  562. if (candidateDist > distanceToNextMatch) {
  563. distanceToNextMatch = candidateDist;
  564. matchChainPos = pos;
  565. } }
  566. if (distanceToNextMatch > 1) {
  567. if (distanceToNextMatch > matchIndex) break; /* avoid overflow */
  568. matchIndex -= distanceToNextMatch;
  569. continue;
  570. } } }
  571. { U32 const distNextMatch = DELTANEXTU16(chainTable, matchIndex);
  572. if (patternAnalysis && distNextMatch==1 && matchChainPos==0) {
  573. U32 const matchCandidateIdx = matchIndex-1;
  574. /* may be a repeated pattern */
  575. if (repeat == rep_untested) {
  576. if ( ((pattern & 0xFFFF) == (pattern >> 16))
  577. & ((pattern & 0xFF) == (pattern >> 24)) ) {
  578. repeat = rep_confirmed;
  579. srcPatternLength = LZ4HC_countPattern(ip+sizeof(pattern), iHighLimit, pattern) + sizeof(pattern);
  580. } else {
  581. repeat = rep_not;
  582. } }
  583. if ( (repeat == rep_confirmed)
  584. && (matchCandidateIdx >= dictLimit) ) { /* same segment only */
  585. const BYTE* const matchPtr = base + matchCandidateIdx;
  586. if (LZ4_read32(matchPtr) == pattern) { /* good candidate */
  587. size_t const forwardPatternLength = LZ4HC_countPattern(matchPtr+sizeof(pattern), iHighLimit, pattern) + sizeof(pattern);
  588. const BYTE* const lowestMatchPtr = (lowPrefixPtr + MAX_DISTANCE >= ip) ? lowPrefixPtr : ip - MAX_DISTANCE;
  589. size_t const backLength = LZ4HC_reverseCountPattern(matchPtr, lowestMatchPtr, pattern);
  590. size_t const currentSegmentLength = backLength + forwardPatternLength;
  591. if ( (currentSegmentLength >= srcPatternLength) /* current pattern segment large enough to contain full srcPatternLength */
  592. && (forwardPatternLength <= srcPatternLength) ) { /* haven't reached this position yet */
  593. matchIndex = matchCandidateIdx + (U32)forwardPatternLength - (U32)srcPatternLength; /* best position, full pattern, might be followed by more match */
  594. } else {
  595. matchIndex = matchCandidateIdx - (U32)backLength; /* farthest position in current segment, will find a match of length currentSegmentLength + maybe some back */
  596. if (lookBackLength==0) { /* no back possible */
  597. size_t const maxML = MIN(currentSegmentLength, srcPatternLength);
  598. if ((size_t)longest < maxML) {
  599. assert(base + matchIndex < ip);
  600. if (ip - (base+matchIndex) > MAX_DISTANCE) break;
  601. assert(maxML < 2 GB);
  602. longest = (int)maxML;
  603. *matchpos = base + matchIndex; /* virtual pos, relative to ip, to retrieve offset */
  604. *startpos = ip;
  605. }
  606. { U32 const distToNextPattern = DELTANEXTU16(chainTable, matchIndex);
  607. if (distToNextPattern > matchIndex) break; /* avoid overflow */
  608. matchIndex -= distToNextPattern;
  609. } } }
  610. continue;
  611. } }
  612. } } /* PA optimization */
  613. /* follow current chain */
  614. matchIndex -= DELTANEXTU16(chainTable, matchIndex+matchChainPos);
  615. } /* while ((matchIndex>=lowestMatchIndex) && (nbAttempts)) */
  616. if (dict == usingDictCtx && nbAttempts && ipIndex - lowestMatchIndex < MAX_DISTANCE) {
  617. size_t const dictEndOffset = dictCtx->end - dictCtx->base;
  618. assert(dictEndOffset <= 1 GB);
  619. dictMatchIndex = dictCtx->hashTable[LZ4HC_hashPtr(ip)];
  620. matchIndex = dictMatchIndex + lowestMatchIndex - (U32)dictEndOffset;
  621. while (ipIndex - matchIndex <= MAX_DISTANCE && nbAttempts--) {
  622. const BYTE* const matchPtr = dictCtx->base + dictMatchIndex;
  623. if (LZ4_read32(matchPtr) == pattern) {
  624. int mlt;
  625. int back = 0;
  626. const BYTE* vLimit = ip + (dictEndOffset - dictMatchIndex);
  627. if (vLimit > iHighLimit) vLimit = iHighLimit;
  628. mlt = LZ4_count(ip+MINMATCH, matchPtr+MINMATCH, vLimit) + MINMATCH;
  629. back = lookBackLength ? LZ4HC_countBack(ip, matchPtr, iLowLimit, dictCtx->base + dictCtx->dictLimit) : 0;
  630. mlt -= back;
  631. if (mlt > longest) {
  632. longest = mlt;
  633. *matchpos = base + matchIndex + back;
  634. *startpos = ip + back;
  635. }
  636. }
  637. { U32 const nextOffset = DELTANEXTU16(dictCtx->chainTable, dictMatchIndex);
  638. dictMatchIndex -= nextOffset;
  639. matchIndex -= nextOffset;
  640. }
  641. }
  642. }
  643. return longest;
  644. }
  645. LZ4_FORCE_INLINE
  646. int LZ4HC_InsertAndFindBestMatch(LZ4HC_CCtx_internal* const hc4, /* Index table will be updated */
  647. const BYTE* const ip, const BYTE* const iLimit,
  648. const BYTE** matchpos,
  649. const int maxNbAttempts,
  650. const int patternAnalysis,
  651. const dictCtx_directive dict)
  652. {
  653. const BYTE* uselessPtr = ip;
  654. /* note : LZ4HC_InsertAndGetWiderMatch() is able to modify the starting position of a match (*startpos),
  655. * but this won't be the case here, as we define iLowLimit==ip,
  656. * so LZ4HC_InsertAndGetWiderMatch() won't be allowed to search past ip */
  657. return LZ4HC_InsertAndGetWiderMatch(hc4, ip, ip, iLimit, MINMATCH-1, matchpos, &uselessPtr, maxNbAttempts, patternAnalysis, 0 /*chainSwap*/, dict, favorCompressionRatio);
  658. }
  659. typedef enum {
  660. noLimit = 0,
  661. limitedOutput = 1,
  662. limitedDestSize = 2,
  663. } limitedOutput_directive;
  664. /* LZ4HC_encodeSequence() :
  665. * @return : 0 if ok,
  666. * 1 if buffer issue detected */
  667. LZ4_FORCE_INLINE int LZ4HC_encodeSequence (
  668. const BYTE** ip,
  669. BYTE** op,
  670. const BYTE** anchor,
  671. int matchLength,
  672. const BYTE* const match,
  673. limitedOutput_directive limit,
  674. BYTE* oend)
  675. {
  676. size_t length;
  677. BYTE* const token = (*op)++;
  678. #if defined(LZ4_DEBUG) && (LZ4_DEBUG >= 6)
  679. static const BYTE* start = NULL;
  680. static U32 totalCost = 0;
  681. U32 const pos = (start==NULL) ? 0 : (U32)(*anchor - start);
  682. U32 const ll = (U32)(*ip - *anchor);
  683. U32 const llAdd = (ll>=15) ? ((ll-15) / 255) + 1 : 0;
  684. U32 const mlAdd = (matchLength>=19) ? ((matchLength-19) / 255) + 1 : 0;
  685. U32 const cost = 1 + llAdd + ll + 2 + mlAdd;
  686. if (start==NULL) start = *anchor; /* only works for single segment */
  687. /* g_debuglog_enable = (pos >= 2228) & (pos <= 2262); */
  688. DEBUGLOG(6, "pos:%7u -- literals:%3u, match:%4i, offset:%5u, cost:%3u + %u",
  689. pos,
  690. (U32)(*ip - *anchor), matchLength, (U32)(*ip-match),
  691. cost, totalCost);
  692. totalCost += cost;
  693. #endif
  694. /* Encode Literal length */
  695. length = (size_t)(*ip - *anchor);
  696. if ((limit) && ((*op + (length >> 8) + length + (2 + 1 + LASTLITERALS)) > oend)) return 1; /* Check output limit */
  697. if (length >= RUN_MASK) {
  698. size_t len = length - RUN_MASK;
  699. *token = (RUN_MASK << ML_BITS);
  700. for(; len >= 255 ; len -= 255) *(*op)++ = 255;
  701. *(*op)++ = (BYTE)len;
  702. } else {
  703. *token = (BYTE)(length << ML_BITS);
  704. }
  705. /* Copy Literals */
  706. LZ4_wildCopy(*op, *anchor, (*op) + length);
  707. *op += length;
  708. /* Encode Offset */
  709. assert( (*ip - match) <= MAX_DISTANCE ); /* note : consider providing offset as a value, rather than as a pointer difference */
  710. LZ4_writeLE16(*op, (U16)(*ip-match)); *op += 2;
  711. /* Encode MatchLength */
  712. assert(matchLength >= MINMATCH);
  713. length = (size_t)(matchLength - MINMATCH);
  714. if ((limit) && (*op + (length >> 8) + (1 + LASTLITERALS) > oend)) return 1; /* Check output limit */
  715. if (length >= ML_MASK) {
  716. *token += ML_MASK;
  717. length -= ML_MASK;
  718. for(; length >= 510 ; length -= 510) { *(*op)++ = 255; *(*op)++ = 255; }
  719. if (length >= 255) { length -= 255; *(*op)++ = 255; }
  720. *(*op)++ = (BYTE)length;
  721. } else {
  722. *token += (BYTE)(length);
  723. }
  724. /* Prepare next loop */
  725. *ip += matchLength;
  726. *anchor = *ip;
  727. return 0;
  728. }
  729. LZ4_FORCE_INLINE int LZ4HC_compress_hashChain (
  730. LZ4HC_CCtx_internal* const ctx,
  731. const char* const source,
  732. char* const dest,
  733. int* srcSizePtr,
  734. int const maxOutputSize,
  735. unsigned maxNbAttempts,
  736. const limitedOutput_directive limit,
  737. const dictCtx_directive dict
  738. )
  739. {
  740. const int inputSize = *srcSizePtr;
  741. const int patternAnalysis = (maxNbAttempts > 128); /* levels 9+ */
  742. const BYTE* ip = (const BYTE*) source;
  743. const BYTE* anchor = ip;
  744. const BYTE* const iend = ip + inputSize;
  745. const BYTE* const mflimit = iend - MFLIMIT;
  746. const BYTE* const matchlimit = (iend - LASTLITERALS);
  747. BYTE* optr = (BYTE*) dest;
  748. BYTE* op = (BYTE*) dest;
  749. BYTE* oend = op + maxOutputSize;
  750. int ml0, ml, ml2, ml3;
  751. const BYTE* start0;
  752. const BYTE* ref0;
  753. const BYTE* ref = NULL;
  754. const BYTE* start2 = NULL;
  755. const BYTE* ref2 = NULL;
  756. const BYTE* start3 = NULL;
  757. const BYTE* ref3 = NULL;
  758. /* init */
  759. *srcSizePtr = 0;
  760. if (limit == limitedDestSize) oend -= LASTLITERALS; /* Hack for support LZ4 format restriction */
  761. if (inputSize < LZ4_minLength) goto _last_literals; /* Input too small, no compression (all literals) */
  762. /* Main Loop */
  763. while (ip <= mflimit) {
  764. ml = LZ4HC_InsertAndFindBestMatch (ctx, ip, matchlimit, &ref, maxNbAttempts, patternAnalysis, dict);
  765. if (ml<MINMATCH) { ip++; continue; }
  766. /* saved, in case we would skip too much */
  767. start0 = ip; ref0 = ref; ml0 = ml;
  768. _Search2:
  769. if (ip+ml <= mflimit) {
  770. ml2 = LZ4HC_InsertAndGetWiderMatch(ctx,
  771. ip + ml - 2, ip + 0, matchlimit, ml, &ref2, &start2,
  772. maxNbAttempts, patternAnalysis, 0, dict, favorCompressionRatio);
  773. } else {
  774. ml2 = ml;
  775. }
  776. if (ml2 == ml) { /* No better match => encode ML1 */
  777. optr = op;
  778. if (LZ4HC_encodeSequence(&ip, &op, &anchor, ml, ref, limit, oend)) goto _dest_overflow;
  779. continue;
  780. }
  781. if (start0 < ip) { /* first match was skipped at least once */
  782. if (start2 < ip + ml0) { /* squeezing ML1 between ML0(original ML1) and ML2 */
  783. ip = start0; ref = ref0; ml = ml0; /* restore initial ML1 */
  784. } }
  785. /* Here, start0==ip */
  786. if ((start2 - ip) < 3) { /* First Match too small : removed */
  787. ml = ml2;
  788. ip = start2;
  789. ref =ref2;
  790. goto _Search2;
  791. }
  792. _Search3:
  793. /* At this stage, we have :
  794. * ml2 > ml1, and
  795. * ip1+3 <= ip2 (usually < ip1+ml1) */
  796. if ((start2 - ip) < OPTIMAL_ML) {
  797. int correction;
  798. int new_ml = ml;
  799. if (new_ml > OPTIMAL_ML) new_ml = OPTIMAL_ML;
  800. if (ip+new_ml > start2 + ml2 - MINMATCH) new_ml = (int)(start2 - ip) + ml2 - MINMATCH;
  801. correction = new_ml - (int)(start2 - ip);
  802. if (correction > 0) {
  803. start2 += correction;
  804. ref2 += correction;
  805. ml2 -= correction;
  806. }
  807. }
  808. /* Now, we have start2 = ip+new_ml, with new_ml = min(ml, OPTIMAL_ML=18) */
  809. if (start2 + ml2 <= mflimit) {
  810. ml3 = LZ4HC_InsertAndGetWiderMatch(ctx,
  811. start2 + ml2 - 3, start2, matchlimit, ml2, &ref3, &start3,
  812. maxNbAttempts, patternAnalysis, 0, dict, favorCompressionRatio);
  813. } else {
  814. ml3 = ml2;
  815. }
  816. if (ml3 == ml2) { /* No better match => encode ML1 and ML2 */
  817. /* ip & ref are known; Now for ml */
  818. if (start2 < ip+ml) ml = (int)(start2 - ip);
  819. /* Now, encode 2 sequences */
  820. optr = op;
  821. if (LZ4HC_encodeSequence(&ip, &op, &anchor, ml, ref, limit, oend)) goto _dest_overflow;
  822. ip = start2;
  823. optr = op;
  824. if (LZ4HC_encodeSequence(&ip, &op, &anchor, ml2, ref2, limit, oend)) goto _dest_overflow;
  825. continue;
  826. }
  827. if (start3 < ip+ml+3) { /* Not enough space for match 2 : remove it */
  828. if (start3 >= (ip+ml)) { /* can write Seq1 immediately ==> Seq2 is removed, so Seq3 becomes Seq1 */
  829. if (start2 < ip+ml) {
  830. int correction = (int)(ip+ml - start2);
  831. start2 += correction;
  832. ref2 += correction;
  833. ml2 -= correction;
  834. if (ml2 < MINMATCH) {
  835. start2 = start3;
  836. ref2 = ref3;
  837. ml2 = ml3;
  838. }
  839. }
  840. optr = op;
  841. if (LZ4HC_encodeSequence(&ip, &op, &anchor, ml, ref, limit, oend)) goto _dest_overflow;
  842. ip = start3;
  843. ref = ref3;
  844. ml = ml3;
  845. start0 = start2;
  846. ref0 = ref2;
  847. ml0 = ml2;
  848. goto _Search2;
  849. }
  850. start2 = start3;
  851. ref2 = ref3;
  852. ml2 = ml3;
  853. goto _Search3;
  854. }
  855. /*
  856. * OK, now we have 3 ascending matches;
  857. * let's write the first one ML1.
  858. * ip & ref are known; Now decide ml.
  859. */
  860. if (start2 < ip+ml) {
  861. if ((start2 - ip) < OPTIMAL_ML) {
  862. int correction;
  863. if (ml > OPTIMAL_ML) ml = OPTIMAL_ML;
  864. if (ip + ml > start2 + ml2 - MINMATCH) ml = (int)(start2 - ip) + ml2 - MINMATCH;
  865. correction = ml - (int)(start2 - ip);
  866. if (correction > 0) {
  867. start2 += correction;
  868. ref2 += correction;
  869. ml2 -= correction;
  870. }
  871. } else {
  872. ml = (int)(start2 - ip);
  873. }
  874. }
  875. optr = op;
  876. if (LZ4HC_encodeSequence(&ip, &op, &anchor, ml, ref, limit, oend)) goto _dest_overflow;
  877. /* ML2 becomes ML1 */
  878. ip = start2; ref = ref2; ml = ml2;
  879. /* ML3 becomes ML2 */
  880. start2 = start3; ref2 = ref3; ml2 = ml3;
  881. /* let's find a new ML3 */
  882. goto _Search3;
  883. }
  884. _last_literals:
  885. /* Encode Last Literals */
  886. { size_t lastRunSize = (size_t)(iend - anchor); /* literals */
  887. size_t litLength = (lastRunSize + 255 - RUN_MASK) / 255;
  888. size_t const totalSize = 1 + litLength + lastRunSize;
  889. if (limit == limitedDestSize) oend += LASTLITERALS; /* restore correct value */
  890. if (limit && (op + totalSize > oend)) {
  891. if (limit == limitedOutput) return 0; /* Check output limit */
  892. /* adapt lastRunSize to fill 'dest' */
  893. lastRunSize = (size_t)(oend - op) - 1;
  894. litLength = (lastRunSize + 255 - RUN_MASK) / 255;
  895. lastRunSize -= litLength;
  896. }
  897. ip = anchor + lastRunSize;
  898. if (lastRunSize >= RUN_MASK) {
  899. size_t accumulator = lastRunSize - RUN_MASK;
  900. *op++ = (RUN_MASK << ML_BITS);
  901. for(; accumulator >= 255 ; accumulator -= 255) *op++ = 255;
  902. *op++ = (BYTE) accumulator;
  903. } else {
  904. *op++ = (BYTE)(lastRunSize << ML_BITS);
  905. }
  906. memcpy(op, anchor, lastRunSize);
  907. op += lastRunSize;
  908. }
  909. /* End */
  910. *srcSizePtr = (int) (((const char*)ip) - source);
  911. return (int) (((char*)op)-dest);
  912. _dest_overflow:
  913. if (limit == limitedDestSize) {
  914. op = optr; /* restore correct out pointer */
  915. goto _last_literals;
  916. }
  917. return 0;
  918. }
  919. static int LZ4HC_compress_optimal( LZ4HC_CCtx_internal* ctx,
  920. const char* const source, char* dst,
  921. int* srcSizePtr, int dstCapacity,
  922. int const nbSearches, size_t sufficient_len,
  923. const limitedOutput_directive limit, int const fullUpdate,
  924. const dictCtx_directive dict,
  925. HCfavor_e favorDecSpeed);
  926. LZ4_FORCE_INLINE int LZ4HC_compress_generic_internal (
  927. LZ4HC_CCtx_internal* const ctx,
  928. const char* const src,
  929. char* const dst,
  930. int* const srcSizePtr,
  931. int const dstCapacity,
  932. int cLevel,
  933. const limitedOutput_directive limit,
  934. const dictCtx_directive dict
  935. )
  936. {
  937. typedef enum { lz4hc, lz4opt } lz4hc_strat_e;
  938. typedef struct {
  939. lz4hc_strat_e strat;
  940. U32 nbSearches;
  941. U32 targetLength;
  942. } cParams_t;
  943. static const cParams_t clTable[LZ4HC_CLEVEL_MAX+1] = {
  944. { lz4hc, 2, 16 }, /* 0, unused */
  945. { lz4hc, 2, 16 }, /* 1, unused */
  946. { lz4hc, 2, 16 }, /* 2, unused */
  947. { lz4hc, 4, 16 }, /* 3 */
  948. { lz4hc, 8, 16 }, /* 4 */
  949. { lz4hc, 16, 16 }, /* 5 */
  950. { lz4hc, 32, 16 }, /* 6 */
  951. { lz4hc, 64, 16 }, /* 7 */
  952. { lz4hc, 128, 16 }, /* 8 */
  953. { lz4hc, 256, 16 }, /* 9 */
  954. { lz4opt, 96, 64 }, /*10==LZ4HC_CLEVEL_OPT_MIN*/
  955. { lz4opt, 512,128 }, /*11 */
  956. { lz4opt,16384,LZ4_OPT_NUM }, /* 12==LZ4HC_CLEVEL_MAX */
  957. };
  958. DEBUGLOG(4, "LZ4HC_compress_generic(%p, %p, %d)", ctx, src, *srcSizePtr);
  959. if (limit == limitedDestSize && dstCapacity < 1) return 0; /* Impossible to store anything */
  960. if ((U32)*srcSizePtr > (U32)LZ4_MAX_INPUT_SIZE) return 0; /* Unsupported input size (too large or negative) */
  961. ctx->end += *srcSizePtr;
  962. if (cLevel < 1) cLevel = LZ4HC_CLEVEL_DEFAULT; /* note : convention is different from lz4frame, maybe something to review */
  963. cLevel = MIN(LZ4HC_CLEVEL_MAX, cLevel);
  964. { cParams_t const cParam = clTable[cLevel];
  965. HCfavor_e const favor = ctx->favorDecSpeed ? favorDecompressionSpeed : favorCompressionRatio;
  966. if (cParam.strat == lz4hc)
  967. return LZ4HC_compress_hashChain(ctx,
  968. src, dst, srcSizePtr, dstCapacity,
  969. cParam.nbSearches, limit, dict);
  970. assert(cParam.strat == lz4opt);
  971. return LZ4HC_compress_optimal(ctx,
  972. src, dst, srcSizePtr, dstCapacity,
  973. cParam.nbSearches, cParam.targetLength, limit,
  974. cLevel == LZ4HC_CLEVEL_MAX, /* ultra mode */
  975. dict, favor);
  976. }
  977. }
  978. static void LZ4HC_setExternalDict(LZ4HC_CCtx_internal* ctxPtr, const BYTE* newBlock);
  979. static int LZ4HC_compress_generic_noDictCtx (
  980. LZ4HC_CCtx_internal* const ctx,
  981. const char* const src,
  982. char* const dst,
  983. int* const srcSizePtr,
  984. int const dstCapacity,
  985. int cLevel,
  986. limitedOutput_directive limit
  987. )
  988. {
  989. assert(ctx->dictCtx == NULL);
  990. return LZ4HC_compress_generic_internal(ctx, src, dst, srcSizePtr, dstCapacity, cLevel, limit, noDictCtx);
  991. }
  992. static int LZ4HC_compress_generic_dictCtx (
  993. LZ4HC_CCtx_internal* const ctx,
  994. const char* const src,
  995. char* const dst,
  996. int* const srcSizePtr,
  997. int const dstCapacity,
  998. int cLevel,
  999. limitedOutput_directive limit
  1000. )
  1001. {
  1002. const size_t position = ctx->end - ctx->base - ctx->lowLimit;
  1003. assert(ctx->dictCtx != NULL);
  1004. if (position >= 64 KB) {
  1005. ctx->dictCtx = NULL;
  1006. return LZ4HC_compress_generic_noDictCtx(ctx, src, dst, srcSizePtr, dstCapacity, cLevel, limit);
  1007. } else if (position == 0 && *srcSizePtr > 4 KB) {
  1008. memcpy(ctx, ctx->dictCtx, sizeof(LZ4HC_CCtx_internal));
  1009. LZ4HC_setExternalDict(ctx, (const BYTE *)src);
  1010. ctx->compressionLevel = (short)cLevel;
  1011. return LZ4HC_compress_generic_noDictCtx(ctx, src, dst, srcSizePtr, dstCapacity, cLevel, limit);
  1012. } else {
  1013. return LZ4HC_compress_generic_internal(ctx, src, dst, srcSizePtr, dstCapacity, cLevel, limit, usingDictCtx);
  1014. }
  1015. }
  1016. static int LZ4HC_compress_generic (
  1017. LZ4HC_CCtx_internal* const ctx,
  1018. const char* const src,
  1019. char* const dst,
  1020. int* const srcSizePtr,
  1021. int const dstCapacity,
  1022. int cLevel,
  1023. limitedOutput_directive limit
  1024. )
  1025. {
  1026. if (ctx->dictCtx == NULL) {
  1027. return LZ4HC_compress_generic_noDictCtx(ctx, src, dst, srcSizePtr, dstCapacity, cLevel, limit);
  1028. } else {
  1029. return LZ4HC_compress_generic_dictCtx(ctx, src, dst, srcSizePtr, dstCapacity, cLevel, limit);
  1030. }
  1031. }
  1032. static void LZ4_setCompressionLevel(LZ4_streamHC_t* LZ4_streamHCPtr, int compressionLevel)
  1033. {
  1034. if (compressionLevel < 1) compressionLevel = LZ4HC_CLEVEL_DEFAULT;
  1035. if (compressionLevel > LZ4HC_CLEVEL_MAX) compressionLevel = LZ4HC_CLEVEL_MAX;
  1036. LZ4_streamHCPtr->internal_donotuse.compressionLevel = (short)compressionLevel;
  1037. }
  1038. static void LZ4_resetStreamHC (LZ4_streamHC_t* LZ4_streamHCPtr, int compressionLevel)
  1039. {
  1040. LZ4_STATIC_ASSERT(sizeof(LZ4HC_CCtx_internal) <= sizeof(size_t) * LZ4_STREAMHCSIZE_SIZET); /* if compilation fails here, LZ4_STREAMHCSIZE must be increased */
  1041. DEBUGLOG(4, "LZ4_resetStreamHC(%p, %d)", LZ4_streamHCPtr, compressionLevel);
  1042. LZ4_streamHCPtr->internal_donotuse.end = (const BYTE *)(ptrdiff_t)-1;
  1043. LZ4_streamHCPtr->internal_donotuse.base = NULL;
  1044. LZ4_streamHCPtr->internal_donotuse.dictCtx = NULL;
  1045. LZ4_streamHCPtr->internal_donotuse.favorDecSpeed = 0;
  1046. LZ4_streamHCPtr->internal_donotuse.dirty = 0;
  1047. LZ4_setCompressionLevel(LZ4_streamHCPtr, compressionLevel);
  1048. }
  1049. static void LZ4_resetStreamHC_fast (LZ4_streamHC_t* LZ4_streamHCPtr, int compressionLevel)
  1050. {
  1051. DEBUGLOG(4, "LZ4_resetStreamHC_fast(%p, %d)", LZ4_streamHCPtr, compressionLevel);
  1052. if (LZ4_streamHCPtr->internal_donotuse.dirty) {
  1053. LZ4_resetStreamHC(LZ4_streamHCPtr, compressionLevel);
  1054. } else {
  1055. LZ4_streamHCPtr->internal_donotuse.end -= (uptrval)LZ4_streamHCPtr->internal_donotuse.base;
  1056. LZ4_streamHCPtr->internal_donotuse.base = NULL;
  1057. LZ4_streamHCPtr->internal_donotuse.dictCtx = NULL;
  1058. LZ4_setCompressionLevel(LZ4_streamHCPtr, compressionLevel);
  1059. }
  1060. }
  1061. static int LZ4_compress_HC_extStateHC_fastReset (void* state, const char* src, char* dst, int srcSize, int dstCapacity, int compressionLevel)
  1062. {
  1063. LZ4HC_CCtx_internal* const ctx = &((LZ4_streamHC_t*)state)->internal_donotuse;
  1064. if (((size_t)(state)&(sizeof(void*)-1)) != 0) return 0; /* Error : state is not aligned for pointers (32 or 64 bits) */
  1065. LZ4_resetStreamHC_fast((LZ4_streamHC_t*)state, compressionLevel);
  1066. LZ4HC_init (ctx, (const BYTE*)src);
  1067. if (dstCapacity < LZ4_compressBound(srcSize))
  1068. return LZ4HC_compress_generic (ctx, src, dst, &srcSize, dstCapacity, compressionLevel, limitedOutput);
  1069. else
  1070. return LZ4HC_compress_generic (ctx, src, dst, &srcSize, dstCapacity, compressionLevel, noLimit);
  1071. }
  1072. static int LZ4_compress_HC_extStateHC (void* state, const char* src, char* dst, int srcSize, int dstCapacity, int compressionLevel)
  1073. {
  1074. if (((size_t)(state)&(sizeof(void*)-1)) != 0) return 0; /* Error : state is not aligned for pointers (32 or 64 bits) */
  1075. LZ4_resetStreamHC ((LZ4_streamHC_t*)state, compressionLevel);
  1076. return LZ4_compress_HC_extStateHC_fastReset(state, src, dst, srcSize, dstCapacity, compressionLevel);
  1077. }
  1078. int LZ4_compress_HC(const void* src, void* dst, int srcSize, int dstCapacity, int compressionLevel)
  1079. {
  1080. #if defined(LZ4HC_HEAPMODE) && LZ4HC_HEAPMODE==1
  1081. LZ4_streamHC_t* const statePtr = (LZ4_streamHC_t*)ALLOC(sizeof(LZ4_streamHC_t));
  1082. #else
  1083. LZ4_streamHC_t state;
  1084. LZ4_streamHC_t* const statePtr = &state;
  1085. #endif
  1086. int const cSize = LZ4_compress_HC_extStateHC(statePtr, src, dst, srcSize, dstCapacity, compressionLevel);
  1087. #if defined(LZ4HC_HEAPMODE) && LZ4HC_HEAPMODE==1
  1088. free(statePtr);
  1089. #endif
  1090. return cSize;
  1091. }
  1092. /* LZ4_compress_HC_destSize() :
  1093. * only compatible with regular HC parser */
  1094. static int LZ4_compress_HC_destSize(void* LZ4HC_Data, const char* source, char* dest, int* sourceSizePtr, int targetDestSize, int cLevel)
  1095. {
  1096. LZ4HC_CCtx_internal* const ctx = &((LZ4_streamHC_t*)LZ4HC_Data)->internal_donotuse;
  1097. LZ4_resetStreamHC((LZ4_streamHC_t*)LZ4HC_Data, cLevel);
  1098. LZ4HC_init(ctx, (const BYTE*) source);
  1099. return LZ4HC_compress_generic(ctx, source, dest, sourceSizePtr, targetDestSize, cLevel, limitedDestSize);
  1100. }
  1101. /* ================================================
  1102. * LZ4 Optimal parser (levels 10-12)
  1103. * ===============================================*/
  1104. typedef struct {
  1105. int price;
  1106. int off;
  1107. int mlen;
  1108. int litlen;
  1109. } LZ4HC_optimal_t;
  1110. /* price in bytes */
  1111. LZ4_FORCE_INLINE int LZ4HC_literalsPrice(int const litlen)
  1112. {
  1113. int price = litlen;
  1114. if (litlen >= (int)RUN_MASK)
  1115. price += 1 + (litlen-RUN_MASK)/255;
  1116. return price;
  1117. }
  1118. /* requires mlen >= MINMATCH */
  1119. LZ4_FORCE_INLINE int LZ4HC_sequencePrice(int litlen, int mlen)
  1120. {
  1121. int price = 1 + 2 ; /* token + 16-bit offset */
  1122. price += LZ4HC_literalsPrice(litlen);
  1123. if (mlen >= (int)(ML_MASK+MINMATCH))
  1124. price += 1 + (mlen-(ML_MASK+MINMATCH))/255;
  1125. return price;
  1126. }
  1127. typedef struct {
  1128. int off;
  1129. int len;
  1130. } LZ4HC_match_t;
  1131. LZ4_FORCE_INLINE LZ4HC_match_t
  1132. LZ4HC_FindLongerMatch(LZ4HC_CCtx_internal* const ctx,
  1133. const BYTE* ip, const BYTE* const iHighLimit,
  1134. int minLen, int nbSearches,
  1135. const dictCtx_directive dict,
  1136. const HCfavor_e favorDecSpeed)
  1137. {
  1138. LZ4HC_match_t match = { 0 , 0 };
  1139. const BYTE* matchPtr = NULL;
  1140. /* note : LZ4HC_InsertAndGetWiderMatch() is able to modify the starting position of a match (*startpos),
  1141. * but this won't be the case here, as we define iLowLimit==ip,
  1142. * so LZ4HC_InsertAndGetWiderMatch() won't be allowed to search past ip */
  1143. int matchLength = LZ4HC_InsertAndGetWiderMatch(ctx, ip, ip, iHighLimit, minLen, &matchPtr, &ip, nbSearches, 1 /*patternAnalysis*/, 1 /*chainSwap*/, dict, favorDecSpeed);
  1144. if (matchLength <= minLen) return match;
  1145. if (favorDecSpeed) {
  1146. if ((matchLength>18) & (matchLength<=36)) matchLength=18; /* favor shortcut */
  1147. }
  1148. match.len = matchLength;
  1149. match.off = (int)(ip-matchPtr);
  1150. return match;
  1151. }
  1152. static int LZ4HC_compress_optimal ( LZ4HC_CCtx_internal* ctx,
  1153. const char* const source,
  1154. char* dst,
  1155. int* srcSizePtr,
  1156. int dstCapacity,
  1157. int const nbSearches,
  1158. size_t sufficient_len,
  1159. const limitedOutput_directive limit,
  1160. int const fullUpdate,
  1161. const dictCtx_directive dict,
  1162. const HCfavor_e favorDecSpeed)
  1163. {
  1164. #define TRAILING_LITERALS 3
  1165. LZ4HC_optimal_t opt[LZ4_OPT_NUM + TRAILING_LITERALS]; /* ~64 KB, which is a bit large for stack... */
  1166. const BYTE* ip = (const BYTE*) source;
  1167. const BYTE* anchor = ip;
  1168. const BYTE* const iend = ip + *srcSizePtr;
  1169. const BYTE* const mflimit = iend - MFLIMIT;
  1170. const BYTE* const matchlimit = iend - LASTLITERALS;
  1171. BYTE* op = (BYTE*) dst;
  1172. BYTE* opSaved = (BYTE*) dst;
  1173. BYTE* oend = op + dstCapacity;
  1174. /* init */
  1175. DEBUGLOG(5, "LZ4HC_compress_optimal");
  1176. *srcSizePtr = 0;
  1177. if (limit == limitedDestSize) oend -= LASTLITERALS; /* Hack for support LZ4 format restriction */
  1178. if (sufficient_len >= LZ4_OPT_NUM) sufficient_len = LZ4_OPT_NUM-1;
  1179. /* Main Loop */
  1180. assert(ip - anchor < LZ4_MAX_INPUT_SIZE);
  1181. while (ip <= mflimit) {
  1182. int const llen = (int)(ip - anchor);
  1183. int best_mlen, best_off;
  1184. int cur, last_match_pos = 0;
  1185. LZ4HC_match_t const firstMatch = LZ4HC_FindLongerMatch(ctx, ip, matchlimit, MINMATCH-1, nbSearches, dict, favorDecSpeed);
  1186. if (firstMatch.len==0) { ip++; continue; }
  1187. if ((size_t)firstMatch.len > sufficient_len) {
  1188. /* good enough solution : immediate encoding */
  1189. int const firstML = firstMatch.len;
  1190. const BYTE* const matchPos = ip - firstMatch.off;
  1191. opSaved = op;
  1192. if ( LZ4HC_encodeSequence(&ip, &op, &anchor, firstML, matchPos, limit, oend) ) /* updates ip, op and anchor */
  1193. goto _dest_overflow;
  1194. continue;
  1195. }
  1196. /* set prices for first positions (literals) */
  1197. { int rPos;
  1198. for (rPos = 0 ; rPos < MINMATCH ; rPos++) {
  1199. int const cost = LZ4HC_literalsPrice(llen + rPos);
  1200. opt[rPos].mlen = 1;
  1201. opt[rPos].off = 0;
  1202. opt[rPos].litlen = llen + rPos;
  1203. opt[rPos].price = cost;
  1204. DEBUGLOG(7, "rPos:%3i => price:%3i (litlen=%i) -- initial setup",
  1205. rPos, cost, opt[rPos].litlen);
  1206. } }
  1207. /* set prices using initial match */
  1208. { int mlen = MINMATCH;
  1209. int const matchML = firstMatch.len; /* necessarily < sufficient_len < LZ4_OPT_NUM */
  1210. int const offset = firstMatch.off;
  1211. assert(matchML < LZ4_OPT_NUM);
  1212. for ( ; mlen <= matchML ; mlen++) {
  1213. int const cost = LZ4HC_sequencePrice(llen, mlen);
  1214. opt[mlen].mlen = mlen;
  1215. opt[mlen].off = offset;
  1216. opt[mlen].litlen = llen;
  1217. opt[mlen].price = cost;
  1218. DEBUGLOG(7, "rPos:%3i => price:%3i (matchlen=%i) -- initial setup",
  1219. mlen, cost, mlen);
  1220. } }
  1221. last_match_pos = firstMatch.len;
  1222. { int addLit;
  1223. for (addLit = 1; addLit <= TRAILING_LITERALS; addLit ++) {
  1224. opt[last_match_pos+addLit].mlen = 1; /* literal */
  1225. opt[last_match_pos+addLit].off = 0;
  1226. opt[last_match_pos+addLit].litlen = addLit;
  1227. opt[last_match_pos+addLit].price = opt[last_match_pos].price + LZ4HC_literalsPrice(addLit);
  1228. DEBUGLOG(7, "rPos:%3i => price:%3i (litlen=%i) -- initial setup",
  1229. last_match_pos+addLit, opt[last_match_pos+addLit].price, addLit);
  1230. } }
  1231. /* check further positions */
  1232. for (cur = 1; cur < last_match_pos; cur++) {
  1233. const BYTE* const curPtr = ip + cur;
  1234. LZ4HC_match_t newMatch;
  1235. if (curPtr > mflimit) break;
  1236. DEBUGLOG(7, "rPos:%u[%u] vs [%u]%u",
  1237. cur, opt[cur].price, opt[cur+1].price, cur+1);
  1238. if (fullUpdate) {
  1239. /* not useful to search here if next position has same (or lower) cost */
  1240. if ( (opt[cur+1].price <= opt[cur].price)
  1241. /* in some cases, next position has same cost, but cost rises sharply after, so a small match would still be beneficial */
  1242. && (opt[cur+MINMATCH].price < opt[cur].price + 3/*min seq price*/) )
  1243. continue;
  1244. } else {
  1245. /* not useful to search here if next position has same (or lower) cost */
  1246. if (opt[cur+1].price <= opt[cur].price) continue;
  1247. }
  1248. DEBUGLOG(7, "search at rPos:%u", cur);
  1249. if (fullUpdate)
  1250. newMatch = LZ4HC_FindLongerMatch(ctx, curPtr, matchlimit, MINMATCH-1, nbSearches, dict, favorDecSpeed);
  1251. else
  1252. /* only test matches of minimum length; slightly faster, but misses a few bytes */
  1253. newMatch = LZ4HC_FindLongerMatch(ctx, curPtr, matchlimit, last_match_pos - cur, nbSearches, dict, favorDecSpeed);
  1254. if (!newMatch.len) continue;
  1255. if ( ((size_t)newMatch.len > sufficient_len)
  1256. || (newMatch.len + cur >= LZ4_OPT_NUM) ) {
  1257. /* immediate encoding */
  1258. best_mlen = newMatch.len;
  1259. best_off = newMatch.off;
  1260. last_match_pos = cur + 1;
  1261. goto encode;
  1262. }
  1263. /* before match : set price with literals at beginning */
  1264. { int const baseLitlen = opt[cur].litlen;
  1265. int litlen;
  1266. for (litlen = 1; litlen < MINMATCH; litlen++) {
  1267. int const price = opt[cur].price - LZ4HC_literalsPrice(baseLitlen) + LZ4HC_literalsPrice(baseLitlen+litlen);
  1268. int const pos = cur + litlen;
  1269. if (price < opt[pos].price) {
  1270. opt[pos].mlen = 1; /* literal */
  1271. opt[pos].off = 0;
  1272. opt[pos].litlen = baseLitlen+litlen;
  1273. opt[pos].price = price;
  1274. DEBUGLOG(7, "rPos:%3i => price:%3i (litlen=%i)",
  1275. pos, price, opt[pos].litlen);
  1276. } } }
  1277. /* set prices using match at position = cur */
  1278. { int const matchML = newMatch.len;
  1279. int ml = MINMATCH;
  1280. assert(cur + newMatch.len < LZ4_OPT_NUM);
  1281. for ( ; ml <= matchML ; ml++) {
  1282. int const pos = cur + ml;
  1283. int const offset = newMatch.off;
  1284. int price;
  1285. int ll;
  1286. DEBUGLOG(7, "testing price rPos %i (last_match_pos=%i)",
  1287. pos, last_match_pos);
  1288. if (opt[cur].mlen == 1) {
  1289. ll = opt[cur].litlen;
  1290. price = ((cur > ll) ? opt[cur - ll].price : 0)
  1291. + LZ4HC_sequencePrice(ll, ml);
  1292. } else {
  1293. ll = 0;
  1294. price = opt[cur].price + LZ4HC_sequencePrice(0, ml);
  1295. }
  1296. assert((U32)favorDecSpeed <= 1);
  1297. if (pos > last_match_pos+TRAILING_LITERALS
  1298. || price <= opt[pos].price - (int)favorDecSpeed) {
  1299. DEBUGLOG(7, "rPos:%3i => price:%3i (matchlen=%i)",
  1300. pos, price, ml);
  1301. assert(pos < LZ4_OPT_NUM);
  1302. if ( (ml == matchML) /* last pos of last match */
  1303. && (last_match_pos < pos) )
  1304. last_match_pos = pos;
  1305. opt[pos].mlen = ml;
  1306. opt[pos].off = offset;
  1307. opt[pos].litlen = ll;
  1308. opt[pos].price = price;
  1309. } } }
  1310. /* complete following positions with literals */
  1311. { int addLit;
  1312. for (addLit = 1; addLit <= TRAILING_LITERALS; addLit ++) {
  1313. opt[last_match_pos+addLit].mlen = 1; /* literal */
  1314. opt[last_match_pos+addLit].off = 0;
  1315. opt[last_match_pos+addLit].litlen = addLit;
  1316. opt[last_match_pos+addLit].price = opt[last_match_pos].price + LZ4HC_literalsPrice(addLit);
  1317. DEBUGLOG(7, "rPos:%3i => price:%3i (litlen=%i)", last_match_pos+addLit, opt[last_match_pos+addLit].price, addLit);
  1318. } }
  1319. } /* for (cur = 1; cur <= last_match_pos; cur++) */
  1320. best_mlen = opt[last_match_pos].mlen;
  1321. best_off = opt[last_match_pos].off;
  1322. cur = last_match_pos - best_mlen;
  1323. encode: /* cur, last_match_pos, best_mlen, best_off must be set */
  1324. assert(cur < LZ4_OPT_NUM);
  1325. assert(last_match_pos >= 1); /* == 1 when only one candidate */
  1326. DEBUGLOG(6, "reverse traversal, looking for shortest path (last_match_pos=%i)", last_match_pos);
  1327. { int candidate_pos = cur;
  1328. int selected_matchLength = best_mlen;
  1329. int selected_offset = best_off;
  1330. while (1) { /* from end to beginning */
  1331. int const next_matchLength = opt[candidate_pos].mlen; /* can be 1, means literal */
  1332. int const next_offset = opt[candidate_pos].off;
  1333. DEBUGLOG(7, "pos %i: sequence length %i", candidate_pos, selected_matchLength);
  1334. opt[candidate_pos].mlen = selected_matchLength;
  1335. opt[candidate_pos].off = selected_offset;
  1336. selected_matchLength = next_matchLength;
  1337. selected_offset = next_offset;
  1338. if (next_matchLength > candidate_pos) break; /* last match elected, first match to encode */
  1339. assert(next_matchLength > 0); /* can be 1, means literal */
  1340. candidate_pos -= next_matchLength;
  1341. } }
  1342. /* encode all recorded sequences in order */
  1343. { int rPos = 0; /* relative position (to ip) */
  1344. while (rPos < last_match_pos) {
  1345. int const ml = opt[rPos].mlen;
  1346. int const offset = opt[rPos].off;
  1347. if (ml == 1) { ip++; rPos++; continue; } /* literal; note: can end up with several literals, in which case, skip them */
  1348. rPos += ml;
  1349. assert(ml >= MINMATCH);
  1350. assert((offset >= 1) && (offset <= MAX_DISTANCE));
  1351. opSaved = op;
  1352. if ( LZ4HC_encodeSequence(&ip, &op, &anchor, ml, ip - offset, limit, oend) ) /* updates ip, op and anchor */
  1353. goto _dest_overflow;
  1354. } }
  1355. } /* while (ip <= mflimit) */
  1356. _last_literals:
  1357. /* Encode Last Literals */
  1358. { size_t lastRunSize = (size_t)(iend - anchor); /* literals */
  1359. size_t litLength = (lastRunSize + 255 - RUN_MASK) / 255;
  1360. size_t const totalSize = 1 + litLength + lastRunSize;
  1361. if (limit == limitedDestSize) oend += LASTLITERALS; /* restore correct value */
  1362. if (limit && (op + totalSize > oend)) {
  1363. if (limit == limitedOutput) return 0; /* Check output limit */
  1364. /* adapt lastRunSize to fill 'dst' */
  1365. lastRunSize = (size_t)(oend - op) - 1;
  1366. litLength = (lastRunSize + 255 - RUN_MASK) / 255;
  1367. lastRunSize -= litLength;
  1368. }
  1369. ip = anchor + lastRunSize;
  1370. if (lastRunSize >= RUN_MASK) {
  1371. size_t accumulator = lastRunSize - RUN_MASK;
  1372. *op++ = (RUN_MASK << ML_BITS);
  1373. for(; accumulator >= 255 ; accumulator -= 255) *op++ = 255;
  1374. *op++ = (BYTE) accumulator;
  1375. } else {
  1376. *op++ = (BYTE)(lastRunSize << ML_BITS);
  1377. }
  1378. memcpy(op, anchor, lastRunSize);
  1379. op += lastRunSize;
  1380. }
  1381. /* End */
  1382. *srcSizePtr = (int) (((const char*)ip) - source);
  1383. return (int) ((char*)op-dst);
  1384. _dest_overflow:
  1385. if (limit == limitedDestSize) {
  1386. op = opSaved; /* restore correct out pointer */
  1387. goto _last_literals;
  1388. }
  1389. return 0;
  1390. }
  1391. typedef enum { endOnOutputSize = 0, endOnInputSize = 1 } endCondition_directive;
  1392. typedef enum { decode_full_block = 0, partial_decode = 1 } earlyEnd_directive;
  1393. typedef enum { noDict = 0, withPrefix64k, usingExtDict } dict_directive;
  1394. typedef enum { noDictIssue = 0, dictSmall } dictIssue_directive;
  1395. /*! LZ4_decompress_generic() :
  1396. * This generic decompression function covers all use cases.
  1397. * It shall be instantiated several times, using different sets of directives.
  1398. * Note that it is important for performance that this function really get inlined,
  1399. * in order to remove useless branches during compilation optimization.
  1400. */
  1401. LZ4_FORCE_INLINE int
  1402. LZ4_decompress_generic(
  1403. const char* const src,
  1404. char* const dst,
  1405. int srcSize,
  1406. int outputSize, /* If endOnInput==endOnInputSize, this value is `dstCapacity` */
  1407. endCondition_directive endOnInput, /* endOnOutputSize, endOnInputSize */
  1408. earlyEnd_directive partialDecoding, /* full, partial */
  1409. dict_directive dict, /* noDict, withPrefix64k, usingExtDict */
  1410. const BYTE* const lowPrefix, /* always <= dst, == dst when no prefix */
  1411. const BYTE* const dictStart, /* only if dict==usingExtDict */
  1412. const size_t dictSize /* note : = 0 if noDict */
  1413. )
  1414. {
  1415. const BYTE* ip = (const BYTE*) src;
  1416. const BYTE* const iend = ip + srcSize;
  1417. BYTE* op = (BYTE*) dst;
  1418. BYTE* const oend = op + outputSize;
  1419. BYTE* cpy;
  1420. const BYTE* const dictEnd = (const BYTE*)dictStart + dictSize;
  1421. const unsigned inc32table[8] = {0, 1, 2, 1, 0, 4, 4, 4};
  1422. const int dec64table[8] = {0, 0, 0, -1, -4, 1, 2, 3};
  1423. const int safeDecode = (endOnInput==endOnInputSize);
  1424. const int checkOffset = ((safeDecode) && (dictSize < (int)(64 KB)));
  1425. /* Set up the "end" pointers for the shortcut. */
  1426. const BYTE* const shortiend = iend - (endOnInput ? 14 : 8) /*maxLL*/ - 2 /*offset*/;
  1427. const BYTE* const shortoend = oend - (endOnInput ? 14 : 8) /*maxLL*/ - 18 /*maxML*/;
  1428. DEBUGLOG(5, "LZ4_decompress_generic (srcSize:%i, dstSize:%i)", srcSize, outputSize);
  1429. /* Special cases */
  1430. assert(lowPrefix <= op);
  1431. assert(src != NULL);
  1432. if ((endOnInput) && (unlikely(outputSize==0))) return ((srcSize==1) && (*ip==0)) ? 0 : -1; /* Empty output buffer */
  1433. if ((!endOnInput) && (unlikely(outputSize==0))) return (*ip==0 ? 1 : -1);
  1434. if ((endOnInput) && unlikely(srcSize==0)) return -1;
  1435. /* Main Loop : decode sequences */
  1436. while (1) {
  1437. const BYTE* match;
  1438. size_t offset;
  1439. unsigned const token = *ip++;
  1440. size_t length = token >> ML_BITS; /* literal length */
  1441. assert(!endOnInput || ip <= iend); /* ip < iend before the increment */
  1442. /* A two-stage shortcut for the most common case:
  1443. * 1) If the literal length is 0..14, and there is enough space,
  1444. * enter the shortcut and copy 16 bytes on behalf of the literals
  1445. * (in the fast mode, only 8 bytes can be safely copied this way).
  1446. * 2) Further if the match length is 4..18, copy 18 bytes in a similar
  1447. * manner; but we ensure that there's enough space in the output for
  1448. * those 18 bytes earlier, upon entering the shortcut (in other words,
  1449. * there is a combined check for both stages).
  1450. */
  1451. if ( (endOnInput ? length != RUN_MASK : length <= 8)
  1452. /* strictly "less than" on input, to re-enter the loop with at least one byte */
  1453. && likely((endOnInput ? ip < shortiend : 1) & (op <= shortoend)) ) {
  1454. /* Copy the literals */
  1455. memcpy(op, ip, endOnInput ? 16 : 8);
  1456. op += length; ip += length;
  1457. /* The second stage: prepare for match copying, decode full info.
  1458. * If it doesn't work out, the info won't be wasted. */
  1459. length = token & ML_MASK; /* match length */
  1460. offset = LZ4_readLE16(ip); ip += 2;
  1461. match = op - offset;
  1462. assert(match <= op); /* check overflow */
  1463. /* Do not deal with overlapping matches. */
  1464. if ( (length != ML_MASK)
  1465. && (offset >= 8)
  1466. && (dict==withPrefix64k || match >= lowPrefix) ) {
  1467. /* Copy the match. */
  1468. memcpy(op + 0, match + 0, 8);
  1469. memcpy(op + 8, match + 8, 8);
  1470. memcpy(op +16, match +16, 2);
  1471. op += length + MINMATCH;
  1472. /* Both stages worked, load the next token. */
  1473. continue;
  1474. }
  1475. /* The second stage didn't work out, but the info is ready.
  1476. * Propel it right to the point of match copying. */
  1477. goto _copy_match;
  1478. }
  1479. /* decode literal length */
  1480. if (length == RUN_MASK) {
  1481. unsigned s;
  1482. if (unlikely(endOnInput ? ip >= iend-RUN_MASK : 0)) goto _output_error; /* overflow detection */
  1483. do {
  1484. s = *ip++;
  1485. length += s;
  1486. } while ( likely(endOnInput ? ip<iend-RUN_MASK : 1) & (s==255) );
  1487. if ((safeDecode) && unlikely((uptrval)(op)+length<(uptrval)(op))) goto _output_error; /* overflow detection */
  1488. if ((safeDecode) && unlikely((uptrval)(ip)+length<(uptrval)(ip))) goto _output_error; /* overflow detection */
  1489. }
  1490. /* copy literals */
  1491. cpy = op+length;
  1492. LZ4_STATIC_ASSERT(MFLIMIT >= WILDCOPYLENGTH);
  1493. if ( ((endOnInput) && ((cpy>oend-MFLIMIT) || (ip+length>iend-(2+1+LASTLITERALS))) )
  1494. || ((!endOnInput) && (cpy>oend-WILDCOPYLENGTH)) )
  1495. {
  1496. if (partialDecoding) {
  1497. if (cpy > oend) { cpy = oend; length = oend-op; } /* Partial decoding : stop in the middle of literal segment */
  1498. if ((endOnInput) && (ip+length > iend)) goto _output_error; /* Error : read attempt beyond end of input buffer */
  1499. } else {
  1500. if ((!endOnInput) && (cpy != oend)) goto _output_error; /* Error : block decoding must stop exactly there */
  1501. if ((endOnInput) && ((ip+length != iend) || (cpy > oend))) goto _output_error; /* Error : input must be consumed */
  1502. }
  1503. memcpy(op, ip, length);
  1504. ip += length;
  1505. op += length;
  1506. if (!partialDecoding || (cpy == oend)) {
  1507. /* Necessarily EOF, due to parsing restrictions */
  1508. break;
  1509. }
  1510. } else {
  1511. LZ4_wildCopy(op, ip, cpy); /* may overwrite up to WILDCOPYLENGTH beyond cpy */
  1512. ip += length; op = cpy;
  1513. }
  1514. /* get offset */
  1515. offset = LZ4_readLE16(ip); ip+=2;
  1516. match = op - offset;
  1517. /* get matchlength */
  1518. length = token & ML_MASK;
  1519. _copy_match:
  1520. if ((checkOffset) && (unlikely(match + dictSize < lowPrefix))) goto _output_error; /* Error : offset outside buffers */
  1521. if (!partialDecoding) {
  1522. assert(oend > op);
  1523. assert(oend - op >= 4);
  1524. LZ4_write32(op, 0); /* silence an msan warning when offset==0; costs <1%; */
  1525. } /* note : when partialDecoding, there is no guarantee that at least 4 bytes remain available in output buffer */
  1526. if (length == ML_MASK) {
  1527. unsigned s;
  1528. do {
  1529. s = *ip++;
  1530. if ((endOnInput) && (ip > iend-LASTLITERALS)) goto _output_error;
  1531. length += s;
  1532. } while (s==255);
  1533. if ((safeDecode) && unlikely((uptrval)(op)+length<(uptrval)op)) goto _output_error; /* overflow detection */
  1534. }
  1535. length += MINMATCH;
  1536. /* match starting within external dictionary */
  1537. if ((dict==usingExtDict) && (match < lowPrefix)) {
  1538. if (unlikely(op+length > oend-LASTLITERALS)) {
  1539. if (partialDecoding) length = MIN(length, (size_t)(oend-op));
  1540. else goto _output_error; /* doesn't respect parsing restriction */
  1541. }
  1542. if (length <= (size_t)(lowPrefix-match)) {
  1543. /* match fits entirely within external dictionary : just copy */
  1544. memmove(op, dictEnd - (lowPrefix-match), length);
  1545. op += length;
  1546. } else {
  1547. /* match stretches into both external dictionary and current block */
  1548. size_t const copySize = (size_t)(lowPrefix - match);
  1549. size_t const restSize = length - copySize;
  1550. memcpy(op, dictEnd - copySize, copySize);
  1551. op += copySize;
  1552. if (restSize > (size_t)(op - lowPrefix)) { /* overlap copy */
  1553. BYTE* const endOfMatch = op + restSize;
  1554. const BYTE* copyFrom = lowPrefix;
  1555. while (op < endOfMatch) *op++ = *copyFrom++;
  1556. } else {
  1557. memcpy(op, lowPrefix, restSize);
  1558. op += restSize;
  1559. } }
  1560. continue;
  1561. }
  1562. /* copy match within block */
  1563. cpy = op + length;
  1564. /* partialDecoding : may not respect endBlock parsing restrictions */
  1565. assert(op<=oend);
  1566. if (partialDecoding && (cpy > oend-MATCH_SAFEGUARD_DISTANCE)) {
  1567. size_t const mlen = MIN(length, (size_t)(oend-op));
  1568. const BYTE* const matchEnd = match + mlen;
  1569. BYTE* const copyEnd = op + mlen;
  1570. if (matchEnd > op) { /* overlap copy */
  1571. while (op < copyEnd) *op++ = *match++;
  1572. } else {
  1573. memcpy(op, match, mlen);
  1574. }
  1575. op = copyEnd;
  1576. if (op==oend) break;
  1577. continue;
  1578. }
  1579. if (unlikely(offset<8)) {
  1580. op[0] = match[0];
  1581. op[1] = match[1];
  1582. op[2] = match[2];
  1583. op[3] = match[3];
  1584. match += inc32table[offset];
  1585. memcpy(op+4, match, 4);
  1586. match -= dec64table[offset];
  1587. } else {
  1588. memcpy(op, match, 8);
  1589. match += 8;
  1590. }
  1591. op += 8;
  1592. if (unlikely(cpy > oend-MATCH_SAFEGUARD_DISTANCE)) {
  1593. BYTE* const oCopyLimit = oend - (WILDCOPYLENGTH-1);
  1594. if (cpy > oend-LASTLITERALS) goto _output_error; /* Error : last LASTLITERALS bytes must be literals (uncompressed) */
  1595. if (op < oCopyLimit) {
  1596. LZ4_wildCopy(op, match, oCopyLimit);
  1597. match += oCopyLimit - op;
  1598. op = oCopyLimit;
  1599. }
  1600. while (op < cpy) *op++ = *match++;
  1601. } else {
  1602. memcpy(op, match, 8);
  1603. if (length > 16) LZ4_wildCopy(op+8, match+8, cpy);
  1604. }
  1605. op = cpy; /* wildcopy correction */
  1606. }
  1607. /* end of decoding */
  1608. if (endOnInput)
  1609. return (int) (((char*)op)-dst); /* Nb of output bytes decoded */
  1610. else
  1611. return (int) (((const char*)ip)-src); /* Nb of input bytes read */
  1612. /* Overflow error detected */
  1613. _output_error:
  1614. return (int) (-(((const char*)ip)-src))-1;
  1615. }
  1616. int LZ4_decompress_fast(const void* source, void* dest, int originalSize)
  1617. {
  1618. return LZ4_decompress_generic(source, dest, 0, originalSize,
  1619. endOnOutputSize, decode_full_block, withPrefix64k,
  1620. (BYTE*)dest - 64 KB, NULL, 0);
  1621. }