zstd_v03.c 109 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105
  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_v03.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. #if defined (__cplusplus)
  622. }
  623. #endif
  624. /*
  625. zstd - standard compression library
  626. Header File
  627. Copyright (C) 2014-2015, Yann Collet.
  628. BSD 2-Clause License (https://opensource.org/licenses/bsd-license.php)
  629. Redistribution and use in source and binary forms, with or without
  630. modification, are permitted provided that the following conditions are
  631. met:
  632. * Redistributions of source code must retain the above copyright
  633. notice, this list of conditions and the following disclaimer.
  634. * Redistributions in binary form must reproduce the above
  635. copyright notice, this list of conditions and the following disclaimer
  636. in the documentation and/or other materials provided with the
  637. distribution.
  638. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  639. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  640. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  641. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  642. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  643. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  644. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  645. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  646. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  647. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  648. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  649. You can contact the author at :
  650. - zstd source repository : https://github.com/Cyan4973/zstd
  651. - ztsd public forum : https://groups.google.com/forum/#!forum/lz4c
  652. */
  653. #if defined (__cplusplus)
  654. extern "C" {
  655. #endif
  656. /* *************************************
  657. * Includes
  658. ***************************************/
  659. #include <stddef.h> /* size_t */
  660. /* *************************************
  661. * Version
  662. ***************************************/
  663. #define ZSTD_VERSION_MAJOR 0 /* for breaking interface changes */
  664. #define ZSTD_VERSION_MINOR 2 /* for new (non-breaking) interface capabilities */
  665. #define ZSTD_VERSION_RELEASE 2 /* for tweaks, bug-fixes, or development */
  666. #define ZSTD_VERSION_NUMBER (ZSTD_VERSION_MAJOR *100*100 + ZSTD_VERSION_MINOR *100 + ZSTD_VERSION_RELEASE)
  667. /* *************************************
  668. * Advanced functions
  669. ***************************************/
  670. typedef struct ZSTD_CCtx_s ZSTD_CCtx; /* incomplete type */
  671. #if defined (__cplusplus)
  672. }
  673. #endif
  674. /*
  675. zstd - standard compression library
  676. Header File for static linking only
  677. Copyright (C) 2014-2015, Yann Collet.
  678. BSD 2-Clause License (https://opensource.org/licenses/bsd-license.php)
  679. Redistribution and use in source and binary forms, with or without
  680. modification, are permitted provided that the following conditions are
  681. met:
  682. * Redistributions of source code must retain the above copyright
  683. notice, this list of conditions and the following disclaimer.
  684. * Redistributions in binary form must reproduce the above
  685. copyright notice, this list of conditions and the following disclaimer
  686. in the documentation and/or other materials provided with the
  687. distribution.
  688. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  689. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  690. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  691. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  692. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  693. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  694. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  695. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  696. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  697. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  698. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  699. You can contact the author at :
  700. - zstd source repository : https://github.com/Cyan4973/zstd
  701. - ztsd public forum : https://groups.google.com/forum/#!forum/lz4c
  702. */
  703. /* The objects defined into this file should be considered experimental.
  704. * They are not labelled stable, as their prototype may change in the future.
  705. * You can use them for tests, provide feedback, or if you can endure risk of future changes.
  706. */
  707. #if defined (__cplusplus)
  708. extern "C" {
  709. #endif
  710. /* *************************************
  711. * Streaming functions
  712. ***************************************/
  713. typedef struct ZSTDv03_Dctx_s ZSTD_DCtx;
  714. /*
  715. Use above functions alternatively.
  716. ZSTD_nextSrcSizeToDecompress() tells how much bytes to provide as 'srcSize' to ZSTD_decompressContinue().
  717. ZSTD_decompressContinue() will use previous data blocks to improve compression if they are located prior to current block.
  718. Result is the number of bytes regenerated within 'dst'.
  719. It can be zero, which is not an error; it just means ZSTD_decompressContinue() has decoded some header.
  720. */
  721. /* *************************************
  722. * Prefix - version detection
  723. ***************************************/
  724. #define ZSTD_magicNumber 0xFD2FB523 /* v0.3 */
  725. #if defined (__cplusplus)
  726. }
  727. #endif
  728. /* ******************************************************************
  729. FSE : Finite State Entropy coder
  730. Copyright (C) 2013-2015, Yann Collet.
  731. BSD 2-Clause License (https://opensource.org/licenses/bsd-license.php)
  732. Redistribution and use in source and binary forms, with or without
  733. modification, are permitted provided that the following conditions are
  734. met:
  735. * Redistributions of source code must retain the above copyright
  736. notice, this list of conditions and the following disclaimer.
  737. * Redistributions in binary form must reproduce the above
  738. copyright notice, this list of conditions and the following disclaimer
  739. in the documentation and/or other materials provided with the
  740. distribution.
  741. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  742. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  743. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  744. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  745. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  746. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  747. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  748. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  749. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  750. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  751. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  752. You can contact the author at :
  753. - FSE source repository : https://github.com/Cyan4973/FiniteStateEntropy
  754. - Public forum : https://groups.google.com/forum/#!forum/lz4c
  755. ****************************************************************** */
  756. #ifndef FSE_COMMONDEFS_ONLY
  757. /****************************************************************
  758. * Tuning parameters
  759. ****************************************************************/
  760. /* MEMORY_USAGE :
  761. * Memory usage formula : N->2^N Bytes (examples : 10 -> 1KB; 12 -> 4KB ; 16 -> 64KB; 20 -> 1MB; etc.)
  762. * Increasing memory usage improves compression ratio
  763. * Reduced memory usage can improve speed, due to cache effect
  764. * Recommended max value is 14, for 16KB, which nicely fits into Intel x86 L1 cache */
  765. #define FSE_MAX_MEMORY_USAGE 14
  766. #define FSE_DEFAULT_MEMORY_USAGE 13
  767. /* FSE_MAX_SYMBOL_VALUE :
  768. * Maximum symbol value authorized.
  769. * Required for proper stack allocation */
  770. #define FSE_MAX_SYMBOL_VALUE 255
  771. /****************************************************************
  772. * template functions type & suffix
  773. ****************************************************************/
  774. #define FSE_FUNCTION_TYPE BYTE
  775. #define FSE_FUNCTION_EXTENSION
  776. /****************************************************************
  777. * Byte symbol type
  778. ****************************************************************/
  779. #endif /* !FSE_COMMONDEFS_ONLY */
  780. /****************************************************************
  781. * Compiler specifics
  782. ****************************************************************/
  783. #ifdef _MSC_VER /* Visual Studio */
  784. # define FORCE_INLINE static __forceinline
  785. # include <intrin.h> /* For Visual 2005 */
  786. # pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */
  787. # pragma warning(disable : 4214) /* disable: C4214: non-int bitfields */
  788. #else
  789. # if defined (__cplusplus) || defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* C99 */
  790. # ifdef __GNUC__
  791. # define FORCE_INLINE static inline __attribute__((always_inline))
  792. # else
  793. # define FORCE_INLINE static inline
  794. # endif
  795. # else
  796. # define FORCE_INLINE static
  797. # endif /* __STDC_VERSION__ */
  798. #endif
  799. /****************************************************************
  800. * Includes
  801. ****************************************************************/
  802. #include <stdlib.h> /* malloc, free, qsort */
  803. #include <string.h> /* memcpy, memset */
  804. #include <stdio.h> /* printf (debug) */
  805. /****************************************************************
  806. * Constants
  807. *****************************************************************/
  808. #define FSE_MAX_TABLELOG (FSE_MAX_MEMORY_USAGE-2)
  809. #define FSE_MAX_TABLESIZE (1U<<FSE_MAX_TABLELOG)
  810. #define FSE_MAXTABLESIZE_MASK (FSE_MAX_TABLESIZE-1)
  811. #define FSE_DEFAULT_TABLELOG (FSE_DEFAULT_MEMORY_USAGE-2)
  812. #define FSE_MIN_TABLELOG 5
  813. #define FSE_TABLELOG_ABSOLUTE_MAX 15
  814. #if FSE_MAX_TABLELOG > FSE_TABLELOG_ABSOLUTE_MAX
  815. #error "FSE_MAX_TABLELOG > FSE_TABLELOG_ABSOLUTE_MAX is not supported"
  816. #endif
  817. /****************************************************************
  818. * Error Management
  819. ****************************************************************/
  820. #define FSE_STATIC_ASSERT(c) { enum { FSE_static_assert = 1/(int)(!!(c)) }; } /* use only *after* variable declarations */
  821. /****************************************************************
  822. * Complex types
  823. ****************************************************************/
  824. typedef U32 DTable_max_t[FSE_DTABLE_SIZE_U32(FSE_MAX_TABLELOG)];
  825. /****************************************************************
  826. * Templates
  827. ****************************************************************/
  828. /*
  829. designed to be included
  830. for type-specific functions (template emulation in C)
  831. Objective is to write these functions only once, for improved maintenance
  832. */
  833. /* safety checks */
  834. #ifndef FSE_FUNCTION_EXTENSION
  835. # error "FSE_FUNCTION_EXTENSION must be defined"
  836. #endif
  837. #ifndef FSE_FUNCTION_TYPE
  838. # error "FSE_FUNCTION_TYPE must be defined"
  839. #endif
  840. /* Function names */
  841. #define FSE_CAT(X,Y) X##Y
  842. #define FSE_FUNCTION_NAME(X,Y) FSE_CAT(X,Y)
  843. #define FSE_TYPE_NAME(X,Y) FSE_CAT(X,Y)
  844. /* Function templates */
  845. #define FSE_DECODE_TYPE FSE_decode_t
  846. static U32 FSE_tableStep(U32 tableSize) { return (tableSize>>1) + (tableSize>>3) + 3; }
  847. static size_t FSE_buildDTable
  848. (FSE_DTable* dt, const short* normalizedCounter, unsigned maxSymbolValue, unsigned tableLog)
  849. {
  850. void* ptr = dt+1;
  851. FSE_DTableHeader DTableH;
  852. FSE_DECODE_TYPE* const tableDecode = (FSE_DECODE_TYPE*)ptr;
  853. const U32 tableSize = 1 << tableLog;
  854. const U32 tableMask = tableSize-1;
  855. const U32 step = FSE_tableStep(tableSize);
  856. U16 symbolNext[FSE_MAX_SYMBOL_VALUE+1];
  857. U32 position = 0;
  858. U32 highThreshold = tableSize-1;
  859. const S16 largeLimit= (S16)(1 << (tableLog-1));
  860. U32 noLarge = 1;
  861. U32 s;
  862. /* Sanity Checks */
  863. if (maxSymbolValue > FSE_MAX_SYMBOL_VALUE) return ERROR(maxSymbolValue_tooLarge);
  864. if (tableLog > FSE_MAX_TABLELOG) return ERROR(tableLog_tooLarge);
  865. /* Init, lay down lowprob symbols */
  866. DTableH.tableLog = (U16)tableLog;
  867. for (s=0; s<=maxSymbolValue; s++)
  868. {
  869. if (normalizedCounter[s]==-1)
  870. {
  871. tableDecode[highThreshold--].symbol = (FSE_FUNCTION_TYPE)s;
  872. symbolNext[s] = 1;
  873. }
  874. else
  875. {
  876. if (normalizedCounter[s] >= largeLimit) noLarge=0;
  877. symbolNext[s] = normalizedCounter[s];
  878. }
  879. }
  880. /* Spread symbols */
  881. for (s=0; s<=maxSymbolValue; s++)
  882. {
  883. int i;
  884. for (i=0; i<normalizedCounter[s]; i++)
  885. {
  886. tableDecode[position].symbol = (FSE_FUNCTION_TYPE)s;
  887. position = (position + step) & tableMask;
  888. while (position > highThreshold) position = (position + step) & tableMask; /* lowprob area */
  889. }
  890. }
  891. if (position!=0) return ERROR(GENERIC); /* position must reach all cells once, otherwise normalizedCounter is incorrect */
  892. /* Build Decoding table */
  893. {
  894. U32 i;
  895. for (i=0; i<tableSize; i++)
  896. {
  897. FSE_FUNCTION_TYPE symbol = (FSE_FUNCTION_TYPE)(tableDecode[i].symbol);
  898. U16 nextState = symbolNext[symbol]++;
  899. tableDecode[i].nbBits = (BYTE) (tableLog - BIT_highbit32 ((U32)nextState) );
  900. tableDecode[i].newState = (U16) ( (nextState << tableDecode[i].nbBits) - tableSize);
  901. }
  902. }
  903. DTableH.fastMode = (U16)noLarge;
  904. memcpy(dt, &DTableH, sizeof(DTableH));
  905. return 0;
  906. }
  907. #ifndef FSE_COMMONDEFS_ONLY
  908. /******************************************
  909. * FSE helper functions
  910. ******************************************/
  911. static unsigned FSE_isError(size_t code) { return ERR_isError(code); }
  912. /****************************************************************
  913. * FSE NCount encoding-decoding
  914. ****************************************************************/
  915. static short FSE_abs(short a)
  916. {
  917. return a<0 ? -a : a;
  918. }
  919. static size_t FSE_readNCount (short* normalizedCounter, unsigned* maxSVPtr, unsigned* tableLogPtr,
  920. const void* headerBuffer, size_t hbSize)
  921. {
  922. const BYTE* const istart = (const BYTE*) headerBuffer;
  923. const BYTE* const iend = istart + hbSize;
  924. const BYTE* ip = istart;
  925. int nbBits;
  926. int remaining;
  927. int threshold;
  928. U32 bitStream;
  929. int bitCount;
  930. unsigned charnum = 0;
  931. int previous0 = 0;
  932. if (hbSize < 4) return ERROR(srcSize_wrong);
  933. bitStream = MEM_readLE32(ip);
  934. nbBits = (bitStream & 0xF) + FSE_MIN_TABLELOG; /* extract tableLog */
  935. if (nbBits > FSE_TABLELOG_ABSOLUTE_MAX) return ERROR(tableLog_tooLarge);
  936. bitStream >>= 4;
  937. bitCount = 4;
  938. *tableLogPtr = nbBits;
  939. remaining = (1<<nbBits)+1;
  940. threshold = 1<<nbBits;
  941. nbBits++;
  942. while ((remaining>1) && (charnum<=*maxSVPtr))
  943. {
  944. if (previous0)
  945. {
  946. unsigned n0 = charnum;
  947. while ((bitStream & 0xFFFF) == 0xFFFF)
  948. {
  949. n0+=24;
  950. if (ip < iend-5)
  951. {
  952. ip+=2;
  953. bitStream = MEM_readLE32(ip) >> bitCount;
  954. }
  955. else
  956. {
  957. bitStream >>= 16;
  958. bitCount+=16;
  959. }
  960. }
  961. while ((bitStream & 3) == 3)
  962. {
  963. n0+=3;
  964. bitStream>>=2;
  965. bitCount+=2;
  966. }
  967. n0 += bitStream & 3;
  968. bitCount += 2;
  969. if (n0 > *maxSVPtr) return ERROR(maxSymbolValue_tooSmall);
  970. while (charnum < n0) normalizedCounter[charnum++] = 0;
  971. if ((ip <= iend-7) || (ip + (bitCount>>3) <= iend-4))
  972. {
  973. ip += bitCount>>3;
  974. bitCount &= 7;
  975. bitStream = MEM_readLE32(ip) >> bitCount;
  976. }
  977. else
  978. bitStream >>= 2;
  979. }
  980. {
  981. const short max = (short)((2*threshold-1)-remaining);
  982. short count;
  983. if ((bitStream & (threshold-1)) < (U32)max)
  984. {
  985. count = (short)(bitStream & (threshold-1));
  986. bitCount += nbBits-1;
  987. }
  988. else
  989. {
  990. count = (short)(bitStream & (2*threshold-1));
  991. if (count >= threshold) count -= max;
  992. bitCount += nbBits;
  993. }
  994. count--; /* extra accuracy */
  995. remaining -= FSE_abs(count);
  996. normalizedCounter[charnum++] = count;
  997. previous0 = !count;
  998. while (remaining < threshold)
  999. {
  1000. nbBits--;
  1001. threshold >>= 1;
  1002. }
  1003. {
  1004. if ((ip <= iend-7) || (ip + (bitCount>>3) <= iend-4))
  1005. {
  1006. ip += bitCount>>3;
  1007. bitCount &= 7;
  1008. }
  1009. else
  1010. {
  1011. bitCount -= (int)(8 * (iend - 4 - ip));
  1012. ip = iend - 4;
  1013. }
  1014. bitStream = MEM_readLE32(ip) >> (bitCount & 31);
  1015. }
  1016. }
  1017. }
  1018. if (remaining != 1) return ERROR(GENERIC);
  1019. *maxSVPtr = charnum-1;
  1020. ip += (bitCount+7)>>3;
  1021. if ((size_t)(ip-istart) > hbSize) return ERROR(srcSize_wrong);
  1022. return ip-istart;
  1023. }
  1024. /*********************************************************
  1025. * Decompression (Byte symbols)
  1026. *********************************************************/
  1027. static size_t FSE_buildDTable_rle (FSE_DTable* dt, BYTE symbolValue)
  1028. {
  1029. void* ptr = dt;
  1030. FSE_DTableHeader* const DTableH = (FSE_DTableHeader*)ptr;
  1031. FSE_decode_t* const cell = (FSE_decode_t*)(ptr) + 1;
  1032. DTableH->tableLog = 0;
  1033. DTableH->fastMode = 0;
  1034. cell->newState = 0;
  1035. cell->symbol = symbolValue;
  1036. cell->nbBits = 0;
  1037. return 0;
  1038. }
  1039. static size_t FSE_buildDTable_raw (FSE_DTable* dt, unsigned nbBits)
  1040. {
  1041. void* ptr = dt;
  1042. FSE_DTableHeader* const DTableH = (FSE_DTableHeader*)ptr;
  1043. FSE_decode_t* const dinfo = (FSE_decode_t*)(ptr) + 1;
  1044. const unsigned tableSize = 1 << nbBits;
  1045. const unsigned tableMask = tableSize - 1;
  1046. const unsigned maxSymbolValue = tableMask;
  1047. unsigned s;
  1048. /* Sanity checks */
  1049. if (nbBits < 1) return ERROR(GENERIC); /* min size */
  1050. /* Build Decoding Table */
  1051. DTableH->tableLog = (U16)nbBits;
  1052. DTableH->fastMode = 1;
  1053. for (s=0; s<=maxSymbolValue; s++)
  1054. {
  1055. dinfo[s].newState = 0;
  1056. dinfo[s].symbol = (BYTE)s;
  1057. dinfo[s].nbBits = (BYTE)nbBits;
  1058. }
  1059. return 0;
  1060. }
  1061. FORCE_INLINE size_t FSE_decompress_usingDTable_generic(
  1062. void* dst, size_t maxDstSize,
  1063. const void* cSrc, size_t cSrcSize,
  1064. const FSE_DTable* dt, const unsigned fast)
  1065. {
  1066. BYTE* const ostart = (BYTE*) dst;
  1067. BYTE* op = ostart;
  1068. BYTE* const omax = op + maxDstSize;
  1069. BYTE* const olimit = omax-3;
  1070. BIT_DStream_t bitD;
  1071. FSE_DState_t state1;
  1072. FSE_DState_t state2;
  1073. size_t errorCode;
  1074. /* Init */
  1075. errorCode = BIT_initDStream(&bitD, cSrc, cSrcSize); /* replaced last arg by maxCompressed Size */
  1076. if (FSE_isError(errorCode)) return errorCode;
  1077. FSE_initDState(&state1, &bitD, dt);
  1078. FSE_initDState(&state2, &bitD, dt);
  1079. #define FSE_GETSYMBOL(statePtr) fast ? FSE_decodeSymbolFast(statePtr, &bitD) : FSE_decodeSymbol(statePtr, &bitD)
  1080. /* 4 symbols per loop */
  1081. for ( ; (BIT_reloadDStream(&bitD)==BIT_DStream_unfinished) && (op<olimit) ; op+=4)
  1082. {
  1083. op[0] = FSE_GETSYMBOL(&state1);
  1084. if (FSE_MAX_TABLELOG*2+7 > sizeof(bitD.bitContainer)*8) /* This test must be static */
  1085. BIT_reloadDStream(&bitD);
  1086. op[1] = FSE_GETSYMBOL(&state2);
  1087. if (FSE_MAX_TABLELOG*4+7 > sizeof(bitD.bitContainer)*8) /* This test must be static */
  1088. { if (BIT_reloadDStream(&bitD) > BIT_DStream_unfinished) { op+=2; break; } }
  1089. op[2] = FSE_GETSYMBOL(&state1);
  1090. if (FSE_MAX_TABLELOG*2+7 > sizeof(bitD.bitContainer)*8) /* This test must be static */
  1091. BIT_reloadDStream(&bitD);
  1092. op[3] = FSE_GETSYMBOL(&state2);
  1093. }
  1094. /* tail */
  1095. /* note : BIT_reloadDStream(&bitD) >= FSE_DStream_partiallyFilled; Ends at exactly BIT_DStream_completed */
  1096. while (1)
  1097. {
  1098. if ( (BIT_reloadDStream(&bitD)>BIT_DStream_completed) || (op==omax) || (BIT_endOfDStream(&bitD) && (fast || FSE_endOfDState(&state1))) )
  1099. break;
  1100. *op++ = FSE_GETSYMBOL(&state1);
  1101. if ( (BIT_reloadDStream(&bitD)>BIT_DStream_completed) || (op==omax) || (BIT_endOfDStream(&bitD) && (fast || FSE_endOfDState(&state2))) )
  1102. break;
  1103. *op++ = FSE_GETSYMBOL(&state2);
  1104. }
  1105. /* end ? */
  1106. if (BIT_endOfDStream(&bitD) && FSE_endOfDState(&state1) && FSE_endOfDState(&state2))
  1107. return op-ostart;
  1108. if (op==omax) return ERROR(dstSize_tooSmall); /* dst buffer is full, but cSrc unfinished */
  1109. return ERROR(corruption_detected);
  1110. }
  1111. static size_t FSE_decompress_usingDTable(void* dst, size_t originalSize,
  1112. const void* cSrc, size_t cSrcSize,
  1113. const FSE_DTable* dt)
  1114. {
  1115. FSE_DTableHeader DTableH;
  1116. memcpy(&DTableH, dt, sizeof(DTableH));
  1117. /* select fast mode (static) */
  1118. if (DTableH.fastMode) return FSE_decompress_usingDTable_generic(dst, originalSize, cSrc, cSrcSize, dt, 1);
  1119. return FSE_decompress_usingDTable_generic(dst, originalSize, cSrc, cSrcSize, dt, 0);
  1120. }
  1121. static size_t FSE_decompress(void* dst, size_t maxDstSize, const void* cSrc, size_t cSrcSize)
  1122. {
  1123. const BYTE* const istart = (const BYTE*)cSrc;
  1124. const BYTE* ip = istart;
  1125. short counting[FSE_MAX_SYMBOL_VALUE+1];
  1126. DTable_max_t dt; /* Static analyzer seems unable to understand this table will be properly initialized later */
  1127. unsigned tableLog;
  1128. unsigned maxSymbolValue = FSE_MAX_SYMBOL_VALUE;
  1129. size_t errorCode;
  1130. if (cSrcSize<2) return ERROR(srcSize_wrong); /* too small input size */
  1131. /* normal FSE decoding mode */
  1132. errorCode = FSE_readNCount (counting, &maxSymbolValue, &tableLog, istart, cSrcSize);
  1133. if (FSE_isError(errorCode)) return errorCode;
  1134. if (errorCode >= cSrcSize) return ERROR(srcSize_wrong); /* too small input size */
  1135. ip += errorCode;
  1136. cSrcSize -= errorCode;
  1137. errorCode = FSE_buildDTable (dt, counting, maxSymbolValue, tableLog);
  1138. if (FSE_isError(errorCode)) return errorCode;
  1139. /* always return, even if it is an error code */
  1140. return FSE_decompress_usingDTable (dst, maxDstSize, ip, cSrcSize, dt);
  1141. }
  1142. #endif /* FSE_COMMONDEFS_ONLY */
  1143. /* ******************************************************************
  1144. Huff0 : Huffman coder, part of New Generation Entropy library
  1145. Copyright (C) 2013-2015, Yann Collet.
  1146. BSD 2-Clause License (https://opensource.org/licenses/bsd-license.php)
  1147. Redistribution and use in source and binary forms, with or without
  1148. modification, are permitted provided that the following conditions are
  1149. met:
  1150. * Redistributions of source code must retain the above copyright
  1151. notice, this list of conditions and the following disclaimer.
  1152. * Redistributions in binary form must reproduce the above
  1153. copyright notice, this list of conditions and the following disclaimer
  1154. in the documentation and/or other materials provided with the
  1155. distribution.
  1156. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  1157. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  1158. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  1159. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  1160. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  1161. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  1162. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  1163. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  1164. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  1165. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  1166. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  1167. You can contact the author at :
  1168. - FSE+Huff0 source repository : https://github.com/Cyan4973/FiniteStateEntropy
  1169. - Public forum : https://groups.google.com/forum/#!forum/lz4c
  1170. ****************************************************************** */
  1171. /****************************************************************
  1172. * Compiler specifics
  1173. ****************************************************************/
  1174. #if defined (__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */)
  1175. /* inline is defined */
  1176. #elif defined(_MSC_VER)
  1177. # pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */
  1178. # define inline __inline
  1179. #else
  1180. # define inline /* disable inline */
  1181. #endif
  1182. /****************************************************************
  1183. * Includes
  1184. ****************************************************************/
  1185. #include <stdlib.h> /* malloc, free, qsort */
  1186. #include <string.h> /* memcpy, memset */
  1187. #include <stdio.h> /* printf (debug) */
  1188. /****************************************************************
  1189. * Error Management
  1190. ****************************************************************/
  1191. #define HUF_STATIC_ASSERT(c) { enum { HUF_static_assert = 1/(int)(!!(c)) }; } /* use only *after* variable declarations */
  1192. /******************************************
  1193. * Helper functions
  1194. ******************************************/
  1195. static unsigned HUF_isError(size_t code) { return ERR_isError(code); }
  1196. #define HUF_ABSOLUTEMAX_TABLELOG 16 /* absolute limit of HUF_MAX_TABLELOG. Beyond that value, code does not work */
  1197. #define HUF_MAX_TABLELOG 12 /* max configured tableLog (for static allocation); can be modified up to HUF_ABSOLUTEMAX_TABLELOG */
  1198. #define HUF_DEFAULT_TABLELOG HUF_MAX_TABLELOG /* tableLog by default, when not specified */
  1199. #define HUF_MAX_SYMBOL_VALUE 255
  1200. #if (HUF_MAX_TABLELOG > HUF_ABSOLUTEMAX_TABLELOG)
  1201. # error "HUF_MAX_TABLELOG is too large !"
  1202. #endif
  1203. /*********************************************************
  1204. * Huff0 : Huffman block decompression
  1205. *********************************************************/
  1206. typedef struct { BYTE byte; BYTE nbBits; } HUF_DEltX2; /* single-symbol decoding */
  1207. typedef struct { U16 sequence; BYTE nbBits; BYTE length; } HUF_DEltX4; /* double-symbols decoding */
  1208. typedef struct { BYTE symbol; BYTE weight; } sortedSymbol_t;
  1209. /*! HUF_readStats
  1210. Read compact Huffman tree, saved by HUF_writeCTable
  1211. @huffWeight : destination buffer
  1212. @return : size read from `src`
  1213. */
  1214. static size_t HUF_readStats(BYTE* huffWeight, size_t hwSize, U32* rankStats,
  1215. U32* nbSymbolsPtr, U32* tableLogPtr,
  1216. const void* src, size_t srcSize)
  1217. {
  1218. U32 weightTotal;
  1219. U32 tableLog;
  1220. const BYTE* ip = (const BYTE*) src;
  1221. size_t iSize;
  1222. size_t oSize;
  1223. U32 n;
  1224. if (!srcSize) return ERROR(srcSize_wrong);
  1225. iSize = ip[0];
  1226. //memset(huffWeight, 0, hwSize); /* is not necessary, even though some analyzer complain ... */
  1227. if (iSize >= 128) /* special header */
  1228. {
  1229. if (iSize >= (242)) /* RLE */
  1230. {
  1231. static int l[14] = { 1, 2, 3, 4, 7, 8, 15, 16, 31, 32, 63, 64, 127, 128 };
  1232. oSize = l[iSize-242];
  1233. memset(huffWeight, 1, hwSize);
  1234. iSize = 0;
  1235. }
  1236. else /* Incompressible */
  1237. {
  1238. oSize = iSize - 127;
  1239. iSize = ((oSize+1)/2);
  1240. if (iSize+1 > srcSize) return ERROR(srcSize_wrong);
  1241. if (oSize >= hwSize) return ERROR(corruption_detected);
  1242. ip += 1;
  1243. for (n=0; n<oSize; n+=2)
  1244. {
  1245. huffWeight[n] = ip[n/2] >> 4;
  1246. huffWeight[n+1] = ip[n/2] & 15;
  1247. }
  1248. }
  1249. }
  1250. else /* header compressed with FSE (normal case) */
  1251. {
  1252. if (iSize+1 > srcSize) return ERROR(srcSize_wrong);
  1253. oSize = FSE_decompress(huffWeight, hwSize-1, ip+1, iSize); /* max (hwSize-1) values decoded, as last one is implied */
  1254. if (FSE_isError(oSize)) return oSize;
  1255. }
  1256. /* collect weight stats */
  1257. memset(rankStats, 0, (HUF_ABSOLUTEMAX_TABLELOG + 1) * sizeof(U32));
  1258. weightTotal = 0;
  1259. for (n=0; n<oSize; n++)
  1260. {
  1261. if (huffWeight[n] >= HUF_ABSOLUTEMAX_TABLELOG) return ERROR(corruption_detected);
  1262. rankStats[huffWeight[n]]++;
  1263. weightTotal += (1 << huffWeight[n]) >> 1;
  1264. }
  1265. if (weightTotal == 0) return ERROR(corruption_detected);
  1266. /* get last non-null symbol weight (implied, total must be 2^n) */
  1267. tableLog = BIT_highbit32(weightTotal) + 1;
  1268. if (tableLog > HUF_ABSOLUTEMAX_TABLELOG) return ERROR(corruption_detected);
  1269. {
  1270. U32 total = 1 << tableLog;
  1271. U32 rest = total - weightTotal;
  1272. U32 verif = 1 << BIT_highbit32(rest);
  1273. U32 lastWeight = BIT_highbit32(rest) + 1;
  1274. if (verif != rest) return ERROR(corruption_detected); /* last value must be a clean power of 2 */
  1275. huffWeight[oSize] = (BYTE)lastWeight;
  1276. rankStats[lastWeight]++;
  1277. }
  1278. /* check tree construction validity */
  1279. if ((rankStats[1] < 2) || (rankStats[1] & 1)) return ERROR(corruption_detected); /* by construction : at least 2 elts of rank 1, must be even */
  1280. /* results */
  1281. *nbSymbolsPtr = (U32)(oSize+1);
  1282. *tableLogPtr = tableLog;
  1283. return iSize+1;
  1284. }
  1285. /**************************/
  1286. /* single-symbol decoding */
  1287. /**************************/
  1288. static size_t HUF_readDTableX2 (U16* DTable, const void* src, size_t srcSize)
  1289. {
  1290. BYTE huffWeight[HUF_MAX_SYMBOL_VALUE + 1];
  1291. U32 rankVal[HUF_ABSOLUTEMAX_TABLELOG + 1]; /* large enough for values from 0 to 16 */
  1292. U32 tableLog = 0;
  1293. const BYTE* ip = (const BYTE*) src;
  1294. size_t iSize = ip[0];
  1295. U32 nbSymbols = 0;
  1296. U32 n;
  1297. U32 nextRankStart;
  1298. void* ptr = DTable+1;
  1299. HUF_DEltX2* const dt = (HUF_DEltX2*)(ptr);
  1300. HUF_STATIC_ASSERT(sizeof(HUF_DEltX2) == sizeof(U16)); /* if compilation fails here, assertion is false */
  1301. //memset(huffWeight, 0, sizeof(huffWeight)); /* is not necessary, even though some analyzer complain ... */
  1302. iSize = HUF_readStats(huffWeight, HUF_MAX_SYMBOL_VALUE + 1, rankVal, &nbSymbols, &tableLog, src, srcSize);
  1303. if (HUF_isError(iSize)) return iSize;
  1304. /* check result */
  1305. if (tableLog > DTable[0]) return ERROR(tableLog_tooLarge); /* DTable is too small */
  1306. DTable[0] = (U16)tableLog; /* maybe should separate sizeof DTable, as allocated, from used size of DTable, in case of DTable re-use */
  1307. /* Prepare ranks */
  1308. nextRankStart = 0;
  1309. for (n=1; n<=tableLog; n++)
  1310. {
  1311. U32 current = nextRankStart;
  1312. nextRankStart += (rankVal[n] << (n-1));
  1313. rankVal[n] = current;
  1314. }
  1315. /* fill DTable */
  1316. for (n=0; n<nbSymbols; n++)
  1317. {
  1318. const U32 w = huffWeight[n];
  1319. const U32 length = (1 << w) >> 1;
  1320. U32 i;
  1321. HUF_DEltX2 D;
  1322. D.byte = (BYTE)n; D.nbBits = (BYTE)(tableLog + 1 - w);
  1323. for (i = rankVal[w]; i < rankVal[w] + length; i++)
  1324. dt[i] = D;
  1325. rankVal[w] += length;
  1326. }
  1327. return iSize;
  1328. }
  1329. static BYTE HUF_decodeSymbolX2(BIT_DStream_t* Dstream, const HUF_DEltX2* dt, const U32 dtLog)
  1330. {
  1331. const size_t val = BIT_lookBitsFast(Dstream, dtLog); /* note : dtLog >= 1 */
  1332. const BYTE c = dt[val].byte;
  1333. BIT_skipBits(Dstream, dt[val].nbBits);
  1334. return c;
  1335. }
  1336. #define HUF_DECODE_SYMBOLX2_0(ptr, DStreamPtr) \
  1337. *ptr++ = HUF_decodeSymbolX2(DStreamPtr, dt, dtLog)
  1338. #define HUF_DECODE_SYMBOLX2_1(ptr, DStreamPtr) \
  1339. if (MEM_64bits() || (HUF_MAX_TABLELOG<=12)) \
  1340. HUF_DECODE_SYMBOLX2_0(ptr, DStreamPtr)
  1341. #define HUF_DECODE_SYMBOLX2_2(ptr, DStreamPtr) \
  1342. if (MEM_64bits()) \
  1343. HUF_DECODE_SYMBOLX2_0(ptr, DStreamPtr)
  1344. static inline size_t HUF_decodeStreamX2(BYTE* p, BIT_DStream_t* const bitDPtr, BYTE* const pEnd, const HUF_DEltX2* const dt, const U32 dtLog)
  1345. {
  1346. BYTE* const pStart = p;
  1347. /* up to 4 symbols at a time */
  1348. while ((BIT_reloadDStream(bitDPtr) == BIT_DStream_unfinished) && (p <= pEnd-4))
  1349. {
  1350. HUF_DECODE_SYMBOLX2_2(p, bitDPtr);
  1351. HUF_DECODE_SYMBOLX2_1(p, bitDPtr);
  1352. HUF_DECODE_SYMBOLX2_2(p, bitDPtr);
  1353. HUF_DECODE_SYMBOLX2_0(p, bitDPtr);
  1354. }
  1355. /* closer to the end */
  1356. while ((BIT_reloadDStream(bitDPtr) == BIT_DStream_unfinished) && (p < pEnd))
  1357. HUF_DECODE_SYMBOLX2_0(p, bitDPtr);
  1358. /* no more data to retrieve from bitstream, hence no need to reload */
  1359. while (p < pEnd)
  1360. HUF_DECODE_SYMBOLX2_0(p, bitDPtr);
  1361. return pEnd-pStart;
  1362. }
  1363. static size_t HUF_decompress4X2_usingDTable(
  1364. void* dst, size_t dstSize,
  1365. const void* cSrc, size_t cSrcSize,
  1366. const U16* DTable)
  1367. {
  1368. if (cSrcSize < 10) return ERROR(corruption_detected); /* strict minimum : jump table + 1 byte per stream */
  1369. {
  1370. const BYTE* const istart = (const BYTE*) cSrc;
  1371. BYTE* const ostart = (BYTE*) dst;
  1372. BYTE* const oend = ostart + dstSize;
  1373. const void* ptr = DTable;
  1374. const HUF_DEltX2* const dt = ((const HUF_DEltX2*)ptr) +1;
  1375. const U32 dtLog = DTable[0];
  1376. size_t errorCode;
  1377. /* Init */
  1378. BIT_DStream_t bitD1;
  1379. BIT_DStream_t bitD2;
  1380. BIT_DStream_t bitD3;
  1381. BIT_DStream_t bitD4;
  1382. const size_t length1 = MEM_readLE16(istart);
  1383. const size_t length2 = MEM_readLE16(istart+2);
  1384. const size_t length3 = MEM_readLE16(istart+4);
  1385. size_t length4;
  1386. const BYTE* const istart1 = istart + 6; /* jumpTable */
  1387. const BYTE* const istart2 = istart1 + length1;
  1388. const BYTE* const istart3 = istart2 + length2;
  1389. const BYTE* const istart4 = istart3 + length3;
  1390. const size_t segmentSize = (dstSize+3) / 4;
  1391. BYTE* const opStart2 = ostart + segmentSize;
  1392. BYTE* const opStart3 = opStart2 + segmentSize;
  1393. BYTE* const opStart4 = opStart3 + segmentSize;
  1394. BYTE* op1 = ostart;
  1395. BYTE* op2 = opStart2;
  1396. BYTE* op3 = opStart3;
  1397. BYTE* op4 = opStart4;
  1398. U32 endSignal;
  1399. length4 = cSrcSize - (length1 + length2 + length3 + 6);
  1400. if (length4 > cSrcSize) return ERROR(corruption_detected); /* overflow */
  1401. errorCode = BIT_initDStream(&bitD1, istart1, length1);
  1402. if (HUF_isError(errorCode)) return errorCode;
  1403. errorCode = BIT_initDStream(&bitD2, istart2, length2);
  1404. if (HUF_isError(errorCode)) return errorCode;
  1405. errorCode = BIT_initDStream(&bitD3, istart3, length3);
  1406. if (HUF_isError(errorCode)) return errorCode;
  1407. errorCode = BIT_initDStream(&bitD4, istart4, length4);
  1408. if (HUF_isError(errorCode)) return errorCode;
  1409. /* 16-32 symbols per loop (4-8 symbols per stream) */
  1410. endSignal = BIT_reloadDStream(&bitD1) | BIT_reloadDStream(&bitD2) | BIT_reloadDStream(&bitD3) | BIT_reloadDStream(&bitD4);
  1411. for ( ; (endSignal==BIT_DStream_unfinished) && (op4<(oend-7)) ; )
  1412. {
  1413. HUF_DECODE_SYMBOLX2_2(op1, &bitD1);
  1414. HUF_DECODE_SYMBOLX2_2(op2, &bitD2);
  1415. HUF_DECODE_SYMBOLX2_2(op3, &bitD3);
  1416. HUF_DECODE_SYMBOLX2_2(op4, &bitD4);
  1417. HUF_DECODE_SYMBOLX2_1(op1, &bitD1);
  1418. HUF_DECODE_SYMBOLX2_1(op2, &bitD2);
  1419. HUF_DECODE_SYMBOLX2_1(op3, &bitD3);
  1420. HUF_DECODE_SYMBOLX2_1(op4, &bitD4);
  1421. HUF_DECODE_SYMBOLX2_2(op1, &bitD1);
  1422. HUF_DECODE_SYMBOLX2_2(op2, &bitD2);
  1423. HUF_DECODE_SYMBOLX2_2(op3, &bitD3);
  1424. HUF_DECODE_SYMBOLX2_2(op4, &bitD4);
  1425. HUF_DECODE_SYMBOLX2_0(op1, &bitD1);
  1426. HUF_DECODE_SYMBOLX2_0(op2, &bitD2);
  1427. HUF_DECODE_SYMBOLX2_0(op3, &bitD3);
  1428. HUF_DECODE_SYMBOLX2_0(op4, &bitD4);
  1429. endSignal = BIT_reloadDStream(&bitD1) | BIT_reloadDStream(&bitD2) | BIT_reloadDStream(&bitD3) | BIT_reloadDStream(&bitD4);
  1430. }
  1431. /* check corruption */
  1432. if (op1 > opStart2) return ERROR(corruption_detected);
  1433. if (op2 > opStart3) return ERROR(corruption_detected);
  1434. if (op3 > opStart4) return ERROR(corruption_detected);
  1435. /* note : op4 supposed already verified within main loop */
  1436. /* finish bitStreams one by one */
  1437. HUF_decodeStreamX2(op1, &bitD1, opStart2, dt, dtLog);
  1438. HUF_decodeStreamX2(op2, &bitD2, opStart3, dt, dtLog);
  1439. HUF_decodeStreamX2(op3, &bitD3, opStart4, dt, dtLog);
  1440. HUF_decodeStreamX2(op4, &bitD4, oend, dt, dtLog);
  1441. /* check */
  1442. endSignal = BIT_endOfDStream(&bitD1) & BIT_endOfDStream(&bitD2) & BIT_endOfDStream(&bitD3) & BIT_endOfDStream(&bitD4);
  1443. if (!endSignal) return ERROR(corruption_detected);
  1444. /* decoded size */
  1445. return dstSize;
  1446. }
  1447. }
  1448. static size_t HUF_decompress4X2 (void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize)
  1449. {
  1450. HUF_CREATE_STATIC_DTABLEX2(DTable, HUF_MAX_TABLELOG);
  1451. const BYTE* ip = (const BYTE*) cSrc;
  1452. size_t errorCode;
  1453. errorCode = HUF_readDTableX2 (DTable, cSrc, cSrcSize);
  1454. if (HUF_isError(errorCode)) return errorCode;
  1455. if (errorCode >= cSrcSize) return ERROR(srcSize_wrong);
  1456. ip += errorCode;
  1457. cSrcSize -= errorCode;
  1458. return HUF_decompress4X2_usingDTable (dst, dstSize, ip, cSrcSize, DTable);
  1459. }
  1460. /***************************/
  1461. /* double-symbols decoding */
  1462. /***************************/
  1463. static void HUF_fillDTableX4Level2(HUF_DEltX4* DTable, U32 sizeLog, const U32 consumed,
  1464. const U32* rankValOrigin, const int minWeight,
  1465. const sortedSymbol_t* sortedSymbols, const U32 sortedListSize,
  1466. U32 nbBitsBaseline, U16 baseSeq)
  1467. {
  1468. HUF_DEltX4 DElt;
  1469. U32 rankVal[HUF_ABSOLUTEMAX_TABLELOG + 1];
  1470. U32 s;
  1471. /* get pre-calculated rankVal */
  1472. memcpy(rankVal, rankValOrigin, sizeof(rankVal));
  1473. /* fill skipped values */
  1474. if (minWeight>1)
  1475. {
  1476. U32 i, skipSize = rankVal[minWeight];
  1477. MEM_writeLE16(&(DElt.sequence), baseSeq);
  1478. DElt.nbBits = (BYTE)(consumed);
  1479. DElt.length = 1;
  1480. for (i = 0; i < skipSize; i++)
  1481. DTable[i] = DElt;
  1482. }
  1483. /* fill DTable */
  1484. for (s=0; s<sortedListSize; s++) /* note : sortedSymbols already skipped */
  1485. {
  1486. const U32 symbol = sortedSymbols[s].symbol;
  1487. const U32 weight = sortedSymbols[s].weight;
  1488. const U32 nbBits = nbBitsBaseline - weight;
  1489. const U32 length = 1 << (sizeLog-nbBits);
  1490. const U32 start = rankVal[weight];
  1491. U32 i = start;
  1492. const U32 end = start + length;
  1493. MEM_writeLE16(&(DElt.sequence), (U16)(baseSeq + (symbol << 8)));
  1494. DElt.nbBits = (BYTE)(nbBits + consumed);
  1495. DElt.length = 2;
  1496. do { DTable[i++] = DElt; } while (i<end); /* since length >= 1 */
  1497. rankVal[weight] += length;
  1498. }
  1499. }
  1500. typedef U32 rankVal_t[HUF_ABSOLUTEMAX_TABLELOG][HUF_ABSOLUTEMAX_TABLELOG + 1];
  1501. static void HUF_fillDTableX4(HUF_DEltX4* DTable, const U32 targetLog,
  1502. const sortedSymbol_t* sortedList, const U32 sortedListSize,
  1503. const U32* rankStart, rankVal_t rankValOrigin, const U32 maxWeight,
  1504. const U32 nbBitsBaseline)
  1505. {
  1506. U32 rankVal[HUF_ABSOLUTEMAX_TABLELOG + 1];
  1507. const int scaleLog = nbBitsBaseline - targetLog; /* note : targetLog >= srcLog, hence scaleLog <= 1 */
  1508. const U32 minBits = nbBitsBaseline - maxWeight;
  1509. U32 s;
  1510. memcpy(rankVal, rankValOrigin, sizeof(rankVal));
  1511. /* fill DTable */
  1512. for (s=0; s<sortedListSize; s++)
  1513. {
  1514. const U16 symbol = sortedList[s].symbol;
  1515. const U32 weight = sortedList[s].weight;
  1516. const U32 nbBits = nbBitsBaseline - weight;
  1517. const U32 start = rankVal[weight];
  1518. const U32 length = 1 << (targetLog-nbBits);
  1519. if (targetLog-nbBits >= minBits) /* enough room for a second symbol */
  1520. {
  1521. U32 sortedRank;
  1522. int minWeight = nbBits + scaleLog;
  1523. if (minWeight < 1) minWeight = 1;
  1524. sortedRank = rankStart[minWeight];
  1525. HUF_fillDTableX4Level2(DTable+start, targetLog-nbBits, nbBits,
  1526. rankValOrigin[nbBits], minWeight,
  1527. sortedList+sortedRank, sortedListSize-sortedRank,
  1528. nbBitsBaseline, symbol);
  1529. }
  1530. else
  1531. {
  1532. U32 i;
  1533. const U32 end = start + length;
  1534. HUF_DEltX4 DElt;
  1535. MEM_writeLE16(&(DElt.sequence), symbol);
  1536. DElt.nbBits = (BYTE)(nbBits);
  1537. DElt.length = 1;
  1538. for (i = start; i < end; i++)
  1539. DTable[i] = DElt;
  1540. }
  1541. rankVal[weight] += length;
  1542. }
  1543. }
  1544. static size_t HUF_readDTableX4 (U32* DTable, const void* src, size_t srcSize)
  1545. {
  1546. BYTE weightList[HUF_MAX_SYMBOL_VALUE + 1];
  1547. sortedSymbol_t sortedSymbol[HUF_MAX_SYMBOL_VALUE + 1];
  1548. U32 rankStats[HUF_ABSOLUTEMAX_TABLELOG + 1] = { 0 };
  1549. U32 rankStart0[HUF_ABSOLUTEMAX_TABLELOG + 2] = { 0 };
  1550. U32* const rankStart = rankStart0+1;
  1551. rankVal_t rankVal;
  1552. U32 tableLog, maxW, sizeOfSort, nbSymbols;
  1553. const U32 memLog = DTable[0];
  1554. const BYTE* ip = (const BYTE*) src;
  1555. size_t iSize = ip[0];
  1556. void* ptr = DTable;
  1557. HUF_DEltX4* const dt = ((HUF_DEltX4*)ptr) + 1;
  1558. HUF_STATIC_ASSERT(sizeof(HUF_DEltX4) == sizeof(U32)); /* if compilation fails here, assertion is false */
  1559. if (memLog > HUF_ABSOLUTEMAX_TABLELOG) return ERROR(tableLog_tooLarge);
  1560. //memset(weightList, 0, sizeof(weightList)); /* is not necessary, even though some analyzer complain ... */
  1561. iSize = HUF_readStats(weightList, HUF_MAX_SYMBOL_VALUE + 1, rankStats, &nbSymbols, &tableLog, src, srcSize);
  1562. if (HUF_isError(iSize)) return iSize;
  1563. /* check result */
  1564. if (tableLog > memLog) return ERROR(tableLog_tooLarge); /* DTable can't fit code depth */
  1565. /* find maxWeight */
  1566. for (maxW = tableLog; rankStats[maxW]==0; maxW--)
  1567. { if (!maxW) return ERROR(GENERIC); } /* necessarily finds a solution before maxW==0 */
  1568. /* Get start index of each weight */
  1569. {
  1570. U32 w, nextRankStart = 0;
  1571. for (w=1; w<=maxW; w++)
  1572. {
  1573. U32 current = nextRankStart;
  1574. nextRankStart += rankStats[w];
  1575. rankStart[w] = current;
  1576. }
  1577. rankStart[0] = nextRankStart; /* put all 0w symbols at the end of sorted list*/
  1578. sizeOfSort = nextRankStart;
  1579. }
  1580. /* sort symbols by weight */
  1581. {
  1582. U32 s;
  1583. for (s=0; s<nbSymbols; s++)
  1584. {
  1585. U32 w = weightList[s];
  1586. U32 r = rankStart[w]++;
  1587. sortedSymbol[r].symbol = (BYTE)s;
  1588. sortedSymbol[r].weight = (BYTE)w;
  1589. }
  1590. rankStart[0] = 0; /* forget 0w symbols; this is beginning of weight(1) */
  1591. }
  1592. /* Build rankVal */
  1593. {
  1594. const U32 minBits = tableLog+1 - maxW;
  1595. U32 nextRankVal = 0;
  1596. U32 w, consumed;
  1597. const int rescale = (memLog-tableLog) - 1; /* tableLog <= memLog */
  1598. U32* rankVal0 = rankVal[0];
  1599. for (w=1; w<=maxW; w++)
  1600. {
  1601. U32 current = nextRankVal;
  1602. nextRankVal += rankStats[w] << (w+rescale);
  1603. rankVal0[w] = current;
  1604. }
  1605. for (consumed = minBits; consumed <= memLog - minBits; consumed++)
  1606. {
  1607. U32* rankValPtr = rankVal[consumed];
  1608. for (w = 1; w <= maxW; w++)
  1609. {
  1610. rankValPtr[w] = rankVal0[w] >> consumed;
  1611. }
  1612. }
  1613. }
  1614. HUF_fillDTableX4(dt, memLog,
  1615. sortedSymbol, sizeOfSort,
  1616. rankStart0, rankVal, maxW,
  1617. tableLog+1);
  1618. return iSize;
  1619. }
  1620. static U32 HUF_decodeSymbolX4(void* op, BIT_DStream_t* DStream, const HUF_DEltX4* dt, const U32 dtLog)
  1621. {
  1622. const size_t val = BIT_lookBitsFast(DStream, dtLog); /* note : dtLog >= 1 */
  1623. memcpy(op, dt+val, 2);
  1624. BIT_skipBits(DStream, dt[val].nbBits);
  1625. return dt[val].length;
  1626. }
  1627. static U32 HUF_decodeLastSymbolX4(void* op, BIT_DStream_t* DStream, const HUF_DEltX4* dt, const U32 dtLog)
  1628. {
  1629. const size_t val = BIT_lookBitsFast(DStream, dtLog); /* note : dtLog >= 1 */
  1630. memcpy(op, dt+val, 1);
  1631. if (dt[val].length==1) BIT_skipBits(DStream, dt[val].nbBits);
  1632. else
  1633. {
  1634. if (DStream->bitsConsumed < (sizeof(DStream->bitContainer)*8))
  1635. {
  1636. BIT_skipBits(DStream, dt[val].nbBits);
  1637. if (DStream->bitsConsumed > (sizeof(DStream->bitContainer)*8))
  1638. 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 */
  1639. }
  1640. }
  1641. return 1;
  1642. }
  1643. #define HUF_DECODE_SYMBOLX4_0(ptr, DStreamPtr) \
  1644. ptr += HUF_decodeSymbolX4(ptr, DStreamPtr, dt, dtLog)
  1645. #define HUF_DECODE_SYMBOLX4_1(ptr, DStreamPtr) \
  1646. if (MEM_64bits() || (HUF_MAX_TABLELOG<=12)) \
  1647. ptr += HUF_decodeSymbolX4(ptr, DStreamPtr, dt, dtLog)
  1648. #define HUF_DECODE_SYMBOLX4_2(ptr, DStreamPtr) \
  1649. if (MEM_64bits()) \
  1650. ptr += HUF_decodeSymbolX4(ptr, DStreamPtr, dt, dtLog)
  1651. static inline size_t HUF_decodeStreamX4(BYTE* p, BIT_DStream_t* bitDPtr, BYTE* const pEnd, const HUF_DEltX4* const dt, const U32 dtLog)
  1652. {
  1653. BYTE* const pStart = p;
  1654. /* up to 8 symbols at a time */
  1655. while ((BIT_reloadDStream(bitDPtr) == BIT_DStream_unfinished) && (p < pEnd-7))
  1656. {
  1657. HUF_DECODE_SYMBOLX4_2(p, bitDPtr);
  1658. HUF_DECODE_SYMBOLX4_1(p, bitDPtr);
  1659. HUF_DECODE_SYMBOLX4_2(p, bitDPtr);
  1660. HUF_DECODE_SYMBOLX4_0(p, bitDPtr);
  1661. }
  1662. /* closer to the end */
  1663. while ((BIT_reloadDStream(bitDPtr) == BIT_DStream_unfinished) && (p <= pEnd-2))
  1664. HUF_DECODE_SYMBOLX4_0(p, bitDPtr);
  1665. while (p <= pEnd-2)
  1666. HUF_DECODE_SYMBOLX4_0(p, bitDPtr); /* no need to reload : reached the end of DStream */
  1667. if (p < pEnd)
  1668. p += HUF_decodeLastSymbolX4(p, bitDPtr, dt, dtLog);
  1669. return p-pStart;
  1670. }
  1671. static size_t HUF_decompress4X4_usingDTable(
  1672. void* dst, size_t dstSize,
  1673. const void* cSrc, size_t cSrcSize,
  1674. const U32* DTable)
  1675. {
  1676. if (cSrcSize < 10) return ERROR(corruption_detected); /* strict minimum : jump table + 1 byte per stream */
  1677. {
  1678. const BYTE* const istart = (const BYTE*) cSrc;
  1679. BYTE* const ostart = (BYTE*) dst;
  1680. BYTE* const oend = ostart + dstSize;
  1681. const void* ptr = DTable;
  1682. const HUF_DEltX4* const dt = ((const HUF_DEltX4*)ptr) +1;
  1683. const U32 dtLog = DTable[0];
  1684. size_t errorCode;
  1685. /* Init */
  1686. BIT_DStream_t bitD1;
  1687. BIT_DStream_t bitD2;
  1688. BIT_DStream_t bitD3;
  1689. BIT_DStream_t bitD4;
  1690. const size_t length1 = MEM_readLE16(istart);
  1691. const size_t length2 = MEM_readLE16(istart+2);
  1692. const size_t length3 = MEM_readLE16(istart+4);
  1693. size_t length4;
  1694. const BYTE* const istart1 = istart + 6; /* jumpTable */
  1695. const BYTE* const istart2 = istart1 + length1;
  1696. const BYTE* const istart3 = istart2 + length2;
  1697. const BYTE* const istart4 = istart3 + length3;
  1698. const size_t segmentSize = (dstSize+3) / 4;
  1699. BYTE* const opStart2 = ostart + segmentSize;
  1700. BYTE* const opStart3 = opStart2 + segmentSize;
  1701. BYTE* const opStart4 = opStart3 + segmentSize;
  1702. BYTE* op1 = ostart;
  1703. BYTE* op2 = opStart2;
  1704. BYTE* op3 = opStart3;
  1705. BYTE* op4 = opStart4;
  1706. U32 endSignal;
  1707. length4 = cSrcSize - (length1 + length2 + length3 + 6);
  1708. if (length4 > cSrcSize) return ERROR(corruption_detected); /* overflow */
  1709. errorCode = BIT_initDStream(&bitD1, istart1, length1);
  1710. if (HUF_isError(errorCode)) return errorCode;
  1711. errorCode = BIT_initDStream(&bitD2, istart2, length2);
  1712. if (HUF_isError(errorCode)) return errorCode;
  1713. errorCode = BIT_initDStream(&bitD3, istart3, length3);
  1714. if (HUF_isError(errorCode)) return errorCode;
  1715. errorCode = BIT_initDStream(&bitD4, istart4, length4);
  1716. if (HUF_isError(errorCode)) return errorCode;
  1717. /* 16-32 symbols per loop (4-8 symbols per stream) */
  1718. endSignal = BIT_reloadDStream(&bitD1) | BIT_reloadDStream(&bitD2) | BIT_reloadDStream(&bitD3) | BIT_reloadDStream(&bitD4);
  1719. for ( ; (endSignal==BIT_DStream_unfinished) && (op4<(oend-7)) ; )
  1720. {
  1721. HUF_DECODE_SYMBOLX4_2(op1, &bitD1);
  1722. HUF_DECODE_SYMBOLX4_2(op2, &bitD2);
  1723. HUF_DECODE_SYMBOLX4_2(op3, &bitD3);
  1724. HUF_DECODE_SYMBOLX4_2(op4, &bitD4);
  1725. HUF_DECODE_SYMBOLX4_1(op1, &bitD1);
  1726. HUF_DECODE_SYMBOLX4_1(op2, &bitD2);
  1727. HUF_DECODE_SYMBOLX4_1(op3, &bitD3);
  1728. HUF_DECODE_SYMBOLX4_1(op4, &bitD4);
  1729. HUF_DECODE_SYMBOLX4_2(op1, &bitD1);
  1730. HUF_DECODE_SYMBOLX4_2(op2, &bitD2);
  1731. HUF_DECODE_SYMBOLX4_2(op3, &bitD3);
  1732. HUF_DECODE_SYMBOLX4_2(op4, &bitD4);
  1733. HUF_DECODE_SYMBOLX4_0(op1, &bitD1);
  1734. HUF_DECODE_SYMBOLX4_0(op2, &bitD2);
  1735. HUF_DECODE_SYMBOLX4_0(op3, &bitD3);
  1736. HUF_DECODE_SYMBOLX4_0(op4, &bitD4);
  1737. endSignal = BIT_reloadDStream(&bitD1) | BIT_reloadDStream(&bitD2) | BIT_reloadDStream(&bitD3) | BIT_reloadDStream(&bitD4);
  1738. }
  1739. /* check corruption */
  1740. if (op1 > opStart2) return ERROR(corruption_detected);
  1741. if (op2 > opStart3) return ERROR(corruption_detected);
  1742. if (op3 > opStart4) return ERROR(corruption_detected);
  1743. /* note : op4 supposed already verified within main loop */
  1744. /* finish bitStreams one by one */
  1745. HUF_decodeStreamX4(op1, &bitD1, opStart2, dt, dtLog);
  1746. HUF_decodeStreamX4(op2, &bitD2, opStart3, dt, dtLog);
  1747. HUF_decodeStreamX4(op3, &bitD3, opStart4, dt, dtLog);
  1748. HUF_decodeStreamX4(op4, &bitD4, oend, dt, dtLog);
  1749. /* check */
  1750. endSignal = BIT_endOfDStream(&bitD1) & BIT_endOfDStream(&bitD2) & BIT_endOfDStream(&bitD3) & BIT_endOfDStream(&bitD4);
  1751. if (!endSignal) return ERROR(corruption_detected);
  1752. /* decoded size */
  1753. return dstSize;
  1754. }
  1755. }
  1756. static size_t HUF_decompress4X4 (void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize)
  1757. {
  1758. HUF_CREATE_STATIC_DTABLEX4(DTable, HUF_MAX_TABLELOG);
  1759. const BYTE* ip = (const BYTE*) cSrc;
  1760. size_t hSize = HUF_readDTableX4 (DTable, cSrc, cSrcSize);
  1761. if (HUF_isError(hSize)) return hSize;
  1762. if (hSize >= cSrcSize) return ERROR(srcSize_wrong);
  1763. ip += hSize;
  1764. cSrcSize -= hSize;
  1765. return HUF_decompress4X4_usingDTable (dst, dstSize, ip, cSrcSize, DTable);
  1766. }
  1767. /**********************************/
  1768. /* Generic decompression selector */
  1769. /**********************************/
  1770. typedef struct { U32 tableTime; U32 decode256Time; } algo_time_t;
  1771. static const algo_time_t algoTime[16 /* Quantization */][3 /* single, double, quad */] =
  1772. {
  1773. /* single, double, quad */
  1774. {{0,0}, {1,1}, {2,2}}, /* Q==0 : impossible */
  1775. {{0,0}, {1,1}, {2,2}}, /* Q==1 : impossible */
  1776. {{ 38,130}, {1313, 74}, {2151, 38}}, /* Q == 2 : 12-18% */
  1777. {{ 448,128}, {1353, 74}, {2238, 41}}, /* Q == 3 : 18-25% */
  1778. {{ 556,128}, {1353, 74}, {2238, 47}}, /* Q == 4 : 25-32% */
  1779. {{ 714,128}, {1418, 74}, {2436, 53}}, /* Q == 5 : 32-38% */
  1780. {{ 883,128}, {1437, 74}, {2464, 61}}, /* Q == 6 : 38-44% */
  1781. {{ 897,128}, {1515, 75}, {2622, 68}}, /* Q == 7 : 44-50% */
  1782. {{ 926,128}, {1613, 75}, {2730, 75}}, /* Q == 8 : 50-56% */
  1783. {{ 947,128}, {1729, 77}, {3359, 77}}, /* Q == 9 : 56-62% */
  1784. {{1107,128}, {2083, 81}, {4006, 84}}, /* Q ==10 : 62-69% */
  1785. {{1177,128}, {2379, 87}, {4785, 88}}, /* Q ==11 : 69-75% */
  1786. {{1242,128}, {2415, 93}, {5155, 84}}, /* Q ==12 : 75-81% */
  1787. {{1349,128}, {2644,106}, {5260,106}}, /* Q ==13 : 81-87% */
  1788. {{1455,128}, {2422,124}, {4174,124}}, /* Q ==14 : 87-93% */
  1789. {{ 722,128}, {1891,145}, {1936,146}}, /* Q ==15 : 93-99% */
  1790. };
  1791. typedef size_t (*decompressionAlgo)(void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize);
  1792. static size_t HUF_decompress (void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize)
  1793. {
  1794. static const decompressionAlgo decompress[3] = { HUF_decompress4X2, HUF_decompress4X4, NULL };
  1795. /* estimate decompression time */
  1796. U32 Q;
  1797. const U32 D256 = (U32)(dstSize >> 8);
  1798. U32 Dtime[3];
  1799. U32 algoNb = 0;
  1800. int n;
  1801. /* validation checks */
  1802. if (dstSize == 0) return ERROR(dstSize_tooSmall);
  1803. if (cSrcSize > dstSize) return ERROR(corruption_detected); /* invalid */
  1804. if (cSrcSize == dstSize) { memcpy(dst, cSrc, dstSize); return dstSize; } /* not compressed */
  1805. if (cSrcSize == 1) { memset(dst, *(const BYTE*)cSrc, dstSize); return dstSize; } /* RLE */
  1806. /* decoder timing evaluation */
  1807. Q = (U32)(cSrcSize * 16 / dstSize); /* Q < 16 since dstSize > cSrcSize */
  1808. for (n=0; n<3; n++)
  1809. Dtime[n] = algoTime[Q][n].tableTime + (algoTime[Q][n].decode256Time * D256);
  1810. Dtime[1] += Dtime[1] >> 4; Dtime[2] += Dtime[2] >> 3; /* advantage to algorithms using less memory, for cache eviction */
  1811. if (Dtime[1] < Dtime[0]) algoNb = 1;
  1812. return decompress[algoNb](dst, dstSize, cSrc, cSrcSize);
  1813. //return HUF_decompress4X2(dst, dstSize, cSrc, cSrcSize); /* multi-streams single-symbol decoding */
  1814. //return HUF_decompress4X4(dst, dstSize, cSrc, cSrcSize); /* multi-streams double-symbols decoding */
  1815. //return HUF_decompress4X6(dst, dstSize, cSrc, cSrcSize); /* multi-streams quad-symbols decoding */
  1816. }
  1817. /*
  1818. zstd - standard compression library
  1819. Copyright (C) 2014-2015, Yann Collet.
  1820. BSD 2-Clause License (https://opensource.org/licenses/bsd-license.php)
  1821. Redistribution and use in source and binary forms, with or without
  1822. modification, are permitted provided that the following conditions are
  1823. met:
  1824. * Redistributions of source code must retain the above copyright
  1825. notice, this list of conditions and the following disclaimer.
  1826. * Redistributions in binary form must reproduce the above
  1827. copyright notice, this list of conditions and the following disclaimer
  1828. in the documentation and/or other materials provided with the
  1829. distribution.
  1830. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  1831. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  1832. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  1833. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  1834. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  1835. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  1836. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  1837. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  1838. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  1839. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  1840. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  1841. You can contact the author at :
  1842. - zstd source repository : https://github.com/Cyan4973/zstd
  1843. - ztsd public forum : https://groups.google.com/forum/#!forum/lz4c
  1844. */
  1845. /* ***************************************************************
  1846. * Tuning parameters
  1847. *****************************************************************/
  1848. /*!
  1849. * MEMORY_USAGE :
  1850. * Memory usage formula : N->2^N Bytes (examples : 10 -> 1KB; 12 -> 4KB ; 16 -> 64KB; 20 -> 1MB; etc.)
  1851. * Increasing memory usage improves compression ratio
  1852. * Reduced memory usage can improve speed, due to cache effect
  1853. */
  1854. #define ZSTD_MEMORY_USAGE 17
  1855. /*!
  1856. * HEAPMODE :
  1857. * Select how default compression functions will allocate memory for their hash table,
  1858. * in memory stack (0, fastest), or in memory heap (1, requires malloc())
  1859. * Note that compression context is fairly large, as a consequence heap memory is recommended.
  1860. */
  1861. #ifndef ZSTD_HEAPMODE
  1862. # define ZSTD_HEAPMODE 1
  1863. #endif /* ZSTD_HEAPMODE */
  1864. /*!
  1865. * LEGACY_SUPPORT :
  1866. * decompressor can decode older formats (starting from Zstd 0.1+)
  1867. */
  1868. #ifndef ZSTD_LEGACY_SUPPORT
  1869. # define ZSTD_LEGACY_SUPPORT 1
  1870. #endif
  1871. /* *******************************************************
  1872. * Includes
  1873. *********************************************************/
  1874. #include <stdlib.h> /* calloc */
  1875. #include <string.h> /* memcpy, memmove */
  1876. #include <stdio.h> /* debug : printf */
  1877. /* *******************************************************
  1878. * Compiler specifics
  1879. *********************************************************/
  1880. #ifdef __AVX2__
  1881. # include <immintrin.h> /* AVX2 intrinsics */
  1882. #endif
  1883. #ifdef _MSC_VER /* Visual Studio */
  1884. # include <intrin.h> /* For Visual 2005 */
  1885. # pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */
  1886. # pragma warning(disable : 4324) /* disable: C4324: padded structure */
  1887. #else
  1888. # define GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__)
  1889. #endif
  1890. /* *******************************************************
  1891. * Constants
  1892. *********************************************************/
  1893. #define HASH_LOG (ZSTD_MEMORY_USAGE - 2)
  1894. #define HASH_TABLESIZE (1 << HASH_LOG)
  1895. #define HASH_MASK (HASH_TABLESIZE - 1)
  1896. #define KNUTH 2654435761
  1897. #define BIT7 128
  1898. #define BIT6 64
  1899. #define BIT5 32
  1900. #define BIT4 16
  1901. #define BIT1 2
  1902. #define BIT0 1
  1903. #define KB *(1 <<10)
  1904. #define MB *(1 <<20)
  1905. #define GB *(1U<<30)
  1906. #define BLOCKSIZE (128 KB) /* define, for static allocation */
  1907. #define MIN_SEQUENCES_SIZE (2 /*seqNb*/ + 2 /*dumps*/ + 3 /*seqTables*/ + 1 /*bitStream*/)
  1908. #define MIN_CBLOCK_SIZE (3 /*litCSize*/ + MIN_SEQUENCES_SIZE)
  1909. #define IS_RAW BIT0
  1910. #define IS_RLE BIT1
  1911. #define WORKPLACESIZE (BLOCKSIZE*3)
  1912. #define MINMATCH 4
  1913. #define MLbits 7
  1914. #define LLbits 6
  1915. #define Offbits 5
  1916. #define MaxML ((1<<MLbits )-1)
  1917. #define MaxLL ((1<<LLbits )-1)
  1918. #define MaxOff 31
  1919. #define LitFSELog 11
  1920. #define MLFSELog 10
  1921. #define LLFSELog 10
  1922. #define OffFSELog 9
  1923. #define MAX(a,b) ((a)<(b)?(b):(a))
  1924. #define MaxSeq MAX(MaxLL, MaxML)
  1925. #define LITERAL_NOENTROPY 63
  1926. #define COMMAND_NOENTROPY 7 /* to remove */
  1927. #define ZSTD_CONTENTSIZE_ERROR (0ULL - 2)
  1928. static const size_t ZSTD_blockHeaderSize = 3;
  1929. static const size_t ZSTD_frameHeaderSize = 4;
  1930. /* *******************************************************
  1931. * Memory operations
  1932. **********************************************************/
  1933. static void ZSTD_copy4(void* dst, const void* src) { memcpy(dst, src, 4); }
  1934. static void ZSTD_copy8(void* dst, const void* src) { memcpy(dst, src, 8); }
  1935. #define COPY8(d,s) { ZSTD_copy8(d,s); d+=8; s+=8; }
  1936. /*! ZSTD_wildcopy : custom version of memcpy(), can copy up to 7-8 bytes too many */
  1937. static void ZSTD_wildcopy(void* dst, const void* src, ptrdiff_t length)
  1938. {
  1939. const BYTE* ip = (const BYTE*)src;
  1940. BYTE* op = (BYTE*)dst;
  1941. BYTE* const oend = op + length;
  1942. do COPY8(op, ip) while (op < oend);
  1943. }
  1944. /* **************************************
  1945. * Local structures
  1946. ****************************************/
  1947. typedef enum { bt_compressed, bt_raw, bt_rle, bt_end } blockType_t;
  1948. typedef struct
  1949. {
  1950. blockType_t blockType;
  1951. U32 origSize;
  1952. } blockProperties_t;
  1953. typedef struct {
  1954. void* buffer;
  1955. U32* offsetStart;
  1956. U32* offset;
  1957. BYTE* offCodeStart;
  1958. BYTE* offCode;
  1959. BYTE* litStart;
  1960. BYTE* lit;
  1961. BYTE* litLengthStart;
  1962. BYTE* litLength;
  1963. BYTE* matchLengthStart;
  1964. BYTE* matchLength;
  1965. BYTE* dumpsStart;
  1966. BYTE* dumps;
  1967. } seqStore_t;
  1968. /* *************************************
  1969. * Error Management
  1970. ***************************************/
  1971. /*! ZSTD_isError
  1972. * tells if a return value is an error code */
  1973. static unsigned ZSTD_isError(size_t code) { return ERR_isError(code); }
  1974. /* *************************************************************
  1975. * Decompression section
  1976. ***************************************************************/
  1977. struct ZSTDv03_Dctx_s
  1978. {
  1979. U32 LLTable[FSE_DTABLE_SIZE_U32(LLFSELog)];
  1980. U32 OffTable[FSE_DTABLE_SIZE_U32(OffFSELog)];
  1981. U32 MLTable[FSE_DTABLE_SIZE_U32(MLFSELog)];
  1982. void* previousDstEnd;
  1983. void* base;
  1984. size_t expected;
  1985. blockType_t bType;
  1986. U32 phase;
  1987. const BYTE* litPtr;
  1988. size_t litSize;
  1989. BYTE litBuffer[BLOCKSIZE + 8 /* margin for wildcopy */];
  1990. }; /* typedef'd to ZSTD_Dctx within "zstd_static.h" */
  1991. static size_t ZSTD_getcBlockSize(const void* src, size_t srcSize, blockProperties_t* bpPtr)
  1992. {
  1993. const BYTE* const in = (const BYTE* const)src;
  1994. BYTE headerFlags;
  1995. U32 cSize;
  1996. if (srcSize < 3) return ERROR(srcSize_wrong);
  1997. headerFlags = *in;
  1998. cSize = in[2] + (in[1]<<8) + ((in[0] & 7)<<16);
  1999. bpPtr->blockType = (blockType_t)(headerFlags >> 6);
  2000. bpPtr->origSize = (bpPtr->blockType == bt_rle) ? cSize : 0;
  2001. if (bpPtr->blockType == bt_end) return 0;
  2002. if (bpPtr->blockType == bt_rle) return 1;
  2003. return cSize;
  2004. }
  2005. static size_t ZSTD_copyUncompressedBlock(void* dst, size_t maxDstSize, const void* src, size_t srcSize)
  2006. {
  2007. if (srcSize > maxDstSize) return ERROR(dstSize_tooSmall);
  2008. if (srcSize > 0) {
  2009. memcpy(dst, src, srcSize);
  2010. }
  2011. return srcSize;
  2012. }
  2013. /** ZSTD_decompressLiterals
  2014. @return : nb of bytes read from src, or an error code*/
  2015. static size_t ZSTD_decompressLiterals(void* dst, size_t* maxDstSizePtr,
  2016. const void* src, size_t srcSize)
  2017. {
  2018. const BYTE* ip = (const BYTE*)src;
  2019. const size_t litSize = (MEM_readLE32(src) & 0x1FFFFF) >> 2; /* no buffer issue : srcSize >= MIN_CBLOCK_SIZE */
  2020. const size_t litCSize = (MEM_readLE32(ip+2) & 0xFFFFFF) >> 5; /* no buffer issue : srcSize >= MIN_CBLOCK_SIZE */
  2021. if (litSize > *maxDstSizePtr) return ERROR(corruption_detected);
  2022. if (litCSize + 5 > srcSize) return ERROR(corruption_detected);
  2023. if (HUF_isError(HUF_decompress(dst, litSize, ip+5, litCSize))) return ERROR(corruption_detected);
  2024. *maxDstSizePtr = litSize;
  2025. return litCSize + 5;
  2026. }
  2027. /** ZSTD_decodeLiteralsBlock
  2028. @return : nb of bytes read from src (< srcSize )*/
  2029. static size_t ZSTD_decodeLiteralsBlock(void* ctx,
  2030. const void* src, size_t srcSize)
  2031. {
  2032. ZSTD_DCtx* dctx = (ZSTD_DCtx*)ctx;
  2033. const BYTE* const istart = (const BYTE* const)src;
  2034. /* any compressed block with literals segment must be at least this size */
  2035. if (srcSize < MIN_CBLOCK_SIZE) return ERROR(corruption_detected);
  2036. switch(*istart & 3)
  2037. {
  2038. default:
  2039. case 0:
  2040. {
  2041. size_t litSize = BLOCKSIZE;
  2042. const size_t readSize = ZSTD_decompressLiterals(dctx->litBuffer, &litSize, src, srcSize);
  2043. dctx->litPtr = dctx->litBuffer;
  2044. dctx->litSize = litSize;
  2045. memset(dctx->litBuffer + dctx->litSize, 0, 8);
  2046. return readSize; /* works if it's an error too */
  2047. }
  2048. case IS_RAW:
  2049. {
  2050. const size_t litSize = (MEM_readLE32(istart) & 0xFFFFFF) >> 2; /* no buffer issue : srcSize >= MIN_CBLOCK_SIZE */
  2051. if (litSize > srcSize-11) /* risk of reading too far with wildcopy */
  2052. {
  2053. if (litSize > BLOCKSIZE) return ERROR(corruption_detected);
  2054. if (litSize > srcSize-3) return ERROR(corruption_detected);
  2055. memcpy(dctx->litBuffer, istart, litSize);
  2056. dctx->litPtr = dctx->litBuffer;
  2057. dctx->litSize = litSize;
  2058. memset(dctx->litBuffer + dctx->litSize, 0, 8);
  2059. return litSize+3;
  2060. }
  2061. /* direct reference into compressed stream */
  2062. dctx->litPtr = istart+3;
  2063. dctx->litSize = litSize;
  2064. return litSize+3;
  2065. }
  2066. case IS_RLE:
  2067. {
  2068. const size_t litSize = (MEM_readLE32(istart) & 0xFFFFFF) >> 2; /* no buffer issue : srcSize >= MIN_CBLOCK_SIZE */
  2069. if (litSize > BLOCKSIZE) return ERROR(corruption_detected);
  2070. memset(dctx->litBuffer, istart[3], litSize + 8);
  2071. dctx->litPtr = dctx->litBuffer;
  2072. dctx->litSize = litSize;
  2073. return 4;
  2074. }
  2075. }
  2076. }
  2077. static size_t ZSTD_decodeSeqHeaders(int* nbSeq, const BYTE** dumpsPtr, size_t* dumpsLengthPtr,
  2078. FSE_DTable* DTableLL, FSE_DTable* DTableML, FSE_DTable* DTableOffb,
  2079. const void* src, size_t srcSize)
  2080. {
  2081. const BYTE* const istart = (const BYTE* const)src;
  2082. const BYTE* ip = istart;
  2083. const BYTE* const iend = istart + srcSize;
  2084. U32 LLtype, Offtype, MLtype;
  2085. U32 LLlog, Offlog, MLlog;
  2086. size_t dumpsLength;
  2087. /* check */
  2088. if (srcSize < 5) return ERROR(srcSize_wrong);
  2089. /* SeqHead */
  2090. *nbSeq = MEM_readLE16(ip); ip+=2;
  2091. LLtype = *ip >> 6;
  2092. Offtype = (*ip >> 4) & 3;
  2093. MLtype = (*ip >> 2) & 3;
  2094. if (*ip & 2)
  2095. {
  2096. dumpsLength = ip[2];
  2097. dumpsLength += ip[1] << 8;
  2098. ip += 3;
  2099. }
  2100. else
  2101. {
  2102. dumpsLength = ip[1];
  2103. dumpsLength += (ip[0] & 1) << 8;
  2104. ip += 2;
  2105. }
  2106. *dumpsPtr = ip;
  2107. ip += dumpsLength;
  2108. *dumpsLengthPtr = dumpsLength;
  2109. /* check */
  2110. if (ip > iend-3) return ERROR(srcSize_wrong); /* min : all 3 are "raw", hence no header, but at least xxLog bits per type */
  2111. /* sequences */
  2112. {
  2113. S16 norm[MaxML+1]; /* assumption : MaxML >= MaxLL and MaxOff */
  2114. size_t headerSize;
  2115. /* Build DTables */
  2116. switch(LLtype)
  2117. {
  2118. case bt_rle :
  2119. LLlog = 0;
  2120. FSE_buildDTable_rle(DTableLL, *ip++); break;
  2121. case bt_raw :
  2122. LLlog = LLbits;
  2123. FSE_buildDTable_raw(DTableLL, LLbits); break;
  2124. default :
  2125. { U32 max = MaxLL;
  2126. headerSize = FSE_readNCount(norm, &max, &LLlog, ip, iend-ip);
  2127. if (FSE_isError(headerSize)) return ERROR(GENERIC);
  2128. if (LLlog > LLFSELog) return ERROR(corruption_detected);
  2129. ip += headerSize;
  2130. FSE_buildDTable(DTableLL, norm, max, LLlog);
  2131. } }
  2132. switch(Offtype)
  2133. {
  2134. case bt_rle :
  2135. Offlog = 0;
  2136. if (ip > iend-2) return ERROR(srcSize_wrong); /* min : "raw", hence no header, but at least xxLog bits */
  2137. FSE_buildDTable_rle(DTableOffb, *ip++ & MaxOff); /* if *ip > MaxOff, data is corrupted */
  2138. break;
  2139. case bt_raw :
  2140. Offlog = Offbits;
  2141. FSE_buildDTable_raw(DTableOffb, Offbits); break;
  2142. default :
  2143. { U32 max = MaxOff;
  2144. headerSize = FSE_readNCount(norm, &max, &Offlog, ip, iend-ip);
  2145. if (FSE_isError(headerSize)) return ERROR(GENERIC);
  2146. if (Offlog > OffFSELog) return ERROR(corruption_detected);
  2147. ip += headerSize;
  2148. FSE_buildDTable(DTableOffb, norm, max, Offlog);
  2149. } }
  2150. switch(MLtype)
  2151. {
  2152. case bt_rle :
  2153. MLlog = 0;
  2154. if (ip > iend-2) return ERROR(srcSize_wrong); /* min : "raw", hence no header, but at least xxLog bits */
  2155. FSE_buildDTable_rle(DTableML, *ip++); break;
  2156. case bt_raw :
  2157. MLlog = MLbits;
  2158. FSE_buildDTable_raw(DTableML, MLbits); break;
  2159. default :
  2160. { U32 max = MaxML;
  2161. headerSize = FSE_readNCount(norm, &max, &MLlog, ip, iend-ip);
  2162. if (FSE_isError(headerSize)) return ERROR(GENERIC);
  2163. if (MLlog > MLFSELog) return ERROR(corruption_detected);
  2164. ip += headerSize;
  2165. FSE_buildDTable(DTableML, norm, max, MLlog);
  2166. } } }
  2167. return ip-istart;
  2168. }
  2169. typedef struct {
  2170. size_t litLength;
  2171. size_t offset;
  2172. size_t matchLength;
  2173. } seq_t;
  2174. typedef struct {
  2175. BIT_DStream_t DStream;
  2176. FSE_DState_t stateLL;
  2177. FSE_DState_t stateOffb;
  2178. FSE_DState_t stateML;
  2179. size_t prevOffset;
  2180. const BYTE* dumps;
  2181. const BYTE* dumpsEnd;
  2182. } seqState_t;
  2183. static void ZSTD_decodeSequence(seq_t* seq, seqState_t* seqState)
  2184. {
  2185. size_t litLength;
  2186. size_t prevOffset;
  2187. size_t offset;
  2188. size_t matchLength;
  2189. const BYTE* dumps = seqState->dumps;
  2190. const BYTE* const de = seqState->dumpsEnd;
  2191. /* Literal length */
  2192. litLength = FSE_decodeSymbol(&(seqState->stateLL), &(seqState->DStream));
  2193. prevOffset = litLength ? seq->offset : seqState->prevOffset;
  2194. seqState->prevOffset = seq->offset;
  2195. if (litLength == MaxLL)
  2196. {
  2197. const U32 add = dumps<de ? *dumps++ : 0;
  2198. if (add < 255) litLength += add;
  2199. else if (dumps + 3 <= de)
  2200. {
  2201. litLength = MEM_readLE24(dumps);
  2202. dumps += 3;
  2203. }
  2204. if (dumps >= de) dumps = de-1; /* late correction, to avoid read overflow (data is now corrupted anyway) */
  2205. }
  2206. /* Offset */
  2207. {
  2208. static const size_t offsetPrefix[MaxOff+1] = { /* note : size_t faster than U32 */
  2209. 1 /*fake*/, 1, 2, 4, 8, 16, 32, 64, 128, 256,
  2210. 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072, 262144,
  2211. 524288, 1048576, 2097152, 4194304, 8388608, 16777216, 33554432, /*fake*/ 1, 1, 1, 1, 1 };
  2212. U32 offsetCode, nbBits;
  2213. offsetCode = FSE_decodeSymbol(&(seqState->stateOffb), &(seqState->DStream)); /* <= maxOff, by table construction */
  2214. if (MEM_32bits()) BIT_reloadDStream(&(seqState->DStream));
  2215. nbBits = offsetCode - 1;
  2216. if (offsetCode==0) nbBits = 0; /* cmove */
  2217. offset = offsetPrefix[offsetCode] + BIT_readBits(&(seqState->DStream), nbBits);
  2218. if (MEM_32bits()) BIT_reloadDStream(&(seqState->DStream));
  2219. if (offsetCode==0) offset = prevOffset; /* cmove */
  2220. }
  2221. /* MatchLength */
  2222. matchLength = FSE_decodeSymbol(&(seqState->stateML), &(seqState->DStream));
  2223. if (matchLength == MaxML)
  2224. {
  2225. const U32 add = dumps<de ? *dumps++ : 0;
  2226. if (add < 255) matchLength += add;
  2227. else if (dumps + 3 <= de)
  2228. {
  2229. matchLength = MEM_readLE24(dumps);
  2230. dumps += 3;
  2231. }
  2232. if (dumps >= de) dumps = de-1; /* late correction, to avoid read overflow (data is now corrupted anyway) */
  2233. }
  2234. matchLength += MINMATCH;
  2235. /* save result */
  2236. seq->litLength = litLength;
  2237. seq->offset = offset;
  2238. seq->matchLength = matchLength;
  2239. seqState->dumps = dumps;
  2240. }
  2241. static size_t ZSTD_execSequence(BYTE* op,
  2242. seq_t sequence,
  2243. const BYTE** litPtr, const BYTE* const litLimit,
  2244. BYTE* const base, BYTE* const oend)
  2245. {
  2246. static const int dec32table[] = {0, 1, 2, 1, 4, 4, 4, 4}; /* added */
  2247. static const int dec64table[] = {8, 8, 8, 7, 8, 9,10,11}; /* subtracted */
  2248. const BYTE* const ostart = op;
  2249. BYTE* const oLitEnd = op + sequence.litLength;
  2250. BYTE* const oMatchEnd = op + sequence.litLength + sequence.matchLength; /* risk : address space overflow (32-bits) */
  2251. BYTE* const oend_8 = oend-8;
  2252. const BYTE* const litEnd = *litPtr + sequence.litLength;
  2253. /* checks */
  2254. size_t const seqLength = sequence.litLength + sequence.matchLength;
  2255. if (seqLength > (size_t)(oend - op)) return ERROR(dstSize_tooSmall);
  2256. if (sequence.litLength > (size_t)(litLimit - *litPtr)) return ERROR(corruption_detected);
  2257. /* Now we know there are no overflow in literal nor match lengths, can use pointer checks */
  2258. if (oLitEnd > oend_8) return ERROR(dstSize_tooSmall);
  2259. if (sequence.offset > (U32)(oLitEnd - base)) return ERROR(corruption_detected);
  2260. if (oMatchEnd > oend) return ERROR(dstSize_tooSmall); /* overwrite beyond dst buffer */
  2261. if (litEnd > litLimit) return ERROR(corruption_detected); /* overRead beyond lit buffer */
  2262. /* copy Literals */
  2263. ZSTD_wildcopy(op, *litPtr, (ptrdiff_t)sequence.litLength); /* note : oLitEnd <= oend-8 : no risk of overwrite beyond oend */
  2264. op = oLitEnd;
  2265. *litPtr = litEnd; /* update for next sequence */
  2266. /* copy Match */
  2267. { const BYTE* match = op - sequence.offset;
  2268. /* check */
  2269. if (sequence.offset > (size_t)op) return ERROR(corruption_detected); /* address space overflow test (this test seems kept by clang optimizer) */
  2270. //if (match > op) return ERROR(corruption_detected); /* address space overflow test (is clang optimizer removing this test ?) */
  2271. if (match < base) return ERROR(corruption_detected);
  2272. /* close range match, overlap */
  2273. if (sequence.offset < 8)
  2274. {
  2275. const int dec64 = dec64table[sequence.offset];
  2276. op[0] = match[0];
  2277. op[1] = match[1];
  2278. op[2] = match[2];
  2279. op[3] = match[3];
  2280. match += dec32table[sequence.offset];
  2281. ZSTD_copy4(op+4, match);
  2282. match -= dec64;
  2283. }
  2284. else
  2285. {
  2286. ZSTD_copy8(op, match);
  2287. }
  2288. op += 8; match += 8;
  2289. if (oMatchEnd > oend-(16-MINMATCH))
  2290. {
  2291. if (op < oend_8)
  2292. {
  2293. ZSTD_wildcopy(op, match, oend_8 - op);
  2294. match += oend_8 - op;
  2295. op = oend_8;
  2296. }
  2297. while (op < oMatchEnd) *op++ = *match++;
  2298. }
  2299. else
  2300. {
  2301. ZSTD_wildcopy(op, match, (ptrdiff_t)sequence.matchLength-8); /* works even if matchLength < 8 */
  2302. }
  2303. }
  2304. return oMatchEnd - ostart;
  2305. }
  2306. static size_t ZSTD_decompressSequences(
  2307. void* ctx,
  2308. void* dst, size_t maxDstSize,
  2309. const void* seqStart, size_t seqSize)
  2310. {
  2311. ZSTD_DCtx* dctx = (ZSTD_DCtx*)ctx;
  2312. const BYTE* ip = (const BYTE*)seqStart;
  2313. const BYTE* const iend = ip + seqSize;
  2314. BYTE* const ostart = (BYTE* const)dst;
  2315. BYTE* op = ostart;
  2316. BYTE* const oend = ostart + maxDstSize;
  2317. size_t errorCode, dumpsLength;
  2318. const BYTE* litPtr = dctx->litPtr;
  2319. const BYTE* const litEnd = litPtr + dctx->litSize;
  2320. int nbSeq;
  2321. const BYTE* dumps;
  2322. U32* DTableLL = dctx->LLTable;
  2323. U32* DTableML = dctx->MLTable;
  2324. U32* DTableOffb = dctx->OffTable;
  2325. BYTE* const base = (BYTE*) (dctx->base);
  2326. /* Build Decoding Tables */
  2327. errorCode = ZSTD_decodeSeqHeaders(&nbSeq, &dumps, &dumpsLength,
  2328. DTableLL, DTableML, DTableOffb,
  2329. ip, iend-ip);
  2330. if (ZSTD_isError(errorCode)) return errorCode;
  2331. ip += errorCode;
  2332. /* Regen sequences */
  2333. {
  2334. seq_t sequence;
  2335. seqState_t seqState;
  2336. memset(&sequence, 0, sizeof(sequence));
  2337. seqState.dumps = dumps;
  2338. seqState.dumpsEnd = dumps + dumpsLength;
  2339. seqState.prevOffset = sequence.offset = 4;
  2340. errorCode = BIT_initDStream(&(seqState.DStream), ip, iend-ip);
  2341. if (ERR_isError(errorCode)) return ERROR(corruption_detected);
  2342. FSE_initDState(&(seqState.stateLL), &(seqState.DStream), DTableLL);
  2343. FSE_initDState(&(seqState.stateOffb), &(seqState.DStream), DTableOffb);
  2344. FSE_initDState(&(seqState.stateML), &(seqState.DStream), DTableML);
  2345. for ( ; (BIT_reloadDStream(&(seqState.DStream)) <= BIT_DStream_completed) && (nbSeq>0) ; )
  2346. {
  2347. size_t oneSeqSize;
  2348. nbSeq--;
  2349. ZSTD_decodeSequence(&sequence, &seqState);
  2350. oneSeqSize = ZSTD_execSequence(op, sequence, &litPtr, litEnd, base, oend);
  2351. if (ZSTD_isError(oneSeqSize)) return oneSeqSize;
  2352. op += oneSeqSize;
  2353. }
  2354. /* check if reached exact end */
  2355. if ( !BIT_endOfDStream(&(seqState.DStream)) ) return ERROR(corruption_detected); /* requested too much : data is corrupted */
  2356. if (nbSeq<0) return ERROR(corruption_detected); /* requested too many sequences : data is corrupted */
  2357. /* last literal segment */
  2358. {
  2359. size_t lastLLSize = litEnd - litPtr;
  2360. if (litPtr > litEnd) return ERROR(corruption_detected);
  2361. if (op+lastLLSize > oend) return ERROR(dstSize_tooSmall);
  2362. if (lastLLSize > 0) {
  2363. if (op != litPtr) memmove(op, litPtr, lastLLSize);
  2364. op += lastLLSize;
  2365. }
  2366. }
  2367. }
  2368. return op-ostart;
  2369. }
  2370. static size_t ZSTD_decompressBlock(
  2371. void* ctx,
  2372. void* dst, size_t maxDstSize,
  2373. const void* src, size_t srcSize)
  2374. {
  2375. /* blockType == blockCompressed */
  2376. const BYTE* ip = (const BYTE*)src;
  2377. /* Decode literals sub-block */
  2378. size_t litCSize = ZSTD_decodeLiteralsBlock(ctx, src, srcSize);
  2379. if (ZSTD_isError(litCSize)) return litCSize;
  2380. ip += litCSize;
  2381. srcSize -= litCSize;
  2382. return ZSTD_decompressSequences(ctx, dst, maxDstSize, ip, srcSize);
  2383. }
  2384. static size_t ZSTD_decompressDCtx(void* ctx, void* dst, size_t maxDstSize, const void* src, size_t srcSize)
  2385. {
  2386. const BYTE* ip = (const BYTE*)src;
  2387. const BYTE* iend = ip + srcSize;
  2388. BYTE* const ostart = (BYTE* const)dst;
  2389. BYTE* op = ostart;
  2390. BYTE* const oend = ostart + maxDstSize;
  2391. size_t remainingSize = srcSize;
  2392. U32 magicNumber;
  2393. blockProperties_t blockProperties;
  2394. /* Frame Header */
  2395. if (srcSize < ZSTD_frameHeaderSize+ZSTD_blockHeaderSize) return ERROR(srcSize_wrong);
  2396. magicNumber = MEM_readLE32(src);
  2397. if (magicNumber != ZSTD_magicNumber) return ERROR(prefix_unknown);
  2398. ip += ZSTD_frameHeaderSize; remainingSize -= ZSTD_frameHeaderSize;
  2399. /* Loop on each block */
  2400. while (1)
  2401. {
  2402. size_t decodedSize=0;
  2403. size_t cBlockSize = ZSTD_getcBlockSize(ip, iend-ip, &blockProperties);
  2404. if (ZSTD_isError(cBlockSize)) return cBlockSize;
  2405. ip += ZSTD_blockHeaderSize;
  2406. remainingSize -= ZSTD_blockHeaderSize;
  2407. if (cBlockSize > remainingSize) return ERROR(srcSize_wrong);
  2408. switch(blockProperties.blockType)
  2409. {
  2410. case bt_compressed:
  2411. decodedSize = ZSTD_decompressBlock(ctx, op, oend-op, ip, cBlockSize);
  2412. break;
  2413. case bt_raw :
  2414. decodedSize = ZSTD_copyUncompressedBlock(op, oend-op, ip, cBlockSize);
  2415. break;
  2416. case bt_rle :
  2417. return ERROR(GENERIC); /* not yet supported */
  2418. break;
  2419. case bt_end :
  2420. /* end of frame */
  2421. if (remainingSize) return ERROR(srcSize_wrong);
  2422. break;
  2423. default:
  2424. return ERROR(GENERIC); /* impossible */
  2425. }
  2426. if (cBlockSize == 0) break; /* bt_end */
  2427. if (ZSTD_isError(decodedSize)) return decodedSize;
  2428. op += decodedSize;
  2429. ip += cBlockSize;
  2430. remainingSize -= cBlockSize;
  2431. }
  2432. return op-ostart;
  2433. }
  2434. static size_t ZSTD_decompress(void* dst, size_t maxDstSize, const void* src, size_t srcSize)
  2435. {
  2436. ZSTD_DCtx ctx;
  2437. ctx.base = dst;
  2438. return ZSTD_decompressDCtx(&ctx, dst, maxDstSize, src, srcSize);
  2439. }
  2440. /* ZSTD_errorFrameSizeInfoLegacy() :
  2441. assumes `cSize` and `dBound` are _not_ NULL */
  2442. MEM_STATIC void ZSTD_errorFrameSizeInfoLegacy(size_t* cSize, unsigned long long* dBound, size_t ret)
  2443. {
  2444. *cSize = ret;
  2445. *dBound = ZSTD_CONTENTSIZE_ERROR;
  2446. }
  2447. void ZSTDv03_findFrameSizeInfoLegacy(const void *src, size_t srcSize, size_t* cSize, unsigned long long* dBound)
  2448. {
  2449. const BYTE* ip = (const BYTE*)src;
  2450. size_t remainingSize = srcSize;
  2451. size_t nbBlocks = 0;
  2452. U32 magicNumber;
  2453. blockProperties_t blockProperties;
  2454. /* Frame Header */
  2455. if (srcSize < ZSTD_frameHeaderSize+ZSTD_blockHeaderSize) {
  2456. ZSTD_errorFrameSizeInfoLegacy(cSize, dBound, ERROR(srcSize_wrong));
  2457. return;
  2458. }
  2459. magicNumber = MEM_readLE32(src);
  2460. if (magicNumber != ZSTD_magicNumber) {
  2461. ZSTD_errorFrameSizeInfoLegacy(cSize, dBound, ERROR(prefix_unknown));
  2462. return;
  2463. }
  2464. ip += ZSTD_frameHeaderSize; remainingSize -= ZSTD_frameHeaderSize;
  2465. /* Loop on each block */
  2466. while (1)
  2467. {
  2468. size_t cBlockSize = ZSTD_getcBlockSize(ip, remainingSize, &blockProperties);
  2469. if (ZSTD_isError(cBlockSize)) {
  2470. ZSTD_errorFrameSizeInfoLegacy(cSize, dBound, cBlockSize);
  2471. return;
  2472. }
  2473. ip += ZSTD_blockHeaderSize;
  2474. remainingSize -= ZSTD_blockHeaderSize;
  2475. if (cBlockSize > remainingSize) {
  2476. ZSTD_errorFrameSizeInfoLegacy(cSize, dBound, ERROR(srcSize_wrong));
  2477. return;
  2478. }
  2479. if (cBlockSize == 0) break; /* bt_end */
  2480. ip += cBlockSize;
  2481. remainingSize -= cBlockSize;
  2482. nbBlocks++;
  2483. }
  2484. *cSize = ip - (const BYTE*)src;
  2485. *dBound = nbBlocks * BLOCKSIZE;
  2486. }
  2487. /*******************************
  2488. * Streaming Decompression API
  2489. *******************************/
  2490. static size_t ZSTD_resetDCtx(ZSTD_DCtx* dctx)
  2491. {
  2492. dctx->expected = ZSTD_frameHeaderSize;
  2493. dctx->phase = 0;
  2494. dctx->previousDstEnd = NULL;
  2495. dctx->base = NULL;
  2496. return 0;
  2497. }
  2498. static ZSTD_DCtx* ZSTD_createDCtx(void)
  2499. {
  2500. ZSTD_DCtx* dctx = (ZSTD_DCtx*)malloc(sizeof(ZSTD_DCtx));
  2501. if (dctx==NULL) return NULL;
  2502. ZSTD_resetDCtx(dctx);
  2503. return dctx;
  2504. }
  2505. static size_t ZSTD_freeDCtx(ZSTD_DCtx* dctx)
  2506. {
  2507. free(dctx);
  2508. return 0;
  2509. }
  2510. static size_t ZSTD_nextSrcSizeToDecompress(ZSTD_DCtx* dctx)
  2511. {
  2512. return dctx->expected;
  2513. }
  2514. static size_t ZSTD_decompressContinue(ZSTD_DCtx* ctx, void* dst, size_t maxDstSize, const void* src, size_t srcSize)
  2515. {
  2516. /* Sanity check */
  2517. if (srcSize != ctx->expected) return ERROR(srcSize_wrong);
  2518. if (dst != ctx->previousDstEnd) /* not contiguous */
  2519. ctx->base = dst;
  2520. /* Decompress : frame header */
  2521. if (ctx->phase == 0)
  2522. {
  2523. /* Check frame magic header */
  2524. U32 magicNumber = MEM_readLE32(src);
  2525. if (magicNumber != ZSTD_magicNumber) return ERROR(prefix_unknown);
  2526. ctx->phase = 1;
  2527. ctx->expected = ZSTD_blockHeaderSize;
  2528. return 0;
  2529. }
  2530. /* Decompress : block header */
  2531. if (ctx->phase == 1)
  2532. {
  2533. blockProperties_t bp;
  2534. size_t blockSize = ZSTD_getcBlockSize(src, ZSTD_blockHeaderSize, &bp);
  2535. if (ZSTD_isError(blockSize)) return blockSize;
  2536. if (bp.blockType == bt_end)
  2537. {
  2538. ctx->expected = 0;
  2539. ctx->phase = 0;
  2540. }
  2541. else
  2542. {
  2543. ctx->expected = blockSize;
  2544. ctx->bType = bp.blockType;
  2545. ctx->phase = 2;
  2546. }
  2547. return 0;
  2548. }
  2549. /* Decompress : block content */
  2550. {
  2551. size_t rSize;
  2552. switch(ctx->bType)
  2553. {
  2554. case bt_compressed:
  2555. rSize = ZSTD_decompressBlock(ctx, dst, maxDstSize, src, srcSize);
  2556. break;
  2557. case bt_raw :
  2558. rSize = ZSTD_copyUncompressedBlock(dst, maxDstSize, src, srcSize);
  2559. break;
  2560. case bt_rle :
  2561. return ERROR(GENERIC); /* not yet handled */
  2562. break;
  2563. case bt_end : /* should never happen (filtered at phase 1) */
  2564. rSize = 0;
  2565. break;
  2566. default:
  2567. return ERROR(GENERIC);
  2568. }
  2569. ctx->phase = 1;
  2570. ctx->expected = ZSTD_blockHeaderSize;
  2571. if (ZSTD_isError(rSize)) return rSize;
  2572. ctx->previousDstEnd = (void*)( ((char*)dst) + rSize);
  2573. return rSize;
  2574. }
  2575. }
  2576. /* wrapper layer */
  2577. unsigned ZSTDv03_isError(size_t code)
  2578. {
  2579. return ZSTD_isError(code);
  2580. }
  2581. size_t ZSTDv03_decompress( void* dst, size_t maxOriginalSize,
  2582. const void* src, size_t compressedSize)
  2583. {
  2584. return ZSTD_decompress(dst, maxOriginalSize, src, compressedSize);
  2585. }
  2586. ZSTDv03_Dctx* ZSTDv03_createDCtx(void)
  2587. {
  2588. return (ZSTDv03_Dctx*)ZSTD_createDCtx();
  2589. }
  2590. size_t ZSTDv03_freeDCtx(ZSTDv03_Dctx* dctx)
  2591. {
  2592. return ZSTD_freeDCtx((ZSTD_DCtx*)dctx);
  2593. }
  2594. size_t ZSTDv03_resetDCtx(ZSTDv03_Dctx* dctx)
  2595. {
  2596. return ZSTD_resetDCtx((ZSTD_DCtx*)dctx);
  2597. }
  2598. size_t ZSTDv03_nextSrcSizeToDecompress(ZSTDv03_Dctx* dctx)
  2599. {
  2600. return ZSTD_nextSrcSizeToDecompress((ZSTD_DCtx*)dctx);
  2601. }
  2602. size_t ZSTDv03_decompressContinue(ZSTDv03_Dctx* dctx, void* dst, size_t maxDstSize, const void* src, size_t srcSize)
  2603. {
  2604. return ZSTD_decompressContinue((ZSTD_DCtx*)dctx, dst, maxDstSize, src, srcSize);
  2605. }