lz4.c 44 KB

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