zstd_v07.c 178 KB

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