lz4.c 99 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404
  1. /*
  2. LZ4 - Fast LZ compression algorithm
  3. Copyright (C) 2011-present, 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 homepage : http://www.lz4.org
  27. - LZ4 source repository : https://github.com/lz4/lz4
  28. */
  29. /* --- Customization --- */
  30. #define LZ4_FORCE_INLINE static
  31. #define LZ4_HEAPMODE 1
  32. #define LZ4_FORCE_MEMORY_ACCESS 1
  33. /*-************************************
  34. * Tuning parameters
  35. **************************************/
  36. /*
  37. * LZ4_HEAPMODE :
  38. * Select how default compression functions will allocate memory for their hash table,
  39. * in memory stack (0:default, fastest), or in memory heap (1:requires malloc()).
  40. */
  41. #ifndef LZ4_HEAPMODE
  42. # define LZ4_HEAPMODE 0
  43. #endif
  44. /*
  45. * ACCELERATION_DEFAULT :
  46. * Select "acceleration" for LZ4_compress_fast() when parameter value <= 0
  47. */
  48. #define ACCELERATION_DEFAULT 1
  49. /*-************************************
  50. * CPU Feature Detection
  51. **************************************/
  52. /* LZ4_FORCE_MEMORY_ACCESS
  53. * By default, access to unaligned memory is controlled by `memcpy()`, which is safe and portable.
  54. * Unfortunately, on some target/compiler combinations, the generated assembly is sub-optimal.
  55. * The below switch allow to select different access method for improved performance.
  56. * Method 0 (default) : use `memcpy()`. Safe and portable.
  57. * Method 1 : `__packed` statement. It depends on compiler extension (ie, not portable).
  58. * This method is safe if your compiler supports it, and *generally* as fast or faster than `memcpy`.
  59. * Method 2 : direct access. This method is portable but violate C standard.
  60. * It can generate buggy code on targets which assembly generation depends on alignment.
  61. * But in some circumstances, it's the only known way to get the most performance (ie GCC + ARMv6)
  62. * See https://fastcompression.blogspot.fr/2015/08/accessing-unaligned-memory.html for details.
  63. * Prefer these methods in priority order (0 > 1 > 2)
  64. */
  65. #ifndef LZ4_FORCE_MEMORY_ACCESS /* can be defined externally */
  66. # if defined(__GNUC__) && \
  67. ( defined(__ARM_ARCH_6__) || defined(__ARM_ARCH_6J__) || defined(__ARM_ARCH_6K__) \
  68. || defined(__ARM_ARCH_6Z__) || defined(__ARM_ARCH_6ZK__) || defined(__ARM_ARCH_6T2__) )
  69. # define LZ4_FORCE_MEMORY_ACCESS 2
  70. # elif (defined(__INTEL_COMPILER) && !defined(_WIN32)) || defined(__GNUC__)
  71. # define LZ4_FORCE_MEMORY_ACCESS 1
  72. # endif
  73. #endif
  74. /*
  75. * LZ4_FORCE_SW_BITCOUNT
  76. * Define this parameter if your target system or compiler does not support hardware bit count
  77. */
  78. #if defined(_MSC_VER) && defined(_WIN32_WCE) /* Visual Studio for WinCE doesn't support Hardware bit count */
  79. # define LZ4_FORCE_SW_BITCOUNT
  80. #endif
  81. /*-************************************
  82. * Dependency
  83. **************************************/
  84. /*
  85. * LZ4_SRC_INCLUDED:
  86. * Amalgamation flag, whether lz4.c is included
  87. */
  88. #ifndef LZ4_SRC_INCLUDED
  89. # define LZ4_SRC_INCLUDED 1
  90. #endif
  91. #ifndef LZ4_STATIC_LINKING_ONLY
  92. #define LZ4_STATIC_LINKING_ONLY
  93. #endif
  94. #ifndef LZ4_DISABLE_DEPRECATE_WARNINGS
  95. #define LZ4_DISABLE_DEPRECATE_WARNINGS /* due to LZ4_decompress_safe_withPrefix64k */
  96. #endif
  97. #define LZ4_STATIC_LINKING_ONLY /* LZ4_DISTANCE_MAX */
  98. #include "lz4.h"
  99. /* see also "memory routines" below */
  100. /*-************************************
  101. * Compiler Options
  102. **************************************/
  103. #ifdef _MSC_VER /* Visual Studio */
  104. # include <intrin.h>
  105. # pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */
  106. # pragma warning(disable : 4293) /* disable: C4293: too large shift (32-bits) */
  107. #endif /* _MSC_VER */
  108. #ifndef LZ4_FORCE_INLINE
  109. # ifdef _MSC_VER /* Visual Studio */
  110. # define LZ4_FORCE_INLINE static __forceinline
  111. # else
  112. # if defined (__cplusplus) || defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* C99 */
  113. # ifdef __GNUC__
  114. # define LZ4_FORCE_INLINE static inline __attribute__((always_inline))
  115. # else
  116. # define LZ4_FORCE_INLINE static inline
  117. # endif
  118. # else
  119. # define LZ4_FORCE_INLINE static
  120. # endif /* __STDC_VERSION__ */
  121. # endif /* _MSC_VER */
  122. #endif /* LZ4_FORCE_INLINE */
  123. /* LZ4_FORCE_O2_GCC_PPC64LE and LZ4_FORCE_O2_INLINE_GCC_PPC64LE
  124. * gcc on ppc64le generates an unrolled SIMDized loop for LZ4_wildCopy8,
  125. * together with a simple 8-byte copy loop as a fall-back path.
  126. * However, this optimization hurts the decompression speed by >30%,
  127. * because the execution does not go to the optimized loop
  128. * for typical compressible data, and all of the preamble checks
  129. * before going to the fall-back path become useless overhead.
  130. * This optimization happens only with the -O3 flag, and -O2 generates
  131. * a simple 8-byte copy loop.
  132. * With gcc on ppc64le, all of the LZ4_decompress_* and LZ4_wildCopy8
  133. * functions are annotated with __attribute__((optimize("O2"))),
  134. * and also LZ4_wildCopy8 is forcibly inlined, so that the O2 attribute
  135. * of LZ4_wildCopy8 does not affect the compression speed.
  136. */
  137. #if defined(__PPC64__) && defined(__LITTLE_ENDIAN__) && defined(__GNUC__) && !defined(__clang__)
  138. # define LZ4_FORCE_O2_GCC_PPC64LE __attribute__((optimize("O2")))
  139. # define LZ4_FORCE_O2_INLINE_GCC_PPC64LE __attribute__((optimize("O2"))) LZ4_FORCE_INLINE
  140. #else
  141. # define LZ4_FORCE_O2_GCC_PPC64LE
  142. # define LZ4_FORCE_O2_INLINE_GCC_PPC64LE static
  143. #endif
  144. #if (defined(__GNUC__) && (__GNUC__ >= 3)) || (defined(__INTEL_COMPILER) && (__INTEL_COMPILER >= 800)) || defined(__clang__)
  145. # define expect(expr,value) (__builtin_expect ((expr),(value)) )
  146. #else
  147. # define expect(expr,value) (expr)
  148. #endif
  149. #ifndef likely
  150. #define likely(expr) expect((expr) != 0, 1)
  151. #endif
  152. #ifndef unlikely
  153. #define unlikely(expr) expect((expr) != 0, 0)
  154. #endif
  155. /*-************************************
  156. * Memory routines
  157. **************************************/
  158. #include <stdlib.h> /* malloc, calloc, free */
  159. #define ALLOC(s) malloc(s)
  160. #define ALLOC_AND_ZERO(s) calloc(1,s)
  161. #define FREEMEM(p) free(p)
  162. #include <string.h> /* memset, memcpy */
  163. #define MEM_INIT(p,v,s) memset((p),(v),(s))
  164. /*-************************************
  165. * Common Constants
  166. **************************************/
  167. #define MINMATCH 4
  168. #define WILDCOPYLENGTH 8
  169. #define LASTLITERALS 5 /* see ../doc/lz4_Block_format.md#parsing-restrictions */
  170. #define MFLIMIT 12 /* see ../doc/lz4_Block_format.md#parsing-restrictions */
  171. #define MATCH_SAFEGUARD_DISTANCE ((2*WILDCOPYLENGTH) - MINMATCH) /* ensure it's possible to write 2 x wildcopyLength without overflowing output buffer */
  172. #define FASTLOOP_SAFE_DISTANCE 64
  173. static const int LZ4_minLength = (MFLIMIT+1);
  174. #define KB *(1 <<10)
  175. #define MB *(1 <<20)
  176. #define GB *(1U<<30)
  177. #define LZ4_DISTANCE_ABSOLUTE_MAX 65535
  178. #if (LZ4_DISTANCE_MAX > LZ4_DISTANCE_ABSOLUTE_MAX) /* max supported by LZ4 format */
  179. # error "LZ4_DISTANCE_MAX is too big : must be <= 65535"
  180. #endif
  181. #define ML_BITS 4
  182. #define ML_MASK ((1U<<ML_BITS)-1)
  183. #define RUN_BITS (8-ML_BITS)
  184. #define RUN_MASK ((1U<<RUN_BITS)-1)
  185. /*-************************************
  186. * Error detection
  187. **************************************/
  188. #if defined(LZ4_DEBUG) && (LZ4_DEBUG>=1)
  189. # include <assert.h>
  190. #else
  191. # ifndef assert
  192. # define assert(condition) ((void)0)
  193. # endif
  194. #endif
  195. #define LZ4_STATIC_ASSERT(c) { enum { LZ4_static_assert = 1/(int)(!!(c)) }; } /* use after variable declarations */
  196. #if defined(LZ4_DEBUG) && (LZ4_DEBUG>=2)
  197. # include <stdio.h>
  198. static int g_debuglog_enable = 1;
  199. # define DEBUGLOG(l, ...) { \
  200. if ((g_debuglog_enable) && (l<=LZ4_DEBUG)) { \
  201. fprintf(stderr, __FILE__ ": "); \
  202. fprintf(stderr, __VA_ARGS__); \
  203. fprintf(stderr, " \n"); \
  204. } }
  205. #else
  206. # define DEBUGLOG(l, ...) {} /* disabled */
  207. #endif
  208. /*-************************************
  209. * Types
  210. **************************************/
  211. #if defined(__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */)
  212. # include <stdint.h>
  213. typedef uint8_t BYTE;
  214. typedef uint16_t U16;
  215. typedef uint32_t U32;
  216. typedef int32_t S32;
  217. typedef uint64_t U64;
  218. typedef uintptr_t uptrval;
  219. #else
  220. typedef unsigned char BYTE;
  221. typedef unsigned short U16;
  222. typedef unsigned int U32;
  223. typedef signed int S32;
  224. typedef unsigned long long U64;
  225. typedef size_t uptrval; /* generally true, except OpenVMS-64 */
  226. #endif
  227. #if defined(__x86_64__)
  228. typedef U64 reg_t; /* 64-bits in x32 mode */
  229. #else
  230. typedef size_t reg_t; /* 32-bits in x32 mode */
  231. #endif
  232. typedef enum {
  233. notLimited = 0,
  234. limitedOutput = 1,
  235. fillOutput = 2
  236. } limitedOutput_directive;
  237. /*-************************************
  238. * Reading and writing into memory
  239. **************************************/
  240. static unsigned LZ4_isLittleEndian(void)
  241. {
  242. const union { U32 u; BYTE c[4]; } one = { 1 }; /* don't use static : performance detrimental */
  243. return one.c[0];
  244. }
  245. #if defined(LZ4_FORCE_MEMORY_ACCESS) && (LZ4_FORCE_MEMORY_ACCESS==2)
  246. /* lie to the compiler about data alignment; use with caution */
  247. static U16 LZ4_read16(const void* memPtr) { return *(const U16*) memPtr; }
  248. static U32 LZ4_read32(const void* memPtr) { return *(const U32*) memPtr; }
  249. static reg_t LZ4_read_ARCH(const void* memPtr) { return *(const reg_t*) memPtr; }
  250. static void LZ4_write16(void* memPtr, U16 value) { *(U16*)memPtr = value; }
  251. static void LZ4_write32(void* memPtr, U32 value) { *(U32*)memPtr = value; }
  252. #elif defined(LZ4_FORCE_MEMORY_ACCESS) && (LZ4_FORCE_MEMORY_ACCESS==1)
  253. /* __pack instructions are safer, but compiler specific, hence potentially problematic for some compilers */
  254. /* currently only defined for gcc and icc */
  255. typedef union { U16 u16; U32 u32; reg_t uArch; } __attribute__((packed)) unalign;
  256. static U16 LZ4_read16(const void* ptr) { return ((const unalign*)ptr)->u16; }
  257. static U32 LZ4_read32(const void* ptr) { return ((const unalign*)ptr)->u32; }
  258. static reg_t LZ4_read_ARCH(const void* ptr) { return ((const unalign*)ptr)->uArch; }
  259. static void LZ4_write16(void* memPtr, U16 value) { ((unalign*)memPtr)->u16 = value; }
  260. static void LZ4_write32(void* memPtr, U32 value) { ((unalign*)memPtr)->u32 = value; }
  261. #else /* safe and portable access using memcpy() */
  262. static U16 LZ4_read16(const void* memPtr)
  263. {
  264. U16 val; memcpy(&val, memPtr, sizeof(val)); return val;
  265. }
  266. static U32 LZ4_read32(const void* memPtr)
  267. {
  268. U32 val; memcpy(&val, memPtr, sizeof(val)); return val;
  269. }
  270. static reg_t LZ4_read_ARCH(const void* memPtr)
  271. {
  272. reg_t val; memcpy(&val, memPtr, sizeof(val)); return val;
  273. }
  274. static void LZ4_write16(void* memPtr, U16 value)
  275. {
  276. memcpy(memPtr, &value, sizeof(value));
  277. }
  278. static void LZ4_write32(void* memPtr, U32 value)
  279. {
  280. memcpy(memPtr, &value, sizeof(value));
  281. }
  282. #endif /* LZ4_FORCE_MEMORY_ACCESS */
  283. static U16 LZ4_readLE16(const void* memPtr)
  284. {
  285. if (LZ4_isLittleEndian()) {
  286. return LZ4_read16(memPtr);
  287. } else {
  288. const BYTE* p = (const BYTE*)memPtr;
  289. return (U16)((U16)p[0] + (p[1]<<8));
  290. }
  291. }
  292. static void LZ4_writeLE16(void* memPtr, U16 value)
  293. {
  294. if (LZ4_isLittleEndian()) {
  295. LZ4_write16(memPtr, value);
  296. } else {
  297. BYTE* p = (BYTE*)memPtr;
  298. p[0] = (BYTE) value;
  299. p[1] = (BYTE)(value>>8);
  300. }
  301. }
  302. /* customized variant of memcpy, which can overwrite up to 8 bytes beyond dstEnd */
  303. LZ4_FORCE_O2_INLINE_GCC_PPC64LE
  304. void LZ4_wildCopy8(void* dstPtr, const void* srcPtr, void* dstEnd)
  305. {
  306. BYTE* d = (BYTE*)dstPtr;
  307. const BYTE* s = (const BYTE*)srcPtr;
  308. BYTE* const e = (BYTE*)dstEnd;
  309. do { memcpy(d,s,8); d+=8; s+=8; } while (d<e);
  310. }
  311. static const unsigned inc32table[8] = {0, 1, 2, 1, 0, 4, 4, 4};
  312. static const int dec64table[8] = {0, 0, 0, -1, -4, 1, 2, 3};
  313. #ifndef LZ4_FAST_DEC_LOOP
  314. # if defined(__i386__) || defined(__x86_64__)
  315. # define LZ4_FAST_DEC_LOOP 1
  316. # elif defined(__aarch64__) && !defined(__clang__)
  317. /* On aarch64, we disable this optimization for clang because on certain
  318. * mobile chipsets and clang, it reduces performance. For more information
  319. * refer to https://github.com/lz4/lz4/pull/707. */
  320. # define LZ4_FAST_DEC_LOOP 1
  321. # else
  322. # define LZ4_FAST_DEC_LOOP 0
  323. # endif
  324. #endif
  325. #if LZ4_FAST_DEC_LOOP
  326. LZ4_FORCE_O2_INLINE_GCC_PPC64LE void
  327. LZ4_memcpy_using_offset_base(BYTE* dstPtr, const BYTE* srcPtr, BYTE* dstEnd, const size_t offset)
  328. {
  329. if (offset < 8) {
  330. dstPtr[0] = srcPtr[0];
  331. dstPtr[1] = srcPtr[1];
  332. dstPtr[2] = srcPtr[2];
  333. dstPtr[3] = srcPtr[3];
  334. srcPtr += inc32table[offset];
  335. memcpy(dstPtr+4, srcPtr, 4);
  336. srcPtr -= dec64table[offset];
  337. dstPtr += 8;
  338. } else {
  339. memcpy(dstPtr, srcPtr, 8);
  340. dstPtr += 8;
  341. srcPtr += 8;
  342. }
  343. LZ4_wildCopy8(dstPtr, srcPtr, dstEnd);
  344. }
  345. /* customized variant of memcpy, which can overwrite up to 32 bytes beyond dstEnd
  346. * this version copies two times 16 bytes (instead of one time 32 bytes)
  347. * because it must be compatible with offsets >= 16. */
  348. LZ4_FORCE_O2_INLINE_GCC_PPC64LE void
  349. LZ4_wildCopy32(void* dstPtr, const void* srcPtr, void* dstEnd)
  350. {
  351. BYTE* d = (BYTE*)dstPtr;
  352. const BYTE* s = (const BYTE*)srcPtr;
  353. BYTE* const e = (BYTE*)dstEnd;
  354. do { memcpy(d,s,16); memcpy(d+16,s+16,16); d+=32; s+=32; } while (d<e);
  355. }
  356. /* LZ4_memcpy_using_offset() presumes :
  357. * - dstEnd >= dstPtr + MINMATCH
  358. * - there is at least 8 bytes available to write after dstEnd */
  359. LZ4_FORCE_O2_INLINE_GCC_PPC64LE void
  360. LZ4_memcpy_using_offset(BYTE* dstPtr, const BYTE* srcPtr, BYTE* dstEnd, const size_t offset)
  361. {
  362. BYTE v[8];
  363. assert(dstEnd >= dstPtr + MINMATCH);
  364. LZ4_write32(dstPtr, 0); /* silence an msan warning when offset==0 */
  365. switch(offset) {
  366. case 1:
  367. memset(v, *srcPtr, 8);
  368. break;
  369. case 2:
  370. memcpy(v, srcPtr, 2);
  371. memcpy(&v[2], srcPtr, 2);
  372. memcpy(&v[4], &v[0], 4);
  373. break;
  374. case 4:
  375. memcpy(v, srcPtr, 4);
  376. memcpy(&v[4], srcPtr, 4);
  377. break;
  378. default:
  379. LZ4_memcpy_using_offset_base(dstPtr, srcPtr, dstEnd, offset);
  380. return;
  381. }
  382. memcpy(dstPtr, v, 8);
  383. dstPtr += 8;
  384. while (dstPtr < dstEnd) {
  385. memcpy(dstPtr, v, 8);
  386. dstPtr += 8;
  387. }
  388. }
  389. #endif
  390. /*-************************************
  391. * Common functions
  392. **************************************/
  393. static unsigned LZ4_NbCommonBytes (reg_t val)
  394. {
  395. if (LZ4_isLittleEndian()) {
  396. if (sizeof(val)==8) {
  397. # if defined(_MSC_VER) && defined(_WIN64) && !defined(LZ4_FORCE_SW_BITCOUNT)
  398. unsigned long r = 0;
  399. _BitScanForward64( &r, (U64)val );
  400. return (int)(r>>3);
  401. # elif (defined(__clang__) || (defined(__GNUC__) && (__GNUC__>=3))) && !defined(LZ4_FORCE_SW_BITCOUNT)
  402. return (unsigned)__builtin_ctzll((U64)val) >> 3;
  403. # else
  404. static const int DeBruijnBytePos[64] = { 0, 0, 0, 0, 0, 1, 1, 2,
  405. 0, 3, 1, 3, 1, 4, 2, 7,
  406. 0, 2, 3, 6, 1, 5, 3, 5,
  407. 1, 3, 4, 4, 2, 5, 6, 7,
  408. 7, 0, 1, 2, 3, 3, 4, 6,
  409. 2, 6, 5, 5, 3, 4, 5, 6,
  410. 7, 1, 2, 4, 6, 4, 4, 5,
  411. 7, 2, 6, 5, 7, 6, 7, 7 };
  412. return DeBruijnBytePos[((U64)((val & -(long long)val) * 0x0218A392CDABBD3FULL)) >> 58];
  413. # endif
  414. } else /* 32 bits */ {
  415. # if defined(_MSC_VER) && !defined(LZ4_FORCE_SW_BITCOUNT)
  416. unsigned long r;
  417. _BitScanForward( &r, (U32)val );
  418. return (int)(r>>3);
  419. # elif (defined(__clang__) || (defined(__GNUC__) && (__GNUC__>=3))) && !defined(LZ4_FORCE_SW_BITCOUNT)
  420. return (unsigned)__builtin_ctz((U32)val) >> 3;
  421. # else
  422. static const int DeBruijnBytePos[32] = { 0, 0, 3, 0, 3, 1, 3, 0,
  423. 3, 2, 2, 1, 3, 2, 0, 1,
  424. 3, 3, 1, 2, 2, 2, 2, 0,
  425. 3, 1, 2, 0, 1, 0, 1, 1 };
  426. return DeBruijnBytePos[((U32)((val & -(S32)val) * 0x077CB531U)) >> 27];
  427. # endif
  428. }
  429. } else /* Big Endian CPU */ {
  430. if (sizeof(val)==8) { /* 64-bits */
  431. # if defined(_MSC_VER) && defined(_WIN64) && !defined(LZ4_FORCE_SW_BITCOUNT)
  432. unsigned long r = 0;
  433. _BitScanReverse64( &r, val );
  434. return (unsigned)(r>>3);
  435. # elif (defined(__clang__) || (defined(__GNUC__) && (__GNUC__>=3))) && !defined(LZ4_FORCE_SW_BITCOUNT)
  436. return (unsigned)__builtin_clzll((U64)val) >> 3;
  437. # else
  438. static const U32 by32 = sizeof(val)*4; /* 32 on 64 bits (goal), 16 on 32 bits.
  439. Just to avoid some static analyzer complaining about shift by 32 on 32-bits target.
  440. Note that this code path is never triggered in 32-bits mode. */
  441. unsigned r;
  442. if (!(val>>by32)) { r=4; } else { r=0; val>>=by32; }
  443. if (!(val>>16)) { r+=2; val>>=8; } else { val>>=24; }
  444. r += (!val);
  445. return r;
  446. # endif
  447. } else /* 32 bits */ {
  448. # if defined(_MSC_VER) && !defined(LZ4_FORCE_SW_BITCOUNT)
  449. unsigned long r = 0;
  450. _BitScanReverse( &r, (unsigned long)val );
  451. return (unsigned)(r>>3);
  452. # elif (defined(__clang__) || (defined(__GNUC__) && (__GNUC__>=3))) && !defined(LZ4_FORCE_SW_BITCOUNT)
  453. return (unsigned)__builtin_clz((U32)val) >> 3;
  454. # else
  455. unsigned r;
  456. if (!(val>>16)) { r=2; val>>=8; } else { r=0; val>>=24; }
  457. r += (!val);
  458. return r;
  459. # endif
  460. }
  461. }
  462. }
  463. #define STEPSIZE sizeof(reg_t)
  464. LZ4_FORCE_INLINE
  465. unsigned LZ4_count(const BYTE* pIn, const BYTE* pMatch, const BYTE* pInLimit)
  466. {
  467. const BYTE* const pStart = pIn;
  468. if (likely(pIn < pInLimit-(STEPSIZE-1))) {
  469. reg_t const diff = LZ4_read_ARCH(pMatch) ^ LZ4_read_ARCH(pIn);
  470. if (!diff) {
  471. pIn+=STEPSIZE; pMatch+=STEPSIZE;
  472. } else {
  473. return LZ4_NbCommonBytes(diff);
  474. } }
  475. while (likely(pIn < pInLimit-(STEPSIZE-1))) {
  476. reg_t const diff = LZ4_read_ARCH(pMatch) ^ LZ4_read_ARCH(pIn);
  477. if (!diff) { pIn+=STEPSIZE; pMatch+=STEPSIZE; continue; }
  478. pIn += LZ4_NbCommonBytes(diff);
  479. return (unsigned)(pIn - pStart);
  480. }
  481. if ((STEPSIZE==8) && (pIn<(pInLimit-3)) && (LZ4_read32(pMatch) == LZ4_read32(pIn))) { pIn+=4; pMatch+=4; }
  482. if ((pIn<(pInLimit-1)) && (LZ4_read16(pMatch) == LZ4_read16(pIn))) { pIn+=2; pMatch+=2; }
  483. if ((pIn<pInLimit) && (*pMatch == *pIn)) pIn++;
  484. return (unsigned)(pIn - pStart);
  485. }
  486. #ifndef LZ4_COMMONDEFS_ONLY
  487. /*-************************************
  488. * Local Constants
  489. **************************************/
  490. static const int LZ4_64Klimit = ((64 KB) + (MFLIMIT-1));
  491. static const U32 LZ4_skipTrigger = 6; /* Increase this value ==> compression run slower on incompressible data */
  492. /*-************************************
  493. * Local Structures and types
  494. **************************************/
  495. typedef enum { clearedTable = 0, byPtr, byU32, byU16 } tableType_t;
  496. /**
  497. * This enum distinguishes several different modes of accessing previous
  498. * content in the stream.
  499. *
  500. * - noDict : There is no preceding content.
  501. * - withPrefix64k : Table entries up to ctx->dictSize before the current blob
  502. * blob being compressed are valid and refer to the preceding
  503. * content (of length ctx->dictSize), which is available
  504. * contiguously preceding in memory the content currently
  505. * being compressed.
  506. * - usingExtDict : Like withPrefix64k, but the preceding content is somewhere
  507. * else in memory, starting at ctx->dictionary with length
  508. * ctx->dictSize.
  509. * - usingDictCtx : Like usingExtDict, but everything concerning the preceding
  510. * content is in a separate context, pointed to by
  511. * ctx->dictCtx. ctx->dictionary, ctx->dictSize, and table
  512. * entries in the current context that refer to positions
  513. * preceding the beginning of the current compression are
  514. * ignored. Instead, ctx->dictCtx->dictionary and ctx->dictCtx
  515. * ->dictSize describe the location and size of the preceding
  516. * content, and matches are found by looking in the ctx
  517. * ->dictCtx->hashTable.
  518. */
  519. typedef enum { noDict = 0, withPrefix64k, usingExtDict, usingDictCtx } dict_directive;
  520. typedef enum { noDictIssue = 0, dictSmall } dictIssue_directive;
  521. /*-************************************
  522. * Local Utils
  523. **************************************/
  524. int LZ4_versionNumber (void) { return LZ4_VERSION_NUMBER; }
  525. const char* LZ4_versionString(void) { return LZ4_VERSION_STRING; }
  526. int LZ4_compressBound(int isize) { return LZ4_COMPRESSBOUND(isize); }
  527. int LZ4_sizeofState() { return LZ4_STREAMSIZE; }
  528. /*-************************************
  529. * Internal Definitions used in Tests
  530. **************************************/
  531. #if defined (__cplusplus)
  532. extern "C" {
  533. #endif
  534. int LZ4_compress_forceExtDict (LZ4_stream_t* LZ4_dict, const char* source, char* dest, int srcSize);
  535. int LZ4_decompress_safe_forceExtDict(const char* source, char* dest,
  536. int compressedSize, int maxOutputSize,
  537. const void* dictStart, size_t dictSize);
  538. #if defined (__cplusplus)
  539. }
  540. #endif
  541. /*-******************************
  542. * Compression functions
  543. ********************************/
  544. static U32 LZ4_hash4(U32 sequence, tableType_t const tableType)
  545. {
  546. if (tableType == byU16)
  547. return ((sequence * 2654435761U) >> ((MINMATCH*8)-(LZ4_HASHLOG+1)));
  548. else
  549. return ((sequence * 2654435761U) >> ((MINMATCH*8)-LZ4_HASHLOG));
  550. }
  551. static U32 LZ4_hash5(U64 sequence, tableType_t const tableType)
  552. {
  553. const U32 hashLog = (tableType == byU16) ? LZ4_HASHLOG+1 : LZ4_HASHLOG;
  554. if (LZ4_isLittleEndian()) {
  555. const U64 prime5bytes = 889523592379ULL;
  556. return (U32)(((sequence << 24) * prime5bytes) >> (64 - hashLog));
  557. } else {
  558. const U64 prime8bytes = 11400714785074694791ULL;
  559. return (U32)(((sequence >> 24) * prime8bytes) >> (64 - hashLog));
  560. }
  561. }
  562. LZ4_FORCE_INLINE U32 LZ4_hashPosition(const void* const p, tableType_t const tableType)
  563. {
  564. if ((sizeof(reg_t)==8) && (tableType != byU16)) return LZ4_hash5(LZ4_read_ARCH(p), tableType);
  565. return LZ4_hash4(LZ4_read32(p), tableType);
  566. }
  567. static void LZ4_clearHash(U32 h, void* tableBase, tableType_t const tableType)
  568. {
  569. switch (tableType)
  570. {
  571. default: /* fallthrough */
  572. case clearedTable: { /* illegal! */ assert(0); return; }
  573. case byPtr: { const BYTE** hashTable = (const BYTE**)tableBase; hashTable[h] = NULL; return; }
  574. case byU32: { U32* hashTable = (U32*) tableBase; hashTable[h] = 0; return; }
  575. case byU16: { U16* hashTable = (U16*) tableBase; hashTable[h] = 0; return; }
  576. }
  577. }
  578. static void LZ4_putIndexOnHash(U32 idx, U32 h, void* tableBase, tableType_t const tableType)
  579. {
  580. switch (tableType)
  581. {
  582. default: /* fallthrough */
  583. case clearedTable: /* fallthrough */
  584. case byPtr: { /* illegal! */ assert(0); return; }
  585. case byU32: { U32* hashTable = (U32*) tableBase; hashTable[h] = idx; return; }
  586. case byU16: { U16* hashTable = (U16*) tableBase; assert(idx < 65536); hashTable[h] = (U16)idx; return; }
  587. }
  588. }
  589. static void LZ4_putPositionOnHash(const BYTE* p, U32 h,
  590. void* tableBase, tableType_t const tableType,
  591. const BYTE* srcBase)
  592. {
  593. switch (tableType)
  594. {
  595. case clearedTable: { /* illegal! */ assert(0); return; }
  596. case byPtr: { const BYTE** hashTable = (const BYTE**)tableBase; hashTable[h] = p; return; }
  597. case byU32: { U32* hashTable = (U32*) tableBase; hashTable[h] = (U32)(p-srcBase); return; }
  598. case byU16: { U16* hashTable = (U16*) tableBase; hashTable[h] = (U16)(p-srcBase); return; }
  599. }
  600. }
  601. LZ4_FORCE_INLINE void LZ4_putPosition(const BYTE* p, void* tableBase, tableType_t tableType, const BYTE* srcBase)
  602. {
  603. U32 const h = LZ4_hashPosition(p, tableType);
  604. LZ4_putPositionOnHash(p, h, tableBase, tableType, srcBase);
  605. }
  606. /* LZ4_getIndexOnHash() :
  607. * Index of match position registered in hash table.
  608. * hash position must be calculated by using base+index, or dictBase+index.
  609. * Assumption 1 : only valid if tableType == byU32 or byU16.
  610. * Assumption 2 : h is presumed valid (within limits of hash table)
  611. */
  612. static U32 LZ4_getIndexOnHash(U32 h, const void* tableBase, tableType_t tableType)
  613. {
  614. LZ4_STATIC_ASSERT(LZ4_MEMORY_USAGE > 2);
  615. if (tableType == byU32) {
  616. const U32* const hashTable = (const U32*) tableBase;
  617. assert(h < (1U << (LZ4_MEMORY_USAGE-2)));
  618. return hashTable[h];
  619. }
  620. if (tableType == byU16) {
  621. const U16* const hashTable = (const U16*) tableBase;
  622. assert(h < (1U << (LZ4_MEMORY_USAGE-1)));
  623. return hashTable[h];
  624. }
  625. assert(0); return 0; /* forbidden case */
  626. }
  627. static const BYTE* LZ4_getPositionOnHash(U32 h, const void* tableBase, tableType_t tableType, const BYTE* srcBase)
  628. {
  629. if (tableType == byPtr) { const BYTE* const* hashTable = (const BYTE* const*) tableBase; return hashTable[h]; }
  630. if (tableType == byU32) { const U32* const hashTable = (const U32*) tableBase; return hashTable[h] + srcBase; }
  631. { const U16* const hashTable = (const U16*) tableBase; return hashTable[h] + srcBase; } /* default, to ensure a return */
  632. }
  633. LZ4_FORCE_INLINE const BYTE*
  634. LZ4_getPosition(const BYTE* p,
  635. const void* tableBase, tableType_t tableType,
  636. const BYTE* srcBase)
  637. {
  638. U32 const h = LZ4_hashPosition(p, tableType);
  639. return LZ4_getPositionOnHash(h, tableBase, tableType, srcBase);
  640. }
  641. LZ4_FORCE_INLINE void
  642. LZ4_prepareTable(LZ4_stream_t_internal* const cctx,
  643. const int inputSize,
  644. const tableType_t tableType) {
  645. /* If compression failed during the previous step, then the context
  646. * is marked as dirty, therefore, it has to be fully reset.
  647. */
  648. if (cctx->dirty) {
  649. DEBUGLOG(5, "LZ4_prepareTable: Full reset for %p", cctx);
  650. MEM_INIT(cctx, 0, sizeof(LZ4_stream_t_internal));
  651. return;
  652. }
  653. /* If the table hasn't been used, it's guaranteed to be zeroed out, and is
  654. * therefore safe to use no matter what mode we're in. Otherwise, we figure
  655. * out if it's safe to leave as is or whether it needs to be reset.
  656. */
  657. if (cctx->tableType != clearedTable) {
  658. assert(inputSize >= 0);
  659. if (cctx->tableType != tableType
  660. || ((tableType == byU16) && cctx->currentOffset + (unsigned)inputSize >= 0xFFFFU)
  661. || ((tableType == byU32) && cctx->currentOffset > 1 GB)
  662. || tableType == byPtr
  663. || inputSize >= 4 KB)
  664. {
  665. DEBUGLOG(4, "LZ4_prepareTable: Resetting table in %p", cctx);
  666. MEM_INIT(cctx->hashTable, 0, LZ4_HASHTABLESIZE);
  667. cctx->currentOffset = 0;
  668. cctx->tableType = clearedTable;
  669. } else {
  670. DEBUGLOG(4, "LZ4_prepareTable: Re-use hash table (no reset)");
  671. }
  672. }
  673. /* Adding a gap, so all previous entries are > LZ4_DISTANCE_MAX back, is faster
  674. * than compressing without a gap. However, compressing with
  675. * currentOffset == 0 is faster still, so we preserve that case.
  676. */
  677. if (cctx->currentOffset != 0 && tableType == byU32) {
  678. DEBUGLOG(5, "LZ4_prepareTable: adding 64KB to currentOffset");
  679. cctx->currentOffset += 64 KB;
  680. }
  681. /* Finally, clear history */
  682. cctx->dictCtx = NULL;
  683. cctx->dictionary = NULL;
  684. cctx->dictSize = 0;
  685. }
  686. /** LZ4_compress_generic() :
  687. inlined, to ensure branches are decided at compilation time */
  688. LZ4_FORCE_INLINE int LZ4_compress_generic(
  689. LZ4_stream_t_internal* const cctx,
  690. const char* const source,
  691. char* const dest,
  692. const int inputSize,
  693. int *inputConsumed, /* only written when outputDirective == fillOutput */
  694. const int maxOutputSize,
  695. const limitedOutput_directive outputDirective,
  696. const tableType_t tableType,
  697. const dict_directive dictDirective,
  698. const dictIssue_directive dictIssue,
  699. const int acceleration)
  700. {
  701. int result;
  702. const BYTE* ip = (const BYTE*) source;
  703. U32 const startIndex = cctx->currentOffset;
  704. const BYTE* base = (const BYTE*) source - startIndex;
  705. const BYTE* lowLimit;
  706. const LZ4_stream_t_internal* dictCtx = (const LZ4_stream_t_internal*) cctx->dictCtx;
  707. const BYTE* const dictionary =
  708. dictDirective == usingDictCtx ? dictCtx->dictionary : cctx->dictionary;
  709. const U32 dictSize =
  710. dictDirective == usingDictCtx ? dictCtx->dictSize : cctx->dictSize;
  711. const U32 dictDelta = (dictDirective == usingDictCtx) ? startIndex - dictCtx->currentOffset : 0; /* make indexes in dictCtx comparable with index in current context */
  712. int const maybe_extMem = (dictDirective == usingExtDict) || (dictDirective == usingDictCtx);
  713. U32 const prefixIdxLimit = startIndex - dictSize; /* used when dictDirective == dictSmall */
  714. const BYTE* const dictEnd = dictionary + dictSize;
  715. const BYTE* anchor = (const BYTE*) source;
  716. const BYTE* const iend = ip + inputSize;
  717. const BYTE* const mflimitPlusOne = iend - MFLIMIT + 1;
  718. const BYTE* const matchlimit = iend - LASTLITERALS;
  719. /* the dictCtx currentOffset is indexed on the start of the dictionary,
  720. * while a dictionary in the current context precedes the currentOffset */
  721. const BYTE* dictBase = (dictDirective == usingDictCtx) ?
  722. dictionary + dictSize - dictCtx->currentOffset :
  723. dictionary + dictSize - startIndex;
  724. BYTE* op = (BYTE*) dest;
  725. BYTE* const olimit = op + maxOutputSize;
  726. U32 offset = 0;
  727. U32 forwardH;
  728. DEBUGLOG(5, "LZ4_compress_generic: srcSize=%i, tableType=%u", inputSize, tableType);
  729. /* If init conditions are not met, we don't have to mark stream
  730. * as having dirty context, since no action was taken yet */
  731. if (outputDirective == fillOutput && maxOutputSize < 1) { return 0; } /* Impossible to store anything */
  732. if ((U32)inputSize > (U32)LZ4_MAX_INPUT_SIZE) { return 0; } /* Unsupported inputSize, too large (or negative) */
  733. if ((tableType == byU16) && (inputSize>=LZ4_64Klimit)) { return 0; } /* Size too large (not within 64K limit) */
  734. if (tableType==byPtr) assert(dictDirective==noDict); /* only supported use case with byPtr */
  735. assert(acceleration >= 1);
  736. lowLimit = (const BYTE*)source - (dictDirective == withPrefix64k ? dictSize : 0);
  737. /* Update context state */
  738. if (dictDirective == usingDictCtx) {
  739. /* Subsequent linked blocks can't use the dictionary. */
  740. /* Instead, they use the block we just compressed. */
  741. cctx->dictCtx = NULL;
  742. cctx->dictSize = (U32)inputSize;
  743. } else {
  744. cctx->dictSize += (U32)inputSize;
  745. }
  746. cctx->currentOffset += (U32)inputSize;
  747. cctx->tableType = (U16)tableType;
  748. if (inputSize<LZ4_minLength) goto _last_literals; /* Input too small, no compression (all literals) */
  749. /* First Byte */
  750. LZ4_putPosition(ip, cctx->hashTable, tableType, base);
  751. ip++; forwardH = LZ4_hashPosition(ip, tableType);
  752. /* Main Loop */
  753. for ( ; ; ) {
  754. const BYTE* match;
  755. BYTE* token;
  756. const BYTE* filledIp;
  757. /* Find a match */
  758. if (tableType == byPtr) {
  759. const BYTE* forwardIp = ip;
  760. int step = 1;
  761. int searchMatchNb = acceleration << LZ4_skipTrigger;
  762. do {
  763. U32 const h = forwardH;
  764. ip = forwardIp;
  765. forwardIp += step;
  766. step = (searchMatchNb++ >> LZ4_skipTrigger);
  767. if (unlikely(forwardIp > mflimitPlusOne)) goto _last_literals;
  768. assert(ip < mflimitPlusOne);
  769. match = LZ4_getPositionOnHash(h, cctx->hashTable, tableType, base);
  770. forwardH = LZ4_hashPosition(forwardIp, tableType);
  771. LZ4_putPositionOnHash(ip, h, cctx->hashTable, tableType, base);
  772. } while ( (match+LZ4_DISTANCE_MAX < ip)
  773. || (LZ4_read32(match) != LZ4_read32(ip)) );
  774. } else { /* byU32, byU16 */
  775. const BYTE* forwardIp = ip;
  776. int step = 1;
  777. int searchMatchNb = acceleration << LZ4_skipTrigger;
  778. do {
  779. U32 const h = forwardH;
  780. U32 const current = (U32)(forwardIp - base);
  781. U32 matchIndex = LZ4_getIndexOnHash(h, cctx->hashTable, tableType);
  782. assert(matchIndex <= current);
  783. assert(forwardIp - base < (ptrdiff_t)(2 GB - 1));
  784. ip = forwardIp;
  785. forwardIp += step;
  786. step = (searchMatchNb++ >> LZ4_skipTrigger);
  787. if (unlikely(forwardIp > mflimitPlusOne)) goto _last_literals;
  788. assert(ip < mflimitPlusOne);
  789. if (dictDirective == usingDictCtx) {
  790. if (matchIndex < startIndex) {
  791. /* there was no match, try the dictionary */
  792. assert(tableType == byU32);
  793. matchIndex = LZ4_getIndexOnHash(h, dictCtx->hashTable, byU32);
  794. match = dictBase + matchIndex;
  795. matchIndex += dictDelta; /* make dictCtx index comparable with current context */
  796. lowLimit = dictionary;
  797. } else {
  798. match = base + matchIndex;
  799. lowLimit = (const BYTE*)source;
  800. }
  801. } else if (dictDirective==usingExtDict) {
  802. if (matchIndex < startIndex) {
  803. DEBUGLOG(7, "extDict candidate: matchIndex=%5u < startIndex=%5u", matchIndex, startIndex);
  804. assert(startIndex - matchIndex >= MINMATCH);
  805. match = dictBase + matchIndex;
  806. lowLimit = dictionary;
  807. } else {
  808. match = base + matchIndex;
  809. lowLimit = (const BYTE*)source;
  810. }
  811. } else { /* single continuous memory segment */
  812. match = base + matchIndex;
  813. }
  814. forwardH = LZ4_hashPosition(forwardIp, tableType);
  815. LZ4_putIndexOnHash(current, h, cctx->hashTable, tableType);
  816. DEBUGLOG(7, "candidate at pos=%u (offset=%u \n", matchIndex, current - matchIndex);
  817. if ((dictIssue == dictSmall) && (matchIndex < prefixIdxLimit)) { continue; } /* match outside of valid area */
  818. assert(matchIndex < current);
  819. if ( ((tableType != byU16) || (LZ4_DISTANCE_MAX < LZ4_DISTANCE_ABSOLUTE_MAX))
  820. && (matchIndex+LZ4_DISTANCE_MAX < current)) {
  821. continue;
  822. } /* too far */
  823. assert((current - matchIndex) <= LZ4_DISTANCE_MAX); /* match now expected within distance */
  824. if (LZ4_read32(match) == LZ4_read32(ip)) {
  825. if (maybe_extMem) offset = current - matchIndex;
  826. break; /* match found */
  827. }
  828. } while(1);
  829. }
  830. /* Catch up */
  831. filledIp = ip;
  832. while (((ip>anchor) & (match > lowLimit)) && (unlikely(ip[-1]==match[-1]))) { ip--; match--; }
  833. /* Encode Literals */
  834. { unsigned const litLength = (unsigned)(ip - anchor);
  835. token = op++;
  836. if ((outputDirective == limitedOutput) && /* Check output buffer overflow */
  837. (unlikely(op + litLength + (2 + 1 + LASTLITERALS) + (litLength/255) > olimit)) ) {
  838. return 0; /* cannot compress within `dst` budget. Stored indexes in hash table are nonetheless fine */
  839. }
  840. if ((outputDirective == fillOutput) &&
  841. (unlikely(op + (litLength+240)/255 /* litlen */ + litLength /* literals */ + 2 /* offset */ + 1 /* token */ + MFLIMIT - MINMATCH /* min last literals so last match is <= end - MFLIMIT */ > olimit))) {
  842. op--;
  843. goto _last_literals;
  844. }
  845. if (litLength >= RUN_MASK) {
  846. int len = (int)(litLength - RUN_MASK);
  847. *token = (RUN_MASK<<ML_BITS);
  848. for(; len >= 255 ; len-=255) *op++ = 255;
  849. *op++ = (BYTE)len;
  850. }
  851. else *token = (BYTE)(litLength<<ML_BITS);
  852. /* Copy Literals */
  853. LZ4_wildCopy8(op, anchor, op+litLength);
  854. op+=litLength;
  855. DEBUGLOG(6, "seq.start:%i, literals=%u, match.start:%i",
  856. (int)(anchor-(const BYTE*)source), litLength, (int)(ip-(const BYTE*)source));
  857. }
  858. _next_match:
  859. /* at this stage, the following variables must be correctly set :
  860. * - ip : at start of LZ operation
  861. * - match : at start of previous pattern occurence; can be within current prefix, or within extDict
  862. * - offset : if maybe_ext_memSegment==1 (constant)
  863. * - lowLimit : must be == dictionary to mean "match is within extDict"; must be == source otherwise
  864. * - token and *token : position to write 4-bits for match length; higher 4-bits for literal length supposed already written
  865. */
  866. if ((outputDirective == fillOutput) &&
  867. (op + 2 /* offset */ + 1 /* token */ + MFLIMIT - MINMATCH /* min last literals so last match is <= end - MFLIMIT */ > olimit)) {
  868. /* the match was too close to the end, rewind and go to last literals */
  869. op = token;
  870. goto _last_literals;
  871. }
  872. /* Encode Offset */
  873. if (maybe_extMem) { /* static test */
  874. DEBUGLOG(6, " with offset=%u (ext if > %i)", offset, (int)(ip - (const BYTE*)source));
  875. assert(offset <= LZ4_DISTANCE_MAX && offset > 0);
  876. LZ4_writeLE16(op, (U16)offset); op+=2;
  877. } else {
  878. DEBUGLOG(6, " with offset=%u (same segment)", (U32)(ip - match));
  879. assert(ip-match <= LZ4_DISTANCE_MAX);
  880. LZ4_writeLE16(op, (U16)(ip - match)); op+=2;
  881. }
  882. /* Encode MatchLength */
  883. { unsigned matchCode;
  884. if ( (dictDirective==usingExtDict || dictDirective==usingDictCtx)
  885. && (lowLimit==dictionary) /* match within extDict */ ) {
  886. const BYTE* limit = ip + (dictEnd-match);
  887. assert(dictEnd > match);
  888. if (limit > matchlimit) limit = matchlimit;
  889. matchCode = LZ4_count(ip+MINMATCH, match+MINMATCH, limit);
  890. ip += (size_t)matchCode + MINMATCH;
  891. if (ip==limit) {
  892. unsigned const more = LZ4_count(limit, (const BYTE*)source, matchlimit);
  893. matchCode += more;
  894. ip += more;
  895. }
  896. DEBUGLOG(6, " with matchLength=%u starting in extDict", matchCode+MINMATCH);
  897. } else {
  898. matchCode = LZ4_count(ip+MINMATCH, match+MINMATCH, matchlimit);
  899. ip += (size_t)matchCode + MINMATCH;
  900. DEBUGLOG(6, " with matchLength=%u", matchCode+MINMATCH);
  901. }
  902. if ((outputDirective) && /* Check output buffer overflow */
  903. (unlikely(op + (1 + LASTLITERALS) + (matchCode+240)/255 > olimit)) ) {
  904. if (outputDirective == fillOutput) {
  905. /* Match description too long : reduce it */
  906. U32 newMatchCode = 15 /* in token */ - 1 /* to avoid needing a zero byte */ + ((U32)(olimit - op) - 1 - LASTLITERALS) * 255;
  907. ip -= matchCode - newMatchCode;
  908. assert(newMatchCode < matchCode);
  909. matchCode = newMatchCode;
  910. if (unlikely(ip <= filledIp)) {
  911. /* We have already filled up to filledIp so if ip ends up less than filledIp
  912. * we have positions in the hash table beyond the current position. This is
  913. * a problem if we reuse the hash table. So we have to remove these positions
  914. * from the hash table.
  915. */
  916. const BYTE* ptr;
  917. DEBUGLOG(5, "Clearing %u positions", (U32)(filledIp - ip));
  918. for (ptr = ip; ptr <= filledIp; ++ptr) {
  919. U32 const h = LZ4_hashPosition(ptr, tableType);
  920. LZ4_clearHash(h, cctx->hashTable, tableType);
  921. }
  922. }
  923. } else {
  924. assert(outputDirective == limitedOutput);
  925. return 0; /* cannot compress within `dst` budget. Stored indexes in hash table are nonetheless fine */
  926. }
  927. }
  928. if (matchCode >= ML_MASK) {
  929. *token += ML_MASK;
  930. matchCode -= ML_MASK;
  931. LZ4_write32(op, 0xFFFFFFFF);
  932. while (matchCode >= 4*255) {
  933. op+=4;
  934. LZ4_write32(op, 0xFFFFFFFF);
  935. matchCode -= 4*255;
  936. }
  937. op += matchCode / 255;
  938. *op++ = (BYTE)(matchCode % 255);
  939. } else
  940. *token += (BYTE)(matchCode);
  941. }
  942. /* Ensure we have enough space for the last literals. */
  943. assert(!(outputDirective == fillOutput && op + 1 + LASTLITERALS > olimit));
  944. anchor = ip;
  945. /* Test end of chunk */
  946. if (ip >= mflimitPlusOne) break;
  947. /* Fill table */
  948. LZ4_putPosition(ip-2, cctx->hashTable, tableType, base);
  949. /* Test next position */
  950. if (tableType == byPtr) {
  951. match = LZ4_getPosition(ip, cctx->hashTable, tableType, base);
  952. LZ4_putPosition(ip, cctx->hashTable, tableType, base);
  953. if ( (match+LZ4_DISTANCE_MAX >= ip)
  954. && (LZ4_read32(match) == LZ4_read32(ip)) )
  955. { token=op++; *token=0; goto _next_match; }
  956. } else { /* byU32, byU16 */
  957. U32 const h = LZ4_hashPosition(ip, tableType);
  958. U32 const current = (U32)(ip-base);
  959. U32 matchIndex = LZ4_getIndexOnHash(h, cctx->hashTable, tableType);
  960. assert(matchIndex < current);
  961. if (dictDirective == usingDictCtx) {
  962. if (matchIndex < startIndex) {
  963. /* there was no match, try the dictionary */
  964. matchIndex = LZ4_getIndexOnHash(h, dictCtx->hashTable, byU32);
  965. match = dictBase + matchIndex;
  966. lowLimit = dictionary; /* required for match length counter */
  967. matchIndex += dictDelta;
  968. } else {
  969. match = base + matchIndex;
  970. lowLimit = (const BYTE*)source; /* required for match length counter */
  971. }
  972. } else if (dictDirective==usingExtDict) {
  973. if (matchIndex < startIndex) {
  974. match = dictBase + matchIndex;
  975. lowLimit = dictionary; /* required for match length counter */
  976. } else {
  977. match = base + matchIndex;
  978. lowLimit = (const BYTE*)source; /* required for match length counter */
  979. }
  980. } else { /* single memory segment */
  981. match = base + matchIndex;
  982. }
  983. LZ4_putIndexOnHash(current, h, cctx->hashTable, tableType);
  984. assert(matchIndex < current);
  985. if ( ((dictIssue==dictSmall) ? (matchIndex >= prefixIdxLimit) : 1)
  986. && (((tableType==byU16) && (LZ4_DISTANCE_MAX == LZ4_DISTANCE_ABSOLUTE_MAX)) ? 1 : (matchIndex+LZ4_DISTANCE_MAX >= current))
  987. && (LZ4_read32(match) == LZ4_read32(ip)) ) {
  988. token=op++;
  989. *token=0;
  990. if (maybe_extMem) offset = current - matchIndex;
  991. DEBUGLOG(6, "seq.start:%i, literals=%u, match.start:%i",
  992. (int)(anchor-(const BYTE*)source), 0, (int)(ip-(const BYTE*)source));
  993. goto _next_match;
  994. }
  995. }
  996. /* Prepare next loop */
  997. forwardH = LZ4_hashPosition(++ip, tableType);
  998. }
  999. _last_literals:
  1000. /* Encode Last Literals */
  1001. { size_t lastRun = (size_t)(iend - anchor);
  1002. if ( (outputDirective) && /* Check output buffer overflow */
  1003. (op + lastRun + 1 + ((lastRun+255-RUN_MASK)/255) > olimit)) {
  1004. if (outputDirective == fillOutput) {
  1005. /* adapt lastRun to fill 'dst' */
  1006. assert(olimit >= op);
  1007. lastRun = (size_t)(olimit-op) - 1;
  1008. lastRun -= (lastRun+240)/255;
  1009. } else {
  1010. assert(outputDirective == limitedOutput);
  1011. return 0; /* cannot compress within `dst` budget. Stored indexes in hash table are nonetheless fine */
  1012. }
  1013. }
  1014. if (lastRun >= RUN_MASK) {
  1015. size_t accumulator = lastRun - RUN_MASK;
  1016. *op++ = RUN_MASK << ML_BITS;
  1017. for(; accumulator >= 255 ; accumulator-=255) *op++ = 255;
  1018. *op++ = (BYTE) accumulator;
  1019. } else {
  1020. *op++ = (BYTE)(lastRun<<ML_BITS);
  1021. }
  1022. memcpy(op, anchor, lastRun);
  1023. ip = anchor + lastRun;
  1024. op += lastRun;
  1025. }
  1026. if (outputDirective == fillOutput) {
  1027. *inputConsumed = (int) (((const char*)ip)-source);
  1028. }
  1029. DEBUGLOG(5, "LZ4_compress_generic: compressed %i bytes into %i bytes", inputSize, (int)(((char*)op) - dest));
  1030. result = (int)(((char*)op) - dest);
  1031. assert(result > 0);
  1032. return result;
  1033. }
  1034. int LZ4_compress_fast_extState(void* state, const char* source, char* dest, int inputSize, int maxOutputSize, int acceleration)
  1035. {
  1036. LZ4_stream_t_internal* const ctx = & LZ4_initStream(state, sizeof(LZ4_stream_t)) -> internal_donotuse;
  1037. assert(ctx != NULL);
  1038. if (acceleration < 1) acceleration = ACCELERATION_DEFAULT;
  1039. if (maxOutputSize >= LZ4_compressBound(inputSize)) {
  1040. if (inputSize < LZ4_64Klimit) {
  1041. return LZ4_compress_generic(ctx, source, dest, inputSize, NULL, 0, notLimited, byU16, noDict, noDictIssue, acceleration);
  1042. } else {
  1043. const tableType_t tableType = ((sizeof(void*)==4) && ((uptrval)source > LZ4_DISTANCE_MAX)) ? byPtr : byU32;
  1044. return LZ4_compress_generic(ctx, source, dest, inputSize, NULL, 0, notLimited, tableType, noDict, noDictIssue, acceleration);
  1045. }
  1046. } else {
  1047. if (inputSize < LZ4_64Klimit) {
  1048. return LZ4_compress_generic(ctx, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, byU16, noDict, noDictIssue, acceleration);
  1049. } else {
  1050. const tableType_t tableType = ((sizeof(void*)==4) && ((uptrval)source > LZ4_DISTANCE_MAX)) ? byPtr : byU32;
  1051. return LZ4_compress_generic(ctx, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, noDict, noDictIssue, acceleration);
  1052. }
  1053. }
  1054. }
  1055. /**
  1056. * LZ4_compress_fast_extState_fastReset() :
  1057. * A variant of LZ4_compress_fast_extState().
  1058. *
  1059. * Using this variant avoids an expensive initialization step. It is only safe
  1060. * to call if the state buffer is known to be correctly initialized already
  1061. * (see comment in lz4.h on LZ4_resetStream_fast() for a definition of
  1062. * "correctly initialized").
  1063. */
  1064. int LZ4_compress_fast_extState_fastReset(void* state, const char* src, char* dst, int srcSize, int dstCapacity, int acceleration)
  1065. {
  1066. LZ4_stream_t_internal* ctx = &((LZ4_stream_t*)state)->internal_donotuse;
  1067. if (acceleration < 1) acceleration = ACCELERATION_DEFAULT;
  1068. if (dstCapacity >= LZ4_compressBound(srcSize)) {
  1069. if (srcSize < LZ4_64Klimit) {
  1070. const tableType_t tableType = byU16;
  1071. LZ4_prepareTable(ctx, srcSize, tableType);
  1072. if (ctx->currentOffset) {
  1073. return LZ4_compress_generic(ctx, src, dst, srcSize, NULL, 0, notLimited, tableType, noDict, dictSmall, acceleration);
  1074. } else {
  1075. return LZ4_compress_generic(ctx, src, dst, srcSize, NULL, 0, notLimited, tableType, noDict, noDictIssue, acceleration);
  1076. }
  1077. } else {
  1078. const tableType_t tableType = ((sizeof(void*)==4) && ((uptrval)src > LZ4_DISTANCE_MAX)) ? byPtr : byU32;
  1079. LZ4_prepareTable(ctx, srcSize, tableType);
  1080. return LZ4_compress_generic(ctx, src, dst, srcSize, NULL, 0, notLimited, tableType, noDict, noDictIssue, acceleration);
  1081. }
  1082. } else {
  1083. if (srcSize < LZ4_64Klimit) {
  1084. const tableType_t tableType = byU16;
  1085. LZ4_prepareTable(ctx, srcSize, tableType);
  1086. if (ctx->currentOffset) {
  1087. return LZ4_compress_generic(ctx, src, dst, srcSize, NULL, dstCapacity, limitedOutput, tableType, noDict, dictSmall, acceleration);
  1088. } else {
  1089. return LZ4_compress_generic(ctx, src, dst, srcSize, NULL, dstCapacity, limitedOutput, tableType, noDict, noDictIssue, acceleration);
  1090. }
  1091. } else {
  1092. const tableType_t tableType = ((sizeof(void*)==4) && ((uptrval)src > LZ4_DISTANCE_MAX)) ? byPtr : byU32;
  1093. LZ4_prepareTable(ctx, srcSize, tableType);
  1094. return LZ4_compress_generic(ctx, src, dst, srcSize, NULL, dstCapacity, limitedOutput, tableType, noDict, noDictIssue, acceleration);
  1095. }
  1096. }
  1097. }
  1098. int LZ4_compress_fast(const char* source, char* dest, int inputSize, int maxOutputSize, int acceleration)
  1099. {
  1100. int result = 0;
  1101. #if (LZ4_HEAPMODE)
  1102. LZ4_stream_t* ctxPtr = ALLOC(sizeof(LZ4_stream_t)); /* malloc-calloc always properly aligned */
  1103. if (ctxPtr == NULL) return 0;
  1104. #else
  1105. LZ4_stream_t ctx;
  1106. LZ4_stream_t* const ctxPtr = &ctx;
  1107. #endif
  1108. result = LZ4_compress_fast_extState(ctxPtr, source, dest, inputSize, maxOutputSize, acceleration);
  1109. #if (LZ4_HEAPMODE)
  1110. FREEMEM(ctxPtr);
  1111. #endif
  1112. return result;
  1113. }
  1114. int LZ4_compress_default(const char* src, char* dst, int srcSize, int maxOutputSize)
  1115. {
  1116. return LZ4_compress_fast(src, dst, srcSize, maxOutputSize, 1);
  1117. }
  1118. /* hidden debug function */
  1119. /* strangely enough, gcc generates faster code when this function is uncommented, even if unused */
  1120. int LZ4_compress_fast_force(const char* src, char* dst, int srcSize, int dstCapacity, int acceleration)
  1121. {
  1122. LZ4_stream_t ctx;
  1123. LZ4_initStream(&ctx, sizeof(ctx));
  1124. if (srcSize < LZ4_64Klimit) {
  1125. return LZ4_compress_generic(&ctx.internal_donotuse, src, dst, srcSize, NULL, dstCapacity, limitedOutput, byU16, noDict, noDictIssue, acceleration);
  1126. } else {
  1127. tableType_t const addrMode = (sizeof(void*) > 4) ? byU32 : byPtr;
  1128. return LZ4_compress_generic(&ctx.internal_donotuse, src, dst, srcSize, NULL, dstCapacity, limitedOutput, addrMode, noDict, noDictIssue, acceleration);
  1129. }
  1130. }
  1131. /* Note!: This function leaves the stream in an unclean/broken state!
  1132. * It is not safe to subsequently use the same state with a _fastReset() or
  1133. * _continue() call without resetting it. */
  1134. static int LZ4_compress_destSize_extState (LZ4_stream_t* state, const char* src, char* dst, int* srcSizePtr, int targetDstSize)
  1135. {
  1136. void* const s = LZ4_initStream(state, sizeof (*state));
  1137. assert(s != NULL); (void)s;
  1138. if (targetDstSize >= LZ4_compressBound(*srcSizePtr)) { /* compression success is guaranteed */
  1139. return LZ4_compress_fast_extState(state, src, dst, *srcSizePtr, targetDstSize, 1);
  1140. } else {
  1141. if (*srcSizePtr < LZ4_64Klimit) {
  1142. return LZ4_compress_generic(&state->internal_donotuse, src, dst, *srcSizePtr, srcSizePtr, targetDstSize, fillOutput, byU16, noDict, noDictIssue, 1);
  1143. } else {
  1144. tableType_t const addrMode = ((sizeof(void*)==4) && ((uptrval)src > LZ4_DISTANCE_MAX)) ? byPtr : byU32;
  1145. return LZ4_compress_generic(&state->internal_donotuse, src, dst, *srcSizePtr, srcSizePtr, targetDstSize, fillOutput, addrMode, noDict, noDictIssue, 1);
  1146. } }
  1147. }
  1148. int LZ4_compress_destSize(const char* src, char* dst, int* srcSizePtr, int targetDstSize)
  1149. {
  1150. int result = 0;
  1151. #if (LZ4_HEAPMODE)
  1152. LZ4_stream_t* ctx = (LZ4_stream_t*)ALLOC(sizeof(LZ4_stream_t)); /* malloc-calloc always properly aligned */
  1153. if (ctx == NULL) return 0;
  1154. #else
  1155. LZ4_stream_t ctxBody;
  1156. LZ4_stream_t* ctx = &ctxBody;
  1157. #endif
  1158. result = LZ4_compress_destSize_extState(ctx, src, dst, srcSizePtr, targetDstSize);
  1159. #if (LZ4_HEAPMODE)
  1160. FREEMEM(ctx);
  1161. #endif
  1162. return result;
  1163. }
  1164. /*-******************************
  1165. * Streaming functions
  1166. ********************************/
  1167. LZ4_stream_t* LZ4_createStream(void)
  1168. {
  1169. LZ4_stream_t* const lz4s = (LZ4_stream_t*)ALLOC(sizeof(LZ4_stream_t));
  1170. LZ4_STATIC_ASSERT(LZ4_STREAMSIZE >= sizeof(LZ4_stream_t_internal)); /* A compilation error here means LZ4_STREAMSIZE is not large enough */
  1171. DEBUGLOG(4, "LZ4_createStream %p", lz4s);
  1172. if (lz4s == NULL) return NULL;
  1173. LZ4_initStream(lz4s, sizeof(*lz4s));
  1174. return lz4s;
  1175. }
  1176. #ifndef _MSC_VER /* for some reason, Visual fails the aligment test on 32-bit x86 :
  1177. it reports an aligment of 8-bytes,
  1178. while actually aligning LZ4_stream_t on 4 bytes. */
  1179. static size_t LZ4_stream_t_alignment(void)
  1180. {
  1181. struct { char c; LZ4_stream_t t; } t_a;
  1182. return sizeof(t_a) - sizeof(t_a.t);
  1183. }
  1184. #endif
  1185. LZ4_stream_t* LZ4_initStream (void* buffer, size_t size)
  1186. {
  1187. DEBUGLOG(5, "LZ4_initStream");
  1188. if (buffer == NULL) { return NULL; }
  1189. if (size < sizeof(LZ4_stream_t)) { return NULL; }
  1190. #ifndef _MSC_VER /* for some reason, Visual fails the aligment test on 32-bit x86 :
  1191. it reports an aligment of 8-bytes,
  1192. while actually aligning LZ4_stream_t on 4 bytes. */
  1193. if (((size_t)buffer) & (LZ4_stream_t_alignment() - 1)) { return NULL; } /* alignment check */
  1194. #endif
  1195. MEM_INIT(buffer, 0, sizeof(LZ4_stream_t));
  1196. return (LZ4_stream_t*)buffer;
  1197. }
  1198. /* resetStream is now deprecated,
  1199. * prefer initStream() which is more general */
  1200. void LZ4_resetStream (LZ4_stream_t* LZ4_stream)
  1201. {
  1202. DEBUGLOG(5, "LZ4_resetStream (ctx:%p)", LZ4_stream);
  1203. MEM_INIT(LZ4_stream, 0, sizeof(LZ4_stream_t));
  1204. }
  1205. void LZ4_resetStream_fast(LZ4_stream_t* ctx) {
  1206. LZ4_prepareTable(&(ctx->internal_donotuse), 0, byU32);
  1207. }
  1208. int LZ4_freeStream (LZ4_stream_t* LZ4_stream)
  1209. {
  1210. if (!LZ4_stream) return 0; /* support free on NULL */
  1211. DEBUGLOG(5, "LZ4_freeStream %p", LZ4_stream);
  1212. FREEMEM(LZ4_stream);
  1213. return (0);
  1214. }
  1215. #define HASH_UNIT sizeof(reg_t)
  1216. int LZ4_loadDict (LZ4_stream_t* LZ4_dict, const char* dictionary, int dictSize)
  1217. {
  1218. LZ4_stream_t_internal* dict = &LZ4_dict->internal_donotuse;
  1219. const tableType_t tableType = byU32;
  1220. const BYTE* p = (const BYTE*)dictionary;
  1221. const BYTE* const dictEnd = p + dictSize;
  1222. const BYTE* base;
  1223. DEBUGLOG(4, "LZ4_loadDict (%i bytes from %p into %p)", dictSize, dictionary, LZ4_dict);
  1224. /* It's necessary to reset the context,
  1225. * and not just continue it with prepareTable()
  1226. * to avoid any risk of generating overflowing matchIndex
  1227. * when compressing using this dictionary */
  1228. LZ4_resetStream(LZ4_dict);
  1229. /* We always increment the offset by 64 KB, since, if the dict is longer,
  1230. * we truncate it to the last 64k, and if it's shorter, we still want to
  1231. * advance by a whole window length so we can provide the guarantee that
  1232. * there are only valid offsets in the window, which allows an optimization
  1233. * in LZ4_compress_fast_continue() where it uses noDictIssue even when the
  1234. * dictionary isn't a full 64k. */
  1235. dict->currentOffset += 64 KB;
  1236. if (dictSize < (int)HASH_UNIT) {
  1237. return 0;
  1238. }
  1239. if ((dictEnd - p) > 64 KB) p = dictEnd - 64 KB;
  1240. base = dictEnd - dict->currentOffset;
  1241. dict->dictionary = p;
  1242. dict->dictSize = (U32)(dictEnd - p);
  1243. dict->tableType = tableType;
  1244. while (p <= dictEnd-HASH_UNIT) {
  1245. LZ4_putPosition(p, dict->hashTable, tableType, base);
  1246. p+=3;
  1247. }
  1248. return (int)dict->dictSize;
  1249. }
  1250. void LZ4_attach_dictionary(LZ4_stream_t* workingStream, const LZ4_stream_t* dictionaryStream) {
  1251. const LZ4_stream_t_internal* dictCtx = dictionaryStream == NULL ? NULL :
  1252. &(dictionaryStream->internal_donotuse);
  1253. DEBUGLOG(4, "LZ4_attach_dictionary (%p, %p, size %u)",
  1254. workingStream, dictionaryStream,
  1255. dictCtx != NULL ? dictCtx->dictSize : 0);
  1256. /* Calling LZ4_resetStream_fast() here makes sure that changes will not be
  1257. * erased by subsequent calls to LZ4_resetStream_fast() in case stream was
  1258. * marked as having dirty context, e.g. requiring full reset.
  1259. */
  1260. LZ4_resetStream_fast(workingStream);
  1261. if (dictCtx != NULL) {
  1262. /* If the current offset is zero, we will never look in the
  1263. * external dictionary context, since there is no value a table
  1264. * entry can take that indicate a miss. In that case, we need
  1265. * to bump the offset to something non-zero.
  1266. */
  1267. if (workingStream->internal_donotuse.currentOffset == 0) {
  1268. workingStream->internal_donotuse.currentOffset = 64 KB;
  1269. }
  1270. /* Don't actually attach an empty dictionary.
  1271. */
  1272. if (dictCtx->dictSize == 0) {
  1273. dictCtx = NULL;
  1274. }
  1275. }
  1276. workingStream->internal_donotuse.dictCtx = dictCtx;
  1277. }
  1278. static void LZ4_renormDictT(LZ4_stream_t_internal* LZ4_dict, int nextSize)
  1279. {
  1280. assert(nextSize >= 0);
  1281. if (LZ4_dict->currentOffset + (unsigned)nextSize > 0x80000000) { /* potential ptrdiff_t overflow (32-bits mode) */
  1282. /* rescale hash table */
  1283. U32 const delta = LZ4_dict->currentOffset - 64 KB;
  1284. const BYTE* dictEnd = LZ4_dict->dictionary + LZ4_dict->dictSize;
  1285. int i;
  1286. DEBUGLOG(4, "LZ4_renormDictT");
  1287. for (i=0; i<LZ4_HASH_SIZE_U32; i++) {
  1288. if (LZ4_dict->hashTable[i] < delta) LZ4_dict->hashTable[i]=0;
  1289. else LZ4_dict->hashTable[i] -= delta;
  1290. }
  1291. LZ4_dict->currentOffset = 64 KB;
  1292. if (LZ4_dict->dictSize > 64 KB) LZ4_dict->dictSize = 64 KB;
  1293. LZ4_dict->dictionary = dictEnd - LZ4_dict->dictSize;
  1294. }
  1295. }
  1296. int LZ4_compress_fast_continue (LZ4_stream_t* LZ4_stream,
  1297. const char* source, char* dest,
  1298. int inputSize, int maxOutputSize,
  1299. int acceleration)
  1300. {
  1301. const tableType_t tableType = byU32;
  1302. LZ4_stream_t_internal* streamPtr = &LZ4_stream->internal_donotuse;
  1303. const BYTE* dictEnd = streamPtr->dictionary + streamPtr->dictSize;
  1304. DEBUGLOG(5, "LZ4_compress_fast_continue (inputSize=%i)", inputSize);
  1305. if (streamPtr->dirty) { return 0; } /* Uninitialized structure detected */
  1306. LZ4_renormDictT(streamPtr, inputSize); /* avoid index overflow */
  1307. if (acceleration < 1) acceleration = ACCELERATION_DEFAULT;
  1308. /* invalidate tiny dictionaries */
  1309. if ( (streamPtr->dictSize-1 < 4-1) /* intentional underflow */
  1310. && (dictEnd != (const BYTE*)source) ) {
  1311. DEBUGLOG(5, "LZ4_compress_fast_continue: dictSize(%u) at addr:%p is too small", streamPtr->dictSize, streamPtr->dictionary);
  1312. streamPtr->dictSize = 0;
  1313. streamPtr->dictionary = (const BYTE*)source;
  1314. dictEnd = (const BYTE*)source;
  1315. }
  1316. /* Check overlapping input/dictionary space */
  1317. { const BYTE* sourceEnd = (const BYTE*) source + inputSize;
  1318. if ((sourceEnd > streamPtr->dictionary) && (sourceEnd < dictEnd)) {
  1319. streamPtr->dictSize = (U32)(dictEnd - sourceEnd);
  1320. if (streamPtr->dictSize > 64 KB) streamPtr->dictSize = 64 KB;
  1321. if (streamPtr->dictSize < 4) streamPtr->dictSize = 0;
  1322. streamPtr->dictionary = dictEnd - streamPtr->dictSize;
  1323. }
  1324. }
  1325. /* prefix mode : source data follows dictionary */
  1326. if (dictEnd == (const BYTE*)source) {
  1327. if ((streamPtr->dictSize < 64 KB) && (streamPtr->dictSize < streamPtr->currentOffset))
  1328. return LZ4_compress_generic(streamPtr, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, withPrefix64k, dictSmall, acceleration);
  1329. else
  1330. return LZ4_compress_generic(streamPtr, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, withPrefix64k, noDictIssue, acceleration);
  1331. }
  1332. /* external dictionary mode */
  1333. { int result;
  1334. if (streamPtr->dictCtx) {
  1335. /* We depend here on the fact that dictCtx'es (produced by
  1336. * LZ4_loadDict) guarantee that their tables contain no references
  1337. * to offsets between dictCtx->currentOffset - 64 KB and
  1338. * dictCtx->currentOffset - dictCtx->dictSize. This makes it safe
  1339. * to use noDictIssue even when the dict isn't a full 64 KB.
  1340. */
  1341. if (inputSize > 4 KB) {
  1342. /* For compressing large blobs, it is faster to pay the setup
  1343. * cost to copy the dictionary's tables into the active context,
  1344. * so that the compression loop is only looking into one table.
  1345. */
  1346. memcpy(streamPtr, streamPtr->dictCtx, sizeof(LZ4_stream_t));
  1347. result = LZ4_compress_generic(streamPtr, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, usingExtDict, noDictIssue, acceleration);
  1348. } else {
  1349. result = LZ4_compress_generic(streamPtr, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, usingDictCtx, noDictIssue, acceleration);
  1350. }
  1351. } else {
  1352. if ((streamPtr->dictSize < 64 KB) && (streamPtr->dictSize < streamPtr->currentOffset)) {
  1353. result = LZ4_compress_generic(streamPtr, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, usingExtDict, dictSmall, acceleration);
  1354. } else {
  1355. result = LZ4_compress_generic(streamPtr, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, usingExtDict, noDictIssue, acceleration);
  1356. }
  1357. }
  1358. streamPtr->dictionary = (const BYTE*)source;
  1359. streamPtr->dictSize = (U32)inputSize;
  1360. return result;
  1361. }
  1362. }
  1363. /* Hidden debug function, to force-test external dictionary mode */
  1364. int LZ4_compress_forceExtDict (LZ4_stream_t* LZ4_dict, const char* source, char* dest, int srcSize)
  1365. {
  1366. LZ4_stream_t_internal* streamPtr = &LZ4_dict->internal_donotuse;
  1367. int result;
  1368. LZ4_renormDictT(streamPtr, srcSize);
  1369. if ((streamPtr->dictSize < 64 KB) && (streamPtr->dictSize < streamPtr->currentOffset)) {
  1370. result = LZ4_compress_generic(streamPtr, source, dest, srcSize, NULL, 0, notLimited, byU32, usingExtDict, dictSmall, 1);
  1371. } else {
  1372. result = LZ4_compress_generic(streamPtr, source, dest, srcSize, NULL, 0, notLimited, byU32, usingExtDict, noDictIssue, 1);
  1373. }
  1374. streamPtr->dictionary = (const BYTE*)source;
  1375. streamPtr->dictSize = (U32)srcSize;
  1376. return result;
  1377. }
  1378. /*! LZ4_saveDict() :
  1379. * If previously compressed data block is not guaranteed to remain available at its memory location,
  1380. * save it into a safer place (char* safeBuffer).
  1381. * Note : you don't need to call LZ4_loadDict() afterwards,
  1382. * dictionary is immediately usable, you can therefore call LZ4_compress_fast_continue().
  1383. * Return : saved dictionary size in bytes (necessarily <= dictSize), or 0 if error.
  1384. */
  1385. int LZ4_saveDict (LZ4_stream_t* LZ4_dict, char* safeBuffer, int dictSize)
  1386. {
  1387. LZ4_stream_t_internal* const dict = &LZ4_dict->internal_donotuse;
  1388. const BYTE* const previousDictEnd = dict->dictionary + dict->dictSize;
  1389. if ((U32)dictSize > 64 KB) { dictSize = 64 KB; } /* useless to define a dictionary > 64 KB */
  1390. if ((U32)dictSize > dict->dictSize) { dictSize = (int)dict->dictSize; }
  1391. memmove(safeBuffer, previousDictEnd - dictSize, dictSize);
  1392. dict->dictionary = (const BYTE*)safeBuffer;
  1393. dict->dictSize = (U32)dictSize;
  1394. return dictSize;
  1395. }
  1396. /*-*******************************
  1397. * Decompression functions
  1398. ********************************/
  1399. typedef enum { endOnOutputSize = 0, endOnInputSize = 1 } endCondition_directive;
  1400. typedef enum { decode_full_block = 0, partial_decode = 1 } earlyEnd_directive;
  1401. #undef MIN
  1402. #define MIN(a,b) ( (a) < (b) ? (a) : (b) )
  1403. /* Read the variable-length literal or match length.
  1404. *
  1405. * ip - pointer to use as input.
  1406. * lencheck - end ip. Return an error if ip advances >= lencheck.
  1407. * loop_check - check ip >= lencheck in body of loop. Returns loop_error if so.
  1408. * initial_check - check ip >= lencheck before start of loop. Returns initial_error if so.
  1409. * error (output) - error code. Should be set to 0 before call.
  1410. */
  1411. typedef enum { loop_error = -2, initial_error = -1, ok = 0 } variable_length_error;
  1412. LZ4_FORCE_INLINE unsigned
  1413. read_variable_length(const BYTE**ip, const BYTE* lencheck, int loop_check, int initial_check, variable_length_error* error)
  1414. {
  1415. unsigned length = 0;
  1416. unsigned s;
  1417. if (initial_check && unlikely((*ip) >= lencheck)) { /* overflow detection */
  1418. *error = initial_error;
  1419. return length;
  1420. }
  1421. do {
  1422. s = **ip;
  1423. (*ip)++;
  1424. length += s;
  1425. if (loop_check && unlikely((*ip) >= lencheck)) { /* overflow detection */
  1426. *error = loop_error;
  1427. return length;
  1428. }
  1429. } while (s==255);
  1430. return length;
  1431. }
  1432. /*! LZ4_decompress_generic() :
  1433. * This generic decompression function covers all use cases.
  1434. * It shall be instantiated several times, using different sets of directives.
  1435. * Note that it is important for performance that this function really get inlined,
  1436. * in order to remove useless branches during compilation optimization.
  1437. */
  1438. LZ4_FORCE_INLINE int
  1439. LZ4_decompress_generic(
  1440. const char* const src,
  1441. char* const dst,
  1442. int srcSize,
  1443. int outputSize, /* If endOnInput==endOnInputSize, this value is `dstCapacity` */
  1444. endCondition_directive endOnInput, /* endOnOutputSize, endOnInputSize */
  1445. earlyEnd_directive partialDecoding, /* full, partial */
  1446. dict_directive dict, /* noDict, withPrefix64k, usingExtDict */
  1447. const BYTE* const lowPrefix, /* always <= dst, == dst when no prefix */
  1448. const BYTE* const dictStart, /* only if dict==usingExtDict */
  1449. const size_t dictSize /* note : = 0 if noDict */
  1450. )
  1451. {
  1452. if (src == NULL) { return -1; }
  1453. { const BYTE* ip = (const BYTE*) src;
  1454. const BYTE* const iend = ip + srcSize;
  1455. BYTE* op = (BYTE*) dst;
  1456. BYTE* const oend = op + outputSize;
  1457. BYTE* cpy;
  1458. const BYTE* const dictEnd = (dictStart == NULL) ? NULL : dictStart + dictSize;
  1459. const int safeDecode = (endOnInput==endOnInputSize);
  1460. const int checkOffset = ((safeDecode) && (dictSize < (int)(64 KB)));
  1461. /* Set up the "end" pointers for the shortcut. */
  1462. const BYTE* const shortiend = iend - (endOnInput ? 14 : 8) /*maxLL*/ - 2 /*offset*/;
  1463. const BYTE* const shortoend = oend - (endOnInput ? 14 : 8) /*maxLL*/ - 18 /*maxML*/;
  1464. const BYTE* match;
  1465. size_t offset;
  1466. unsigned token;
  1467. size_t length;
  1468. DEBUGLOG(5, "LZ4_decompress_generic (srcSize:%i, dstSize:%i)", srcSize, outputSize);
  1469. /* Special cases */
  1470. assert(lowPrefix <= op);
  1471. if ((endOnInput) && (unlikely(outputSize==0))) {
  1472. /* Empty output buffer */
  1473. if (partialDecoding) return 0;
  1474. return ((srcSize==1) && (*ip==0)) ? 0 : -1;
  1475. }
  1476. if ((!endOnInput) && (unlikely(outputSize==0))) { return (*ip==0 ? 1 : -1); }
  1477. if ((endOnInput) && unlikely(srcSize==0)) { return -1; }
  1478. /* Currently the fast loop shows a regression on qualcomm arm chips. */
  1479. #if LZ4_FAST_DEC_LOOP
  1480. if ((oend - op) < FASTLOOP_SAFE_DISTANCE) {
  1481. DEBUGLOG(6, "skip fast decode loop");
  1482. goto safe_decode;
  1483. }
  1484. /* Fast loop : decode sequences as long as output < iend-FASTLOOP_SAFE_DISTANCE */
  1485. while (1) {
  1486. /* Main fastloop assertion: We can always wildcopy FASTLOOP_SAFE_DISTANCE */
  1487. assert(oend - op >= FASTLOOP_SAFE_DISTANCE);
  1488. if (endOnInput) { assert(ip < iend); }
  1489. token = *ip++;
  1490. length = token >> ML_BITS; /* literal length */
  1491. assert(!endOnInput || ip <= iend); /* ip < iend before the increment */
  1492. /* decode literal length */
  1493. if (length == RUN_MASK) {
  1494. variable_length_error error = ok;
  1495. length += read_variable_length(&ip, iend-RUN_MASK, endOnInput, endOnInput, &error);
  1496. if (error == initial_error) { goto _output_error; }
  1497. if ((safeDecode) && unlikely((uptrval)(op)+length<(uptrval)(op))) { goto _output_error; } /* overflow detection */
  1498. if ((safeDecode) && unlikely((uptrval)(ip)+length<(uptrval)(ip))) { goto _output_error; } /* overflow detection */
  1499. /* copy literals */
  1500. cpy = op+length;
  1501. LZ4_STATIC_ASSERT(MFLIMIT >= WILDCOPYLENGTH);
  1502. if (endOnInput) { /* LZ4_decompress_safe() */
  1503. if ((cpy>oend-32) || (ip+length>iend-32)) { goto safe_literal_copy; }
  1504. LZ4_wildCopy32(op, ip, cpy);
  1505. } else { /* LZ4_decompress_fast() */
  1506. if (cpy>oend-8) { goto safe_literal_copy; }
  1507. LZ4_wildCopy8(op, ip, cpy); /* LZ4_decompress_fast() cannot copy more than 8 bytes at a time :
  1508. * it doesn't know input length, and only relies on end-of-block properties */
  1509. }
  1510. ip += length; op = cpy;
  1511. } else {
  1512. cpy = op+length;
  1513. if (endOnInput) { /* LZ4_decompress_safe() */
  1514. DEBUGLOG(7, "copy %u bytes in a 16-bytes stripe", (unsigned)length);
  1515. /* We don't need to check oend, since we check it once for each loop below */
  1516. if (ip > iend-(16 + 1/*max lit + offset + nextToken*/)) { goto safe_literal_copy; }
  1517. /* Literals can only be 14, but hope compilers optimize if we copy by a register size */
  1518. memcpy(op, ip, 16);
  1519. } else { /* LZ4_decompress_fast() */
  1520. /* LZ4_decompress_fast() cannot copy more than 8 bytes at a time :
  1521. * it doesn't know input length, and relies on end-of-block properties */
  1522. memcpy(op, ip, 8);
  1523. if (length > 8) { memcpy(op+8, ip+8, 8); }
  1524. }
  1525. ip += length; op = cpy;
  1526. }
  1527. /* get offset */
  1528. offset = LZ4_readLE16(ip); ip+=2;
  1529. match = op - offset;
  1530. assert(match <= op);
  1531. /* get matchlength */
  1532. length = token & ML_MASK;
  1533. if (length == ML_MASK) {
  1534. variable_length_error error = ok;
  1535. if ((checkOffset) && (unlikely(match + dictSize < lowPrefix))) { goto _output_error; } /* Error : offset outside buffers */
  1536. length += read_variable_length(&ip, iend - LASTLITERALS + 1, endOnInput, 0, &error);
  1537. if (error != ok) { goto _output_error; }
  1538. if ((safeDecode) && unlikely((uptrval)(op)+length<(uptrval)op)) { goto _output_error; } /* overflow detection */
  1539. length += MINMATCH;
  1540. if (op + length >= oend - FASTLOOP_SAFE_DISTANCE) {
  1541. goto safe_match_copy;
  1542. }
  1543. } else {
  1544. length += MINMATCH;
  1545. if (op + length >= oend - FASTLOOP_SAFE_DISTANCE) {
  1546. goto safe_match_copy;
  1547. }
  1548. /* Fastpath check: Avoids a branch in LZ4_wildCopy32 if true */
  1549. if ((dict == withPrefix64k) || (match >= lowPrefix)) {
  1550. if (offset >= 8) {
  1551. assert(match >= lowPrefix);
  1552. assert(match <= op);
  1553. assert(op + 18 <= oend);
  1554. memcpy(op, match, 8);
  1555. memcpy(op+8, match+8, 8);
  1556. memcpy(op+16, match+16, 2);
  1557. op += length;
  1558. continue;
  1559. } } }
  1560. if ((checkOffset) && (unlikely(match + dictSize < lowPrefix))) { goto _output_error; } /* Error : offset outside buffers */
  1561. /* match starting within external dictionary */
  1562. if ((dict==usingExtDict) && (match < lowPrefix)) {
  1563. if (unlikely(op+length > oend-LASTLITERALS)) {
  1564. if (partialDecoding) {
  1565. length = MIN(length, (size_t)(oend-op)); /* reach end of buffer */
  1566. } else {
  1567. goto _output_error; /* end-of-block condition violated */
  1568. } }
  1569. if (length <= (size_t)(lowPrefix-match)) {
  1570. /* match fits entirely within external dictionary : just copy */
  1571. memmove(op, dictEnd - (lowPrefix-match), length);
  1572. op += length;
  1573. } else {
  1574. /* match stretches into both external dictionary and current block */
  1575. size_t const copySize = (size_t)(lowPrefix - match);
  1576. size_t const restSize = length - copySize;
  1577. memcpy(op, dictEnd - copySize, copySize);
  1578. op += copySize;
  1579. if (restSize > (size_t)(op - lowPrefix)) { /* overlap copy */
  1580. BYTE* const endOfMatch = op + restSize;
  1581. const BYTE* copyFrom = lowPrefix;
  1582. while (op < endOfMatch) { *op++ = *copyFrom++; }
  1583. } else {
  1584. memcpy(op, lowPrefix, restSize);
  1585. op += restSize;
  1586. } }
  1587. continue;
  1588. }
  1589. /* copy match within block */
  1590. cpy = op + length;
  1591. assert((op <= oend) && (oend-op >= 32));
  1592. if (unlikely(offset<16)) {
  1593. LZ4_memcpy_using_offset(op, match, cpy, offset);
  1594. } else {
  1595. LZ4_wildCopy32(op, match, cpy);
  1596. }
  1597. op = cpy; /* wildcopy correction */
  1598. }
  1599. safe_decode:
  1600. #endif
  1601. /* Main Loop : decode remaining sequences where output < FASTLOOP_SAFE_DISTANCE */
  1602. while (1) {
  1603. token = *ip++;
  1604. length = token >> ML_BITS; /* literal length */
  1605. assert(!endOnInput || ip <= iend); /* ip < iend before the increment */
  1606. /* A two-stage shortcut for the most common case:
  1607. * 1) If the literal length is 0..14, and there is enough space,
  1608. * enter the shortcut and copy 16 bytes on behalf of the literals
  1609. * (in the fast mode, only 8 bytes can be safely copied this way).
  1610. * 2) Further if the match length is 4..18, copy 18 bytes in a similar
  1611. * manner; but we ensure that there's enough space in the output for
  1612. * those 18 bytes earlier, upon entering the shortcut (in other words,
  1613. * there is a combined check for both stages).
  1614. */
  1615. if ( (endOnInput ? length != RUN_MASK : length <= 8)
  1616. /* strictly "less than" on input, to re-enter the loop with at least one byte */
  1617. && likely((endOnInput ? ip < shortiend : 1) & (op <= shortoend)) ) {
  1618. /* Copy the literals */
  1619. memcpy(op, ip, endOnInput ? 16 : 8);
  1620. op += length; ip += length;
  1621. /* The second stage: prepare for match copying, decode full info.
  1622. * If it doesn't work out, the info won't be wasted. */
  1623. length = token & ML_MASK; /* match length */
  1624. offset = LZ4_readLE16(ip); ip += 2;
  1625. match = op - offset;
  1626. assert(match <= op); /* check overflow */
  1627. /* Do not deal with overlapping matches. */
  1628. if ( (length != ML_MASK)
  1629. && (offset >= 8)
  1630. && (dict==withPrefix64k || match >= lowPrefix) ) {
  1631. /* Copy the match. */
  1632. memcpy(op + 0, match + 0, 8);
  1633. memcpy(op + 8, match + 8, 8);
  1634. memcpy(op +16, match +16, 2);
  1635. op += length + MINMATCH;
  1636. /* Both stages worked, load the next token. */
  1637. continue;
  1638. }
  1639. /* The second stage didn't work out, but the info is ready.
  1640. * Propel it right to the point of match copying. */
  1641. goto _copy_match;
  1642. }
  1643. /* decode literal length */
  1644. if (length == RUN_MASK) {
  1645. variable_length_error error = ok;
  1646. length += read_variable_length(&ip, iend-RUN_MASK, endOnInput, endOnInput, &error);
  1647. if (error == initial_error) { goto _output_error; }
  1648. if ((safeDecode) && unlikely((uptrval)(op)+length<(uptrval)(op))) { goto _output_error; } /* overflow detection */
  1649. if ((safeDecode) && unlikely((uptrval)(ip)+length<(uptrval)(ip))) { goto _output_error; } /* overflow detection */
  1650. }
  1651. /* copy literals */
  1652. cpy = op+length;
  1653. #if LZ4_FAST_DEC_LOOP
  1654. safe_literal_copy:
  1655. #endif
  1656. LZ4_STATIC_ASSERT(MFLIMIT >= WILDCOPYLENGTH);
  1657. if ( ((endOnInput) && ((cpy>oend-MFLIMIT) || (ip+length>iend-(2+1+LASTLITERALS))) )
  1658. || ((!endOnInput) && (cpy>oend-WILDCOPYLENGTH)) )
  1659. {
  1660. /* We've either hit the input parsing restriction or the output parsing restriction.
  1661. * If we've hit the input parsing condition then this must be the last sequence.
  1662. * If we've hit the output parsing condition then we are either using partialDecoding
  1663. * or we've hit the output parsing condition.
  1664. */
  1665. if (partialDecoding) {
  1666. /* Since we are partial decoding we may be in this block because of the output parsing
  1667. * restriction, which is not valid since the output buffer is allowed to be undersized.
  1668. */
  1669. assert(endOnInput);
  1670. /* If we're in this block because of the input parsing condition, then we must be on the
  1671. * last sequence (or invalid), so we must check that we exactly consume the input.
  1672. */
  1673. if ((ip+length>iend-(2+1+LASTLITERALS)) && (ip+length != iend)) { goto _output_error; }
  1674. assert(ip+length <= iend);
  1675. /* We are finishing in the middle of a literals segment.
  1676. * Break after the copy.
  1677. */
  1678. if (cpy > oend) {
  1679. cpy = oend;
  1680. assert(op<=oend);
  1681. length = (size_t)(oend-op);
  1682. }
  1683. assert(ip+length <= iend);
  1684. } else {
  1685. /* We must be on the last sequence because of the parsing limitations so check
  1686. * that we exactly regenerate the original size (must be exact when !endOnInput).
  1687. */
  1688. if ((!endOnInput) && (cpy != oend)) { goto _output_error; }
  1689. /* We must be on the last sequence (or invalid) because of the parsing limitations
  1690. * so check that we exactly consume the input and don't overrun the output buffer.
  1691. */
  1692. if ((endOnInput) && ((ip+length != iend) || (cpy > oend))) { goto _output_error; }
  1693. }
  1694. memmove(op, ip, length); /* supports overlapping memory regions, which only matters for in-place decompression scenarios */
  1695. ip += length;
  1696. op += length;
  1697. /* Necessarily EOF when !partialDecoding. When partialDecoding
  1698. * it is EOF if we've either filled the output buffer or hit
  1699. * the input parsing restriction.
  1700. */
  1701. if (!partialDecoding || (cpy == oend) || (ip == iend)) {
  1702. break;
  1703. }
  1704. } else {
  1705. LZ4_wildCopy8(op, ip, cpy); /* may overwrite up to WILDCOPYLENGTH beyond cpy */
  1706. ip += length; op = cpy;
  1707. }
  1708. /* get offset */
  1709. offset = LZ4_readLE16(ip); ip+=2;
  1710. match = op - offset;
  1711. /* get matchlength */
  1712. length = token & ML_MASK;
  1713. _copy_match:
  1714. if (length == ML_MASK) {
  1715. variable_length_error error = ok;
  1716. length += read_variable_length(&ip, iend - LASTLITERALS + 1, endOnInput, 0, &error);
  1717. if (error != ok) goto _output_error;
  1718. if ((safeDecode) && unlikely((uptrval)(op)+length<(uptrval)op)) goto _output_error; /* overflow detection */
  1719. }
  1720. length += MINMATCH;
  1721. #if LZ4_FAST_DEC_LOOP
  1722. safe_match_copy:
  1723. #endif
  1724. if ((checkOffset) && (unlikely(match + dictSize < lowPrefix))) goto _output_error; /* Error : offset outside buffers */
  1725. /* match starting within external dictionary */
  1726. if ((dict==usingExtDict) && (match < lowPrefix)) {
  1727. if (unlikely(op+length > oend-LASTLITERALS)) {
  1728. if (partialDecoding) length = MIN(length, (size_t)(oend-op));
  1729. else goto _output_error; /* doesn't respect parsing restriction */
  1730. }
  1731. if (length <= (size_t)(lowPrefix-match)) {
  1732. /* match fits entirely within external dictionary : just copy */
  1733. memmove(op, dictEnd - (lowPrefix-match), length);
  1734. op += length;
  1735. } else {
  1736. /* match stretches into both external dictionary and current block */
  1737. size_t const copySize = (size_t)(lowPrefix - match);
  1738. size_t const restSize = length - copySize;
  1739. memcpy(op, dictEnd - copySize, copySize);
  1740. op += copySize;
  1741. if (restSize > (size_t)(op - lowPrefix)) { /* overlap copy */
  1742. BYTE* const endOfMatch = op + restSize;
  1743. const BYTE* copyFrom = lowPrefix;
  1744. while (op < endOfMatch) *op++ = *copyFrom++;
  1745. } else {
  1746. memcpy(op, lowPrefix, restSize);
  1747. op += restSize;
  1748. } }
  1749. continue;
  1750. }
  1751. assert(match >= lowPrefix);
  1752. /* copy match within block */
  1753. cpy = op + length;
  1754. /* partialDecoding : may end anywhere within the block */
  1755. assert(op<=oend);
  1756. if (partialDecoding && (cpy > oend-MATCH_SAFEGUARD_DISTANCE)) {
  1757. size_t const mlen = MIN(length, (size_t)(oend-op));
  1758. const BYTE* const matchEnd = match + mlen;
  1759. BYTE* const copyEnd = op + mlen;
  1760. if (matchEnd > op) { /* overlap copy */
  1761. while (op < copyEnd) { *op++ = *match++; }
  1762. } else {
  1763. memcpy(op, match, mlen);
  1764. }
  1765. op = copyEnd;
  1766. if (op == oend) { break; }
  1767. continue;
  1768. }
  1769. if (unlikely(offset<8)) {
  1770. LZ4_write32(op, 0); /* silence msan warning when offset==0 */
  1771. op[0] = match[0];
  1772. op[1] = match[1];
  1773. op[2] = match[2];
  1774. op[3] = match[3];
  1775. match += inc32table[offset];
  1776. memcpy(op+4, match, 4);
  1777. match -= dec64table[offset];
  1778. } else {
  1779. memcpy(op, match, 8);
  1780. match += 8;
  1781. }
  1782. op += 8;
  1783. if (unlikely(cpy > oend-MATCH_SAFEGUARD_DISTANCE)) {
  1784. BYTE* const oCopyLimit = oend - (WILDCOPYLENGTH-1);
  1785. if (cpy > oend-LASTLITERALS) { goto _output_error; } /* Error : last LASTLITERALS bytes must be literals (uncompressed) */
  1786. if (op < oCopyLimit) {
  1787. LZ4_wildCopy8(op, match, oCopyLimit);
  1788. match += oCopyLimit - op;
  1789. op = oCopyLimit;
  1790. }
  1791. while (op < cpy) { *op++ = *match++; }
  1792. } else {
  1793. memcpy(op, match, 8);
  1794. if (length > 16) { LZ4_wildCopy8(op+8, match+8, cpy); }
  1795. }
  1796. op = cpy; /* wildcopy correction */
  1797. }
  1798. /* end of decoding */
  1799. if (endOnInput) {
  1800. return (int) (((char*)op)-dst); /* Nb of output bytes decoded */
  1801. } else {
  1802. return (int) (((const char*)ip)-src); /* Nb of input bytes read */
  1803. }
  1804. /* Overflow error detected */
  1805. _output_error:
  1806. return (int) (-(((const char*)ip)-src))-1;
  1807. }
  1808. }
  1809. /*===== Instantiate the API decoding functions. =====*/
  1810. LZ4_FORCE_O2_GCC_PPC64LE
  1811. int LZ4_decompress_safe(const char* source, char* dest, int compressedSize, int maxDecompressedSize)
  1812. {
  1813. return LZ4_decompress_generic(source, dest, compressedSize, maxDecompressedSize,
  1814. endOnInputSize, decode_full_block, noDict,
  1815. (BYTE*)dest, NULL, 0);
  1816. }
  1817. LZ4_FORCE_O2_GCC_PPC64LE
  1818. int LZ4_decompress_safe_partial(const char* src, char* dst, int compressedSize, int targetOutputSize, int dstCapacity)
  1819. {
  1820. dstCapacity = MIN(targetOutputSize, dstCapacity);
  1821. return LZ4_decompress_generic(src, dst, compressedSize, dstCapacity,
  1822. endOnInputSize, partial_decode,
  1823. noDict, (BYTE*)dst, NULL, 0);
  1824. }
  1825. LZ4_FORCE_O2_GCC_PPC64LE
  1826. int LZ4_decompress_fast(const char* source, char* dest, int originalSize)
  1827. {
  1828. return LZ4_decompress_generic(source, dest, 0, originalSize,
  1829. endOnOutputSize, decode_full_block, withPrefix64k,
  1830. (BYTE*)dest - 64 KB, NULL, 0);
  1831. }
  1832. /*===== Instantiate a few more decoding cases, used more than once. =====*/
  1833. LZ4_FORCE_O2_GCC_PPC64LE /* Exported, an obsolete API function. */
  1834. int LZ4_decompress_safe_withPrefix64k(const char* source, char* dest, int compressedSize, int maxOutputSize)
  1835. {
  1836. return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize,
  1837. endOnInputSize, decode_full_block, withPrefix64k,
  1838. (BYTE*)dest - 64 KB, NULL, 0);
  1839. }
  1840. /* Another obsolete API function, paired with the previous one. */
  1841. int LZ4_decompress_fast_withPrefix64k(const char* source, char* dest, int originalSize)
  1842. {
  1843. /* LZ4_decompress_fast doesn't validate match offsets,
  1844. * and thus serves well with any prefixed dictionary. */
  1845. return LZ4_decompress_fast(source, dest, originalSize);
  1846. }
  1847. LZ4_FORCE_O2_GCC_PPC64LE
  1848. static int LZ4_decompress_safe_withSmallPrefix(const char* source, char* dest, int compressedSize, int maxOutputSize,
  1849. size_t prefixSize)
  1850. {
  1851. return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize,
  1852. endOnInputSize, decode_full_block, noDict,
  1853. (BYTE*)dest-prefixSize, NULL, 0);
  1854. }
  1855. LZ4_FORCE_O2_GCC_PPC64LE
  1856. int LZ4_decompress_safe_forceExtDict(const char* source, char* dest,
  1857. int compressedSize, int maxOutputSize,
  1858. const void* dictStart, size_t dictSize)
  1859. {
  1860. return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize,
  1861. endOnInputSize, decode_full_block, usingExtDict,
  1862. (BYTE*)dest, (const BYTE*)dictStart, dictSize);
  1863. }
  1864. LZ4_FORCE_O2_GCC_PPC64LE
  1865. static int LZ4_decompress_fast_extDict(const char* source, char* dest, int originalSize,
  1866. const void* dictStart, size_t dictSize)
  1867. {
  1868. return LZ4_decompress_generic(source, dest, 0, originalSize,
  1869. endOnOutputSize, decode_full_block, usingExtDict,
  1870. (BYTE*)dest, (const BYTE*)dictStart, dictSize);
  1871. }
  1872. /* The "double dictionary" mode, for use with e.g. ring buffers: the first part
  1873. * of the dictionary is passed as prefix, and the second via dictStart + dictSize.
  1874. * These routines are used only once, in LZ4_decompress_*_continue().
  1875. */
  1876. LZ4_FORCE_INLINE
  1877. int LZ4_decompress_safe_doubleDict(const char* source, char* dest, int compressedSize, int maxOutputSize,
  1878. size_t prefixSize, const void* dictStart, size_t dictSize)
  1879. {
  1880. return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize,
  1881. endOnInputSize, decode_full_block, usingExtDict,
  1882. (BYTE*)dest-prefixSize, (const BYTE*)dictStart, dictSize);
  1883. }
  1884. LZ4_FORCE_INLINE
  1885. int LZ4_decompress_fast_doubleDict(const char* source, char* dest, int originalSize,
  1886. size_t prefixSize, const void* dictStart, size_t dictSize)
  1887. {
  1888. return LZ4_decompress_generic(source, dest, 0, originalSize,
  1889. endOnOutputSize, decode_full_block, usingExtDict,
  1890. (BYTE*)dest-prefixSize, (const BYTE*)dictStart, dictSize);
  1891. }
  1892. /*===== streaming decompression functions =====*/
  1893. LZ4_streamDecode_t* LZ4_createStreamDecode(void)
  1894. {
  1895. LZ4_streamDecode_t* lz4s = (LZ4_streamDecode_t*) ALLOC_AND_ZERO(sizeof(LZ4_streamDecode_t));
  1896. LZ4_STATIC_ASSERT(LZ4_STREAMDECODESIZE >= sizeof(LZ4_streamDecode_t_internal)); /* A compilation error here means LZ4_STREAMDECODESIZE is not large enough */
  1897. return lz4s;
  1898. }
  1899. int LZ4_freeStreamDecode (LZ4_streamDecode_t* LZ4_stream)
  1900. {
  1901. if (LZ4_stream == NULL) { return 0; } /* support free on NULL */
  1902. FREEMEM(LZ4_stream);
  1903. return 0;
  1904. }
  1905. /*! LZ4_setStreamDecode() :
  1906. * Use this function to instruct where to find the dictionary.
  1907. * This function is not necessary if previous data is still available where it was decoded.
  1908. * Loading a size of 0 is allowed (same effect as no dictionary).
  1909. * @return : 1 if OK, 0 if error
  1910. */
  1911. int LZ4_setStreamDecode (LZ4_streamDecode_t* LZ4_streamDecode, const char* dictionary, int dictSize)
  1912. {
  1913. LZ4_streamDecode_t_internal* lz4sd = &LZ4_streamDecode->internal_donotuse;
  1914. lz4sd->prefixSize = (size_t) dictSize;
  1915. lz4sd->prefixEnd = (const BYTE*) dictionary + dictSize;
  1916. lz4sd->externalDict = NULL;
  1917. lz4sd->extDictSize = 0;
  1918. return 1;
  1919. }
  1920. /*! LZ4_decoderRingBufferSize() :
  1921. * when setting a ring buffer for streaming decompression (optional scenario),
  1922. * provides the minimum size of this ring buffer
  1923. * to be compatible with any source respecting maxBlockSize condition.
  1924. * Note : in a ring buffer scenario,
  1925. * blocks are presumed decompressed next to each other.
  1926. * When not enough space remains for next block (remainingSize < maxBlockSize),
  1927. * decoding resumes from beginning of ring buffer.
  1928. * @return : minimum ring buffer size,
  1929. * or 0 if there is an error (invalid maxBlockSize).
  1930. */
  1931. int LZ4_decoderRingBufferSize(int maxBlockSize)
  1932. {
  1933. if (maxBlockSize < 0) return 0;
  1934. if (maxBlockSize > LZ4_MAX_INPUT_SIZE) return 0;
  1935. if (maxBlockSize < 16) maxBlockSize = 16;
  1936. return LZ4_DECODER_RING_BUFFER_SIZE(maxBlockSize);
  1937. }
  1938. /*
  1939. *_continue() :
  1940. These decoding functions allow decompression of multiple blocks in "streaming" mode.
  1941. Previously decoded blocks must still be available at the memory position where they were decoded.
  1942. If it's not possible, save the relevant part of decoded data into a safe buffer,
  1943. and indicate where it stands using LZ4_setStreamDecode()
  1944. */
  1945. LZ4_FORCE_O2_GCC_PPC64LE
  1946. int LZ4_decompress_safe_continue (LZ4_streamDecode_t* LZ4_streamDecode, const char* source, char* dest, int compressedSize, int maxOutputSize)
  1947. {
  1948. LZ4_streamDecode_t_internal* lz4sd = &LZ4_streamDecode->internal_donotuse;
  1949. int result;
  1950. if (lz4sd->prefixSize == 0) {
  1951. /* The first call, no dictionary yet. */
  1952. assert(lz4sd->extDictSize == 0);
  1953. result = LZ4_decompress_safe(source, dest, compressedSize, maxOutputSize);
  1954. if (result <= 0) return result;
  1955. lz4sd->prefixSize = (size_t)result;
  1956. lz4sd->prefixEnd = (BYTE*)dest + result;
  1957. } else if (lz4sd->prefixEnd == (BYTE*)dest) {
  1958. /* They're rolling the current segment. */
  1959. if (lz4sd->prefixSize >= 64 KB - 1)
  1960. result = LZ4_decompress_safe_withPrefix64k(source, dest, compressedSize, maxOutputSize);
  1961. else if (lz4sd->extDictSize == 0)
  1962. result = LZ4_decompress_safe_withSmallPrefix(source, dest, compressedSize, maxOutputSize,
  1963. lz4sd->prefixSize);
  1964. else
  1965. result = LZ4_decompress_safe_doubleDict(source, dest, compressedSize, maxOutputSize,
  1966. lz4sd->prefixSize, lz4sd->externalDict, lz4sd->extDictSize);
  1967. if (result <= 0) return result;
  1968. lz4sd->prefixSize += (size_t)result;
  1969. lz4sd->prefixEnd += result;
  1970. } else {
  1971. /* The buffer wraps around, or they're switching to another buffer. */
  1972. lz4sd->extDictSize = lz4sd->prefixSize;
  1973. lz4sd->externalDict = lz4sd->prefixEnd - lz4sd->extDictSize;
  1974. result = LZ4_decompress_safe_forceExtDict(source, dest, compressedSize, maxOutputSize,
  1975. lz4sd->externalDict, lz4sd->extDictSize);
  1976. if (result <= 0) return result;
  1977. lz4sd->prefixSize = (size_t)result;
  1978. lz4sd->prefixEnd = (BYTE*)dest + result;
  1979. }
  1980. return result;
  1981. }
  1982. LZ4_FORCE_O2_GCC_PPC64LE
  1983. int LZ4_decompress_fast_continue (LZ4_streamDecode_t* LZ4_streamDecode, const char* source, char* dest, int originalSize)
  1984. {
  1985. LZ4_streamDecode_t_internal* lz4sd = &LZ4_streamDecode->internal_donotuse;
  1986. int result;
  1987. assert(originalSize >= 0);
  1988. if (lz4sd->prefixSize == 0) {
  1989. assert(lz4sd->extDictSize == 0);
  1990. result = LZ4_decompress_fast(source, dest, originalSize);
  1991. if (result <= 0) return result;
  1992. lz4sd->prefixSize = (size_t)originalSize;
  1993. lz4sd->prefixEnd = (BYTE*)dest + originalSize;
  1994. } else if (lz4sd->prefixEnd == (BYTE*)dest) {
  1995. if (lz4sd->prefixSize >= 64 KB - 1 || lz4sd->extDictSize == 0)
  1996. result = LZ4_decompress_fast(source, dest, originalSize);
  1997. else
  1998. result = LZ4_decompress_fast_doubleDict(source, dest, originalSize,
  1999. lz4sd->prefixSize, lz4sd->externalDict, lz4sd->extDictSize);
  2000. if (result <= 0) return result;
  2001. lz4sd->prefixSize += (size_t)originalSize;
  2002. lz4sd->prefixEnd += originalSize;
  2003. } else {
  2004. lz4sd->extDictSize = lz4sd->prefixSize;
  2005. lz4sd->externalDict = lz4sd->prefixEnd - lz4sd->extDictSize;
  2006. result = LZ4_decompress_fast_extDict(source, dest, originalSize,
  2007. lz4sd->externalDict, lz4sd->extDictSize);
  2008. if (result <= 0) return result;
  2009. lz4sd->prefixSize = (size_t)originalSize;
  2010. lz4sd->prefixEnd = (BYTE*)dest + originalSize;
  2011. }
  2012. return result;
  2013. }
  2014. /*
  2015. Advanced decoding functions :
  2016. *_usingDict() :
  2017. These decoding functions work the same as "_continue" ones,
  2018. the dictionary must be explicitly provided within parameters
  2019. */
  2020. int LZ4_decompress_safe_usingDict(const char* source, char* dest, int compressedSize, int maxOutputSize, const char* dictStart, int dictSize)
  2021. {
  2022. if (dictSize==0)
  2023. return LZ4_decompress_safe(source, dest, compressedSize, maxOutputSize);
  2024. if (dictStart+dictSize == dest) {
  2025. if (dictSize >= 64 KB - 1) {
  2026. return LZ4_decompress_safe_withPrefix64k(source, dest, compressedSize, maxOutputSize);
  2027. }
  2028. assert(dictSize >= 0);
  2029. return LZ4_decompress_safe_withSmallPrefix(source, dest, compressedSize, maxOutputSize, (size_t)dictSize);
  2030. }
  2031. assert(dictSize >= 0);
  2032. return LZ4_decompress_safe_forceExtDict(source, dest, compressedSize, maxOutputSize, dictStart, (size_t)dictSize);
  2033. }
  2034. int LZ4_decompress_fast_usingDict(const char* source, char* dest, int originalSize, const char* dictStart, int dictSize)
  2035. {
  2036. if (dictSize==0 || dictStart+dictSize == dest)
  2037. return LZ4_decompress_fast(source, dest, originalSize);
  2038. assert(dictSize >= 0);
  2039. return LZ4_decompress_fast_extDict(source, dest, originalSize, dictStart, (size_t)dictSize);
  2040. }
  2041. /*=*************************************************
  2042. * Obsolete Functions
  2043. ***************************************************/
  2044. /* obsolete compression functions */
  2045. int LZ4_compress_limitedOutput(const char* source, char* dest, int inputSize, int maxOutputSize)
  2046. {
  2047. return LZ4_compress_default(source, dest, inputSize, maxOutputSize);
  2048. }
  2049. int LZ4_compress(const char* src, char* dest, int srcSize)
  2050. {
  2051. return LZ4_compress_default(src, dest, srcSize, LZ4_compressBound(srcSize));
  2052. }
  2053. int LZ4_compress_limitedOutput_withState (void* state, const char* src, char* dst, int srcSize, int dstSize)
  2054. {
  2055. return LZ4_compress_fast_extState(state, src, dst, srcSize, dstSize, 1);
  2056. }
  2057. int LZ4_compress_withState (void* state, const char* src, char* dst, int srcSize)
  2058. {
  2059. return LZ4_compress_fast_extState(state, src, dst, srcSize, LZ4_compressBound(srcSize), 1);
  2060. }
  2061. int LZ4_compress_limitedOutput_continue (LZ4_stream_t* LZ4_stream, const char* src, char* dst, int srcSize, int dstCapacity)
  2062. {
  2063. return LZ4_compress_fast_continue(LZ4_stream, src, dst, srcSize, dstCapacity, 1);
  2064. }
  2065. int LZ4_compress_continue (LZ4_stream_t* LZ4_stream, const char* source, char* dest, int inputSize)
  2066. {
  2067. return LZ4_compress_fast_continue(LZ4_stream, source, dest, inputSize, LZ4_compressBound(inputSize), 1);
  2068. }
  2069. /*
  2070. These decompression functions are deprecated and should no longer be used.
  2071. They are only provided here for compatibility with older user programs.
  2072. - LZ4_uncompress is totally equivalent to LZ4_decompress_fast
  2073. - LZ4_uncompress_unknownOutputSize is totally equivalent to LZ4_decompress_safe
  2074. */
  2075. int LZ4_uncompress (const char* source, char* dest, int outputSize)
  2076. {
  2077. return LZ4_decompress_fast(source, dest, outputSize);
  2078. }
  2079. int LZ4_uncompress_unknownOutputSize (const char* source, char* dest, int isize, int maxOutputSize)
  2080. {
  2081. return LZ4_decompress_safe(source, dest, isize, maxOutputSize);
  2082. }
  2083. /* Obsolete Streaming functions */
  2084. int LZ4_sizeofStreamState() { return LZ4_STREAMSIZE; }
  2085. int LZ4_resetStreamState(void* state, char* inputBuffer)
  2086. {
  2087. (void)inputBuffer;
  2088. LZ4_resetStream((LZ4_stream_t*)state);
  2089. return 0;
  2090. }
  2091. void* LZ4_create (char* inputBuffer)
  2092. {
  2093. (void)inputBuffer;
  2094. return LZ4_createStream();
  2095. }
  2096. char* LZ4_slideInputBuffer (void* state)
  2097. {
  2098. /* avoid const char * -> char * conversion warning */
  2099. return (char *)(uptrval)((LZ4_stream_t*)state)->internal_donotuse.dictionary;
  2100. }
  2101. #endif /* LZ4_COMMONDEFS_ONLY */