zstd_v04.c 133 KB

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