zstd_v02.c 123 KB

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