zstd_v01.c 72 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178
  1. /* ******************************************************************
  2. ZSTD_v01
  3. Zstandard decoder, compatible with v0.1.x format
  4. Copyright (C) 2013-2015, Yann Collet.
  5. BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
  6. Redistribution and use in source and binary forms, with or without
  7. modification, are permitted provided that the following conditions are
  8. met:
  9. * Redistributions of source code must retain the above copyright
  10. notice, this list of conditions and the following disclaimer.
  11. * Redistributions in binary form must reproduce the above
  12. copyright notice, this list of conditions and the following disclaimer
  13. in the documentation and/or other materials provided with the
  14. distribution.
  15. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  16. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  17. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  18. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  19. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  20. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  21. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  22. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  23. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  25. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. You can contact the author at :
  27. - Source repository : https://github.com/Cyan4973/FiniteStateEntropy
  28. - Public forum : https://groups.google.com/forum/#!forum/lz4c
  29. ****************************************************************** */
  30. /******************************************
  31. * Includes
  32. ******************************************/
  33. #include <stddef.h> /* size_t, ptrdiff_t */
  34. #include "zstd_v01.h"
  35. /******************************************
  36. * Static allocation
  37. ******************************************/
  38. /* You can statically allocate FSE CTable/DTable as a table of unsigned using below macro */
  39. #define FSE_DTABLE_SIZE_U32(maxTableLog) (1 + (1<<maxTableLog))
  40. /* You can statically allocate Huff0 DTable as a table of unsigned short using below macro */
  41. #define HUF_DTABLE_SIZE_U16(maxTableLog) (1 + (1<<maxTableLog))
  42. #define HUF_CREATE_STATIC_DTABLE(DTable, maxTableLog) \
  43. unsigned short DTable[HUF_DTABLE_SIZE_U16(maxTableLog)] = { maxTableLog }
  44. /******************************************
  45. * Error Management
  46. ******************************************/
  47. #define FSE_LIST_ERRORS(ITEM) \
  48. ITEM(FSE_OK_NoError) ITEM(FSE_ERROR_GENERIC) \
  49. ITEM(FSE_ERROR_tableLog_tooLarge) ITEM(FSE_ERROR_maxSymbolValue_tooLarge) ITEM(FSE_ERROR_maxSymbolValue_tooSmall) \
  50. ITEM(FSE_ERROR_dstSize_tooSmall) ITEM(FSE_ERROR_srcSize_wrong)\
  51. ITEM(FSE_ERROR_corruptionDetected) \
  52. ITEM(FSE_ERROR_maxCode)
  53. #define FSE_GENERATE_ENUM(ENUM) ENUM,
  54. typedef enum { FSE_LIST_ERRORS(FSE_GENERATE_ENUM) } FSE_errorCodes; /* enum is exposed, to detect & handle specific errors; compare function result to -enum value */
  55. /******************************************
  56. * FSE symbol compression API
  57. ******************************************/
  58. /*
  59. This API consists of small unitary functions, which highly benefit from being inlined.
  60. You will want to enable link-time-optimization to ensure these functions are properly inlined in your binary.
  61. Visual seems to do it automatically.
  62. For gcc or clang, you'll need to add -flto flag at compilation and linking stages.
  63. If none of these solutions is applicable, include "fse.c" directly.
  64. */
  65. typedef unsigned FSE_CTable; /* don't allocate that. It's just a way to be more restrictive than void* */
  66. typedef unsigned FSE_DTable; /* don't allocate that. It's just a way to be more restrictive than void* */
  67. typedef struct
  68. {
  69. size_t bitContainer;
  70. int bitPos;
  71. char* startPtr;
  72. char* ptr;
  73. char* endPtr;
  74. } FSE_CStream_t;
  75. typedef struct
  76. {
  77. ptrdiff_t value;
  78. const void* stateTable;
  79. const void* symbolTT;
  80. unsigned stateLog;
  81. } FSE_CState_t;
  82. typedef struct
  83. {
  84. size_t bitContainer;
  85. unsigned bitsConsumed;
  86. const char* ptr;
  87. const char* start;
  88. } FSE_DStream_t;
  89. typedef struct
  90. {
  91. size_t state;
  92. const void* table; /* precise table may vary, depending on U16 */
  93. } FSE_DState_t;
  94. typedef enum { FSE_DStream_unfinished = 0,
  95. FSE_DStream_endOfBuffer = 1,
  96. FSE_DStream_completed = 2,
  97. FSE_DStream_tooFar = 3 } FSE_DStream_status; /* result of FSE_reloadDStream() */
  98. /* 1,2,4,8 would be better for bitmap combinations, but slows down performance a bit ... ?! */
  99. /****************************************************************
  100. * Tuning parameters
  101. ****************************************************************/
  102. /* MEMORY_USAGE :
  103. * Memory usage formula : N->2^N Bytes (examples : 10 -> 1KB; 12 -> 4KB ; 16 -> 64KB; 20 -> 1MB; etc.)
  104. * Increasing memory usage improves compression ratio
  105. * Reduced memory usage can improve speed, due to cache effect
  106. * Recommended max value is 14, for 16KB, which nicely fits into Intel x86 L1 cache */
  107. #define FSE_MAX_MEMORY_USAGE 14
  108. #define FSE_DEFAULT_MEMORY_USAGE 13
  109. /* FSE_MAX_SYMBOL_VALUE :
  110. * Maximum symbol value authorized.
  111. * Required for proper stack allocation */
  112. #define FSE_MAX_SYMBOL_VALUE 255
  113. /****************************************************************
  114. * template functions type & suffix
  115. ****************************************************************/
  116. #define FSE_FUNCTION_TYPE BYTE
  117. #define FSE_FUNCTION_EXTENSION
  118. /****************************************************************
  119. * Byte symbol type
  120. ****************************************************************/
  121. typedef struct
  122. {
  123. unsigned short newState;
  124. unsigned char symbol;
  125. unsigned char nbBits;
  126. } FSE_decode_t; /* size == U32 */
  127. /****************************************************************
  128. * Compiler specifics
  129. ****************************************************************/
  130. #ifdef _MSC_VER /* Visual Studio */
  131. # define FORCE_INLINE static __forceinline
  132. # include <intrin.h> /* For Visual 2005 */
  133. # pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */
  134. # pragma warning(disable : 4214) /* disable: C4214: non-int bitfields */
  135. #else
  136. # define GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__)
  137. # ifdef __GNUC__
  138. # define FORCE_INLINE static inline __attribute__((always_inline))
  139. # else
  140. # define FORCE_INLINE static inline
  141. # endif
  142. #endif
  143. /****************************************************************
  144. * Includes
  145. ****************************************************************/
  146. #include <stdlib.h> /* malloc, free, qsort */
  147. #include <string.h> /* memcpy, memset */
  148. #include <stdio.h> /* printf (debug) */
  149. #ifndef MEM_ACCESS_MODULE
  150. #define MEM_ACCESS_MODULE
  151. /****************************************************************
  152. * Basic Types
  153. *****************************************************************/
  154. #if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* C99 */
  155. # include <stdint.h>
  156. typedef uint8_t BYTE;
  157. typedef uint16_t U16;
  158. typedef int16_t S16;
  159. typedef uint32_t U32;
  160. typedef int32_t S32;
  161. typedef uint64_t U64;
  162. typedef int64_t S64;
  163. #else
  164. typedef unsigned char BYTE;
  165. typedef unsigned short U16;
  166. typedef signed short S16;
  167. typedef unsigned int U32;
  168. typedef signed int S32;
  169. typedef unsigned long long U64;
  170. typedef signed long long S64;
  171. #endif
  172. #endif /* MEM_ACCESS_MODULE */
  173. /****************************************************************
  174. * Memory I/O
  175. *****************************************************************/
  176. /* FSE_FORCE_MEMORY_ACCESS
  177. * By default, access to unaligned memory is controlled by `memcpy()`, which is safe and portable.
  178. * Unfortunately, on some target/compiler combinations, the generated assembly is sub-optimal.
  179. * The below switch allow to select different access method for improved performance.
  180. * Method 0 (default) : use `memcpy()`. Safe and portable.
  181. * Method 1 : `__packed` statement. It depends on compiler extension (ie, not portable).
  182. * This method is safe if your compiler supports it, and *generally* as fast or faster than `memcpy`.
  183. * Method 2 : direct access. This method is portable but violate C standard.
  184. * It can generate buggy code on targets generating assembly depending on alignment.
  185. * But in some circumstances, it's the only known way to get the most performance (ie GCC + ARMv6)
  186. * See http://fastcompression.blogspot.fr/2015/08/accessing-unaligned-memory.html for details.
  187. * Prefer these methods in priority order (0 > 1 > 2)
  188. */
  189. #ifndef FSE_FORCE_MEMORY_ACCESS /* can be defined externally, on command line for example */
  190. # if defined(__GNUC__) && ( defined(__ARM_ARCH_6__) || defined(__ARM_ARCH_6J__) || defined(__ARM_ARCH_6K__) || defined(__ARM_ARCH_6Z__) || defined(__ARM_ARCH_6ZK__) || defined(__ARM_ARCH_6T2__) )
  191. # define FSE_FORCE_MEMORY_ACCESS 2
  192. # elif defined(__INTEL_COMPILER) || \
  193. (defined(__GNUC__) && ( defined(__ARM_ARCH_7__) || defined(__ARM_ARCH_7A__) || defined(__ARM_ARCH_7R__) || defined(__ARM_ARCH_7M__) || defined(__ARM_ARCH_7S__) ))
  194. # define FSE_FORCE_MEMORY_ACCESS 1
  195. # endif
  196. #endif
  197. static unsigned FSE_32bits(void)
  198. {
  199. return sizeof(void*)==4;
  200. }
  201. static unsigned FSE_isLittleEndian(void)
  202. {
  203. const union { U32 i; BYTE c[4]; } one = { 1 }; /* don't use static : performance detrimental */
  204. return one.c[0];
  205. }
  206. #if defined(FSE_FORCE_MEMORY_ACCESS) && (FSE_FORCE_MEMORY_ACCESS==2)
  207. static U16 FSE_read16(const void* memPtr) { return *(const U16*) memPtr; }
  208. static U32 FSE_read32(const void* memPtr) { return *(const U32*) memPtr; }
  209. static U64 FSE_read64(const void* memPtr) { return *(const U64*) memPtr; }
  210. #elif defined(FSE_FORCE_MEMORY_ACCESS) && (FSE_FORCE_MEMORY_ACCESS==1)
  211. /* __pack instructions are safer, but compiler specific, hence potentially problematic for some compilers */
  212. /* currently only defined for gcc and icc */
  213. typedef union { U16 u16; U32 u32; U64 u64; } __attribute__((packed)) unalign;
  214. static U16 FSE_read16(const void* ptr) { return ((const unalign*)ptr)->u16; }
  215. static U32 FSE_read32(const void* ptr) { return ((const unalign*)ptr)->u32; }
  216. static U64 FSE_read64(const void* ptr) { return ((const unalign*)ptr)->u64; }
  217. #else
  218. static U16 FSE_read16(const void* memPtr)
  219. {
  220. U16 val; memcpy(&val, memPtr, sizeof(val)); return val;
  221. }
  222. static U32 FSE_read32(const void* memPtr)
  223. {
  224. U32 val; memcpy(&val, memPtr, sizeof(val)); return val;
  225. }
  226. static U64 FSE_read64(const void* memPtr)
  227. {
  228. U64 val; memcpy(&val, memPtr, sizeof(val)); return val;
  229. }
  230. #endif // FSE_FORCE_MEMORY_ACCESS
  231. static U16 FSE_readLE16(const void* memPtr)
  232. {
  233. if (FSE_isLittleEndian())
  234. return FSE_read16(memPtr);
  235. else
  236. {
  237. const BYTE* p = (const BYTE*)memPtr;
  238. return (U16)(p[0] + (p[1]<<8));
  239. }
  240. }
  241. static U32 FSE_readLE32(const void* memPtr)
  242. {
  243. if (FSE_isLittleEndian())
  244. return FSE_read32(memPtr);
  245. else
  246. {
  247. const BYTE* p = (const BYTE*)memPtr;
  248. return (U32)((U32)p[0] + ((U32)p[1]<<8) + ((U32)p[2]<<16) + ((U32)p[3]<<24));
  249. }
  250. }
  251. static U64 FSE_readLE64(const void* memPtr)
  252. {
  253. if (FSE_isLittleEndian())
  254. return FSE_read64(memPtr);
  255. else
  256. {
  257. const BYTE* p = (const BYTE*)memPtr;
  258. return (U64)((U64)p[0] + ((U64)p[1]<<8) + ((U64)p[2]<<16) + ((U64)p[3]<<24)
  259. + ((U64)p[4]<<32) + ((U64)p[5]<<40) + ((U64)p[6]<<48) + ((U64)p[7]<<56));
  260. }
  261. }
  262. static size_t FSE_readLEST(const void* memPtr)
  263. {
  264. if (FSE_32bits())
  265. return (size_t)FSE_readLE32(memPtr);
  266. else
  267. return (size_t)FSE_readLE64(memPtr);
  268. }
  269. /****************************************************************
  270. * Constants
  271. *****************************************************************/
  272. #define FSE_MAX_TABLELOG (FSE_MAX_MEMORY_USAGE-2)
  273. #define FSE_MAX_TABLESIZE (1U<<FSE_MAX_TABLELOG)
  274. #define FSE_MAXTABLESIZE_MASK (FSE_MAX_TABLESIZE-1)
  275. #define FSE_DEFAULT_TABLELOG (FSE_DEFAULT_MEMORY_USAGE-2)
  276. #define FSE_MIN_TABLELOG 5
  277. #define FSE_TABLELOG_ABSOLUTE_MAX 15
  278. #if FSE_MAX_TABLELOG > FSE_TABLELOG_ABSOLUTE_MAX
  279. #error "FSE_MAX_TABLELOG > FSE_TABLELOG_ABSOLUTE_MAX is not supported"
  280. #endif
  281. /****************************************************************
  282. * Error Management
  283. ****************************************************************/
  284. #define FSE_STATIC_ASSERT(c) { enum { FSE_static_assert = 1/(int)(!!(c)) }; } /* use only *after* variable declarations */
  285. /****************************************************************
  286. * Complex types
  287. ****************************************************************/
  288. typedef struct
  289. {
  290. int deltaFindState;
  291. U32 deltaNbBits;
  292. } FSE_symbolCompressionTransform; /* total 8 bytes */
  293. typedef U32 DTable_max_t[FSE_DTABLE_SIZE_U32(FSE_MAX_TABLELOG)];
  294. /****************************************************************
  295. * Internal functions
  296. ****************************************************************/
  297. FORCE_INLINE unsigned FSE_highbit32 (register U32 val)
  298. {
  299. # if defined(_MSC_VER) /* Visual */
  300. unsigned long r;
  301. _BitScanReverse ( &r, val );
  302. return (unsigned) r;
  303. # elif defined(__GNUC__) && (GCC_VERSION >= 304) /* GCC Intrinsic */
  304. return 31 - __builtin_clz (val);
  305. # else /* Software version */
  306. 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 };
  307. U32 v = val;
  308. unsigned r;
  309. v |= v >> 1;
  310. v |= v >> 2;
  311. v |= v >> 4;
  312. v |= v >> 8;
  313. v |= v >> 16;
  314. r = DeBruijnClz[ (U32) (v * 0x07C4ACDDU) >> 27];
  315. return r;
  316. # endif
  317. }
  318. /****************************************************************
  319. * Templates
  320. ****************************************************************/
  321. /*
  322. designed to be included
  323. for type-specific functions (template emulation in C)
  324. Objective is to write these functions only once, for improved maintenance
  325. */
  326. /* safety checks */
  327. #ifndef FSE_FUNCTION_EXTENSION
  328. # error "FSE_FUNCTION_EXTENSION must be defined"
  329. #endif
  330. #ifndef FSE_FUNCTION_TYPE
  331. # error "FSE_FUNCTION_TYPE must be defined"
  332. #endif
  333. /* Function names */
  334. #define FSE_CAT(X,Y) X##Y
  335. #define FSE_FUNCTION_NAME(X,Y) FSE_CAT(X,Y)
  336. #define FSE_TYPE_NAME(X,Y) FSE_CAT(X,Y)
  337. static U32 FSE_tableStep(U32 tableSize) { return (tableSize>>1) + (tableSize>>3) + 3; }
  338. #define FSE_DECODE_TYPE FSE_decode_t
  339. typedef struct {
  340. U16 tableLog;
  341. U16 fastMode;
  342. } FSE_DTableHeader; /* sizeof U32 */
  343. static size_t FSE_buildDTable
  344. (FSE_DTable* dt, const short* normalizedCounter, unsigned maxSymbolValue, unsigned tableLog)
  345. {
  346. void* ptr = dt;
  347. FSE_DTableHeader* const DTableH = (FSE_DTableHeader*)ptr;
  348. FSE_DECODE_TYPE* const tableDecode = (FSE_DECODE_TYPE*)(ptr) + 1; /* because dt is unsigned, 32-bits aligned on 32-bits */
  349. const U32 tableSize = 1 << tableLog;
  350. const U32 tableMask = tableSize-1;
  351. const U32 step = FSE_tableStep(tableSize);
  352. U16 symbolNext[FSE_MAX_SYMBOL_VALUE+1];
  353. U32 position = 0;
  354. U32 highThreshold = tableSize-1;
  355. const S16 largeLimit= (S16)(1 << (tableLog-1));
  356. U32 noLarge = 1;
  357. U32 s;
  358. /* Sanity Checks */
  359. if (maxSymbolValue > FSE_MAX_SYMBOL_VALUE) return (size_t)-FSE_ERROR_maxSymbolValue_tooLarge;
  360. if (tableLog > FSE_MAX_TABLELOG) return (size_t)-FSE_ERROR_tableLog_tooLarge;
  361. /* Init, lay down lowprob symbols */
  362. DTableH[0].tableLog = (U16)tableLog;
  363. for (s=0; s<=maxSymbolValue; s++)
  364. {
  365. if (normalizedCounter[s]==-1)
  366. {
  367. tableDecode[highThreshold--].symbol = (FSE_FUNCTION_TYPE)s;
  368. symbolNext[s] = 1;
  369. }
  370. else
  371. {
  372. if (normalizedCounter[s] >= largeLimit) noLarge=0;
  373. symbolNext[s] = normalizedCounter[s];
  374. }
  375. }
  376. /* Spread symbols */
  377. for (s=0; s<=maxSymbolValue; s++)
  378. {
  379. int i;
  380. for (i=0; i<normalizedCounter[s]; i++)
  381. {
  382. tableDecode[position].symbol = (FSE_FUNCTION_TYPE)s;
  383. position = (position + step) & tableMask;
  384. while (position > highThreshold) position = (position + step) & tableMask; /* lowprob area */
  385. }
  386. }
  387. if (position!=0) return (size_t)-FSE_ERROR_GENERIC; /* position must reach all cells once, otherwise normalizedCounter is incorrect */
  388. /* Build Decoding table */
  389. {
  390. U32 i;
  391. for (i=0; i<tableSize; i++)
  392. {
  393. FSE_FUNCTION_TYPE symbol = (FSE_FUNCTION_TYPE)(tableDecode[i].symbol);
  394. U16 nextState = symbolNext[symbol]++;
  395. tableDecode[i].nbBits = (BYTE) (tableLog - FSE_highbit32 ((U32)nextState) );
  396. tableDecode[i].newState = (U16) ( (nextState << tableDecode[i].nbBits) - tableSize);
  397. }
  398. }
  399. DTableH->fastMode = (U16)noLarge;
  400. return 0;
  401. }
  402. /******************************************
  403. * FSE byte symbol
  404. ******************************************/
  405. #ifndef FSE_COMMONDEFS_ONLY
  406. static unsigned FSE_isError(size_t code) { return (code > (size_t)(-FSE_ERROR_maxCode)); }
  407. static short FSE_abs(short a)
  408. {
  409. return a<0? -a : a;
  410. }
  411. /****************************************************************
  412. * Header bitstream management
  413. ****************************************************************/
  414. static size_t FSE_readNCount (short* normalizedCounter, unsigned* maxSVPtr, unsigned* tableLogPtr,
  415. const void* headerBuffer, size_t hbSize)
  416. {
  417. const BYTE* const istart = (const BYTE*) headerBuffer;
  418. const BYTE* const iend = istart + hbSize;
  419. const BYTE* ip = istart;
  420. int nbBits;
  421. int remaining;
  422. int threshold;
  423. U32 bitStream;
  424. int bitCount;
  425. unsigned charnum = 0;
  426. int previous0 = 0;
  427. if (hbSize < 4) return (size_t)-FSE_ERROR_srcSize_wrong;
  428. bitStream = FSE_readLE32(ip);
  429. nbBits = (bitStream & 0xF) + FSE_MIN_TABLELOG; /* extract tableLog */
  430. if (nbBits > FSE_TABLELOG_ABSOLUTE_MAX) return (size_t)-FSE_ERROR_tableLog_tooLarge;
  431. bitStream >>= 4;
  432. bitCount = 4;
  433. *tableLogPtr = nbBits;
  434. remaining = (1<<nbBits)+1;
  435. threshold = 1<<nbBits;
  436. nbBits++;
  437. while ((remaining>1) && (charnum<=*maxSVPtr))
  438. {
  439. if (previous0)
  440. {
  441. unsigned n0 = charnum;
  442. while ((bitStream & 0xFFFF) == 0xFFFF)
  443. {
  444. n0+=24;
  445. if (ip < iend-5)
  446. {
  447. ip+=2;
  448. bitStream = FSE_readLE32(ip) >> bitCount;
  449. }
  450. else
  451. {
  452. bitStream >>= 16;
  453. bitCount+=16;
  454. }
  455. }
  456. while ((bitStream & 3) == 3)
  457. {
  458. n0+=3;
  459. bitStream>>=2;
  460. bitCount+=2;
  461. }
  462. n0 += bitStream & 3;
  463. bitCount += 2;
  464. if (n0 > *maxSVPtr) return (size_t)-FSE_ERROR_maxSymbolValue_tooSmall;
  465. while (charnum < n0) normalizedCounter[charnum++] = 0;
  466. if ((ip <= iend-7) || (ip + (bitCount>>3) <= iend-4))
  467. {
  468. ip += bitCount>>3;
  469. bitCount &= 7;
  470. bitStream = FSE_readLE32(ip) >> bitCount;
  471. }
  472. else
  473. bitStream >>= 2;
  474. }
  475. {
  476. const short max = (short)((2*threshold-1)-remaining);
  477. short count;
  478. if ((bitStream & (threshold-1)) < (U32)max)
  479. {
  480. count = (short)(bitStream & (threshold-1));
  481. bitCount += nbBits-1;
  482. }
  483. else
  484. {
  485. count = (short)(bitStream & (2*threshold-1));
  486. if (count >= threshold) count -= max;
  487. bitCount += nbBits;
  488. }
  489. count--; /* extra accuracy */
  490. remaining -= FSE_abs(count);
  491. normalizedCounter[charnum++] = count;
  492. previous0 = !count;
  493. while (remaining < threshold)
  494. {
  495. nbBits--;
  496. threshold >>= 1;
  497. }
  498. {
  499. if ((ip <= iend-7) || (ip + (bitCount>>3) <= iend-4))
  500. {
  501. ip += bitCount>>3;
  502. bitCount &= 7;
  503. }
  504. else
  505. {
  506. bitCount -= (int)(8 * (iend - 4 - ip));
  507. ip = iend - 4;
  508. }
  509. bitStream = FSE_readLE32(ip) >> (bitCount & 31);
  510. }
  511. }
  512. }
  513. if (remaining != 1) return (size_t)-FSE_ERROR_GENERIC;
  514. *maxSVPtr = charnum-1;
  515. ip += (bitCount+7)>>3;
  516. if ((size_t)(ip-istart) > hbSize) return (size_t)-FSE_ERROR_srcSize_wrong;
  517. return ip-istart;
  518. }
  519. /*********************************************************
  520. * Decompression (Byte symbols)
  521. *********************************************************/
  522. static size_t FSE_buildDTable_rle (FSE_DTable* dt, BYTE symbolValue)
  523. {
  524. void* ptr = dt;
  525. FSE_DTableHeader* const DTableH = (FSE_DTableHeader*)ptr;
  526. FSE_decode_t* const cell = (FSE_decode_t*)(ptr) + 1; /* because dt is unsigned */
  527. DTableH->tableLog = 0;
  528. DTableH->fastMode = 0;
  529. cell->newState = 0;
  530. cell->symbol = symbolValue;
  531. cell->nbBits = 0;
  532. return 0;
  533. }
  534. static size_t FSE_buildDTable_raw (FSE_DTable* dt, unsigned nbBits)
  535. {
  536. void* ptr = dt;
  537. FSE_DTableHeader* const DTableH = (FSE_DTableHeader*)ptr;
  538. FSE_decode_t* const dinfo = (FSE_decode_t*)(ptr) + 1; /* because dt is unsigned */
  539. const unsigned tableSize = 1 << nbBits;
  540. const unsigned tableMask = tableSize - 1;
  541. const unsigned maxSymbolValue = tableMask;
  542. unsigned s;
  543. /* Sanity checks */
  544. if (nbBits < 1) return (size_t)-FSE_ERROR_GENERIC; /* min size */
  545. /* Build Decoding Table */
  546. DTableH->tableLog = (U16)nbBits;
  547. DTableH->fastMode = 1;
  548. for (s=0; s<=maxSymbolValue; s++)
  549. {
  550. dinfo[s].newState = 0;
  551. dinfo[s].symbol = (BYTE)s;
  552. dinfo[s].nbBits = (BYTE)nbBits;
  553. }
  554. return 0;
  555. }
  556. /* FSE_initDStream
  557. * Initialize a FSE_DStream_t.
  558. * srcBuffer must point at the beginning of an FSE block.
  559. * The function result is the size of the FSE_block (== srcSize).
  560. * If srcSize is too small, the function will return an errorCode;
  561. */
  562. static size_t FSE_initDStream(FSE_DStream_t* bitD, const void* srcBuffer, size_t srcSize)
  563. {
  564. if (srcSize < 1) return (size_t)-FSE_ERROR_srcSize_wrong;
  565. if (srcSize >= sizeof(size_t))
  566. {
  567. U32 contain32;
  568. bitD->start = (const char*)srcBuffer;
  569. bitD->ptr = (const char*)srcBuffer + srcSize - sizeof(size_t);
  570. bitD->bitContainer = FSE_readLEST(bitD->ptr);
  571. contain32 = ((const BYTE*)srcBuffer)[srcSize-1];
  572. if (contain32 == 0) return (size_t)-FSE_ERROR_GENERIC; /* stop bit not present */
  573. bitD->bitsConsumed = 8 - FSE_highbit32(contain32);
  574. }
  575. else
  576. {
  577. U32 contain32;
  578. bitD->start = (const char*)srcBuffer;
  579. bitD->ptr = bitD->start;
  580. bitD->bitContainer = *(const BYTE*)(bitD->start);
  581. switch(srcSize)
  582. {
  583. case 7: bitD->bitContainer += (size_t)(((const BYTE*)(bitD->start))[6]) << (sizeof(size_t)*8 - 16);
  584. case 6: bitD->bitContainer += (size_t)(((const BYTE*)(bitD->start))[5]) << (sizeof(size_t)*8 - 24);
  585. case 5: bitD->bitContainer += (size_t)(((const BYTE*)(bitD->start))[4]) << (sizeof(size_t)*8 - 32);
  586. case 4: bitD->bitContainer += (size_t)(((const BYTE*)(bitD->start))[3]) << 24;
  587. case 3: bitD->bitContainer += (size_t)(((const BYTE*)(bitD->start))[2]) << 16;
  588. case 2: bitD->bitContainer += (size_t)(((const BYTE*)(bitD->start))[1]) << 8;
  589. default:;
  590. }
  591. contain32 = ((const BYTE*)srcBuffer)[srcSize-1];
  592. if (contain32 == 0) return (size_t)-FSE_ERROR_GENERIC; /* stop bit not present */
  593. bitD->bitsConsumed = 8 - FSE_highbit32(contain32);
  594. bitD->bitsConsumed += (U32)(sizeof(size_t) - srcSize)*8;
  595. }
  596. return srcSize;
  597. }
  598. /*!FSE_lookBits
  599. * Provides next n bits from the bitContainer.
  600. * bitContainer is not modified (bits are still present for next read/look)
  601. * On 32-bits, maxNbBits==25
  602. * On 64-bits, maxNbBits==57
  603. * return : value extracted.
  604. */
  605. static size_t FSE_lookBits(FSE_DStream_t* bitD, U32 nbBits)
  606. {
  607. const U32 bitMask = sizeof(bitD->bitContainer)*8 - 1;
  608. return ((bitD->bitContainer << (bitD->bitsConsumed & bitMask)) >> 1) >> ((bitMask-nbBits) & bitMask);
  609. }
  610. static size_t FSE_lookBitsFast(FSE_DStream_t* bitD, U32 nbBits) /* only if nbBits >= 1 !! */
  611. {
  612. const U32 bitMask = sizeof(bitD->bitContainer)*8 - 1;
  613. return (bitD->bitContainer << (bitD->bitsConsumed & bitMask)) >> (((bitMask+1)-nbBits) & bitMask);
  614. }
  615. static void FSE_skipBits(FSE_DStream_t* bitD, U32 nbBits)
  616. {
  617. bitD->bitsConsumed += nbBits;
  618. }
  619. /*!FSE_readBits
  620. * Read next n bits from the bitContainer.
  621. * On 32-bits, don't read more than maxNbBits==25
  622. * On 64-bits, don't read more than maxNbBits==57
  623. * Use the fast variant *only* if n >= 1.
  624. * return : value extracted.
  625. */
  626. static size_t FSE_readBits(FSE_DStream_t* bitD, U32 nbBits)
  627. {
  628. size_t value = FSE_lookBits(bitD, nbBits);
  629. FSE_skipBits(bitD, nbBits);
  630. return value;
  631. }
  632. static size_t FSE_readBitsFast(FSE_DStream_t* bitD, U32 nbBits) /* only if nbBits >= 1 !! */
  633. {
  634. size_t value = FSE_lookBitsFast(bitD, nbBits);
  635. FSE_skipBits(bitD, nbBits);
  636. return value;
  637. }
  638. static unsigned FSE_reloadDStream(FSE_DStream_t* bitD)
  639. {
  640. if (bitD->bitsConsumed > (sizeof(bitD->bitContainer)*8)) /* should never happen */
  641. return FSE_DStream_tooFar;
  642. if (bitD->ptr >= bitD->start + sizeof(bitD->bitContainer))
  643. {
  644. bitD->ptr -= bitD->bitsConsumed >> 3;
  645. bitD->bitsConsumed &= 7;
  646. bitD->bitContainer = FSE_readLEST(bitD->ptr);
  647. return FSE_DStream_unfinished;
  648. }
  649. if (bitD->ptr == bitD->start)
  650. {
  651. if (bitD->bitsConsumed < sizeof(bitD->bitContainer)*8) return FSE_DStream_endOfBuffer;
  652. return FSE_DStream_completed;
  653. }
  654. {
  655. U32 nbBytes = bitD->bitsConsumed >> 3;
  656. U32 result = FSE_DStream_unfinished;
  657. if (bitD->ptr - nbBytes < bitD->start)
  658. {
  659. nbBytes = (U32)(bitD->ptr - bitD->start); /* ptr > start */
  660. result = FSE_DStream_endOfBuffer;
  661. }
  662. bitD->ptr -= nbBytes;
  663. bitD->bitsConsumed -= nbBytes*8;
  664. bitD->bitContainer = FSE_readLEST(bitD->ptr); /* reminder : srcSize > sizeof(bitD) */
  665. return result;
  666. }
  667. }
  668. static void FSE_initDState(FSE_DState_t* DStatePtr, FSE_DStream_t* bitD, const FSE_DTable* dt)
  669. {
  670. const void* ptr = dt;
  671. const FSE_DTableHeader* const DTableH = (const FSE_DTableHeader*)ptr;
  672. DStatePtr->state = FSE_readBits(bitD, DTableH->tableLog);
  673. FSE_reloadDStream(bitD);
  674. DStatePtr->table = dt + 1;
  675. }
  676. static BYTE FSE_decodeSymbol(FSE_DState_t* DStatePtr, FSE_DStream_t* bitD)
  677. {
  678. const FSE_decode_t DInfo = ((const FSE_decode_t*)(DStatePtr->table))[DStatePtr->state];
  679. const U32 nbBits = DInfo.nbBits;
  680. BYTE symbol = DInfo.symbol;
  681. size_t lowBits = FSE_readBits(bitD, nbBits);
  682. DStatePtr->state = DInfo.newState + lowBits;
  683. return symbol;
  684. }
  685. static BYTE FSE_decodeSymbolFast(FSE_DState_t* DStatePtr, FSE_DStream_t* bitD)
  686. {
  687. const FSE_decode_t DInfo = ((const FSE_decode_t*)(DStatePtr->table))[DStatePtr->state];
  688. const U32 nbBits = DInfo.nbBits;
  689. BYTE symbol = DInfo.symbol;
  690. size_t lowBits = FSE_readBitsFast(bitD, nbBits);
  691. DStatePtr->state = DInfo.newState + lowBits;
  692. return symbol;
  693. }
  694. /* FSE_endOfDStream
  695. Tells if bitD has reached end of bitStream or not */
  696. static unsigned FSE_endOfDStream(const FSE_DStream_t* bitD)
  697. {
  698. return ((bitD->ptr == bitD->start) && (bitD->bitsConsumed == sizeof(bitD->bitContainer)*8));
  699. }
  700. static unsigned FSE_endOfDState(const FSE_DState_t* DStatePtr)
  701. {
  702. return DStatePtr->state == 0;
  703. }
  704. FORCE_INLINE size_t FSE_decompress_usingDTable_generic(
  705. void* dst, size_t maxDstSize,
  706. const void* cSrc, size_t cSrcSize,
  707. const FSE_DTable* dt, const unsigned fast)
  708. {
  709. BYTE* const ostart = (BYTE*) dst;
  710. BYTE* op = ostart;
  711. BYTE* const omax = op + maxDstSize;
  712. BYTE* const olimit = omax-3;
  713. FSE_DStream_t bitD;
  714. FSE_DState_t state1;
  715. FSE_DState_t state2;
  716. size_t errorCode;
  717. /* Init */
  718. errorCode = FSE_initDStream(&bitD, cSrc, cSrcSize); /* replaced last arg by maxCompressed Size */
  719. if (FSE_isError(errorCode)) return errorCode;
  720. FSE_initDState(&state1, &bitD, dt);
  721. FSE_initDState(&state2, &bitD, dt);
  722. #define FSE_GETSYMBOL(statePtr) fast ? FSE_decodeSymbolFast(statePtr, &bitD) : FSE_decodeSymbol(statePtr, &bitD)
  723. /* 4 symbols per loop */
  724. for ( ; (FSE_reloadDStream(&bitD)==FSE_DStream_unfinished) && (op<olimit) ; op+=4)
  725. {
  726. op[0] = FSE_GETSYMBOL(&state1);
  727. if (FSE_MAX_TABLELOG*2+7 > sizeof(bitD.bitContainer)*8) /* This test must be static */
  728. FSE_reloadDStream(&bitD);
  729. op[1] = FSE_GETSYMBOL(&state2);
  730. if (FSE_MAX_TABLELOG*4+7 > sizeof(bitD.bitContainer)*8) /* This test must be static */
  731. { if (FSE_reloadDStream(&bitD) > FSE_DStream_unfinished) { op+=2; break; } }
  732. op[2] = FSE_GETSYMBOL(&state1);
  733. if (FSE_MAX_TABLELOG*2+7 > sizeof(bitD.bitContainer)*8) /* This test must be static */
  734. FSE_reloadDStream(&bitD);
  735. op[3] = FSE_GETSYMBOL(&state2);
  736. }
  737. /* tail */
  738. /* note : FSE_reloadDStream(&bitD) >= FSE_DStream_partiallyFilled; Ends at exactly FSE_DStream_completed */
  739. while (1)
  740. {
  741. if ( (FSE_reloadDStream(&bitD)>FSE_DStream_completed) || (op==omax) || (FSE_endOfDStream(&bitD) && (fast || FSE_endOfDState(&state1))) )
  742. break;
  743. *op++ = FSE_GETSYMBOL(&state1);
  744. if ( (FSE_reloadDStream(&bitD)>FSE_DStream_completed) || (op==omax) || (FSE_endOfDStream(&bitD) && (fast || FSE_endOfDState(&state2))) )
  745. break;
  746. *op++ = FSE_GETSYMBOL(&state2);
  747. }
  748. /* end ? */
  749. if (FSE_endOfDStream(&bitD) && FSE_endOfDState(&state1) && FSE_endOfDState(&state2))
  750. return op-ostart;
  751. if (op==omax) return (size_t)-FSE_ERROR_dstSize_tooSmall; /* dst buffer is full, but cSrc unfinished */
  752. return (size_t)-FSE_ERROR_corruptionDetected;
  753. }
  754. static size_t FSE_decompress_usingDTable(void* dst, size_t originalSize,
  755. const void* cSrc, size_t cSrcSize,
  756. const FSE_DTable* dt)
  757. {
  758. FSE_DTableHeader DTableH;
  759. memcpy(&DTableH, dt, sizeof(DTableH)); /* memcpy() into local variable, to avoid strict aliasing warning */
  760. /* select fast mode (static) */
  761. if (DTableH.fastMode) return FSE_decompress_usingDTable_generic(dst, originalSize, cSrc, cSrcSize, dt, 1);
  762. return FSE_decompress_usingDTable_generic(dst, originalSize, cSrc, cSrcSize, dt, 0);
  763. }
  764. static size_t FSE_decompress(void* dst, size_t maxDstSize, const void* cSrc, size_t cSrcSize)
  765. {
  766. const BYTE* const istart = (const BYTE*)cSrc;
  767. const BYTE* ip = istart;
  768. short counting[FSE_MAX_SYMBOL_VALUE+1];
  769. DTable_max_t dt; /* Static analyzer seems unable to understand this table will be properly initialized later */
  770. unsigned tableLog;
  771. unsigned maxSymbolValue = FSE_MAX_SYMBOL_VALUE;
  772. size_t errorCode;
  773. if (cSrcSize<2) return (size_t)-FSE_ERROR_srcSize_wrong; /* too small input size */
  774. /* normal FSE decoding mode */
  775. errorCode = FSE_readNCount (counting, &maxSymbolValue, &tableLog, istart, cSrcSize);
  776. if (FSE_isError(errorCode)) return errorCode;
  777. if (errorCode >= cSrcSize) return (size_t)-FSE_ERROR_srcSize_wrong; /* too small input size */
  778. ip += errorCode;
  779. cSrcSize -= errorCode;
  780. errorCode = FSE_buildDTable (dt, counting, maxSymbolValue, tableLog);
  781. if (FSE_isError(errorCode)) return errorCode;
  782. /* always return, even if it is an error code */
  783. return FSE_decompress_usingDTable (dst, maxDstSize, ip, cSrcSize, dt);
  784. }
  785. /* *******************************************************
  786. * Huff0 : Huffman block compression
  787. *********************************************************/
  788. #define HUF_MAX_SYMBOL_VALUE 255
  789. #define HUF_DEFAULT_TABLELOG 12 /* used by default, when not specified */
  790. #define HUF_MAX_TABLELOG 12 /* max possible tableLog; for allocation purpose; can be modified */
  791. #define HUF_ABSOLUTEMAX_TABLELOG 16 /* absolute limit of HUF_MAX_TABLELOG. Beyond that value, code does not work */
  792. #if (HUF_MAX_TABLELOG > HUF_ABSOLUTEMAX_TABLELOG)
  793. # error "HUF_MAX_TABLELOG is too large !"
  794. #endif
  795. typedef struct HUF_CElt_s {
  796. U16 val;
  797. BYTE nbBits;
  798. } HUF_CElt ;
  799. typedef struct nodeElt_s {
  800. U32 count;
  801. U16 parent;
  802. BYTE byte;
  803. BYTE nbBits;
  804. } nodeElt;
  805. /* *******************************************************
  806. * Huff0 : Huffman block decompression
  807. *********************************************************/
  808. typedef struct {
  809. BYTE byte;
  810. BYTE nbBits;
  811. } HUF_DElt;
  812. static size_t HUF_readDTable (U16* DTable, const void* src, size_t srcSize)
  813. {
  814. BYTE huffWeight[HUF_MAX_SYMBOL_VALUE + 1];
  815. U32 rankVal[HUF_ABSOLUTEMAX_TABLELOG + 1]; /* large enough for values from 0 to 16 */
  816. U32 weightTotal;
  817. U32 maxBits;
  818. const BYTE* ip = (const BYTE*) src;
  819. size_t iSize = ip[0];
  820. size_t oSize;
  821. U32 n;
  822. U32 nextRankStart;
  823. void* ptr = DTable+1;
  824. HUF_DElt* const dt = (HUF_DElt*)ptr;
  825. FSE_STATIC_ASSERT(sizeof(HUF_DElt) == sizeof(U16)); /* if compilation fails here, assertion is false */
  826. //memset(huffWeight, 0, sizeof(huffWeight)); /* should not be necessary, but some analyzer complain ... */
  827. if (iSize >= 128) /* special header */
  828. {
  829. if (iSize >= (242)) /* RLE */
  830. {
  831. static int l[14] = { 1, 2, 3, 4, 7, 8, 15, 16, 31, 32, 63, 64, 127, 128 };
  832. oSize = l[iSize-242];
  833. memset(huffWeight, 1, sizeof(huffWeight));
  834. iSize = 0;
  835. }
  836. else /* Incompressible */
  837. {
  838. oSize = iSize - 127;
  839. iSize = ((oSize+1)/2);
  840. if (iSize+1 > srcSize) return (size_t)-FSE_ERROR_srcSize_wrong;
  841. ip += 1;
  842. for (n=0; n<oSize; n+=2)
  843. {
  844. huffWeight[n] = ip[n/2] >> 4;
  845. huffWeight[n+1] = ip[n/2] & 15;
  846. }
  847. }
  848. }
  849. else /* header compressed with FSE (normal case) */
  850. {
  851. if (iSize+1 > srcSize) return (size_t)-FSE_ERROR_srcSize_wrong;
  852. oSize = FSE_decompress(huffWeight, HUF_MAX_SYMBOL_VALUE, ip+1, iSize); /* max 255 values decoded, last one is implied */
  853. if (FSE_isError(oSize)) return oSize;
  854. }
  855. /* collect weight stats */
  856. memset(rankVal, 0, sizeof(rankVal));
  857. weightTotal = 0;
  858. for (n=0; n<oSize; n++)
  859. {
  860. if (huffWeight[n] >= HUF_ABSOLUTEMAX_TABLELOG) return (size_t)-FSE_ERROR_corruptionDetected;
  861. rankVal[huffWeight[n]]++;
  862. weightTotal += (1 << huffWeight[n]) >> 1;
  863. }
  864. /* get last non-null symbol weight (implied, total must be 2^n) */
  865. maxBits = FSE_highbit32(weightTotal) + 1;
  866. if (maxBits > DTable[0]) return (size_t)-FSE_ERROR_tableLog_tooLarge; /* DTable is too small */
  867. DTable[0] = (U16)maxBits;
  868. {
  869. U32 total = 1 << maxBits;
  870. U32 rest = total - weightTotal;
  871. U32 verif = 1 << FSE_highbit32(rest);
  872. U32 lastWeight = FSE_highbit32(rest) + 1;
  873. if (verif != rest) return (size_t)-FSE_ERROR_corruptionDetected; /* last value must be a clean power of 2 */
  874. huffWeight[oSize] = (BYTE)lastWeight;
  875. rankVal[lastWeight]++;
  876. }
  877. /* check tree construction validity */
  878. if ((rankVal[1] < 2) || (rankVal[1] & 1)) return (size_t)-FSE_ERROR_corruptionDetected; /* by construction : at least 2 elts of rank 1, must be even */
  879. /* Prepare ranks */
  880. nextRankStart = 0;
  881. for (n=1; n<=maxBits; n++)
  882. {
  883. U32 current = nextRankStart;
  884. nextRankStart += (rankVal[n] << (n-1));
  885. rankVal[n] = current;
  886. }
  887. /* fill DTable */
  888. for (n=0; n<=oSize; n++)
  889. {
  890. const U32 w = huffWeight[n];
  891. const U32 length = (1 << w) >> 1;
  892. U32 i;
  893. HUF_DElt D;
  894. D.byte = (BYTE)n; D.nbBits = (BYTE)(maxBits + 1 - w);
  895. for (i = rankVal[w]; i < rankVal[w] + length; i++)
  896. dt[i] = D;
  897. rankVal[w] += length;
  898. }
  899. return iSize+1;
  900. }
  901. static BYTE HUF_decodeSymbol(FSE_DStream_t* Dstream, const HUF_DElt* dt, const U32 dtLog)
  902. {
  903. const size_t val = FSE_lookBitsFast(Dstream, dtLog); /* note : dtLog >= 1 */
  904. const BYTE c = dt[val].byte;
  905. FSE_skipBits(Dstream, dt[val].nbBits);
  906. return c;
  907. }
  908. static size_t HUF_decompress_usingDTable( /* -3% slower when non static */
  909. void* dst, size_t maxDstSize,
  910. const void* cSrc, size_t cSrcSize,
  911. const U16* DTable)
  912. {
  913. BYTE* const ostart = (BYTE*) dst;
  914. BYTE* op = ostart;
  915. BYTE* const omax = op + maxDstSize;
  916. BYTE* const olimit = omax-15;
  917. const void* ptr = DTable;
  918. const HUF_DElt* const dt = (const HUF_DElt*)(ptr)+1;
  919. const U32 dtLog = DTable[0];
  920. size_t errorCode;
  921. U32 reloadStatus;
  922. /* Init */
  923. const U16* jumpTable = (const U16*)cSrc;
  924. const size_t length1 = FSE_readLE16(jumpTable);
  925. const size_t length2 = FSE_readLE16(jumpTable+1);
  926. const size_t length3 = FSE_readLE16(jumpTable+2);
  927. const size_t length4 = cSrcSize - 6 - length1 - length2 - length3; // check coherency !!
  928. const char* const start1 = (const char*)(cSrc) + 6;
  929. const char* const start2 = start1 + length1;
  930. const char* const start3 = start2 + length2;
  931. const char* const start4 = start3 + length3;
  932. FSE_DStream_t bitD1, bitD2, bitD3, bitD4;
  933. if (length1+length2+length3+6 >= cSrcSize) return (size_t)-FSE_ERROR_srcSize_wrong;
  934. errorCode = FSE_initDStream(&bitD1, start1, length1);
  935. if (FSE_isError(errorCode)) return errorCode;
  936. errorCode = FSE_initDStream(&bitD2, start2, length2);
  937. if (FSE_isError(errorCode)) return errorCode;
  938. errorCode = FSE_initDStream(&bitD3, start3, length3);
  939. if (FSE_isError(errorCode)) return errorCode;
  940. errorCode = FSE_initDStream(&bitD4, start4, length4);
  941. if (FSE_isError(errorCode)) return errorCode;
  942. reloadStatus=FSE_reloadDStream(&bitD2);
  943. /* 16 symbols per loop */
  944. for ( ; (reloadStatus<FSE_DStream_completed) && (op<olimit); /* D2-3-4 are supposed to be synchronized and finish together */
  945. op+=16, reloadStatus = FSE_reloadDStream(&bitD2) | FSE_reloadDStream(&bitD3) | FSE_reloadDStream(&bitD4), FSE_reloadDStream(&bitD1))
  946. {
  947. #define HUF_DECODE_SYMBOL_0(n, Dstream) \
  948. op[n] = HUF_decodeSymbol(&Dstream, dt, dtLog);
  949. #define HUF_DECODE_SYMBOL_1(n, Dstream) \
  950. op[n] = HUF_decodeSymbol(&Dstream, dt, dtLog); \
  951. if (FSE_32bits() && (HUF_MAX_TABLELOG>12)) FSE_reloadDStream(&Dstream)
  952. #define HUF_DECODE_SYMBOL_2(n, Dstream) \
  953. op[n] = HUF_decodeSymbol(&Dstream, dt, dtLog); \
  954. if (FSE_32bits()) FSE_reloadDStream(&Dstream)
  955. HUF_DECODE_SYMBOL_1( 0, bitD1);
  956. HUF_DECODE_SYMBOL_1( 1, bitD2);
  957. HUF_DECODE_SYMBOL_1( 2, bitD3);
  958. HUF_DECODE_SYMBOL_1( 3, bitD4);
  959. HUF_DECODE_SYMBOL_2( 4, bitD1);
  960. HUF_DECODE_SYMBOL_2( 5, bitD2);
  961. HUF_DECODE_SYMBOL_2( 6, bitD3);
  962. HUF_DECODE_SYMBOL_2( 7, bitD4);
  963. HUF_DECODE_SYMBOL_1( 8, bitD1);
  964. HUF_DECODE_SYMBOL_1( 9, bitD2);
  965. HUF_DECODE_SYMBOL_1(10, bitD3);
  966. HUF_DECODE_SYMBOL_1(11, bitD4);
  967. HUF_DECODE_SYMBOL_0(12, bitD1);
  968. HUF_DECODE_SYMBOL_0(13, bitD2);
  969. HUF_DECODE_SYMBOL_0(14, bitD3);
  970. HUF_DECODE_SYMBOL_0(15, bitD4);
  971. }
  972. if (reloadStatus!=FSE_DStream_completed) /* not complete : some bitStream might be FSE_DStream_unfinished */
  973. return (size_t)-FSE_ERROR_corruptionDetected;
  974. /* tail */
  975. {
  976. // bitTail = bitD1; // *much* slower : -20% !??!
  977. FSE_DStream_t bitTail;
  978. bitTail.ptr = bitD1.ptr;
  979. bitTail.bitsConsumed = bitD1.bitsConsumed;
  980. bitTail.bitContainer = bitD1.bitContainer; // required in case of FSE_DStream_endOfBuffer
  981. bitTail.start = start1;
  982. for ( ; (FSE_reloadDStream(&bitTail) < FSE_DStream_completed) && (op<omax) ; op++)
  983. {
  984. HUF_DECODE_SYMBOL_0(0, bitTail);
  985. }
  986. if (FSE_endOfDStream(&bitTail))
  987. return op-ostart;
  988. }
  989. if (op==omax) return (size_t)-FSE_ERROR_dstSize_tooSmall; /* dst buffer is full, but cSrc unfinished */
  990. return (size_t)-FSE_ERROR_corruptionDetected;
  991. }
  992. static size_t HUF_decompress (void* dst, size_t maxDstSize, const void* cSrc, size_t cSrcSize)
  993. {
  994. HUF_CREATE_STATIC_DTABLE(DTable, HUF_MAX_TABLELOG);
  995. const BYTE* ip = (const BYTE*) cSrc;
  996. size_t errorCode;
  997. errorCode = HUF_readDTable (DTable, cSrc, cSrcSize);
  998. if (FSE_isError(errorCode)) return errorCode;
  999. if (errorCode >= cSrcSize) return (size_t)-FSE_ERROR_srcSize_wrong;
  1000. ip += errorCode;
  1001. cSrcSize -= errorCode;
  1002. return HUF_decompress_usingDTable (dst, maxDstSize, ip, cSrcSize, DTable);
  1003. }
  1004. #endif /* FSE_COMMONDEFS_ONLY */
  1005. /*
  1006. zstd - standard compression library
  1007. Header File for static linking only
  1008. Copyright (C) 2014-2015, Yann Collet.
  1009. BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
  1010. Redistribution and use in source and binary forms, with or without
  1011. modification, are permitted provided that the following conditions are
  1012. met:
  1013. * Redistributions of source code must retain the above copyright
  1014. notice, this list of conditions and the following disclaimer.
  1015. * Redistributions in binary form must reproduce the above
  1016. copyright notice, this list of conditions and the following disclaimer
  1017. in the documentation and/or other materials provided with the
  1018. distribution.
  1019. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  1020. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  1021. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  1022. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  1023. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  1024. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  1025. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  1026. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  1027. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  1028. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  1029. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  1030. You can contact the author at :
  1031. - zstd source repository : https://github.com/Cyan4973/zstd
  1032. - ztsd public forum : https://groups.google.com/forum/#!forum/lz4c
  1033. */
  1034. /* The objects defined into this file should be considered experimental.
  1035. * They are not labelled stable, as their prototype may change in the future.
  1036. * You can use them for tests, provide feedback, or if you can endure risk of future changes.
  1037. */
  1038. /**************************************
  1039. * Error management
  1040. **************************************/
  1041. #define ZSTD_LIST_ERRORS(ITEM) \
  1042. ITEM(ZSTD_OK_NoError) ITEM(ZSTD_ERROR_GENERIC) \
  1043. ITEM(ZSTD_ERROR_MagicNumber) \
  1044. ITEM(ZSTD_ERROR_SrcSize) ITEM(ZSTD_ERROR_maxDstSize_tooSmall) \
  1045. ITEM(ZSTD_ERROR_corruption) \
  1046. ITEM(ZSTD_ERROR_maxCode)
  1047. #define ZSTD_GENERATE_ENUM(ENUM) ENUM,
  1048. typedef enum { ZSTD_LIST_ERRORS(ZSTD_GENERATE_ENUM) } ZSTD_errorCodes; /* exposed list of errors; static linking only */
  1049. /*
  1050. zstd - standard compression library
  1051. Copyright (C) 2014-2015, Yann Collet.
  1052. BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
  1053. Redistribution and use in source and binary forms, with or without
  1054. modification, are permitted provided that the following conditions are
  1055. met:
  1056. * Redistributions of source code must retain the above copyright
  1057. notice, this list of conditions and the following disclaimer.
  1058. * Redistributions in binary form must reproduce the above
  1059. copyright notice, this list of conditions and the following disclaimer
  1060. in the documentation and/or other materials provided with the
  1061. distribution.
  1062. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  1063. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  1064. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  1065. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  1066. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  1067. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  1068. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  1069. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  1070. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  1071. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  1072. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  1073. You can contact the author at :
  1074. - zstd source repository : https://github.com/Cyan4973/zstd
  1075. - ztsd public forum : https://groups.google.com/forum/#!forum/lz4c
  1076. */
  1077. /****************************************************************
  1078. * Tuning parameters
  1079. *****************************************************************/
  1080. /* MEMORY_USAGE :
  1081. * Memory usage formula : N->2^N Bytes (examples : 10 -> 1KB; 12 -> 4KB ; 16 -> 64KB; 20 -> 1MB; etc.)
  1082. * Increasing memory usage improves compression ratio
  1083. * Reduced memory usage can improve speed, due to cache effect */
  1084. #define ZSTD_MEMORY_USAGE 17
  1085. /**************************************
  1086. CPU Feature Detection
  1087. **************************************/
  1088. /*
  1089. * Automated efficient unaligned memory access detection
  1090. * Based on known hardware architectures
  1091. * This list will be updated thanks to feedbacks
  1092. */
  1093. #if defined(CPU_HAS_EFFICIENT_UNALIGNED_MEMORY_ACCESS) \
  1094. || defined(__ARM_FEATURE_UNALIGNED) \
  1095. || defined(__i386__) || defined(__x86_64__) \
  1096. || defined(_M_IX86) || defined(_M_X64) \
  1097. || defined(__ARM_ARCH_7__) || defined(__ARM_ARCH_8__) \
  1098. || (defined(_M_ARM) && (_M_ARM >= 7))
  1099. # define ZSTD_UNALIGNED_ACCESS 1
  1100. #else
  1101. # define ZSTD_UNALIGNED_ACCESS 0
  1102. #endif
  1103. /********************************************************
  1104. * Includes
  1105. *********************************************************/
  1106. #include <stdlib.h> /* calloc */
  1107. #include <string.h> /* memcpy, memmove */
  1108. #include <stdio.h> /* debug : printf */
  1109. /********************************************************
  1110. * Compiler specifics
  1111. *********************************************************/
  1112. #ifdef __AVX2__
  1113. # include <immintrin.h> /* AVX2 intrinsics */
  1114. #endif
  1115. #ifdef _MSC_VER /* Visual Studio */
  1116. # define FORCE_INLINE static __forceinline
  1117. # include <intrin.h> /* For Visual 2005 */
  1118. # pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */
  1119. # pragma warning(disable : 4324) /* disable: C4324: padded structure */
  1120. #else
  1121. # define GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__)
  1122. # ifdef __GNUC__
  1123. # define FORCE_INLINE static inline __attribute__((always_inline))
  1124. # else
  1125. # define FORCE_INLINE static inline
  1126. # endif
  1127. #endif
  1128. #ifndef MEM_ACCESS_MODULE
  1129. #define MEM_ACCESS_MODULE
  1130. /********************************************************
  1131. * Basic Types
  1132. *********************************************************/
  1133. #if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* C99 */
  1134. # include <stdint.h>
  1135. typedef uint8_t BYTE;
  1136. typedef uint16_t U16;
  1137. typedef int16_t S16;
  1138. typedef uint32_t U32;
  1139. typedef int32_t S32;
  1140. typedef uint64_t U64;
  1141. #else
  1142. typedef unsigned char BYTE;
  1143. typedef unsigned short U16;
  1144. typedef signed short S16;
  1145. typedef unsigned int U32;
  1146. typedef signed int S32;
  1147. typedef unsigned long long U64;
  1148. #endif
  1149. #endif /* MEM_ACCESS_MODULE */
  1150. /********************************************************
  1151. * Constants
  1152. *********************************************************/
  1153. static const U32 ZSTD_magicNumber = 0xFD2FB51E; /* 3rd version : seqNb header */
  1154. #define HASH_LOG (ZSTD_MEMORY_USAGE - 2)
  1155. #define HASH_TABLESIZE (1 << HASH_LOG)
  1156. #define HASH_MASK (HASH_TABLESIZE - 1)
  1157. #define KNUTH 2654435761
  1158. #define BIT7 128
  1159. #define BIT6 64
  1160. #define BIT5 32
  1161. #define BIT4 16
  1162. #define KB *(1 <<10)
  1163. #define MB *(1 <<20)
  1164. #define GB *(1U<<30)
  1165. #define BLOCKSIZE (128 KB) /* define, for static allocation */
  1166. #define WORKPLACESIZE (BLOCKSIZE*3)
  1167. #define MINMATCH 4
  1168. #define MLbits 7
  1169. #define LLbits 6
  1170. #define Offbits 5
  1171. #define MaxML ((1<<MLbits )-1)
  1172. #define MaxLL ((1<<LLbits )-1)
  1173. #define MaxOff ((1<<Offbits)-1)
  1174. #define LitFSELog 11
  1175. #define MLFSELog 10
  1176. #define LLFSELog 10
  1177. #define OffFSELog 9
  1178. #define MAX(a,b) ((a)<(b)?(b):(a))
  1179. #define MaxSeq MAX(MaxLL, MaxML)
  1180. #define LITERAL_NOENTROPY 63
  1181. #define COMMAND_NOENTROPY 7 /* to remove */
  1182. static const size_t ZSTD_blockHeaderSize = 3;
  1183. static const size_t ZSTD_frameHeaderSize = 4;
  1184. /********************************************************
  1185. * Memory operations
  1186. *********************************************************/
  1187. static unsigned ZSTD_32bits(void) { return sizeof(void*)==4; }
  1188. static unsigned ZSTD_isLittleEndian(void)
  1189. {
  1190. const union { U32 i; BYTE c[4]; } one = { 1 }; /* don't use static : performance detrimental */
  1191. return one.c[0];
  1192. }
  1193. static U16 ZSTD_read16(const void* p) { U16 r; memcpy(&r, p, sizeof(r)); return r; }
  1194. static U32 ZSTD_read32(const void* p) { U32 r; memcpy(&r, p, sizeof(r)); return r; }
  1195. static void ZSTD_copy4(void* dst, const void* src) { memcpy(dst, src, 4); }
  1196. static void ZSTD_copy8(void* dst, const void* src) { memcpy(dst, src, 8); }
  1197. #define COPY8(d,s) { ZSTD_copy8(d,s); d+=8; s+=8; }
  1198. static void ZSTD_wildcopy(void* dst, const void* src, size_t length)
  1199. {
  1200. const BYTE* ip = (const BYTE*)src;
  1201. BYTE* op = (BYTE*)dst;
  1202. BYTE* const oend = op + length;
  1203. while (op < oend) COPY8(op, ip);
  1204. }
  1205. static U16 ZSTD_readLE16(const void* memPtr)
  1206. {
  1207. if (ZSTD_isLittleEndian()) return ZSTD_read16(memPtr);
  1208. else
  1209. {
  1210. const BYTE* p = (const BYTE*)memPtr;
  1211. return (U16)((U16)p[0] + ((U16)p[1]<<8));
  1212. }
  1213. }
  1214. static U32 ZSTD_readLE32(const void* memPtr)
  1215. {
  1216. if (ZSTD_isLittleEndian())
  1217. return ZSTD_read32(memPtr);
  1218. else
  1219. {
  1220. const BYTE* p = (const BYTE*)memPtr;
  1221. return (U32)((U32)p[0] + ((U32)p[1]<<8) + ((U32)p[2]<<16) + ((U32)p[3]<<24));
  1222. }
  1223. }
  1224. static U32 ZSTD_readBE32(const void* memPtr)
  1225. {
  1226. const BYTE* p = (const BYTE*)memPtr;
  1227. return (U32)(((U32)p[0]<<24) + ((U32)p[1]<<16) + ((U32)p[2]<<8) + ((U32)p[3]<<0));
  1228. }
  1229. /**************************************
  1230. * Local structures
  1231. ***************************************/
  1232. typedef struct ZSTD_Cctx_s ZSTD_Cctx;
  1233. typedef enum { bt_compressed, bt_raw, bt_rle, bt_end } blockType_t;
  1234. typedef struct
  1235. {
  1236. blockType_t blockType;
  1237. U32 origSize;
  1238. } blockProperties_t;
  1239. typedef struct {
  1240. void* buffer;
  1241. U32* offsetStart;
  1242. U32* offset;
  1243. BYTE* offCodeStart;
  1244. BYTE* offCode;
  1245. BYTE* litStart;
  1246. BYTE* lit;
  1247. BYTE* litLengthStart;
  1248. BYTE* litLength;
  1249. BYTE* matchLengthStart;
  1250. BYTE* matchLength;
  1251. BYTE* dumpsStart;
  1252. BYTE* dumps;
  1253. } seqStore_t;
  1254. typedef struct ZSTD_Cctx_s
  1255. {
  1256. const BYTE* base;
  1257. U32 current;
  1258. U32 nextUpdate;
  1259. seqStore_t seqStore;
  1260. #ifdef __AVX2__
  1261. __m256i hashTable[HASH_TABLESIZE>>3];
  1262. #else
  1263. U32 hashTable[HASH_TABLESIZE];
  1264. #endif
  1265. BYTE buffer[WORKPLACESIZE];
  1266. } cctxi_t;
  1267. /**************************************
  1268. * Error Management
  1269. **************************************/
  1270. /* tells if a return value is an error code */
  1271. static unsigned ZSTD_isError(size_t code) { return (code > (size_t)(-ZSTD_ERROR_maxCode)); }
  1272. /* published entry point */
  1273. unsigned ZSTDv01_isError(size_t code) { return ZSTD_isError(code); }
  1274. /**************************************
  1275. * Tool functions
  1276. **************************************/
  1277. #define ZSTD_VERSION_MAJOR 0 /* for breaking interface changes */
  1278. #define ZSTD_VERSION_MINOR 1 /* for new (non-breaking) interface capabilities */
  1279. #define ZSTD_VERSION_RELEASE 3 /* for tweaks, bug-fixes, or development */
  1280. #define ZSTD_VERSION_NUMBER (ZSTD_VERSION_MAJOR *100*100 + ZSTD_VERSION_MINOR *100 + ZSTD_VERSION_RELEASE)
  1281. /**************************************************************
  1282. * Decompression code
  1283. **************************************************************/
  1284. static size_t ZSTD_getcBlockSize(const void* src, size_t srcSize, blockProperties_t* bpPtr)
  1285. {
  1286. const BYTE* const in = (const BYTE* const)src;
  1287. BYTE headerFlags;
  1288. U32 cSize;
  1289. if (srcSize < 3) return (size_t)-ZSTD_ERROR_SrcSize;
  1290. headerFlags = *in;
  1291. cSize = in[2] + (in[1]<<8) + ((in[0] & 7)<<16);
  1292. bpPtr->blockType = (blockType_t)(headerFlags >> 6);
  1293. bpPtr->origSize = (bpPtr->blockType == bt_rle) ? cSize : 0;
  1294. if (bpPtr->blockType == bt_end) return 0;
  1295. if (bpPtr->blockType == bt_rle) return 1;
  1296. return cSize;
  1297. }
  1298. static size_t ZSTD_copyUncompressedBlock(void* dst, size_t maxDstSize, const void* src, size_t srcSize)
  1299. {
  1300. if (srcSize > maxDstSize) return (size_t)-ZSTD_ERROR_maxDstSize_tooSmall;
  1301. memcpy(dst, src, srcSize);
  1302. return srcSize;
  1303. }
  1304. static size_t ZSTD_decompressLiterals(void* ctx,
  1305. void* dst, size_t maxDstSize,
  1306. const void* src, size_t srcSize)
  1307. {
  1308. BYTE* op = (BYTE*)dst;
  1309. BYTE* const oend = op + maxDstSize;
  1310. const BYTE* ip = (const BYTE*)src;
  1311. size_t errorCode;
  1312. size_t litSize;
  1313. /* check : minimum 2, for litSize, +1, for content */
  1314. if (srcSize <= 3) return (size_t)-ZSTD_ERROR_corruption;
  1315. litSize = ip[1] + (ip[0]<<8);
  1316. litSize += ((ip[-3] >> 3) & 7) << 16; // mmmmh....
  1317. op = oend - litSize;
  1318. (void)ctx;
  1319. if (litSize > maxDstSize) return (size_t)-ZSTD_ERROR_maxDstSize_tooSmall;
  1320. errorCode = HUF_decompress(op, litSize, ip+2, srcSize-2);
  1321. if (FSE_isError(errorCode)) return (size_t)-ZSTD_ERROR_GENERIC;
  1322. return litSize;
  1323. }
  1324. static size_t ZSTD_decodeLiteralsBlock(void* ctx,
  1325. void* dst, size_t maxDstSize,
  1326. const BYTE** litStart, size_t* litSize,
  1327. const void* src, size_t srcSize)
  1328. {
  1329. const BYTE* const istart = (const BYTE* const)src;
  1330. const BYTE* ip = istart;
  1331. BYTE* const ostart = (BYTE* const)dst;
  1332. BYTE* const oend = ostart + maxDstSize;
  1333. blockProperties_t litbp;
  1334. size_t litcSize = ZSTD_getcBlockSize(src, srcSize, &litbp);
  1335. if (ZSTD_isError(litcSize)) return litcSize;
  1336. if (litcSize > srcSize - ZSTD_blockHeaderSize) return (size_t)-ZSTD_ERROR_SrcSize;
  1337. ip += ZSTD_blockHeaderSize;
  1338. switch(litbp.blockType)
  1339. {
  1340. case bt_raw:
  1341. *litStart = ip;
  1342. ip += litcSize;
  1343. *litSize = litcSize;
  1344. break;
  1345. case bt_rle:
  1346. {
  1347. size_t rleSize = litbp.origSize;
  1348. if (rleSize>maxDstSize) return (size_t)-ZSTD_ERROR_maxDstSize_tooSmall;
  1349. memset(oend - rleSize, *ip, rleSize);
  1350. *litStart = oend - rleSize;
  1351. *litSize = rleSize;
  1352. ip++;
  1353. break;
  1354. }
  1355. case bt_compressed:
  1356. {
  1357. size_t decodedLitSize = ZSTD_decompressLiterals(ctx, dst, maxDstSize, ip, litcSize);
  1358. if (ZSTD_isError(decodedLitSize)) return decodedLitSize;
  1359. *litStart = oend - decodedLitSize;
  1360. *litSize = decodedLitSize;
  1361. ip += litcSize;
  1362. break;
  1363. }
  1364. case bt_end:
  1365. default:
  1366. return (size_t)-ZSTD_ERROR_GENERIC;
  1367. }
  1368. return ip-istart;
  1369. }
  1370. static size_t ZSTD_decodeSeqHeaders(int* nbSeq, const BYTE** dumpsPtr, size_t* dumpsLengthPtr,
  1371. FSE_DTable* DTableLL, FSE_DTable* DTableML, FSE_DTable* DTableOffb,
  1372. const void* src, size_t srcSize)
  1373. {
  1374. const BYTE* const istart = (const BYTE* const)src;
  1375. const BYTE* ip = istart;
  1376. const BYTE* const iend = istart + srcSize;
  1377. U32 LLtype, Offtype, MLtype;
  1378. U32 LLlog, Offlog, MLlog;
  1379. size_t dumpsLength;
  1380. /* check */
  1381. if (srcSize < 5) return (size_t)-ZSTD_ERROR_SrcSize;
  1382. /* SeqHead */
  1383. *nbSeq = ZSTD_readLE16(ip); ip+=2;
  1384. LLtype = *ip >> 6;
  1385. Offtype = (*ip >> 4) & 3;
  1386. MLtype = (*ip >> 2) & 3;
  1387. if (*ip & 2)
  1388. {
  1389. dumpsLength = ip[2];
  1390. dumpsLength += ip[1] << 8;
  1391. ip += 3;
  1392. }
  1393. else
  1394. {
  1395. dumpsLength = ip[1];
  1396. dumpsLength += (ip[0] & 1) << 8;
  1397. ip += 2;
  1398. }
  1399. *dumpsPtr = ip;
  1400. ip += dumpsLength;
  1401. *dumpsLengthPtr = dumpsLength;
  1402. /* check */
  1403. if (ip > iend-3) return (size_t)-ZSTD_ERROR_SrcSize; /* min : all 3 are "raw", hence no header, but at least xxLog bits per type */
  1404. /* sequences */
  1405. {
  1406. S16 norm[MaxML+1]; /* assumption : MaxML >= MaxLL and MaxOff */
  1407. size_t headerSize;
  1408. /* Build DTables */
  1409. switch(LLtype)
  1410. {
  1411. U32 max;
  1412. case bt_rle :
  1413. LLlog = 0;
  1414. FSE_buildDTable_rle(DTableLL, *ip++); break;
  1415. case bt_raw :
  1416. LLlog = LLbits;
  1417. FSE_buildDTable_raw(DTableLL, LLbits); break;
  1418. default :
  1419. max = MaxLL;
  1420. headerSize = FSE_readNCount(norm, &max, &LLlog, ip, iend-ip);
  1421. if (FSE_isError(headerSize)) return (size_t)-ZSTD_ERROR_GENERIC;
  1422. if (LLlog > LLFSELog) return (size_t)-ZSTD_ERROR_corruption;
  1423. ip += headerSize;
  1424. FSE_buildDTable(DTableLL, norm, max, LLlog);
  1425. }
  1426. switch(Offtype)
  1427. {
  1428. U32 max;
  1429. case bt_rle :
  1430. Offlog = 0;
  1431. if (ip > iend-2) return (size_t)-ZSTD_ERROR_SrcSize; /* min : "raw", hence no header, but at least xxLog bits */
  1432. FSE_buildDTable_rle(DTableOffb, *ip++); break;
  1433. case bt_raw :
  1434. Offlog = Offbits;
  1435. FSE_buildDTable_raw(DTableOffb, Offbits); break;
  1436. default :
  1437. max = MaxOff;
  1438. headerSize = FSE_readNCount(norm, &max, &Offlog, ip, iend-ip);
  1439. if (FSE_isError(headerSize)) return (size_t)-ZSTD_ERROR_GENERIC;
  1440. if (Offlog > OffFSELog) return (size_t)-ZSTD_ERROR_corruption;
  1441. ip += headerSize;
  1442. FSE_buildDTable(DTableOffb, norm, max, Offlog);
  1443. }
  1444. switch(MLtype)
  1445. {
  1446. U32 max;
  1447. case bt_rle :
  1448. MLlog = 0;
  1449. if (ip > iend-2) return (size_t)-ZSTD_ERROR_SrcSize; /* min : "raw", hence no header, but at least xxLog bits */
  1450. FSE_buildDTable_rle(DTableML, *ip++); break;
  1451. case bt_raw :
  1452. MLlog = MLbits;
  1453. FSE_buildDTable_raw(DTableML, MLbits); break;
  1454. default :
  1455. max = MaxML;
  1456. headerSize = FSE_readNCount(norm, &max, &MLlog, ip, iend-ip);
  1457. if (FSE_isError(headerSize)) return (size_t)-ZSTD_ERROR_GENERIC;
  1458. if (MLlog > MLFSELog) return (size_t)-ZSTD_ERROR_corruption;
  1459. ip += headerSize;
  1460. FSE_buildDTable(DTableML, norm, max, MLlog);
  1461. }
  1462. }
  1463. return ip-istart;
  1464. }
  1465. typedef struct {
  1466. size_t litLength;
  1467. size_t offset;
  1468. size_t matchLength;
  1469. } seq_t;
  1470. typedef struct {
  1471. FSE_DStream_t DStream;
  1472. FSE_DState_t stateLL;
  1473. FSE_DState_t stateOffb;
  1474. FSE_DState_t stateML;
  1475. size_t prevOffset;
  1476. const BYTE* dumps;
  1477. const BYTE* dumpsEnd;
  1478. } seqState_t;
  1479. static void ZSTD_decodeSequence(seq_t* seq, seqState_t* seqState)
  1480. {
  1481. size_t litLength;
  1482. size_t prevOffset;
  1483. size_t offset;
  1484. size_t matchLength;
  1485. const BYTE* dumps = seqState->dumps;
  1486. const BYTE* const de = seqState->dumpsEnd;
  1487. /* Literal length */
  1488. litLength = FSE_decodeSymbol(&(seqState->stateLL), &(seqState->DStream));
  1489. prevOffset = litLength ? seq->offset : seqState->prevOffset;
  1490. seqState->prevOffset = seq->offset;
  1491. if (litLength == MaxLL)
  1492. {
  1493. U32 add = dumps<de ? *dumps++ : 0;
  1494. if (add < 255) litLength += add;
  1495. else
  1496. {
  1497. if (dumps<=(de-3))
  1498. {
  1499. litLength = ZSTD_readLE32(dumps) & 0xFFFFFF; /* no pb : dumps is always followed by seq tables > 1 byte */
  1500. dumps += 3;
  1501. }
  1502. }
  1503. }
  1504. /* Offset */
  1505. {
  1506. U32 offsetCode, nbBits;
  1507. offsetCode = FSE_decodeSymbol(&(seqState->stateOffb), &(seqState->DStream));
  1508. if (ZSTD_32bits()) FSE_reloadDStream(&(seqState->DStream));
  1509. nbBits = offsetCode - 1;
  1510. if (offsetCode==0) nbBits = 0; /* cmove */
  1511. offset = ((size_t)1 << (nbBits & ((sizeof(offset)*8)-1))) + FSE_readBits(&(seqState->DStream), nbBits);
  1512. if (ZSTD_32bits()) FSE_reloadDStream(&(seqState->DStream));
  1513. if (offsetCode==0) offset = prevOffset;
  1514. }
  1515. /* MatchLength */
  1516. matchLength = FSE_decodeSymbol(&(seqState->stateML), &(seqState->DStream));
  1517. if (matchLength == MaxML)
  1518. {
  1519. U32 add = dumps<de ? *dumps++ : 0;
  1520. if (add < 255) matchLength += add;
  1521. else
  1522. {
  1523. if (dumps<=(de-3))
  1524. {
  1525. matchLength = ZSTD_readLE32(dumps) & 0xFFFFFF; /* no pb : dumps is always followed by seq tables > 1 byte */
  1526. dumps += 3;
  1527. }
  1528. }
  1529. }
  1530. matchLength += MINMATCH;
  1531. /* save result */
  1532. seq->litLength = litLength;
  1533. seq->offset = offset;
  1534. seq->matchLength = matchLength;
  1535. seqState->dumps = dumps;
  1536. }
  1537. static size_t ZSTD_execSequence(BYTE* op,
  1538. seq_t sequence,
  1539. const BYTE** litPtr, const BYTE* const litLimit,
  1540. BYTE* const base, BYTE* const oend)
  1541. {
  1542. static const int dec32table[] = {0, 1, 2, 1, 4, 4, 4, 4}; /* added */
  1543. static const int dec64table[] = {8, 8, 8, 7, 8, 9,10,11}; /* substracted */
  1544. const BYTE* const ostart = op;
  1545. const size_t litLength = sequence.litLength;
  1546. BYTE* const endMatch = op + litLength + sequence.matchLength; /* risk : address space overflow (32-bits) */
  1547. const BYTE* const litEnd = *litPtr + litLength;
  1548. /* check */
  1549. if (endMatch > oend) return (size_t)-ZSTD_ERROR_maxDstSize_tooSmall; /* overwrite beyond dst buffer */
  1550. if (litEnd > litLimit) return (size_t)-ZSTD_ERROR_corruption;
  1551. if (sequence.matchLength > (size_t)(*litPtr-op)) return (size_t)-ZSTD_ERROR_maxDstSize_tooSmall; /* overwrite literal segment */
  1552. /* copy Literals */
  1553. if (((size_t)(*litPtr - op) < 8) || ((size_t)(oend-litEnd) < 8) || (op+litLength > oend-8))
  1554. memmove(op, *litPtr, litLength); /* overwrite risk */
  1555. else
  1556. ZSTD_wildcopy(op, *litPtr, litLength);
  1557. op += litLength;
  1558. *litPtr = litEnd; /* update for next sequence */
  1559. /* check : last match must be at a minimum distance of 8 from end of dest buffer */
  1560. if (oend-op < 8) return (size_t)-ZSTD_ERROR_maxDstSize_tooSmall;
  1561. /* copy Match */
  1562. {
  1563. const U32 overlapRisk = (((size_t)(litEnd - endMatch)) < 12);
  1564. const BYTE* match = op - sequence.offset; /* possible underflow at op - offset ? */
  1565. size_t qutt = 12;
  1566. U64 saved[2];
  1567. /* check */
  1568. if (match < base) return (size_t)-ZSTD_ERROR_corruption;
  1569. if (sequence.offset > (size_t)base) return (size_t)-ZSTD_ERROR_corruption;
  1570. /* save beginning of literal sequence, in case of write overlap */
  1571. if (overlapRisk)
  1572. {
  1573. if ((endMatch + qutt) > oend) qutt = oend-endMatch;
  1574. memcpy(saved, endMatch, qutt);
  1575. }
  1576. if (sequence.offset < 8)
  1577. {
  1578. const int dec64 = dec64table[sequence.offset];
  1579. op[0] = match[0];
  1580. op[1] = match[1];
  1581. op[2] = match[2];
  1582. op[3] = match[3];
  1583. match += dec32table[sequence.offset];
  1584. ZSTD_copy4(op+4, match);
  1585. match -= dec64;
  1586. } else { ZSTD_copy8(op, match); }
  1587. op += 8; match += 8;
  1588. if (endMatch > oend-12)
  1589. {
  1590. if (op < oend-8)
  1591. {
  1592. ZSTD_wildcopy(op, match, (oend-8) - op);
  1593. match += (oend-8) - op;
  1594. op = oend-8;
  1595. }
  1596. while (op<endMatch) *op++ = *match++;
  1597. }
  1598. else
  1599. ZSTD_wildcopy(op, match, sequence.matchLength-8); /* works even if matchLength < 8 */
  1600. /* restore, in case of overlap */
  1601. if (overlapRisk) memcpy(endMatch, saved, qutt);
  1602. }
  1603. return endMatch-ostart;
  1604. }
  1605. typedef struct ZSTDv01_Dctx_s
  1606. {
  1607. U32 LLTable[FSE_DTABLE_SIZE_U32(LLFSELog)];
  1608. U32 OffTable[FSE_DTABLE_SIZE_U32(OffFSELog)];
  1609. U32 MLTable[FSE_DTABLE_SIZE_U32(MLFSELog)];
  1610. void* previousDstEnd;
  1611. void* base;
  1612. size_t expected;
  1613. blockType_t bType;
  1614. U32 phase;
  1615. } dctx_t;
  1616. static size_t ZSTD_decompressSequences(
  1617. void* ctx,
  1618. void* dst, size_t maxDstSize,
  1619. const void* seqStart, size_t seqSize,
  1620. const BYTE* litStart, size_t litSize)
  1621. {
  1622. dctx_t* dctx = (dctx_t*)ctx;
  1623. const BYTE* ip = (const BYTE*)seqStart;
  1624. const BYTE* const iend = ip + seqSize;
  1625. BYTE* const ostart = (BYTE* const)dst;
  1626. BYTE* op = ostart;
  1627. BYTE* const oend = ostart + maxDstSize;
  1628. size_t errorCode, dumpsLength;
  1629. const BYTE* litPtr = litStart;
  1630. const BYTE* const litEnd = litStart + litSize;
  1631. int nbSeq;
  1632. const BYTE* dumps;
  1633. U32* DTableLL = dctx->LLTable;
  1634. U32* DTableML = dctx->MLTable;
  1635. U32* DTableOffb = dctx->OffTable;
  1636. BYTE* const base = (BYTE*) (dctx->base);
  1637. /* Build Decoding Tables */
  1638. errorCode = ZSTD_decodeSeqHeaders(&nbSeq, &dumps, &dumpsLength,
  1639. DTableLL, DTableML, DTableOffb,
  1640. ip, iend-ip);
  1641. if (ZSTD_isError(errorCode)) return errorCode;
  1642. ip += errorCode;
  1643. /* Regen sequences */
  1644. {
  1645. seq_t sequence;
  1646. seqState_t seqState;
  1647. memset(&sequence, 0, sizeof(sequence));
  1648. seqState.dumps = dumps;
  1649. seqState.dumpsEnd = dumps + dumpsLength;
  1650. seqState.prevOffset = 1;
  1651. errorCode = FSE_initDStream(&(seqState.DStream), ip, iend-ip);
  1652. if (FSE_isError(errorCode)) return (size_t)-ZSTD_ERROR_corruption;
  1653. FSE_initDState(&(seqState.stateLL), &(seqState.DStream), DTableLL);
  1654. FSE_initDState(&(seqState.stateOffb), &(seqState.DStream), DTableOffb);
  1655. FSE_initDState(&(seqState.stateML), &(seqState.DStream), DTableML);
  1656. for ( ; (FSE_reloadDStream(&(seqState.DStream)) <= FSE_DStream_completed) && (nbSeq>0) ; )
  1657. {
  1658. size_t oneSeqSize;
  1659. nbSeq--;
  1660. ZSTD_decodeSequence(&sequence, &seqState);
  1661. oneSeqSize = ZSTD_execSequence(op, sequence, &litPtr, litEnd, base, oend);
  1662. if (ZSTD_isError(oneSeqSize)) return oneSeqSize;
  1663. op += oneSeqSize;
  1664. }
  1665. /* check if reached exact end */
  1666. if ( !FSE_endOfDStream(&(seqState.DStream)) ) return (size_t)-ZSTD_ERROR_corruption; /* requested too much : data is corrupted */
  1667. if (nbSeq<0) return (size_t)-ZSTD_ERROR_corruption; /* requested too many sequences : data is corrupted */
  1668. /* last literal segment */
  1669. {
  1670. size_t lastLLSize = litEnd - litPtr;
  1671. if (op+lastLLSize > oend) return (size_t)-ZSTD_ERROR_maxDstSize_tooSmall;
  1672. if (op != litPtr) memmove(op, litPtr, lastLLSize);
  1673. op += lastLLSize;
  1674. }
  1675. }
  1676. return op-ostart;
  1677. }
  1678. static size_t ZSTD_decompressBlock(
  1679. void* ctx,
  1680. void* dst, size_t maxDstSize,
  1681. const void* src, size_t srcSize)
  1682. {
  1683. /* blockType == blockCompressed, srcSize is trusted */
  1684. const BYTE* ip = (const BYTE*)src;
  1685. const BYTE* litPtr = NULL;
  1686. size_t litSize = 0;
  1687. size_t errorCode;
  1688. /* Decode literals sub-block */
  1689. errorCode = ZSTD_decodeLiteralsBlock(ctx, dst, maxDstSize, &litPtr, &litSize, src, srcSize);
  1690. if (ZSTD_isError(errorCode)) return errorCode;
  1691. ip += errorCode;
  1692. srcSize -= errorCode;
  1693. return ZSTD_decompressSequences(ctx, dst, maxDstSize, ip, srcSize, litPtr, litSize);
  1694. }
  1695. size_t ZSTDv01_decompressDCtx(void* ctx, void* dst, size_t maxDstSize, const void* src, size_t srcSize)
  1696. {
  1697. const BYTE* ip = (const BYTE*)src;
  1698. const BYTE* iend = ip + srcSize;
  1699. BYTE* const ostart = (BYTE* const)dst;
  1700. BYTE* op = ostart;
  1701. BYTE* const oend = ostart + maxDstSize;
  1702. size_t remainingSize = srcSize;
  1703. U32 magicNumber;
  1704. size_t errorCode=0;
  1705. blockProperties_t blockProperties;
  1706. /* Frame Header */
  1707. if (srcSize < ZSTD_frameHeaderSize+ZSTD_blockHeaderSize) return (size_t)-ZSTD_ERROR_SrcSize;
  1708. magicNumber = ZSTD_readBE32(src);
  1709. if (magicNumber != ZSTD_magicNumber) return (size_t)-ZSTD_ERROR_MagicNumber;
  1710. ip += ZSTD_frameHeaderSize; remainingSize -= ZSTD_frameHeaderSize;
  1711. /* Loop on each block */
  1712. while (1)
  1713. {
  1714. size_t blockSize = ZSTD_getcBlockSize(ip, iend-ip, &blockProperties);
  1715. if (ZSTD_isError(blockSize)) return blockSize;
  1716. ip += ZSTD_blockHeaderSize;
  1717. remainingSize -= ZSTD_blockHeaderSize;
  1718. if (blockSize > remainingSize) return (size_t)-ZSTD_ERROR_SrcSize;
  1719. switch(blockProperties.blockType)
  1720. {
  1721. case bt_compressed:
  1722. errorCode = ZSTD_decompressBlock(ctx, op, oend-op, ip, blockSize);
  1723. break;
  1724. case bt_raw :
  1725. errorCode = ZSTD_copyUncompressedBlock(op, oend-op, ip, blockSize);
  1726. break;
  1727. case bt_rle :
  1728. return (size_t)-ZSTD_ERROR_GENERIC; /* not yet supported */
  1729. break;
  1730. case bt_end :
  1731. /* end of frame */
  1732. if (remainingSize) return (size_t)-ZSTD_ERROR_SrcSize;
  1733. break;
  1734. default:
  1735. return (size_t)-ZSTD_ERROR_GENERIC;
  1736. }
  1737. if (blockSize == 0) break; /* bt_end */
  1738. if (ZSTD_isError(errorCode)) return errorCode;
  1739. op += errorCode;
  1740. ip += blockSize;
  1741. remainingSize -= blockSize;
  1742. }
  1743. return op-ostart;
  1744. }
  1745. size_t ZSTDv01_decompress(void* dst, size_t maxDstSize, const void* src, size_t srcSize)
  1746. {
  1747. dctx_t ctx;
  1748. ctx.base = dst;
  1749. return ZSTDv01_decompressDCtx(&ctx, dst, maxDstSize, src, srcSize);
  1750. }
  1751. /*******************************
  1752. * Streaming Decompression API
  1753. *******************************/
  1754. size_t ZSTDv01_resetDCtx(ZSTDv01_Dctx* dctx)
  1755. {
  1756. dctx->expected = ZSTD_frameHeaderSize;
  1757. dctx->phase = 0;
  1758. dctx->previousDstEnd = NULL;
  1759. dctx->base = NULL;
  1760. return 0;
  1761. }
  1762. ZSTDv01_Dctx* ZSTDv01_createDCtx(void)
  1763. {
  1764. ZSTDv01_Dctx* dctx = (ZSTDv01_Dctx*)malloc(sizeof(ZSTDv01_Dctx));
  1765. if (dctx==NULL) return NULL;
  1766. ZSTDv01_resetDCtx(dctx);
  1767. return dctx;
  1768. }
  1769. size_t ZSTDv01_freeDCtx(ZSTDv01_Dctx* dctx)
  1770. {
  1771. free(dctx);
  1772. return 0;
  1773. }
  1774. size_t ZSTDv01_nextSrcSizeToDecompress(ZSTDv01_Dctx* dctx)
  1775. {
  1776. return ((dctx_t*)dctx)->expected;
  1777. }
  1778. size_t ZSTDv01_decompressContinue(ZSTDv01_Dctx* dctx, void* dst, size_t maxDstSize, const void* src, size_t srcSize)
  1779. {
  1780. dctx_t* ctx = (dctx_t*)dctx;
  1781. /* Sanity check */
  1782. if (srcSize != ctx->expected) return (size_t)-ZSTD_ERROR_SrcSize;
  1783. if (dst != ctx->previousDstEnd) /* not contiguous */
  1784. ctx->base = dst;
  1785. /* Decompress : frame header */
  1786. if (ctx->phase == 0)
  1787. {
  1788. /* Check frame magic header */
  1789. U32 magicNumber = ZSTD_readBE32(src);
  1790. if (magicNumber != ZSTD_magicNumber) return (size_t)-ZSTD_ERROR_MagicNumber;
  1791. ctx->phase = 1;
  1792. ctx->expected = ZSTD_blockHeaderSize;
  1793. return 0;
  1794. }
  1795. /* Decompress : block header */
  1796. if (ctx->phase == 1)
  1797. {
  1798. blockProperties_t bp;
  1799. size_t blockSize = ZSTD_getcBlockSize(src, ZSTD_blockHeaderSize, &bp);
  1800. if (ZSTD_isError(blockSize)) return blockSize;
  1801. if (bp.blockType == bt_end)
  1802. {
  1803. ctx->expected = 0;
  1804. ctx->phase = 0;
  1805. }
  1806. else
  1807. {
  1808. ctx->expected = blockSize;
  1809. ctx->bType = bp.blockType;
  1810. ctx->phase = 2;
  1811. }
  1812. return 0;
  1813. }
  1814. /* Decompress : block content */
  1815. {
  1816. size_t rSize;
  1817. switch(ctx->bType)
  1818. {
  1819. case bt_compressed:
  1820. rSize = ZSTD_decompressBlock(ctx, dst, maxDstSize, src, srcSize);
  1821. break;
  1822. case bt_raw :
  1823. rSize = ZSTD_copyUncompressedBlock(dst, maxDstSize, src, srcSize);
  1824. break;
  1825. case bt_rle :
  1826. return (size_t)-ZSTD_ERROR_GENERIC; /* not yet handled */
  1827. break;
  1828. case bt_end : /* should never happen (filtered at phase 1) */
  1829. rSize = 0;
  1830. break;
  1831. default:
  1832. return (size_t)-ZSTD_ERROR_GENERIC;
  1833. }
  1834. ctx->phase = 1;
  1835. ctx->expected = ZSTD_blockHeaderSize;
  1836. ctx->previousDstEnd = (void*)( ((char*)dst) + rSize);
  1837. return rSize;
  1838. }
  1839. }