lz4.c 111 KB

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