lz4.c 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367
  1. /*
  2. LZ4 - Fast LZ compression algorithm
  3. Copyright (C) 2011-2015, 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 : http://code.google.com/p/lz4
  27. - LZ4 source mirror : https://github.com/Cyan4973/lz4
  28. - LZ4 public forum : https://groups.google.com/forum/#!forum/lz4c
  29. */
  30. /**************************************
  31. Tuning parameters
  32. **************************************/
  33. /*
  34. * HEAPMODE :
  35. * Select how default compression functions will allocate memory for their hash table,
  36. * in memory stack (0:default, fastest), or in memory heap (1:requires malloc()).
  37. */
  38. #define HEAPMODE 0
  39. /*
  40. * CPU_HAS_EFFICIENT_UNALIGNED_MEMORY_ACCESS :
  41. * By default, the source code expects the compiler to correctly optimize
  42. * 4-bytes and 8-bytes read on architectures able to handle it efficiently.
  43. * This is not always the case. In some circumstances (ARM notably),
  44. * the compiler will issue cautious code even when target is able to correctly handle unaligned memory accesses.
  45. *
  46. * You can force the compiler to use unaligned memory access by uncommenting the line below.
  47. * One of the below scenarios will happen :
  48. * 1 - Your target CPU correctly handle unaligned access, and was not well optimized by compiler (good case).
  49. * You will witness large performance improvements (+50% and up).
  50. * Keep the line uncommented and send a word to upstream (https://groups.google.com/forum/#!forum/lz4c)
  51. * The goal is to automatically detect such situations by adding your target CPU within an exception list.
  52. * 2 - Your target CPU correctly handle unaligned access, and was already already optimized by compiler
  53. * No change will be experienced.
  54. * 3 - Your target CPU inefficiently handle unaligned access.
  55. * You will experience a performance loss. Comment back the line.
  56. * 4 - Your target CPU does not handle unaligned access.
  57. * Program will crash.
  58. * If uncommenting results in better performance (case 1)
  59. * please report your configuration to upstream (https://groups.google.com/forum/#!forum/lz4c)
  60. * An automatic detection macro will be added to match your case within future versions of the library.
  61. */
  62. /* #define CPU_HAS_EFFICIENT_UNALIGNED_MEMORY_ACCESS 1 */
  63. /**************************************
  64. CPU Feature Detection
  65. **************************************/
  66. /*
  67. * Automated efficient unaligned memory access detection
  68. * Based on known hardware architectures
  69. * This list will be updated thanks to feedbacks
  70. */
  71. #if defined(CPU_HAS_EFFICIENT_UNALIGNED_MEMORY_ACCESS) \
  72. || defined(__ARM_FEATURE_UNALIGNED) \
  73. || defined(__i386__) || defined(__x86_64__) \
  74. || defined(_M_IX86) || defined(_M_X64) \
  75. || defined(__ARM_ARCH_7__) || defined(__ARM_ARCH_8__) \
  76. || (defined(_M_ARM) && (_M_ARM >= 7))
  77. # define LZ4_UNALIGNED_ACCESS 1
  78. #else
  79. # define LZ4_UNALIGNED_ACCESS 0
  80. #endif
  81. /*
  82. * LZ4_FORCE_SW_BITCOUNT
  83. * Define this parameter if your target system or compiler does not support hardware bit count
  84. */
  85. #if defined(_MSC_VER) && defined(_WIN32_WCE) /* Visual Studio for Windows CE does not support Hardware bit count */
  86. # define LZ4_FORCE_SW_BITCOUNT
  87. #endif
  88. /**************************************
  89. Compiler Options
  90. **************************************/
  91. #if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */
  92. /* "restrict" is a known keyword */
  93. #else
  94. # define restrict /* Disable restrict */
  95. #endif
  96. #ifdef _MSC_VER /* Visual Studio */
  97. # define FORCE_INLINE static __forceinline
  98. # include <intrin.h>
  99. # pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */
  100. # pragma warning(disable : 4293) /* disable: C4293: too large shift (32-bits) */
  101. #else
  102. # if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */
  103. # ifdef __GNUC__
  104. # define FORCE_INLINE static inline __attribute__((always_inline))
  105. # else
  106. # define FORCE_INLINE static inline
  107. # endif
  108. # else
  109. # define FORCE_INLINE static
  110. # endif /* __STDC_VERSION__ */
  111. #endif /* _MSC_VER */
  112. #define GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__)
  113. #if (GCC_VERSION >= 302) || (__INTEL_COMPILER >= 800) || defined(__clang__)
  114. # define expect(expr,value) (__builtin_expect ((expr),(value)) )
  115. #else
  116. # define expect(expr,value) (expr)
  117. #endif
  118. #define likely(expr) expect((expr) != 0, 1)
  119. #define unlikely(expr) expect((expr) != 0, 0)
  120. /**************************************
  121. Memory routines
  122. **************************************/
  123. #include <stdlib.h> /* malloc, calloc, free */
  124. #define ALLOCATOR(n,s) calloc(n,s)
  125. #define FREEMEM free
  126. #include <string.h> /* memset, memcpy */
  127. #define MEM_INIT memset
  128. /**************************************
  129. Includes
  130. **************************************/
  131. #include "lz4.h"
  132. /**************************************
  133. Basic Types
  134. **************************************/
  135. #if defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */
  136. # include <stdint.h>
  137. typedef uint8_t BYTE;
  138. typedef uint16_t U16;
  139. typedef uint32_t U32;
  140. typedef int32_t S32;
  141. typedef uint64_t U64;
  142. #else
  143. typedef unsigned char BYTE;
  144. typedef unsigned short U16;
  145. typedef unsigned int U32;
  146. typedef signed int S32;
  147. typedef unsigned long long U64;
  148. #endif
  149. /**************************************
  150. Reading and writing into memory
  151. **************************************/
  152. #define STEPSIZE sizeof(size_t)
  153. static unsigned LZ4_64bits(void) { return sizeof(void*)==8; }
  154. static unsigned LZ4_isLittleEndian(void)
  155. {
  156. const union { U32 i; BYTE c[4]; } one = { 1 }; /* don't use static : performance detrimental */
  157. return one.c[0];
  158. }
  159. static U16 LZ4_readLE16(const void* memPtr)
  160. {
  161. if ((LZ4_UNALIGNED_ACCESS) && (LZ4_isLittleEndian()))
  162. return *(U16*)memPtr;
  163. else
  164. {
  165. const BYTE* p = memPtr;
  166. return (U16)((U16)p[0] + (p[1]<<8));
  167. }
  168. }
  169. static void LZ4_writeLE16(void* memPtr, U16 value)
  170. {
  171. if ((LZ4_UNALIGNED_ACCESS) && (LZ4_isLittleEndian()))
  172. {
  173. *(U16*)memPtr = value;
  174. return;
  175. }
  176. else
  177. {
  178. BYTE* p = memPtr;
  179. p[0] = (BYTE) value;
  180. p[1] = (BYTE)(value>>8);
  181. }
  182. }
  183. static U16 LZ4_read16(const void* memPtr)
  184. {
  185. if (LZ4_UNALIGNED_ACCESS)
  186. return *(U16*)memPtr;
  187. else
  188. {
  189. U16 val16;
  190. memcpy(&val16, memPtr, 2);
  191. return val16;
  192. }
  193. }
  194. static U32 LZ4_read32(const void* memPtr)
  195. {
  196. if (LZ4_UNALIGNED_ACCESS)
  197. return *(U32*)memPtr;
  198. else
  199. {
  200. U32 val32;
  201. memcpy(&val32, memPtr, 4);
  202. return val32;
  203. }
  204. }
  205. static U64 LZ4_read64(const void* memPtr)
  206. {
  207. if (LZ4_UNALIGNED_ACCESS)
  208. return *(U64*)memPtr;
  209. else
  210. {
  211. U64 val64;
  212. memcpy(&val64, memPtr, 8);
  213. return val64;
  214. }
  215. }
  216. static size_t LZ4_read_ARCH(const void* p)
  217. {
  218. if (LZ4_64bits())
  219. return (size_t)LZ4_read64(p);
  220. else
  221. return (size_t)LZ4_read32(p);
  222. }
  223. static void LZ4_copy4(void* dstPtr, const void* srcPtr)
  224. {
  225. if (LZ4_UNALIGNED_ACCESS)
  226. {
  227. *(U32*)dstPtr = *(U32*)srcPtr;
  228. return;
  229. }
  230. memcpy(dstPtr, srcPtr, 4);
  231. }
  232. static void LZ4_copy8(void* dstPtr, const void* srcPtr)
  233. {
  234. #if GCC_VERSION!=409 /* disabled on GCC 4.9, as it generates invalid opcode (crash) */
  235. if (LZ4_UNALIGNED_ACCESS)
  236. {
  237. if (LZ4_64bits())
  238. *(U64*)dstPtr = *(U64*)srcPtr;
  239. else
  240. ((U32*)dstPtr)[0] = ((U32*)srcPtr)[0],
  241. ((U32*)dstPtr)[1] = ((U32*)srcPtr)[1];
  242. return;
  243. }
  244. #endif
  245. memcpy(dstPtr, srcPtr, 8);
  246. }
  247. /* customized version of memcpy, which may overwrite up to 7 bytes beyond dstEnd */
  248. static void LZ4_wildCopy(void* dstPtr, const void* srcPtr, void* dstEnd)
  249. {
  250. BYTE* d = dstPtr;
  251. const BYTE* s = srcPtr;
  252. BYTE* e = dstEnd;
  253. do { LZ4_copy8(d,s); d+=8; s+=8; } while (d<e);
  254. }
  255. /**************************************
  256. Common Constants
  257. **************************************/
  258. #define MINMATCH 4
  259. #define COPYLENGTH 8
  260. #define LASTLITERALS 5
  261. #define MFLIMIT (COPYLENGTH+MINMATCH)
  262. static const int LZ4_minLength = (MFLIMIT+1);
  263. #define KB *(1 <<10)
  264. #define MB *(1 <<20)
  265. #define GB *(1U<<30)
  266. #define MAXD_LOG 16
  267. #define MAX_DISTANCE ((1 << MAXD_LOG) - 1)
  268. #define ML_BITS 4
  269. #define ML_MASK ((1U<<ML_BITS)-1)
  270. #define RUN_BITS (8-ML_BITS)
  271. #define RUN_MASK ((1U<<RUN_BITS)-1)
  272. /**************************************
  273. Common Utils
  274. **************************************/
  275. #define LZ4_STATIC_ASSERT(c) { enum { LZ4_static_assert = 1/(int)(!!(c)) }; } /* use only *after* variable declarations */
  276. /********************************
  277. Common functions
  278. ********************************/
  279. static unsigned LZ4_NbCommonBytes (register size_t val)
  280. {
  281. if (LZ4_isLittleEndian())
  282. {
  283. if (LZ4_64bits())
  284. {
  285. # if defined(_MSC_VER) && defined(_WIN64) && !defined(LZ4_FORCE_SW_BITCOUNT)
  286. unsigned long r = 0;
  287. _BitScanForward64( &r, (U64)val );
  288. return (int)(r>>3);
  289. # elif defined(__GNUC__) && (GCC_VERSION >= 304) && !defined(LZ4_FORCE_SW_BITCOUNT)
  290. return (__builtin_ctzll((U64)val) >> 3);
  291. # else
  292. static const int DeBruijnBytePos[64] = { 0, 0, 0, 0, 0, 1, 1, 2, 0, 3, 1, 3, 1, 4, 2, 7, 0, 2, 3, 6, 1, 5, 3, 5, 1, 3, 4, 4, 2, 5, 6, 7, 7, 0, 1, 2, 3, 3, 4, 6, 2, 6, 5, 5, 3, 4, 5, 6, 7, 1, 2, 4, 6, 4, 4, 5, 7, 2, 6, 5, 7, 6, 7, 7 };
  293. return DeBruijnBytePos[((U64)((val & -(long long)val) * 0x0218A392CDABBD3FULL)) >> 58];
  294. # endif
  295. }
  296. else /* 32 bits */
  297. {
  298. # if defined(_MSC_VER) && !defined(LZ4_FORCE_SW_BITCOUNT)
  299. unsigned long r;
  300. _BitScanForward( &r, (U32)val );
  301. return (int)(r>>3);
  302. # elif defined(__GNUC__) && (GCC_VERSION >= 304) && !defined(LZ4_FORCE_SW_BITCOUNT)
  303. return (__builtin_ctz((U32)val) >> 3);
  304. # else
  305. static const int DeBruijnBytePos[32] = { 0, 0, 3, 0, 3, 1, 3, 0, 3, 2, 2, 1, 3, 2, 0, 1, 3, 3, 1, 2, 2, 2, 2, 0, 3, 1, 2, 0, 1, 0, 1, 1 };
  306. return DeBruijnBytePos[((U32)((val & -(S32)val) * 0x077CB531U)) >> 27];
  307. # endif
  308. }
  309. }
  310. else /* Big Endian CPU */
  311. {
  312. if (LZ4_64bits())
  313. {
  314. # if defined(_MSC_VER) && defined(_WIN64) && !defined(LZ4_FORCE_SW_BITCOUNT)
  315. unsigned long r = 0;
  316. _BitScanReverse64( &r, val );
  317. return (unsigned)(r>>3);
  318. # elif defined(__GNUC__) && (GCC_VERSION >= 304) && !defined(LZ4_FORCE_SW_BITCOUNT)
  319. return (__builtin_clzll(val) >> 3);
  320. # else
  321. unsigned r;
  322. if (!(val>>32)) { r=4; } else { r=0; val>>=32; }
  323. if (!(val>>16)) { r+=2; val>>=8; } else { val>>=24; }
  324. r += (!val);
  325. return r;
  326. # endif
  327. }
  328. else /* 32 bits */
  329. {
  330. # if defined(_MSC_VER) && !defined(LZ4_FORCE_SW_BITCOUNT)
  331. unsigned long r = 0;
  332. _BitScanReverse( &r, (unsigned long)val );
  333. return (unsigned)(r>>3);
  334. # elif defined(__GNUC__) && (GCC_VERSION >= 304) && !defined(LZ4_FORCE_SW_BITCOUNT)
  335. return (__builtin_clz(val) >> 3);
  336. # else
  337. unsigned r;
  338. if (!(val>>16)) { r=2; val>>=8; } else { r=0; val>>=24; }
  339. r += (!val);
  340. return r;
  341. # endif
  342. }
  343. }
  344. }
  345. static unsigned LZ4_count(const BYTE* pIn, const BYTE* pMatch, const BYTE* pInLimit)
  346. {
  347. const BYTE* const pStart = pIn;
  348. while (likely(pIn<pInLimit-(STEPSIZE-1)))
  349. {
  350. size_t diff = LZ4_read_ARCH(pMatch) ^ LZ4_read_ARCH(pIn);
  351. if (!diff) { pIn+=STEPSIZE; pMatch+=STEPSIZE; continue; }
  352. pIn += LZ4_NbCommonBytes(diff);
  353. return (unsigned)(pIn - pStart);
  354. }
  355. if (LZ4_64bits()) if ((pIn<(pInLimit-3)) && (LZ4_read32(pMatch) == LZ4_read32(pIn))) { pIn+=4; pMatch+=4; }
  356. if ((pIn<(pInLimit-1)) && (LZ4_read16(pMatch) == LZ4_read16(pIn))) { pIn+=2; pMatch+=2; }
  357. if ((pIn<pInLimit) && (*pMatch == *pIn)) pIn++;
  358. return (unsigned)(pIn - pStart);
  359. }
  360. #ifndef LZ4_COMMONDEFS_ONLY
  361. /**************************************
  362. Local Constants
  363. **************************************/
  364. #define LZ4_HASHLOG (LZ4_MEMORY_USAGE-2)
  365. #define HASHTABLESIZE (1 << LZ4_MEMORY_USAGE)
  366. #define HASH_SIZE_U32 (1 << LZ4_HASHLOG) /* required as macro for static allocation */
  367. static const int LZ4_64Klimit = ((64 KB) + (MFLIMIT-1));
  368. static const U32 LZ4_skipTrigger = 6; /* Increase this value ==> compression run slower on incompressible data */
  369. /**************************************
  370. Local Utils
  371. **************************************/
  372. int LZ4_versionNumber (void) { return LZ4_VERSION_NUMBER; }
  373. int LZ4_compressBound(int isize) { return LZ4_COMPRESSBOUND(isize); }
  374. /**************************************
  375. Local Structures and types
  376. **************************************/
  377. typedef struct {
  378. U32 hashTable[HASH_SIZE_U32];
  379. U32 currentOffset;
  380. U32 initCheck;
  381. const BYTE* dictionary;
  382. const BYTE* bufferStart;
  383. U32 dictSize;
  384. } LZ4_stream_t_internal;
  385. typedef enum { notLimited = 0, limitedOutput = 1 } limitedOutput_directive;
  386. typedef enum { byPtr, byU32, byU16 } tableType_t;
  387. typedef enum { noDict = 0, withPrefix64k, usingExtDict } dict_directive;
  388. typedef enum { noDictIssue = 0, dictSmall } dictIssue_directive;
  389. typedef enum { endOnOutputSize = 0, endOnInputSize = 1 } endCondition_directive;
  390. typedef enum { full = 0, partial = 1 } earlyEnd_directive;
  391. /********************************
  392. Compression functions
  393. ********************************/
  394. static U32 LZ4_hashSequence(U32 sequence, tableType_t tableType)
  395. {
  396. if (tableType == byU16)
  397. return (((sequence) * 2654435761U) >> ((MINMATCH*8)-(LZ4_HASHLOG+1)));
  398. else
  399. return (((sequence) * 2654435761U) >> ((MINMATCH*8)-LZ4_HASHLOG));
  400. }
  401. static U32 LZ4_hashPosition(const BYTE* p, tableType_t tableType) { return LZ4_hashSequence(LZ4_read32(p), tableType); }
  402. static void LZ4_putPositionOnHash(const BYTE* p, U32 h, void* tableBase, tableType_t tableType, const BYTE* srcBase)
  403. {
  404. switch (tableType)
  405. {
  406. case byPtr: { const BYTE** hashTable = (const BYTE**)tableBase; hashTable[h] = p; return; }
  407. case byU32: { U32* hashTable = (U32*) tableBase; hashTable[h] = (U32)(p-srcBase); return; }
  408. case byU16: { U16* hashTable = (U16*) tableBase; hashTable[h] = (U16)(p-srcBase); return; }
  409. }
  410. }
  411. static void LZ4_putPosition(const BYTE* p, void* tableBase, tableType_t tableType, const BYTE* srcBase)
  412. {
  413. U32 h = LZ4_hashPosition(p, tableType);
  414. LZ4_putPositionOnHash(p, h, tableBase, tableType, srcBase);
  415. }
  416. static const BYTE* LZ4_getPositionOnHash(U32 h, void* tableBase, tableType_t tableType, const BYTE* srcBase)
  417. {
  418. if (tableType == byPtr) { const BYTE** hashTable = (const BYTE**) tableBase; return hashTable[h]; }
  419. if (tableType == byU32) { U32* hashTable = (U32*) tableBase; return hashTable[h] + srcBase; }
  420. { U16* hashTable = (U16*) tableBase; return hashTable[h] + srcBase; } /* default, to ensure a return */
  421. }
  422. static const BYTE* LZ4_getPosition(const BYTE* p, void* tableBase, tableType_t tableType, const BYTE* srcBase)
  423. {
  424. U32 h = LZ4_hashPosition(p, tableType);
  425. return LZ4_getPositionOnHash(h, tableBase, tableType, srcBase);
  426. }
  427. static int LZ4_compress_generic(
  428. void* ctx,
  429. const char* source,
  430. char* dest,
  431. int inputSize,
  432. int maxOutputSize,
  433. limitedOutput_directive outputLimited,
  434. tableType_t tableType,
  435. dict_directive dict,
  436. dictIssue_directive dictIssue)
  437. {
  438. LZ4_stream_t_internal* const dictPtr = (LZ4_stream_t_internal*)ctx;
  439. const BYTE* ip = (const BYTE*) source;
  440. const BYTE* base;
  441. const BYTE* lowLimit;
  442. const BYTE* const lowRefLimit = ip - dictPtr->dictSize;
  443. const BYTE* const dictionary = dictPtr->dictionary;
  444. const BYTE* const dictEnd = dictionary + dictPtr->dictSize;
  445. const size_t dictDelta = dictEnd - (const BYTE*)source;
  446. const BYTE* anchor = (const BYTE*) source;
  447. const BYTE* const iend = ip + inputSize;
  448. const BYTE* const mflimit = iend - MFLIMIT;
  449. const BYTE* const matchlimit = iend - LASTLITERALS;
  450. BYTE* op = (BYTE*) dest;
  451. BYTE* const olimit = op + maxOutputSize;
  452. U32 forwardH;
  453. size_t refDelta=0;
  454. /* Init conditions */
  455. if ((U32)inputSize > (U32)LZ4_MAX_INPUT_SIZE) return 0; /* Unsupported input size, too large (or negative) */
  456. switch(dict)
  457. {
  458. case noDict:
  459. default:
  460. base = (const BYTE*)source;
  461. lowLimit = (const BYTE*)source;
  462. break;
  463. case withPrefix64k:
  464. base = (const BYTE*)source - dictPtr->currentOffset;
  465. lowLimit = (const BYTE*)source - dictPtr->dictSize;
  466. break;
  467. case usingExtDict:
  468. base = (const BYTE*)source - dictPtr->currentOffset;
  469. lowLimit = (const BYTE*)source;
  470. break;
  471. }
  472. if ((tableType == byU16) && (inputSize>=LZ4_64Klimit)) return 0; /* Size too large (not within 64K limit) */
  473. if (inputSize<LZ4_minLength) goto _last_literals; /* Input too small, no compression (all literals) */
  474. /* First Byte */
  475. LZ4_putPosition(ip, ctx, tableType, base);
  476. ip++; forwardH = LZ4_hashPosition(ip, tableType);
  477. /* Main Loop */
  478. for ( ; ; )
  479. {
  480. const BYTE* match;
  481. BYTE* token;
  482. {
  483. const BYTE* forwardIp = ip;
  484. unsigned step=1;
  485. unsigned searchMatchNb = (1U << LZ4_skipTrigger);
  486. /* Find a match */
  487. do {
  488. U32 h = forwardH;
  489. ip = forwardIp;
  490. forwardIp += step;
  491. step = searchMatchNb++ >> LZ4_skipTrigger;
  492. if (unlikely(forwardIp > mflimit)) goto _last_literals;
  493. match = LZ4_getPositionOnHash(h, ctx, tableType, base);
  494. if (dict==usingExtDict)
  495. {
  496. if (match<(const BYTE*)source)
  497. {
  498. refDelta = dictDelta;
  499. lowLimit = dictionary;
  500. }
  501. else
  502. {
  503. refDelta = 0;
  504. lowLimit = (const BYTE*)source;
  505. }
  506. }
  507. forwardH = LZ4_hashPosition(forwardIp, tableType);
  508. LZ4_putPositionOnHash(ip, h, ctx, tableType, base);
  509. } while ( ((dictIssue==dictSmall) ? (match < lowRefLimit) : 0)
  510. || ((tableType==byU16) ? 0 : (match + MAX_DISTANCE < ip))
  511. || (LZ4_read32(match+refDelta) != LZ4_read32(ip)) );
  512. }
  513. /* Catch up */
  514. while ((ip>anchor) && (match+refDelta > lowLimit) && (unlikely(ip[-1]==match[refDelta-1]))) { ip--; match--; }
  515. {
  516. /* Encode Literal length */
  517. unsigned litLength = (unsigned)(ip - anchor);
  518. token = op++;
  519. if ((outputLimited) && (unlikely(op + litLength + (2 + 1 + LASTLITERALS) + (litLength/255) > olimit)))
  520. return 0; /* Check output limit */
  521. if (litLength>=RUN_MASK)
  522. {
  523. int len = (int)litLength-RUN_MASK;
  524. *token=(RUN_MASK<<ML_BITS);
  525. for(; len >= 255 ; len-=255) *op++ = 255;
  526. *op++ = (BYTE)len;
  527. }
  528. else *token = (BYTE)(litLength<<ML_BITS);
  529. /* Copy Literals */
  530. LZ4_wildCopy(op, anchor, op+litLength);
  531. op+=litLength;
  532. }
  533. _next_match:
  534. /* Encode Offset */
  535. LZ4_writeLE16(op, (U16)(ip-match)); op+=2;
  536. /* Encode MatchLength */
  537. {
  538. unsigned matchLength;
  539. if ((dict==usingExtDict) && (lowLimit==dictionary))
  540. {
  541. const BYTE* limit;
  542. match += refDelta;
  543. limit = ip + (dictEnd-match);
  544. if (limit > matchlimit) limit = matchlimit;
  545. matchLength = LZ4_count(ip+MINMATCH, match+MINMATCH, limit);
  546. ip += MINMATCH + matchLength;
  547. if (ip==limit)
  548. {
  549. unsigned more = LZ4_count(ip, (const BYTE*)source, matchlimit);
  550. matchLength += more;
  551. ip += more;
  552. }
  553. }
  554. else
  555. {
  556. matchLength = LZ4_count(ip+MINMATCH, match+MINMATCH, matchlimit);
  557. ip += MINMATCH + matchLength;
  558. }
  559. if ((outputLimited) && (unlikely(op + (1 + LASTLITERALS) + (matchLength>>8) > olimit)))
  560. return 0; /* Check output limit */
  561. if (matchLength>=ML_MASK)
  562. {
  563. *token += ML_MASK;
  564. matchLength -= ML_MASK;
  565. for (; matchLength >= 510 ; matchLength-=510) { *op++ = 255; *op++ = 255; }
  566. if (matchLength >= 255) { matchLength-=255; *op++ = 255; }
  567. *op++ = (BYTE)matchLength;
  568. }
  569. else *token += (BYTE)(matchLength);
  570. }
  571. anchor = ip;
  572. /* Test end of chunk */
  573. if (ip > mflimit) break;
  574. /* Fill table */
  575. LZ4_putPosition(ip-2, ctx, tableType, base);
  576. /* Test next position */
  577. match = LZ4_getPosition(ip, ctx, tableType, base);
  578. if (dict==usingExtDict)
  579. {
  580. if (match<(const BYTE*)source)
  581. {
  582. refDelta = dictDelta;
  583. lowLimit = dictionary;
  584. }
  585. else
  586. {
  587. refDelta = 0;
  588. lowLimit = (const BYTE*)source;
  589. }
  590. }
  591. LZ4_putPosition(ip, ctx, tableType, base);
  592. if ( ((dictIssue==dictSmall) ? (match>=lowRefLimit) : 1)
  593. && (match+MAX_DISTANCE>=ip)
  594. && (LZ4_read32(match+refDelta)==LZ4_read32(ip)) )
  595. { token=op++; *token=0; goto _next_match; }
  596. /* Prepare next loop */
  597. forwardH = LZ4_hashPosition(++ip, tableType);
  598. }
  599. _last_literals:
  600. /* Encode Last Literals */
  601. {
  602. int lastRun = (int)(iend - anchor);
  603. if ((outputLimited) && (((char*)op - dest) + lastRun + 1 + ((lastRun+255-RUN_MASK)/255) > (U32)maxOutputSize))
  604. return 0; /* Check output limit */
  605. if (lastRun>=(int)RUN_MASK) { *op++=(RUN_MASK<<ML_BITS); lastRun-=RUN_MASK; for(; lastRun >= 255 ; lastRun-=255) *op++ = 255; *op++ = (BYTE) lastRun; }
  606. else *op++ = (BYTE)(lastRun<<ML_BITS);
  607. memcpy(op, anchor, iend - anchor);
  608. op += iend-anchor;
  609. }
  610. /* End */
  611. return (int) (((char*)op)-dest);
  612. }
  613. int LZ4_compress(const char* source, char* dest, int inputSize)
  614. {
  615. #if (HEAPMODE)
  616. void* ctx = ALLOCATOR(LZ4_STREAMSIZE_U64, 8); /* Aligned on 8-bytes boundaries */
  617. #else
  618. U64 ctx[LZ4_STREAMSIZE_U64] = {0}; /* Ensure data is aligned on 8-bytes boundaries */
  619. #endif
  620. int result;
  621. if (inputSize < LZ4_64Klimit)
  622. result = LZ4_compress_generic((void*)ctx, source, dest, inputSize, 0, notLimited, byU16, noDict, noDictIssue);
  623. else
  624. result = LZ4_compress_generic((void*)ctx, source, dest, inputSize, 0, notLimited, LZ4_64bits() ? byU32 : byPtr, noDict, noDictIssue);
  625. #if (HEAPMODE)
  626. FREEMEM(ctx);
  627. #endif
  628. return result;
  629. }
  630. int LZ4_compress_limitedOutput(const char* source, char* dest, int inputSize, int maxOutputSize)
  631. {
  632. #if (HEAPMODE)
  633. void* ctx = ALLOCATOR(LZ4_STREAMSIZE_U64, 8); /* Aligned on 8-bytes boundaries */
  634. #else
  635. U64 ctx[LZ4_STREAMSIZE_U64] = {0}; /* Ensure data is aligned on 8-bytes boundaries */
  636. #endif
  637. int result;
  638. if (inputSize < LZ4_64Klimit)
  639. result = LZ4_compress_generic((void*)ctx, source, dest, inputSize, maxOutputSize, limitedOutput, byU16, noDict, noDictIssue);
  640. else
  641. result = LZ4_compress_generic((void*)ctx, source, dest, inputSize, maxOutputSize, limitedOutput, LZ4_64bits() ? byU32 : byPtr, noDict, noDictIssue);
  642. #if (HEAPMODE)
  643. FREEMEM(ctx);
  644. #endif
  645. return result;
  646. }
  647. /*****************************************
  648. Experimental : Streaming functions
  649. *****************************************/
  650. /*
  651. * LZ4_initStream
  652. * Use this function once, to init a newly allocated LZ4_stream_t structure
  653. * Return : 1 if OK, 0 if error
  654. */
  655. void LZ4_resetStream (LZ4_stream_t* LZ4_stream)
  656. {
  657. MEM_INIT(LZ4_stream, 0, sizeof(LZ4_stream_t));
  658. }
  659. LZ4_stream_t* LZ4_createStream(void)
  660. {
  661. LZ4_stream_t* lz4s = (LZ4_stream_t*)ALLOCATOR(8, LZ4_STREAMSIZE_U64);
  662. LZ4_STATIC_ASSERT(LZ4_STREAMSIZE >= sizeof(LZ4_stream_t_internal)); /* A compilation error here means LZ4_STREAMSIZE is not large enough */
  663. LZ4_resetStream(lz4s);
  664. return lz4s;
  665. }
  666. int LZ4_freeStream (LZ4_stream_t* LZ4_stream)
  667. {
  668. FREEMEM(LZ4_stream);
  669. return (0);
  670. }
  671. int LZ4_loadDict (LZ4_stream_t* LZ4_dict, const char* dictionary, int dictSize)
  672. {
  673. LZ4_stream_t_internal* dict = (LZ4_stream_t_internal*) LZ4_dict;
  674. const BYTE* p = (const BYTE*)dictionary;
  675. const BYTE* const dictEnd = p + dictSize;
  676. const BYTE* base;
  677. if (dict->initCheck) LZ4_resetStream(LZ4_dict); /* Uninitialized structure detected */
  678. if (dictSize < MINMATCH)
  679. {
  680. dict->dictionary = NULL;
  681. dict->dictSize = 0;
  682. return 0;
  683. }
  684. if (p <= dictEnd - 64 KB) p = dictEnd - 64 KB;
  685. base = p - dict->currentOffset;
  686. dict->dictionary = p;
  687. dict->dictSize = (U32)(dictEnd - p);
  688. dict->currentOffset += dict->dictSize;
  689. while (p <= dictEnd-MINMATCH)
  690. {
  691. LZ4_putPosition(p, dict, byU32, base);
  692. p+=3;
  693. }
  694. return dict->dictSize;
  695. }
  696. static void LZ4_renormDictT(LZ4_stream_t_internal* LZ4_dict, const BYTE* src)
  697. {
  698. if ((LZ4_dict->currentOffset > 0x80000000) ||
  699. ((size_t)LZ4_dict->currentOffset > (size_t)src)) /* address space overflow */
  700. {
  701. /* rescale hash table */
  702. U32 delta = LZ4_dict->currentOffset - 64 KB;
  703. const BYTE* dictEnd = LZ4_dict->dictionary + LZ4_dict->dictSize;
  704. int i;
  705. for (i=0; i<HASH_SIZE_U32; i++)
  706. {
  707. if (LZ4_dict->hashTable[i] < delta) LZ4_dict->hashTable[i]=0;
  708. else LZ4_dict->hashTable[i] -= delta;
  709. }
  710. LZ4_dict->currentOffset = 64 KB;
  711. if (LZ4_dict->dictSize > 64 KB) LZ4_dict->dictSize = 64 KB;
  712. LZ4_dict->dictionary = dictEnd - LZ4_dict->dictSize;
  713. }
  714. }
  715. FORCE_INLINE int LZ4_compress_continue_generic (void* LZ4_stream, const char* source, char* dest, int inputSize,
  716. int maxOutputSize, limitedOutput_directive limit)
  717. {
  718. LZ4_stream_t_internal* streamPtr = (LZ4_stream_t_internal*)LZ4_stream;
  719. const BYTE* const dictEnd = streamPtr->dictionary + streamPtr->dictSize;
  720. const BYTE* smallest = (const BYTE*) source;
  721. if (streamPtr->initCheck) return 0; /* Uninitialized structure detected */
  722. if ((streamPtr->dictSize>0) && (smallest>dictEnd)) smallest = dictEnd;
  723. LZ4_renormDictT(streamPtr, smallest);
  724. /* Check overlapping input/dictionary space */
  725. {
  726. const BYTE* sourceEnd = (const BYTE*) source + inputSize;
  727. if ((sourceEnd > streamPtr->dictionary) && (sourceEnd < dictEnd))
  728. {
  729. streamPtr->dictSize = (U32)(dictEnd - sourceEnd);
  730. if (streamPtr->dictSize > 64 KB) streamPtr->dictSize = 64 KB;
  731. if (streamPtr->dictSize < 4) streamPtr->dictSize = 0;
  732. streamPtr->dictionary = dictEnd - streamPtr->dictSize;
  733. }
  734. }
  735. /* prefix mode : source data follows dictionary */
  736. if (dictEnd == (const BYTE*)source)
  737. {
  738. int result;
  739. if ((streamPtr->dictSize < 64 KB) && (streamPtr->dictSize < streamPtr->currentOffset))
  740. result = LZ4_compress_generic(LZ4_stream, source, dest, inputSize, maxOutputSize, limit, byU32, withPrefix64k, dictSmall);
  741. else
  742. result = LZ4_compress_generic(LZ4_stream, source, dest, inputSize, maxOutputSize, limit, byU32, withPrefix64k, noDictIssue);
  743. streamPtr->dictSize += (U32)inputSize;
  744. streamPtr->currentOffset += (U32)inputSize;
  745. return result;
  746. }
  747. /* external dictionary mode */
  748. {
  749. int result;
  750. if ((streamPtr->dictSize < 64 KB) && (streamPtr->dictSize < streamPtr->currentOffset))
  751. result = LZ4_compress_generic(LZ4_stream, source, dest, inputSize, maxOutputSize, limit, byU32, usingExtDict, dictSmall);
  752. else
  753. result = LZ4_compress_generic(LZ4_stream, source, dest, inputSize, maxOutputSize, limit, byU32, usingExtDict, noDictIssue);
  754. streamPtr->dictionary = (const BYTE*)source;
  755. streamPtr->dictSize = (U32)inputSize;
  756. streamPtr->currentOffset += (U32)inputSize;
  757. return result;
  758. }
  759. }
  760. int LZ4_compress_continue (LZ4_stream_t* LZ4_stream, const char* source, char* dest, int inputSize)
  761. {
  762. return LZ4_compress_continue_generic(LZ4_stream, source, dest, inputSize, 0, notLimited);
  763. }
  764. int LZ4_compress_limitedOutput_continue (LZ4_stream_t* LZ4_stream, const char* source, char* dest, int inputSize, int maxOutputSize)
  765. {
  766. return LZ4_compress_continue_generic(LZ4_stream, source, dest, inputSize, maxOutputSize, limitedOutput);
  767. }
  768. /* Hidden debug function, to force separate dictionary mode */
  769. int LZ4_compress_forceExtDict (LZ4_stream_t* LZ4_dict, const char* source, char* dest, int inputSize)
  770. {
  771. LZ4_stream_t_internal* streamPtr = (LZ4_stream_t_internal*)LZ4_dict;
  772. int result;
  773. const BYTE* const dictEnd = streamPtr->dictionary + streamPtr->dictSize;
  774. const BYTE* smallest = dictEnd;
  775. if (smallest > (const BYTE*) source) smallest = (const BYTE*) source;
  776. LZ4_renormDictT((LZ4_stream_t_internal*)LZ4_dict, smallest);
  777. result = LZ4_compress_generic(LZ4_dict, source, dest, inputSize, 0, notLimited, byU32, usingExtDict, noDictIssue);
  778. streamPtr->dictionary = (const BYTE*)source;
  779. streamPtr->dictSize = (U32)inputSize;
  780. streamPtr->currentOffset += (U32)inputSize;
  781. return result;
  782. }
  783. int LZ4_saveDict (LZ4_stream_t* LZ4_dict, char* safeBuffer, int dictSize)
  784. {
  785. LZ4_stream_t_internal* dict = (LZ4_stream_t_internal*) LZ4_dict;
  786. const BYTE* previousDictEnd = dict->dictionary + dict->dictSize;
  787. if ((U32)dictSize > 64 KB) dictSize = 64 KB; /* useless to define a dictionary > 64 KB */
  788. if ((U32)dictSize > dict->dictSize) dictSize = dict->dictSize;
  789. memmove(safeBuffer, previousDictEnd - dictSize, dictSize);
  790. dict->dictionary = (const BYTE*)safeBuffer;
  791. dict->dictSize = (U32)dictSize;
  792. return dictSize;
  793. }
  794. /****************************
  795. Decompression functions
  796. ****************************/
  797. /*
  798. * This generic decompression function cover all use cases.
  799. * It shall be instantiated several times, using different sets of directives
  800. * Note that it is essential this generic function is really inlined,
  801. * in order to remove useless branches during compilation optimization.
  802. */
  803. FORCE_INLINE int LZ4_decompress_generic(
  804. const char* const source,
  805. char* const dest,
  806. int inputSize,
  807. int outputSize, /* If endOnInput==endOnInputSize, this value is the max size of Output Buffer. */
  808. int endOnInput, /* endOnOutputSize, endOnInputSize */
  809. int partialDecoding, /* full, partial */
  810. int targetOutputSize, /* only used if partialDecoding==partial */
  811. int dict, /* noDict, withPrefix64k, usingExtDict */
  812. const BYTE* const lowPrefix, /* == dest if dict == noDict */
  813. const BYTE* const dictStart, /* only if dict==usingExtDict */
  814. const size_t dictSize /* note : = 0 if noDict */
  815. )
  816. {
  817. /* Local Variables */
  818. const BYTE* restrict ip = (const BYTE*) source;
  819. const BYTE* const iend = ip + inputSize;
  820. BYTE* op = (BYTE*) dest;
  821. BYTE* const oend = op + outputSize;
  822. BYTE* cpy;
  823. BYTE* oexit = op + targetOutputSize;
  824. const BYTE* const lowLimit = lowPrefix - dictSize;
  825. const BYTE* const dictEnd = (const BYTE*)dictStart + dictSize;
  826. const size_t dec32table[] = {4, 1, 2, 1, 4, 4, 4, 4};
  827. const size_t dec64table[] = {0, 0, 0, (size_t)-1, 0, 1, 2, 3};
  828. const int safeDecode = (endOnInput==endOnInputSize);
  829. const int checkOffset = ((safeDecode) && (dictSize < (int)(64 KB)));
  830. /* Special cases */
  831. if ((partialDecoding) && (oexit> oend-MFLIMIT)) oexit = oend-MFLIMIT; /* targetOutputSize too high => decode everything */
  832. if ((endOnInput) && (unlikely(outputSize==0))) return ((inputSize==1) && (*ip==0)) ? 0 : -1; /* Empty output buffer */
  833. if ((!endOnInput) && (unlikely(outputSize==0))) return (*ip==0?1:-1);
  834. /* Main Loop */
  835. while (1)
  836. {
  837. unsigned token;
  838. size_t length;
  839. const BYTE* match;
  840. /* get literal length */
  841. token = *ip++;
  842. if ((length=(token>>ML_BITS)) == RUN_MASK)
  843. {
  844. unsigned s;
  845. do
  846. {
  847. s = *ip++;
  848. length += s;
  849. }
  850. while (likely((endOnInput)?ip<iend-RUN_MASK:1) && (s==255));
  851. if ((safeDecode) && unlikely((size_t)(op+length)<(size_t)(op))) goto _output_error; /* overflow detection */
  852. if ((safeDecode) && unlikely((size_t)(ip+length)<(size_t)(ip))) goto _output_error; /* overflow detection */
  853. }
  854. /* copy literals */
  855. cpy = op+length;
  856. if (((endOnInput) && ((cpy>(partialDecoding?oexit:oend-MFLIMIT)) || (ip+length>iend-(2+1+LASTLITERALS))) )
  857. || ((!endOnInput) && (cpy>oend-COPYLENGTH)))
  858. {
  859. if (partialDecoding)
  860. {
  861. if (cpy > oend) goto _output_error; /* Error : write attempt beyond end of output buffer */
  862. if ((endOnInput) && (ip+length > iend)) goto _output_error; /* Error : read attempt beyond end of input buffer */
  863. }
  864. else
  865. {
  866. if ((!endOnInput) && (cpy != oend)) goto _output_error; /* Error : block decoding must stop exactly there */
  867. if ((endOnInput) && ((ip+length != iend) || (cpy > oend))) goto _output_error; /* Error : input must be consumed */
  868. }
  869. memcpy(op, ip, length);
  870. ip += length;
  871. op += length;
  872. break; /* Necessarily EOF, due to parsing restrictions */
  873. }
  874. LZ4_wildCopy(op, ip, cpy);
  875. ip += length; op = cpy;
  876. /* get offset */
  877. match = cpy - LZ4_readLE16(ip); ip+=2;
  878. if ((checkOffset) && (unlikely(match < lowLimit))) goto _output_error; /* Error : offset outside destination buffer */
  879. /* get matchlength */
  880. length = token & ML_MASK;
  881. if (length == ML_MASK)
  882. {
  883. unsigned s;
  884. do
  885. {
  886. if ((endOnInput) && (ip > iend-LASTLITERALS)) goto _output_error;
  887. s = *ip++;
  888. length += s;
  889. } while (s==255);
  890. if ((safeDecode) && unlikely((size_t)(op+length)<(size_t)op)) goto _output_error; /* overflow detection */
  891. }
  892. length += MINMATCH;
  893. /* check external dictionary */
  894. if ((dict==usingExtDict) && (match < lowPrefix))
  895. {
  896. if (unlikely(op+length > oend-LASTLITERALS)) goto _output_error; /* doesn't respect parsing restriction */
  897. if (length <= (size_t)(lowPrefix-match))
  898. {
  899. /* match can be copied as a single segment from external dictionary */
  900. match = dictEnd - (lowPrefix-match);
  901. memcpy(op, match, length);
  902. op += length;
  903. }
  904. else
  905. {
  906. /* match encompass external dictionary and current segment */
  907. size_t copySize = (size_t)(lowPrefix-match);
  908. memcpy(op, dictEnd - copySize, copySize);
  909. op += copySize;
  910. copySize = length - copySize;
  911. if (copySize > (size_t)(op-lowPrefix)) /* overlap within current segment */
  912. {
  913. BYTE* const endOfMatch = op + copySize;
  914. const BYTE* copyFrom = lowPrefix;
  915. while (op < endOfMatch) *op++ = *copyFrom++;
  916. }
  917. else
  918. {
  919. memcpy(op, lowPrefix, copySize);
  920. op += copySize;
  921. }
  922. }
  923. continue;
  924. }
  925. /* copy repeated sequence */
  926. cpy = op + length;
  927. if (unlikely((op-match)<8))
  928. {
  929. const size_t dec64 = dec64table[op-match];
  930. op[0] = match[0];
  931. op[1] = match[1];
  932. op[2] = match[2];
  933. op[3] = match[3];
  934. match += dec32table[op-match];
  935. LZ4_copy4(op+4, match);
  936. op += 8; match -= dec64;
  937. } else { LZ4_copy8(op, match); op+=8; match+=8; }
  938. if (unlikely(cpy>oend-12))
  939. {
  940. if (cpy > oend-LASTLITERALS) goto _output_error; /* Error : last LASTLITERALS bytes must be literals */
  941. if (op < oend-8)
  942. {
  943. LZ4_wildCopy(op, match, oend-8);
  944. match += (oend-8) - op;
  945. op = oend-8;
  946. }
  947. while (op<cpy) *op++ = *match++;
  948. }
  949. else
  950. LZ4_wildCopy(op, match, cpy);
  951. op=cpy; /* correction */
  952. }
  953. /* end of decoding */
  954. if (endOnInput)
  955. return (int) (((char*)op)-dest); /* Nb of output bytes decoded */
  956. else
  957. return (int) (((char*)ip)-source); /* Nb of input bytes read */
  958. /* Overflow error detected */
  959. _output_error:
  960. return (int) (-(((char*)ip)-source))-1;
  961. }
  962. int LZ4_decompress_safe(const char* source, char* dest, int compressedSize, int maxDecompressedSize)
  963. {
  964. return LZ4_decompress_generic(source, dest, compressedSize, maxDecompressedSize, endOnInputSize, full, 0, noDict, (BYTE*)dest, NULL, 0);
  965. }
  966. int LZ4_decompress_safe_partial(const char* source, char* dest, int compressedSize, int targetOutputSize, int maxDecompressedSize)
  967. {
  968. return LZ4_decompress_generic(source, dest, compressedSize, maxDecompressedSize, endOnInputSize, partial, targetOutputSize, noDict, (BYTE*)dest, NULL, 0);
  969. }
  970. int LZ4_decompress_fast(const char* source, char* dest, int originalSize)
  971. {
  972. return LZ4_decompress_generic(source, dest, 0, originalSize, endOnOutputSize, full, 0, withPrefix64k, (BYTE*)(dest - 64 KB), NULL, 64 KB);
  973. }
  974. /* streaming decompression functions */
  975. typedef struct
  976. {
  977. BYTE* externalDict;
  978. size_t extDictSize;
  979. BYTE* prefixEnd;
  980. size_t prefixSize;
  981. } LZ4_streamDecode_t_internal;
  982. /*
  983. * If you prefer dynamic allocation methods,
  984. * LZ4_createStreamDecode()
  985. * provides a pointer (void*) towards an initialized LZ4_streamDecode_t structure.
  986. */
  987. LZ4_streamDecode_t* LZ4_createStreamDecode(void)
  988. {
  989. LZ4_streamDecode_t* lz4s = (LZ4_streamDecode_t*) ALLOCATOR(sizeof(U64), LZ4_STREAMDECODESIZE_U64);
  990. return lz4s;
  991. }
  992. int LZ4_freeStreamDecode (LZ4_streamDecode_t* LZ4_stream)
  993. {
  994. FREEMEM(LZ4_stream);
  995. return 0;
  996. }
  997. /*
  998. * LZ4_setStreamDecode
  999. * Use this function to instruct where to find the dictionary
  1000. * This function is not necessary if previous data is still available where it was decoded.
  1001. * Loading a size of 0 is allowed (same effect as no dictionary).
  1002. * Return : 1 if OK, 0 if error
  1003. */
  1004. int LZ4_setStreamDecode (LZ4_streamDecode_t* LZ4_streamDecode, const char* dictionary, int dictSize)
  1005. {
  1006. LZ4_streamDecode_t_internal* lz4sd = (LZ4_streamDecode_t_internal*) LZ4_streamDecode;
  1007. lz4sd->prefixSize = (size_t) dictSize;
  1008. lz4sd->prefixEnd = (BYTE*) dictionary + dictSize;
  1009. lz4sd->externalDict = NULL;
  1010. lz4sd->extDictSize = 0;
  1011. return 1;
  1012. }
  1013. /*
  1014. *_continue() :
  1015. These decoding functions allow decompression of multiple blocks in "streaming" mode.
  1016. Previously decoded blocks must still be available at the memory position where they were decoded.
  1017. If it's not possible, save the relevant part of decoded data into a safe buffer,
  1018. and indicate where it stands using LZ4_setStreamDecode()
  1019. */
  1020. int LZ4_decompress_safe_continue (LZ4_streamDecode_t* LZ4_streamDecode, const char* source, char* dest, int compressedSize, int maxOutputSize)
  1021. {
  1022. LZ4_streamDecode_t_internal* lz4sd = (LZ4_streamDecode_t_internal*) LZ4_streamDecode;
  1023. int result;
  1024. if (lz4sd->prefixEnd == (BYTE*)dest)
  1025. {
  1026. result = LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize,
  1027. endOnInputSize, full, 0,
  1028. usingExtDict, lz4sd->prefixEnd - lz4sd->prefixSize, lz4sd->externalDict, lz4sd->extDictSize);
  1029. if (result <= 0) return result;
  1030. lz4sd->prefixSize += result;
  1031. lz4sd->prefixEnd += result;
  1032. }
  1033. else
  1034. {
  1035. lz4sd->extDictSize = lz4sd->prefixSize;
  1036. lz4sd->externalDict = lz4sd->prefixEnd - lz4sd->extDictSize;
  1037. result = LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize,
  1038. endOnInputSize, full, 0,
  1039. usingExtDict, (BYTE*)dest, lz4sd->externalDict, lz4sd->extDictSize);
  1040. if (result <= 0) return result;
  1041. lz4sd->prefixSize = result;
  1042. lz4sd->prefixEnd = (BYTE*)dest + result;
  1043. }
  1044. return result;
  1045. }
  1046. int LZ4_decompress_fast_continue (LZ4_streamDecode_t* LZ4_streamDecode, const char* source, char* dest, int originalSize)
  1047. {
  1048. LZ4_streamDecode_t_internal* lz4sd = (LZ4_streamDecode_t_internal*) LZ4_streamDecode;
  1049. int result;
  1050. if (lz4sd->prefixEnd == (BYTE*)dest)
  1051. {
  1052. result = LZ4_decompress_generic(source, dest, 0, originalSize,
  1053. endOnOutputSize, full, 0,
  1054. usingExtDict, lz4sd->prefixEnd - lz4sd->prefixSize, lz4sd->externalDict, lz4sd->extDictSize);
  1055. if (result <= 0) return result;
  1056. lz4sd->prefixSize += originalSize;
  1057. lz4sd->prefixEnd += originalSize;
  1058. }
  1059. else
  1060. {
  1061. lz4sd->extDictSize = lz4sd->prefixSize;
  1062. lz4sd->externalDict = (BYTE*)dest - lz4sd->extDictSize;
  1063. result = LZ4_decompress_generic(source, dest, 0, originalSize,
  1064. endOnOutputSize, full, 0,
  1065. usingExtDict, (BYTE*)dest, lz4sd->externalDict, lz4sd->extDictSize);
  1066. if (result <= 0) return result;
  1067. lz4sd->prefixSize = originalSize;
  1068. lz4sd->prefixEnd = (BYTE*)dest + originalSize;
  1069. }
  1070. return result;
  1071. }
  1072. /*
  1073. Advanced decoding functions :
  1074. *_usingDict() :
  1075. These decoding functions work the same as "_continue" ones,
  1076. the dictionary must be explicitly provided within parameters
  1077. */
  1078. FORCE_INLINE int LZ4_decompress_usingDict_generic(const char* source, char* dest, int compressedSize, int maxOutputSize, int safe, const char* dictStart, int dictSize)
  1079. {
  1080. if (dictSize==0)
  1081. return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize, safe, full, 0, noDict, (BYTE*)dest, NULL, 0);
  1082. if (dictStart+dictSize == dest)
  1083. {
  1084. if (dictSize >= (int)(64 KB - 1))
  1085. return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize, safe, full, 0, withPrefix64k, (BYTE*)dest-64 KB, NULL, 0);
  1086. return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize, safe, full, 0, noDict, (BYTE*)dest-dictSize, NULL, 0);
  1087. }
  1088. return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize, safe, full, 0, usingExtDict, (BYTE*)dest, (BYTE*)dictStart, dictSize);
  1089. }
  1090. int LZ4_decompress_safe_usingDict(const char* source, char* dest, int compressedSize, int maxOutputSize, const char* dictStart, int dictSize)
  1091. {
  1092. return LZ4_decompress_usingDict_generic(source, dest, compressedSize, maxOutputSize, 1, dictStart, dictSize);
  1093. }
  1094. int LZ4_decompress_fast_usingDict(const char* source, char* dest, int originalSize, const char* dictStart, int dictSize)
  1095. {
  1096. return LZ4_decompress_usingDict_generic(source, dest, 0, originalSize, 0, dictStart, dictSize);
  1097. }
  1098. /* debug function */
  1099. int LZ4_decompress_safe_forceExtDict(const char* source, char* dest, int compressedSize, int maxOutputSize, const char* dictStart, int dictSize)
  1100. {
  1101. return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize, endOnInputSize, full, 0, usingExtDict, (BYTE*)dest, (BYTE*)dictStart, dictSize);
  1102. }
  1103. /***************************************************
  1104. Obsolete Functions
  1105. ***************************************************/
  1106. /*
  1107. These function names are deprecated and should no longer be used.
  1108. They are only provided here for compatibility with older user programs.
  1109. - LZ4_uncompress is totally equivalent to LZ4_decompress_fast
  1110. - LZ4_uncompress_unknownOutputSize is totally equivalent to LZ4_decompress_safe
  1111. */
  1112. int LZ4_uncompress (const char* source, char* dest, int outputSize) { return LZ4_decompress_fast(source, dest, outputSize); }
  1113. int LZ4_uncompress_unknownOutputSize (const char* source, char* dest, int isize, int maxOutputSize) { return LZ4_decompress_safe(source, dest, isize, maxOutputSize); }
  1114. /* Obsolete Streaming functions */
  1115. int LZ4_sizeofStreamState() { return LZ4_STREAMSIZE; }
  1116. static void LZ4_init(LZ4_stream_t_internal* lz4ds, const BYTE* base)
  1117. {
  1118. MEM_INIT(lz4ds, 0, LZ4_STREAMSIZE);
  1119. lz4ds->bufferStart = base;
  1120. }
  1121. int LZ4_resetStreamState(void* state, const char* inputBuffer)
  1122. {
  1123. if ((((size_t)state) & 3) != 0) return 1; /* Error : pointer is not aligned on 4-bytes boundary */
  1124. LZ4_init((LZ4_stream_t_internal*)state, (const BYTE*)inputBuffer);
  1125. return 0;
  1126. }
  1127. void* LZ4_create (const char* inputBuffer)
  1128. {
  1129. void* lz4ds = ALLOCATOR(8, LZ4_STREAMSIZE_U64);
  1130. LZ4_init ((LZ4_stream_t_internal*)lz4ds, (const BYTE*)inputBuffer);
  1131. return lz4ds;
  1132. }
  1133. char* LZ4_slideInputBuffer (void* LZ4_Data)
  1134. {
  1135. LZ4_stream_t_internal* ctx = (LZ4_stream_t_internal*)LZ4_Data;
  1136. int dictSize = LZ4_saveDict((LZ4_stream_t*)ctx, (char*)ctx->bufferStart, 64 KB);
  1137. return (char*)(ctx->bufferStart + dictSize);
  1138. }
  1139. /* Obsolete compresson functions using User-allocated state */
  1140. int LZ4_sizeofState() { return LZ4_STREAMSIZE; }
  1141. int LZ4_compress_withState (void* state, const char* source, char* dest, int inputSize)
  1142. {
  1143. if (((size_t)(state)&3) != 0) return 0; /* Error : state is not aligned on 4-bytes boundary */
  1144. MEM_INIT(state, 0, LZ4_STREAMSIZE);
  1145. if (inputSize < LZ4_64Klimit)
  1146. return LZ4_compress_generic(state, source, dest, inputSize, 0, notLimited, byU16, noDict, noDictIssue);
  1147. else
  1148. return LZ4_compress_generic(state, source, dest, inputSize, 0, notLimited, LZ4_64bits() ? byU32 : byPtr, noDict, noDictIssue);
  1149. }
  1150. int LZ4_compress_limitedOutput_withState (void* state, const char* source, char* dest, int inputSize, int maxOutputSize)
  1151. {
  1152. if (((size_t)(state)&3) != 0) return 0; /* Error : state is not aligned on 4-bytes boundary */
  1153. MEM_INIT(state, 0, LZ4_STREAMSIZE);
  1154. if (inputSize < LZ4_64Klimit)
  1155. return LZ4_compress_generic(state, source, dest, inputSize, maxOutputSize, limitedOutput, byU16, noDict, noDictIssue);
  1156. else
  1157. return LZ4_compress_generic(state, source, dest, inputSize, maxOutputSize, limitedOutput, LZ4_64bits() ? byU32 : byPtr, noDict, noDictIssue);
  1158. }
  1159. /* Obsolete streaming decompression functions */
  1160. int LZ4_decompress_safe_withPrefix64k(const char* source, char* dest, int compressedSize, int maxOutputSize)
  1161. {
  1162. return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize, endOnInputSize, full, 0, withPrefix64k, (BYTE*)dest - 64 KB, NULL, 64 KB);
  1163. }
  1164. int LZ4_decompress_fast_withPrefix64k(const char* source, char* dest, int originalSize)
  1165. {
  1166. return LZ4_decompress_generic(source, dest, 0, originalSize, endOnOutputSize, full, 0, withPrefix64k, (BYTE*)dest - 64 KB, NULL, 64 KB);
  1167. }
  1168. #endif /* LZ4_COMMONDEFS_ONLY */