lz4.c 103 KB

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