zstd_v05.c 151 KB

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