2
0

zstd_v03.c 111 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160
  1. /*
  2. * Copyright (c) Yann Collet, Facebook, Inc.
  3. * All rights reserved.
  4. *
  5. * This source code is licensed under both the BSD-style license (found in the
  6. * LICENSE file in the root directory of this source tree) and the GPLv2 (found
  7. * in the COPYING file in the root directory of this source tree).
  8. * You may select, at your option, one of the above-listed licenses.
  9. */
  10. #include <stddef.h> /* size_t, ptrdiff_t */
  11. #include "zstd_v03.h"
  12. #include "../common/error_private.h"
  13. /******************************************
  14. * Compiler-specific
  15. ******************************************/
  16. #if defined(_MSC_VER) /* Visual Studio */
  17. # include <stdlib.h> /* _byteswap_ulong */
  18. # include <intrin.h> /* _byteswap_* */
  19. #endif
  20. /* ******************************************************************
  21. mem.h
  22. low-level memory access routines
  23. Copyright (C) 2013-2015, Yann Collet.
  24. BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
  25. Redistribution and use in source and binary forms, with or without
  26. modification, are permitted provided that the following conditions are
  27. met:
  28. * Redistributions of source code must retain the above copyright
  29. notice, this list of conditions and the following disclaimer.
  30. * Redistributions in binary form must reproduce the above
  31. copyright notice, this list of conditions and the following disclaimer
  32. in the documentation and/or other materials provided with the
  33. distribution.
  34. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  35. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  36. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  37. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  38. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  39. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  40. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  41. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  42. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  43. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  44. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  45. You can contact the author at :
  46. - FSE source repository : https://github.com/Cyan4973/FiniteStateEntropy
  47. - Public forum : https://groups.google.com/forum/#!forum/lz4c
  48. ****************************************************************** */
  49. #ifndef MEM_H_MODULE
  50. #define MEM_H_MODULE
  51. #if defined (__cplusplus)
  52. extern "C" {
  53. #endif
  54. /******************************************
  55. * Includes
  56. ******************************************/
  57. #include <stddef.h> /* size_t, ptrdiff_t */
  58. #include <string.h> /* memcpy */
  59. /******************************************
  60. * Compiler-specific
  61. ******************************************/
  62. #if defined(__GNUC__)
  63. # define MEM_STATIC static __attribute__((unused))
  64. #elif defined (__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */)
  65. # define MEM_STATIC static inline
  66. #elif defined(_MSC_VER)
  67. # define MEM_STATIC static __inline
  68. #else
  69. # define MEM_STATIC static /* this version may generate warnings for unused static functions; disable the relevant warning */
  70. #endif
  71. /****************************************************************
  72. * Basic Types
  73. *****************************************************************/
  74. #if defined (__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */)
  75. # if defined(_AIX)
  76. # include <inttypes.h>
  77. # else
  78. # include <stdint.h> /* intptr_t */
  79. # endif
  80. typedef uint8_t BYTE;
  81. typedef uint16_t U16;
  82. typedef int16_t S16;
  83. typedef uint32_t U32;
  84. typedef int32_t S32;
  85. typedef uint64_t U64;
  86. typedef int64_t S64;
  87. #else
  88. typedef unsigned char BYTE;
  89. typedef unsigned short U16;
  90. typedef signed short S16;
  91. typedef unsigned int U32;
  92. typedef signed int S32;
  93. typedef unsigned long long U64;
  94. typedef signed long long S64;
  95. #endif
  96. /****************************************************************
  97. * Memory I/O
  98. *****************************************************************/
  99. /* MEM_FORCE_MEMORY_ACCESS
  100. * By default, access to unaligned memory is controlled by `memcpy()`, which is safe and portable.
  101. * Unfortunately, on some target/compiler combinations, the generated assembly is sub-optimal.
  102. * The below switch allow to select different access method for improved performance.
  103. * Method 0 (default) : use `memcpy()`. Safe and portable.
  104. * Method 1 : `__packed` statement. It depends on compiler extension (ie, not portable).
  105. * This method is safe if your compiler supports it, and *generally* as fast or faster than `memcpy`.
  106. * Method 2 : direct access. This method is portable but violate C standard.
  107. * It can generate buggy code on targets generating assembly depending on alignment.
  108. * But in some circumstances, it's the only known way to get the most performance (ie GCC + ARMv6)
  109. * See http://fastcompression.blogspot.fr/2015/08/accessing-unaligned-memory.html for details.
  110. * Prefer these methods in priority order (0 > 1 > 2)
  111. */
  112. #ifndef MEM_FORCE_MEMORY_ACCESS /* can be defined externally, on command line for example */
  113. # if defined(__INTEL_COMPILER) || defined(__GNUC__) || defined(__ICCARM__)
  114. # define MEM_FORCE_MEMORY_ACCESS 1
  115. # endif
  116. #endif
  117. MEM_STATIC unsigned MEM_32bits(void) { return sizeof(void*)==4; }
  118. MEM_STATIC unsigned MEM_64bits(void) { return sizeof(void*)==8; }
  119. MEM_STATIC unsigned MEM_isLittleEndian(void)
  120. {
  121. const union { U32 u; BYTE c[4]; } one = { 1 }; /* don't use static : performance detrimental */
  122. return one.c[0];
  123. }
  124. #if defined(MEM_FORCE_MEMORY_ACCESS) && (MEM_FORCE_MEMORY_ACCESS==2)
  125. /* violates C standard on structure alignment.
  126. Only use if no other choice to achieve best performance on target platform */
  127. MEM_STATIC U16 MEM_read16(const void* memPtr) { return *(const U16*) memPtr; }
  128. MEM_STATIC U32 MEM_read32(const void* memPtr) { return *(const U32*) memPtr; }
  129. MEM_STATIC U64 MEM_read64(const void* memPtr) { return *(const U64*) memPtr; }
  130. MEM_STATIC void MEM_write16(void* memPtr, U16 value) { *(U16*)memPtr = value; }
  131. #elif defined(MEM_FORCE_MEMORY_ACCESS) && (MEM_FORCE_MEMORY_ACCESS==1)
  132. /* __pack instructions are safer, but compiler specific, hence potentially problematic for some compilers */
  133. /* currently only defined for gcc and icc */
  134. typedef union { U16 u16; U32 u32; U64 u64; } __attribute__((packed)) unalign;
  135. MEM_STATIC U16 MEM_read16(const void* ptr) { return ((const unalign*)ptr)->u16; }
  136. MEM_STATIC U32 MEM_read32(const void* ptr) { return ((const unalign*)ptr)->u32; }
  137. MEM_STATIC U64 MEM_read64(const void* ptr) { return ((const unalign*)ptr)->u64; }
  138. MEM_STATIC void MEM_write16(void* memPtr, U16 value) { ((unalign*)memPtr)->u16 = value; }
  139. #else
  140. /* default method, safe and standard.
  141. can sometimes prove slower */
  142. MEM_STATIC U16 MEM_read16(const void* memPtr)
  143. {
  144. U16 val; memcpy(&val, memPtr, sizeof(val)); return val;
  145. }
  146. MEM_STATIC U32 MEM_read32(const void* memPtr)
  147. {
  148. U32 val; memcpy(&val, memPtr, sizeof(val)); return val;
  149. }
  150. MEM_STATIC U64 MEM_read64(const void* memPtr)
  151. {
  152. U64 val; memcpy(&val, memPtr, sizeof(val)); return val;
  153. }
  154. MEM_STATIC void MEM_write16(void* memPtr, U16 value)
  155. {
  156. memcpy(memPtr, &value, sizeof(value));
  157. }
  158. #endif /* MEM_FORCE_MEMORY_ACCESS */
  159. MEM_STATIC U16 MEM_readLE16(const void* memPtr)
  160. {
  161. if (MEM_isLittleEndian())
  162. return MEM_read16(memPtr);
  163. else
  164. {
  165. const BYTE* p = (const BYTE*)memPtr;
  166. return (U16)(p[0] + (p[1]<<8));
  167. }
  168. }
  169. MEM_STATIC void MEM_writeLE16(void* memPtr, U16 val)
  170. {
  171. if (MEM_isLittleEndian())
  172. {
  173. MEM_write16(memPtr, val);
  174. }
  175. else
  176. {
  177. BYTE* p = (BYTE*)memPtr;
  178. p[0] = (BYTE)val;
  179. p[1] = (BYTE)(val>>8);
  180. }
  181. }
  182. MEM_STATIC U32 MEM_readLE24(const void* memPtr)
  183. {
  184. return MEM_readLE16(memPtr) + (((const BYTE*)memPtr)[2] << 16);
  185. }
  186. MEM_STATIC U32 MEM_readLE32(const void* memPtr)
  187. {
  188. if (MEM_isLittleEndian())
  189. return MEM_read32(memPtr);
  190. else
  191. {
  192. const BYTE* p = (const BYTE*)memPtr;
  193. return (U32)((U32)p[0] + ((U32)p[1]<<8) + ((U32)p[2]<<16) + ((U32)p[3]<<24));
  194. }
  195. }
  196. MEM_STATIC U64 MEM_readLE64(const void* memPtr)
  197. {
  198. if (MEM_isLittleEndian())
  199. return MEM_read64(memPtr);
  200. else
  201. {
  202. const BYTE* p = (const BYTE*)memPtr;
  203. return (U64)((U64)p[0] + ((U64)p[1]<<8) + ((U64)p[2]<<16) + ((U64)p[3]<<24)
  204. + ((U64)p[4]<<32) + ((U64)p[5]<<40) + ((U64)p[6]<<48) + ((U64)p[7]<<56));
  205. }
  206. }
  207. MEM_STATIC size_t MEM_readLEST(const void* memPtr)
  208. {
  209. if (MEM_32bits())
  210. return (size_t)MEM_readLE32(memPtr);
  211. else
  212. return (size_t)MEM_readLE64(memPtr);
  213. }
  214. #if defined (__cplusplus)
  215. }
  216. #endif
  217. #endif /* MEM_H_MODULE */
  218. /* ******************************************************************
  219. bitstream
  220. Part of NewGen Entropy library
  221. header file (to include)
  222. Copyright (C) 2013-2015, Yann Collet.
  223. BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
  224. Redistribution and use in source and binary forms, with or without
  225. modification, are permitted provided that the following conditions are
  226. met:
  227. * Redistributions of source code must retain the above copyright
  228. notice, this list of conditions and the following disclaimer.
  229. * Redistributions in binary form must reproduce the above
  230. copyright notice, this list of conditions and the following disclaimer
  231. in the documentation and/or other materials provided with the
  232. distribution.
  233. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  234. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  235. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  236. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  237. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  238. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  239. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  240. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  241. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  242. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  243. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  244. You can contact the author at :
  245. - Source repository : https://github.com/Cyan4973/FiniteStateEntropy
  246. - Public forum : https://groups.google.com/forum/#!forum/lz4c
  247. ****************************************************************** */
  248. #ifndef BITSTREAM_H_MODULE
  249. #define BITSTREAM_H_MODULE
  250. #if defined (__cplusplus)
  251. extern "C" {
  252. #endif
  253. /*
  254. * This API consists of small unitary functions, which highly benefit from being inlined.
  255. * Since link-time-optimization is not available for all compilers,
  256. * these functions are defined into a .h to be included.
  257. */
  258. /**********************************************
  259. * bitStream decompression API (read backward)
  260. **********************************************/
  261. typedef struct
  262. {
  263. size_t bitContainer;
  264. unsigned bitsConsumed;
  265. const char* ptr;
  266. const char* start;
  267. } BIT_DStream_t;
  268. typedef enum { BIT_DStream_unfinished = 0,
  269. BIT_DStream_endOfBuffer = 1,
  270. BIT_DStream_completed = 2,
  271. BIT_DStream_overflow = 3 } BIT_DStream_status; /* result of BIT_reloadDStream() */
  272. /* 1,2,4,8 would be better for bitmap combinations, but slows down performance a bit ... :( */
  273. MEM_STATIC size_t BIT_initDStream(BIT_DStream_t* bitD, const void* srcBuffer, size_t srcSize);
  274. MEM_STATIC size_t BIT_readBits(BIT_DStream_t* bitD, unsigned nbBits);
  275. MEM_STATIC BIT_DStream_status BIT_reloadDStream(BIT_DStream_t* bitD);
  276. MEM_STATIC unsigned BIT_endOfDStream(const BIT_DStream_t* bitD);
  277. /******************************************
  278. * unsafe API
  279. ******************************************/
  280. MEM_STATIC size_t BIT_readBitsFast(BIT_DStream_t* bitD, unsigned nbBits);
  281. /* faster, but works only if nbBits >= 1 */
  282. /****************************************************************
  283. * Helper functions
  284. ****************************************************************/
  285. MEM_STATIC unsigned BIT_highbit32 (U32 val)
  286. {
  287. # if defined(_MSC_VER) /* Visual */
  288. unsigned long r;
  289. return _BitScanReverse(&r, val) ? (unsigned)r : 0;
  290. # elif defined(__GNUC__) && (__GNUC__ >= 3) /* Use GCC Intrinsic */
  291. return __builtin_clz (val) ^ 31;
  292. # else /* Software version */
  293. static const unsigned DeBruijnClz[32] = { 0, 9, 1, 10, 13, 21, 2, 29, 11, 14, 16, 18, 22, 25, 3, 30, 8, 12, 20, 28, 15, 17, 24, 7, 19, 27, 23, 6, 26, 5, 4, 31 };
  294. U32 v = val;
  295. unsigned r;
  296. v |= v >> 1;
  297. v |= v >> 2;
  298. v |= v >> 4;
  299. v |= v >> 8;
  300. v |= v >> 16;
  301. r = DeBruijnClz[ (U32) (v * 0x07C4ACDDU) >> 27];
  302. return r;
  303. # endif
  304. }
  305. /**********************************************************
  306. * bitStream decoding
  307. **********************************************************/
  308. /*!BIT_initDStream
  309. * Initialize a BIT_DStream_t.
  310. * @bitD : a pointer to an already allocated BIT_DStream_t structure
  311. * @srcBuffer must point at the beginning of a bitStream
  312. * @srcSize must be the exact size of the bitStream
  313. * @result : size of stream (== srcSize) or an errorCode if a problem is detected
  314. */
  315. MEM_STATIC size_t BIT_initDStream(BIT_DStream_t* bitD, const void* srcBuffer, size_t srcSize)
  316. {
  317. if (srcSize < 1) { memset(bitD, 0, sizeof(*bitD)); return ERROR(srcSize_wrong); }
  318. if (srcSize >= sizeof(size_t)) /* normal case */
  319. {
  320. U32 contain32;
  321. bitD->start = (const char*)srcBuffer;
  322. bitD->ptr = (const char*)srcBuffer + srcSize - sizeof(size_t);
  323. bitD->bitContainer = MEM_readLEST(bitD->ptr);
  324. contain32 = ((const BYTE*)srcBuffer)[srcSize-1];
  325. if (contain32 == 0) return ERROR(GENERIC); /* endMark not present */
  326. bitD->bitsConsumed = 8 - BIT_highbit32(contain32);
  327. }
  328. else
  329. {
  330. U32 contain32;
  331. bitD->start = (const char*)srcBuffer;
  332. bitD->ptr = bitD->start;
  333. bitD->bitContainer = *(const BYTE*)(bitD->start);
  334. switch(srcSize)
  335. {
  336. case 7: bitD->bitContainer += (size_t)(((const BYTE*)(bitD->start))[6]) << (sizeof(size_t)*8 - 16);
  337. /* fallthrough */
  338. case 6: bitD->bitContainer += (size_t)(((const BYTE*)(bitD->start))[5]) << (sizeof(size_t)*8 - 24);
  339. /* fallthrough */
  340. case 5: bitD->bitContainer += (size_t)(((const BYTE*)(bitD->start))[4]) << (sizeof(size_t)*8 - 32);
  341. /* fallthrough */
  342. case 4: bitD->bitContainer += (size_t)(((const BYTE*)(bitD->start))[3]) << 24;
  343. /* fallthrough */
  344. case 3: bitD->bitContainer += (size_t)(((const BYTE*)(bitD->start))[2]) << 16;
  345. /* fallthrough */
  346. case 2: bitD->bitContainer += (size_t)(((const BYTE*)(bitD->start))[1]) << 8;
  347. /* fallthrough */
  348. default:;
  349. }
  350. contain32 = ((const BYTE*)srcBuffer)[srcSize-1];
  351. if (contain32 == 0) return ERROR(GENERIC); /* endMark not present */
  352. bitD->bitsConsumed = 8 - BIT_highbit32(contain32);
  353. bitD->bitsConsumed += (U32)(sizeof(size_t) - srcSize)*8;
  354. }
  355. return srcSize;
  356. }
  357. MEM_STATIC size_t BIT_lookBits(BIT_DStream_t* bitD, U32 nbBits)
  358. {
  359. const U32 bitMask = sizeof(bitD->bitContainer)*8 - 1;
  360. return ((bitD->bitContainer << (bitD->bitsConsumed & bitMask)) >> 1) >> ((bitMask-nbBits) & bitMask);
  361. }
  362. /*! BIT_lookBitsFast :
  363. * unsafe version; only works only if nbBits >= 1 */
  364. MEM_STATIC size_t BIT_lookBitsFast(BIT_DStream_t* bitD, U32 nbBits)
  365. {
  366. const U32 bitMask = sizeof(bitD->bitContainer)*8 - 1;
  367. return (bitD->bitContainer << (bitD->bitsConsumed & bitMask)) >> (((bitMask+1)-nbBits) & bitMask);
  368. }
  369. MEM_STATIC void BIT_skipBits(BIT_DStream_t* bitD, U32 nbBits)
  370. {
  371. bitD->bitsConsumed += nbBits;
  372. }
  373. MEM_STATIC size_t BIT_readBits(BIT_DStream_t* bitD, U32 nbBits)
  374. {
  375. size_t value = BIT_lookBits(bitD, nbBits);
  376. BIT_skipBits(bitD, nbBits);
  377. return value;
  378. }
  379. /*!BIT_readBitsFast :
  380. * unsafe version; only works only if nbBits >= 1 */
  381. MEM_STATIC size_t BIT_readBitsFast(BIT_DStream_t* bitD, U32 nbBits)
  382. {
  383. size_t value = BIT_lookBitsFast(bitD, nbBits);
  384. BIT_skipBits(bitD, nbBits);
  385. return value;
  386. }
  387. MEM_STATIC BIT_DStream_status BIT_reloadDStream(BIT_DStream_t* bitD)
  388. {
  389. if (bitD->bitsConsumed > (sizeof(bitD->bitContainer)*8)) /* should never happen */
  390. return BIT_DStream_overflow;
  391. if (bitD->ptr >= bitD->start + sizeof(bitD->bitContainer))
  392. {
  393. bitD->ptr -= bitD->bitsConsumed >> 3;
  394. bitD->bitsConsumed &= 7;
  395. bitD->bitContainer = MEM_readLEST(bitD->ptr);
  396. return BIT_DStream_unfinished;
  397. }
  398. if (bitD->ptr == bitD->start)
  399. {
  400. if (bitD->bitsConsumed < sizeof(bitD->bitContainer)*8) return BIT_DStream_endOfBuffer;
  401. return BIT_DStream_completed;
  402. }
  403. {
  404. U32 nbBytes = bitD->bitsConsumed >> 3;
  405. BIT_DStream_status result = BIT_DStream_unfinished;
  406. if (bitD->ptr - nbBytes < bitD->start)
  407. {
  408. nbBytes = (U32)(bitD->ptr - bitD->start); /* ptr > start */
  409. result = BIT_DStream_endOfBuffer;
  410. }
  411. bitD->ptr -= nbBytes;
  412. bitD->bitsConsumed -= nbBytes*8;
  413. bitD->bitContainer = MEM_readLEST(bitD->ptr); /* reminder : srcSize > sizeof(bitD) */
  414. return result;
  415. }
  416. }
  417. /*! BIT_endOfDStream
  418. * @return Tells if DStream has reached its exact end
  419. */
  420. MEM_STATIC unsigned BIT_endOfDStream(const BIT_DStream_t* DStream)
  421. {
  422. return ((DStream->ptr == DStream->start) && (DStream->bitsConsumed == sizeof(DStream->bitContainer)*8));
  423. }
  424. #if defined (__cplusplus)
  425. }
  426. #endif
  427. #endif /* BITSTREAM_H_MODULE */
  428. /* ******************************************************************
  429. Error codes and messages
  430. Copyright (C) 2013-2015, Yann Collet
  431. BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
  432. Redistribution and use in source and binary forms, with or without
  433. modification, are permitted provided that the following conditions are
  434. met:
  435. * Redistributions of source code must retain the above copyright
  436. notice, this list of conditions and the following disclaimer.
  437. * Redistributions in binary form must reproduce the above
  438. copyright notice, this list of conditions and the following disclaimer
  439. in the documentation and/or other materials provided with the
  440. distribution.
  441. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  442. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  443. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  444. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  445. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  446. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  447. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  448. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  449. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  450. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  451. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  452. You can contact the author at :
  453. - Source repository : https://github.com/Cyan4973/FiniteStateEntropy
  454. - Public forum : https://groups.google.com/forum/#!forum/lz4c
  455. ****************************************************************** */
  456. #ifndef ERROR_H_MODULE
  457. #define ERROR_H_MODULE
  458. #if defined (__cplusplus)
  459. extern "C" {
  460. #endif
  461. /******************************************
  462. * Compiler-specific
  463. ******************************************/
  464. #if defined (__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */)
  465. # define ERR_STATIC static inline
  466. #elif defined(_MSC_VER)
  467. # define ERR_STATIC static __inline
  468. #elif defined(__GNUC__)
  469. # define ERR_STATIC static __attribute__((unused))
  470. #else
  471. # define ERR_STATIC static /* this version may generate warnings for unused static functions; disable the relevant warning */
  472. #endif
  473. /******************************************
  474. * Error Management
  475. ******************************************/
  476. #define PREFIX(name) ZSTD_error_##name
  477. #define ERROR(name) (size_t)-PREFIX(name)
  478. #define ERROR_LIST(ITEM) \
  479. ITEM(PREFIX(No_Error)) ITEM(PREFIX(GENERIC)) \
  480. ITEM(PREFIX(dstSize_tooSmall)) ITEM(PREFIX(srcSize_wrong)) \
  481. ITEM(PREFIX(prefix_unknown)) ITEM(PREFIX(corruption_detected)) \
  482. ITEM(PREFIX(tableLog_tooLarge)) ITEM(PREFIX(maxSymbolValue_tooLarge)) ITEM(PREFIX(maxSymbolValue_tooSmall)) \
  483. ITEM(PREFIX(maxCode))
  484. #define ERROR_GENERATE_ENUM(ENUM) ENUM,
  485. typedef enum { ERROR_LIST(ERROR_GENERATE_ENUM) } ERR_codes; /* enum is exposed, to detect & handle specific errors; compare function result to -enum value */
  486. #define ERROR_CONVERTTOSTRING(STRING) #STRING,
  487. #define ERROR_GENERATE_STRING(EXPR) ERROR_CONVERTTOSTRING(EXPR)
  488. static const char* ERR_strings[] = { ERROR_LIST(ERROR_GENERATE_STRING) };
  489. ERR_STATIC unsigned ERR_isError(size_t code) { return (code > ERROR(maxCode)); }
  490. ERR_STATIC const char* ERR_getErrorName(size_t code)
  491. {
  492. static const char* codeError = "Unspecified error code";
  493. if (ERR_isError(code)) return ERR_strings[-(int)(code)];
  494. return codeError;
  495. }
  496. #if defined (__cplusplus)
  497. }
  498. #endif
  499. #endif /* ERROR_H_MODULE */
  500. /*
  501. Constructor and Destructor of type FSE_CTable
  502. Note that its size depends on 'tableLog' and 'maxSymbolValue' */
  503. typedef unsigned FSE_CTable; /* don't allocate that. It's just a way to be more restrictive than void* */
  504. typedef unsigned FSE_DTable; /* don't allocate that. It's just a way to be more restrictive than void* */
  505. /* ******************************************************************
  506. FSE : Finite State Entropy coder
  507. header file for static linking (only)
  508. Copyright (C) 2013-2015, Yann Collet
  509. BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
  510. Redistribution and use in source and binary forms, with or without
  511. modification, are permitted provided that the following conditions are
  512. met:
  513. * Redistributions of source code must retain the above copyright
  514. notice, this list of conditions and the following disclaimer.
  515. * Redistributions in binary form must reproduce the above
  516. copyright notice, this list of conditions and the following disclaimer
  517. in the documentation and/or other materials provided with the
  518. distribution.
  519. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  520. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  521. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  522. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  523. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  524. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  525. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  526. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  527. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  528. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  529. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  530. You can contact the author at :
  531. - Source repository : https://github.com/Cyan4973/FiniteStateEntropy
  532. - Public forum : https://groups.google.com/forum/#!forum/lz4c
  533. ****************************************************************** */
  534. #if defined (__cplusplus)
  535. extern "C" {
  536. #endif
  537. /******************************************
  538. * Static allocation
  539. ******************************************/
  540. /* FSE buffer bounds */
  541. #define FSE_NCOUNTBOUND 512
  542. #define FSE_BLOCKBOUND(size) (size + (size>>7))
  543. #define FSE_COMPRESSBOUND(size) (FSE_NCOUNTBOUND + FSE_BLOCKBOUND(size)) /* Macro version, useful for static allocation */
  544. /* You can statically allocate FSE CTable/DTable as a table of unsigned using below macro */
  545. #define FSE_CTABLE_SIZE_U32(maxTableLog, maxSymbolValue) (1 + (1<<(maxTableLog-1)) + ((maxSymbolValue+1)*2))
  546. #define FSE_DTABLE_SIZE_U32(maxTableLog) (1 + (1<<maxTableLog))
  547. /******************************************
  548. * FSE advanced API
  549. ******************************************/
  550. static size_t FSE_buildDTable_raw (FSE_DTable* dt, unsigned nbBits);
  551. /* build a fake FSE_DTable, designed to read an uncompressed bitstream where each symbol uses nbBits */
  552. static size_t FSE_buildDTable_rle (FSE_DTable* dt, unsigned char symbolValue);
  553. /* build a fake FSE_DTable, designed to always generate the same symbolValue */
  554. /******************************************
  555. * FSE symbol decompression API
  556. ******************************************/
  557. typedef struct
  558. {
  559. size_t state;
  560. const void* table; /* precise table may vary, depending on U16 */
  561. } FSE_DState_t;
  562. static void FSE_initDState(FSE_DState_t* DStatePtr, BIT_DStream_t* bitD, const FSE_DTable* dt);
  563. static unsigned char FSE_decodeSymbol(FSE_DState_t* DStatePtr, BIT_DStream_t* bitD);
  564. static unsigned FSE_endOfDState(const FSE_DState_t* DStatePtr);
  565. /******************************************
  566. * FSE unsafe API
  567. ******************************************/
  568. static unsigned char FSE_decodeSymbolFast(FSE_DState_t* DStatePtr, BIT_DStream_t* bitD);
  569. /* faster, but works only if nbBits is always >= 1 (otherwise, result will be corrupted) */
  570. /******************************************
  571. * Implementation of inline functions
  572. ******************************************/
  573. /* decompression */
  574. typedef struct {
  575. U16 tableLog;
  576. U16 fastMode;
  577. } FSE_DTableHeader; /* sizeof U32 */
  578. typedef struct
  579. {
  580. unsigned short newState;
  581. unsigned char symbol;
  582. unsigned char nbBits;
  583. } FSE_decode_t; /* size == U32 */
  584. MEM_STATIC void FSE_initDState(FSE_DState_t* DStatePtr, BIT_DStream_t* bitD, const FSE_DTable* dt)
  585. {
  586. FSE_DTableHeader DTableH;
  587. memcpy(&DTableH, dt, sizeof(DTableH));
  588. DStatePtr->state = BIT_readBits(bitD, DTableH.tableLog);
  589. BIT_reloadDStream(bitD);
  590. DStatePtr->table = dt + 1;
  591. }
  592. MEM_STATIC BYTE FSE_decodeSymbol(FSE_DState_t* DStatePtr, BIT_DStream_t* bitD)
  593. {
  594. const FSE_decode_t DInfo = ((const FSE_decode_t*)(DStatePtr->table))[DStatePtr->state];
  595. const U32 nbBits = DInfo.nbBits;
  596. BYTE symbol = DInfo.symbol;
  597. size_t lowBits = BIT_readBits(bitD, nbBits);
  598. DStatePtr->state = DInfo.newState + lowBits;
  599. return symbol;
  600. }
  601. MEM_STATIC BYTE FSE_decodeSymbolFast(FSE_DState_t* DStatePtr, BIT_DStream_t* bitD)
  602. {
  603. const FSE_decode_t DInfo = ((const FSE_decode_t*)(DStatePtr->table))[DStatePtr->state];
  604. const U32 nbBits = DInfo.nbBits;
  605. BYTE symbol = DInfo.symbol;
  606. size_t lowBits = BIT_readBitsFast(bitD, nbBits);
  607. DStatePtr->state = DInfo.newState + lowBits;
  608. return symbol;
  609. }
  610. MEM_STATIC unsigned FSE_endOfDState(const FSE_DState_t* DStatePtr)
  611. {
  612. return DStatePtr->state == 0;
  613. }
  614. #if defined (__cplusplus)
  615. }
  616. #endif
  617. /* ******************************************************************
  618. Huff0 : Huffman coder, part of New Generation Entropy library
  619. header file for static linking (only)
  620. Copyright (C) 2013-2015, Yann Collet
  621. BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
  622. Redistribution and use in source and binary forms, with or without
  623. modification, are permitted provided that the following conditions are
  624. met:
  625. * Redistributions of source code must retain the above copyright
  626. notice, this list of conditions and the following disclaimer.
  627. * Redistributions in binary form must reproduce the above
  628. copyright notice, this list of conditions and the following disclaimer
  629. in the documentation and/or other materials provided with the
  630. distribution.
  631. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  632. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  633. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  634. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  635. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  636. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  637. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  638. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  639. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  640. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  641. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  642. You can contact the author at :
  643. - Source repository : https://github.com/Cyan4973/FiniteStateEntropy
  644. - Public forum : https://groups.google.com/forum/#!forum/lz4c
  645. ****************************************************************** */
  646. #if defined (__cplusplus)
  647. extern "C" {
  648. #endif
  649. /******************************************
  650. * Static allocation macros
  651. ******************************************/
  652. /* Huff0 buffer bounds */
  653. #define HUF_CTABLEBOUND 129
  654. #define HUF_BLOCKBOUND(size) (size + (size>>8) + 8) /* only true if incompressible pre-filtered with fast heuristic */
  655. #define HUF_COMPRESSBOUND(size) (HUF_CTABLEBOUND + HUF_BLOCKBOUND(size)) /* Macro version, useful for static allocation */
  656. /* static allocation of Huff0's DTable */
  657. #define HUF_DTABLE_SIZE(maxTableLog) (1 + (1<<maxTableLog)) /* nb Cells; use unsigned short for X2, unsigned int for X4 */
  658. #define HUF_CREATE_STATIC_DTABLEX2(DTable, maxTableLog) \
  659. unsigned short DTable[HUF_DTABLE_SIZE(maxTableLog)] = { maxTableLog }
  660. #define HUF_CREATE_STATIC_DTABLEX4(DTable, maxTableLog) \
  661. unsigned int DTable[HUF_DTABLE_SIZE(maxTableLog)] = { maxTableLog }
  662. #define HUF_CREATE_STATIC_DTABLEX6(DTable, maxTableLog) \
  663. unsigned int DTable[HUF_DTABLE_SIZE(maxTableLog) * 3 / 2] = { maxTableLog }
  664. /******************************************
  665. * Advanced functions
  666. ******************************************/
  667. static size_t HUF_decompress4X2 (void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize); /* single-symbol decoder */
  668. static size_t HUF_decompress4X4 (void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize); /* double-symbols decoder */
  669. #if defined (__cplusplus)
  670. }
  671. #endif
  672. /*
  673. zstd - standard compression library
  674. Header File
  675. Copyright (C) 2014-2015, Yann Collet.
  676. BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
  677. Redistribution and use in source and binary forms, with or without
  678. modification, are permitted provided that the following conditions are
  679. met:
  680. * Redistributions of source code must retain the above copyright
  681. notice, this list of conditions and the following disclaimer.
  682. * Redistributions in binary form must reproduce the above
  683. copyright notice, this list of conditions and the following disclaimer
  684. in the documentation and/or other materials provided with the
  685. distribution.
  686. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  687. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  688. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  689. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  690. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  691. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  692. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  693. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  694. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  695. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  696. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  697. You can contact the author at :
  698. - zstd source repository : https://github.com/Cyan4973/zstd
  699. - ztsd public forum : https://groups.google.com/forum/#!forum/lz4c
  700. */
  701. #if defined (__cplusplus)
  702. extern "C" {
  703. #endif
  704. /* *************************************
  705. * Includes
  706. ***************************************/
  707. #include <stddef.h> /* size_t */
  708. /* *************************************
  709. * Version
  710. ***************************************/
  711. #define ZSTD_VERSION_MAJOR 0 /* for breaking interface changes */
  712. #define ZSTD_VERSION_MINOR 2 /* for new (non-breaking) interface capabilities */
  713. #define ZSTD_VERSION_RELEASE 2 /* for tweaks, bug-fixes, or development */
  714. #define ZSTD_VERSION_NUMBER (ZSTD_VERSION_MAJOR *100*100 + ZSTD_VERSION_MINOR *100 + ZSTD_VERSION_RELEASE)
  715. /* *************************************
  716. * Advanced functions
  717. ***************************************/
  718. typedef struct ZSTD_CCtx_s ZSTD_CCtx; /* incomplete type */
  719. #if defined (__cplusplus)
  720. }
  721. #endif
  722. /*
  723. zstd - standard compression library
  724. Header File for static linking only
  725. Copyright (C) 2014-2015, Yann Collet.
  726. BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
  727. Redistribution and use in source and binary forms, with or without
  728. modification, are permitted provided that the following conditions are
  729. met:
  730. * Redistributions of source code must retain the above copyright
  731. notice, this list of conditions and the following disclaimer.
  732. * Redistributions in binary form must reproduce the above
  733. copyright notice, this list of conditions and the following disclaimer
  734. in the documentation and/or other materials provided with the
  735. distribution.
  736. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  737. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  738. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  739. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  740. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  741. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  742. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  743. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  744. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  745. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  746. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  747. You can contact the author at :
  748. - zstd source repository : https://github.com/Cyan4973/zstd
  749. - ztsd public forum : https://groups.google.com/forum/#!forum/lz4c
  750. */
  751. /* The objects defined into this file should be considered experimental.
  752. * They are not labelled stable, as their prototype may change in the future.
  753. * You can use them for tests, provide feedback, or if you can endure risk of future changes.
  754. */
  755. #if defined (__cplusplus)
  756. extern "C" {
  757. #endif
  758. /* *************************************
  759. * Streaming functions
  760. ***************************************/
  761. typedef struct ZSTD_DCtx_s ZSTD_DCtx;
  762. /*
  763. Use above functions alternatively.
  764. ZSTD_nextSrcSizeToDecompress() tells how much bytes to provide as 'srcSize' to ZSTD_decompressContinue().
  765. ZSTD_decompressContinue() will use previous data blocks to improve compression if they are located prior to current block.
  766. Result is the number of bytes regenerated within 'dst'.
  767. It can be zero, which is not an error; it just means ZSTD_decompressContinue() has decoded some header.
  768. */
  769. /* *************************************
  770. * Prefix - version detection
  771. ***************************************/
  772. #define ZSTD_magicNumber 0xFD2FB523 /* v0.3 */
  773. #if defined (__cplusplus)
  774. }
  775. #endif
  776. /* ******************************************************************
  777. FSE : Finite State Entropy coder
  778. Copyright (C) 2013-2015, Yann Collet.
  779. BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
  780. Redistribution and use in source and binary forms, with or without
  781. modification, are permitted provided that the following conditions are
  782. met:
  783. * Redistributions of source code must retain the above copyright
  784. notice, this list of conditions and the following disclaimer.
  785. * Redistributions in binary form must reproduce the above
  786. copyright notice, this list of conditions and the following disclaimer
  787. in the documentation and/or other materials provided with the
  788. distribution.
  789. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  790. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  791. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  792. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  793. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  794. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  795. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  796. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  797. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  798. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  799. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  800. You can contact the author at :
  801. - FSE source repository : https://github.com/Cyan4973/FiniteStateEntropy
  802. - Public forum : https://groups.google.com/forum/#!forum/lz4c
  803. ****************************************************************** */
  804. #ifndef FSE_COMMONDEFS_ONLY
  805. /****************************************************************
  806. * Tuning parameters
  807. ****************************************************************/
  808. /* MEMORY_USAGE :
  809. * Memory usage formula : N->2^N Bytes (examples : 10 -> 1KB; 12 -> 4KB ; 16 -> 64KB; 20 -> 1MB; etc.)
  810. * Increasing memory usage improves compression ratio
  811. * Reduced memory usage can improve speed, due to cache effect
  812. * Recommended max value is 14, for 16KB, which nicely fits into Intel x86 L1 cache */
  813. #define FSE_MAX_MEMORY_USAGE 14
  814. #define FSE_DEFAULT_MEMORY_USAGE 13
  815. /* FSE_MAX_SYMBOL_VALUE :
  816. * Maximum symbol value authorized.
  817. * Required for proper stack allocation */
  818. #define FSE_MAX_SYMBOL_VALUE 255
  819. /****************************************************************
  820. * template functions type & suffix
  821. ****************************************************************/
  822. #define FSE_FUNCTION_TYPE BYTE
  823. #define FSE_FUNCTION_EXTENSION
  824. /****************************************************************
  825. * Byte symbol type
  826. ****************************************************************/
  827. #endif /* !FSE_COMMONDEFS_ONLY */
  828. /****************************************************************
  829. * Compiler specifics
  830. ****************************************************************/
  831. #ifdef _MSC_VER /* Visual Studio */
  832. # define FORCE_INLINE static __forceinline
  833. # include <intrin.h> /* For Visual 2005 */
  834. # pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */
  835. # pragma warning(disable : 4214) /* disable: C4214: non-int bitfields */
  836. #else
  837. # if defined (__cplusplus) || defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* C99 */
  838. # ifdef __GNUC__
  839. # define FORCE_INLINE static inline __attribute__((always_inline))
  840. # else
  841. # define FORCE_INLINE static inline
  842. # endif
  843. # else
  844. # define FORCE_INLINE static
  845. # endif /* __STDC_VERSION__ */
  846. #endif
  847. /****************************************************************
  848. * Includes
  849. ****************************************************************/
  850. #include <stdlib.h> /* malloc, free, qsort */
  851. #include <string.h> /* memcpy, memset */
  852. #include <stdio.h> /* printf (debug) */
  853. /****************************************************************
  854. * Constants
  855. *****************************************************************/
  856. #define FSE_MAX_TABLELOG (FSE_MAX_MEMORY_USAGE-2)
  857. #define FSE_MAX_TABLESIZE (1U<<FSE_MAX_TABLELOG)
  858. #define FSE_MAXTABLESIZE_MASK (FSE_MAX_TABLESIZE-1)
  859. #define FSE_DEFAULT_TABLELOG (FSE_DEFAULT_MEMORY_USAGE-2)
  860. #define FSE_MIN_TABLELOG 5
  861. #define FSE_TABLELOG_ABSOLUTE_MAX 15
  862. #if FSE_MAX_TABLELOG > FSE_TABLELOG_ABSOLUTE_MAX
  863. #error "FSE_MAX_TABLELOG > FSE_TABLELOG_ABSOLUTE_MAX is not supported"
  864. #endif
  865. /****************************************************************
  866. * Error Management
  867. ****************************************************************/
  868. #define FSE_STATIC_ASSERT(c) { enum { FSE_static_assert = 1/(int)(!!(c)) }; } /* use only *after* variable declarations */
  869. /****************************************************************
  870. * Complex types
  871. ****************************************************************/
  872. typedef U32 DTable_max_t[FSE_DTABLE_SIZE_U32(FSE_MAX_TABLELOG)];
  873. /****************************************************************
  874. * Templates
  875. ****************************************************************/
  876. /*
  877. designed to be included
  878. for type-specific functions (template emulation in C)
  879. Objective is to write these functions only once, for improved maintenance
  880. */
  881. /* safety checks */
  882. #ifndef FSE_FUNCTION_EXTENSION
  883. # error "FSE_FUNCTION_EXTENSION must be defined"
  884. #endif
  885. #ifndef FSE_FUNCTION_TYPE
  886. # error "FSE_FUNCTION_TYPE must be defined"
  887. #endif
  888. /* Function names */
  889. #define FSE_CAT(X,Y) X##Y
  890. #define FSE_FUNCTION_NAME(X,Y) FSE_CAT(X,Y)
  891. #define FSE_TYPE_NAME(X,Y) FSE_CAT(X,Y)
  892. /* Function templates */
  893. #define FSE_DECODE_TYPE FSE_decode_t
  894. static U32 FSE_tableStep(U32 tableSize) { return (tableSize>>1) + (tableSize>>3) + 3; }
  895. static size_t FSE_buildDTable
  896. (FSE_DTable* dt, const short* normalizedCounter, unsigned maxSymbolValue, unsigned tableLog)
  897. {
  898. void* ptr = dt+1;
  899. FSE_DTableHeader DTableH;
  900. FSE_DECODE_TYPE* const tableDecode = (FSE_DECODE_TYPE*)ptr;
  901. const U32 tableSize = 1 << tableLog;
  902. const U32 tableMask = tableSize-1;
  903. const U32 step = FSE_tableStep(tableSize);
  904. U16 symbolNext[FSE_MAX_SYMBOL_VALUE+1];
  905. U32 position = 0;
  906. U32 highThreshold = tableSize-1;
  907. const S16 largeLimit= (S16)(1 << (tableLog-1));
  908. U32 noLarge = 1;
  909. U32 s;
  910. /* Sanity Checks */
  911. if (maxSymbolValue > FSE_MAX_SYMBOL_VALUE) return ERROR(maxSymbolValue_tooLarge);
  912. if (tableLog > FSE_MAX_TABLELOG) return ERROR(tableLog_tooLarge);
  913. /* Init, lay down lowprob symbols */
  914. DTableH.tableLog = (U16)tableLog;
  915. for (s=0; s<=maxSymbolValue; s++)
  916. {
  917. if (normalizedCounter[s]==-1)
  918. {
  919. tableDecode[highThreshold--].symbol = (FSE_FUNCTION_TYPE)s;
  920. symbolNext[s] = 1;
  921. }
  922. else
  923. {
  924. if (normalizedCounter[s] >= largeLimit) noLarge=0;
  925. symbolNext[s] = normalizedCounter[s];
  926. }
  927. }
  928. /* Spread symbols */
  929. for (s=0; s<=maxSymbolValue; s++)
  930. {
  931. int i;
  932. for (i=0; i<normalizedCounter[s]; i++)
  933. {
  934. tableDecode[position].symbol = (FSE_FUNCTION_TYPE)s;
  935. position = (position + step) & tableMask;
  936. while (position > highThreshold) position = (position + step) & tableMask; /* lowprob area */
  937. }
  938. }
  939. if (position!=0) return ERROR(GENERIC); /* position must reach all cells once, otherwise normalizedCounter is incorrect */
  940. /* Build Decoding table */
  941. {
  942. U32 i;
  943. for (i=0; i<tableSize; i++)
  944. {
  945. FSE_FUNCTION_TYPE symbol = (FSE_FUNCTION_TYPE)(tableDecode[i].symbol);
  946. U16 nextState = symbolNext[symbol]++;
  947. tableDecode[i].nbBits = (BYTE) (tableLog - BIT_highbit32 ((U32)nextState) );
  948. tableDecode[i].newState = (U16) ( (nextState << tableDecode[i].nbBits) - tableSize);
  949. }
  950. }
  951. DTableH.fastMode = (U16)noLarge;
  952. memcpy(dt, &DTableH, sizeof(DTableH));
  953. return 0;
  954. }
  955. #ifndef FSE_COMMONDEFS_ONLY
  956. /******************************************
  957. * FSE helper functions
  958. ******************************************/
  959. static unsigned FSE_isError(size_t code) { return ERR_isError(code); }
  960. /****************************************************************
  961. * FSE NCount encoding-decoding
  962. ****************************************************************/
  963. static short FSE_abs(short a)
  964. {
  965. return a<0 ? -a : a;
  966. }
  967. static size_t FSE_readNCount (short* normalizedCounter, unsigned* maxSVPtr, unsigned* tableLogPtr,
  968. const void* headerBuffer, size_t hbSize)
  969. {
  970. const BYTE* const istart = (const BYTE*) headerBuffer;
  971. const BYTE* const iend = istart + hbSize;
  972. const BYTE* ip = istart;
  973. int nbBits;
  974. int remaining;
  975. int threshold;
  976. U32 bitStream;
  977. int bitCount;
  978. unsigned charnum = 0;
  979. int previous0 = 0;
  980. if (hbSize < 4) return ERROR(srcSize_wrong);
  981. bitStream = MEM_readLE32(ip);
  982. nbBits = (bitStream & 0xF) + FSE_MIN_TABLELOG; /* extract tableLog */
  983. if (nbBits > FSE_TABLELOG_ABSOLUTE_MAX) return ERROR(tableLog_tooLarge);
  984. bitStream >>= 4;
  985. bitCount = 4;
  986. *tableLogPtr = nbBits;
  987. remaining = (1<<nbBits)+1;
  988. threshold = 1<<nbBits;
  989. nbBits++;
  990. while ((remaining>1) && (charnum<=*maxSVPtr))
  991. {
  992. if (previous0)
  993. {
  994. unsigned n0 = charnum;
  995. while ((bitStream & 0xFFFF) == 0xFFFF)
  996. {
  997. n0+=24;
  998. if (ip < iend-5)
  999. {
  1000. ip+=2;
  1001. bitStream = MEM_readLE32(ip) >> bitCount;
  1002. }
  1003. else
  1004. {
  1005. bitStream >>= 16;
  1006. bitCount+=16;
  1007. }
  1008. }
  1009. while ((bitStream & 3) == 3)
  1010. {
  1011. n0+=3;
  1012. bitStream>>=2;
  1013. bitCount+=2;
  1014. }
  1015. n0 += bitStream & 3;
  1016. bitCount += 2;
  1017. if (n0 > *maxSVPtr) return ERROR(maxSymbolValue_tooSmall);
  1018. while (charnum < n0) normalizedCounter[charnum++] = 0;
  1019. if ((ip <= iend-7) || (ip + (bitCount>>3) <= iend-4))
  1020. {
  1021. ip += bitCount>>3;
  1022. bitCount &= 7;
  1023. bitStream = MEM_readLE32(ip) >> bitCount;
  1024. }
  1025. else
  1026. bitStream >>= 2;
  1027. }
  1028. {
  1029. const short max = (short)((2*threshold-1)-remaining);
  1030. short count;
  1031. if ((bitStream & (threshold-1)) < (U32)max)
  1032. {
  1033. count = (short)(bitStream & (threshold-1));
  1034. bitCount += nbBits-1;
  1035. }
  1036. else
  1037. {
  1038. count = (short)(bitStream & (2*threshold-1));
  1039. if (count >= threshold) count -= max;
  1040. bitCount += nbBits;
  1041. }
  1042. count--; /* extra accuracy */
  1043. remaining -= FSE_abs(count);
  1044. normalizedCounter[charnum++] = count;
  1045. previous0 = !count;
  1046. while (remaining < threshold)
  1047. {
  1048. nbBits--;
  1049. threshold >>= 1;
  1050. }
  1051. {
  1052. if ((ip <= iend-7) || (ip + (bitCount>>3) <= iend-4))
  1053. {
  1054. ip += bitCount>>3;
  1055. bitCount &= 7;
  1056. }
  1057. else
  1058. {
  1059. bitCount -= (int)(8 * (iend - 4 - ip));
  1060. ip = iend - 4;
  1061. }
  1062. bitStream = MEM_readLE32(ip) >> (bitCount & 31);
  1063. }
  1064. }
  1065. }
  1066. if (remaining != 1) return ERROR(GENERIC);
  1067. *maxSVPtr = charnum-1;
  1068. ip += (bitCount+7)>>3;
  1069. if ((size_t)(ip-istart) > hbSize) return ERROR(srcSize_wrong);
  1070. return ip-istart;
  1071. }
  1072. /*********************************************************
  1073. * Decompression (Byte symbols)
  1074. *********************************************************/
  1075. static size_t FSE_buildDTable_rle (FSE_DTable* dt, BYTE symbolValue)
  1076. {
  1077. void* ptr = dt;
  1078. FSE_DTableHeader* const DTableH = (FSE_DTableHeader*)ptr;
  1079. FSE_decode_t* const cell = (FSE_decode_t*)(ptr) + 1;
  1080. DTableH->tableLog = 0;
  1081. DTableH->fastMode = 0;
  1082. cell->newState = 0;
  1083. cell->symbol = symbolValue;
  1084. cell->nbBits = 0;
  1085. return 0;
  1086. }
  1087. static size_t FSE_buildDTable_raw (FSE_DTable* dt, unsigned nbBits)
  1088. {
  1089. void* ptr = dt;
  1090. FSE_DTableHeader* const DTableH = (FSE_DTableHeader*)ptr;
  1091. FSE_decode_t* const dinfo = (FSE_decode_t*)(ptr) + 1;
  1092. const unsigned tableSize = 1 << nbBits;
  1093. const unsigned tableMask = tableSize - 1;
  1094. const unsigned maxSymbolValue = tableMask;
  1095. unsigned s;
  1096. /* Sanity checks */
  1097. if (nbBits < 1) return ERROR(GENERIC); /* min size */
  1098. /* Build Decoding Table */
  1099. DTableH->tableLog = (U16)nbBits;
  1100. DTableH->fastMode = 1;
  1101. for (s=0; s<=maxSymbolValue; s++)
  1102. {
  1103. dinfo[s].newState = 0;
  1104. dinfo[s].symbol = (BYTE)s;
  1105. dinfo[s].nbBits = (BYTE)nbBits;
  1106. }
  1107. return 0;
  1108. }
  1109. FORCE_INLINE size_t FSE_decompress_usingDTable_generic(
  1110. void* dst, size_t maxDstSize,
  1111. const void* cSrc, size_t cSrcSize,
  1112. const FSE_DTable* dt, const unsigned fast)
  1113. {
  1114. BYTE* const ostart = (BYTE*) dst;
  1115. BYTE* op = ostart;
  1116. BYTE* const omax = op + maxDstSize;
  1117. BYTE* const olimit = omax-3;
  1118. BIT_DStream_t bitD;
  1119. FSE_DState_t state1;
  1120. FSE_DState_t state2;
  1121. size_t errorCode;
  1122. /* Init */
  1123. errorCode = BIT_initDStream(&bitD, cSrc, cSrcSize); /* replaced last arg by maxCompressed Size */
  1124. if (FSE_isError(errorCode)) return errorCode;
  1125. FSE_initDState(&state1, &bitD, dt);
  1126. FSE_initDState(&state2, &bitD, dt);
  1127. #define FSE_GETSYMBOL(statePtr) fast ? FSE_decodeSymbolFast(statePtr, &bitD) : FSE_decodeSymbol(statePtr, &bitD)
  1128. /* 4 symbols per loop */
  1129. for ( ; (BIT_reloadDStream(&bitD)==BIT_DStream_unfinished) && (op<olimit) ; op+=4)
  1130. {
  1131. op[0] = FSE_GETSYMBOL(&state1);
  1132. if (FSE_MAX_TABLELOG*2+7 > sizeof(bitD.bitContainer)*8) /* This test must be static */
  1133. BIT_reloadDStream(&bitD);
  1134. op[1] = FSE_GETSYMBOL(&state2);
  1135. if (FSE_MAX_TABLELOG*4+7 > sizeof(bitD.bitContainer)*8) /* This test must be static */
  1136. { if (BIT_reloadDStream(&bitD) > BIT_DStream_unfinished) { op+=2; break; } }
  1137. op[2] = FSE_GETSYMBOL(&state1);
  1138. if (FSE_MAX_TABLELOG*2+7 > sizeof(bitD.bitContainer)*8) /* This test must be static */
  1139. BIT_reloadDStream(&bitD);
  1140. op[3] = FSE_GETSYMBOL(&state2);
  1141. }
  1142. /* tail */
  1143. /* note : BIT_reloadDStream(&bitD) >= FSE_DStream_partiallyFilled; Ends at exactly BIT_DStream_completed */
  1144. while (1)
  1145. {
  1146. if ( (BIT_reloadDStream(&bitD)>BIT_DStream_completed) || (op==omax) || (BIT_endOfDStream(&bitD) && (fast || FSE_endOfDState(&state1))) )
  1147. break;
  1148. *op++ = FSE_GETSYMBOL(&state1);
  1149. if ( (BIT_reloadDStream(&bitD)>BIT_DStream_completed) || (op==omax) || (BIT_endOfDStream(&bitD) && (fast || FSE_endOfDState(&state2))) )
  1150. break;
  1151. *op++ = FSE_GETSYMBOL(&state2);
  1152. }
  1153. /* end ? */
  1154. if (BIT_endOfDStream(&bitD) && FSE_endOfDState(&state1) && FSE_endOfDState(&state2))
  1155. return op-ostart;
  1156. if (op==omax) return ERROR(dstSize_tooSmall); /* dst buffer is full, but cSrc unfinished */
  1157. return ERROR(corruption_detected);
  1158. }
  1159. static size_t FSE_decompress_usingDTable(void* dst, size_t originalSize,
  1160. const void* cSrc, size_t cSrcSize,
  1161. const FSE_DTable* dt)
  1162. {
  1163. FSE_DTableHeader DTableH;
  1164. memcpy(&DTableH, dt, sizeof(DTableH));
  1165. /* select fast mode (static) */
  1166. if (DTableH.fastMode) return FSE_decompress_usingDTable_generic(dst, originalSize, cSrc, cSrcSize, dt, 1);
  1167. return FSE_decompress_usingDTable_generic(dst, originalSize, cSrc, cSrcSize, dt, 0);
  1168. }
  1169. static size_t FSE_decompress(void* dst, size_t maxDstSize, const void* cSrc, size_t cSrcSize)
  1170. {
  1171. const BYTE* const istart = (const BYTE*)cSrc;
  1172. const BYTE* ip = istart;
  1173. short counting[FSE_MAX_SYMBOL_VALUE+1];
  1174. DTable_max_t dt; /* Static analyzer seems unable to understand this table will be properly initialized later */
  1175. unsigned tableLog;
  1176. unsigned maxSymbolValue = FSE_MAX_SYMBOL_VALUE;
  1177. size_t errorCode;
  1178. if (cSrcSize<2) return ERROR(srcSize_wrong); /* too small input size */
  1179. /* normal FSE decoding mode */
  1180. errorCode = FSE_readNCount (counting, &maxSymbolValue, &tableLog, istart, cSrcSize);
  1181. if (FSE_isError(errorCode)) return errorCode;
  1182. if (errorCode >= cSrcSize) return ERROR(srcSize_wrong); /* too small input size */
  1183. ip += errorCode;
  1184. cSrcSize -= errorCode;
  1185. errorCode = FSE_buildDTable (dt, counting, maxSymbolValue, tableLog);
  1186. if (FSE_isError(errorCode)) return errorCode;
  1187. /* always return, even if it is an error code */
  1188. return FSE_decompress_usingDTable (dst, maxDstSize, ip, cSrcSize, dt);
  1189. }
  1190. #endif /* FSE_COMMONDEFS_ONLY */
  1191. /* ******************************************************************
  1192. Huff0 : Huffman coder, part of New Generation Entropy library
  1193. Copyright (C) 2013-2015, Yann Collet.
  1194. BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
  1195. Redistribution and use in source and binary forms, with or without
  1196. modification, are permitted provided that the following conditions are
  1197. met:
  1198. * Redistributions of source code must retain the above copyright
  1199. notice, this list of conditions and the following disclaimer.
  1200. * Redistributions in binary form must reproduce the above
  1201. copyright notice, this list of conditions and the following disclaimer
  1202. in the documentation and/or other materials provided with the
  1203. distribution.
  1204. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  1205. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  1206. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  1207. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  1208. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  1209. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  1210. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  1211. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  1212. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  1213. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  1214. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  1215. You can contact the author at :
  1216. - FSE+Huff0 source repository : https://github.com/Cyan4973/FiniteStateEntropy
  1217. - Public forum : https://groups.google.com/forum/#!forum/lz4c
  1218. ****************************************************************** */
  1219. /****************************************************************
  1220. * Compiler specifics
  1221. ****************************************************************/
  1222. #if defined (__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */)
  1223. /* inline is defined */
  1224. #elif defined(_MSC_VER)
  1225. # pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */
  1226. # define inline __inline
  1227. #else
  1228. # define inline /* disable inline */
  1229. #endif
  1230. /****************************************************************
  1231. * Includes
  1232. ****************************************************************/
  1233. #include <stdlib.h> /* malloc, free, qsort */
  1234. #include <string.h> /* memcpy, memset */
  1235. #include <stdio.h> /* printf (debug) */
  1236. /****************************************************************
  1237. * Error Management
  1238. ****************************************************************/
  1239. #define HUF_STATIC_ASSERT(c) { enum { HUF_static_assert = 1/(int)(!!(c)) }; } /* use only *after* variable declarations */
  1240. /******************************************
  1241. * Helper functions
  1242. ******************************************/
  1243. static unsigned HUF_isError(size_t code) { return ERR_isError(code); }
  1244. #define HUF_ABSOLUTEMAX_TABLELOG 16 /* absolute limit of HUF_MAX_TABLELOG. Beyond that value, code does not work */
  1245. #define HUF_MAX_TABLELOG 12 /* max configured tableLog (for static allocation); can be modified up to HUF_ABSOLUTEMAX_TABLELOG */
  1246. #define HUF_DEFAULT_TABLELOG HUF_MAX_TABLELOG /* tableLog by default, when not specified */
  1247. #define HUF_MAX_SYMBOL_VALUE 255
  1248. #if (HUF_MAX_TABLELOG > HUF_ABSOLUTEMAX_TABLELOG)
  1249. # error "HUF_MAX_TABLELOG is too large !"
  1250. #endif
  1251. /*********************************************************
  1252. * Huff0 : Huffman block decompression
  1253. *********************************************************/
  1254. typedef struct { BYTE byte; BYTE nbBits; } HUF_DEltX2; /* single-symbol decoding */
  1255. typedef struct { U16 sequence; BYTE nbBits; BYTE length; } HUF_DEltX4; /* double-symbols decoding */
  1256. typedef struct { BYTE symbol; BYTE weight; } sortedSymbol_t;
  1257. /*! HUF_readStats
  1258. Read compact Huffman tree, saved by HUF_writeCTable
  1259. @huffWeight : destination buffer
  1260. @return : size read from `src`
  1261. */
  1262. static size_t HUF_readStats(BYTE* huffWeight, size_t hwSize, U32* rankStats,
  1263. U32* nbSymbolsPtr, U32* tableLogPtr,
  1264. const void* src, size_t srcSize)
  1265. {
  1266. U32 weightTotal;
  1267. U32 tableLog;
  1268. const BYTE* ip = (const BYTE*) src;
  1269. size_t iSize;
  1270. size_t oSize;
  1271. U32 n;
  1272. if (!srcSize) return ERROR(srcSize_wrong);
  1273. iSize = ip[0];
  1274. //memset(huffWeight, 0, hwSize); /* is not necessary, even though some analyzer complain ... */
  1275. if (iSize >= 128) /* special header */
  1276. {
  1277. if (iSize >= (242)) /* RLE */
  1278. {
  1279. static int l[14] = { 1, 2, 3, 4, 7, 8, 15, 16, 31, 32, 63, 64, 127, 128 };
  1280. oSize = l[iSize-242];
  1281. memset(huffWeight, 1, hwSize);
  1282. iSize = 0;
  1283. }
  1284. else /* Incompressible */
  1285. {
  1286. oSize = iSize - 127;
  1287. iSize = ((oSize+1)/2);
  1288. if (iSize+1 > srcSize) return ERROR(srcSize_wrong);
  1289. if (oSize >= hwSize) return ERROR(corruption_detected);
  1290. ip += 1;
  1291. for (n=0; n<oSize; n+=2)
  1292. {
  1293. huffWeight[n] = ip[n/2] >> 4;
  1294. huffWeight[n+1] = ip[n/2] & 15;
  1295. }
  1296. }
  1297. }
  1298. else /* header compressed with FSE (normal case) */
  1299. {
  1300. if (iSize+1 > srcSize) return ERROR(srcSize_wrong);
  1301. oSize = FSE_decompress(huffWeight, hwSize-1, ip+1, iSize); /* max (hwSize-1) values decoded, as last one is implied */
  1302. if (FSE_isError(oSize)) return oSize;
  1303. }
  1304. /* collect weight stats */
  1305. memset(rankStats, 0, (HUF_ABSOLUTEMAX_TABLELOG + 1) * sizeof(U32));
  1306. weightTotal = 0;
  1307. for (n=0; n<oSize; n++)
  1308. {
  1309. if (huffWeight[n] >= HUF_ABSOLUTEMAX_TABLELOG) return ERROR(corruption_detected);
  1310. rankStats[huffWeight[n]]++;
  1311. weightTotal += (1 << huffWeight[n]) >> 1;
  1312. }
  1313. if (weightTotal == 0) return ERROR(corruption_detected);
  1314. /* get last non-null symbol weight (implied, total must be 2^n) */
  1315. tableLog = BIT_highbit32(weightTotal) + 1;
  1316. if (tableLog > HUF_ABSOLUTEMAX_TABLELOG) return ERROR(corruption_detected);
  1317. {
  1318. U32 total = 1 << tableLog;
  1319. U32 rest = total - weightTotal;
  1320. U32 verif = 1 << BIT_highbit32(rest);
  1321. U32 lastWeight = BIT_highbit32(rest) + 1;
  1322. if (verif != rest) return ERROR(corruption_detected); /* last value must be a clean power of 2 */
  1323. huffWeight[oSize] = (BYTE)lastWeight;
  1324. rankStats[lastWeight]++;
  1325. }
  1326. /* check tree construction validity */
  1327. if ((rankStats[1] < 2) || (rankStats[1] & 1)) return ERROR(corruption_detected); /* by construction : at least 2 elts of rank 1, must be even */
  1328. /* results */
  1329. *nbSymbolsPtr = (U32)(oSize+1);
  1330. *tableLogPtr = tableLog;
  1331. return iSize+1;
  1332. }
  1333. /**************************/
  1334. /* single-symbol decoding */
  1335. /**************************/
  1336. static size_t HUF_readDTableX2 (U16* DTable, const void* src, size_t srcSize)
  1337. {
  1338. BYTE huffWeight[HUF_MAX_SYMBOL_VALUE + 1];
  1339. U32 rankVal[HUF_ABSOLUTEMAX_TABLELOG + 1]; /* large enough for values from 0 to 16 */
  1340. U32 tableLog = 0;
  1341. const BYTE* ip = (const BYTE*) src;
  1342. size_t iSize = ip[0];
  1343. U32 nbSymbols = 0;
  1344. U32 n;
  1345. U32 nextRankStart;
  1346. void* ptr = DTable+1;
  1347. HUF_DEltX2* const dt = (HUF_DEltX2*)(ptr);
  1348. HUF_STATIC_ASSERT(sizeof(HUF_DEltX2) == sizeof(U16)); /* if compilation fails here, assertion is false */
  1349. //memset(huffWeight, 0, sizeof(huffWeight)); /* is not necessary, even though some analyzer complain ... */
  1350. iSize = HUF_readStats(huffWeight, HUF_MAX_SYMBOL_VALUE + 1, rankVal, &nbSymbols, &tableLog, src, srcSize);
  1351. if (HUF_isError(iSize)) return iSize;
  1352. /* check result */
  1353. if (tableLog > DTable[0]) return ERROR(tableLog_tooLarge); /* DTable is too small */
  1354. DTable[0] = (U16)tableLog; /* maybe should separate sizeof DTable, as allocated, from used size of DTable, in case of DTable re-use */
  1355. /* Prepare ranks */
  1356. nextRankStart = 0;
  1357. for (n=1; n<=tableLog; n++)
  1358. {
  1359. U32 current = nextRankStart;
  1360. nextRankStart += (rankVal[n] << (n-1));
  1361. rankVal[n] = current;
  1362. }
  1363. /* fill DTable */
  1364. for (n=0; n<nbSymbols; n++)
  1365. {
  1366. const U32 w = huffWeight[n];
  1367. const U32 length = (1 << w) >> 1;
  1368. U32 i;
  1369. HUF_DEltX2 D;
  1370. D.byte = (BYTE)n; D.nbBits = (BYTE)(tableLog + 1 - w);
  1371. for (i = rankVal[w]; i < rankVal[w] + length; i++)
  1372. dt[i] = D;
  1373. rankVal[w] += length;
  1374. }
  1375. return iSize;
  1376. }
  1377. static BYTE HUF_decodeSymbolX2(BIT_DStream_t* Dstream, const HUF_DEltX2* dt, const U32 dtLog)
  1378. {
  1379. const size_t val = BIT_lookBitsFast(Dstream, dtLog); /* note : dtLog >= 1 */
  1380. const BYTE c = dt[val].byte;
  1381. BIT_skipBits(Dstream, dt[val].nbBits);
  1382. return c;
  1383. }
  1384. #define HUF_DECODE_SYMBOLX2_0(ptr, DStreamPtr) \
  1385. *ptr++ = HUF_decodeSymbolX2(DStreamPtr, dt, dtLog)
  1386. #define HUF_DECODE_SYMBOLX2_1(ptr, DStreamPtr) \
  1387. if (MEM_64bits() || (HUF_MAX_TABLELOG<=12)) \
  1388. HUF_DECODE_SYMBOLX2_0(ptr, DStreamPtr)
  1389. #define HUF_DECODE_SYMBOLX2_2(ptr, DStreamPtr) \
  1390. if (MEM_64bits()) \
  1391. HUF_DECODE_SYMBOLX2_0(ptr, DStreamPtr)
  1392. static inline size_t HUF_decodeStreamX2(BYTE* p, BIT_DStream_t* const bitDPtr, BYTE* const pEnd, const HUF_DEltX2* const dt, const U32 dtLog)
  1393. {
  1394. BYTE* const pStart = p;
  1395. /* up to 4 symbols at a time */
  1396. while ((BIT_reloadDStream(bitDPtr) == BIT_DStream_unfinished) && (p <= pEnd-4))
  1397. {
  1398. HUF_DECODE_SYMBOLX2_2(p, bitDPtr);
  1399. HUF_DECODE_SYMBOLX2_1(p, bitDPtr);
  1400. HUF_DECODE_SYMBOLX2_2(p, bitDPtr);
  1401. HUF_DECODE_SYMBOLX2_0(p, bitDPtr);
  1402. }
  1403. /* closer to the end */
  1404. while ((BIT_reloadDStream(bitDPtr) == BIT_DStream_unfinished) && (p < pEnd))
  1405. HUF_DECODE_SYMBOLX2_0(p, bitDPtr);
  1406. /* no more data to retrieve from bitstream, hence no need to reload */
  1407. while (p < pEnd)
  1408. HUF_DECODE_SYMBOLX2_0(p, bitDPtr);
  1409. return pEnd-pStart;
  1410. }
  1411. static size_t HUF_decompress4X2_usingDTable(
  1412. void* dst, size_t dstSize,
  1413. const void* cSrc, size_t cSrcSize,
  1414. const U16* DTable)
  1415. {
  1416. if (cSrcSize < 10) return ERROR(corruption_detected); /* strict minimum : jump table + 1 byte per stream */
  1417. {
  1418. const BYTE* const istart = (const BYTE*) cSrc;
  1419. BYTE* const ostart = (BYTE*) dst;
  1420. BYTE* const oend = ostart + dstSize;
  1421. const void* ptr = DTable;
  1422. const HUF_DEltX2* const dt = ((const HUF_DEltX2*)ptr) +1;
  1423. const U32 dtLog = DTable[0];
  1424. size_t errorCode;
  1425. /* Init */
  1426. BIT_DStream_t bitD1;
  1427. BIT_DStream_t bitD2;
  1428. BIT_DStream_t bitD3;
  1429. BIT_DStream_t bitD4;
  1430. const size_t length1 = MEM_readLE16(istart);
  1431. const size_t length2 = MEM_readLE16(istart+2);
  1432. const size_t length3 = MEM_readLE16(istart+4);
  1433. size_t length4;
  1434. const BYTE* const istart1 = istart + 6; /* jumpTable */
  1435. const BYTE* const istart2 = istart1 + length1;
  1436. const BYTE* const istart3 = istart2 + length2;
  1437. const BYTE* const istart4 = istart3 + length3;
  1438. const size_t segmentSize = (dstSize+3) / 4;
  1439. BYTE* const opStart2 = ostart + segmentSize;
  1440. BYTE* const opStart3 = opStart2 + segmentSize;
  1441. BYTE* const opStart4 = opStart3 + segmentSize;
  1442. BYTE* op1 = ostart;
  1443. BYTE* op2 = opStart2;
  1444. BYTE* op3 = opStart3;
  1445. BYTE* op4 = opStart4;
  1446. U32 endSignal;
  1447. length4 = cSrcSize - (length1 + length2 + length3 + 6);
  1448. if (length4 > cSrcSize) return ERROR(corruption_detected); /* overflow */
  1449. errorCode = BIT_initDStream(&bitD1, istart1, length1);
  1450. if (HUF_isError(errorCode)) return errorCode;
  1451. errorCode = BIT_initDStream(&bitD2, istart2, length2);
  1452. if (HUF_isError(errorCode)) return errorCode;
  1453. errorCode = BIT_initDStream(&bitD3, istart3, length3);
  1454. if (HUF_isError(errorCode)) return errorCode;
  1455. errorCode = BIT_initDStream(&bitD4, istart4, length4);
  1456. if (HUF_isError(errorCode)) return errorCode;
  1457. /* 16-32 symbols per loop (4-8 symbols per stream) */
  1458. endSignal = BIT_reloadDStream(&bitD1) | BIT_reloadDStream(&bitD2) | BIT_reloadDStream(&bitD3) | BIT_reloadDStream(&bitD4);
  1459. for ( ; (endSignal==BIT_DStream_unfinished) && (op4<(oend-7)) ; )
  1460. {
  1461. HUF_DECODE_SYMBOLX2_2(op1, &bitD1);
  1462. HUF_DECODE_SYMBOLX2_2(op2, &bitD2);
  1463. HUF_DECODE_SYMBOLX2_2(op3, &bitD3);
  1464. HUF_DECODE_SYMBOLX2_2(op4, &bitD4);
  1465. HUF_DECODE_SYMBOLX2_1(op1, &bitD1);
  1466. HUF_DECODE_SYMBOLX2_1(op2, &bitD2);
  1467. HUF_DECODE_SYMBOLX2_1(op3, &bitD3);
  1468. HUF_DECODE_SYMBOLX2_1(op4, &bitD4);
  1469. HUF_DECODE_SYMBOLX2_2(op1, &bitD1);
  1470. HUF_DECODE_SYMBOLX2_2(op2, &bitD2);
  1471. HUF_DECODE_SYMBOLX2_2(op3, &bitD3);
  1472. HUF_DECODE_SYMBOLX2_2(op4, &bitD4);
  1473. HUF_DECODE_SYMBOLX2_0(op1, &bitD1);
  1474. HUF_DECODE_SYMBOLX2_0(op2, &bitD2);
  1475. HUF_DECODE_SYMBOLX2_0(op3, &bitD3);
  1476. HUF_DECODE_SYMBOLX2_0(op4, &bitD4);
  1477. endSignal = BIT_reloadDStream(&bitD1) | BIT_reloadDStream(&bitD2) | BIT_reloadDStream(&bitD3) | BIT_reloadDStream(&bitD4);
  1478. }
  1479. /* check corruption */
  1480. if (op1 > opStart2) return ERROR(corruption_detected);
  1481. if (op2 > opStart3) return ERROR(corruption_detected);
  1482. if (op3 > opStart4) return ERROR(corruption_detected);
  1483. /* note : op4 supposed already verified within main loop */
  1484. /* finish bitStreams one by one */
  1485. HUF_decodeStreamX2(op1, &bitD1, opStart2, dt, dtLog);
  1486. HUF_decodeStreamX2(op2, &bitD2, opStart3, dt, dtLog);
  1487. HUF_decodeStreamX2(op3, &bitD3, opStart4, dt, dtLog);
  1488. HUF_decodeStreamX2(op4, &bitD4, oend, dt, dtLog);
  1489. /* check */
  1490. endSignal = BIT_endOfDStream(&bitD1) & BIT_endOfDStream(&bitD2) & BIT_endOfDStream(&bitD3) & BIT_endOfDStream(&bitD4);
  1491. if (!endSignal) return ERROR(corruption_detected);
  1492. /* decoded size */
  1493. return dstSize;
  1494. }
  1495. }
  1496. static size_t HUF_decompress4X2 (void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize)
  1497. {
  1498. HUF_CREATE_STATIC_DTABLEX2(DTable, HUF_MAX_TABLELOG);
  1499. const BYTE* ip = (const BYTE*) cSrc;
  1500. size_t errorCode;
  1501. errorCode = HUF_readDTableX2 (DTable, cSrc, cSrcSize);
  1502. if (HUF_isError(errorCode)) return errorCode;
  1503. if (errorCode >= cSrcSize) return ERROR(srcSize_wrong);
  1504. ip += errorCode;
  1505. cSrcSize -= errorCode;
  1506. return HUF_decompress4X2_usingDTable (dst, dstSize, ip, cSrcSize, DTable);
  1507. }
  1508. /***************************/
  1509. /* double-symbols decoding */
  1510. /***************************/
  1511. static void HUF_fillDTableX4Level2(HUF_DEltX4* DTable, U32 sizeLog, const U32 consumed,
  1512. const U32* rankValOrigin, const int minWeight,
  1513. const sortedSymbol_t* sortedSymbols, const U32 sortedListSize,
  1514. U32 nbBitsBaseline, U16 baseSeq)
  1515. {
  1516. HUF_DEltX4 DElt;
  1517. U32 rankVal[HUF_ABSOLUTEMAX_TABLELOG + 1];
  1518. U32 s;
  1519. /* get pre-calculated rankVal */
  1520. memcpy(rankVal, rankValOrigin, sizeof(rankVal));
  1521. /* fill skipped values */
  1522. if (minWeight>1)
  1523. {
  1524. U32 i, skipSize = rankVal[minWeight];
  1525. MEM_writeLE16(&(DElt.sequence), baseSeq);
  1526. DElt.nbBits = (BYTE)(consumed);
  1527. DElt.length = 1;
  1528. for (i = 0; i < skipSize; i++)
  1529. DTable[i] = DElt;
  1530. }
  1531. /* fill DTable */
  1532. for (s=0; s<sortedListSize; s++) /* note : sortedSymbols already skipped */
  1533. {
  1534. const U32 symbol = sortedSymbols[s].symbol;
  1535. const U32 weight = sortedSymbols[s].weight;
  1536. const U32 nbBits = nbBitsBaseline - weight;
  1537. const U32 length = 1 << (sizeLog-nbBits);
  1538. const U32 start = rankVal[weight];
  1539. U32 i = start;
  1540. const U32 end = start + length;
  1541. MEM_writeLE16(&(DElt.sequence), (U16)(baseSeq + (symbol << 8)));
  1542. DElt.nbBits = (BYTE)(nbBits + consumed);
  1543. DElt.length = 2;
  1544. do { DTable[i++] = DElt; } while (i<end); /* since length >= 1 */
  1545. rankVal[weight] += length;
  1546. }
  1547. }
  1548. typedef U32 rankVal_t[HUF_ABSOLUTEMAX_TABLELOG][HUF_ABSOLUTEMAX_TABLELOG + 1];
  1549. static void HUF_fillDTableX4(HUF_DEltX4* DTable, const U32 targetLog,
  1550. const sortedSymbol_t* sortedList, const U32 sortedListSize,
  1551. const U32* rankStart, rankVal_t rankValOrigin, const U32 maxWeight,
  1552. const U32 nbBitsBaseline)
  1553. {
  1554. U32 rankVal[HUF_ABSOLUTEMAX_TABLELOG + 1];
  1555. const int scaleLog = nbBitsBaseline - targetLog; /* note : targetLog >= srcLog, hence scaleLog <= 1 */
  1556. const U32 minBits = nbBitsBaseline - maxWeight;
  1557. U32 s;
  1558. memcpy(rankVal, rankValOrigin, sizeof(rankVal));
  1559. /* fill DTable */
  1560. for (s=0; s<sortedListSize; s++)
  1561. {
  1562. const U16 symbol = sortedList[s].symbol;
  1563. const U32 weight = sortedList[s].weight;
  1564. const U32 nbBits = nbBitsBaseline - weight;
  1565. const U32 start = rankVal[weight];
  1566. const U32 length = 1 << (targetLog-nbBits);
  1567. if (targetLog-nbBits >= minBits) /* enough room for a second symbol */
  1568. {
  1569. U32 sortedRank;
  1570. int minWeight = nbBits + scaleLog;
  1571. if (minWeight < 1) minWeight = 1;
  1572. sortedRank = rankStart[minWeight];
  1573. HUF_fillDTableX4Level2(DTable+start, targetLog-nbBits, nbBits,
  1574. rankValOrigin[nbBits], minWeight,
  1575. sortedList+sortedRank, sortedListSize-sortedRank,
  1576. nbBitsBaseline, symbol);
  1577. }
  1578. else
  1579. {
  1580. U32 i;
  1581. const U32 end = start + length;
  1582. HUF_DEltX4 DElt;
  1583. MEM_writeLE16(&(DElt.sequence), symbol);
  1584. DElt.nbBits = (BYTE)(nbBits);
  1585. DElt.length = 1;
  1586. for (i = start; i < end; i++)
  1587. DTable[i] = DElt;
  1588. }
  1589. rankVal[weight] += length;
  1590. }
  1591. }
  1592. static size_t HUF_readDTableX4 (U32* DTable, const void* src, size_t srcSize)
  1593. {
  1594. BYTE weightList[HUF_MAX_SYMBOL_VALUE + 1];
  1595. sortedSymbol_t sortedSymbol[HUF_MAX_SYMBOL_VALUE + 1];
  1596. U32 rankStats[HUF_ABSOLUTEMAX_TABLELOG + 1] = { 0 };
  1597. U32 rankStart0[HUF_ABSOLUTEMAX_TABLELOG + 2] = { 0 };
  1598. U32* const rankStart = rankStart0+1;
  1599. rankVal_t rankVal;
  1600. U32 tableLog, maxW, sizeOfSort, nbSymbols;
  1601. const U32 memLog = DTable[0];
  1602. const BYTE* ip = (const BYTE*) src;
  1603. size_t iSize = ip[0];
  1604. void* ptr = DTable;
  1605. HUF_DEltX4* const dt = ((HUF_DEltX4*)ptr) + 1;
  1606. HUF_STATIC_ASSERT(sizeof(HUF_DEltX4) == sizeof(U32)); /* if compilation fails here, assertion is false */
  1607. if (memLog > HUF_ABSOLUTEMAX_TABLELOG) return ERROR(tableLog_tooLarge);
  1608. //memset(weightList, 0, sizeof(weightList)); /* is not necessary, even though some analyzer complain ... */
  1609. iSize = HUF_readStats(weightList, HUF_MAX_SYMBOL_VALUE + 1, rankStats, &nbSymbols, &tableLog, src, srcSize);
  1610. if (HUF_isError(iSize)) return iSize;
  1611. /* check result */
  1612. if (tableLog > memLog) return ERROR(tableLog_tooLarge); /* DTable can't fit code depth */
  1613. /* find maxWeight */
  1614. for (maxW = tableLog; rankStats[maxW]==0; maxW--)
  1615. { if (!maxW) return ERROR(GENERIC); } /* necessarily finds a solution before maxW==0 */
  1616. /* Get start index of each weight */
  1617. {
  1618. U32 w, nextRankStart = 0;
  1619. for (w=1; w<=maxW; w++)
  1620. {
  1621. U32 current = nextRankStart;
  1622. nextRankStart += rankStats[w];
  1623. rankStart[w] = current;
  1624. }
  1625. rankStart[0] = nextRankStart; /* put all 0w symbols at the end of sorted list*/
  1626. sizeOfSort = nextRankStart;
  1627. }
  1628. /* sort symbols by weight */
  1629. {
  1630. U32 s;
  1631. for (s=0; s<nbSymbols; s++)
  1632. {
  1633. U32 w = weightList[s];
  1634. U32 r = rankStart[w]++;
  1635. sortedSymbol[r].symbol = (BYTE)s;
  1636. sortedSymbol[r].weight = (BYTE)w;
  1637. }
  1638. rankStart[0] = 0; /* forget 0w symbols; this is beginning of weight(1) */
  1639. }
  1640. /* Build rankVal */
  1641. {
  1642. const U32 minBits = tableLog+1 - maxW;
  1643. U32 nextRankVal = 0;
  1644. U32 w, consumed;
  1645. const int rescale = (memLog-tableLog) - 1; /* tableLog <= memLog */
  1646. U32* rankVal0 = rankVal[0];
  1647. for (w=1; w<=maxW; w++)
  1648. {
  1649. U32 current = nextRankVal;
  1650. nextRankVal += rankStats[w] << (w+rescale);
  1651. rankVal0[w] = current;
  1652. }
  1653. for (consumed = minBits; consumed <= memLog - minBits; consumed++)
  1654. {
  1655. U32* rankValPtr = rankVal[consumed];
  1656. for (w = 1; w <= maxW; w++)
  1657. {
  1658. rankValPtr[w] = rankVal0[w] >> consumed;
  1659. }
  1660. }
  1661. }
  1662. HUF_fillDTableX4(dt, memLog,
  1663. sortedSymbol, sizeOfSort,
  1664. rankStart0, rankVal, maxW,
  1665. tableLog+1);
  1666. return iSize;
  1667. }
  1668. static U32 HUF_decodeSymbolX4(void* op, BIT_DStream_t* DStream, const HUF_DEltX4* dt, const U32 dtLog)
  1669. {
  1670. const size_t val = BIT_lookBitsFast(DStream, dtLog); /* note : dtLog >= 1 */
  1671. memcpy(op, dt+val, 2);
  1672. BIT_skipBits(DStream, dt[val].nbBits);
  1673. return dt[val].length;
  1674. }
  1675. static U32 HUF_decodeLastSymbolX4(void* op, BIT_DStream_t* DStream, const HUF_DEltX4* dt, const U32 dtLog)
  1676. {
  1677. const size_t val = BIT_lookBitsFast(DStream, dtLog); /* note : dtLog >= 1 */
  1678. memcpy(op, dt+val, 1);
  1679. if (dt[val].length==1) BIT_skipBits(DStream, dt[val].nbBits);
  1680. else
  1681. {
  1682. if (DStream->bitsConsumed < (sizeof(DStream->bitContainer)*8))
  1683. {
  1684. BIT_skipBits(DStream, dt[val].nbBits);
  1685. if (DStream->bitsConsumed > (sizeof(DStream->bitContainer)*8))
  1686. DStream->bitsConsumed = (sizeof(DStream->bitContainer)*8); /* ugly hack; works only because it's the last symbol. Note : can't easily extract nbBits from just this symbol */
  1687. }
  1688. }
  1689. return 1;
  1690. }
  1691. #define HUF_DECODE_SYMBOLX4_0(ptr, DStreamPtr) \
  1692. ptr += HUF_decodeSymbolX4(ptr, DStreamPtr, dt, dtLog)
  1693. #define HUF_DECODE_SYMBOLX4_1(ptr, DStreamPtr) \
  1694. if (MEM_64bits() || (HUF_MAX_TABLELOG<=12)) \
  1695. ptr += HUF_decodeSymbolX4(ptr, DStreamPtr, dt, dtLog)
  1696. #define HUF_DECODE_SYMBOLX4_2(ptr, DStreamPtr) \
  1697. if (MEM_64bits()) \
  1698. ptr += HUF_decodeSymbolX4(ptr, DStreamPtr, dt, dtLog)
  1699. static inline size_t HUF_decodeStreamX4(BYTE* p, BIT_DStream_t* bitDPtr, BYTE* const pEnd, const HUF_DEltX4* const dt, const U32 dtLog)
  1700. {
  1701. BYTE* const pStart = p;
  1702. /* up to 8 symbols at a time */
  1703. while ((BIT_reloadDStream(bitDPtr) == BIT_DStream_unfinished) && (p < pEnd-7))
  1704. {
  1705. HUF_DECODE_SYMBOLX4_2(p, bitDPtr);
  1706. HUF_DECODE_SYMBOLX4_1(p, bitDPtr);
  1707. HUF_DECODE_SYMBOLX4_2(p, bitDPtr);
  1708. HUF_DECODE_SYMBOLX4_0(p, bitDPtr);
  1709. }
  1710. /* closer to the end */
  1711. while ((BIT_reloadDStream(bitDPtr) == BIT_DStream_unfinished) && (p <= pEnd-2))
  1712. HUF_DECODE_SYMBOLX4_0(p, bitDPtr);
  1713. while (p <= pEnd-2)
  1714. HUF_DECODE_SYMBOLX4_0(p, bitDPtr); /* no need to reload : reached the end of DStream */
  1715. if (p < pEnd)
  1716. p += HUF_decodeLastSymbolX4(p, bitDPtr, dt, dtLog);
  1717. return p-pStart;
  1718. }
  1719. static size_t HUF_decompress4X4_usingDTable(
  1720. void* dst, size_t dstSize,
  1721. const void* cSrc, size_t cSrcSize,
  1722. const U32* DTable)
  1723. {
  1724. if (cSrcSize < 10) return ERROR(corruption_detected); /* strict minimum : jump table + 1 byte per stream */
  1725. {
  1726. const BYTE* const istart = (const BYTE*) cSrc;
  1727. BYTE* const ostart = (BYTE*) dst;
  1728. BYTE* const oend = ostart + dstSize;
  1729. const void* ptr = DTable;
  1730. const HUF_DEltX4* const dt = ((const HUF_DEltX4*)ptr) +1;
  1731. const U32 dtLog = DTable[0];
  1732. size_t errorCode;
  1733. /* Init */
  1734. BIT_DStream_t bitD1;
  1735. BIT_DStream_t bitD2;
  1736. BIT_DStream_t bitD3;
  1737. BIT_DStream_t bitD4;
  1738. const size_t length1 = MEM_readLE16(istart);
  1739. const size_t length2 = MEM_readLE16(istart+2);
  1740. const size_t length3 = MEM_readLE16(istart+4);
  1741. size_t length4;
  1742. const BYTE* const istart1 = istart + 6; /* jumpTable */
  1743. const BYTE* const istart2 = istart1 + length1;
  1744. const BYTE* const istart3 = istart2 + length2;
  1745. const BYTE* const istart4 = istart3 + length3;
  1746. const size_t segmentSize = (dstSize+3) / 4;
  1747. BYTE* const opStart2 = ostart + segmentSize;
  1748. BYTE* const opStart3 = opStart2 + segmentSize;
  1749. BYTE* const opStart4 = opStart3 + segmentSize;
  1750. BYTE* op1 = ostart;
  1751. BYTE* op2 = opStart2;
  1752. BYTE* op3 = opStart3;
  1753. BYTE* op4 = opStart4;
  1754. U32 endSignal;
  1755. length4 = cSrcSize - (length1 + length2 + length3 + 6);
  1756. if (length4 > cSrcSize) return ERROR(corruption_detected); /* overflow */
  1757. errorCode = BIT_initDStream(&bitD1, istart1, length1);
  1758. if (HUF_isError(errorCode)) return errorCode;
  1759. errorCode = BIT_initDStream(&bitD2, istart2, length2);
  1760. if (HUF_isError(errorCode)) return errorCode;
  1761. errorCode = BIT_initDStream(&bitD3, istart3, length3);
  1762. if (HUF_isError(errorCode)) return errorCode;
  1763. errorCode = BIT_initDStream(&bitD4, istart4, length4);
  1764. if (HUF_isError(errorCode)) return errorCode;
  1765. /* 16-32 symbols per loop (4-8 symbols per stream) */
  1766. endSignal = BIT_reloadDStream(&bitD1) | BIT_reloadDStream(&bitD2) | BIT_reloadDStream(&bitD3) | BIT_reloadDStream(&bitD4);
  1767. for ( ; (endSignal==BIT_DStream_unfinished) && (op4<(oend-7)) ; )
  1768. {
  1769. HUF_DECODE_SYMBOLX4_2(op1, &bitD1);
  1770. HUF_DECODE_SYMBOLX4_2(op2, &bitD2);
  1771. HUF_DECODE_SYMBOLX4_2(op3, &bitD3);
  1772. HUF_DECODE_SYMBOLX4_2(op4, &bitD4);
  1773. HUF_DECODE_SYMBOLX4_1(op1, &bitD1);
  1774. HUF_DECODE_SYMBOLX4_1(op2, &bitD2);
  1775. HUF_DECODE_SYMBOLX4_1(op3, &bitD3);
  1776. HUF_DECODE_SYMBOLX4_1(op4, &bitD4);
  1777. HUF_DECODE_SYMBOLX4_2(op1, &bitD1);
  1778. HUF_DECODE_SYMBOLX4_2(op2, &bitD2);
  1779. HUF_DECODE_SYMBOLX4_2(op3, &bitD3);
  1780. HUF_DECODE_SYMBOLX4_2(op4, &bitD4);
  1781. HUF_DECODE_SYMBOLX4_0(op1, &bitD1);
  1782. HUF_DECODE_SYMBOLX4_0(op2, &bitD2);
  1783. HUF_DECODE_SYMBOLX4_0(op3, &bitD3);
  1784. HUF_DECODE_SYMBOLX4_0(op4, &bitD4);
  1785. endSignal = BIT_reloadDStream(&bitD1) | BIT_reloadDStream(&bitD2) | BIT_reloadDStream(&bitD3) | BIT_reloadDStream(&bitD4);
  1786. }
  1787. /* check corruption */
  1788. if (op1 > opStart2) return ERROR(corruption_detected);
  1789. if (op2 > opStart3) return ERROR(corruption_detected);
  1790. if (op3 > opStart4) return ERROR(corruption_detected);
  1791. /* note : op4 supposed already verified within main loop */
  1792. /* finish bitStreams one by one */
  1793. HUF_decodeStreamX4(op1, &bitD1, opStart2, dt, dtLog);
  1794. HUF_decodeStreamX4(op2, &bitD2, opStart3, dt, dtLog);
  1795. HUF_decodeStreamX4(op3, &bitD3, opStart4, dt, dtLog);
  1796. HUF_decodeStreamX4(op4, &bitD4, oend, dt, dtLog);
  1797. /* check */
  1798. endSignal = BIT_endOfDStream(&bitD1) & BIT_endOfDStream(&bitD2) & BIT_endOfDStream(&bitD3) & BIT_endOfDStream(&bitD4);
  1799. if (!endSignal) return ERROR(corruption_detected);
  1800. /* decoded size */
  1801. return dstSize;
  1802. }
  1803. }
  1804. static size_t HUF_decompress4X4 (void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize)
  1805. {
  1806. HUF_CREATE_STATIC_DTABLEX4(DTable, HUF_MAX_TABLELOG);
  1807. const BYTE* ip = (const BYTE*) cSrc;
  1808. size_t hSize = HUF_readDTableX4 (DTable, cSrc, cSrcSize);
  1809. if (HUF_isError(hSize)) return hSize;
  1810. if (hSize >= cSrcSize) return ERROR(srcSize_wrong);
  1811. ip += hSize;
  1812. cSrcSize -= hSize;
  1813. return HUF_decompress4X4_usingDTable (dst, dstSize, ip, cSrcSize, DTable);
  1814. }
  1815. /**********************************/
  1816. /* Generic decompression selector */
  1817. /**********************************/
  1818. typedef struct { U32 tableTime; U32 decode256Time; } algo_time_t;
  1819. static const algo_time_t algoTime[16 /* Quantization */][3 /* single, double, quad */] =
  1820. {
  1821. /* single, double, quad */
  1822. {{0,0}, {1,1}, {2,2}}, /* Q==0 : impossible */
  1823. {{0,0}, {1,1}, {2,2}}, /* Q==1 : impossible */
  1824. {{ 38,130}, {1313, 74}, {2151, 38}}, /* Q == 2 : 12-18% */
  1825. {{ 448,128}, {1353, 74}, {2238, 41}}, /* Q == 3 : 18-25% */
  1826. {{ 556,128}, {1353, 74}, {2238, 47}}, /* Q == 4 : 25-32% */
  1827. {{ 714,128}, {1418, 74}, {2436, 53}}, /* Q == 5 : 32-38% */
  1828. {{ 883,128}, {1437, 74}, {2464, 61}}, /* Q == 6 : 38-44% */
  1829. {{ 897,128}, {1515, 75}, {2622, 68}}, /* Q == 7 : 44-50% */
  1830. {{ 926,128}, {1613, 75}, {2730, 75}}, /* Q == 8 : 50-56% */
  1831. {{ 947,128}, {1729, 77}, {3359, 77}}, /* Q == 9 : 56-62% */
  1832. {{1107,128}, {2083, 81}, {4006, 84}}, /* Q ==10 : 62-69% */
  1833. {{1177,128}, {2379, 87}, {4785, 88}}, /* Q ==11 : 69-75% */
  1834. {{1242,128}, {2415, 93}, {5155, 84}}, /* Q ==12 : 75-81% */
  1835. {{1349,128}, {2644,106}, {5260,106}}, /* Q ==13 : 81-87% */
  1836. {{1455,128}, {2422,124}, {4174,124}}, /* Q ==14 : 87-93% */
  1837. {{ 722,128}, {1891,145}, {1936,146}}, /* Q ==15 : 93-99% */
  1838. };
  1839. typedef size_t (*decompressionAlgo)(void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize);
  1840. static size_t HUF_decompress (void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize)
  1841. {
  1842. static const decompressionAlgo decompress[3] = { HUF_decompress4X2, HUF_decompress4X4, NULL };
  1843. /* estimate decompression time */
  1844. U32 Q;
  1845. const U32 D256 = (U32)(dstSize >> 8);
  1846. U32 Dtime[3];
  1847. U32 algoNb = 0;
  1848. int n;
  1849. /* validation checks */
  1850. if (dstSize == 0) return ERROR(dstSize_tooSmall);
  1851. if (cSrcSize > dstSize) return ERROR(corruption_detected); /* invalid */
  1852. if (cSrcSize == dstSize) { memcpy(dst, cSrc, dstSize); return dstSize; } /* not compressed */
  1853. if (cSrcSize == 1) { memset(dst, *(const BYTE*)cSrc, dstSize); return dstSize; } /* RLE */
  1854. /* decoder timing evaluation */
  1855. Q = (U32)(cSrcSize * 16 / dstSize); /* Q < 16 since dstSize > cSrcSize */
  1856. for (n=0; n<3; n++)
  1857. Dtime[n] = algoTime[Q][n].tableTime + (algoTime[Q][n].decode256Time * D256);
  1858. Dtime[1] += Dtime[1] >> 4; Dtime[2] += Dtime[2] >> 3; /* advantage to algorithms using less memory, for cache eviction */
  1859. if (Dtime[1] < Dtime[0]) algoNb = 1;
  1860. return decompress[algoNb](dst, dstSize, cSrc, cSrcSize);
  1861. //return HUF_decompress4X2(dst, dstSize, cSrc, cSrcSize); /* multi-streams single-symbol decoding */
  1862. //return HUF_decompress4X4(dst, dstSize, cSrc, cSrcSize); /* multi-streams double-symbols decoding */
  1863. //return HUF_decompress4X6(dst, dstSize, cSrc, cSrcSize); /* multi-streams quad-symbols decoding */
  1864. }
  1865. /*
  1866. zstd - standard compression library
  1867. Copyright (C) 2014-2015, Yann Collet.
  1868. BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
  1869. Redistribution and use in source and binary forms, with or without
  1870. modification, are permitted provided that the following conditions are
  1871. met:
  1872. * Redistributions of source code must retain the above copyright
  1873. notice, this list of conditions and the following disclaimer.
  1874. * Redistributions in binary form must reproduce the above
  1875. copyright notice, this list of conditions and the following disclaimer
  1876. in the documentation and/or other materials provided with the
  1877. distribution.
  1878. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  1879. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  1880. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  1881. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  1882. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  1883. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  1884. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  1885. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  1886. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  1887. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  1888. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  1889. You can contact the author at :
  1890. - zstd source repository : https://github.com/Cyan4973/zstd
  1891. - ztsd public forum : https://groups.google.com/forum/#!forum/lz4c
  1892. */
  1893. /* ***************************************************************
  1894. * Tuning parameters
  1895. *****************************************************************/
  1896. /*!
  1897. * MEMORY_USAGE :
  1898. * Memory usage formula : N->2^N Bytes (examples : 10 -> 1KB; 12 -> 4KB ; 16 -> 64KB; 20 -> 1MB; etc.)
  1899. * Increasing memory usage improves compression ratio
  1900. * Reduced memory usage can improve speed, due to cache effect
  1901. */
  1902. #define ZSTD_MEMORY_USAGE 17
  1903. /*!
  1904. * HEAPMODE :
  1905. * Select how default compression functions will allocate memory for their hash table,
  1906. * in memory stack (0, fastest), or in memory heap (1, requires malloc())
  1907. * Note that compression context is fairly large, as a consequence heap memory is recommended.
  1908. */
  1909. #ifndef ZSTD_HEAPMODE
  1910. # define ZSTD_HEAPMODE 1
  1911. #endif /* ZSTD_HEAPMODE */
  1912. /*!
  1913. * LEGACY_SUPPORT :
  1914. * decompressor can decode older formats (starting from Zstd 0.1+)
  1915. */
  1916. #ifndef ZSTD_LEGACY_SUPPORT
  1917. # define ZSTD_LEGACY_SUPPORT 1
  1918. #endif
  1919. /* *******************************************************
  1920. * Includes
  1921. *********************************************************/
  1922. #include <stdlib.h> /* calloc */
  1923. #include <string.h> /* memcpy, memmove */
  1924. #include <stdio.h> /* debug : printf */
  1925. /* *******************************************************
  1926. * Compiler specifics
  1927. *********************************************************/
  1928. #ifdef __AVX2__
  1929. # include <immintrin.h> /* AVX2 intrinsics */
  1930. #endif
  1931. #ifdef _MSC_VER /* Visual Studio */
  1932. # include <intrin.h> /* For Visual 2005 */
  1933. # pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */
  1934. # pragma warning(disable : 4324) /* disable: C4324: padded structure */
  1935. #else
  1936. # define GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__)
  1937. #endif
  1938. /* *******************************************************
  1939. * Constants
  1940. *********************************************************/
  1941. #define HASH_LOG (ZSTD_MEMORY_USAGE - 2)
  1942. #define HASH_TABLESIZE (1 << HASH_LOG)
  1943. #define HASH_MASK (HASH_TABLESIZE - 1)
  1944. #define KNUTH 2654435761
  1945. #define BIT7 128
  1946. #define BIT6 64
  1947. #define BIT5 32
  1948. #define BIT4 16
  1949. #define BIT1 2
  1950. #define BIT0 1
  1951. #define KB *(1 <<10)
  1952. #define MB *(1 <<20)
  1953. #define GB *(1U<<30)
  1954. #define BLOCKSIZE (128 KB) /* define, for static allocation */
  1955. #define MIN_SEQUENCES_SIZE (2 /*seqNb*/ + 2 /*dumps*/ + 3 /*seqTables*/ + 1 /*bitStream*/)
  1956. #define MIN_CBLOCK_SIZE (3 /*litCSize*/ + MIN_SEQUENCES_SIZE)
  1957. #define IS_RAW BIT0
  1958. #define IS_RLE BIT1
  1959. #define WORKPLACESIZE (BLOCKSIZE*3)
  1960. #define MINMATCH 4
  1961. #define MLbits 7
  1962. #define LLbits 6
  1963. #define Offbits 5
  1964. #define MaxML ((1<<MLbits )-1)
  1965. #define MaxLL ((1<<LLbits )-1)
  1966. #define MaxOff 31
  1967. #define LitFSELog 11
  1968. #define MLFSELog 10
  1969. #define LLFSELog 10
  1970. #define OffFSELog 9
  1971. #define MAX(a,b) ((a)<(b)?(b):(a))
  1972. #define MaxSeq MAX(MaxLL, MaxML)
  1973. #define LITERAL_NOENTROPY 63
  1974. #define COMMAND_NOENTROPY 7 /* to remove */
  1975. #define ZSTD_CONTENTSIZE_ERROR (0ULL - 2)
  1976. static const size_t ZSTD_blockHeaderSize = 3;
  1977. static const size_t ZSTD_frameHeaderSize = 4;
  1978. /* *******************************************************
  1979. * Memory operations
  1980. **********************************************************/
  1981. static void ZSTD_copy4(void* dst, const void* src) { memcpy(dst, src, 4); }
  1982. static void ZSTD_copy8(void* dst, const void* src) { memcpy(dst, src, 8); }
  1983. #define COPY8(d,s) { ZSTD_copy8(d,s); d+=8; s+=8; }
  1984. /*! ZSTD_wildcopy : custom version of memcpy(), can copy up to 7-8 bytes too many */
  1985. static void ZSTD_wildcopy(void* dst, const void* src, ptrdiff_t length)
  1986. {
  1987. const BYTE* ip = (const BYTE*)src;
  1988. BYTE* op = (BYTE*)dst;
  1989. BYTE* const oend = op + length;
  1990. do COPY8(op, ip) while (op < oend);
  1991. }
  1992. /* **************************************
  1993. * Local structures
  1994. ****************************************/
  1995. typedef enum { bt_compressed, bt_raw, bt_rle, bt_end } blockType_t;
  1996. typedef struct
  1997. {
  1998. blockType_t blockType;
  1999. U32 origSize;
  2000. } blockProperties_t;
  2001. typedef struct {
  2002. void* buffer;
  2003. U32* offsetStart;
  2004. U32* offset;
  2005. BYTE* offCodeStart;
  2006. BYTE* offCode;
  2007. BYTE* litStart;
  2008. BYTE* lit;
  2009. BYTE* litLengthStart;
  2010. BYTE* litLength;
  2011. BYTE* matchLengthStart;
  2012. BYTE* matchLength;
  2013. BYTE* dumpsStart;
  2014. BYTE* dumps;
  2015. } seqStore_t;
  2016. /* *************************************
  2017. * Error Management
  2018. ***************************************/
  2019. /*! ZSTD_isError
  2020. * tells if a return value is an error code */
  2021. static unsigned ZSTD_isError(size_t code) { return ERR_isError(code); }
  2022. /* *************************************************************
  2023. * Decompression section
  2024. ***************************************************************/
  2025. struct ZSTD_DCtx_s
  2026. {
  2027. U32 LLTable[FSE_DTABLE_SIZE_U32(LLFSELog)];
  2028. U32 OffTable[FSE_DTABLE_SIZE_U32(OffFSELog)];
  2029. U32 MLTable[FSE_DTABLE_SIZE_U32(MLFSELog)];
  2030. void* previousDstEnd;
  2031. void* base;
  2032. size_t expected;
  2033. blockType_t bType;
  2034. U32 phase;
  2035. const BYTE* litPtr;
  2036. size_t litSize;
  2037. BYTE litBuffer[BLOCKSIZE + 8 /* margin for wildcopy */];
  2038. }; /* typedef'd to ZSTD_Dctx within "zstd_static.h" */
  2039. static size_t ZSTD_getcBlockSize(const void* src, size_t srcSize, blockProperties_t* bpPtr)
  2040. {
  2041. const BYTE* const in = (const BYTE* const)src;
  2042. BYTE headerFlags;
  2043. U32 cSize;
  2044. if (srcSize < 3) return ERROR(srcSize_wrong);
  2045. headerFlags = *in;
  2046. cSize = in[2] + (in[1]<<8) + ((in[0] & 7)<<16);
  2047. bpPtr->blockType = (blockType_t)(headerFlags >> 6);
  2048. bpPtr->origSize = (bpPtr->blockType == bt_rle) ? cSize : 0;
  2049. if (bpPtr->blockType == bt_end) return 0;
  2050. if (bpPtr->blockType == bt_rle) return 1;
  2051. return cSize;
  2052. }
  2053. static size_t ZSTD_copyUncompressedBlock(void* dst, size_t maxDstSize, const void* src, size_t srcSize)
  2054. {
  2055. if (srcSize > maxDstSize) return ERROR(dstSize_tooSmall);
  2056. if (srcSize > 0) {
  2057. memcpy(dst, src, srcSize);
  2058. }
  2059. return srcSize;
  2060. }
  2061. /** ZSTD_decompressLiterals
  2062. @return : nb of bytes read from src, or an error code*/
  2063. static size_t ZSTD_decompressLiterals(void* dst, size_t* maxDstSizePtr,
  2064. const void* src, size_t srcSize)
  2065. {
  2066. const BYTE* ip = (const BYTE*)src;
  2067. const size_t litSize = (MEM_readLE32(src) & 0x1FFFFF) >> 2; /* no buffer issue : srcSize >= MIN_CBLOCK_SIZE */
  2068. const size_t litCSize = (MEM_readLE32(ip+2) & 0xFFFFFF) >> 5; /* no buffer issue : srcSize >= MIN_CBLOCK_SIZE */
  2069. if (litSize > *maxDstSizePtr) return ERROR(corruption_detected);
  2070. if (litCSize + 5 > srcSize) return ERROR(corruption_detected);
  2071. if (HUF_isError(HUF_decompress(dst, litSize, ip+5, litCSize))) return ERROR(corruption_detected);
  2072. *maxDstSizePtr = litSize;
  2073. return litCSize + 5;
  2074. }
  2075. /** ZSTD_decodeLiteralsBlock
  2076. @return : nb of bytes read from src (< srcSize )*/
  2077. static size_t ZSTD_decodeLiteralsBlock(void* ctx,
  2078. const void* src, size_t srcSize)
  2079. {
  2080. ZSTD_DCtx* dctx = (ZSTD_DCtx*)ctx;
  2081. const BYTE* const istart = (const BYTE* const)src;
  2082. /* any compressed block with literals segment must be at least this size */
  2083. if (srcSize < MIN_CBLOCK_SIZE) return ERROR(corruption_detected);
  2084. switch(*istart & 3)
  2085. {
  2086. default:
  2087. case 0:
  2088. {
  2089. size_t litSize = BLOCKSIZE;
  2090. const size_t readSize = ZSTD_decompressLiterals(dctx->litBuffer, &litSize, src, srcSize);
  2091. dctx->litPtr = dctx->litBuffer;
  2092. dctx->litSize = litSize;
  2093. memset(dctx->litBuffer + dctx->litSize, 0, 8);
  2094. return readSize; /* works if it's an error too */
  2095. }
  2096. case IS_RAW:
  2097. {
  2098. const size_t litSize = (MEM_readLE32(istart) & 0xFFFFFF) >> 2; /* no buffer issue : srcSize >= MIN_CBLOCK_SIZE */
  2099. if (litSize > srcSize-11) /* risk of reading too far with wildcopy */
  2100. {
  2101. if (litSize > BLOCKSIZE) return ERROR(corruption_detected);
  2102. if (litSize > srcSize-3) return ERROR(corruption_detected);
  2103. memcpy(dctx->litBuffer, istart, litSize);
  2104. dctx->litPtr = dctx->litBuffer;
  2105. dctx->litSize = litSize;
  2106. memset(dctx->litBuffer + dctx->litSize, 0, 8);
  2107. return litSize+3;
  2108. }
  2109. /* direct reference into compressed stream */
  2110. dctx->litPtr = istart+3;
  2111. dctx->litSize = litSize;
  2112. return litSize+3;
  2113. }
  2114. case IS_RLE:
  2115. {
  2116. const size_t litSize = (MEM_readLE32(istart) & 0xFFFFFF) >> 2; /* no buffer issue : srcSize >= MIN_CBLOCK_SIZE */
  2117. if (litSize > BLOCKSIZE) return ERROR(corruption_detected);
  2118. memset(dctx->litBuffer, istart[3], litSize + 8);
  2119. dctx->litPtr = dctx->litBuffer;
  2120. dctx->litSize = litSize;
  2121. return 4;
  2122. }
  2123. }
  2124. }
  2125. static size_t ZSTD_decodeSeqHeaders(int* nbSeq, const BYTE** dumpsPtr, size_t* dumpsLengthPtr,
  2126. FSE_DTable* DTableLL, FSE_DTable* DTableML, FSE_DTable* DTableOffb,
  2127. const void* src, size_t srcSize)
  2128. {
  2129. const BYTE* const istart = (const BYTE* const)src;
  2130. const BYTE* ip = istart;
  2131. const BYTE* const iend = istart + srcSize;
  2132. U32 LLtype, Offtype, MLtype;
  2133. U32 LLlog, Offlog, MLlog;
  2134. size_t dumpsLength;
  2135. /* check */
  2136. if (srcSize < 5) return ERROR(srcSize_wrong);
  2137. /* SeqHead */
  2138. *nbSeq = MEM_readLE16(ip); ip+=2;
  2139. LLtype = *ip >> 6;
  2140. Offtype = (*ip >> 4) & 3;
  2141. MLtype = (*ip >> 2) & 3;
  2142. if (*ip & 2)
  2143. {
  2144. dumpsLength = ip[2];
  2145. dumpsLength += ip[1] << 8;
  2146. ip += 3;
  2147. }
  2148. else
  2149. {
  2150. dumpsLength = ip[1];
  2151. dumpsLength += (ip[0] & 1) << 8;
  2152. ip += 2;
  2153. }
  2154. *dumpsPtr = ip;
  2155. ip += dumpsLength;
  2156. *dumpsLengthPtr = dumpsLength;
  2157. /* check */
  2158. if (ip > iend-3) return ERROR(srcSize_wrong); /* min : all 3 are "raw", hence no header, but at least xxLog bits per type */
  2159. /* sequences */
  2160. {
  2161. S16 norm[MaxML+1]; /* assumption : MaxML >= MaxLL and MaxOff */
  2162. size_t headerSize;
  2163. /* Build DTables */
  2164. switch(LLtype)
  2165. {
  2166. case bt_rle :
  2167. LLlog = 0;
  2168. FSE_buildDTable_rle(DTableLL, *ip++); break;
  2169. case bt_raw :
  2170. LLlog = LLbits;
  2171. FSE_buildDTable_raw(DTableLL, LLbits); break;
  2172. default :
  2173. { U32 max = MaxLL;
  2174. headerSize = FSE_readNCount(norm, &max, &LLlog, ip, iend-ip);
  2175. if (FSE_isError(headerSize)) return ERROR(GENERIC);
  2176. if (LLlog > LLFSELog) return ERROR(corruption_detected);
  2177. ip += headerSize;
  2178. FSE_buildDTable(DTableLL, norm, max, LLlog);
  2179. } }
  2180. switch(Offtype)
  2181. {
  2182. case bt_rle :
  2183. Offlog = 0;
  2184. if (ip > iend-2) return ERROR(srcSize_wrong); /* min : "raw", hence no header, but at least xxLog bits */
  2185. FSE_buildDTable_rle(DTableOffb, *ip++ & MaxOff); /* if *ip > MaxOff, data is corrupted */
  2186. break;
  2187. case bt_raw :
  2188. Offlog = Offbits;
  2189. FSE_buildDTable_raw(DTableOffb, Offbits); break;
  2190. default :
  2191. { U32 max = MaxOff;
  2192. headerSize = FSE_readNCount(norm, &max, &Offlog, ip, iend-ip);
  2193. if (FSE_isError(headerSize)) return ERROR(GENERIC);
  2194. if (Offlog > OffFSELog) return ERROR(corruption_detected);
  2195. ip += headerSize;
  2196. FSE_buildDTable(DTableOffb, norm, max, Offlog);
  2197. } }
  2198. switch(MLtype)
  2199. {
  2200. case bt_rle :
  2201. MLlog = 0;
  2202. if (ip > iend-2) return ERROR(srcSize_wrong); /* min : "raw", hence no header, but at least xxLog bits */
  2203. FSE_buildDTable_rle(DTableML, *ip++); break;
  2204. case bt_raw :
  2205. MLlog = MLbits;
  2206. FSE_buildDTable_raw(DTableML, MLbits); break;
  2207. default :
  2208. { U32 max = MaxML;
  2209. headerSize = FSE_readNCount(norm, &max, &MLlog, ip, iend-ip);
  2210. if (FSE_isError(headerSize)) return ERROR(GENERIC);
  2211. if (MLlog > MLFSELog) return ERROR(corruption_detected);
  2212. ip += headerSize;
  2213. FSE_buildDTable(DTableML, norm, max, MLlog);
  2214. } } }
  2215. return ip-istart;
  2216. }
  2217. typedef struct {
  2218. size_t litLength;
  2219. size_t offset;
  2220. size_t matchLength;
  2221. } seq_t;
  2222. typedef struct {
  2223. BIT_DStream_t DStream;
  2224. FSE_DState_t stateLL;
  2225. FSE_DState_t stateOffb;
  2226. FSE_DState_t stateML;
  2227. size_t prevOffset;
  2228. const BYTE* dumps;
  2229. const BYTE* dumpsEnd;
  2230. } seqState_t;
  2231. static void ZSTD_decodeSequence(seq_t* seq, seqState_t* seqState)
  2232. {
  2233. size_t litLength;
  2234. size_t prevOffset;
  2235. size_t offset;
  2236. size_t matchLength;
  2237. const BYTE* dumps = seqState->dumps;
  2238. const BYTE* const de = seqState->dumpsEnd;
  2239. /* Literal length */
  2240. litLength = FSE_decodeSymbol(&(seqState->stateLL), &(seqState->DStream));
  2241. prevOffset = litLength ? seq->offset : seqState->prevOffset;
  2242. seqState->prevOffset = seq->offset;
  2243. if (litLength == MaxLL)
  2244. {
  2245. const U32 add = dumps<de ? *dumps++ : 0;
  2246. if (add < 255) litLength += add;
  2247. else if (dumps + 3 <= de)
  2248. {
  2249. litLength = MEM_readLE24(dumps);
  2250. dumps += 3;
  2251. }
  2252. if (dumps >= de) dumps = de-1; /* late correction, to avoid read overflow (data is now corrupted anyway) */
  2253. }
  2254. /* Offset */
  2255. {
  2256. static const size_t offsetPrefix[MaxOff+1] = { /* note : size_t faster than U32 */
  2257. 1 /*fake*/, 1, 2, 4, 8, 16, 32, 64, 128, 256,
  2258. 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072, 262144,
  2259. 524288, 1048576, 2097152, 4194304, 8388608, 16777216, 33554432, /*fake*/ 1, 1, 1, 1, 1 };
  2260. U32 offsetCode, nbBits;
  2261. offsetCode = FSE_decodeSymbol(&(seqState->stateOffb), &(seqState->DStream)); /* <= maxOff, by table construction */
  2262. if (MEM_32bits()) BIT_reloadDStream(&(seqState->DStream));
  2263. nbBits = offsetCode - 1;
  2264. if (offsetCode==0) nbBits = 0; /* cmove */
  2265. offset = offsetPrefix[offsetCode] + BIT_readBits(&(seqState->DStream), nbBits);
  2266. if (MEM_32bits()) BIT_reloadDStream(&(seqState->DStream));
  2267. if (offsetCode==0) offset = prevOffset; /* cmove */
  2268. }
  2269. /* MatchLength */
  2270. matchLength = FSE_decodeSymbol(&(seqState->stateML), &(seqState->DStream));
  2271. if (matchLength == MaxML)
  2272. {
  2273. const U32 add = dumps<de ? *dumps++ : 0;
  2274. if (add < 255) matchLength += add;
  2275. else if (dumps + 3 <= de)
  2276. {
  2277. matchLength = MEM_readLE24(dumps);
  2278. dumps += 3;
  2279. }
  2280. if (dumps >= de) dumps = de-1; /* late correction, to avoid read overflow (data is now corrupted anyway) */
  2281. }
  2282. matchLength += MINMATCH;
  2283. /* save result */
  2284. seq->litLength = litLength;
  2285. seq->offset = offset;
  2286. seq->matchLength = matchLength;
  2287. seqState->dumps = dumps;
  2288. }
  2289. static size_t ZSTD_execSequence(BYTE* op,
  2290. seq_t sequence,
  2291. const BYTE** litPtr, const BYTE* const litLimit,
  2292. BYTE* const base, BYTE* const oend)
  2293. {
  2294. static const int dec32table[] = {0, 1, 2, 1, 4, 4, 4, 4}; /* added */
  2295. static const int dec64table[] = {8, 8, 8, 7, 8, 9,10,11}; /* subtracted */
  2296. const BYTE* const ostart = op;
  2297. BYTE* const oLitEnd = op + sequence.litLength;
  2298. BYTE* const oMatchEnd = op + sequence.litLength + sequence.matchLength; /* risk : address space overflow (32-bits) */
  2299. BYTE* const oend_8 = oend-8;
  2300. const BYTE* const litEnd = *litPtr + sequence.litLength;
  2301. /* checks */
  2302. if (oLitEnd > oend_8) return ERROR(dstSize_tooSmall); /* last match must start at a minimum distance of 8 from oend */
  2303. if (oMatchEnd > oend) return ERROR(dstSize_tooSmall); /* overwrite beyond dst buffer */
  2304. if (litEnd > litLimit) return ERROR(corruption_detected); /* overRead beyond lit buffer */
  2305. /* copy Literals */
  2306. ZSTD_wildcopy(op, *litPtr, sequence.litLength); /* note : oLitEnd <= oend-8 : no risk of overwrite beyond oend */
  2307. op = oLitEnd;
  2308. *litPtr = litEnd; /* update for next sequence */
  2309. /* copy Match */
  2310. {
  2311. const BYTE* match = op - sequence.offset;
  2312. /* check */
  2313. if (sequence.offset > (size_t)op) return ERROR(corruption_detected); /* address space overflow test (this test seems kept by clang optimizer) */
  2314. //if (match > op) return ERROR(corruption_detected); /* address space overflow test (is clang optimizer removing this test ?) */
  2315. if (match < base) return ERROR(corruption_detected);
  2316. /* close range match, overlap */
  2317. if (sequence.offset < 8)
  2318. {
  2319. const int dec64 = dec64table[sequence.offset];
  2320. op[0] = match[0];
  2321. op[1] = match[1];
  2322. op[2] = match[2];
  2323. op[3] = match[3];
  2324. match += dec32table[sequence.offset];
  2325. ZSTD_copy4(op+4, match);
  2326. match -= dec64;
  2327. }
  2328. else
  2329. {
  2330. ZSTD_copy8(op, match);
  2331. }
  2332. op += 8; match += 8;
  2333. if (oMatchEnd > oend-(16-MINMATCH))
  2334. {
  2335. if (op < oend_8)
  2336. {
  2337. ZSTD_wildcopy(op, match, oend_8 - op);
  2338. match += oend_8 - op;
  2339. op = oend_8;
  2340. }
  2341. while (op < oMatchEnd) *op++ = *match++;
  2342. }
  2343. else
  2344. {
  2345. ZSTD_wildcopy(op, match, (ptrdiff_t)sequence.matchLength-8); /* works even if matchLength < 8 */
  2346. }
  2347. }
  2348. return oMatchEnd - ostart;
  2349. }
  2350. static size_t ZSTD_decompressSequences(
  2351. void* ctx,
  2352. void* dst, size_t maxDstSize,
  2353. const void* seqStart, size_t seqSize)
  2354. {
  2355. ZSTD_DCtx* dctx = (ZSTD_DCtx*)ctx;
  2356. const BYTE* ip = (const BYTE*)seqStart;
  2357. const BYTE* const iend = ip + seqSize;
  2358. BYTE* const ostart = (BYTE* const)dst;
  2359. BYTE* op = ostart;
  2360. BYTE* const oend = ostart + maxDstSize;
  2361. size_t errorCode, dumpsLength;
  2362. const BYTE* litPtr = dctx->litPtr;
  2363. const BYTE* const litEnd = litPtr + dctx->litSize;
  2364. int nbSeq;
  2365. const BYTE* dumps;
  2366. U32* DTableLL = dctx->LLTable;
  2367. U32* DTableML = dctx->MLTable;
  2368. U32* DTableOffb = dctx->OffTable;
  2369. BYTE* const base = (BYTE*) (dctx->base);
  2370. /* Build Decoding Tables */
  2371. errorCode = ZSTD_decodeSeqHeaders(&nbSeq, &dumps, &dumpsLength,
  2372. DTableLL, DTableML, DTableOffb,
  2373. ip, iend-ip);
  2374. if (ZSTD_isError(errorCode)) return errorCode;
  2375. ip += errorCode;
  2376. /* Regen sequences */
  2377. {
  2378. seq_t sequence;
  2379. seqState_t seqState;
  2380. memset(&sequence, 0, sizeof(sequence));
  2381. seqState.dumps = dumps;
  2382. seqState.dumpsEnd = dumps + dumpsLength;
  2383. seqState.prevOffset = sequence.offset = 4;
  2384. errorCode = BIT_initDStream(&(seqState.DStream), ip, iend-ip);
  2385. if (ERR_isError(errorCode)) return ERROR(corruption_detected);
  2386. FSE_initDState(&(seqState.stateLL), &(seqState.DStream), DTableLL);
  2387. FSE_initDState(&(seqState.stateOffb), &(seqState.DStream), DTableOffb);
  2388. FSE_initDState(&(seqState.stateML), &(seqState.DStream), DTableML);
  2389. for ( ; (BIT_reloadDStream(&(seqState.DStream)) <= BIT_DStream_completed) && (nbSeq>0) ; )
  2390. {
  2391. size_t oneSeqSize;
  2392. nbSeq--;
  2393. ZSTD_decodeSequence(&sequence, &seqState);
  2394. oneSeqSize = ZSTD_execSequence(op, sequence, &litPtr, litEnd, base, oend);
  2395. if (ZSTD_isError(oneSeqSize)) return oneSeqSize;
  2396. op += oneSeqSize;
  2397. }
  2398. /* check if reached exact end */
  2399. if ( !BIT_endOfDStream(&(seqState.DStream)) ) return ERROR(corruption_detected); /* requested too much : data is corrupted */
  2400. if (nbSeq<0) return ERROR(corruption_detected); /* requested too many sequences : data is corrupted */
  2401. /* last literal segment */
  2402. {
  2403. size_t lastLLSize = litEnd - litPtr;
  2404. if (litPtr > litEnd) return ERROR(corruption_detected);
  2405. if (op+lastLLSize > oend) return ERROR(dstSize_tooSmall);
  2406. if (lastLLSize > 0) {
  2407. if (op != litPtr) memmove(op, litPtr, lastLLSize);
  2408. op += lastLLSize;
  2409. }
  2410. }
  2411. }
  2412. return op-ostart;
  2413. }
  2414. static size_t ZSTD_decompressBlock(
  2415. void* ctx,
  2416. void* dst, size_t maxDstSize,
  2417. const void* src, size_t srcSize)
  2418. {
  2419. /* blockType == blockCompressed */
  2420. const BYTE* ip = (const BYTE*)src;
  2421. /* Decode literals sub-block */
  2422. size_t litCSize = ZSTD_decodeLiteralsBlock(ctx, src, srcSize);
  2423. if (ZSTD_isError(litCSize)) return litCSize;
  2424. ip += litCSize;
  2425. srcSize -= litCSize;
  2426. return ZSTD_decompressSequences(ctx, dst, maxDstSize, ip, srcSize);
  2427. }
  2428. static size_t ZSTD_decompressDCtx(void* ctx, void* dst, size_t maxDstSize, const void* src, size_t srcSize)
  2429. {
  2430. const BYTE* ip = (const BYTE*)src;
  2431. const BYTE* iend = ip + srcSize;
  2432. BYTE* const ostart = (BYTE* const)dst;
  2433. BYTE* op = ostart;
  2434. BYTE* const oend = ostart + maxDstSize;
  2435. size_t remainingSize = srcSize;
  2436. U32 magicNumber;
  2437. blockProperties_t blockProperties;
  2438. /* Frame Header */
  2439. if (srcSize < ZSTD_frameHeaderSize+ZSTD_blockHeaderSize) return ERROR(srcSize_wrong);
  2440. magicNumber = MEM_readLE32(src);
  2441. if (magicNumber != ZSTD_magicNumber) return ERROR(prefix_unknown);
  2442. ip += ZSTD_frameHeaderSize; remainingSize -= ZSTD_frameHeaderSize;
  2443. /* Loop on each block */
  2444. while (1)
  2445. {
  2446. size_t decodedSize=0;
  2447. size_t cBlockSize = ZSTD_getcBlockSize(ip, iend-ip, &blockProperties);
  2448. if (ZSTD_isError(cBlockSize)) return cBlockSize;
  2449. ip += ZSTD_blockHeaderSize;
  2450. remainingSize -= ZSTD_blockHeaderSize;
  2451. if (cBlockSize > remainingSize) return ERROR(srcSize_wrong);
  2452. switch(blockProperties.blockType)
  2453. {
  2454. case bt_compressed:
  2455. decodedSize = ZSTD_decompressBlock(ctx, op, oend-op, ip, cBlockSize);
  2456. break;
  2457. case bt_raw :
  2458. decodedSize = ZSTD_copyUncompressedBlock(op, oend-op, ip, cBlockSize);
  2459. break;
  2460. case bt_rle :
  2461. return ERROR(GENERIC); /* not yet supported */
  2462. break;
  2463. case bt_end :
  2464. /* end of frame */
  2465. if (remainingSize) return ERROR(srcSize_wrong);
  2466. break;
  2467. default:
  2468. return ERROR(GENERIC); /* impossible */
  2469. }
  2470. if (cBlockSize == 0) break; /* bt_end */
  2471. if (ZSTD_isError(decodedSize)) return decodedSize;
  2472. op += decodedSize;
  2473. ip += cBlockSize;
  2474. remainingSize -= cBlockSize;
  2475. }
  2476. return op-ostart;
  2477. }
  2478. static size_t ZSTD_decompress(void* dst, size_t maxDstSize, const void* src, size_t srcSize)
  2479. {
  2480. ZSTD_DCtx ctx;
  2481. ctx.base = dst;
  2482. return ZSTD_decompressDCtx(&ctx, dst, maxDstSize, src, srcSize);
  2483. }
  2484. /* ZSTD_errorFrameSizeInfoLegacy() :
  2485. assumes `cSize` and `dBound` are _not_ NULL */
  2486. MEM_STATIC void ZSTD_errorFrameSizeInfoLegacy(size_t* cSize, unsigned long long* dBound, size_t ret)
  2487. {
  2488. *cSize = ret;
  2489. *dBound = ZSTD_CONTENTSIZE_ERROR;
  2490. }
  2491. void ZSTDv03_findFrameSizeInfoLegacy(const void *src, size_t srcSize, size_t* cSize, unsigned long long* dBound)
  2492. {
  2493. const BYTE* ip = (const BYTE*)src;
  2494. size_t remainingSize = srcSize;
  2495. size_t nbBlocks = 0;
  2496. U32 magicNumber;
  2497. blockProperties_t blockProperties;
  2498. /* Frame Header */
  2499. if (srcSize < ZSTD_frameHeaderSize+ZSTD_blockHeaderSize) {
  2500. ZSTD_errorFrameSizeInfoLegacy(cSize, dBound, ERROR(srcSize_wrong));
  2501. return;
  2502. }
  2503. magicNumber = MEM_readLE32(src);
  2504. if (magicNumber != ZSTD_magicNumber) {
  2505. ZSTD_errorFrameSizeInfoLegacy(cSize, dBound, ERROR(prefix_unknown));
  2506. return;
  2507. }
  2508. ip += ZSTD_frameHeaderSize; remainingSize -= ZSTD_frameHeaderSize;
  2509. /* Loop on each block */
  2510. while (1)
  2511. {
  2512. size_t cBlockSize = ZSTD_getcBlockSize(ip, remainingSize, &blockProperties);
  2513. if (ZSTD_isError(cBlockSize)) {
  2514. ZSTD_errorFrameSizeInfoLegacy(cSize, dBound, cBlockSize);
  2515. return;
  2516. }
  2517. ip += ZSTD_blockHeaderSize;
  2518. remainingSize -= ZSTD_blockHeaderSize;
  2519. if (cBlockSize > remainingSize) {
  2520. ZSTD_errorFrameSizeInfoLegacy(cSize, dBound, ERROR(srcSize_wrong));
  2521. return;
  2522. }
  2523. if (cBlockSize == 0) break; /* bt_end */
  2524. ip += cBlockSize;
  2525. remainingSize -= cBlockSize;
  2526. nbBlocks++;
  2527. }
  2528. *cSize = ip - (const BYTE*)src;
  2529. *dBound = nbBlocks * BLOCKSIZE;
  2530. }
  2531. /*******************************
  2532. * Streaming Decompression API
  2533. *******************************/
  2534. static size_t ZSTD_resetDCtx(ZSTD_DCtx* dctx)
  2535. {
  2536. dctx->expected = ZSTD_frameHeaderSize;
  2537. dctx->phase = 0;
  2538. dctx->previousDstEnd = NULL;
  2539. dctx->base = NULL;
  2540. return 0;
  2541. }
  2542. static ZSTD_DCtx* ZSTD_createDCtx(void)
  2543. {
  2544. ZSTD_DCtx* dctx = (ZSTD_DCtx*)malloc(sizeof(ZSTD_DCtx));
  2545. if (dctx==NULL) return NULL;
  2546. ZSTD_resetDCtx(dctx);
  2547. return dctx;
  2548. }
  2549. static size_t ZSTD_freeDCtx(ZSTD_DCtx* dctx)
  2550. {
  2551. free(dctx);
  2552. return 0;
  2553. }
  2554. static size_t ZSTD_nextSrcSizeToDecompress(ZSTD_DCtx* dctx)
  2555. {
  2556. return dctx->expected;
  2557. }
  2558. static size_t ZSTD_decompressContinue(ZSTD_DCtx* ctx, void* dst, size_t maxDstSize, const void* src, size_t srcSize)
  2559. {
  2560. /* Sanity check */
  2561. if (srcSize != ctx->expected) return ERROR(srcSize_wrong);
  2562. if (dst != ctx->previousDstEnd) /* not contiguous */
  2563. ctx->base = dst;
  2564. /* Decompress : frame header */
  2565. if (ctx->phase == 0)
  2566. {
  2567. /* Check frame magic header */
  2568. U32 magicNumber = MEM_readLE32(src);
  2569. if (magicNumber != ZSTD_magicNumber) return ERROR(prefix_unknown);
  2570. ctx->phase = 1;
  2571. ctx->expected = ZSTD_blockHeaderSize;
  2572. return 0;
  2573. }
  2574. /* Decompress : block header */
  2575. if (ctx->phase == 1)
  2576. {
  2577. blockProperties_t bp;
  2578. size_t blockSize = ZSTD_getcBlockSize(src, ZSTD_blockHeaderSize, &bp);
  2579. if (ZSTD_isError(blockSize)) return blockSize;
  2580. if (bp.blockType == bt_end)
  2581. {
  2582. ctx->expected = 0;
  2583. ctx->phase = 0;
  2584. }
  2585. else
  2586. {
  2587. ctx->expected = blockSize;
  2588. ctx->bType = bp.blockType;
  2589. ctx->phase = 2;
  2590. }
  2591. return 0;
  2592. }
  2593. /* Decompress : block content */
  2594. {
  2595. size_t rSize;
  2596. switch(ctx->bType)
  2597. {
  2598. case bt_compressed:
  2599. rSize = ZSTD_decompressBlock(ctx, dst, maxDstSize, src, srcSize);
  2600. break;
  2601. case bt_raw :
  2602. rSize = ZSTD_copyUncompressedBlock(dst, maxDstSize, src, srcSize);
  2603. break;
  2604. case bt_rle :
  2605. return ERROR(GENERIC); /* not yet handled */
  2606. break;
  2607. case bt_end : /* should never happen (filtered at phase 1) */
  2608. rSize = 0;
  2609. break;
  2610. default:
  2611. return ERROR(GENERIC);
  2612. }
  2613. ctx->phase = 1;
  2614. ctx->expected = ZSTD_blockHeaderSize;
  2615. ctx->previousDstEnd = (void*)( ((char*)dst) + rSize);
  2616. return rSize;
  2617. }
  2618. }
  2619. /* wrapper layer */
  2620. unsigned ZSTDv03_isError(size_t code)
  2621. {
  2622. return ZSTD_isError(code);
  2623. }
  2624. size_t ZSTDv03_decompress( void* dst, size_t maxOriginalSize,
  2625. const void* src, size_t compressedSize)
  2626. {
  2627. return ZSTD_decompress(dst, maxOriginalSize, src, compressedSize);
  2628. }
  2629. ZSTDv03_Dctx* ZSTDv03_createDCtx(void)
  2630. {
  2631. return (ZSTDv03_Dctx*)ZSTD_createDCtx();
  2632. }
  2633. size_t ZSTDv03_freeDCtx(ZSTDv03_Dctx* dctx)
  2634. {
  2635. return ZSTD_freeDCtx((ZSTD_DCtx*)dctx);
  2636. }
  2637. size_t ZSTDv03_resetDCtx(ZSTDv03_Dctx* dctx)
  2638. {
  2639. return ZSTD_resetDCtx((ZSTD_DCtx*)dctx);
  2640. }
  2641. size_t ZSTDv03_nextSrcSizeToDecompress(ZSTDv03_Dctx* dctx)
  2642. {
  2643. return ZSTD_nextSrcSizeToDecompress((ZSTD_DCtx*)dctx);
  2644. }
  2645. size_t ZSTDv03_decompressContinue(ZSTDv03_Dctx* dctx, void* dst, size_t maxDstSize, const void* src, size_t srcSize)
  2646. {
  2647. return ZSTD_decompressContinue((ZSTD_DCtx*)dctx, dst, maxDstSize, src, srcSize);
  2648. }