zstd_v06.c 160 KB

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