zstd_v06.c 162 KB

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