zstd_v05.c 163 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325
  1. /* ******************************************************************
  2. zstd_v05.c
  3. Decompression module for ZSTD v0.5 legacy format
  4. Copyright (C) 2016, Yann Collet.
  5. BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
  6. Redistribution and use in source and binary forms, with or without
  7. modification, are permitted provided that the following conditions are
  8. met:
  9. * Redistributions of source code must retain the above copyright
  10. notice, this list of conditions and the following disclaimer.
  11. * Redistributions in binary form must reproduce the above
  12. copyright notice, this list of conditions and the following disclaimer
  13. in the documentation and/or other materials provided with the
  14. distribution.
  15. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  16. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  17. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  18. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  19. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  20. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  21. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  22. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  23. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  25. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. You can contact the author at :
  27. - Homepage : http://www.zstd.net/
  28. ****************************************************************** */
  29. /*- Dependencies -*/
  30. #include "zstd_v05.h"
  31. /* ******************************************************************
  32. mem.h
  33. low-level memory access routines
  34. Copyright (C) 2013-2015, Yann Collet.
  35. BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
  36. Redistribution and use in source and binary forms, with or without
  37. modification, are permitted provided that the following conditions are
  38. met:
  39. * Redistributions of source code must retain the above copyright
  40. notice, this list of conditions and the following disclaimer.
  41. * Redistributions in binary form must reproduce the above
  42. copyright notice, this list of conditions and the following disclaimer
  43. in the documentation and/or other materials provided with the
  44. distribution.
  45. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  46. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  47. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  48. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  49. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  50. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  51. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  52. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  53. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  54. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  55. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  56. You can contact the author at :
  57. - FSEv05 source repository : https://github.com/Cyan4973/FiniteStateEntropy
  58. - Public forum : https://groups.google.com/forum/#!forum/lz4c
  59. ****************************************************************** */
  60. #ifndef MEM_H_MODULE
  61. #define MEM_H_MODULE
  62. #if defined (__cplusplus)
  63. extern "C" {
  64. #endif
  65. /*-****************************************
  66. * Dependencies
  67. ******************************************/
  68. #include <stddef.h> /* size_t, ptrdiff_t */
  69. #include <string.h> /* memcpy */
  70. /*-****************************************
  71. * Compiler specifics
  72. ******************************************/
  73. #if defined(__GNUC__)
  74. # define MEM_STATIC static __attribute__((unused))
  75. #elif defined (__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */)
  76. # define MEM_STATIC static inline
  77. #elif defined(_MSC_VER)
  78. # define MEM_STATIC static __inline
  79. #else
  80. # define MEM_STATIC static /* this version may generate warnings for unused static functions; disable the relevant warning */
  81. #endif
  82. /*-**************************************************************
  83. * Basic Types
  84. *****************************************************************/
  85. #if defined (__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */)
  86. # include <stdint.h>
  87. typedef uint8_t BYTE;
  88. typedef uint16_t U16;
  89. typedef int16_t S16;
  90. typedef uint32_t U32;
  91. typedef int32_t S32;
  92. typedef uint64_t U64;
  93. typedef int64_t S64;
  94. #else
  95. typedef unsigned char BYTE;
  96. typedef unsigned short U16;
  97. typedef signed short S16;
  98. typedef unsigned int U32;
  99. typedef signed int S32;
  100. typedef unsigned long long U64;
  101. typedef signed long long S64;
  102. #endif
  103. /*-**************************************************************
  104. * Memory I/O
  105. *****************************************************************/
  106. /* MEM_FORCE_MEMORY_ACCESS :
  107. * By default, access to unaligned memory is controlled by `memcpy()`, which is safe and portable.
  108. * Unfortunately, on some target/compiler combinations, the generated assembly is sub-optimal.
  109. * The below switch allow to select different access method for improved performance.
  110. * Method 0 (default) : use `memcpy()`. Safe and portable.
  111. * Method 1 : `__packed` statement. It depends on compiler extension (ie, not portable).
  112. * This method is safe if your compiler supports it, and *generally* as fast or faster than `memcpy`.
  113. * Method 2 : direct access. This method is portable but violate C standard.
  114. * It can generate buggy code on targets depending on alignment.
  115. * In some circumstances, it's the only known way to get the most performance (ie GCC + ARMv6)
  116. * See http://fastcompression.blogspot.fr/2015/08/accessing-unaligned-memory.html for details.
  117. * Prefer these methods in priority order (0 > 1 > 2)
  118. */
  119. #ifndef MEM_FORCE_MEMORY_ACCESS /* can be defined externally, on command line for example */
  120. # 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__) )
  121. # define MEM_FORCE_MEMORY_ACCESS 2
  122. # elif defined(__INTEL_COMPILER) || \
  123. (defined(__GNUC__) && ( defined(__ARM_ARCH_7__) || defined(__ARM_ARCH_7A__) || defined(__ARM_ARCH_7R__) || defined(__ARM_ARCH_7M__) || defined(__ARM_ARCH_7S__) ))
  124. # define MEM_FORCE_MEMORY_ACCESS 1
  125. # endif
  126. #endif
  127. MEM_STATIC unsigned MEM_32bits(void) { return sizeof(void*)==4; }
  128. MEM_STATIC unsigned MEM_64bits(void) { return sizeof(void*)==8; }
  129. MEM_STATIC unsigned MEM_isLittleEndian(void)
  130. {
  131. const union { U32 u; BYTE c[4]; } one = { 1 }; /* don't use static : performance detrimental */
  132. return one.c[0];
  133. }
  134. #if defined(MEM_FORCE_MEMORY_ACCESS) && (MEM_FORCE_MEMORY_ACCESS==2)
  135. /* violates C standard, by lying on structure alignment.
  136. Only use if no other choice to achieve best performance on target platform */
  137. MEM_STATIC U16 MEM_read16(const void* memPtr) { return *(const U16*) memPtr; }
  138. MEM_STATIC U32 MEM_read32(const void* memPtr) { return *(const U32*) memPtr; }
  139. MEM_STATIC U64 MEM_read64(const void* memPtr) { return *(const U64*) memPtr; }
  140. MEM_STATIC void MEM_write16(void* memPtr, U16 value) { *(U16*)memPtr = value; }
  141. MEM_STATIC void MEM_write32(void* memPtr, U32 value) { *(U32*)memPtr = value; }
  142. MEM_STATIC void MEM_write64(void* memPtr, U64 value) { *(U64*)memPtr = value; }
  143. #elif defined(MEM_FORCE_MEMORY_ACCESS) && (MEM_FORCE_MEMORY_ACCESS==1)
  144. /* __pack instructions are safer, but compiler specific, hence potentially problematic for some compilers */
  145. /* currently only defined for gcc and icc */
  146. typedef union { U16 u16; U32 u32; U64 u64; size_t st; } __attribute__((packed)) unalign;
  147. MEM_STATIC U16 MEM_read16(const void* ptr) { return ((const unalign*)ptr)->u16; }
  148. MEM_STATIC U32 MEM_read32(const void* ptr) { return ((const unalign*)ptr)->u32; }
  149. MEM_STATIC U64 MEM_read64(const void* ptr) { return ((const unalign*)ptr)->u64; }
  150. MEM_STATIC void MEM_write16(void* memPtr, U16 value) { ((unalign*)memPtr)->u16 = value; }
  151. MEM_STATIC void MEM_write32(void* memPtr, U32 value) { ((unalign*)memPtr)->u32 = value; }
  152. MEM_STATIC void MEM_write64(void* memPtr, U64 value) { ((unalign*)memPtr)->u64 = value; }
  153. #else
  154. /* default method, safe and standard.
  155. can sometimes prove slower */
  156. MEM_STATIC U16 MEM_read16(const void* memPtr)
  157. {
  158. U16 val; memcpy(&val, memPtr, sizeof(val)); return val;
  159. }
  160. MEM_STATIC U32 MEM_read32(const void* memPtr)
  161. {
  162. U32 val; memcpy(&val, memPtr, sizeof(val)); return val;
  163. }
  164. MEM_STATIC U64 MEM_read64(const void* memPtr)
  165. {
  166. U64 val; memcpy(&val, memPtr, sizeof(val)); return val;
  167. }
  168. MEM_STATIC void MEM_write16(void* memPtr, U16 value)
  169. {
  170. memcpy(memPtr, &value, sizeof(value));
  171. }
  172. MEM_STATIC void MEM_write32(void* memPtr, U32 value)
  173. {
  174. memcpy(memPtr, &value, sizeof(value));
  175. }
  176. MEM_STATIC void MEM_write64(void* memPtr, U64 value)
  177. {
  178. memcpy(memPtr, &value, sizeof(value));
  179. }
  180. #endif /* MEM_FORCE_MEMORY_ACCESS */
  181. MEM_STATIC U16 MEM_readLE16(const void* memPtr)
  182. {
  183. if (MEM_isLittleEndian())
  184. return MEM_read16(memPtr);
  185. else {
  186. const BYTE* p = (const BYTE*)memPtr;
  187. return (U16)(p[0] + (p[1]<<8));
  188. }
  189. }
  190. MEM_STATIC void MEM_writeLE16(void* memPtr, U16 val)
  191. {
  192. if (MEM_isLittleEndian()) {
  193. MEM_write16(memPtr, val);
  194. } else {
  195. BYTE* p = (BYTE*)memPtr;
  196. p[0] = (BYTE)val;
  197. p[1] = (BYTE)(val>>8);
  198. }
  199. }
  200. MEM_STATIC U32 MEM_readLE32(const void* memPtr)
  201. {
  202. if (MEM_isLittleEndian())
  203. return MEM_read32(memPtr);
  204. else {
  205. const BYTE* p = (const BYTE*)memPtr;
  206. return (U32)((U32)p[0] + ((U32)p[1]<<8) + ((U32)p[2]<<16) + ((U32)p[3]<<24));
  207. }
  208. }
  209. MEM_STATIC void MEM_writeLE32(void* memPtr, U32 val32)
  210. {
  211. if (MEM_isLittleEndian()) {
  212. MEM_write32(memPtr, val32);
  213. } else {
  214. BYTE* p = (BYTE*)memPtr;
  215. p[0] = (BYTE)val32;
  216. p[1] = (BYTE)(val32>>8);
  217. p[2] = (BYTE)(val32>>16);
  218. p[3] = (BYTE)(val32>>24);
  219. }
  220. }
  221. MEM_STATIC U64 MEM_readLE64(const void* memPtr)
  222. {
  223. if (MEM_isLittleEndian())
  224. return MEM_read64(memPtr);
  225. else {
  226. const BYTE* p = (const BYTE*)memPtr;
  227. return (U64)((U64)p[0] + ((U64)p[1]<<8) + ((U64)p[2]<<16) + ((U64)p[3]<<24)
  228. + ((U64)p[4]<<32) + ((U64)p[5]<<40) + ((U64)p[6]<<48) + ((U64)p[7]<<56));
  229. }
  230. }
  231. MEM_STATIC void MEM_writeLE64(void* memPtr, U64 val64)
  232. {
  233. if (MEM_isLittleEndian()) {
  234. MEM_write64(memPtr, val64);
  235. } else {
  236. BYTE* p = (BYTE*)memPtr;
  237. p[0] = (BYTE)val64;
  238. p[1] = (BYTE)(val64>>8);
  239. p[2] = (BYTE)(val64>>16);
  240. p[3] = (BYTE)(val64>>24);
  241. p[4] = (BYTE)(val64>>32);
  242. p[5] = (BYTE)(val64>>40);
  243. p[6] = (BYTE)(val64>>48);
  244. p[7] = (BYTE)(val64>>56);
  245. }
  246. }
  247. MEM_STATIC size_t MEM_readLEST(const void* memPtr)
  248. {
  249. if (MEM_32bits())
  250. return (size_t)MEM_readLE32(memPtr);
  251. else
  252. return (size_t)MEM_readLE64(memPtr);
  253. }
  254. MEM_STATIC void MEM_writeLEST(void* memPtr, size_t val)
  255. {
  256. if (MEM_32bits())
  257. MEM_writeLE32(memPtr, (U32)val);
  258. else
  259. MEM_writeLE64(memPtr, (U64)val);
  260. }
  261. #if defined (__cplusplus)
  262. }
  263. #endif
  264. #endif /* MEM_H_MODULE */
  265. /* ******************************************************************
  266. Error codes list
  267. Copyright (C) 2016, Yann Collet
  268. BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
  269. Redistribution and use in source and binary forms, with or without
  270. modification, are permitted provided that the following conditions are
  271. met:
  272. * Redistributions of source code must retain the above copyright
  273. notice, this list of conditions and the following disclaimer.
  274. * Redistributions in binary form must reproduce the above
  275. copyright notice, this list of conditions and the following disclaimer
  276. in the documentation and/or other materials provided with the
  277. distribution.
  278. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  279. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  280. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  281. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  282. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  283. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  284. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  285. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  286. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  287. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  288. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  289. You can contact the author at :
  290. - Source repository : https://github.com/Cyan4973/zstd
  291. ****************************************************************** */
  292. #ifndef ERROR_PUBLIC_H_MODULE
  293. #define ERROR_PUBLIC_H_MODULE
  294. #if defined (__cplusplus)
  295. extern "C" {
  296. #endif
  297. /* ****************************************
  298. * error codes list
  299. ******************************************/
  300. typedef enum {
  301. ZSTDv05_error_no_error,
  302. ZSTDv05_error_GENERIC,
  303. ZSTDv05_error_prefix_unknown,
  304. ZSTDv05_error_frameParameter_unsupported,
  305. ZSTDv05_error_frameParameter_unsupportedBy32bits,
  306. ZSTDv05_error_init_missing,
  307. ZSTDv05_error_memory_allocation,
  308. ZSTDv05_error_stage_wrong,
  309. ZSTDv05_error_dstSize_tooSmall,
  310. ZSTDv05_error_srcSize_wrong,
  311. ZSTDv05_error_corruption_detected,
  312. ZSTDv05_error_tableLog_tooLarge,
  313. ZSTDv05_error_maxSymbolValue_tooLarge,
  314. ZSTDv05_error_maxSymbolValue_tooSmall,
  315. ZSTDv05_error_dictionary_corrupted,
  316. ZSTDv05_error_maxCode
  317. } ZSTDv05_ErrorCode;
  318. /* note : functions provide error codes in reverse negative order,
  319. so compare with (size_t)(0-enum) */
  320. #if defined (__cplusplus)
  321. }
  322. #endif
  323. #endif /* ERROR_PUBLIC_H_MODULE */
  324. /*
  325. zstd - standard compression library
  326. Header File for static linking only
  327. Copyright (C) 2014-2016, Yann Collet.
  328. BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
  329. Redistribution and use in source and binary forms, with or without
  330. modification, are permitted provided that the following conditions are
  331. met:
  332. * Redistributions of source code must retain the above copyright
  333. notice, this list of conditions and the following disclaimer.
  334. * Redistributions in binary form must reproduce the above
  335. copyright notice, this list of conditions and the following disclaimer
  336. in the documentation and/or other materials provided with the
  337. distribution.
  338. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  339. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  340. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  341. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  342. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  343. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  344. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  345. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  346. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  347. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  348. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  349. You can contact the author at :
  350. - zstd homepage : http://www.zstd.net
  351. */
  352. #ifndef ZSTD_STATIC_H
  353. #define ZSTD_STATIC_H
  354. /* The prototypes defined within this file are considered experimental.
  355. * They should not be used in the context DLL as they may change in the future.
  356. * Prefer static linking if you need them, to control breaking version changes issues.
  357. */
  358. #if defined (__cplusplus)
  359. extern "C" {
  360. #endif
  361. /*-*************************************
  362. * Types
  363. ***************************************/
  364. #define ZSTDv05_WINDOWLOG_ABSOLUTEMIN 11
  365. /*-*************************************
  366. * Advanced functions
  367. ***************************************/
  368. /*- Advanced Decompression functions -*/
  369. /*! ZSTDv05_decompress_usingPreparedDCtx() :
  370. * Same as ZSTDv05_decompress_usingDict, but using a reference context `preparedDCtx`, where dictionary has been loaded.
  371. * It avoids reloading the dictionary each time.
  372. * `preparedDCtx` must have been properly initialized using ZSTDv05_decompressBegin_usingDict().
  373. * Requires 2 contexts : 1 for reference, which will not be modified, and 1 to run the decompression operation */
  374. size_t ZSTDv05_decompress_usingPreparedDCtx(
  375. ZSTDv05_DCtx* dctx, const ZSTDv05_DCtx* preparedDCtx,
  376. void* dst, size_t dstCapacity,
  377. const void* src, size_t srcSize);
  378. /* **************************************
  379. * Streaming functions (direct mode)
  380. ****************************************/
  381. size_t ZSTDv05_decompressBegin(ZSTDv05_DCtx* dctx);
  382. size_t ZSTDv05_decompressBegin_usingDict(ZSTDv05_DCtx* dctx, const void* dict, size_t dictSize);
  383. void ZSTDv05_copyDCtx(ZSTDv05_DCtx* dctx, const ZSTDv05_DCtx* preparedDCtx);
  384. size_t ZSTDv05_getFrameParams(ZSTDv05_parameters* params, const void* src, size_t srcSize);
  385. size_t ZSTDv05_nextSrcSizeToDecompress(ZSTDv05_DCtx* dctx);
  386. size_t ZSTDv05_decompressContinue(ZSTDv05_DCtx* dctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize);
  387. /*
  388. Streaming decompression, direct mode (bufferless)
  389. A ZSTDv05_DCtx object is required to track streaming operations.
  390. Use ZSTDv05_createDCtx() / ZSTDv05_freeDCtx() to manage it.
  391. A ZSTDv05_DCtx object can be re-used multiple times.
  392. First typical operation is to retrieve frame parameters, using ZSTDv05_getFrameParams().
  393. This operation is independent, and just needs enough input data to properly decode the frame header.
  394. Objective is to retrieve *params.windowlog, to know minimum amount of memory required during decoding.
  395. Result : 0 when successful, it means the ZSTDv05_parameters structure has been filled.
  396. >0 : means there is not enough data into src. Provides the expected size to successfully decode header.
  397. errorCode, which can be tested using ZSTDv05_isError()
  398. Start decompression, with ZSTDv05_decompressBegin() or ZSTDv05_decompressBegin_usingDict()
  399. Alternatively, you can copy a prepared context, using ZSTDv05_copyDCtx()
  400. Then use ZSTDv05_nextSrcSizeToDecompress() and ZSTDv05_decompressContinue() alternatively.
  401. ZSTDv05_nextSrcSizeToDecompress() tells how much bytes to provide as 'srcSize' to ZSTDv05_decompressContinue().
  402. ZSTDv05_decompressContinue() requires this exact amount of bytes, or it will fail.
  403. ZSTDv05_decompressContinue() needs previous data blocks during decompression, up to (1 << windowlog).
  404. They should preferably be located contiguously, prior to current block. Alternatively, a round buffer is also possible.
  405. @result of ZSTDv05_decompressContinue() is the number of bytes regenerated within 'dst'.
  406. It can be zero, which is not an error; it just means ZSTDv05_decompressContinue() has decoded some header.
  407. A frame is fully decoded when ZSTDv05_nextSrcSizeToDecompress() returns zero.
  408. Context can then be reset to start a new decompression.
  409. */
  410. /* **************************************
  411. * Block functions
  412. ****************************************/
  413. /*! Block functions produce and decode raw zstd blocks, without frame metadata.
  414. User will have to take in charge required information to regenerate data, such as block sizes.
  415. A few rules to respect :
  416. - Uncompressed block size must be <= 128 KB
  417. - Compressing or decompressing requires a context structure
  418. + Use ZSTDv05_createCCtx() and ZSTDv05_createDCtx()
  419. - It is necessary to init context before starting
  420. + compression : ZSTDv05_compressBegin()
  421. + decompression : ZSTDv05_decompressBegin()
  422. + variants _usingDict() are also allowed
  423. + copyCCtx() and copyDCtx() work too
  424. - When a block is considered not compressible enough, ZSTDv05_compressBlock() result will be zero.
  425. In which case, nothing is produced into `dst`.
  426. + User must test for such outcome and deal directly with uncompressed data
  427. + ZSTDv05_decompressBlock() doesn't accept uncompressed data as input !!
  428. */
  429. size_t ZSTDv05_decompressBlock(ZSTDv05_DCtx* dctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize);
  430. #if defined (__cplusplus)
  431. }
  432. #endif
  433. #endif /* ZSTDv05_STATIC_H */
  434. /* ******************************************************************
  435. Error codes and messages
  436. Copyright (C) 2013-2016, Yann Collet
  437. BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
  438. Redistribution and use in source and binary forms, with or without
  439. modification, are permitted provided that the following conditions are
  440. met:
  441. * Redistributions of source code must retain the above copyright
  442. notice, this list of conditions and the following disclaimer.
  443. * Redistributions in binary form must reproduce the above
  444. copyright notice, this list of conditions and the following disclaimer
  445. in the documentation and/or other materials provided with the
  446. distribution.
  447. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  448. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  449. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  450. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  451. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  452. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  453. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  454. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  455. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  456. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  457. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  458. You can contact the author at :
  459. - Source repository : https://github.com/Cyan4973/zstd
  460. ****************************************************************** */
  461. /* Note : this module is expected to remain private, do not expose it */
  462. #ifndef ERROR_H_MODULE
  463. #define ERROR_H_MODULE
  464. #if defined (__cplusplus)
  465. extern "C" {
  466. #endif
  467. /* ****************************************
  468. * Compiler-specific
  469. ******************************************/
  470. #if defined(__GNUC__)
  471. # define ERR_STATIC static __attribute__((unused))
  472. #elif defined (__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */)
  473. # define ERR_STATIC static inline
  474. #elif defined(_MSC_VER)
  475. # define ERR_STATIC static __inline
  476. #else
  477. # define ERR_STATIC static /* this version may generate warnings for unused static functions; disable the relevant warning */
  478. #endif
  479. /*-****************************************
  480. * Customization
  481. ******************************************/
  482. typedef ZSTDv05_ErrorCode ERR_enum;
  483. #define PREFIX(name) ZSTDv05_error_##name
  484. /*-****************************************
  485. * Error codes handling
  486. ******************************************/
  487. #ifdef ERROR
  488. # undef ERROR /* reported already defined on VS 2015 (Rich Geldreich) */
  489. #endif
  490. #define ERROR(name) (size_t)-PREFIX(name)
  491. ERR_STATIC unsigned ERR_isError(size_t code) { return (code > ERROR(maxCode)); }
  492. ERR_STATIC ERR_enum ERR_getError(size_t code) { if (!ERR_isError(code)) return (ERR_enum)0; return (ERR_enum) (0-code); }
  493. /*-****************************************
  494. * Error Strings
  495. ******************************************/
  496. ERR_STATIC const char* ERR_getErrorName(size_t code)
  497. {
  498. static const char* notErrorCode = "Unspecified error code";
  499. switch( ERR_getError(code) )
  500. {
  501. case PREFIX(no_error): return "No error detected";
  502. case PREFIX(GENERIC): return "Error (generic)";
  503. case PREFIX(prefix_unknown): return "Unknown frame descriptor";
  504. case PREFIX(frameParameter_unsupported): return "Unsupported frame parameter";
  505. case PREFIX(frameParameter_unsupportedBy32bits): return "Frame parameter unsupported in 32-bits mode";
  506. case PREFIX(init_missing): return "Context should be init first";
  507. case PREFIX(memory_allocation): return "Allocation error : not enough memory";
  508. case PREFIX(stage_wrong): return "Operation not authorized at current processing stage";
  509. case PREFIX(dstSize_tooSmall): return "Destination buffer is too small";
  510. case PREFIX(srcSize_wrong): return "Src size incorrect";
  511. case PREFIX(corruption_detected): return "Corrupted block detected";
  512. case PREFIX(tableLog_tooLarge): return "tableLog requires too much memory";
  513. case PREFIX(maxSymbolValue_tooLarge): return "Unsupported max possible Symbol Value : too large";
  514. case PREFIX(maxSymbolValue_tooSmall): return "Specified maxSymbolValue is too small";
  515. case PREFIX(dictionary_corrupted): return "Dictionary is corrupted";
  516. case PREFIX(maxCode):
  517. default: return notErrorCode; /* should be impossible, due to ERR_getError() */
  518. }
  519. }
  520. #if defined (__cplusplus)
  521. }
  522. #endif
  523. #endif /* ERROR_H_MODULE */
  524. /*
  525. zstd_internal - common functions to include
  526. Header File for include
  527. Copyright (C) 2014-2016, Yann Collet.
  528. BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
  529. Redistribution and use in source and binary forms, with or without
  530. modification, are permitted provided that the following conditions are
  531. met:
  532. * Redistributions of source code must retain the above copyright
  533. notice, this list of conditions and the following disclaimer.
  534. * Redistributions in binary form must reproduce the above
  535. copyright notice, this list of conditions and the following disclaimer
  536. in the documentation and/or other materials provided with the
  537. distribution.
  538. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  539. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  540. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  541. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  542. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  543. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  544. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  545. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  546. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  547. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  548. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  549. You can contact the author at :
  550. - zstd source repository : https://github.com/Cyan4973/zstd
  551. */
  552. #ifndef ZSTD_CCOMMON_H_MODULE
  553. #define ZSTD_CCOMMON_H_MODULE
  554. /*-*************************************
  555. * Common macros
  556. ***************************************/
  557. #define MIN(a,b) ((a)<(b) ? (a) : (b))
  558. #define MAX(a,b) ((a)>(b) ? (a) : (b))
  559. /*-*************************************
  560. * Common constants
  561. ***************************************/
  562. #define ZSTDv05_DICT_MAGIC 0xEC30A435
  563. #define KB *(1 <<10)
  564. #define MB *(1 <<20)
  565. #define GB *(1U<<30)
  566. #define BLOCKSIZE (128 KB) /* define, for static allocation */
  567. static const size_t ZSTDv05_blockHeaderSize = 3;
  568. static const size_t ZSTDv05_frameHeaderSize_min = 5;
  569. #define ZSTDv05_frameHeaderSize_max 5 /* define, for static allocation */
  570. #define BITv057 128
  571. #define BITv056 64
  572. #define BITv055 32
  573. #define BITv054 16
  574. #define BITv051 2
  575. #define BITv050 1
  576. #define IS_HUFv05 0
  577. #define IS_PCH 1
  578. #define IS_RAW 2
  579. #define IS_RLE 3
  580. #define MINMATCH 4
  581. #define REPCODE_STARTVALUE 1
  582. #define Litbits 8
  583. #define MLbits 7
  584. #define LLbits 6
  585. #define Offbits 5
  586. #define MaxLit ((1<<Litbits) - 1)
  587. #define MaxML ((1<<MLbits) - 1)
  588. #define MaxLL ((1<<LLbits) - 1)
  589. #define MaxOff ((1<<Offbits)- 1)
  590. #define MLFSEv05Log 10
  591. #define LLFSEv05Log 10
  592. #define OffFSEv05Log 9
  593. #define MaxSeq MAX(MaxLL, MaxML)
  594. #define FSEv05_ENCODING_RAW 0
  595. #define FSEv05_ENCODING_RLE 1
  596. #define FSEv05_ENCODING_STATIC 2
  597. #define FSEv05_ENCODING_DYNAMIC 3
  598. #define HufLog 12
  599. #define MIN_SEQUENCES_SIZE 1 /* nbSeq==0 */
  600. #define MIN_CBLOCK_SIZE (1 /*litCSize*/ + 1 /* RLE or RAW */ + MIN_SEQUENCES_SIZE /* nbSeq==0 */) /* for a non-null block */
  601. #define WILDCOPY_OVERLENGTH 8
  602. typedef enum { bt_compressed, bt_raw, bt_rle, bt_end } blockType_t;
  603. /*-*******************************************
  604. * Shared functions to include for inlining
  605. *********************************************/
  606. static void ZSTDv05_copy8(void* dst, const void* src) { memcpy(dst, src, 8); }
  607. #define COPY8(d,s) { ZSTDv05_copy8(d,s); d+=8; s+=8; }
  608. /*! ZSTDv05_wildcopy() :
  609. * custom version of memcpy(), can copy up to 7 bytes too many (8 bytes if length==0) */
  610. MEM_STATIC void ZSTDv05_wildcopy(void* dst, const void* src, size_t length)
  611. {
  612. const BYTE* ip = (const BYTE*)src;
  613. BYTE* op = (BYTE*)dst;
  614. BYTE* const oend = op + length;
  615. do
  616. COPY8(op, ip)
  617. while (op < oend);
  618. }
  619. MEM_STATIC unsigned ZSTDv05_highbit(U32 val)
  620. {
  621. # if defined(_MSC_VER) /* Visual */
  622. unsigned long r=0;
  623. _BitScanReverse(&r, val);
  624. return (unsigned)r;
  625. # elif defined(__GNUC__) && (__GNUC__ >= 3) /* GCC Intrinsic */
  626. return 31 - __builtin_clz(val);
  627. # else /* Software version */
  628. static const int 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 };
  629. U32 v = val;
  630. int r;
  631. v |= v >> 1;
  632. v |= v >> 2;
  633. v |= v >> 4;
  634. v |= v >> 8;
  635. v |= v >> 16;
  636. r = DeBruijnClz[(U32)(v * 0x07C4ACDDU) >> 27];
  637. return r;
  638. # endif
  639. }
  640. /*-*******************************************
  641. * Private interfaces
  642. *********************************************/
  643. typedef struct {
  644. void* buffer;
  645. U32* offsetStart;
  646. U32* offset;
  647. BYTE* offCodeStart;
  648. BYTE* offCode;
  649. BYTE* litStart;
  650. BYTE* lit;
  651. BYTE* litLengthStart;
  652. BYTE* litLength;
  653. BYTE* matchLengthStart;
  654. BYTE* matchLength;
  655. BYTE* dumpsStart;
  656. BYTE* dumps;
  657. /* opt */
  658. U32* matchLengthFreq;
  659. U32* litLengthFreq;
  660. U32* litFreq;
  661. U32* offCodeFreq;
  662. U32 matchLengthSum;
  663. U32 litLengthSum;
  664. U32 litSum;
  665. U32 offCodeSum;
  666. } seqStore_t;
  667. #endif /* ZSTDv05_CCOMMON_H_MODULE */
  668. /* ******************************************************************
  669. FSEv05 : Finite State Entropy coder
  670. header file
  671. Copyright (C) 2013-2015, Yann Collet.
  672. BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
  673. Redistribution and use in source and binary forms, with or without
  674. modification, are permitted provided that the following conditions are
  675. met:
  676. * Redistributions of source code must retain the above copyright
  677. notice, this list of conditions and the following disclaimer.
  678. * Redistributions in binary form must reproduce the above
  679. copyright notice, this list of conditions and the following disclaimer
  680. in the documentation and/or other materials provided with the
  681. distribution.
  682. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  683. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  684. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  685. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  686. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  687. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  688. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  689. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  690. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  691. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  692. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  693. You can contact the author at :
  694. - Source repository : https://github.com/Cyan4973/FiniteStateEntropy
  695. - Public forum : https://groups.google.com/forum/#!forum/lz4c
  696. ****************************************************************** */
  697. #ifndef FSEv05_H
  698. #define FSEv05_H
  699. #if defined (__cplusplus)
  700. extern "C" {
  701. #endif
  702. /* *****************************************
  703. * Includes
  704. ******************************************/
  705. #include <stddef.h> /* size_t, ptrdiff_t */
  706. /*-****************************************
  707. * FSEv05 simple functions
  708. ******************************************/
  709. size_t FSEv05_decompress(void* dst, size_t maxDstSize,
  710. const void* cSrc, size_t cSrcSize);
  711. /*!
  712. FSEv05_decompress():
  713. Decompress FSEv05 data from buffer 'cSrc', of size 'cSrcSize',
  714. into already allocated destination buffer 'dst', of size 'maxDstSize'.
  715. return : size of regenerated data (<= maxDstSize)
  716. or an error code, which can be tested using FSEv05_isError()
  717. ** Important ** : FSEv05_decompress() doesn't decompress non-compressible nor RLE data !!!
  718. Why ? : making this distinction requires a header.
  719. Header management is intentionally delegated to the user layer, which can better manage special cases.
  720. */
  721. /* *****************************************
  722. * Tool functions
  723. ******************************************/
  724. /* Error Management */
  725. unsigned FSEv05_isError(size_t code); /* tells if a return value is an error code */
  726. const char* FSEv05_getErrorName(size_t code); /* provides error code string (useful for debugging) */
  727. /* *****************************************
  728. * FSEv05 detailed API
  729. ******************************************/
  730. /* *** DECOMPRESSION *** */
  731. /*!
  732. FSEv05_readNCount():
  733. Read compactly saved 'normalizedCounter' from 'rBuffer'.
  734. return : size read from 'rBuffer'
  735. or an errorCode, which can be tested using FSEv05_isError()
  736. maxSymbolValuePtr[0] and tableLogPtr[0] will also be updated with their respective values */
  737. size_t FSEv05_readNCount (short* normalizedCounter, unsigned* maxSymbolValuePtr, unsigned* tableLogPtr, const void* rBuffer, size_t rBuffSize);
  738. /*!
  739. Constructor and Destructor of type FSEv05_DTable
  740. Note that its size depends on 'tableLog' */
  741. typedef unsigned FSEv05_DTable; /* don't allocate that. It's just a way to be more restrictive than void* */
  742. FSEv05_DTable* FSEv05_createDTable(unsigned tableLog);
  743. void FSEv05_freeDTable(FSEv05_DTable* dt);
  744. /*!
  745. FSEv05_buildDTable():
  746. Builds 'dt', which must be already allocated, using FSEv05_createDTable()
  747. return : 0,
  748. or an errorCode, which can be tested using FSEv05_isError() */
  749. size_t FSEv05_buildDTable (FSEv05_DTable* dt, const short* normalizedCounter, unsigned maxSymbolValue, unsigned tableLog);
  750. /*!
  751. FSEv05_decompress_usingDTable():
  752. Decompress compressed source @cSrc of size @cSrcSize using @dt
  753. into @dst which must be already allocated.
  754. return : size of regenerated data (necessarily <= @dstCapacity)
  755. or an errorCode, which can be tested using FSEv05_isError() */
  756. size_t FSEv05_decompress_usingDTable(void* dst, size_t dstCapacity, const void* cSrc, size_t cSrcSize, const FSEv05_DTable* dt);
  757. #if defined (__cplusplus)
  758. }
  759. #endif
  760. #endif /* FSEv05_H */
  761. /* ******************************************************************
  762. bitstream
  763. Part of FSEv05 library
  764. header file (to include)
  765. Copyright (C) 2013-2016, Yann Collet.
  766. BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
  767. Redistribution and use in source and binary forms, with or without
  768. modification, are permitted provided that the following conditions are
  769. met:
  770. * Redistributions of source code must retain the above copyright
  771. notice, this list of conditions and the following disclaimer.
  772. * Redistributions in binary form must reproduce the above
  773. copyright notice, this list of conditions and the following disclaimer
  774. in the documentation and/or other materials provided with the
  775. distribution.
  776. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  777. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  778. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  779. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  780. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  781. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  782. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  783. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  784. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  785. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  786. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  787. You can contact the author at :
  788. - Source repository : https://github.com/Cyan4973/FiniteStateEntropy
  789. ****************************************************************** */
  790. #ifndef BITv05STREAM_H_MODULE
  791. #define BITv05STREAM_H_MODULE
  792. #if defined (__cplusplus)
  793. extern "C" {
  794. #endif
  795. /*
  796. * This API consists of small unitary functions, which highly benefit from being inlined.
  797. * Since link-time-optimization is not available for all compilers,
  798. * these functions are defined into a .h to be included.
  799. */
  800. /*-********************************************
  801. * bitStream decoding API (read backward)
  802. **********************************************/
  803. typedef struct
  804. {
  805. size_t bitContainer;
  806. unsigned bitsConsumed;
  807. const char* ptr;
  808. const char* start;
  809. } BITv05_DStream_t;
  810. typedef enum { BITv05_DStream_unfinished = 0,
  811. BITv05_DStream_endOfBuffer = 1,
  812. BITv05_DStream_completed = 2,
  813. BITv05_DStream_overflow = 3 } BITv05_DStream_status; /* result of BITv05_reloadDStream() */
  814. /* 1,2,4,8 would be better for bitmap combinations, but slows down performance a bit ... :( */
  815. MEM_STATIC size_t BITv05_initDStream(BITv05_DStream_t* bitD, const void* srcBuffer, size_t srcSize);
  816. MEM_STATIC size_t BITv05_readBits(BITv05_DStream_t* bitD, unsigned nbBits);
  817. MEM_STATIC BITv05_DStream_status BITv05_reloadDStream(BITv05_DStream_t* bitD);
  818. MEM_STATIC unsigned BITv05_endOfDStream(const BITv05_DStream_t* bitD);
  819. /*!
  820. * Start by invoking BITv05_initDStream().
  821. * A chunk of the bitStream is then stored into a local register.
  822. * Local register size is 64-bits on 64-bits systems, 32-bits on 32-bits systems (size_t).
  823. * You can then retrieve bitFields stored into the local register, **in reverse order**.
  824. * Local register is explicitly reloaded from memory by the BITv05_reloadDStream() method.
  825. * A reload guarantee a minimum of ((8*sizeof(size_t))-7) bits when its result is BITv05_DStream_unfinished.
  826. * Otherwise, it can be less than that, so proceed accordingly.
  827. * Checking if DStream has reached its end can be performed with BITv05_endOfDStream()
  828. */
  829. /*-****************************************
  830. * unsafe API
  831. ******************************************/
  832. MEM_STATIC size_t BITv05_readBitsFast(BITv05_DStream_t* bitD, unsigned nbBits);
  833. /* faster, but works only if nbBits >= 1 */
  834. /*-**************************************************************
  835. * Helper functions
  836. ****************************************************************/
  837. MEM_STATIC unsigned BITv05_highbit32 (register U32 val)
  838. {
  839. # if defined(_MSC_VER) /* Visual */
  840. unsigned long r=0;
  841. _BitScanReverse ( &r, val );
  842. return (unsigned) r;
  843. # elif defined(__GNUC__) && (__GNUC__ >= 3) /* Use GCC Intrinsic */
  844. return 31 - __builtin_clz (val);
  845. # else /* Software version */
  846. 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 };
  847. U32 v = val;
  848. unsigned r;
  849. v |= v >> 1;
  850. v |= v >> 2;
  851. v |= v >> 4;
  852. v |= v >> 8;
  853. v |= v >> 16;
  854. r = DeBruijnClz[ (U32) (v * 0x07C4ACDDU) >> 27];
  855. return r;
  856. # endif
  857. }
  858. /*-********************************************************
  859. * bitStream decoding
  860. **********************************************************/
  861. /*!BITv05_initDStream
  862. * Initialize a BITv05_DStream_t.
  863. * @bitD : a pointer to an already allocated BITv05_DStream_t structure
  864. * @srcBuffer must point at the beginning of a bitStream
  865. * @srcSize must be the exact size of the bitStream
  866. * @result : size of stream (== srcSize) or an errorCode if a problem is detected
  867. */
  868. MEM_STATIC size_t BITv05_initDStream(BITv05_DStream_t* bitD, const void* srcBuffer, size_t srcSize)
  869. {
  870. if (srcSize < 1) { memset(bitD, 0, sizeof(*bitD)); return ERROR(srcSize_wrong); }
  871. if (srcSize >= sizeof(size_t)) { /* normal case */
  872. U32 contain32;
  873. bitD->start = (const char*)srcBuffer;
  874. bitD->ptr = (const char*)srcBuffer + srcSize - sizeof(size_t);
  875. bitD->bitContainer = MEM_readLEST(bitD->ptr);
  876. contain32 = ((const BYTE*)srcBuffer)[srcSize-1];
  877. if (contain32 == 0) return ERROR(GENERIC); /* endMark not present */
  878. bitD->bitsConsumed = 8 - BITv05_highbit32(contain32);
  879. } else {
  880. U32 contain32;
  881. bitD->start = (const char*)srcBuffer;
  882. bitD->ptr = bitD->start;
  883. bitD->bitContainer = *(const BYTE*)(bitD->start);
  884. switch(srcSize)
  885. {
  886. case 7: bitD->bitContainer += (size_t)(((const BYTE*)(bitD->start))[6]) << (sizeof(size_t)*8 - 16);
  887. case 6: bitD->bitContainer += (size_t)(((const BYTE*)(bitD->start))[5]) << (sizeof(size_t)*8 - 24);
  888. case 5: bitD->bitContainer += (size_t)(((const BYTE*)(bitD->start))[4]) << (sizeof(size_t)*8 - 32);
  889. case 4: bitD->bitContainer += (size_t)(((const BYTE*)(bitD->start))[3]) << 24;
  890. case 3: bitD->bitContainer += (size_t)(((const BYTE*)(bitD->start))[2]) << 16;
  891. case 2: bitD->bitContainer += (size_t)(((const BYTE*)(bitD->start))[1]) << 8;
  892. default:;
  893. }
  894. contain32 = ((const BYTE*)srcBuffer)[srcSize-1];
  895. if (contain32 == 0) return ERROR(GENERIC); /* endMark not present */
  896. bitD->bitsConsumed = 8 - BITv05_highbit32(contain32);
  897. bitD->bitsConsumed += (U32)(sizeof(size_t) - srcSize)*8;
  898. }
  899. return srcSize;
  900. }
  901. /*!BITv05_lookBits
  902. * Provides next n bits from local register
  903. * local register is not modified (bits are still present for next read/look)
  904. * On 32-bits, maxNbBits==25
  905. * On 64-bits, maxNbBits==57
  906. * @return : value extracted
  907. */
  908. MEM_STATIC size_t BITv05_lookBits(BITv05_DStream_t* bitD, U32 nbBits)
  909. {
  910. const U32 bitMask = sizeof(bitD->bitContainer)*8 - 1;
  911. return ((bitD->bitContainer << (bitD->bitsConsumed & bitMask)) >> 1) >> ((bitMask-nbBits) & bitMask);
  912. }
  913. /*! BITv05_lookBitsFast :
  914. * unsafe version; only works only if nbBits >= 1 */
  915. MEM_STATIC size_t BITv05_lookBitsFast(BITv05_DStream_t* bitD, U32 nbBits)
  916. {
  917. const U32 bitMask = sizeof(bitD->bitContainer)*8 - 1;
  918. return (bitD->bitContainer << (bitD->bitsConsumed & bitMask)) >> (((bitMask+1)-nbBits) & bitMask);
  919. }
  920. MEM_STATIC void BITv05_skipBits(BITv05_DStream_t* bitD, U32 nbBits)
  921. {
  922. bitD->bitsConsumed += nbBits;
  923. }
  924. /*!BITv05_readBits
  925. * Read next n bits from local register.
  926. * pay attention to not read more than nbBits contained into local register.
  927. * @return : extracted value.
  928. */
  929. MEM_STATIC size_t BITv05_readBits(BITv05_DStream_t* bitD, U32 nbBits)
  930. {
  931. size_t value = BITv05_lookBits(bitD, nbBits);
  932. BITv05_skipBits(bitD, nbBits);
  933. return value;
  934. }
  935. /*!BITv05_readBitsFast :
  936. * unsafe version; only works only if nbBits >= 1 */
  937. MEM_STATIC size_t BITv05_readBitsFast(BITv05_DStream_t* bitD, U32 nbBits)
  938. {
  939. size_t value = BITv05_lookBitsFast(bitD, nbBits);
  940. BITv05_skipBits(bitD, nbBits);
  941. return value;
  942. }
  943. MEM_STATIC BITv05_DStream_status BITv05_reloadDStream(BITv05_DStream_t* bitD)
  944. {
  945. if (bitD->bitsConsumed > (sizeof(bitD->bitContainer)*8)) /* should never happen */
  946. return BITv05_DStream_overflow;
  947. if (bitD->ptr >= bitD->start + sizeof(bitD->bitContainer)) {
  948. bitD->ptr -= bitD->bitsConsumed >> 3;
  949. bitD->bitsConsumed &= 7;
  950. bitD->bitContainer = MEM_readLEST(bitD->ptr);
  951. return BITv05_DStream_unfinished;
  952. }
  953. if (bitD->ptr == bitD->start) {
  954. if (bitD->bitsConsumed < sizeof(bitD->bitContainer)*8) return BITv05_DStream_endOfBuffer;
  955. return BITv05_DStream_completed;
  956. }
  957. {
  958. U32 nbBytes = bitD->bitsConsumed >> 3;
  959. BITv05_DStream_status result = BITv05_DStream_unfinished;
  960. if (bitD->ptr - nbBytes < bitD->start) {
  961. nbBytes = (U32)(bitD->ptr - bitD->start); /* ptr > start */
  962. result = BITv05_DStream_endOfBuffer;
  963. }
  964. bitD->ptr -= nbBytes;
  965. bitD->bitsConsumed -= nbBytes*8;
  966. bitD->bitContainer = MEM_readLEST(bitD->ptr); /* reminder : srcSize > sizeof(bitD) */
  967. return result;
  968. }
  969. }
  970. /*! BITv05_endOfDStream
  971. * @return Tells if DStream has reached its exact end
  972. */
  973. MEM_STATIC unsigned BITv05_endOfDStream(const BITv05_DStream_t* DStream)
  974. {
  975. return ((DStream->ptr == DStream->start) && (DStream->bitsConsumed == sizeof(DStream->bitContainer)*8));
  976. }
  977. #if defined (__cplusplus)
  978. }
  979. #endif
  980. #endif /* BITv05STREAM_H_MODULE */
  981. /* ******************************************************************
  982. FSEv05 : Finite State Entropy coder
  983. header file for static linking (only)
  984. Copyright (C) 2013-2015, Yann Collet
  985. BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
  986. Redistribution and use in source and binary forms, with or without
  987. modification, are permitted provided that the following conditions are
  988. met:
  989. * Redistributions of source code must retain the above copyright
  990. notice, this list of conditions and the following disclaimer.
  991. * Redistributions in binary form must reproduce the above
  992. copyright notice, this list of conditions and the following disclaimer
  993. in the documentation and/or other materials provided with the
  994. distribution.
  995. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  996. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  997. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  998. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  999. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  1000. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  1001. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  1002. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  1003. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  1004. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  1005. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  1006. You can contact the author at :
  1007. - Source repository : https://github.com/Cyan4973/FiniteStateEntropy
  1008. - Public forum : https://groups.google.com/forum/#!forum/lz4c
  1009. ****************************************************************** */
  1010. #ifndef FSEv05_STATIC_H
  1011. #define FSEv05_STATIC_H
  1012. #if defined (__cplusplus)
  1013. extern "C" {
  1014. #endif
  1015. /* *****************************************
  1016. * Static allocation
  1017. *******************************************/
  1018. /* It is possible to statically allocate FSEv05 CTable/DTable as a table of unsigned using below macros */
  1019. #define FSEv05_DTABLE_SIZE_U32(maxTableLog) (1 + (1<<maxTableLog))
  1020. /* *****************************************
  1021. * FSEv05 advanced API
  1022. *******************************************/
  1023. size_t FSEv05_buildDTable_raw (FSEv05_DTable* dt, unsigned nbBits);
  1024. /* build a fake FSEv05_DTable, designed to read an uncompressed bitstream where each symbol uses nbBits */
  1025. size_t FSEv05_buildDTable_rle (FSEv05_DTable* dt, unsigned char symbolValue);
  1026. /* build a fake FSEv05_DTable, designed to always generate the same symbolValue */
  1027. /* *****************************************
  1028. * FSEv05 symbol decompression API
  1029. *******************************************/
  1030. typedef struct
  1031. {
  1032. size_t state;
  1033. const void* table; /* precise table may vary, depending on U16 */
  1034. } FSEv05_DState_t;
  1035. static void FSEv05_initDState(FSEv05_DState_t* DStatePtr, BITv05_DStream_t* bitD, const FSEv05_DTable* dt);
  1036. static unsigned char FSEv05_decodeSymbol(FSEv05_DState_t* DStatePtr, BITv05_DStream_t* bitD);
  1037. static unsigned FSEv05_endOfDState(const FSEv05_DState_t* DStatePtr);
  1038. /*!
  1039. Let's now decompose FSEv05_decompress_usingDTable() into its unitary components.
  1040. You will decode FSEv05-encoded symbols from the bitStream,
  1041. and also any other bitFields you put in, **in reverse order**.
  1042. You will need a few variables to track your bitStream. They are :
  1043. BITv05_DStream_t DStream; // Stream context
  1044. FSEv05_DState_t DState; // State context. Multiple ones are possible
  1045. FSEv05_DTable* DTablePtr; // Decoding table, provided by FSEv05_buildDTable()
  1046. The first thing to do is to init the bitStream.
  1047. errorCode = BITv05_initDStream(&DStream, srcBuffer, srcSize);
  1048. You should then retrieve your initial state(s)
  1049. (in reverse flushing order if you have several ones) :
  1050. errorCode = FSEv05_initDState(&DState, &DStream, DTablePtr);
  1051. You can then decode your data, symbol after symbol.
  1052. For information the maximum number of bits read by FSEv05_decodeSymbol() is 'tableLog'.
  1053. Keep in mind that symbols are decoded in reverse order, like a LIFO stack (last in, first out).
  1054. unsigned char symbol = FSEv05_decodeSymbol(&DState, &DStream);
  1055. You can retrieve any bitfield you eventually stored into the bitStream (in reverse order)
  1056. Note : maximum allowed nbBits is 25, for 32-bits compatibility
  1057. size_t bitField = BITv05_readBits(&DStream, nbBits);
  1058. All above operations only read from local register (which size depends on size_t).
  1059. Refueling the register from memory is manually performed by the reload method.
  1060. endSignal = FSEv05_reloadDStream(&DStream);
  1061. BITv05_reloadDStream() result tells if there is still some more data to read from DStream.
  1062. BITv05_DStream_unfinished : there is still some data left into the DStream.
  1063. BITv05_DStream_endOfBuffer : Dstream reached end of buffer. Its container may no longer be completely filled.
  1064. BITv05_DStream_completed : Dstream reached its exact end, corresponding in general to decompression completed.
  1065. BITv05_DStream_tooFar : Dstream went too far. Decompression result is corrupted.
  1066. When reaching end of buffer (BITv05_DStream_endOfBuffer), progress slowly, notably if you decode multiple symbols per loop,
  1067. to properly detect the exact end of stream.
  1068. After each decoded symbol, check if DStream is fully consumed using this simple test :
  1069. BITv05_reloadDStream(&DStream) >= BITv05_DStream_completed
  1070. When it's done, verify decompression is fully completed, by checking both DStream and the relevant states.
  1071. Checking if DStream has reached its end is performed by :
  1072. BITv05_endOfDStream(&DStream);
  1073. Check also the states. There might be some symbols left there, if some high probability ones (>50%) are possible.
  1074. FSEv05_endOfDState(&DState);
  1075. */
  1076. /* *****************************************
  1077. * FSEv05 unsafe API
  1078. *******************************************/
  1079. static unsigned char FSEv05_decodeSymbolFast(FSEv05_DState_t* DStatePtr, BITv05_DStream_t* bitD);
  1080. /* faster, but works only if nbBits is always >= 1 (otherwise, result will be corrupted) */
  1081. /* *****************************************
  1082. * Implementation of inlined functions
  1083. *******************************************/
  1084. /* decompression */
  1085. typedef struct {
  1086. U16 tableLog;
  1087. U16 fastMode;
  1088. } FSEv05_DTableHeader; /* sizeof U32 */
  1089. typedef struct
  1090. {
  1091. unsigned short newState;
  1092. unsigned char symbol;
  1093. unsigned char nbBits;
  1094. } FSEv05_decode_t; /* size == U32 */
  1095. MEM_STATIC void FSEv05_initDState(FSEv05_DState_t* DStatePtr, BITv05_DStream_t* bitD, const FSEv05_DTable* dt)
  1096. {
  1097. const void* ptr = dt;
  1098. const FSEv05_DTableHeader* const DTableH = (const FSEv05_DTableHeader*)ptr;
  1099. DStatePtr->state = BITv05_readBits(bitD, DTableH->tableLog);
  1100. BITv05_reloadDStream(bitD);
  1101. DStatePtr->table = dt + 1;
  1102. }
  1103. MEM_STATIC size_t FSEv05_getStateValue(FSEv05_DState_t* DStatePtr)
  1104. {
  1105. return DStatePtr->state;
  1106. }
  1107. MEM_STATIC BYTE FSEv05_peakSymbol(FSEv05_DState_t* DStatePtr)
  1108. {
  1109. const FSEv05_decode_t DInfo = ((const FSEv05_decode_t*)(DStatePtr->table))[DStatePtr->state];
  1110. return DInfo.symbol;
  1111. }
  1112. MEM_STATIC BYTE FSEv05_decodeSymbol(FSEv05_DState_t* DStatePtr, BITv05_DStream_t* bitD)
  1113. {
  1114. const FSEv05_decode_t DInfo = ((const FSEv05_decode_t*)(DStatePtr->table))[DStatePtr->state];
  1115. const U32 nbBits = DInfo.nbBits;
  1116. BYTE symbol = DInfo.symbol;
  1117. size_t lowBits = BITv05_readBits(bitD, nbBits);
  1118. DStatePtr->state = DInfo.newState + lowBits;
  1119. return symbol;
  1120. }
  1121. MEM_STATIC BYTE FSEv05_decodeSymbolFast(FSEv05_DState_t* DStatePtr, BITv05_DStream_t* bitD)
  1122. {
  1123. const FSEv05_decode_t DInfo = ((const FSEv05_decode_t*)(DStatePtr->table))[DStatePtr->state];
  1124. const U32 nbBits = DInfo.nbBits;
  1125. BYTE symbol = DInfo.symbol;
  1126. size_t lowBits = BITv05_readBitsFast(bitD, nbBits);
  1127. DStatePtr->state = DInfo.newState + lowBits;
  1128. return symbol;
  1129. }
  1130. MEM_STATIC unsigned FSEv05_endOfDState(const FSEv05_DState_t* DStatePtr)
  1131. {
  1132. return DStatePtr->state == 0;
  1133. }
  1134. #if defined (__cplusplus)
  1135. }
  1136. #endif
  1137. #endif /* FSEv05_STATIC_H */
  1138. /* ******************************************************************
  1139. FSEv05 : Finite State Entropy coder
  1140. Copyright (C) 2013-2015, Yann Collet.
  1141. BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
  1142. Redistribution and use in source and binary forms, with or without
  1143. modification, are permitted provided that the following conditions are
  1144. met:
  1145. * Redistributions of source code must retain the above copyright
  1146. notice, this list of conditions and the following disclaimer.
  1147. * Redistributions in binary form must reproduce the above
  1148. copyright notice, this list of conditions and the following disclaimer
  1149. in the documentation and/or other materials provided with the
  1150. distribution.
  1151. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  1152. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  1153. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  1154. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  1155. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  1156. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  1157. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  1158. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  1159. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  1160. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  1161. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  1162. You can contact the author at :
  1163. - FSEv05 source repository : https://github.com/Cyan4973/FiniteStateEntropy
  1164. - Public forum : https://groups.google.com/forum/#!forum/lz4c
  1165. ****************************************************************** */
  1166. #ifndef FSEv05_COMMONDEFS_ONLY
  1167. /* **************************************************************
  1168. * Tuning parameters
  1169. ****************************************************************/
  1170. /*!MEMORY_USAGE :
  1171. * Memory usage formula : N->2^N Bytes (examples : 10 -> 1KB; 12 -> 4KB ; 16 -> 64KB; 20 -> 1MB; etc.)
  1172. * Increasing memory usage improves compression ratio
  1173. * Reduced memory usage can improve speed, due to cache effect
  1174. * Recommended max value is 14, for 16KB, which nicely fits into Intel x86 L1 cache */
  1175. #define FSEv05_MAX_MEMORY_USAGE 14
  1176. #define FSEv05_DEFAULT_MEMORY_USAGE 13
  1177. /*!FSEv05_MAX_SYMBOL_VALUE :
  1178. * Maximum symbol value authorized.
  1179. * Required for proper stack allocation */
  1180. #define FSEv05_MAX_SYMBOL_VALUE 255
  1181. /* **************************************************************
  1182. * template functions type & suffix
  1183. ****************************************************************/
  1184. #define FSEv05_FUNCTION_TYPE BYTE
  1185. #define FSEv05_FUNCTION_EXTENSION
  1186. #define FSEv05_DECODE_TYPE FSEv05_decode_t
  1187. #endif /* !FSEv05_COMMONDEFS_ONLY */
  1188. /* **************************************************************
  1189. * Compiler specifics
  1190. ****************************************************************/
  1191. #ifdef _MSC_VER /* Visual Studio */
  1192. # define FORCE_INLINE static __forceinline
  1193. # include <intrin.h> /* For Visual 2005 */
  1194. # pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */
  1195. # pragma warning(disable : 4214) /* disable: C4214: non-int bitfields */
  1196. #else
  1197. # ifdef __GNUC__
  1198. # define GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__)
  1199. # define FORCE_INLINE static inline __attribute__((always_inline))
  1200. # else
  1201. # define FORCE_INLINE static inline
  1202. # endif
  1203. #endif
  1204. /* **************************************************************
  1205. * Includes
  1206. ****************************************************************/
  1207. #include <stdlib.h> /* malloc, free, qsort */
  1208. #include <string.h> /* memcpy, memset */
  1209. #include <stdio.h> /* printf (debug) */
  1210. /* ***************************************************************
  1211. * Constants
  1212. *****************************************************************/
  1213. #define FSEv05_MAX_TABLELOG (FSEv05_MAX_MEMORY_USAGE-2)
  1214. #define FSEv05_MAX_TABLESIZE (1U<<FSEv05_MAX_TABLELOG)
  1215. #define FSEv05_MAXTABLESIZE_MASK (FSEv05_MAX_TABLESIZE-1)
  1216. #define FSEv05_DEFAULT_TABLELOG (FSEv05_DEFAULT_MEMORY_USAGE-2)
  1217. #define FSEv05_MIN_TABLELOG 5
  1218. #define FSEv05_TABLELOG_ABSOLUTE_MAX 15
  1219. #if FSEv05_MAX_TABLELOG > FSEv05_TABLELOG_ABSOLUTE_MAX
  1220. #error "FSEv05_MAX_TABLELOG > FSEv05_TABLELOG_ABSOLUTE_MAX is not supported"
  1221. #endif
  1222. /* **************************************************************
  1223. * Error Management
  1224. ****************************************************************/
  1225. #define FSEv05_STATIC_ASSERT(c) { enum { FSEv05_static_assert = 1/(int)(!!(c)) }; } /* use only *after* variable declarations */
  1226. /* **************************************************************
  1227. * Complex types
  1228. ****************************************************************/
  1229. typedef U32 DTable_max_t[FSEv05_DTABLE_SIZE_U32(FSEv05_MAX_TABLELOG)];
  1230. /* **************************************************************
  1231. * Templates
  1232. ****************************************************************/
  1233. /*
  1234. designed to be included
  1235. for type-specific functions (template emulation in C)
  1236. Objective is to write these functions only once, for improved maintenance
  1237. */
  1238. /* safety checks */
  1239. #ifndef FSEv05_FUNCTION_EXTENSION
  1240. # error "FSEv05_FUNCTION_EXTENSION must be defined"
  1241. #endif
  1242. #ifndef FSEv05_FUNCTION_TYPE
  1243. # error "FSEv05_FUNCTION_TYPE must be defined"
  1244. #endif
  1245. /* Function names */
  1246. #define FSEv05_CAT(X,Y) X##Y
  1247. #define FSEv05_FUNCTION_NAME(X,Y) FSEv05_CAT(X,Y)
  1248. #define FSEv05_TYPE_NAME(X,Y) FSEv05_CAT(X,Y)
  1249. /* Function templates */
  1250. static U32 FSEv05_tableStep(U32 tableSize) { return (tableSize>>1) + (tableSize>>3) + 3; }
  1251. FSEv05_DTable* FSEv05_createDTable (unsigned tableLog)
  1252. {
  1253. if (tableLog > FSEv05_TABLELOG_ABSOLUTE_MAX) tableLog = FSEv05_TABLELOG_ABSOLUTE_MAX;
  1254. return (FSEv05_DTable*)malloc( FSEv05_DTABLE_SIZE_U32(tableLog) * sizeof (U32) );
  1255. }
  1256. void FSEv05_freeDTable (FSEv05_DTable* dt)
  1257. {
  1258. free(dt);
  1259. }
  1260. size_t FSEv05_buildDTable(FSEv05_DTable* dt, const short* normalizedCounter, unsigned maxSymbolValue, unsigned tableLog)
  1261. {
  1262. FSEv05_DTableHeader DTableH;
  1263. void* const tdPtr = dt+1; /* because dt is unsigned, 32-bits aligned on 32-bits */
  1264. FSEv05_DECODE_TYPE* const tableDecode = (FSEv05_DECODE_TYPE*) (tdPtr);
  1265. const U32 tableSize = 1 << tableLog;
  1266. const U32 tableMask = tableSize-1;
  1267. const U32 step = FSEv05_tableStep(tableSize);
  1268. U16 symbolNext[FSEv05_MAX_SYMBOL_VALUE+1];
  1269. U32 position = 0;
  1270. U32 highThreshold = tableSize-1;
  1271. const S16 largeLimit= (S16)(1 << (tableLog-1));
  1272. U32 noLarge = 1;
  1273. U32 s;
  1274. /* Sanity Checks */
  1275. if (maxSymbolValue > FSEv05_MAX_SYMBOL_VALUE) return ERROR(maxSymbolValue_tooLarge);
  1276. if (tableLog > FSEv05_MAX_TABLELOG) return ERROR(tableLog_tooLarge);
  1277. /* Init, lay down lowprob symbols */
  1278. DTableH.tableLog = (U16)tableLog;
  1279. for (s=0; s<=maxSymbolValue; s++) {
  1280. if (normalizedCounter[s]==-1) {
  1281. tableDecode[highThreshold--].symbol = (FSEv05_FUNCTION_TYPE)s;
  1282. symbolNext[s] = 1;
  1283. } else {
  1284. if (normalizedCounter[s] >= largeLimit) noLarge=0;
  1285. symbolNext[s] = normalizedCounter[s];
  1286. } }
  1287. /* Spread symbols */
  1288. for (s=0; s<=maxSymbolValue; s++) {
  1289. int i;
  1290. for (i=0; i<normalizedCounter[s]; i++) {
  1291. tableDecode[position].symbol = (FSEv05_FUNCTION_TYPE)s;
  1292. position = (position + step) & tableMask;
  1293. while (position > highThreshold) position = (position + step) & tableMask; /* lowprob area */
  1294. } }
  1295. if (position!=0) return ERROR(GENERIC); /* position must reach all cells once, otherwise normalizedCounter is incorrect */
  1296. /* Build Decoding table */
  1297. {
  1298. U32 i;
  1299. for (i=0; i<tableSize; i++) {
  1300. FSEv05_FUNCTION_TYPE symbol = (FSEv05_FUNCTION_TYPE)(tableDecode[i].symbol);
  1301. U16 nextState = symbolNext[symbol]++;
  1302. tableDecode[i].nbBits = (BYTE) (tableLog - BITv05_highbit32 ((U32)nextState) );
  1303. tableDecode[i].newState = (U16) ( (nextState << tableDecode[i].nbBits) - tableSize);
  1304. } }
  1305. DTableH.fastMode = (U16)noLarge;
  1306. memcpy(dt, &DTableH, sizeof(DTableH));
  1307. return 0;
  1308. }
  1309. #ifndef FSEv05_COMMONDEFS_ONLY
  1310. /*-****************************************
  1311. * FSEv05 helper functions
  1312. ******************************************/
  1313. unsigned FSEv05_isError(size_t code) { return ERR_isError(code); }
  1314. const char* FSEv05_getErrorName(size_t code) { return ERR_getErrorName(code); }
  1315. /*-**************************************************************
  1316. * FSEv05 NCount encoding-decoding
  1317. ****************************************************************/
  1318. static short FSEv05_abs(short a) { return a<0 ? -a : a; }
  1319. size_t FSEv05_readNCount (short* normalizedCounter, unsigned* maxSVPtr, unsigned* tableLogPtr,
  1320. const void* headerBuffer, size_t hbSize)
  1321. {
  1322. const BYTE* const istart = (const BYTE*) headerBuffer;
  1323. const BYTE* const iend = istart + hbSize;
  1324. const BYTE* ip = istart;
  1325. int nbBits;
  1326. int remaining;
  1327. int threshold;
  1328. U32 bitStream;
  1329. int bitCount;
  1330. unsigned charnum = 0;
  1331. int previous0 = 0;
  1332. if (hbSize < 4) return ERROR(srcSize_wrong);
  1333. bitStream = MEM_readLE32(ip);
  1334. nbBits = (bitStream & 0xF) + FSEv05_MIN_TABLELOG; /* extract tableLog */
  1335. if (nbBits > FSEv05_TABLELOG_ABSOLUTE_MAX) return ERROR(tableLog_tooLarge);
  1336. bitStream >>= 4;
  1337. bitCount = 4;
  1338. *tableLogPtr = nbBits;
  1339. remaining = (1<<nbBits)+1;
  1340. threshold = 1<<nbBits;
  1341. nbBits++;
  1342. while ((remaining>1) && (charnum<=*maxSVPtr)) {
  1343. if (previous0) {
  1344. unsigned n0 = charnum;
  1345. while ((bitStream & 0xFFFF) == 0xFFFF) {
  1346. n0+=24;
  1347. if (ip < iend-5) {
  1348. ip+=2;
  1349. bitStream = MEM_readLE32(ip) >> bitCount;
  1350. } else {
  1351. bitStream >>= 16;
  1352. bitCount+=16;
  1353. } }
  1354. while ((bitStream & 3) == 3) {
  1355. n0+=3;
  1356. bitStream>>=2;
  1357. bitCount+=2;
  1358. }
  1359. n0 += bitStream & 3;
  1360. bitCount += 2;
  1361. if (n0 > *maxSVPtr) return ERROR(maxSymbolValue_tooSmall);
  1362. while (charnum < n0) normalizedCounter[charnum++] = 0;
  1363. if ((ip <= iend-7) || (ip + (bitCount>>3) <= iend-4)) {
  1364. ip += bitCount>>3;
  1365. bitCount &= 7;
  1366. bitStream = MEM_readLE32(ip) >> bitCount;
  1367. }
  1368. else
  1369. bitStream >>= 2;
  1370. }
  1371. {
  1372. const short max = (short)((2*threshold-1)-remaining);
  1373. short count;
  1374. if ((bitStream & (threshold-1)) < (U32)max) {
  1375. count = (short)(bitStream & (threshold-1));
  1376. bitCount += nbBits-1;
  1377. } else {
  1378. count = (short)(bitStream & (2*threshold-1));
  1379. if (count >= threshold) count -= max;
  1380. bitCount += nbBits;
  1381. }
  1382. count--; /* extra accuracy */
  1383. remaining -= FSEv05_abs(count);
  1384. normalizedCounter[charnum++] = count;
  1385. previous0 = !count;
  1386. while (remaining < threshold) {
  1387. nbBits--;
  1388. threshold >>= 1;
  1389. }
  1390. if ((ip <= iend-7) || (ip + (bitCount>>3) <= iend-4)) {
  1391. ip += bitCount>>3;
  1392. bitCount &= 7;
  1393. } else {
  1394. bitCount -= (int)(8 * (iend - 4 - ip));
  1395. ip = iend - 4;
  1396. }
  1397. bitStream = MEM_readLE32(ip) >> (bitCount & 31);
  1398. } }
  1399. if (remaining != 1) return ERROR(GENERIC);
  1400. *maxSVPtr = charnum-1;
  1401. ip += (bitCount+7)>>3;
  1402. if ((size_t)(ip-istart) > hbSize) return ERROR(srcSize_wrong);
  1403. return ip-istart;
  1404. }
  1405. /*-*******************************************************
  1406. * Decompression (Byte symbols)
  1407. *********************************************************/
  1408. size_t FSEv05_buildDTable_rle (FSEv05_DTable* dt, BYTE symbolValue)
  1409. {
  1410. void* ptr = dt;
  1411. FSEv05_DTableHeader* const DTableH = (FSEv05_DTableHeader*)ptr;
  1412. void* dPtr = dt + 1;
  1413. FSEv05_decode_t* const cell = (FSEv05_decode_t*)dPtr;
  1414. DTableH->tableLog = 0;
  1415. DTableH->fastMode = 0;
  1416. cell->newState = 0;
  1417. cell->symbol = symbolValue;
  1418. cell->nbBits = 0;
  1419. return 0;
  1420. }
  1421. size_t FSEv05_buildDTable_raw (FSEv05_DTable* dt, unsigned nbBits)
  1422. {
  1423. void* ptr = dt;
  1424. FSEv05_DTableHeader* const DTableH = (FSEv05_DTableHeader*)ptr;
  1425. void* dPtr = dt + 1;
  1426. FSEv05_decode_t* const dinfo = (FSEv05_decode_t*)dPtr;
  1427. const unsigned tableSize = 1 << nbBits;
  1428. const unsigned tableMask = tableSize - 1;
  1429. const unsigned maxSymbolValue = tableMask;
  1430. unsigned s;
  1431. /* Sanity checks */
  1432. if (nbBits < 1) return ERROR(GENERIC); /* min size */
  1433. /* Build Decoding Table */
  1434. DTableH->tableLog = (U16)nbBits;
  1435. DTableH->fastMode = 1;
  1436. for (s=0; s<=maxSymbolValue; s++) {
  1437. dinfo[s].newState = 0;
  1438. dinfo[s].symbol = (BYTE)s;
  1439. dinfo[s].nbBits = (BYTE)nbBits;
  1440. }
  1441. return 0;
  1442. }
  1443. FORCE_INLINE size_t FSEv05_decompress_usingDTable_generic(
  1444. void* dst, size_t maxDstSize,
  1445. const void* cSrc, size_t cSrcSize,
  1446. const FSEv05_DTable* dt, const unsigned fast)
  1447. {
  1448. BYTE* const ostart = (BYTE*) dst;
  1449. BYTE* op = ostart;
  1450. BYTE* const omax = op + maxDstSize;
  1451. BYTE* const olimit = omax-3;
  1452. BITv05_DStream_t bitD;
  1453. FSEv05_DState_t state1;
  1454. FSEv05_DState_t state2;
  1455. size_t errorCode;
  1456. /* Init */
  1457. errorCode = BITv05_initDStream(&bitD, cSrc, cSrcSize); /* replaced last arg by maxCompressed Size */
  1458. if (FSEv05_isError(errorCode)) return errorCode;
  1459. FSEv05_initDState(&state1, &bitD, dt);
  1460. FSEv05_initDState(&state2, &bitD, dt);
  1461. #define FSEv05_GETSYMBOL(statePtr) fast ? FSEv05_decodeSymbolFast(statePtr, &bitD) : FSEv05_decodeSymbol(statePtr, &bitD)
  1462. /* 4 symbols per loop */
  1463. for ( ; (BITv05_reloadDStream(&bitD)==BITv05_DStream_unfinished) && (op<olimit) ; op+=4) {
  1464. op[0] = FSEv05_GETSYMBOL(&state1);
  1465. if (FSEv05_MAX_TABLELOG*2+7 > sizeof(bitD.bitContainer)*8) /* This test must be static */
  1466. BITv05_reloadDStream(&bitD);
  1467. op[1] = FSEv05_GETSYMBOL(&state2);
  1468. if (FSEv05_MAX_TABLELOG*4+7 > sizeof(bitD.bitContainer)*8) /* This test must be static */
  1469. { if (BITv05_reloadDStream(&bitD) > BITv05_DStream_unfinished) { op+=2; break; } }
  1470. op[2] = FSEv05_GETSYMBOL(&state1);
  1471. if (FSEv05_MAX_TABLELOG*2+7 > sizeof(bitD.bitContainer)*8) /* This test must be static */
  1472. BITv05_reloadDStream(&bitD);
  1473. op[3] = FSEv05_GETSYMBOL(&state2);
  1474. }
  1475. /* tail */
  1476. /* note : BITv05_reloadDStream(&bitD) >= FSEv05_DStream_partiallyFilled; Ends at exactly BITv05_DStream_completed */
  1477. while (1) {
  1478. if ( (BITv05_reloadDStream(&bitD)>BITv05_DStream_completed) || (op==omax) || (BITv05_endOfDStream(&bitD) && (fast || FSEv05_endOfDState(&state1))) )
  1479. break;
  1480. *op++ = FSEv05_GETSYMBOL(&state1);
  1481. if ( (BITv05_reloadDStream(&bitD)>BITv05_DStream_completed) || (op==omax) || (BITv05_endOfDStream(&bitD) && (fast || FSEv05_endOfDState(&state2))) )
  1482. break;
  1483. *op++ = FSEv05_GETSYMBOL(&state2);
  1484. }
  1485. /* end ? */
  1486. if (BITv05_endOfDStream(&bitD) && FSEv05_endOfDState(&state1) && FSEv05_endOfDState(&state2))
  1487. return op-ostart;
  1488. if (op==omax) return ERROR(dstSize_tooSmall); /* dst buffer is full, but cSrc unfinished */
  1489. return ERROR(corruption_detected);
  1490. }
  1491. size_t FSEv05_decompress_usingDTable(void* dst, size_t originalSize,
  1492. const void* cSrc, size_t cSrcSize,
  1493. const FSEv05_DTable* dt)
  1494. {
  1495. const void* ptr = dt;
  1496. const FSEv05_DTableHeader* DTableH = (const FSEv05_DTableHeader*)ptr;
  1497. const U32 fastMode = DTableH->fastMode;
  1498. /* select fast mode (static) */
  1499. if (fastMode) return FSEv05_decompress_usingDTable_generic(dst, originalSize, cSrc, cSrcSize, dt, 1);
  1500. return FSEv05_decompress_usingDTable_generic(dst, originalSize, cSrc, cSrcSize, dt, 0);
  1501. }
  1502. size_t FSEv05_decompress(void* dst, size_t maxDstSize, const void* cSrc, size_t cSrcSize)
  1503. {
  1504. const BYTE* const istart = (const BYTE*)cSrc;
  1505. const BYTE* ip = istart;
  1506. short counting[FSEv05_MAX_SYMBOL_VALUE+1];
  1507. DTable_max_t dt; /* Static analyzer seems unable to understand this table will be properly initialized later */
  1508. unsigned tableLog;
  1509. unsigned maxSymbolValue = FSEv05_MAX_SYMBOL_VALUE;
  1510. size_t errorCode;
  1511. if (cSrcSize<2) return ERROR(srcSize_wrong); /* too small input size */
  1512. /* normal FSEv05 decoding mode */
  1513. errorCode = FSEv05_readNCount (counting, &maxSymbolValue, &tableLog, istart, cSrcSize);
  1514. if (FSEv05_isError(errorCode)) return errorCode;
  1515. if (errorCode >= cSrcSize) return ERROR(srcSize_wrong); /* too small input size */
  1516. ip += errorCode;
  1517. cSrcSize -= errorCode;
  1518. errorCode = FSEv05_buildDTable (dt, counting, maxSymbolValue, tableLog);
  1519. if (FSEv05_isError(errorCode)) return errorCode;
  1520. /* always return, even if it is an error code */
  1521. return FSEv05_decompress_usingDTable (dst, maxDstSize, ip, cSrcSize, dt);
  1522. }
  1523. #endif /* FSEv05_COMMONDEFS_ONLY */
  1524. /* ******************************************************************
  1525. Huff0 : Huffman coder, part of New Generation Entropy library
  1526. header file
  1527. Copyright (C) 2013-2016, Yann Collet.
  1528. BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
  1529. Redistribution and use in source and binary forms, with or without
  1530. modification, are permitted provided that the following conditions are
  1531. met:
  1532. * Redistributions of source code must retain the above copyright
  1533. notice, this list of conditions and the following disclaimer.
  1534. * Redistributions in binary form must reproduce the above
  1535. copyright notice, this list of conditions and the following disclaimer
  1536. in the documentation and/or other materials provided with the
  1537. distribution.
  1538. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  1539. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  1540. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  1541. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  1542. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  1543. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  1544. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  1545. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  1546. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  1547. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  1548. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  1549. You can contact the author at :
  1550. - Source repository : https://github.com/Cyan4973/FiniteStateEntropy
  1551. ****************************************************************** */
  1552. #ifndef HUFF0_H
  1553. #define HUFF0_H
  1554. #if defined (__cplusplus)
  1555. extern "C" {
  1556. #endif
  1557. /* ****************************************
  1558. * Huff0 simple functions
  1559. ******************************************/
  1560. size_t HUFv05_decompress(void* dst, size_t dstSize,
  1561. const void* cSrc, size_t cSrcSize);
  1562. /*!
  1563. HUFv05_decompress():
  1564. Decompress Huff0 data from buffer 'cSrc', of size 'cSrcSize',
  1565. into already allocated destination buffer 'dst', of size 'dstSize'.
  1566. @dstSize : must be the **exact** size of original (uncompressed) data.
  1567. Note : in contrast with FSEv05, HUFv05_decompress can regenerate
  1568. RLE (cSrcSize==1) and uncompressed (cSrcSize==dstSize) data,
  1569. because it knows size to regenerate.
  1570. @return : size of regenerated data (== dstSize)
  1571. or an error code, which can be tested using HUFv05_isError()
  1572. */
  1573. /* ****************************************
  1574. * Tool functions
  1575. ******************************************/
  1576. /* Error Management */
  1577. unsigned HUFv05_isError(size_t code); /* tells if a return value is an error code */
  1578. const char* HUFv05_getErrorName(size_t code); /* provides error code string (useful for debugging) */
  1579. #if defined (__cplusplus)
  1580. }
  1581. #endif
  1582. #endif /* HUF0_H */
  1583. /* ******************************************************************
  1584. Huff0 : Huffman codec, part of New Generation Entropy library
  1585. header file, for static linking only
  1586. Copyright (C) 2013-2016, Yann Collet
  1587. BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
  1588. Redistribution and use in source and binary forms, with or without
  1589. modification, are permitted provided that the following conditions are
  1590. met:
  1591. * Redistributions of source code must retain the above copyright
  1592. notice, this list of conditions and the following disclaimer.
  1593. * Redistributions in binary form must reproduce the above
  1594. copyright notice, this list of conditions and the following disclaimer
  1595. in the documentation and/or other materials provided with the
  1596. distribution.
  1597. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  1598. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  1599. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  1600. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  1601. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  1602. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  1603. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  1604. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  1605. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  1606. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  1607. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  1608. You can contact the author at :
  1609. - Source repository : https://github.com/Cyan4973/FiniteStateEntropy
  1610. ****************************************************************** */
  1611. #ifndef HUF0_STATIC_H
  1612. #define HUF0_STATIC_H
  1613. #if defined (__cplusplus)
  1614. extern "C" {
  1615. #endif
  1616. /* ****************************************
  1617. * Static allocation
  1618. ******************************************/
  1619. /* static allocation of Huff0's DTable */
  1620. #define HUFv05_DTABLE_SIZE(maxTableLog) (1 + (1<<maxTableLog))
  1621. #define HUFv05_CREATE_STATIC_DTABLEX2(DTable, maxTableLog) \
  1622. unsigned short DTable[HUFv05_DTABLE_SIZE(maxTableLog)] = { maxTableLog }
  1623. #define HUFv05_CREATE_STATIC_DTABLEX4(DTable, maxTableLog) \
  1624. unsigned int DTable[HUFv05_DTABLE_SIZE(maxTableLog)] = { maxTableLog }
  1625. #define HUFv05_CREATE_STATIC_DTABLEX6(DTable, maxTableLog) \
  1626. unsigned int DTable[HUFv05_DTABLE_SIZE(maxTableLog) * 3 / 2] = { maxTableLog }
  1627. /* ****************************************
  1628. * Advanced decompression functions
  1629. ******************************************/
  1630. size_t HUFv05_decompress4X2 (void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize); /* single-symbol decoder */
  1631. size_t HUFv05_decompress4X4 (void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize); /* double-symbols decoder */
  1632. /* ****************************************
  1633. * Huff0 detailed API
  1634. ******************************************/
  1635. /*!
  1636. HUFv05_decompress() does the following:
  1637. 1. select the decompression algorithm (X2, X4, X6) based on pre-computed heuristics
  1638. 2. build Huffman table from save, using HUFv05_readDTableXn()
  1639. 3. decode 1 or 4 segments in parallel using HUFv05_decompressSXn_usingDTable
  1640. */
  1641. size_t HUFv05_readDTableX2 (unsigned short* DTable, const void* src, size_t srcSize);
  1642. size_t HUFv05_readDTableX4 (unsigned* DTable, const void* src, size_t srcSize);
  1643. size_t HUFv05_decompress4X2_usingDTable(void* dst, size_t maxDstSize, const void* cSrc, size_t cSrcSize, const unsigned short* DTable);
  1644. size_t HUFv05_decompress4X4_usingDTable(void* dst, size_t maxDstSize, const void* cSrc, size_t cSrcSize, const unsigned* DTable);
  1645. /* single stream variants */
  1646. size_t HUFv05_decompress1X2 (void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize); /* single-symbol decoder */
  1647. size_t HUFv05_decompress1X4 (void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize); /* double-symbol decoder */
  1648. size_t HUFv05_decompress1X2_usingDTable(void* dst, size_t maxDstSize, const void* cSrc, size_t cSrcSize, const unsigned short* DTable);
  1649. size_t HUFv05_decompress1X4_usingDTable(void* dst, size_t maxDstSize, const void* cSrc, size_t cSrcSize, const unsigned* DTable);
  1650. #if defined (__cplusplus)
  1651. }
  1652. #endif
  1653. #endif /* HUF0_STATIC_H */
  1654. /* ******************************************************************
  1655. Huff0 : Huffman coder, part of New Generation Entropy library
  1656. Copyright (C) 2013-2015, Yann Collet.
  1657. BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
  1658. Redistribution and use in source and binary forms, with or without
  1659. modification, are permitted provided that the following conditions are
  1660. met:
  1661. * Redistributions of source code must retain the above copyright
  1662. notice, this list of conditions and the following disclaimer.
  1663. * Redistributions in binary form must reproduce the above
  1664. copyright notice, this list of conditions and the following disclaimer
  1665. in the documentation and/or other materials provided with the
  1666. distribution.
  1667. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  1668. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  1669. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  1670. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  1671. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  1672. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  1673. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  1674. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  1675. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  1676. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  1677. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  1678. You can contact the author at :
  1679. - FSEv05+Huff0 source repository : https://github.com/Cyan4973/FiniteStateEntropy
  1680. - Public forum : https://groups.google.com/forum/#!forum/lz4c
  1681. ****************************************************************** */
  1682. /* **************************************************************
  1683. * Compiler specifics
  1684. ****************************************************************/
  1685. #if defined (__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */)
  1686. /* inline is defined */
  1687. #elif defined(_MSC_VER)
  1688. # define inline __inline
  1689. #else
  1690. # define inline /* disable inline */
  1691. #endif
  1692. #ifdef _MSC_VER /* Visual Studio */
  1693. # define FORCE_INLINE static __forceinline
  1694. # pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */
  1695. #else
  1696. # ifdef __GNUC__
  1697. # define FORCE_INLINE static inline __attribute__((always_inline))
  1698. # else
  1699. # define FORCE_INLINE static inline
  1700. # endif
  1701. #endif
  1702. /* **************************************************************
  1703. * Includes
  1704. ****************************************************************/
  1705. #include <stdlib.h> /* malloc, free, qsort */
  1706. #include <string.h> /* memcpy, memset */
  1707. #include <stdio.h> /* printf (debug) */
  1708. /* **************************************************************
  1709. * Constants
  1710. ****************************************************************/
  1711. #define HUFv05_ABSOLUTEMAX_TABLELOG 16 /* absolute limit of HUFv05_MAX_TABLELOG. Beyond that value, code does not work */
  1712. #define HUFv05_MAX_TABLELOG 12 /* max configured tableLog (for static allocation); can be modified up to HUFv05_ABSOLUTEMAX_TABLELOG */
  1713. #define HUFv05_DEFAULT_TABLELOG HUFv05_MAX_TABLELOG /* tableLog by default, when not specified */
  1714. #define HUFv05_MAX_SYMBOL_VALUE 255
  1715. #if (HUFv05_MAX_TABLELOG > HUFv05_ABSOLUTEMAX_TABLELOG)
  1716. # error "HUFv05_MAX_TABLELOG is too large !"
  1717. #endif
  1718. /* **************************************************************
  1719. * Error Management
  1720. ****************************************************************/
  1721. unsigned HUFv05_isError(size_t code) { return ERR_isError(code); }
  1722. const char* HUFv05_getErrorName(size_t code) { return ERR_getErrorName(code); }
  1723. #define HUFv05_STATIC_ASSERT(c) { enum { HUFv05_static_assert = 1/(int)(!!(c)) }; } /* use only *after* variable declarations */
  1724. /* *******************************************************
  1725. * Huff0 : Huffman block decompression
  1726. *********************************************************/
  1727. typedef struct { BYTE byte; BYTE nbBits; } HUFv05_DEltX2; /* single-symbol decoding */
  1728. typedef struct { U16 sequence; BYTE nbBits; BYTE length; } HUFv05_DEltX4; /* double-symbols decoding */
  1729. typedef struct { BYTE symbol; BYTE weight; } sortedSymbol_t;
  1730. /*! HUFv05_readStats
  1731. Read compact Huffman tree, saved by HUFv05_writeCTable
  1732. @huffWeight : destination buffer
  1733. @return : size read from `src`
  1734. */
  1735. static size_t HUFv05_readStats(BYTE* huffWeight, size_t hwSize, U32* rankStats,
  1736. U32* nbSymbolsPtr, U32* tableLogPtr,
  1737. const void* src, size_t srcSize)
  1738. {
  1739. U32 weightTotal;
  1740. U32 tableLog;
  1741. const BYTE* ip = (const BYTE*) src;
  1742. size_t iSize = ip[0];
  1743. size_t oSize;
  1744. U32 n;
  1745. //memset(huffWeight, 0, hwSize); /* is not necessary, even though some analyzer complain ... */
  1746. if (iSize >= 128) { /* special header */
  1747. if (iSize >= (242)) { /* RLE */
  1748. static int l[14] = { 1, 2, 3, 4, 7, 8, 15, 16, 31, 32, 63, 64, 127, 128 };
  1749. oSize = l[iSize-242];
  1750. memset(huffWeight, 1, hwSize);
  1751. iSize = 0;
  1752. }
  1753. else { /* Incompressible */
  1754. oSize = iSize - 127;
  1755. iSize = ((oSize+1)/2);
  1756. if (iSize+1 > srcSize) return ERROR(srcSize_wrong);
  1757. if (oSize >= hwSize) return ERROR(corruption_detected);
  1758. ip += 1;
  1759. for (n=0; n<oSize; n+=2) {
  1760. huffWeight[n] = ip[n/2] >> 4;
  1761. huffWeight[n+1] = ip[n/2] & 15;
  1762. } } }
  1763. else { /* header compressed with FSEv05 (normal case) */
  1764. if (iSize+1 > srcSize) return ERROR(srcSize_wrong);
  1765. oSize = FSEv05_decompress(huffWeight, hwSize-1, ip+1, iSize); /* max (hwSize-1) values decoded, as last one is implied */
  1766. if (FSEv05_isError(oSize)) return oSize;
  1767. }
  1768. /* collect weight stats */
  1769. memset(rankStats, 0, (HUFv05_ABSOLUTEMAX_TABLELOG + 1) * sizeof(U32));
  1770. weightTotal = 0;
  1771. for (n=0; n<oSize; n++) {
  1772. if (huffWeight[n] >= HUFv05_ABSOLUTEMAX_TABLELOG) return ERROR(corruption_detected);
  1773. rankStats[huffWeight[n]]++;
  1774. weightTotal += (1 << huffWeight[n]) >> 1;
  1775. }
  1776. /* get last non-null symbol weight (implied, total must be 2^n) */
  1777. tableLog = BITv05_highbit32(weightTotal) + 1;
  1778. if (tableLog > HUFv05_ABSOLUTEMAX_TABLELOG) return ERROR(corruption_detected);
  1779. { /* determine last weight */
  1780. U32 total = 1 << tableLog;
  1781. U32 rest = total - weightTotal;
  1782. U32 verif = 1 << BITv05_highbit32(rest);
  1783. U32 lastWeight = BITv05_highbit32(rest) + 1;
  1784. if (verif != rest) return ERROR(corruption_detected); /* last value must be a clean power of 2 */
  1785. huffWeight[oSize] = (BYTE)lastWeight;
  1786. rankStats[lastWeight]++;
  1787. }
  1788. /* check tree construction validity */
  1789. if ((rankStats[1] < 2) || (rankStats[1] & 1)) return ERROR(corruption_detected); /* by construction : at least 2 elts of rank 1, must be even */
  1790. /* results */
  1791. *nbSymbolsPtr = (U32)(oSize+1);
  1792. *tableLogPtr = tableLog;
  1793. return iSize+1;
  1794. }
  1795. /*-***************************/
  1796. /* single-symbol decoding */
  1797. /*-***************************/
  1798. size_t HUFv05_readDTableX2 (U16* DTable, const void* src, size_t srcSize)
  1799. {
  1800. BYTE huffWeight[HUFv05_MAX_SYMBOL_VALUE + 1];
  1801. U32 rankVal[HUFv05_ABSOLUTEMAX_TABLELOG + 1]; /* large enough for values from 0 to 16 */
  1802. U32 tableLog = 0;
  1803. size_t iSize;
  1804. U32 nbSymbols = 0;
  1805. U32 n;
  1806. U32 nextRankStart;
  1807. void* const dtPtr = DTable + 1;
  1808. HUFv05_DEltX2* const dt = (HUFv05_DEltX2*)dtPtr;
  1809. HUFv05_STATIC_ASSERT(sizeof(HUFv05_DEltX2) == sizeof(U16)); /* if compilation fails here, assertion is false */
  1810. //memset(huffWeight, 0, sizeof(huffWeight)); /* is not necessary, even though some analyzer complain ... */
  1811. iSize = HUFv05_readStats(huffWeight, HUFv05_MAX_SYMBOL_VALUE + 1, rankVal, &nbSymbols, &tableLog, src, srcSize);
  1812. if (HUFv05_isError(iSize)) return iSize;
  1813. /* check result */
  1814. if (tableLog > DTable[0]) return ERROR(tableLog_tooLarge); /* DTable is too small */
  1815. DTable[0] = (U16)tableLog; /* maybe should separate sizeof allocated DTable, from used size of DTable, in case of re-use */
  1816. /* Prepare ranks */
  1817. nextRankStart = 0;
  1818. for (n=1; n<=tableLog; n++) {
  1819. U32 current = nextRankStart;
  1820. nextRankStart += (rankVal[n] << (n-1));
  1821. rankVal[n] = current;
  1822. }
  1823. /* fill DTable */
  1824. for (n=0; n<nbSymbols; n++) {
  1825. const U32 w = huffWeight[n];
  1826. const U32 length = (1 << w) >> 1;
  1827. U32 i;
  1828. HUFv05_DEltX2 D;
  1829. D.byte = (BYTE)n; D.nbBits = (BYTE)(tableLog + 1 - w);
  1830. for (i = rankVal[w]; i < rankVal[w] + length; i++)
  1831. dt[i] = D;
  1832. rankVal[w] += length;
  1833. }
  1834. return iSize;
  1835. }
  1836. static BYTE HUFv05_decodeSymbolX2(BITv05_DStream_t* Dstream, const HUFv05_DEltX2* dt, const U32 dtLog)
  1837. {
  1838. const size_t val = BITv05_lookBitsFast(Dstream, dtLog); /* note : dtLog >= 1 */
  1839. const BYTE c = dt[val].byte;
  1840. BITv05_skipBits(Dstream, dt[val].nbBits);
  1841. return c;
  1842. }
  1843. #define HUFv05_DECODE_SYMBOLX2_0(ptr, DStreamPtr) \
  1844. *ptr++ = HUFv05_decodeSymbolX2(DStreamPtr, dt, dtLog)
  1845. #define HUFv05_DECODE_SYMBOLX2_1(ptr, DStreamPtr) \
  1846. if (MEM_64bits() || (HUFv05_MAX_TABLELOG<=12)) \
  1847. HUFv05_DECODE_SYMBOLX2_0(ptr, DStreamPtr)
  1848. #define HUFv05_DECODE_SYMBOLX2_2(ptr, DStreamPtr) \
  1849. if (MEM_64bits()) \
  1850. HUFv05_DECODE_SYMBOLX2_0(ptr, DStreamPtr)
  1851. static inline size_t HUFv05_decodeStreamX2(BYTE* p, BITv05_DStream_t* const bitDPtr, BYTE* const pEnd, const HUFv05_DEltX2* const dt, const U32 dtLog)
  1852. {
  1853. BYTE* const pStart = p;
  1854. /* up to 4 symbols at a time */
  1855. while ((BITv05_reloadDStream(bitDPtr) == BITv05_DStream_unfinished) && (p <= pEnd-4)) {
  1856. HUFv05_DECODE_SYMBOLX2_2(p, bitDPtr);
  1857. HUFv05_DECODE_SYMBOLX2_1(p, bitDPtr);
  1858. HUFv05_DECODE_SYMBOLX2_2(p, bitDPtr);
  1859. HUFv05_DECODE_SYMBOLX2_0(p, bitDPtr);
  1860. }
  1861. /* closer to the end */
  1862. while ((BITv05_reloadDStream(bitDPtr) == BITv05_DStream_unfinished) && (p < pEnd))
  1863. HUFv05_DECODE_SYMBOLX2_0(p, bitDPtr);
  1864. /* no more data to retrieve from bitstream, hence no need to reload */
  1865. while (p < pEnd)
  1866. HUFv05_DECODE_SYMBOLX2_0(p, bitDPtr);
  1867. return pEnd-pStart;
  1868. }
  1869. size_t HUFv05_decompress1X2_usingDTable(
  1870. void* dst, size_t dstSize,
  1871. const void* cSrc, size_t cSrcSize,
  1872. const U16* DTable)
  1873. {
  1874. BYTE* op = (BYTE*)dst;
  1875. BYTE* const oend = op + dstSize;
  1876. size_t errorCode;
  1877. const U32 dtLog = DTable[0];
  1878. const void* dtPtr = DTable;
  1879. const HUFv05_DEltX2* const dt = ((const HUFv05_DEltX2*)dtPtr)+1;
  1880. BITv05_DStream_t bitD;
  1881. errorCode = BITv05_initDStream(&bitD, cSrc, cSrcSize);
  1882. if (HUFv05_isError(errorCode)) return errorCode;
  1883. HUFv05_decodeStreamX2(op, &bitD, oend, dt, dtLog);
  1884. /* check */
  1885. if (!BITv05_endOfDStream(&bitD)) return ERROR(corruption_detected);
  1886. return dstSize;
  1887. }
  1888. size_t HUFv05_decompress1X2 (void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize)
  1889. {
  1890. HUFv05_CREATE_STATIC_DTABLEX2(DTable, HUFv05_MAX_TABLELOG);
  1891. const BYTE* ip = (const BYTE*) cSrc;
  1892. size_t errorCode;
  1893. errorCode = HUFv05_readDTableX2 (DTable, cSrc, cSrcSize);
  1894. if (HUFv05_isError(errorCode)) return errorCode;
  1895. if (errorCode >= cSrcSize) return ERROR(srcSize_wrong);
  1896. ip += errorCode;
  1897. cSrcSize -= errorCode;
  1898. return HUFv05_decompress1X2_usingDTable (dst, dstSize, ip, cSrcSize, DTable);
  1899. }
  1900. size_t HUFv05_decompress4X2_usingDTable(
  1901. void* dst, size_t dstSize,
  1902. const void* cSrc, size_t cSrcSize,
  1903. const U16* DTable)
  1904. {
  1905. const BYTE* const istart = (const BYTE*) cSrc;
  1906. BYTE* const ostart = (BYTE*) dst;
  1907. BYTE* const oend = ostart + dstSize;
  1908. const void* const dtPtr = DTable;
  1909. const HUFv05_DEltX2* const dt = ((const HUFv05_DEltX2*)dtPtr) +1;
  1910. const U32 dtLog = DTable[0];
  1911. size_t errorCode;
  1912. /* Init */
  1913. BITv05_DStream_t bitD1;
  1914. BITv05_DStream_t bitD2;
  1915. BITv05_DStream_t bitD3;
  1916. BITv05_DStream_t bitD4;
  1917. const size_t length1 = MEM_readLE16(istart);
  1918. const size_t length2 = MEM_readLE16(istart+2);
  1919. const size_t length3 = MEM_readLE16(istart+4);
  1920. size_t length4;
  1921. const BYTE* const istart1 = istart + 6; /* jumpTable */
  1922. const BYTE* const istart2 = istart1 + length1;
  1923. const BYTE* const istart3 = istart2 + length2;
  1924. const BYTE* const istart4 = istart3 + length3;
  1925. const size_t segmentSize = (dstSize+3) / 4;
  1926. BYTE* const opStart2 = ostart + segmentSize;
  1927. BYTE* const opStart3 = opStart2 + segmentSize;
  1928. BYTE* const opStart4 = opStart3 + segmentSize;
  1929. BYTE* op1 = ostart;
  1930. BYTE* op2 = opStart2;
  1931. BYTE* op3 = opStart3;
  1932. BYTE* op4 = opStart4;
  1933. U32 endSignal;
  1934. /* Check */
  1935. if (cSrcSize < 10) return ERROR(corruption_detected); /* strict minimum : jump table + 1 byte per stream */
  1936. length4 = cSrcSize - (length1 + length2 + length3 + 6);
  1937. if (length4 > cSrcSize) return ERROR(corruption_detected); /* overflow */
  1938. errorCode = BITv05_initDStream(&bitD1, istart1, length1);
  1939. if (HUFv05_isError(errorCode)) return errorCode;
  1940. errorCode = BITv05_initDStream(&bitD2, istart2, length2);
  1941. if (HUFv05_isError(errorCode)) return errorCode;
  1942. errorCode = BITv05_initDStream(&bitD3, istart3, length3);
  1943. if (HUFv05_isError(errorCode)) return errorCode;
  1944. errorCode = BITv05_initDStream(&bitD4, istart4, length4);
  1945. if (HUFv05_isError(errorCode)) return errorCode;
  1946. /* 16-32 symbols per loop (4-8 symbols per stream) */
  1947. endSignal = BITv05_reloadDStream(&bitD1) | BITv05_reloadDStream(&bitD2) | BITv05_reloadDStream(&bitD3) | BITv05_reloadDStream(&bitD4);
  1948. for ( ; (endSignal==BITv05_DStream_unfinished) && (op4<(oend-7)) ; ) {
  1949. HUFv05_DECODE_SYMBOLX2_2(op1, &bitD1);
  1950. HUFv05_DECODE_SYMBOLX2_2(op2, &bitD2);
  1951. HUFv05_DECODE_SYMBOLX2_2(op3, &bitD3);
  1952. HUFv05_DECODE_SYMBOLX2_2(op4, &bitD4);
  1953. HUFv05_DECODE_SYMBOLX2_1(op1, &bitD1);
  1954. HUFv05_DECODE_SYMBOLX2_1(op2, &bitD2);
  1955. HUFv05_DECODE_SYMBOLX2_1(op3, &bitD3);
  1956. HUFv05_DECODE_SYMBOLX2_1(op4, &bitD4);
  1957. HUFv05_DECODE_SYMBOLX2_2(op1, &bitD1);
  1958. HUFv05_DECODE_SYMBOLX2_2(op2, &bitD2);
  1959. HUFv05_DECODE_SYMBOLX2_2(op3, &bitD3);
  1960. HUFv05_DECODE_SYMBOLX2_2(op4, &bitD4);
  1961. HUFv05_DECODE_SYMBOLX2_0(op1, &bitD1);
  1962. HUFv05_DECODE_SYMBOLX2_0(op2, &bitD2);
  1963. HUFv05_DECODE_SYMBOLX2_0(op3, &bitD3);
  1964. HUFv05_DECODE_SYMBOLX2_0(op4, &bitD4);
  1965. endSignal = BITv05_reloadDStream(&bitD1) | BITv05_reloadDStream(&bitD2) | BITv05_reloadDStream(&bitD3) | BITv05_reloadDStream(&bitD4);
  1966. }
  1967. /* check corruption */
  1968. if (op1 > opStart2) return ERROR(corruption_detected);
  1969. if (op2 > opStart3) return ERROR(corruption_detected);
  1970. if (op3 > opStart4) return ERROR(corruption_detected);
  1971. /* note : op4 supposed already verified within main loop */
  1972. /* finish bitStreams one by one */
  1973. HUFv05_decodeStreamX2(op1, &bitD1, opStart2, dt, dtLog);
  1974. HUFv05_decodeStreamX2(op2, &bitD2, opStart3, dt, dtLog);
  1975. HUFv05_decodeStreamX2(op3, &bitD3, opStart4, dt, dtLog);
  1976. HUFv05_decodeStreamX2(op4, &bitD4, oend, dt, dtLog);
  1977. /* check */
  1978. endSignal = BITv05_endOfDStream(&bitD1) & BITv05_endOfDStream(&bitD2) & BITv05_endOfDStream(&bitD3) & BITv05_endOfDStream(&bitD4);
  1979. if (!endSignal) return ERROR(corruption_detected);
  1980. /* decoded size */
  1981. return dstSize;
  1982. }
  1983. size_t HUFv05_decompress4X2 (void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize)
  1984. {
  1985. HUFv05_CREATE_STATIC_DTABLEX2(DTable, HUFv05_MAX_TABLELOG);
  1986. const BYTE* ip = (const BYTE*) cSrc;
  1987. size_t errorCode;
  1988. errorCode = HUFv05_readDTableX2 (DTable, cSrc, cSrcSize);
  1989. if (HUFv05_isError(errorCode)) return errorCode;
  1990. if (errorCode >= cSrcSize) return ERROR(srcSize_wrong);
  1991. ip += errorCode;
  1992. cSrcSize -= errorCode;
  1993. return HUFv05_decompress4X2_usingDTable (dst, dstSize, ip, cSrcSize, DTable);
  1994. }
  1995. /* *************************/
  1996. /* double-symbols decoding */
  1997. /* *************************/
  1998. static void HUFv05_fillDTableX4Level2(HUFv05_DEltX4* DTable, U32 sizeLog, const U32 consumed,
  1999. const U32* rankValOrigin, const int minWeight,
  2000. const sortedSymbol_t* sortedSymbols, const U32 sortedListSize,
  2001. U32 nbBitsBaseline, U16 baseSeq)
  2002. {
  2003. HUFv05_DEltX4 DElt;
  2004. U32 rankVal[HUFv05_ABSOLUTEMAX_TABLELOG + 1];
  2005. U32 s;
  2006. /* get pre-calculated rankVal */
  2007. memcpy(rankVal, rankValOrigin, sizeof(rankVal));
  2008. /* fill skipped values */
  2009. if (minWeight>1) {
  2010. U32 i, skipSize = rankVal[minWeight];
  2011. MEM_writeLE16(&(DElt.sequence), baseSeq);
  2012. DElt.nbBits = (BYTE)(consumed);
  2013. DElt.length = 1;
  2014. for (i = 0; i < skipSize; i++)
  2015. DTable[i] = DElt;
  2016. }
  2017. /* fill DTable */
  2018. for (s=0; s<sortedListSize; s++) { /* note : sortedSymbols already skipped */
  2019. const U32 symbol = sortedSymbols[s].symbol;
  2020. const U32 weight = sortedSymbols[s].weight;
  2021. const U32 nbBits = nbBitsBaseline - weight;
  2022. const U32 length = 1 << (sizeLog-nbBits);
  2023. const U32 start = rankVal[weight];
  2024. U32 i = start;
  2025. const U32 end = start + length;
  2026. MEM_writeLE16(&(DElt.sequence), (U16)(baseSeq + (symbol << 8)));
  2027. DElt.nbBits = (BYTE)(nbBits + consumed);
  2028. DElt.length = 2;
  2029. do { DTable[i++] = DElt; } while (i<end); /* since length >= 1 */
  2030. rankVal[weight] += length;
  2031. }
  2032. }
  2033. typedef U32 rankVal_t[HUFv05_ABSOLUTEMAX_TABLELOG][HUFv05_ABSOLUTEMAX_TABLELOG + 1];
  2034. static void HUFv05_fillDTableX4(HUFv05_DEltX4* DTable, const U32 targetLog,
  2035. const sortedSymbol_t* sortedList, const U32 sortedListSize,
  2036. const U32* rankStart, rankVal_t rankValOrigin, const U32 maxWeight,
  2037. const U32 nbBitsBaseline)
  2038. {
  2039. U32 rankVal[HUFv05_ABSOLUTEMAX_TABLELOG + 1];
  2040. const int scaleLog = nbBitsBaseline - targetLog; /* note : targetLog >= srcLog, hence scaleLog <= 1 */
  2041. const U32 minBits = nbBitsBaseline - maxWeight;
  2042. U32 s;
  2043. memcpy(rankVal, rankValOrigin, sizeof(rankVal));
  2044. /* fill DTable */
  2045. for (s=0; s<sortedListSize; s++) {
  2046. const U16 symbol = sortedList[s].symbol;
  2047. const U32 weight = sortedList[s].weight;
  2048. const U32 nbBits = nbBitsBaseline - weight;
  2049. const U32 start = rankVal[weight];
  2050. const U32 length = 1 << (targetLog-nbBits);
  2051. if (targetLog-nbBits >= minBits) { /* enough room for a second symbol */
  2052. U32 sortedRank;
  2053. int minWeight = nbBits + scaleLog;
  2054. if (minWeight < 1) minWeight = 1;
  2055. sortedRank = rankStart[minWeight];
  2056. HUFv05_fillDTableX4Level2(DTable+start, targetLog-nbBits, nbBits,
  2057. rankValOrigin[nbBits], minWeight,
  2058. sortedList+sortedRank, sortedListSize-sortedRank,
  2059. nbBitsBaseline, symbol);
  2060. } else {
  2061. U32 i;
  2062. const U32 end = start + length;
  2063. HUFv05_DEltX4 DElt;
  2064. MEM_writeLE16(&(DElt.sequence), symbol);
  2065. DElt.nbBits = (BYTE)(nbBits);
  2066. DElt.length = 1;
  2067. for (i = start; i < end; i++)
  2068. DTable[i] = DElt;
  2069. }
  2070. rankVal[weight] += length;
  2071. }
  2072. }
  2073. size_t HUFv05_readDTableX4 (U32* DTable, const void* src, size_t srcSize)
  2074. {
  2075. BYTE weightList[HUFv05_MAX_SYMBOL_VALUE + 1];
  2076. sortedSymbol_t sortedSymbol[HUFv05_MAX_SYMBOL_VALUE + 1];
  2077. U32 rankStats[HUFv05_ABSOLUTEMAX_TABLELOG + 1] = { 0 };
  2078. U32 rankStart0[HUFv05_ABSOLUTEMAX_TABLELOG + 2] = { 0 };
  2079. U32* const rankStart = rankStart0+1;
  2080. rankVal_t rankVal;
  2081. U32 tableLog, maxW, sizeOfSort, nbSymbols;
  2082. const U32 memLog = DTable[0];
  2083. size_t iSize;
  2084. void* dtPtr = DTable;
  2085. HUFv05_DEltX4* const dt = ((HUFv05_DEltX4*)dtPtr) + 1;
  2086. HUFv05_STATIC_ASSERT(sizeof(HUFv05_DEltX4) == sizeof(U32)); /* if compilation fails here, assertion is false */
  2087. if (memLog > HUFv05_ABSOLUTEMAX_TABLELOG) return ERROR(tableLog_tooLarge);
  2088. //memset(weightList, 0, sizeof(weightList)); /* is not necessary, even though some analyzer complain ... */
  2089. iSize = HUFv05_readStats(weightList, HUFv05_MAX_SYMBOL_VALUE + 1, rankStats, &nbSymbols, &tableLog, src, srcSize);
  2090. if (HUFv05_isError(iSize)) return iSize;
  2091. /* check result */
  2092. if (tableLog > memLog) return ERROR(tableLog_tooLarge); /* DTable can't fit code depth */
  2093. /* find maxWeight */
  2094. for (maxW = tableLog; rankStats[maxW]==0; maxW--) {} /* necessarily finds a solution before 0 */
  2095. /* Get start index of each weight */
  2096. {
  2097. U32 w, nextRankStart = 0;
  2098. for (w=1; w<=maxW; w++) {
  2099. U32 current = nextRankStart;
  2100. nextRankStart += rankStats[w];
  2101. rankStart[w] = current;
  2102. }
  2103. rankStart[0] = nextRankStart; /* put all 0w symbols at the end of sorted list*/
  2104. sizeOfSort = nextRankStart;
  2105. }
  2106. /* sort symbols by weight */
  2107. {
  2108. U32 s;
  2109. for (s=0; s<nbSymbols; s++) {
  2110. U32 w = weightList[s];
  2111. U32 r = rankStart[w]++;
  2112. sortedSymbol[r].symbol = (BYTE)s;
  2113. sortedSymbol[r].weight = (BYTE)w;
  2114. }
  2115. rankStart[0] = 0; /* forget 0w symbols; this is beginning of weight(1) */
  2116. }
  2117. /* Build rankVal */
  2118. {
  2119. const U32 minBits = tableLog+1 - maxW;
  2120. U32 nextRankVal = 0;
  2121. U32 w, consumed;
  2122. const int rescale = (memLog-tableLog) - 1; /* tableLog <= memLog */
  2123. U32* rankVal0 = rankVal[0];
  2124. for (w=1; w<=maxW; w++) {
  2125. U32 current = nextRankVal;
  2126. nextRankVal += rankStats[w] << (w+rescale);
  2127. rankVal0[w] = current;
  2128. }
  2129. for (consumed = minBits; consumed <= memLog - minBits; consumed++) {
  2130. U32* rankValPtr = rankVal[consumed];
  2131. for (w = 1; w <= maxW; w++) {
  2132. rankValPtr[w] = rankVal0[w] >> consumed;
  2133. } } }
  2134. HUFv05_fillDTableX4(dt, memLog,
  2135. sortedSymbol, sizeOfSort,
  2136. rankStart0, rankVal, maxW,
  2137. tableLog+1);
  2138. return iSize;
  2139. }
  2140. static U32 HUFv05_decodeSymbolX4(void* op, BITv05_DStream_t* DStream, const HUFv05_DEltX4* dt, const U32 dtLog)
  2141. {
  2142. const size_t val = BITv05_lookBitsFast(DStream, dtLog); /* note : dtLog >= 1 */
  2143. memcpy(op, dt+val, 2);
  2144. BITv05_skipBits(DStream, dt[val].nbBits);
  2145. return dt[val].length;
  2146. }
  2147. static U32 HUFv05_decodeLastSymbolX4(void* op, BITv05_DStream_t* DStream, const HUFv05_DEltX4* dt, const U32 dtLog)
  2148. {
  2149. const size_t val = BITv05_lookBitsFast(DStream, dtLog); /* note : dtLog >= 1 */
  2150. memcpy(op, dt+val, 1);
  2151. if (dt[val].length==1) BITv05_skipBits(DStream, dt[val].nbBits);
  2152. else {
  2153. if (DStream->bitsConsumed < (sizeof(DStream->bitContainer)*8)) {
  2154. BITv05_skipBits(DStream, dt[val].nbBits);
  2155. if (DStream->bitsConsumed > (sizeof(DStream->bitContainer)*8))
  2156. 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 */
  2157. } }
  2158. return 1;
  2159. }
  2160. #define HUFv05_DECODE_SYMBOLX4_0(ptr, DStreamPtr) \
  2161. ptr += HUFv05_decodeSymbolX4(ptr, DStreamPtr, dt, dtLog)
  2162. #define HUFv05_DECODE_SYMBOLX4_1(ptr, DStreamPtr) \
  2163. if (MEM_64bits() || (HUFv05_MAX_TABLELOG<=12)) \
  2164. ptr += HUFv05_decodeSymbolX4(ptr, DStreamPtr, dt, dtLog)
  2165. #define HUFv05_DECODE_SYMBOLX4_2(ptr, DStreamPtr) \
  2166. if (MEM_64bits()) \
  2167. ptr += HUFv05_decodeSymbolX4(ptr, DStreamPtr, dt, dtLog)
  2168. static inline size_t HUFv05_decodeStreamX4(BYTE* p, BITv05_DStream_t* bitDPtr, BYTE* const pEnd, const HUFv05_DEltX4* const dt, const U32 dtLog)
  2169. {
  2170. BYTE* const pStart = p;
  2171. /* up to 8 symbols at a time */
  2172. while ((BITv05_reloadDStream(bitDPtr) == BITv05_DStream_unfinished) && (p < pEnd-7)) {
  2173. HUFv05_DECODE_SYMBOLX4_2(p, bitDPtr);
  2174. HUFv05_DECODE_SYMBOLX4_1(p, bitDPtr);
  2175. HUFv05_DECODE_SYMBOLX4_2(p, bitDPtr);
  2176. HUFv05_DECODE_SYMBOLX4_0(p, bitDPtr);
  2177. }
  2178. /* closer to the end */
  2179. while ((BITv05_reloadDStream(bitDPtr) == BITv05_DStream_unfinished) && (p <= pEnd-2))
  2180. HUFv05_DECODE_SYMBOLX4_0(p, bitDPtr);
  2181. while (p <= pEnd-2)
  2182. HUFv05_DECODE_SYMBOLX4_0(p, bitDPtr); /* no need to reload : reached the end of DStream */
  2183. if (p < pEnd)
  2184. p += HUFv05_decodeLastSymbolX4(p, bitDPtr, dt, dtLog);
  2185. return p-pStart;
  2186. }
  2187. size_t HUFv05_decompress1X4_usingDTable(
  2188. void* dst, size_t dstSize,
  2189. const void* cSrc, size_t cSrcSize,
  2190. const U32* DTable)
  2191. {
  2192. const BYTE* const istart = (const BYTE*) cSrc;
  2193. BYTE* const ostart = (BYTE*) dst;
  2194. BYTE* const oend = ostart + dstSize;
  2195. const U32 dtLog = DTable[0];
  2196. const void* const dtPtr = DTable;
  2197. const HUFv05_DEltX4* const dt = ((const HUFv05_DEltX4*)dtPtr) +1;
  2198. size_t errorCode;
  2199. /* Init */
  2200. BITv05_DStream_t bitD;
  2201. errorCode = BITv05_initDStream(&bitD, istart, cSrcSize);
  2202. if (HUFv05_isError(errorCode)) return errorCode;
  2203. /* finish bitStreams one by one */
  2204. HUFv05_decodeStreamX4(ostart, &bitD, oend, dt, dtLog);
  2205. /* check */
  2206. if (!BITv05_endOfDStream(&bitD)) return ERROR(corruption_detected);
  2207. /* decoded size */
  2208. return dstSize;
  2209. }
  2210. size_t HUFv05_decompress1X4 (void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize)
  2211. {
  2212. HUFv05_CREATE_STATIC_DTABLEX4(DTable, HUFv05_MAX_TABLELOG);
  2213. const BYTE* ip = (const BYTE*) cSrc;
  2214. size_t hSize = HUFv05_readDTableX4 (DTable, cSrc, cSrcSize);
  2215. if (HUFv05_isError(hSize)) return hSize;
  2216. if (hSize >= cSrcSize) return ERROR(srcSize_wrong);
  2217. ip += hSize;
  2218. cSrcSize -= hSize;
  2219. return HUFv05_decompress1X4_usingDTable (dst, dstSize, ip, cSrcSize, DTable);
  2220. }
  2221. size_t HUFv05_decompress4X4_usingDTable(
  2222. void* dst, size_t dstSize,
  2223. const void* cSrc, size_t cSrcSize,
  2224. const U32* DTable)
  2225. {
  2226. if (cSrcSize < 10) return ERROR(corruption_detected); /* strict minimum : jump table + 1 byte per stream */
  2227. {
  2228. const BYTE* const istart = (const BYTE*) cSrc;
  2229. BYTE* const ostart = (BYTE*) dst;
  2230. BYTE* const oend = ostart + dstSize;
  2231. const void* const dtPtr = DTable;
  2232. const HUFv05_DEltX4* const dt = ((const HUFv05_DEltX4*)dtPtr) +1;
  2233. const U32 dtLog = DTable[0];
  2234. size_t errorCode;
  2235. /* Init */
  2236. BITv05_DStream_t bitD1;
  2237. BITv05_DStream_t bitD2;
  2238. BITv05_DStream_t bitD3;
  2239. BITv05_DStream_t bitD4;
  2240. const size_t length1 = MEM_readLE16(istart);
  2241. const size_t length2 = MEM_readLE16(istart+2);
  2242. const size_t length3 = MEM_readLE16(istart+4);
  2243. size_t length4;
  2244. const BYTE* const istart1 = istart + 6; /* jumpTable */
  2245. const BYTE* const istart2 = istart1 + length1;
  2246. const BYTE* const istart3 = istart2 + length2;
  2247. const BYTE* const istart4 = istart3 + length3;
  2248. const size_t segmentSize = (dstSize+3) / 4;
  2249. BYTE* const opStart2 = ostart + segmentSize;
  2250. BYTE* const opStart3 = opStart2 + segmentSize;
  2251. BYTE* const opStart4 = opStart3 + segmentSize;
  2252. BYTE* op1 = ostart;
  2253. BYTE* op2 = opStart2;
  2254. BYTE* op3 = opStart3;
  2255. BYTE* op4 = opStart4;
  2256. U32 endSignal;
  2257. length4 = cSrcSize - (length1 + length2 + length3 + 6);
  2258. if (length4 > cSrcSize) return ERROR(corruption_detected); /* overflow */
  2259. errorCode = BITv05_initDStream(&bitD1, istart1, length1);
  2260. if (HUFv05_isError(errorCode)) return errorCode;
  2261. errorCode = BITv05_initDStream(&bitD2, istart2, length2);
  2262. if (HUFv05_isError(errorCode)) return errorCode;
  2263. errorCode = BITv05_initDStream(&bitD3, istart3, length3);
  2264. if (HUFv05_isError(errorCode)) return errorCode;
  2265. errorCode = BITv05_initDStream(&bitD4, istart4, length4);
  2266. if (HUFv05_isError(errorCode)) return errorCode;
  2267. /* 16-32 symbols per loop (4-8 symbols per stream) */
  2268. endSignal = BITv05_reloadDStream(&bitD1) | BITv05_reloadDStream(&bitD2) | BITv05_reloadDStream(&bitD3) | BITv05_reloadDStream(&bitD4);
  2269. for ( ; (endSignal==BITv05_DStream_unfinished) && (op4<(oend-7)) ; ) {
  2270. HUFv05_DECODE_SYMBOLX4_2(op1, &bitD1);
  2271. HUFv05_DECODE_SYMBOLX4_2(op2, &bitD2);
  2272. HUFv05_DECODE_SYMBOLX4_2(op3, &bitD3);
  2273. HUFv05_DECODE_SYMBOLX4_2(op4, &bitD4);
  2274. HUFv05_DECODE_SYMBOLX4_1(op1, &bitD1);
  2275. HUFv05_DECODE_SYMBOLX4_1(op2, &bitD2);
  2276. HUFv05_DECODE_SYMBOLX4_1(op3, &bitD3);
  2277. HUFv05_DECODE_SYMBOLX4_1(op4, &bitD4);
  2278. HUFv05_DECODE_SYMBOLX4_2(op1, &bitD1);
  2279. HUFv05_DECODE_SYMBOLX4_2(op2, &bitD2);
  2280. HUFv05_DECODE_SYMBOLX4_2(op3, &bitD3);
  2281. HUFv05_DECODE_SYMBOLX4_2(op4, &bitD4);
  2282. HUFv05_DECODE_SYMBOLX4_0(op1, &bitD1);
  2283. HUFv05_DECODE_SYMBOLX4_0(op2, &bitD2);
  2284. HUFv05_DECODE_SYMBOLX4_0(op3, &bitD3);
  2285. HUFv05_DECODE_SYMBOLX4_0(op4, &bitD4);
  2286. endSignal = BITv05_reloadDStream(&bitD1) | BITv05_reloadDStream(&bitD2) | BITv05_reloadDStream(&bitD3) | BITv05_reloadDStream(&bitD4);
  2287. }
  2288. /* check corruption */
  2289. if (op1 > opStart2) return ERROR(corruption_detected);
  2290. if (op2 > opStart3) return ERROR(corruption_detected);
  2291. if (op3 > opStart4) return ERROR(corruption_detected);
  2292. /* note : op4 supposed already verified within main loop */
  2293. /* finish bitStreams one by one */
  2294. HUFv05_decodeStreamX4(op1, &bitD1, opStart2, dt, dtLog);
  2295. HUFv05_decodeStreamX4(op2, &bitD2, opStart3, dt, dtLog);
  2296. HUFv05_decodeStreamX4(op3, &bitD3, opStart4, dt, dtLog);
  2297. HUFv05_decodeStreamX4(op4, &bitD4, oend, dt, dtLog);
  2298. /* check */
  2299. endSignal = BITv05_endOfDStream(&bitD1) & BITv05_endOfDStream(&bitD2) & BITv05_endOfDStream(&bitD3) & BITv05_endOfDStream(&bitD4);
  2300. if (!endSignal) return ERROR(corruption_detected);
  2301. /* decoded size */
  2302. return dstSize;
  2303. }
  2304. }
  2305. size_t HUFv05_decompress4X4 (void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize)
  2306. {
  2307. HUFv05_CREATE_STATIC_DTABLEX4(DTable, HUFv05_MAX_TABLELOG);
  2308. const BYTE* ip = (const BYTE*) cSrc;
  2309. size_t hSize = HUFv05_readDTableX4 (DTable, cSrc, cSrcSize);
  2310. if (HUFv05_isError(hSize)) return hSize;
  2311. if (hSize >= cSrcSize) return ERROR(srcSize_wrong);
  2312. ip += hSize;
  2313. cSrcSize -= hSize;
  2314. return HUFv05_decompress4X4_usingDTable (dst, dstSize, ip, cSrcSize, DTable);
  2315. }
  2316. /* ********************************/
  2317. /* Generic decompression selector */
  2318. /* ********************************/
  2319. typedef struct { U32 tableTime; U32 decode256Time; } algo_time_t;
  2320. static const algo_time_t algoTime[16 /* Quantization */][3 /* single, double, quad */] =
  2321. {
  2322. /* single, double, quad */
  2323. {{0,0}, {1,1}, {2,2}}, /* Q==0 : impossible */
  2324. {{0,0}, {1,1}, {2,2}}, /* Q==1 : impossible */
  2325. {{ 38,130}, {1313, 74}, {2151, 38}}, /* Q == 2 : 12-18% */
  2326. {{ 448,128}, {1353, 74}, {2238, 41}}, /* Q == 3 : 18-25% */
  2327. {{ 556,128}, {1353, 74}, {2238, 47}}, /* Q == 4 : 25-32% */
  2328. {{ 714,128}, {1418, 74}, {2436, 53}}, /* Q == 5 : 32-38% */
  2329. {{ 883,128}, {1437, 74}, {2464, 61}}, /* Q == 6 : 38-44% */
  2330. {{ 897,128}, {1515, 75}, {2622, 68}}, /* Q == 7 : 44-50% */
  2331. {{ 926,128}, {1613, 75}, {2730, 75}}, /* Q == 8 : 50-56% */
  2332. {{ 947,128}, {1729, 77}, {3359, 77}}, /* Q == 9 : 56-62% */
  2333. {{1107,128}, {2083, 81}, {4006, 84}}, /* Q ==10 : 62-69% */
  2334. {{1177,128}, {2379, 87}, {4785, 88}}, /* Q ==11 : 69-75% */
  2335. {{1242,128}, {2415, 93}, {5155, 84}}, /* Q ==12 : 75-81% */
  2336. {{1349,128}, {2644,106}, {5260,106}}, /* Q ==13 : 81-87% */
  2337. {{1455,128}, {2422,124}, {4174,124}}, /* Q ==14 : 87-93% */
  2338. {{ 722,128}, {1891,145}, {1936,146}}, /* Q ==15 : 93-99% */
  2339. };
  2340. typedef size_t (*decompressionAlgo)(void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize);
  2341. size_t HUFv05_decompress (void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize)
  2342. {
  2343. static const decompressionAlgo decompress[3] = { HUFv05_decompress4X2, HUFv05_decompress4X4, NULL };
  2344. /* estimate decompression time */
  2345. U32 Q;
  2346. const U32 D256 = (U32)(dstSize >> 8);
  2347. U32 Dtime[3];
  2348. U32 algoNb = 0;
  2349. int n;
  2350. /* validation checks */
  2351. if (dstSize == 0) return ERROR(dstSize_tooSmall);
  2352. if (cSrcSize >= dstSize) return ERROR(corruption_detected); /* invalid, or not compressed, but not compressed already dealt with */
  2353. if (cSrcSize == 1) { memset(dst, *(const BYTE*)cSrc, dstSize); return dstSize; } /* RLE */
  2354. /* decoder timing evaluation */
  2355. Q = (U32)(cSrcSize * 16 / dstSize); /* Q < 16 since dstSize > cSrcSize */
  2356. for (n=0; n<3; n++)
  2357. Dtime[n] = algoTime[Q][n].tableTime + (algoTime[Q][n].decode256Time * D256);
  2358. Dtime[1] += Dtime[1] >> 4; Dtime[2] += Dtime[2] >> 3; /* advantage to algorithms using less memory, for cache eviction */
  2359. if (Dtime[1] < Dtime[0]) algoNb = 1;
  2360. return decompress[algoNb](dst, dstSize, cSrc, cSrcSize);
  2361. //return HUFv05_decompress4X2(dst, dstSize, cSrc, cSrcSize); /* multi-streams single-symbol decoding */
  2362. //return HUFv05_decompress4X4(dst, dstSize, cSrc, cSrcSize); /* multi-streams double-symbols decoding */
  2363. //return HUFv05_decompress4X6(dst, dstSize, cSrc, cSrcSize); /* multi-streams quad-symbols decoding */
  2364. }
  2365. /*
  2366. zstd - standard compression library
  2367. Copyright (C) 2014-2016, Yann Collet.
  2368. BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
  2369. Redistribution and use in source and binary forms, with or without
  2370. modification, are permitted provided that the following conditions are
  2371. met:
  2372. * Redistributions of source code must retain the above copyright
  2373. notice, this list of conditions and the following disclaimer.
  2374. * Redistributions in binary form must reproduce the above
  2375. copyright notice, this list of conditions and the following disclaimer
  2376. in the documentation and/or other materials provided with the
  2377. distribution.
  2378. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  2379. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  2380. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  2381. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  2382. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  2383. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  2384. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  2385. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  2386. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  2387. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  2388. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  2389. You can contact the author at :
  2390. - zstd source repository : https://github.com/Cyan4973/zstd
  2391. */
  2392. /* ***************************************************************
  2393. * Tuning parameters
  2394. *****************************************************************/
  2395. /*!
  2396. * HEAPMODE :
  2397. * Select how default decompression function ZSTDv05_decompress() will allocate memory,
  2398. * in memory stack (0), or in memory heap (1, requires malloc())
  2399. */
  2400. #ifndef ZSTDv05_HEAPMODE
  2401. # define ZSTDv05_HEAPMODE 1
  2402. #endif
  2403. /*-*******************************************************
  2404. * Dependencies
  2405. *********************************************************/
  2406. #include <stdlib.h> /* calloc */
  2407. #include <string.h> /* memcpy, memmove */
  2408. #include <stdio.h> /* debug only : printf */
  2409. /*-*******************************************************
  2410. * Compiler specifics
  2411. *********************************************************/
  2412. #ifdef _MSC_VER /* Visual Studio */
  2413. # define FORCE_INLINE static __forceinline
  2414. # include <intrin.h> /* For Visual 2005 */
  2415. # pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */
  2416. # pragma warning(disable : 4324) /* disable: C4324: padded structure */
  2417. #else
  2418. # define GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__)
  2419. # ifdef __GNUC__
  2420. # define FORCE_INLINE static inline __attribute__((always_inline))
  2421. # else
  2422. # define FORCE_INLINE static inline
  2423. # endif
  2424. #endif
  2425. /*-*************************************
  2426. * Local types
  2427. ***************************************/
  2428. typedef struct
  2429. {
  2430. blockType_t blockType;
  2431. U32 origSize;
  2432. } blockProperties_t;
  2433. /* *******************************************************
  2434. * Memory operations
  2435. **********************************************************/
  2436. static void ZSTDv05_copy4(void* dst, const void* src) { memcpy(dst, src, 4); }
  2437. /* *************************************
  2438. * Error Management
  2439. ***************************************/
  2440. /*! ZSTDv05_isError() :
  2441. * tells if a return value is an error code */
  2442. unsigned ZSTDv05_isError(size_t code) { return ERR_isError(code); }
  2443. /*! ZSTDv05_getError() :
  2444. * convert a `size_t` function result into a proper ZSTDv05_errorCode enum */
  2445. ZSTDv05_ErrorCode ZSTDv05_getError(size_t code) { return ERR_getError(code); }
  2446. /*! ZSTDv05_getErrorName() :
  2447. * provides error code string (useful for debugging) */
  2448. const char* ZSTDv05_getErrorName(size_t code) { return ERR_getErrorName(code); }
  2449. /* *************************************************************
  2450. * Context management
  2451. ***************************************************************/
  2452. typedef enum { ZSTDv05ds_getFrameHeaderSize, ZSTDv05ds_decodeFrameHeader,
  2453. ZSTDv05ds_decodeBlockHeader, ZSTDv05ds_decompressBlock } ZSTDv05_dStage;
  2454. struct ZSTDv05_DCtx_s
  2455. {
  2456. FSEv05_DTable LLTable[FSEv05_DTABLE_SIZE_U32(LLFSEv05Log)];
  2457. FSEv05_DTable OffTable[FSEv05_DTABLE_SIZE_U32(OffFSEv05Log)];
  2458. FSEv05_DTable MLTable[FSEv05_DTABLE_SIZE_U32(MLFSEv05Log)];
  2459. unsigned hufTableX4[HUFv05_DTABLE_SIZE(HufLog)];
  2460. const void* previousDstEnd;
  2461. const void* base;
  2462. const void* vBase;
  2463. const void* dictEnd;
  2464. size_t expected;
  2465. size_t headerSize;
  2466. ZSTDv05_parameters params;
  2467. blockType_t bType; /* used in ZSTDv05_decompressContinue(), to transfer blockType between header decoding and block decoding stages */
  2468. ZSTDv05_dStage stage;
  2469. U32 flagStaticTables;
  2470. const BYTE* litPtr;
  2471. size_t litBufSize;
  2472. size_t litSize;
  2473. BYTE litBuffer[BLOCKSIZE + WILDCOPY_OVERLENGTH];
  2474. BYTE headerBuffer[ZSTDv05_frameHeaderSize_max];
  2475. }; /* typedef'd to ZSTDv05_DCtx within "zstd_static.h" */
  2476. size_t ZSTDv05_sizeofDCtx (void) { return sizeof(ZSTDv05_DCtx); }
  2477. size_t ZSTDv05_decompressBegin(ZSTDv05_DCtx* dctx)
  2478. {
  2479. dctx->expected = ZSTDv05_frameHeaderSize_min;
  2480. dctx->stage = ZSTDv05ds_getFrameHeaderSize;
  2481. dctx->previousDstEnd = NULL;
  2482. dctx->base = NULL;
  2483. dctx->vBase = NULL;
  2484. dctx->dictEnd = NULL;
  2485. dctx->hufTableX4[0] = HufLog;
  2486. dctx->flagStaticTables = 0;
  2487. return 0;
  2488. }
  2489. ZSTDv05_DCtx* ZSTDv05_createDCtx(void)
  2490. {
  2491. ZSTDv05_DCtx* dctx = (ZSTDv05_DCtx*)malloc(sizeof(ZSTDv05_DCtx));
  2492. if (dctx==NULL) return NULL;
  2493. ZSTDv05_decompressBegin(dctx);
  2494. return dctx;
  2495. }
  2496. size_t ZSTDv05_freeDCtx(ZSTDv05_DCtx* dctx)
  2497. {
  2498. free(dctx);
  2499. return 0; /* reserved as a potential error code in the future */
  2500. }
  2501. void ZSTDv05_copyDCtx(ZSTDv05_DCtx* dstDCtx, const ZSTDv05_DCtx* srcDCtx)
  2502. {
  2503. memcpy(dstDCtx, srcDCtx,
  2504. sizeof(ZSTDv05_DCtx) - (BLOCKSIZE+WILDCOPY_OVERLENGTH + ZSTDv05_frameHeaderSize_max)); /* no need to copy workspace */
  2505. }
  2506. /* *************************************************************
  2507. * Decompression section
  2508. ***************************************************************/
  2509. /* Frame format description
  2510. Frame Header - [ Block Header - Block ] - Frame End
  2511. 1) Frame Header
  2512. - 4 bytes - Magic Number : ZSTDv05_MAGICNUMBER (defined within zstd_internal.h)
  2513. - 1 byte - Window Descriptor
  2514. 2) Block Header
  2515. - 3 bytes, starting with a 2-bits descriptor
  2516. Uncompressed, Compressed, Frame End, unused
  2517. 3) Block
  2518. See Block Format Description
  2519. 4) Frame End
  2520. - 3 bytes, compatible with Block Header
  2521. */
  2522. /* Block format description
  2523. Block = Literal Section - Sequences Section
  2524. Prerequisite : size of (compressed) block, maximum size of regenerated data
  2525. 1) Literal Section
  2526. 1.1) Header : 1-5 bytes
  2527. flags: 2 bits
  2528. 00 compressed by Huff0
  2529. 01 unused
  2530. 10 is Raw (uncompressed)
  2531. 11 is Rle
  2532. Note : using 01 => Huff0 with precomputed table ?
  2533. Note : delta map ? => compressed ?
  2534. 1.1.1) Huff0-compressed literal block : 3-5 bytes
  2535. srcSize < 1 KB => 3 bytes (2-2-10-10) => single stream
  2536. srcSize < 1 KB => 3 bytes (2-2-10-10)
  2537. srcSize < 16KB => 4 bytes (2-2-14-14)
  2538. else => 5 bytes (2-2-18-18)
  2539. big endian convention
  2540. 1.1.2) Raw (uncompressed) literal block header : 1-3 bytes
  2541. size : 5 bits: (IS_RAW<<6) + (0<<4) + size
  2542. 12 bits: (IS_RAW<<6) + (2<<4) + (size>>8)
  2543. size&255
  2544. 20 bits: (IS_RAW<<6) + (3<<4) + (size>>16)
  2545. size>>8&255
  2546. size&255
  2547. 1.1.3) Rle (repeated single byte) literal block header : 1-3 bytes
  2548. size : 5 bits: (IS_RLE<<6) + (0<<4) + size
  2549. 12 bits: (IS_RLE<<6) + (2<<4) + (size>>8)
  2550. size&255
  2551. 20 bits: (IS_RLE<<6) + (3<<4) + (size>>16)
  2552. size>>8&255
  2553. size&255
  2554. 1.1.4) Huff0-compressed literal block, using precomputed CTables : 3-5 bytes
  2555. srcSize < 1 KB => 3 bytes (2-2-10-10) => single stream
  2556. srcSize < 1 KB => 3 bytes (2-2-10-10)
  2557. srcSize < 16KB => 4 bytes (2-2-14-14)
  2558. else => 5 bytes (2-2-18-18)
  2559. big endian convention
  2560. 1- CTable available (stored into workspace ?)
  2561. 2- Small input (fast heuristic ? Full comparison ? depend on clevel ?)
  2562. 1.2) Literal block content
  2563. 1.2.1) Huff0 block, using sizes from header
  2564. See Huff0 format
  2565. 1.2.2) Huff0 block, using prepared table
  2566. 1.2.3) Raw content
  2567. 1.2.4) single byte
  2568. 2) Sequences section
  2569. TO DO
  2570. */
  2571. /** ZSTDv05_decodeFrameHeader_Part1() :
  2572. * decode the 1st part of the Frame Header, which tells Frame Header size.
  2573. * srcSize must be == ZSTDv05_frameHeaderSize_min.
  2574. * @return : the full size of the Frame Header */
  2575. static size_t ZSTDv05_decodeFrameHeader_Part1(ZSTDv05_DCtx* zc, const void* src, size_t srcSize)
  2576. {
  2577. U32 magicNumber;
  2578. if (srcSize != ZSTDv05_frameHeaderSize_min)
  2579. return ERROR(srcSize_wrong);
  2580. magicNumber = MEM_readLE32(src);
  2581. if (magicNumber != ZSTDv05_MAGICNUMBER) return ERROR(prefix_unknown);
  2582. zc->headerSize = ZSTDv05_frameHeaderSize_min;
  2583. return zc->headerSize;
  2584. }
  2585. size_t ZSTDv05_getFrameParams(ZSTDv05_parameters* params, const void* src, size_t srcSize)
  2586. {
  2587. U32 magicNumber;
  2588. if (srcSize < ZSTDv05_frameHeaderSize_min) return ZSTDv05_frameHeaderSize_max;
  2589. magicNumber = MEM_readLE32(src);
  2590. if (magicNumber != ZSTDv05_MAGICNUMBER) return ERROR(prefix_unknown);
  2591. memset(params, 0, sizeof(*params));
  2592. params->windowLog = (((const BYTE*)src)[4] & 15) + ZSTDv05_WINDOWLOG_ABSOLUTEMIN;
  2593. if ((((const BYTE*)src)[4] >> 4) != 0) return ERROR(frameParameter_unsupported); /* reserved bits */
  2594. return 0;
  2595. }
  2596. /** ZSTDv05_decodeFrameHeader_Part2() :
  2597. * decode the full Frame Header.
  2598. * srcSize must be the size provided by ZSTDv05_decodeFrameHeader_Part1().
  2599. * @return : 0, or an error code, which can be tested using ZSTDv05_isError() */
  2600. static size_t ZSTDv05_decodeFrameHeader_Part2(ZSTDv05_DCtx* zc, const void* src, size_t srcSize)
  2601. {
  2602. size_t result;
  2603. if (srcSize != zc->headerSize)
  2604. return ERROR(srcSize_wrong);
  2605. result = ZSTDv05_getFrameParams(&(zc->params), src, srcSize);
  2606. if ((MEM_32bits()) && (zc->params.windowLog > 25)) return ERROR(frameParameter_unsupportedBy32bits);
  2607. return result;
  2608. }
  2609. size_t ZSTDv05_getcBlockSize(const void* src, size_t srcSize, blockProperties_t* bpPtr)
  2610. {
  2611. const BYTE* const in = (const BYTE* const)src;
  2612. BYTE headerFlags;
  2613. U32 cSize;
  2614. if (srcSize < 3)
  2615. return ERROR(srcSize_wrong);
  2616. headerFlags = *in;
  2617. cSize = in[2] + (in[1]<<8) + ((in[0] & 7)<<16);
  2618. bpPtr->blockType = (blockType_t)(headerFlags >> 6);
  2619. bpPtr->origSize = (bpPtr->blockType == bt_rle) ? cSize : 0;
  2620. if (bpPtr->blockType == bt_end) return 0;
  2621. if (bpPtr->blockType == bt_rle) return 1;
  2622. return cSize;
  2623. }
  2624. static size_t ZSTDv05_copyRawBlock(void* dst, size_t maxDstSize, const void* src, size_t srcSize)
  2625. {
  2626. if (srcSize > maxDstSize) return ERROR(dstSize_tooSmall);
  2627. memcpy(dst, src, srcSize);
  2628. return srcSize;
  2629. }
  2630. /*! ZSTDv05_decodeLiteralsBlock() :
  2631. @return : nb of bytes read from src (< srcSize ) */
  2632. size_t ZSTDv05_decodeLiteralsBlock(ZSTDv05_DCtx* dctx,
  2633. const void* src, size_t srcSize) /* note : srcSize < BLOCKSIZE */
  2634. {
  2635. const BYTE* const istart = (const BYTE*) src;
  2636. /* any compressed block with literals segment must be at least this size */
  2637. if (srcSize < MIN_CBLOCK_SIZE) return ERROR(corruption_detected);
  2638. switch(istart[0]>> 6)
  2639. {
  2640. case IS_HUFv05:
  2641. {
  2642. size_t litSize, litCSize, singleStream=0;
  2643. U32 lhSize = ((istart[0]) >> 4) & 3;
  2644. switch(lhSize)
  2645. {
  2646. case 0: case 1: default: /* note : default is impossible, since lhSize into [0..3] */
  2647. /* 2 - 2 - 10 - 10 */
  2648. lhSize=3;
  2649. singleStream = istart[0] & 16;
  2650. litSize = ((istart[0] & 15) << 6) + (istart[1] >> 2);
  2651. litCSize = ((istart[1] & 3) << 8) + istart[2];
  2652. break;
  2653. case 2:
  2654. /* 2 - 2 - 14 - 14 */
  2655. lhSize=4;
  2656. litSize = ((istart[0] & 15) << 10) + (istart[1] << 2) + (istart[2] >> 6);
  2657. litCSize = ((istart[2] & 63) << 8) + istart[3];
  2658. break;
  2659. case 3:
  2660. /* 2 - 2 - 18 - 18 */
  2661. lhSize=5;
  2662. litSize = ((istart[0] & 15) << 14) + (istart[1] << 6) + (istart[2] >> 2);
  2663. litCSize = ((istart[2] & 3) << 16) + (istart[3] << 8) + istart[4];
  2664. break;
  2665. }
  2666. if (litSize > BLOCKSIZE) return ERROR(corruption_detected);
  2667. if (HUFv05_isError(singleStream ?
  2668. HUFv05_decompress1X2(dctx->litBuffer, litSize, istart+lhSize, litCSize) :
  2669. HUFv05_decompress (dctx->litBuffer, litSize, istart+lhSize, litCSize) ))
  2670. return ERROR(corruption_detected);
  2671. dctx->litPtr = dctx->litBuffer;
  2672. dctx->litBufSize = BLOCKSIZE+8;
  2673. dctx->litSize = litSize;
  2674. return litCSize + lhSize;
  2675. }
  2676. case IS_PCH:
  2677. {
  2678. size_t errorCode;
  2679. size_t litSize, litCSize;
  2680. U32 lhSize = ((istart[0]) >> 4) & 3;
  2681. if (lhSize != 1) /* only case supported for now : small litSize, single stream */
  2682. return ERROR(corruption_detected);
  2683. if (!dctx->flagStaticTables)
  2684. return ERROR(dictionary_corrupted);
  2685. /* 2 - 2 - 10 - 10 */
  2686. lhSize=3;
  2687. litSize = ((istart[0] & 15) << 6) + (istart[1] >> 2);
  2688. litCSize = ((istart[1] & 3) << 8) + istart[2];
  2689. errorCode = HUFv05_decompress1X4_usingDTable(dctx->litBuffer, litSize, istart+lhSize, litCSize, dctx->hufTableX4);
  2690. if (HUFv05_isError(errorCode)) return ERROR(corruption_detected);
  2691. dctx->litPtr = dctx->litBuffer;
  2692. dctx->litBufSize = BLOCKSIZE+WILDCOPY_OVERLENGTH;
  2693. dctx->litSize = litSize;
  2694. return litCSize + lhSize;
  2695. }
  2696. case IS_RAW:
  2697. {
  2698. size_t litSize;
  2699. U32 lhSize = ((istart[0]) >> 4) & 3;
  2700. switch(lhSize)
  2701. {
  2702. case 0: case 1: default: /* note : default is impossible, since lhSize into [0..3] */
  2703. lhSize=1;
  2704. litSize = istart[0] & 31;
  2705. break;
  2706. case 2:
  2707. litSize = ((istart[0] & 15) << 8) + istart[1];
  2708. break;
  2709. case 3:
  2710. litSize = ((istart[0] & 15) << 16) + (istart[1] << 8) + istart[2];
  2711. break;
  2712. }
  2713. if (lhSize+litSize+WILDCOPY_OVERLENGTH > srcSize) { /* risk reading beyond src buffer with wildcopy */
  2714. if (litSize+lhSize > srcSize) return ERROR(corruption_detected);
  2715. memcpy(dctx->litBuffer, istart+lhSize, litSize);
  2716. dctx->litPtr = dctx->litBuffer;
  2717. dctx->litBufSize = BLOCKSIZE+8;
  2718. dctx->litSize = litSize;
  2719. return lhSize+litSize;
  2720. }
  2721. /* direct reference into compressed stream */
  2722. dctx->litPtr = istart+lhSize;
  2723. dctx->litBufSize = srcSize-lhSize;
  2724. dctx->litSize = litSize;
  2725. return lhSize+litSize;
  2726. }
  2727. case IS_RLE:
  2728. {
  2729. size_t litSize;
  2730. U32 lhSize = ((istart[0]) >> 4) & 3;
  2731. switch(lhSize)
  2732. {
  2733. case 0: case 1: default: /* note : default is impossible, since lhSize into [0..3] */
  2734. lhSize = 1;
  2735. litSize = istart[0] & 31;
  2736. break;
  2737. case 2:
  2738. litSize = ((istart[0] & 15) << 8) + istart[1];
  2739. break;
  2740. case 3:
  2741. litSize = ((istart[0] & 15) << 16) + (istart[1] << 8) + istart[2];
  2742. break;
  2743. }
  2744. if (litSize > BLOCKSIZE) return ERROR(corruption_detected);
  2745. memset(dctx->litBuffer, istart[lhSize], litSize);
  2746. dctx->litPtr = dctx->litBuffer;
  2747. dctx->litBufSize = BLOCKSIZE+WILDCOPY_OVERLENGTH;
  2748. dctx->litSize = litSize;
  2749. return lhSize+1;
  2750. }
  2751. default:
  2752. return ERROR(corruption_detected); /* impossible */
  2753. }
  2754. }
  2755. size_t ZSTDv05_decodeSeqHeaders(int* nbSeq, const BYTE** dumpsPtr, size_t* dumpsLengthPtr,
  2756. FSEv05_DTable* DTableLL, FSEv05_DTable* DTableML, FSEv05_DTable* DTableOffb,
  2757. const void* src, size_t srcSize)
  2758. {
  2759. const BYTE* const istart = (const BYTE* const)src;
  2760. const BYTE* ip = istart;
  2761. const BYTE* const iend = istart + srcSize;
  2762. U32 LLtype, Offtype, MLtype;
  2763. U32 LLlog, Offlog, MLlog;
  2764. size_t dumpsLength;
  2765. /* check */
  2766. if (srcSize < MIN_SEQUENCES_SIZE)
  2767. return ERROR(srcSize_wrong);
  2768. /* SeqHead */
  2769. *nbSeq = *ip++;
  2770. if (*nbSeq==0) return 1;
  2771. if (*nbSeq >= 128)
  2772. *nbSeq = ((nbSeq[0]-128)<<8) + *ip++;
  2773. LLtype = *ip >> 6;
  2774. Offtype = (*ip >> 4) & 3;
  2775. MLtype = (*ip >> 2) & 3;
  2776. if (*ip & 2) {
  2777. dumpsLength = ip[2];
  2778. dumpsLength += ip[1] << 8;
  2779. ip += 3;
  2780. } else {
  2781. dumpsLength = ip[1];
  2782. dumpsLength += (ip[0] & 1) << 8;
  2783. ip += 2;
  2784. }
  2785. *dumpsPtr = ip;
  2786. ip += dumpsLength;
  2787. *dumpsLengthPtr = dumpsLength;
  2788. /* check */
  2789. if (ip > iend-3) return ERROR(srcSize_wrong); /* min : all 3 are "raw", hence no header, but at least xxLog bits per type */
  2790. /* sequences */
  2791. {
  2792. S16 norm[MaxML+1]; /* assumption : MaxML >= MaxLL >= MaxOff */
  2793. size_t headerSize;
  2794. /* Build DTables */
  2795. switch(LLtype)
  2796. {
  2797. U32 max;
  2798. case FSEv05_ENCODING_RLE :
  2799. LLlog = 0;
  2800. FSEv05_buildDTable_rle(DTableLL, *ip++);
  2801. break;
  2802. case FSEv05_ENCODING_RAW :
  2803. LLlog = LLbits;
  2804. FSEv05_buildDTable_raw(DTableLL, LLbits);
  2805. break;
  2806. case FSEv05_ENCODING_STATIC:
  2807. break;
  2808. case FSEv05_ENCODING_DYNAMIC :
  2809. default : /* impossible */
  2810. max = MaxLL;
  2811. headerSize = FSEv05_readNCount(norm, &max, &LLlog, ip, iend-ip);
  2812. if (FSEv05_isError(headerSize)) return ERROR(GENERIC);
  2813. if (LLlog > LLFSEv05Log) return ERROR(corruption_detected);
  2814. ip += headerSize;
  2815. FSEv05_buildDTable(DTableLL, norm, max, LLlog);
  2816. }
  2817. switch(Offtype)
  2818. {
  2819. U32 max;
  2820. case FSEv05_ENCODING_RLE :
  2821. Offlog = 0;
  2822. if (ip > iend-2) return ERROR(srcSize_wrong); /* min : "raw", hence no header, but at least xxLog bits */
  2823. FSEv05_buildDTable_rle(DTableOffb, *ip++ & MaxOff); /* if *ip > MaxOff, data is corrupted */
  2824. break;
  2825. case FSEv05_ENCODING_RAW :
  2826. Offlog = Offbits;
  2827. FSEv05_buildDTable_raw(DTableOffb, Offbits);
  2828. break;
  2829. case FSEv05_ENCODING_STATIC:
  2830. break;
  2831. case FSEv05_ENCODING_DYNAMIC :
  2832. default : /* impossible */
  2833. max = MaxOff;
  2834. headerSize = FSEv05_readNCount(norm, &max, &Offlog, ip, iend-ip);
  2835. if (FSEv05_isError(headerSize)) return ERROR(GENERIC);
  2836. if (Offlog > OffFSEv05Log) return ERROR(corruption_detected);
  2837. ip += headerSize;
  2838. FSEv05_buildDTable(DTableOffb, norm, max, Offlog);
  2839. }
  2840. switch(MLtype)
  2841. {
  2842. U32 max;
  2843. case FSEv05_ENCODING_RLE :
  2844. MLlog = 0;
  2845. if (ip > iend-2) return ERROR(srcSize_wrong); /* min : "raw", hence no header, but at least xxLog bits */
  2846. FSEv05_buildDTable_rle(DTableML, *ip++);
  2847. break;
  2848. case FSEv05_ENCODING_RAW :
  2849. MLlog = MLbits;
  2850. FSEv05_buildDTable_raw(DTableML, MLbits);
  2851. break;
  2852. case FSEv05_ENCODING_STATIC:
  2853. break;
  2854. case FSEv05_ENCODING_DYNAMIC :
  2855. default : /* impossible */
  2856. max = MaxML;
  2857. headerSize = FSEv05_readNCount(norm, &max, &MLlog, ip, iend-ip);
  2858. if (FSEv05_isError(headerSize)) return ERROR(GENERIC);
  2859. if (MLlog > MLFSEv05Log) return ERROR(corruption_detected);
  2860. ip += headerSize;
  2861. FSEv05_buildDTable(DTableML, norm, max, MLlog);
  2862. } }
  2863. return ip-istart;
  2864. }
  2865. typedef struct {
  2866. size_t litLength;
  2867. size_t matchLength;
  2868. size_t offset;
  2869. } seq_t;
  2870. typedef struct {
  2871. BITv05_DStream_t DStream;
  2872. FSEv05_DState_t stateLL;
  2873. FSEv05_DState_t stateOffb;
  2874. FSEv05_DState_t stateML;
  2875. size_t prevOffset;
  2876. const BYTE* dumps;
  2877. const BYTE* dumpsEnd;
  2878. } seqState_t;
  2879. static void ZSTDv05_decodeSequence(seq_t* seq, seqState_t* seqState)
  2880. {
  2881. size_t litLength;
  2882. size_t prevOffset;
  2883. size_t offset;
  2884. size_t matchLength;
  2885. const BYTE* dumps = seqState->dumps;
  2886. const BYTE* const de = seqState->dumpsEnd;
  2887. /* Literal length */
  2888. litLength = FSEv05_peakSymbol(&(seqState->stateLL));
  2889. prevOffset = litLength ? seq->offset : seqState->prevOffset;
  2890. if (litLength == MaxLL) {
  2891. U32 add = *dumps++;
  2892. if (add < 255) litLength += add;
  2893. else {
  2894. litLength = MEM_readLE32(dumps) & 0xFFFFFF; /* no risk : dumps is always followed by seq tables > 1 byte */
  2895. if (litLength&1) litLength>>=1, dumps += 3;
  2896. else litLength = (U16)(litLength)>>1, dumps += 2;
  2897. }
  2898. if (dumps >= de) dumps = de-1; /* late correction, to avoid read overflow (data is now corrupted anyway) */
  2899. }
  2900. /* Offset */
  2901. {
  2902. static const U32 offsetPrefix[MaxOff+1] = {
  2903. 1 /*fake*/, 1, 2, 4, 8, 16, 32, 64, 128, 256,
  2904. 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072, 262144,
  2905. 524288, 1048576, 2097152, 4194304, 8388608, 16777216, 33554432, /*fake*/ 1, 1, 1, 1, 1 };
  2906. U32 offsetCode = FSEv05_peakSymbol(&(seqState->stateOffb)); /* <= maxOff, by table construction */
  2907. U32 nbBits = offsetCode - 1;
  2908. if (offsetCode==0) nbBits = 0; /* cmove */
  2909. offset = offsetPrefix[offsetCode] + BITv05_readBits(&(seqState->DStream), nbBits);
  2910. if (MEM_32bits()) BITv05_reloadDStream(&(seqState->DStream));
  2911. if (offsetCode==0) offset = prevOffset; /* repcode, cmove */
  2912. if (offsetCode | !litLength) seqState->prevOffset = seq->offset; /* cmove */
  2913. FSEv05_decodeSymbol(&(seqState->stateOffb), &(seqState->DStream)); /* update */
  2914. }
  2915. /* Literal length update */
  2916. FSEv05_decodeSymbol(&(seqState->stateLL), &(seqState->DStream)); /* update */
  2917. if (MEM_32bits()) BITv05_reloadDStream(&(seqState->DStream));
  2918. /* MatchLength */
  2919. matchLength = FSEv05_decodeSymbol(&(seqState->stateML), &(seqState->DStream));
  2920. if (matchLength == MaxML) {
  2921. U32 add = *dumps++;
  2922. if (add < 255) matchLength += add;
  2923. else {
  2924. matchLength = MEM_readLE32(dumps) & 0xFFFFFF; /* no pb : dumps is always followed by seq tables > 1 byte */
  2925. if (matchLength&1) matchLength>>=1, dumps += 3;
  2926. else matchLength = (U16)(matchLength)>>1, dumps += 2;
  2927. }
  2928. if (dumps >= de) dumps = de-1; /* late correction, to avoid read overflow (data is now corrupted anyway) */
  2929. }
  2930. matchLength += MINMATCH;
  2931. /* save result */
  2932. seq->litLength = litLength;
  2933. seq->offset = offset;
  2934. seq->matchLength = matchLength;
  2935. seqState->dumps = dumps;
  2936. #if 0 /* debug */
  2937. {
  2938. static U64 totalDecoded = 0;
  2939. printf("pos %6u : %3u literals & match %3u bytes at distance %6u \n",
  2940. (U32)(totalDecoded), (U32)litLength, (U32)matchLength, (U32)offset);
  2941. totalDecoded += litLength + matchLength;
  2942. }
  2943. #endif
  2944. }
  2945. static size_t ZSTDv05_execSequence(BYTE* op,
  2946. BYTE* const oend, seq_t sequence,
  2947. const BYTE** litPtr, const BYTE* const litLimit_8,
  2948. const BYTE* const base, const BYTE* const vBase, const BYTE* const dictEnd)
  2949. {
  2950. static const int dec32table[] = { 0, 1, 2, 1, 4, 4, 4, 4 }; /* added */
  2951. static const int dec64table[] = { 8, 8, 8, 7, 8, 9,10,11 }; /* substracted */
  2952. BYTE* const oLitEnd = op + sequence.litLength;
  2953. const size_t sequenceLength = sequence.litLength + sequence.matchLength;
  2954. BYTE* const oMatchEnd = op + sequenceLength; /* risk : address space overflow (32-bits) */
  2955. BYTE* const oend_8 = oend-8;
  2956. const BYTE* const litEnd = *litPtr + sequence.litLength;
  2957. const BYTE* match = oLitEnd - sequence.offset;
  2958. /* check */
  2959. if (oLitEnd > oend_8) return ERROR(dstSize_tooSmall); /* last match must start at a minimum distance of 8 from oend */
  2960. if (oMatchEnd > oend) return ERROR(dstSize_tooSmall); /* overwrite beyond dst buffer */
  2961. if (litEnd > litLimit_8) return ERROR(corruption_detected); /* risk read beyond lit buffer */
  2962. /* copy Literals */
  2963. ZSTDv05_wildcopy(op, *litPtr, sequence.litLength); /* note : oLitEnd <= oend-8 : no risk of overwrite beyond oend */
  2964. op = oLitEnd;
  2965. *litPtr = litEnd; /* update for next sequence */
  2966. /* copy Match */
  2967. if (sequence.offset > (size_t)(oLitEnd - base)) {
  2968. /* offset beyond prefix */
  2969. if (sequence.offset > (size_t)(oLitEnd - vBase))
  2970. return ERROR(corruption_detected);
  2971. match = dictEnd - (base-match);
  2972. if (match + sequence.matchLength <= dictEnd) {
  2973. memmove(oLitEnd, match, sequence.matchLength);
  2974. return sequenceLength;
  2975. }
  2976. /* span extDict & currentPrefixSegment */
  2977. {
  2978. size_t length1 = dictEnd - match;
  2979. memmove(oLitEnd, match, length1);
  2980. op = oLitEnd + length1;
  2981. sequence.matchLength -= length1;
  2982. match = base;
  2983. } }
  2984. /* match within prefix */
  2985. if (sequence.offset < 8) {
  2986. /* close range match, overlap */
  2987. const int sub2 = dec64table[sequence.offset];
  2988. op[0] = match[0];
  2989. op[1] = match[1];
  2990. op[2] = match[2];
  2991. op[3] = match[3];
  2992. match += dec32table[sequence.offset];
  2993. ZSTDv05_copy4(op+4, match);
  2994. match -= sub2;
  2995. } else {
  2996. ZSTDv05_copy8(op, match);
  2997. }
  2998. op += 8; match += 8;
  2999. if (oMatchEnd > oend-12) {
  3000. if (op < oend_8) {
  3001. ZSTDv05_wildcopy(op, match, oend_8 - op);
  3002. match += oend_8 - op;
  3003. op = oend_8;
  3004. }
  3005. while (op < oMatchEnd)
  3006. *op++ = *match++;
  3007. } else {
  3008. ZSTDv05_wildcopy(op, match, sequence.matchLength-8); /* works even if matchLength < 8 */
  3009. }
  3010. return sequenceLength;
  3011. }
  3012. static size_t ZSTDv05_decompressSequences(
  3013. ZSTDv05_DCtx* dctx,
  3014. void* dst, size_t maxDstSize,
  3015. const void* seqStart, size_t seqSize)
  3016. {
  3017. const BYTE* ip = (const BYTE*)seqStart;
  3018. const BYTE* const iend = ip + seqSize;
  3019. BYTE* const ostart = (BYTE* const)dst;
  3020. BYTE* op = ostart;
  3021. BYTE* const oend = ostart + maxDstSize;
  3022. size_t errorCode, dumpsLength;
  3023. const BYTE* litPtr = dctx->litPtr;
  3024. const BYTE* const litLimit_8 = litPtr + dctx->litBufSize - 8;
  3025. const BYTE* const litEnd = litPtr + dctx->litSize;
  3026. int nbSeq;
  3027. const BYTE* dumps;
  3028. U32* DTableLL = dctx->LLTable;
  3029. U32* DTableML = dctx->MLTable;
  3030. U32* DTableOffb = dctx->OffTable;
  3031. const BYTE* const base = (const BYTE*) (dctx->base);
  3032. const BYTE* const vBase = (const BYTE*) (dctx->vBase);
  3033. const BYTE* const dictEnd = (const BYTE*) (dctx->dictEnd);
  3034. /* Build Decoding Tables */
  3035. errorCode = ZSTDv05_decodeSeqHeaders(&nbSeq, &dumps, &dumpsLength,
  3036. DTableLL, DTableML, DTableOffb,
  3037. ip, seqSize);
  3038. if (ZSTDv05_isError(errorCode)) return errorCode;
  3039. ip += errorCode;
  3040. /* Regen sequences */
  3041. if (nbSeq) {
  3042. seq_t sequence;
  3043. seqState_t seqState;
  3044. memset(&sequence, 0, sizeof(sequence));
  3045. sequence.offset = REPCODE_STARTVALUE;
  3046. seqState.dumps = dumps;
  3047. seqState.dumpsEnd = dumps + dumpsLength;
  3048. seqState.prevOffset = REPCODE_STARTVALUE;
  3049. errorCode = BITv05_initDStream(&(seqState.DStream), ip, iend-ip);
  3050. if (ERR_isError(errorCode)) return ERROR(corruption_detected);
  3051. FSEv05_initDState(&(seqState.stateLL), &(seqState.DStream), DTableLL);
  3052. FSEv05_initDState(&(seqState.stateOffb), &(seqState.DStream), DTableOffb);
  3053. FSEv05_initDState(&(seqState.stateML), &(seqState.DStream), DTableML);
  3054. for ( ; (BITv05_reloadDStream(&(seqState.DStream)) <= BITv05_DStream_completed) && nbSeq ; ) {
  3055. size_t oneSeqSize;
  3056. nbSeq--;
  3057. ZSTDv05_decodeSequence(&sequence, &seqState);
  3058. oneSeqSize = ZSTDv05_execSequence(op, oend, sequence, &litPtr, litLimit_8, base, vBase, dictEnd);
  3059. if (ZSTDv05_isError(oneSeqSize)) return oneSeqSize;
  3060. op += oneSeqSize;
  3061. }
  3062. /* check if reached exact end */
  3063. if (nbSeq) return ERROR(corruption_detected);
  3064. }
  3065. /* last literal segment */
  3066. {
  3067. size_t lastLLSize = litEnd - litPtr;
  3068. if (litPtr > litEnd) return ERROR(corruption_detected); /* too many literals already used */
  3069. if (op+lastLLSize > oend) return ERROR(dstSize_tooSmall);
  3070. memcpy(op, litPtr, lastLLSize);
  3071. op += lastLLSize;
  3072. }
  3073. return op-ostart;
  3074. }
  3075. static void ZSTDv05_checkContinuity(ZSTDv05_DCtx* dctx, const void* dst)
  3076. {
  3077. if (dst != dctx->previousDstEnd) { /* not contiguous */
  3078. dctx->dictEnd = dctx->previousDstEnd;
  3079. dctx->vBase = (const char*)dst - ((const char*)(dctx->previousDstEnd) - (const char*)(dctx->base));
  3080. dctx->base = dst;
  3081. dctx->previousDstEnd = dst;
  3082. }
  3083. }
  3084. static size_t ZSTDv05_decompressBlock_internal(ZSTDv05_DCtx* dctx,
  3085. void* dst, size_t dstCapacity,
  3086. const void* src, size_t srcSize)
  3087. { /* blockType == blockCompressed */
  3088. const BYTE* ip = (const BYTE*)src;
  3089. size_t litCSize;
  3090. if (srcSize >= BLOCKSIZE) return ERROR(srcSize_wrong);
  3091. /* Decode literals sub-block */
  3092. litCSize = ZSTDv05_decodeLiteralsBlock(dctx, src, srcSize);
  3093. if (ZSTDv05_isError(litCSize)) return litCSize;
  3094. ip += litCSize;
  3095. srcSize -= litCSize;
  3096. return ZSTDv05_decompressSequences(dctx, dst, dstCapacity, ip, srcSize);
  3097. }
  3098. size_t ZSTDv05_decompressBlock(ZSTDv05_DCtx* dctx,
  3099. void* dst, size_t dstCapacity,
  3100. const void* src, size_t srcSize)
  3101. {
  3102. ZSTDv05_checkContinuity(dctx, dst);
  3103. return ZSTDv05_decompressBlock_internal(dctx, dst, dstCapacity, src, srcSize);
  3104. }
  3105. /*! ZSTDv05_decompress_continueDCtx
  3106. * dctx must have been properly initialized */
  3107. static size_t ZSTDv05_decompress_continueDCtx(ZSTDv05_DCtx* dctx,
  3108. void* dst, size_t maxDstSize,
  3109. const void* src, size_t srcSize)
  3110. {
  3111. const BYTE* ip = (const BYTE*)src;
  3112. const BYTE* iend = ip + srcSize;
  3113. BYTE* const ostart = (BYTE* const)dst;
  3114. BYTE* op = ostart;
  3115. BYTE* const oend = ostart + maxDstSize;
  3116. size_t remainingSize = srcSize;
  3117. blockProperties_t blockProperties;
  3118. /* Frame Header */
  3119. {
  3120. size_t frameHeaderSize;
  3121. if (srcSize < ZSTDv05_frameHeaderSize_min+ZSTDv05_blockHeaderSize) return ERROR(srcSize_wrong);
  3122. frameHeaderSize = ZSTDv05_decodeFrameHeader_Part1(dctx, src, ZSTDv05_frameHeaderSize_min);
  3123. if (ZSTDv05_isError(frameHeaderSize)) return frameHeaderSize;
  3124. if (srcSize < frameHeaderSize+ZSTDv05_blockHeaderSize) return ERROR(srcSize_wrong);
  3125. ip += frameHeaderSize; remainingSize -= frameHeaderSize;
  3126. frameHeaderSize = ZSTDv05_decodeFrameHeader_Part2(dctx, src, frameHeaderSize);
  3127. if (ZSTDv05_isError(frameHeaderSize)) return frameHeaderSize;
  3128. }
  3129. /* Loop on each block */
  3130. while (1)
  3131. {
  3132. size_t decodedSize=0;
  3133. size_t cBlockSize = ZSTDv05_getcBlockSize(ip, iend-ip, &blockProperties);
  3134. if (ZSTDv05_isError(cBlockSize)) return cBlockSize;
  3135. ip += ZSTDv05_blockHeaderSize;
  3136. remainingSize -= ZSTDv05_blockHeaderSize;
  3137. if (cBlockSize > remainingSize) return ERROR(srcSize_wrong);
  3138. switch(blockProperties.blockType)
  3139. {
  3140. case bt_compressed:
  3141. decodedSize = ZSTDv05_decompressBlock_internal(dctx, op, oend-op, ip, cBlockSize);
  3142. break;
  3143. case bt_raw :
  3144. decodedSize = ZSTDv05_copyRawBlock(op, oend-op, ip, cBlockSize);
  3145. break;
  3146. case bt_rle :
  3147. return ERROR(GENERIC); /* not yet supported */
  3148. break;
  3149. case bt_end :
  3150. /* end of frame */
  3151. if (remainingSize) return ERROR(srcSize_wrong);
  3152. break;
  3153. default:
  3154. return ERROR(GENERIC); /* impossible */
  3155. }
  3156. if (cBlockSize == 0) break; /* bt_end */
  3157. if (ZSTDv05_isError(decodedSize)) return decodedSize;
  3158. op += decodedSize;
  3159. ip += cBlockSize;
  3160. remainingSize -= cBlockSize;
  3161. }
  3162. return op-ostart;
  3163. }
  3164. size_t ZSTDv05_decompress_usingPreparedDCtx(ZSTDv05_DCtx* dctx, const ZSTDv05_DCtx* refDCtx,
  3165. void* dst, size_t maxDstSize,
  3166. const void* src, size_t srcSize)
  3167. {
  3168. ZSTDv05_copyDCtx(dctx, refDCtx);
  3169. ZSTDv05_checkContinuity(dctx, dst);
  3170. return ZSTDv05_decompress_continueDCtx(dctx, dst, maxDstSize, src, srcSize);
  3171. }
  3172. size_t ZSTDv05_decompress_usingDict(ZSTDv05_DCtx* dctx,
  3173. void* dst, size_t maxDstSize,
  3174. const void* src, size_t srcSize,
  3175. const void* dict, size_t dictSize)
  3176. {
  3177. ZSTDv05_decompressBegin_usingDict(dctx, dict, dictSize);
  3178. ZSTDv05_checkContinuity(dctx, dst);
  3179. return ZSTDv05_decompress_continueDCtx(dctx, dst, maxDstSize, src, srcSize);
  3180. }
  3181. size_t ZSTDv05_decompressDCtx(ZSTDv05_DCtx* dctx, void* dst, size_t maxDstSize, const void* src, size_t srcSize)
  3182. {
  3183. return ZSTDv05_decompress_usingDict(dctx, dst, maxDstSize, src, srcSize, NULL, 0);
  3184. }
  3185. size_t ZSTDv05_decompress(void* dst, size_t maxDstSize, const void* src, size_t srcSize)
  3186. {
  3187. #if defined(ZSTDv05_HEAPMODE) && (ZSTDv05_HEAPMODE==1)
  3188. size_t regenSize;
  3189. ZSTDv05_DCtx* dctx = ZSTDv05_createDCtx();
  3190. if (dctx==NULL) return ERROR(memory_allocation);
  3191. regenSize = ZSTDv05_decompressDCtx(dctx, dst, maxDstSize, src, srcSize);
  3192. ZSTDv05_freeDCtx(dctx);
  3193. return regenSize;
  3194. #else
  3195. ZSTDv05_DCtx dctx;
  3196. return ZSTDv05_decompressDCtx(&dctx, dst, maxDstSize, src, srcSize);
  3197. #endif
  3198. }
  3199. /* ******************************
  3200. * Streaming Decompression API
  3201. ********************************/
  3202. size_t ZSTDv05_nextSrcSizeToDecompress(ZSTDv05_DCtx* dctx)
  3203. {
  3204. return dctx->expected;
  3205. }
  3206. size_t ZSTDv05_decompressContinue(ZSTDv05_DCtx* dctx, void* dst, size_t maxDstSize, const void* src, size_t srcSize)
  3207. {
  3208. /* Sanity check */
  3209. if (srcSize != dctx->expected) return ERROR(srcSize_wrong);
  3210. ZSTDv05_checkContinuity(dctx, dst);
  3211. /* Decompress : frame header; part 1 */
  3212. switch (dctx->stage)
  3213. {
  3214. case ZSTDv05ds_getFrameHeaderSize :
  3215. /* get frame header size */
  3216. if (srcSize != ZSTDv05_frameHeaderSize_min) return ERROR(srcSize_wrong); /* impossible */
  3217. dctx->headerSize = ZSTDv05_decodeFrameHeader_Part1(dctx, src, ZSTDv05_frameHeaderSize_min);
  3218. if (ZSTDv05_isError(dctx->headerSize)) return dctx->headerSize;
  3219. memcpy(dctx->headerBuffer, src, ZSTDv05_frameHeaderSize_min);
  3220. if (dctx->headerSize > ZSTDv05_frameHeaderSize_min) return ERROR(GENERIC); /* should never happen */
  3221. dctx->expected = 0; /* not necessary to copy more */
  3222. /* fallthrough */
  3223. case ZSTDv05ds_decodeFrameHeader:
  3224. /* get frame header */
  3225. { size_t const result = ZSTDv05_decodeFrameHeader_Part2(dctx, dctx->headerBuffer, dctx->headerSize);
  3226. if (ZSTDv05_isError(result)) return result;
  3227. dctx->expected = ZSTDv05_blockHeaderSize;
  3228. dctx->stage = ZSTDv05ds_decodeBlockHeader;
  3229. return 0;
  3230. }
  3231. case ZSTDv05ds_decodeBlockHeader:
  3232. {
  3233. /* Decode block header */
  3234. blockProperties_t bp;
  3235. size_t blockSize = ZSTDv05_getcBlockSize(src, ZSTDv05_blockHeaderSize, &bp);
  3236. if (ZSTDv05_isError(blockSize)) return blockSize;
  3237. if (bp.blockType == bt_end) {
  3238. dctx->expected = 0;
  3239. dctx->stage = ZSTDv05ds_getFrameHeaderSize;
  3240. }
  3241. else {
  3242. dctx->expected = blockSize;
  3243. dctx->bType = bp.blockType;
  3244. dctx->stage = ZSTDv05ds_decompressBlock;
  3245. }
  3246. return 0;
  3247. }
  3248. case ZSTDv05ds_decompressBlock:
  3249. {
  3250. /* Decompress : block content */
  3251. size_t rSize;
  3252. switch(dctx->bType)
  3253. {
  3254. case bt_compressed:
  3255. rSize = ZSTDv05_decompressBlock_internal(dctx, dst, maxDstSize, src, srcSize);
  3256. break;
  3257. case bt_raw :
  3258. rSize = ZSTDv05_copyRawBlock(dst, maxDstSize, src, srcSize);
  3259. break;
  3260. case bt_rle :
  3261. return ERROR(GENERIC); /* not yet handled */
  3262. break;
  3263. case bt_end : /* should never happen (filtered at phase 1) */
  3264. rSize = 0;
  3265. break;
  3266. default:
  3267. return ERROR(GENERIC); /* impossible */
  3268. }
  3269. dctx->stage = ZSTDv05ds_decodeBlockHeader;
  3270. dctx->expected = ZSTDv05_blockHeaderSize;
  3271. dctx->previousDstEnd = (char*)dst + rSize;
  3272. return rSize;
  3273. }
  3274. default:
  3275. return ERROR(GENERIC); /* impossible */
  3276. }
  3277. }
  3278. static void ZSTDv05_refDictContent(ZSTDv05_DCtx* dctx, const void* dict, size_t dictSize)
  3279. {
  3280. dctx->dictEnd = dctx->previousDstEnd;
  3281. dctx->vBase = (const char*)dict - ((const char*)(dctx->previousDstEnd) - (const char*)(dctx->base));
  3282. dctx->base = dict;
  3283. dctx->previousDstEnd = (const char*)dict + dictSize;
  3284. }
  3285. static size_t ZSTDv05_loadEntropy(ZSTDv05_DCtx* dctx, const void* dict, size_t dictSize)
  3286. {
  3287. size_t hSize, offcodeHeaderSize, matchlengthHeaderSize, errorCode, litlengthHeaderSize;
  3288. short offcodeNCount[MaxOff+1];
  3289. U32 offcodeMaxValue=MaxOff, offcodeLog=OffFSEv05Log;
  3290. short matchlengthNCount[MaxML+1];
  3291. unsigned matchlengthMaxValue = MaxML, matchlengthLog = MLFSEv05Log;
  3292. short litlengthNCount[MaxLL+1];
  3293. unsigned litlengthMaxValue = MaxLL, litlengthLog = LLFSEv05Log;
  3294. hSize = HUFv05_readDTableX4(dctx->hufTableX4, dict, dictSize);
  3295. if (HUFv05_isError(hSize)) return ERROR(dictionary_corrupted);
  3296. dict = (const char*)dict + hSize;
  3297. dictSize -= hSize;
  3298. offcodeHeaderSize = FSEv05_readNCount(offcodeNCount, &offcodeMaxValue, &offcodeLog, dict, dictSize);
  3299. if (FSEv05_isError(offcodeHeaderSize)) return ERROR(dictionary_corrupted);
  3300. errorCode = FSEv05_buildDTable(dctx->OffTable, offcodeNCount, offcodeMaxValue, offcodeLog);
  3301. if (FSEv05_isError(errorCode)) return ERROR(dictionary_corrupted);
  3302. dict = (const char*)dict + offcodeHeaderSize;
  3303. dictSize -= offcodeHeaderSize;
  3304. matchlengthHeaderSize = FSEv05_readNCount(matchlengthNCount, &matchlengthMaxValue, &matchlengthLog, dict, dictSize);
  3305. if (FSEv05_isError(matchlengthHeaderSize)) return ERROR(dictionary_corrupted);
  3306. errorCode = FSEv05_buildDTable(dctx->MLTable, matchlengthNCount, matchlengthMaxValue, matchlengthLog);
  3307. if (FSEv05_isError(errorCode)) return ERROR(dictionary_corrupted);
  3308. dict = (const char*)dict + matchlengthHeaderSize;
  3309. dictSize -= matchlengthHeaderSize;
  3310. litlengthHeaderSize = FSEv05_readNCount(litlengthNCount, &litlengthMaxValue, &litlengthLog, dict, dictSize);
  3311. if (FSEv05_isError(litlengthHeaderSize)) return ERROR(dictionary_corrupted);
  3312. errorCode = FSEv05_buildDTable(dctx->LLTable, litlengthNCount, litlengthMaxValue, litlengthLog);
  3313. if (FSEv05_isError(errorCode)) return ERROR(dictionary_corrupted);
  3314. dctx->flagStaticTables = 1;
  3315. return hSize + offcodeHeaderSize + matchlengthHeaderSize + litlengthHeaderSize;
  3316. }
  3317. static size_t ZSTDv05_decompress_insertDictionary(ZSTDv05_DCtx* dctx, const void* dict, size_t dictSize)
  3318. {
  3319. size_t eSize;
  3320. U32 magic = MEM_readLE32(dict);
  3321. if (magic != ZSTDv05_DICT_MAGIC) {
  3322. /* pure content mode */
  3323. ZSTDv05_refDictContent(dctx, dict, dictSize);
  3324. return 0;
  3325. }
  3326. /* load entropy tables */
  3327. dict = (const char*)dict + 4;
  3328. dictSize -= 4;
  3329. eSize = ZSTDv05_loadEntropy(dctx, dict, dictSize);
  3330. if (ZSTDv05_isError(eSize)) return ERROR(dictionary_corrupted);
  3331. /* reference dictionary content */
  3332. dict = (const char*)dict + eSize;
  3333. dictSize -= eSize;
  3334. ZSTDv05_refDictContent(dctx, dict, dictSize);
  3335. return 0;
  3336. }
  3337. size_t ZSTDv05_decompressBegin_usingDict(ZSTDv05_DCtx* dctx, const void* dict, size_t dictSize)
  3338. {
  3339. size_t errorCode;
  3340. errorCode = ZSTDv05_decompressBegin(dctx);
  3341. if (ZSTDv05_isError(errorCode)) return errorCode;
  3342. if (dict && dictSize) {
  3343. errorCode = ZSTDv05_decompress_insertDictionary(dctx, dict, dictSize);
  3344. if (ZSTDv05_isError(errorCode)) return ERROR(dictionary_corrupted);
  3345. }
  3346. return 0;
  3347. }
  3348. /*
  3349. Buffered version of Zstd compression library
  3350. Copyright (C) 2015-2016, Yann Collet.
  3351. BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
  3352. Redistribution and use in source and binary forms, with or without
  3353. modification, are permitted provided that the following conditions are
  3354. met:
  3355. * Redistributions of source code must retain the above copyright
  3356. notice, this list of conditions and the following disclaimer.
  3357. * Redistributions in binary form must reproduce the above
  3358. copyright notice, this list of conditions and the following disclaimer
  3359. in the documentation and/or other materials provided with the
  3360. distribution.
  3361. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  3362. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  3363. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  3364. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  3365. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  3366. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  3367. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  3368. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  3369. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  3370. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  3371. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  3372. You can contact the author at :
  3373. - zstd source repository : https://github.com/Cyan4973/zstd
  3374. - ztsd public forum : https://groups.google.com/forum/#!forum/lz4c
  3375. */
  3376. /* The objects defined into this file should be considered experimental.
  3377. * They are not labelled stable, as their prototype may change in the future.
  3378. * You can use them for tests, provide feedback, or if you can endure risk of future changes.
  3379. */
  3380. /* *************************************
  3381. * Constants
  3382. ***************************************/
  3383. static size_t ZBUFFv05_blockHeaderSize = 3;
  3384. /* *** Compression *** */
  3385. static size_t ZBUFFv05_limitCopy(void* dst, size_t maxDstSize, const void* src, size_t srcSize)
  3386. {
  3387. size_t length = MIN(maxDstSize, srcSize);
  3388. memcpy(dst, src, length);
  3389. return length;
  3390. }
  3391. /** ************************************************
  3392. * Streaming decompression
  3393. *
  3394. * A ZBUFFv05_DCtx object is required to track streaming operation.
  3395. * Use ZBUFFv05_createDCtx() and ZBUFFv05_freeDCtx() to create/release resources.
  3396. * Use ZBUFFv05_decompressInit() to start a new decompression operation.
  3397. * ZBUFFv05_DCtx objects can be reused multiple times.
  3398. *
  3399. * Use ZBUFFv05_decompressContinue() repetitively to consume your input.
  3400. * *srcSizePtr and *maxDstSizePtr can be any size.
  3401. * The function will report how many bytes were read or written by modifying *srcSizePtr and *maxDstSizePtr.
  3402. * 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.
  3403. * The content of dst will be overwritten (up to *maxDstSizePtr) at each function call, so save its content if it matters or change dst .
  3404. * @return : a hint to preferred nb of bytes to use as input for next function call (it's only a hint, to improve latency)
  3405. * or 0 when a frame is completely decoded
  3406. * or an error code, which can be tested using ZBUFFv05_isError().
  3407. *
  3408. * Hint : recommended buffer sizes (not compulsory)
  3409. * output : 128 KB block size is the internal unit, it ensures it's always possible to write a full block when it's decoded.
  3410. * input : just follow indications from ZBUFFv05_decompressContinue() to minimize latency. It should always be <= 128 KB + 3 .
  3411. * **************************************************/
  3412. typedef enum { ZBUFFv05ds_init, ZBUFFv05ds_readHeader, ZBUFFv05ds_loadHeader, ZBUFFv05ds_decodeHeader,
  3413. ZBUFFv05ds_read, ZBUFFv05ds_load, ZBUFFv05ds_flush } ZBUFFv05_dStage;
  3414. /* *** Resource management *** */
  3415. #define ZSTDv05_frameHeaderSize_max 5 /* too magical, should come from reference */
  3416. struct ZBUFFv05_DCtx_s {
  3417. ZSTDv05_DCtx* zc;
  3418. ZSTDv05_parameters params;
  3419. char* inBuff;
  3420. size_t inBuffSize;
  3421. size_t inPos;
  3422. char* outBuff;
  3423. size_t outBuffSize;
  3424. size_t outStart;
  3425. size_t outEnd;
  3426. size_t hPos;
  3427. ZBUFFv05_dStage stage;
  3428. unsigned char headerBuffer[ZSTDv05_frameHeaderSize_max];
  3429. }; /* typedef'd to ZBUFFv05_DCtx within "zstd_buffered.h" */
  3430. ZBUFFv05_DCtx* ZBUFFv05_createDCtx(void)
  3431. {
  3432. ZBUFFv05_DCtx* zbc = (ZBUFFv05_DCtx*)malloc(sizeof(ZBUFFv05_DCtx));
  3433. if (zbc==NULL) return NULL;
  3434. memset(zbc, 0, sizeof(*zbc));
  3435. zbc->zc = ZSTDv05_createDCtx();
  3436. zbc->stage = ZBUFFv05ds_init;
  3437. return zbc;
  3438. }
  3439. size_t ZBUFFv05_freeDCtx(ZBUFFv05_DCtx* zbc)
  3440. {
  3441. if (zbc==NULL) return 0; /* support free on null */
  3442. ZSTDv05_freeDCtx(zbc->zc);
  3443. free(zbc->inBuff);
  3444. free(zbc->outBuff);
  3445. free(zbc);
  3446. return 0;
  3447. }
  3448. /* *** Initialization *** */
  3449. size_t ZBUFFv05_decompressInitDictionary(ZBUFFv05_DCtx* zbc, const void* dict, size_t dictSize)
  3450. {
  3451. zbc->stage = ZBUFFv05ds_readHeader;
  3452. zbc->hPos = zbc->inPos = zbc->outStart = zbc->outEnd = 0;
  3453. return ZSTDv05_decompressBegin_usingDict(zbc->zc, dict, dictSize);
  3454. }
  3455. size_t ZBUFFv05_decompressInit(ZBUFFv05_DCtx* zbc)
  3456. {
  3457. return ZBUFFv05_decompressInitDictionary(zbc, NULL, 0);
  3458. }
  3459. /* *** Decompression *** */
  3460. size_t ZBUFFv05_decompressContinue(ZBUFFv05_DCtx* zbc, void* dst, size_t* maxDstSizePtr, const void* src, size_t* srcSizePtr)
  3461. {
  3462. const char* const istart = (const char*)src;
  3463. const char* ip = istart;
  3464. const char* const iend = istart + *srcSizePtr;
  3465. char* const ostart = (char*)dst;
  3466. char* op = ostart;
  3467. char* const oend = ostart + *maxDstSizePtr;
  3468. U32 notDone = 1;
  3469. while (notDone) {
  3470. switch(zbc->stage)
  3471. {
  3472. case ZBUFFv05ds_init :
  3473. return ERROR(init_missing);
  3474. case ZBUFFv05ds_readHeader :
  3475. /* read header from src */
  3476. {
  3477. size_t headerSize = ZSTDv05_getFrameParams(&(zbc->params), src, *srcSizePtr);
  3478. if (ZSTDv05_isError(headerSize)) return headerSize;
  3479. if (headerSize) {
  3480. /* not enough input to decode header : tell how many bytes would be necessary */
  3481. memcpy(zbc->headerBuffer+zbc->hPos, src, *srcSizePtr);
  3482. zbc->hPos += *srcSizePtr;
  3483. *maxDstSizePtr = 0;
  3484. zbc->stage = ZBUFFv05ds_loadHeader;
  3485. return headerSize - zbc->hPos;
  3486. }
  3487. zbc->stage = ZBUFFv05ds_decodeHeader;
  3488. break;
  3489. }
  3490. case ZBUFFv05ds_loadHeader:
  3491. /* complete header from src */
  3492. {
  3493. size_t headerSize = ZBUFFv05_limitCopy(
  3494. zbc->headerBuffer + zbc->hPos, ZSTDv05_frameHeaderSize_max - zbc->hPos,
  3495. src, *srcSizePtr);
  3496. zbc->hPos += headerSize;
  3497. ip += headerSize;
  3498. headerSize = ZSTDv05_getFrameParams(&(zbc->params), zbc->headerBuffer, zbc->hPos);
  3499. if (ZSTDv05_isError(headerSize)) return headerSize;
  3500. if (headerSize) {
  3501. /* not enough input to decode header : tell how many bytes would be necessary */
  3502. *maxDstSizePtr = 0;
  3503. return headerSize - zbc->hPos;
  3504. }
  3505. // zbc->stage = ZBUFFv05ds_decodeHeader; break; /* useless : stage follows */
  3506. }
  3507. case ZBUFFv05ds_decodeHeader:
  3508. /* apply header to create / resize buffers */
  3509. {
  3510. size_t neededOutSize = (size_t)1 << zbc->params.windowLog;
  3511. size_t neededInSize = BLOCKSIZE; /* a block is never > BLOCKSIZE */
  3512. if (zbc->inBuffSize < neededInSize) {
  3513. free(zbc->inBuff);
  3514. zbc->inBuffSize = neededInSize;
  3515. zbc->inBuff = (char*)malloc(neededInSize);
  3516. if (zbc->inBuff == NULL) return ERROR(memory_allocation);
  3517. }
  3518. if (zbc->outBuffSize < neededOutSize) {
  3519. free(zbc->outBuff);
  3520. zbc->outBuffSize = neededOutSize;
  3521. zbc->outBuff = (char*)malloc(neededOutSize);
  3522. if (zbc->outBuff == NULL) return ERROR(memory_allocation);
  3523. } }
  3524. if (zbc->hPos) {
  3525. /* some data already loaded into headerBuffer : transfer into inBuff */
  3526. memcpy(zbc->inBuff, zbc->headerBuffer, zbc->hPos);
  3527. zbc->inPos = zbc->hPos;
  3528. zbc->hPos = 0;
  3529. zbc->stage = ZBUFFv05ds_load;
  3530. break;
  3531. }
  3532. zbc->stage = ZBUFFv05ds_read;
  3533. case ZBUFFv05ds_read:
  3534. {
  3535. size_t neededInSize = ZSTDv05_nextSrcSizeToDecompress(zbc->zc);
  3536. if (neededInSize==0) { /* end of frame */
  3537. zbc->stage = ZBUFFv05ds_init;
  3538. notDone = 0;
  3539. break;
  3540. }
  3541. if ((size_t)(iend-ip) >= neededInSize) {
  3542. /* directly decode from src */
  3543. size_t decodedSize = ZSTDv05_decompressContinue(zbc->zc,
  3544. zbc->outBuff + zbc->outStart, zbc->outBuffSize - zbc->outStart,
  3545. ip, neededInSize);
  3546. if (ZSTDv05_isError(decodedSize)) return decodedSize;
  3547. ip += neededInSize;
  3548. if (!decodedSize) break; /* this was just a header */
  3549. zbc->outEnd = zbc->outStart + decodedSize;
  3550. zbc->stage = ZBUFFv05ds_flush;
  3551. break;
  3552. }
  3553. if (ip==iend) { notDone = 0; break; } /* no more input */
  3554. zbc->stage = ZBUFFv05ds_load;
  3555. }
  3556. case ZBUFFv05ds_load:
  3557. {
  3558. size_t neededInSize = ZSTDv05_nextSrcSizeToDecompress(zbc->zc);
  3559. size_t toLoad = neededInSize - zbc->inPos; /* should always be <= remaining space within inBuff */
  3560. size_t loadedSize;
  3561. if (toLoad > zbc->inBuffSize - zbc->inPos) return ERROR(corruption_detected); /* should never happen */
  3562. loadedSize = ZBUFFv05_limitCopy(zbc->inBuff + zbc->inPos, toLoad, ip, iend-ip);
  3563. ip += loadedSize;
  3564. zbc->inPos += loadedSize;
  3565. if (loadedSize < toLoad) { notDone = 0; break; } /* not enough input, wait for more */
  3566. {
  3567. size_t decodedSize = ZSTDv05_decompressContinue(zbc->zc,
  3568. zbc->outBuff + zbc->outStart, zbc->outBuffSize - zbc->outStart,
  3569. zbc->inBuff, neededInSize);
  3570. if (ZSTDv05_isError(decodedSize)) return decodedSize;
  3571. zbc->inPos = 0; /* input is consumed */
  3572. if (!decodedSize) { zbc->stage = ZBUFFv05ds_read; break; } /* this was just a header */
  3573. zbc->outEnd = zbc->outStart + decodedSize;
  3574. zbc->stage = ZBUFFv05ds_flush;
  3575. // break; /* ZBUFFv05ds_flush follows */
  3576. } }
  3577. case ZBUFFv05ds_flush:
  3578. {
  3579. size_t toFlushSize = zbc->outEnd - zbc->outStart;
  3580. size_t flushedSize = ZBUFFv05_limitCopy(op, oend-op, zbc->outBuff + zbc->outStart, toFlushSize);
  3581. op += flushedSize;
  3582. zbc->outStart += flushedSize;
  3583. if (flushedSize == toFlushSize) {
  3584. zbc->stage = ZBUFFv05ds_read;
  3585. if (zbc->outStart + BLOCKSIZE > zbc->outBuffSize)
  3586. zbc->outStart = zbc->outEnd = 0;
  3587. break;
  3588. }
  3589. /* cannot flush everything */
  3590. notDone = 0;
  3591. break;
  3592. }
  3593. default: return ERROR(GENERIC); /* impossible */
  3594. } }
  3595. *srcSizePtr = ip-istart;
  3596. *maxDstSizePtr = op-ostart;
  3597. { size_t nextSrcSizeHint = ZSTDv05_nextSrcSizeToDecompress(zbc->zc);
  3598. if (nextSrcSizeHint > ZBUFFv05_blockHeaderSize) nextSrcSizeHint+= ZBUFFv05_blockHeaderSize; /* get next block header too */
  3599. nextSrcSizeHint -= zbc->inPos; /* already loaded*/
  3600. return nextSrcSizeHint;
  3601. }
  3602. }
  3603. /* *************************************
  3604. * Tool functions
  3605. ***************************************/
  3606. unsigned ZBUFFv05_isError(size_t errorCode) { return ERR_isError(errorCode); }
  3607. const char* ZBUFFv05_getErrorName(size_t errorCode) { return ERR_getErrorName(errorCode); }
  3608. size_t ZBUFFv05_recommendedDInSize(void) { return BLOCKSIZE + ZBUFFv05_blockHeaderSize /* block header size*/ ; }
  3609. size_t ZBUFFv05_recommendedDOutSize(void) { return BLOCKSIZE; }