zstd_v06.c 160 KB

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