zstd_v02.c 124 KB

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