zstd_v02.c 122 KB

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