zstd_compress.c 278 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393
  1. /*
  2. * Copyright (c) Yann Collet, Facebook, Inc.
  3. * All rights reserved.
  4. *
  5. * This source code is licensed under both the BSD-style license (found in the
  6. * LICENSE file in the root directory of this source tree) and the GPLv2 (found
  7. * in the COPYING file in the root directory of this source tree).
  8. * You may select, at your option, one of the above-listed licenses.
  9. */
  10. /*-*************************************
  11. * Dependencies
  12. ***************************************/
  13. #include "../common/zstd_deps.h" /* INT_MAX, ZSTD_memset, ZSTD_memcpy */
  14. #include "../common/cpu.h"
  15. #include "../common/mem.h"
  16. #include "hist.h" /* HIST_countFast_wksp */
  17. #define FSE_STATIC_LINKING_ONLY /* FSE_encodeSymbol */
  18. #include "../common/fse.h"
  19. #define HUF_STATIC_LINKING_ONLY
  20. #include "../common/huf.h"
  21. #include "zstd_compress_internal.h"
  22. #include "zstd_compress_sequences.h"
  23. #include "zstd_compress_literals.h"
  24. #include "zstd_fast.h"
  25. #include "zstd_double_fast.h"
  26. #include "zstd_lazy.h"
  27. #include "zstd_opt.h"
  28. #include "zstd_ldm.h"
  29. #include "zstd_compress_superblock.h"
  30. /* ***************************************************************
  31. * Tuning parameters
  32. *****************************************************************/
  33. /*!
  34. * COMPRESS_HEAPMODE :
  35. * Select how default decompression function ZSTD_compress() allocates its context,
  36. * on stack (0, default), or into heap (1).
  37. * Note that functions with explicit context such as ZSTD_compressCCtx() are unaffected.
  38. */
  39. #ifndef ZSTD_COMPRESS_HEAPMODE
  40. # define ZSTD_COMPRESS_HEAPMODE 0
  41. #endif
  42. /*-*************************************
  43. * Helper functions
  44. ***************************************/
  45. /* ZSTD_compressBound()
  46. * Note that the result from this function is only compatible with the "normal"
  47. * full-block strategy.
  48. * When there are a lot of small blocks due to frequent flush in streaming mode
  49. * the overhead of headers can make the compressed data to be larger than the
  50. * return value of ZSTD_compressBound().
  51. */
  52. size_t ZSTD_compressBound(size_t srcSize) {
  53. return ZSTD_COMPRESSBOUND(srcSize);
  54. }
  55. /*-*************************************
  56. * Context memory management
  57. ***************************************/
  58. struct ZSTD_CDict_s {
  59. const void* dictContent;
  60. size_t dictContentSize;
  61. ZSTD_dictContentType_e dictContentType; /* The dictContentType the CDict was created with */
  62. U32* entropyWorkspace; /* entropy workspace of HUF_WORKSPACE_SIZE bytes */
  63. ZSTD_cwksp workspace;
  64. ZSTD_matchState_t matchState;
  65. ZSTD_compressedBlockState_t cBlockState;
  66. ZSTD_customMem customMem;
  67. U32 dictID;
  68. int compressionLevel; /* 0 indicates that advanced API was used to select CDict params */
  69. ZSTD_useRowMatchFinderMode_e useRowMatchFinder; /* Indicates whether the CDict was created with params that would use
  70. * row-based matchfinder. Unless the cdict is reloaded, we will use
  71. * the same greedy/lazy matchfinder at compression time.
  72. */
  73. }; /* typedef'd to ZSTD_CDict within "zstd.h" */
  74. ZSTD_CCtx* ZSTD_createCCtx(void)
  75. {
  76. return ZSTD_createCCtx_advanced(ZSTD_defaultCMem);
  77. }
  78. static void ZSTD_initCCtx(ZSTD_CCtx* cctx, ZSTD_customMem memManager)
  79. {
  80. assert(cctx != NULL);
  81. ZSTD_memset(cctx, 0, sizeof(*cctx));
  82. cctx->customMem = memManager;
  83. cctx->bmi2 = ZSTD_cpuid_bmi2(ZSTD_cpuid());
  84. { size_t const err = ZSTD_CCtx_reset(cctx, ZSTD_reset_parameters);
  85. assert(!ZSTD_isError(err));
  86. (void)err;
  87. }
  88. }
  89. ZSTD_CCtx* ZSTD_createCCtx_advanced(ZSTD_customMem customMem)
  90. {
  91. ZSTD_STATIC_ASSERT(zcss_init==0);
  92. ZSTD_STATIC_ASSERT(ZSTD_CONTENTSIZE_UNKNOWN==(0ULL - 1));
  93. if ((!customMem.customAlloc) ^ (!customMem.customFree)) return NULL;
  94. { ZSTD_CCtx* const cctx = (ZSTD_CCtx*)ZSTD_customMalloc(sizeof(ZSTD_CCtx), customMem);
  95. if (!cctx) return NULL;
  96. ZSTD_initCCtx(cctx, customMem);
  97. return cctx;
  98. }
  99. }
  100. ZSTD_CCtx* ZSTD_initStaticCCtx(void* workspace, size_t workspaceSize)
  101. {
  102. ZSTD_cwksp ws;
  103. ZSTD_CCtx* cctx;
  104. if (workspaceSize <= sizeof(ZSTD_CCtx)) return NULL; /* minimum size */
  105. if ((size_t)workspace & 7) return NULL; /* must be 8-aligned */
  106. ZSTD_cwksp_init(&ws, workspace, workspaceSize, ZSTD_cwksp_static_alloc);
  107. cctx = (ZSTD_CCtx*)ZSTD_cwksp_reserve_object(&ws, sizeof(ZSTD_CCtx));
  108. if (cctx == NULL) return NULL;
  109. ZSTD_memset(cctx, 0, sizeof(ZSTD_CCtx));
  110. ZSTD_cwksp_move(&cctx->workspace, &ws);
  111. cctx->staticSize = workspaceSize;
  112. /* statically sized space. entropyWorkspace never moves (but prev/next block swap places) */
  113. if (!ZSTD_cwksp_check_available(&cctx->workspace, ENTROPY_WORKSPACE_SIZE + 2 * sizeof(ZSTD_compressedBlockState_t))) return NULL;
  114. cctx->blockState.prevCBlock = (ZSTD_compressedBlockState_t*)ZSTD_cwksp_reserve_object(&cctx->workspace, sizeof(ZSTD_compressedBlockState_t));
  115. cctx->blockState.nextCBlock = (ZSTD_compressedBlockState_t*)ZSTD_cwksp_reserve_object(&cctx->workspace, sizeof(ZSTD_compressedBlockState_t));
  116. cctx->entropyWorkspace = (U32*)ZSTD_cwksp_reserve_object(&cctx->workspace, ENTROPY_WORKSPACE_SIZE);
  117. cctx->bmi2 = ZSTD_cpuid_bmi2(ZSTD_cpuid());
  118. return cctx;
  119. }
  120. /**
  121. * Clears and frees all of the dictionaries in the CCtx.
  122. */
  123. static void ZSTD_clearAllDicts(ZSTD_CCtx* cctx)
  124. {
  125. ZSTD_customFree(cctx->localDict.dictBuffer, cctx->customMem);
  126. ZSTD_freeCDict(cctx->localDict.cdict);
  127. ZSTD_memset(&cctx->localDict, 0, sizeof(cctx->localDict));
  128. ZSTD_memset(&cctx->prefixDict, 0, sizeof(cctx->prefixDict));
  129. cctx->cdict = NULL;
  130. }
  131. static size_t ZSTD_sizeof_localDict(ZSTD_localDict dict)
  132. {
  133. size_t const bufferSize = dict.dictBuffer != NULL ? dict.dictSize : 0;
  134. size_t const cdictSize = ZSTD_sizeof_CDict(dict.cdict);
  135. return bufferSize + cdictSize;
  136. }
  137. static void ZSTD_freeCCtxContent(ZSTD_CCtx* cctx)
  138. {
  139. assert(cctx != NULL);
  140. assert(cctx->staticSize == 0);
  141. ZSTD_clearAllDicts(cctx);
  142. #ifdef ZSTD_MULTITHREAD
  143. ZSTDMT_freeCCtx(cctx->mtctx); cctx->mtctx = NULL;
  144. #endif
  145. ZSTD_cwksp_free(&cctx->workspace, cctx->customMem);
  146. }
  147. size_t ZSTD_freeCCtx(ZSTD_CCtx* cctx)
  148. {
  149. if (cctx==NULL) return 0; /* support free on NULL */
  150. RETURN_ERROR_IF(cctx->staticSize, memory_allocation,
  151. "not compatible with static CCtx");
  152. {
  153. int cctxInWorkspace = ZSTD_cwksp_owns_buffer(&cctx->workspace, cctx);
  154. ZSTD_freeCCtxContent(cctx);
  155. if (!cctxInWorkspace) {
  156. ZSTD_customFree(cctx, cctx->customMem);
  157. }
  158. }
  159. return 0;
  160. }
  161. static size_t ZSTD_sizeof_mtctx(const ZSTD_CCtx* cctx)
  162. {
  163. #ifdef ZSTD_MULTITHREAD
  164. return ZSTDMT_sizeof_CCtx(cctx->mtctx);
  165. #else
  166. (void)cctx;
  167. return 0;
  168. #endif
  169. }
  170. size_t ZSTD_sizeof_CCtx(const ZSTD_CCtx* cctx)
  171. {
  172. if (cctx==NULL) return 0; /* support sizeof on NULL */
  173. /* cctx may be in the workspace */
  174. return (cctx->workspace.workspace == cctx ? 0 : sizeof(*cctx))
  175. + ZSTD_cwksp_sizeof(&cctx->workspace)
  176. + ZSTD_sizeof_localDict(cctx->localDict)
  177. + ZSTD_sizeof_mtctx(cctx);
  178. }
  179. size_t ZSTD_sizeof_CStream(const ZSTD_CStream* zcs)
  180. {
  181. return ZSTD_sizeof_CCtx(zcs); /* same object */
  182. }
  183. /* private API call, for dictBuilder only */
  184. const seqStore_t* ZSTD_getSeqStore(const ZSTD_CCtx* ctx) { return &(ctx->seqStore); }
  185. /* Returns true if the strategy supports using a row based matchfinder */
  186. static int ZSTD_rowMatchFinderSupported(const ZSTD_strategy strategy) {
  187. return (strategy >= ZSTD_greedy && strategy <= ZSTD_lazy2);
  188. }
  189. /* Returns true if the strategy and useRowMatchFinder mode indicate that we will use the row based matchfinder
  190. * for this compression.
  191. */
  192. static int ZSTD_rowMatchFinderUsed(const ZSTD_strategy strategy, const ZSTD_useRowMatchFinderMode_e mode) {
  193. assert(mode != ZSTD_urm_auto);
  194. return ZSTD_rowMatchFinderSupported(strategy) && (mode == ZSTD_urm_enableRowMatchFinder);
  195. }
  196. /* Returns row matchfinder usage enum given an initial mode and cParams */
  197. static ZSTD_useRowMatchFinderMode_e ZSTD_resolveRowMatchFinderMode(ZSTD_useRowMatchFinderMode_e mode,
  198. const ZSTD_compressionParameters* const cParams) {
  199. #if !defined(ZSTD_NO_INTRINSICS) && (defined(__SSE2__) || defined(__ARM_NEON))
  200. int const kHasSIMD128 = 1;
  201. #else
  202. int const kHasSIMD128 = 0;
  203. #endif
  204. if (mode != ZSTD_urm_auto) return mode; /* if requested enabled, but no SIMD, we still will use row matchfinder */
  205. mode = ZSTD_urm_disableRowMatchFinder;
  206. if (!ZSTD_rowMatchFinderSupported(cParams->strategy)) return mode;
  207. if (kHasSIMD128) {
  208. if (cParams->windowLog > 14) mode = ZSTD_urm_enableRowMatchFinder;
  209. } else {
  210. if (cParams->windowLog > 17) mode = ZSTD_urm_enableRowMatchFinder;
  211. }
  212. return mode;
  213. }
  214. /* Returns 1 if the arguments indicate that we should allocate a chainTable, 0 otherwise */
  215. static int ZSTD_allocateChainTable(const ZSTD_strategy strategy,
  216. const ZSTD_useRowMatchFinderMode_e useRowMatchFinder,
  217. const U32 forDDSDict) {
  218. assert(useRowMatchFinder != ZSTD_urm_auto);
  219. /* We always should allocate a chaintable if we are allocating a matchstate for a DDS dictionary matchstate.
  220. * We do not allocate a chaintable if we are using ZSTD_fast, or are using the row-based matchfinder.
  221. */
  222. return forDDSDict || ((strategy != ZSTD_fast) && !ZSTD_rowMatchFinderUsed(strategy, useRowMatchFinder));
  223. }
  224. /* Returns 1 if compression parameters are such that we should
  225. * enable long distance matching (wlog >= 27, strategy >= btopt).
  226. * Returns 0 otherwise.
  227. */
  228. static U32 ZSTD_CParams_shouldEnableLdm(const ZSTD_compressionParameters* const cParams) {
  229. return cParams->strategy >= ZSTD_btopt && cParams->windowLog >= 27;
  230. }
  231. /* Returns 1 if compression parameters are such that we should
  232. * enable blockSplitter (wlog >= 17, strategy >= btopt).
  233. * Returns 0 otherwise.
  234. */
  235. static U32 ZSTD_CParams_useBlockSplitter(const ZSTD_compressionParameters* const cParams) {
  236. return cParams->strategy >= ZSTD_btopt && cParams->windowLog >= 17;
  237. }
  238. static ZSTD_CCtx_params ZSTD_makeCCtxParamsFromCParams(
  239. ZSTD_compressionParameters cParams)
  240. {
  241. ZSTD_CCtx_params cctxParams;
  242. /* should not matter, as all cParams are presumed properly defined */
  243. ZSTD_CCtxParams_init(&cctxParams, ZSTD_CLEVEL_DEFAULT);
  244. cctxParams.cParams = cParams;
  245. /* Adjust advanced params according to cParams */
  246. if (ZSTD_CParams_shouldEnableLdm(&cParams)) {
  247. DEBUGLOG(4, "ZSTD_makeCCtxParamsFromCParams(): Including LDM into cctx params");
  248. cctxParams.ldmParams.enableLdm = 1;
  249. /* LDM is enabled by default for optimal parser and window size >= 128MB */
  250. ZSTD_ldm_adjustParameters(&cctxParams.ldmParams, &cParams);
  251. assert(cctxParams.ldmParams.hashLog >= cctxParams.ldmParams.bucketSizeLog);
  252. assert(cctxParams.ldmParams.hashRateLog < 32);
  253. }
  254. if (ZSTD_CParams_useBlockSplitter(&cParams)) {
  255. DEBUGLOG(4, "ZSTD_makeCCtxParamsFromCParams(): Including block splitting into cctx params");
  256. cctxParams.splitBlocks = 1;
  257. }
  258. cctxParams.useRowMatchFinder = ZSTD_resolveRowMatchFinderMode(cctxParams.useRowMatchFinder, &cParams);
  259. assert(!ZSTD_checkCParams(cParams));
  260. return cctxParams;
  261. }
  262. static ZSTD_CCtx_params* ZSTD_createCCtxParams_advanced(
  263. ZSTD_customMem customMem)
  264. {
  265. ZSTD_CCtx_params* params;
  266. if ((!customMem.customAlloc) ^ (!customMem.customFree)) return NULL;
  267. params = (ZSTD_CCtx_params*)ZSTD_customCalloc(
  268. sizeof(ZSTD_CCtx_params), customMem);
  269. if (!params) { return NULL; }
  270. ZSTD_CCtxParams_init(params, ZSTD_CLEVEL_DEFAULT);
  271. params->customMem = customMem;
  272. return params;
  273. }
  274. ZSTD_CCtx_params* ZSTD_createCCtxParams(void)
  275. {
  276. return ZSTD_createCCtxParams_advanced(ZSTD_defaultCMem);
  277. }
  278. size_t ZSTD_freeCCtxParams(ZSTD_CCtx_params* params)
  279. {
  280. if (params == NULL) { return 0; }
  281. ZSTD_customFree(params, params->customMem);
  282. return 0;
  283. }
  284. size_t ZSTD_CCtxParams_reset(ZSTD_CCtx_params* params)
  285. {
  286. return ZSTD_CCtxParams_init(params, ZSTD_CLEVEL_DEFAULT);
  287. }
  288. size_t ZSTD_CCtxParams_init(ZSTD_CCtx_params* cctxParams, int compressionLevel) {
  289. RETURN_ERROR_IF(!cctxParams, GENERIC, "NULL pointer!");
  290. ZSTD_memset(cctxParams, 0, sizeof(*cctxParams));
  291. cctxParams->compressionLevel = compressionLevel;
  292. cctxParams->fParams.contentSizeFlag = 1;
  293. return 0;
  294. }
  295. #define ZSTD_NO_CLEVEL 0
  296. /**
  297. * Initializes the cctxParams from params and compressionLevel.
  298. * @param compressionLevel If params are derived from a compression level then that compression level, otherwise ZSTD_NO_CLEVEL.
  299. */
  300. static void ZSTD_CCtxParams_init_internal(ZSTD_CCtx_params* cctxParams, ZSTD_parameters const* params, int compressionLevel)
  301. {
  302. assert(!ZSTD_checkCParams(params->cParams));
  303. ZSTD_memset(cctxParams, 0, sizeof(*cctxParams));
  304. cctxParams->cParams = params->cParams;
  305. cctxParams->fParams = params->fParams;
  306. /* Should not matter, as all cParams are presumed properly defined.
  307. * But, set it for tracing anyway.
  308. */
  309. cctxParams->compressionLevel = compressionLevel;
  310. cctxParams->useRowMatchFinder = ZSTD_resolveRowMatchFinderMode(cctxParams->useRowMatchFinder, &params->cParams);
  311. DEBUGLOG(4, "ZSTD_CCtxParams_init_internal: useRowMatchFinder=%d", cctxParams->useRowMatchFinder);
  312. }
  313. size_t ZSTD_CCtxParams_init_advanced(ZSTD_CCtx_params* cctxParams, ZSTD_parameters params)
  314. {
  315. RETURN_ERROR_IF(!cctxParams, GENERIC, "NULL pointer!");
  316. FORWARD_IF_ERROR( ZSTD_checkCParams(params.cParams) , "");
  317. ZSTD_CCtxParams_init_internal(cctxParams, &params, ZSTD_NO_CLEVEL);
  318. return 0;
  319. }
  320. /**
  321. * Sets cctxParams' cParams and fParams from params, but otherwise leaves them alone.
  322. * @param param Validated zstd parameters.
  323. */
  324. static void ZSTD_CCtxParams_setZstdParams(
  325. ZSTD_CCtx_params* cctxParams, const ZSTD_parameters* params)
  326. {
  327. assert(!ZSTD_checkCParams(params->cParams));
  328. cctxParams->cParams = params->cParams;
  329. cctxParams->fParams = params->fParams;
  330. /* Should not matter, as all cParams are presumed properly defined.
  331. * But, set it for tracing anyway.
  332. */
  333. cctxParams->compressionLevel = ZSTD_NO_CLEVEL;
  334. }
  335. ZSTD_bounds ZSTD_cParam_getBounds(ZSTD_cParameter param)
  336. {
  337. ZSTD_bounds bounds = { 0, 0, 0 };
  338. switch(param)
  339. {
  340. case ZSTD_c_compressionLevel:
  341. bounds.lowerBound = ZSTD_minCLevel();
  342. bounds.upperBound = ZSTD_maxCLevel();
  343. return bounds;
  344. case ZSTD_c_windowLog:
  345. bounds.lowerBound = ZSTD_WINDOWLOG_MIN;
  346. bounds.upperBound = ZSTD_WINDOWLOG_MAX;
  347. return bounds;
  348. case ZSTD_c_hashLog:
  349. bounds.lowerBound = ZSTD_HASHLOG_MIN;
  350. bounds.upperBound = ZSTD_HASHLOG_MAX;
  351. return bounds;
  352. case ZSTD_c_chainLog:
  353. bounds.lowerBound = ZSTD_CHAINLOG_MIN;
  354. bounds.upperBound = ZSTD_CHAINLOG_MAX;
  355. return bounds;
  356. case ZSTD_c_searchLog:
  357. bounds.lowerBound = ZSTD_SEARCHLOG_MIN;
  358. bounds.upperBound = ZSTD_SEARCHLOG_MAX;
  359. return bounds;
  360. case ZSTD_c_minMatch:
  361. bounds.lowerBound = ZSTD_MINMATCH_MIN;
  362. bounds.upperBound = ZSTD_MINMATCH_MAX;
  363. return bounds;
  364. case ZSTD_c_targetLength:
  365. bounds.lowerBound = ZSTD_TARGETLENGTH_MIN;
  366. bounds.upperBound = ZSTD_TARGETLENGTH_MAX;
  367. return bounds;
  368. case ZSTD_c_strategy:
  369. bounds.lowerBound = ZSTD_STRATEGY_MIN;
  370. bounds.upperBound = ZSTD_STRATEGY_MAX;
  371. return bounds;
  372. case ZSTD_c_contentSizeFlag:
  373. bounds.lowerBound = 0;
  374. bounds.upperBound = 1;
  375. return bounds;
  376. case ZSTD_c_checksumFlag:
  377. bounds.lowerBound = 0;
  378. bounds.upperBound = 1;
  379. return bounds;
  380. case ZSTD_c_dictIDFlag:
  381. bounds.lowerBound = 0;
  382. bounds.upperBound = 1;
  383. return bounds;
  384. case ZSTD_c_nbWorkers:
  385. bounds.lowerBound = 0;
  386. #ifdef ZSTD_MULTITHREAD
  387. bounds.upperBound = ZSTDMT_NBWORKERS_MAX;
  388. #else
  389. bounds.upperBound = 0;
  390. #endif
  391. return bounds;
  392. case ZSTD_c_jobSize:
  393. bounds.lowerBound = 0;
  394. #ifdef ZSTD_MULTITHREAD
  395. bounds.upperBound = ZSTDMT_JOBSIZE_MAX;
  396. #else
  397. bounds.upperBound = 0;
  398. #endif
  399. return bounds;
  400. case ZSTD_c_overlapLog:
  401. #ifdef ZSTD_MULTITHREAD
  402. bounds.lowerBound = ZSTD_OVERLAPLOG_MIN;
  403. bounds.upperBound = ZSTD_OVERLAPLOG_MAX;
  404. #else
  405. bounds.lowerBound = 0;
  406. bounds.upperBound = 0;
  407. #endif
  408. return bounds;
  409. case ZSTD_c_enableDedicatedDictSearch:
  410. bounds.lowerBound = 0;
  411. bounds.upperBound = 1;
  412. return bounds;
  413. case ZSTD_c_enableLongDistanceMatching:
  414. bounds.lowerBound = 0;
  415. bounds.upperBound = 1;
  416. return bounds;
  417. case ZSTD_c_ldmHashLog:
  418. bounds.lowerBound = ZSTD_LDM_HASHLOG_MIN;
  419. bounds.upperBound = ZSTD_LDM_HASHLOG_MAX;
  420. return bounds;
  421. case ZSTD_c_ldmMinMatch:
  422. bounds.lowerBound = ZSTD_LDM_MINMATCH_MIN;
  423. bounds.upperBound = ZSTD_LDM_MINMATCH_MAX;
  424. return bounds;
  425. case ZSTD_c_ldmBucketSizeLog:
  426. bounds.lowerBound = ZSTD_LDM_BUCKETSIZELOG_MIN;
  427. bounds.upperBound = ZSTD_LDM_BUCKETSIZELOG_MAX;
  428. return bounds;
  429. case ZSTD_c_ldmHashRateLog:
  430. bounds.lowerBound = ZSTD_LDM_HASHRATELOG_MIN;
  431. bounds.upperBound = ZSTD_LDM_HASHRATELOG_MAX;
  432. return bounds;
  433. /* experimental parameters */
  434. case ZSTD_c_rsyncable:
  435. bounds.lowerBound = 0;
  436. bounds.upperBound = 1;
  437. return bounds;
  438. case ZSTD_c_forceMaxWindow :
  439. bounds.lowerBound = 0;
  440. bounds.upperBound = 1;
  441. return bounds;
  442. case ZSTD_c_format:
  443. ZSTD_STATIC_ASSERT(ZSTD_f_zstd1 < ZSTD_f_zstd1_magicless);
  444. bounds.lowerBound = ZSTD_f_zstd1;
  445. bounds.upperBound = ZSTD_f_zstd1_magicless; /* note : how to ensure at compile time that this is the highest value enum ? */
  446. return bounds;
  447. case ZSTD_c_forceAttachDict:
  448. ZSTD_STATIC_ASSERT(ZSTD_dictDefaultAttach < ZSTD_dictForceLoad);
  449. bounds.lowerBound = ZSTD_dictDefaultAttach;
  450. bounds.upperBound = ZSTD_dictForceLoad; /* note : how to ensure at compile time that this is the highest value enum ? */
  451. return bounds;
  452. case ZSTD_c_literalCompressionMode:
  453. ZSTD_STATIC_ASSERT(ZSTD_lcm_auto < ZSTD_lcm_huffman && ZSTD_lcm_huffman < ZSTD_lcm_uncompressed);
  454. bounds.lowerBound = ZSTD_lcm_auto;
  455. bounds.upperBound = ZSTD_lcm_uncompressed;
  456. return bounds;
  457. case ZSTD_c_targetCBlockSize:
  458. bounds.lowerBound = ZSTD_TARGETCBLOCKSIZE_MIN;
  459. bounds.upperBound = ZSTD_TARGETCBLOCKSIZE_MAX;
  460. return bounds;
  461. case ZSTD_c_srcSizeHint:
  462. bounds.lowerBound = ZSTD_SRCSIZEHINT_MIN;
  463. bounds.upperBound = ZSTD_SRCSIZEHINT_MAX;
  464. return bounds;
  465. case ZSTD_c_stableInBuffer:
  466. case ZSTD_c_stableOutBuffer:
  467. bounds.lowerBound = (int)ZSTD_bm_buffered;
  468. bounds.upperBound = (int)ZSTD_bm_stable;
  469. return bounds;
  470. case ZSTD_c_blockDelimiters:
  471. bounds.lowerBound = (int)ZSTD_sf_noBlockDelimiters;
  472. bounds.upperBound = (int)ZSTD_sf_explicitBlockDelimiters;
  473. return bounds;
  474. case ZSTD_c_validateSequences:
  475. bounds.lowerBound = 0;
  476. bounds.upperBound = 1;
  477. return bounds;
  478. case ZSTD_c_splitBlocks:
  479. bounds.lowerBound = 0;
  480. bounds.upperBound = 1;
  481. return bounds;
  482. case ZSTD_c_useRowMatchFinder:
  483. bounds.lowerBound = (int)ZSTD_urm_auto;
  484. bounds.upperBound = (int)ZSTD_urm_enableRowMatchFinder;
  485. return bounds;
  486. case ZSTD_c_deterministicRefPrefix:
  487. bounds.lowerBound = 0;
  488. bounds.upperBound = 1;
  489. return bounds;
  490. default:
  491. bounds.error = ERROR(parameter_unsupported);
  492. return bounds;
  493. }
  494. }
  495. /* ZSTD_cParam_clampBounds:
  496. * Clamps the value into the bounded range.
  497. */
  498. static size_t ZSTD_cParam_clampBounds(ZSTD_cParameter cParam, int* value)
  499. {
  500. ZSTD_bounds const bounds = ZSTD_cParam_getBounds(cParam);
  501. if (ZSTD_isError(bounds.error)) return bounds.error;
  502. if (*value < bounds.lowerBound) *value = bounds.lowerBound;
  503. if (*value > bounds.upperBound) *value = bounds.upperBound;
  504. return 0;
  505. }
  506. #define BOUNDCHECK(cParam, val) { \
  507. RETURN_ERROR_IF(!ZSTD_cParam_withinBounds(cParam,val), \
  508. parameter_outOfBound, "Param out of bounds"); \
  509. }
  510. static int ZSTD_isUpdateAuthorized(ZSTD_cParameter param)
  511. {
  512. switch(param)
  513. {
  514. case ZSTD_c_compressionLevel:
  515. case ZSTD_c_hashLog:
  516. case ZSTD_c_chainLog:
  517. case ZSTD_c_searchLog:
  518. case ZSTD_c_minMatch:
  519. case ZSTD_c_targetLength:
  520. case ZSTD_c_strategy:
  521. return 1;
  522. case ZSTD_c_format:
  523. case ZSTD_c_windowLog:
  524. case ZSTD_c_contentSizeFlag:
  525. case ZSTD_c_checksumFlag:
  526. case ZSTD_c_dictIDFlag:
  527. case ZSTD_c_forceMaxWindow :
  528. case ZSTD_c_nbWorkers:
  529. case ZSTD_c_jobSize:
  530. case ZSTD_c_overlapLog:
  531. case ZSTD_c_rsyncable:
  532. case ZSTD_c_enableDedicatedDictSearch:
  533. case ZSTD_c_enableLongDistanceMatching:
  534. case ZSTD_c_ldmHashLog:
  535. case ZSTD_c_ldmMinMatch:
  536. case ZSTD_c_ldmBucketSizeLog:
  537. case ZSTD_c_ldmHashRateLog:
  538. case ZSTD_c_forceAttachDict:
  539. case ZSTD_c_literalCompressionMode:
  540. case ZSTD_c_targetCBlockSize:
  541. case ZSTD_c_srcSizeHint:
  542. case ZSTD_c_stableInBuffer:
  543. case ZSTD_c_stableOutBuffer:
  544. case ZSTD_c_blockDelimiters:
  545. case ZSTD_c_validateSequences:
  546. case ZSTD_c_splitBlocks:
  547. case ZSTD_c_useRowMatchFinder:
  548. case ZSTD_c_deterministicRefPrefix:
  549. default:
  550. return 0;
  551. }
  552. }
  553. size_t ZSTD_CCtx_setParameter(ZSTD_CCtx* cctx, ZSTD_cParameter param, int value)
  554. {
  555. DEBUGLOG(4, "ZSTD_CCtx_setParameter (%i, %i)", (int)param, value);
  556. if (cctx->streamStage != zcss_init) {
  557. if (ZSTD_isUpdateAuthorized(param)) {
  558. cctx->cParamsChanged = 1;
  559. } else {
  560. RETURN_ERROR(stage_wrong, "can only set params in ctx init stage");
  561. } }
  562. switch(param)
  563. {
  564. case ZSTD_c_nbWorkers:
  565. RETURN_ERROR_IF((value!=0) && cctx->staticSize, parameter_unsupported,
  566. "MT not compatible with static alloc");
  567. break;
  568. case ZSTD_c_compressionLevel:
  569. case ZSTD_c_windowLog:
  570. case ZSTD_c_hashLog:
  571. case ZSTD_c_chainLog:
  572. case ZSTD_c_searchLog:
  573. case ZSTD_c_minMatch:
  574. case ZSTD_c_targetLength:
  575. case ZSTD_c_strategy:
  576. case ZSTD_c_ldmHashRateLog:
  577. case ZSTD_c_format:
  578. case ZSTD_c_contentSizeFlag:
  579. case ZSTD_c_checksumFlag:
  580. case ZSTD_c_dictIDFlag:
  581. case ZSTD_c_forceMaxWindow:
  582. case ZSTD_c_forceAttachDict:
  583. case ZSTD_c_literalCompressionMode:
  584. case ZSTD_c_jobSize:
  585. case ZSTD_c_overlapLog:
  586. case ZSTD_c_rsyncable:
  587. case ZSTD_c_enableDedicatedDictSearch:
  588. case ZSTD_c_enableLongDistanceMatching:
  589. case ZSTD_c_ldmHashLog:
  590. case ZSTD_c_ldmMinMatch:
  591. case ZSTD_c_ldmBucketSizeLog:
  592. case ZSTD_c_targetCBlockSize:
  593. case ZSTD_c_srcSizeHint:
  594. case ZSTD_c_stableInBuffer:
  595. case ZSTD_c_stableOutBuffer:
  596. case ZSTD_c_blockDelimiters:
  597. case ZSTD_c_validateSequences:
  598. case ZSTD_c_splitBlocks:
  599. case ZSTD_c_useRowMatchFinder:
  600. case ZSTD_c_deterministicRefPrefix:
  601. break;
  602. default: RETURN_ERROR(parameter_unsupported, "unknown parameter");
  603. }
  604. return ZSTD_CCtxParams_setParameter(&cctx->requestedParams, param, value);
  605. }
  606. size_t ZSTD_CCtxParams_setParameter(ZSTD_CCtx_params* CCtxParams,
  607. ZSTD_cParameter param, int value)
  608. {
  609. DEBUGLOG(4, "ZSTD_CCtxParams_setParameter (%i, %i)", (int)param, value);
  610. switch(param)
  611. {
  612. case ZSTD_c_format :
  613. BOUNDCHECK(ZSTD_c_format, value);
  614. CCtxParams->format = (ZSTD_format_e)value;
  615. return (size_t)CCtxParams->format;
  616. case ZSTD_c_compressionLevel : {
  617. FORWARD_IF_ERROR(ZSTD_cParam_clampBounds(param, &value), "");
  618. if (value == 0)
  619. CCtxParams->compressionLevel = ZSTD_CLEVEL_DEFAULT; /* 0 == default */
  620. else
  621. CCtxParams->compressionLevel = value;
  622. if (CCtxParams->compressionLevel >= 0) return (size_t)CCtxParams->compressionLevel;
  623. return 0; /* return type (size_t) cannot represent negative values */
  624. }
  625. case ZSTD_c_windowLog :
  626. if (value!=0) /* 0 => use default */
  627. BOUNDCHECK(ZSTD_c_windowLog, value);
  628. CCtxParams->cParams.windowLog = (U32)value;
  629. return CCtxParams->cParams.windowLog;
  630. case ZSTD_c_hashLog :
  631. if (value!=0) /* 0 => use default */
  632. BOUNDCHECK(ZSTD_c_hashLog, value);
  633. CCtxParams->cParams.hashLog = (U32)value;
  634. return CCtxParams->cParams.hashLog;
  635. case ZSTD_c_chainLog :
  636. if (value!=0) /* 0 => use default */
  637. BOUNDCHECK(ZSTD_c_chainLog, value);
  638. CCtxParams->cParams.chainLog = (U32)value;
  639. return CCtxParams->cParams.chainLog;
  640. case ZSTD_c_searchLog :
  641. if (value!=0) /* 0 => use default */
  642. BOUNDCHECK(ZSTD_c_searchLog, value);
  643. CCtxParams->cParams.searchLog = (U32)value;
  644. return (size_t)value;
  645. case ZSTD_c_minMatch :
  646. if (value!=0) /* 0 => use default */
  647. BOUNDCHECK(ZSTD_c_minMatch, value);
  648. CCtxParams->cParams.minMatch = value;
  649. return CCtxParams->cParams.minMatch;
  650. case ZSTD_c_targetLength :
  651. BOUNDCHECK(ZSTD_c_targetLength, value);
  652. CCtxParams->cParams.targetLength = value;
  653. return CCtxParams->cParams.targetLength;
  654. case ZSTD_c_strategy :
  655. if (value!=0) /* 0 => use default */
  656. BOUNDCHECK(ZSTD_c_strategy, value);
  657. CCtxParams->cParams.strategy = (ZSTD_strategy)value;
  658. return (size_t)CCtxParams->cParams.strategy;
  659. case ZSTD_c_contentSizeFlag :
  660. /* Content size written in frame header _when known_ (default:1) */
  661. DEBUGLOG(4, "set content size flag = %u", (value!=0));
  662. CCtxParams->fParams.contentSizeFlag = value != 0;
  663. return CCtxParams->fParams.contentSizeFlag;
  664. case ZSTD_c_checksumFlag :
  665. /* A 32-bits content checksum will be calculated and written at end of frame (default:0) */
  666. CCtxParams->fParams.checksumFlag = value != 0;
  667. return CCtxParams->fParams.checksumFlag;
  668. case ZSTD_c_dictIDFlag : /* When applicable, dictionary's dictID is provided in frame header (default:1) */
  669. DEBUGLOG(4, "set dictIDFlag = %u", (value!=0));
  670. CCtxParams->fParams.noDictIDFlag = !value;
  671. return !CCtxParams->fParams.noDictIDFlag;
  672. case ZSTD_c_forceMaxWindow :
  673. CCtxParams->forceWindow = (value != 0);
  674. return CCtxParams->forceWindow;
  675. case ZSTD_c_forceAttachDict : {
  676. const ZSTD_dictAttachPref_e pref = (ZSTD_dictAttachPref_e)value;
  677. BOUNDCHECK(ZSTD_c_forceAttachDict, pref);
  678. CCtxParams->attachDictPref = pref;
  679. return CCtxParams->attachDictPref;
  680. }
  681. case ZSTD_c_literalCompressionMode : {
  682. const ZSTD_literalCompressionMode_e lcm = (ZSTD_literalCompressionMode_e)value;
  683. BOUNDCHECK(ZSTD_c_literalCompressionMode, lcm);
  684. CCtxParams->literalCompressionMode = lcm;
  685. return CCtxParams->literalCompressionMode;
  686. }
  687. case ZSTD_c_nbWorkers :
  688. #ifndef ZSTD_MULTITHREAD
  689. RETURN_ERROR_IF(value!=0, parameter_unsupported, "not compiled with multithreading");
  690. return 0;
  691. #else
  692. FORWARD_IF_ERROR(ZSTD_cParam_clampBounds(param, &value), "");
  693. CCtxParams->nbWorkers = value;
  694. return CCtxParams->nbWorkers;
  695. #endif
  696. case ZSTD_c_jobSize :
  697. #ifndef ZSTD_MULTITHREAD
  698. RETURN_ERROR_IF(value!=0, parameter_unsupported, "not compiled with multithreading");
  699. return 0;
  700. #else
  701. /* Adjust to the minimum non-default value. */
  702. if (value != 0 && value < ZSTDMT_JOBSIZE_MIN)
  703. value = ZSTDMT_JOBSIZE_MIN;
  704. FORWARD_IF_ERROR(ZSTD_cParam_clampBounds(param, &value), "");
  705. assert(value >= 0);
  706. CCtxParams->jobSize = value;
  707. return CCtxParams->jobSize;
  708. #endif
  709. case ZSTD_c_overlapLog :
  710. #ifndef ZSTD_MULTITHREAD
  711. RETURN_ERROR_IF(value!=0, parameter_unsupported, "not compiled with multithreading");
  712. return 0;
  713. #else
  714. FORWARD_IF_ERROR(ZSTD_cParam_clampBounds(ZSTD_c_overlapLog, &value), "");
  715. CCtxParams->overlapLog = value;
  716. return CCtxParams->overlapLog;
  717. #endif
  718. case ZSTD_c_rsyncable :
  719. #ifndef ZSTD_MULTITHREAD
  720. RETURN_ERROR_IF(value!=0, parameter_unsupported, "not compiled with multithreading");
  721. return 0;
  722. #else
  723. FORWARD_IF_ERROR(ZSTD_cParam_clampBounds(ZSTD_c_overlapLog, &value), "");
  724. CCtxParams->rsyncable = value;
  725. return CCtxParams->rsyncable;
  726. #endif
  727. case ZSTD_c_enableDedicatedDictSearch :
  728. CCtxParams->enableDedicatedDictSearch = (value!=0);
  729. return CCtxParams->enableDedicatedDictSearch;
  730. case ZSTD_c_enableLongDistanceMatching :
  731. CCtxParams->ldmParams.enableLdm = (value!=0);
  732. return CCtxParams->ldmParams.enableLdm;
  733. case ZSTD_c_ldmHashLog :
  734. if (value!=0) /* 0 ==> auto */
  735. BOUNDCHECK(ZSTD_c_ldmHashLog, value);
  736. CCtxParams->ldmParams.hashLog = value;
  737. return CCtxParams->ldmParams.hashLog;
  738. case ZSTD_c_ldmMinMatch :
  739. if (value!=0) /* 0 ==> default */
  740. BOUNDCHECK(ZSTD_c_ldmMinMatch, value);
  741. CCtxParams->ldmParams.minMatchLength = value;
  742. return CCtxParams->ldmParams.minMatchLength;
  743. case ZSTD_c_ldmBucketSizeLog :
  744. if (value!=0) /* 0 ==> default */
  745. BOUNDCHECK(ZSTD_c_ldmBucketSizeLog, value);
  746. CCtxParams->ldmParams.bucketSizeLog = value;
  747. return CCtxParams->ldmParams.bucketSizeLog;
  748. case ZSTD_c_ldmHashRateLog :
  749. RETURN_ERROR_IF(value > ZSTD_WINDOWLOG_MAX - ZSTD_HASHLOG_MIN,
  750. parameter_outOfBound, "Param out of bounds!");
  751. CCtxParams->ldmParams.hashRateLog = value;
  752. return CCtxParams->ldmParams.hashRateLog;
  753. case ZSTD_c_targetCBlockSize :
  754. if (value!=0) /* 0 ==> default */
  755. BOUNDCHECK(ZSTD_c_targetCBlockSize, value);
  756. CCtxParams->targetCBlockSize = value;
  757. return CCtxParams->targetCBlockSize;
  758. case ZSTD_c_srcSizeHint :
  759. if (value!=0) /* 0 ==> default */
  760. BOUNDCHECK(ZSTD_c_srcSizeHint, value);
  761. CCtxParams->srcSizeHint = value;
  762. return CCtxParams->srcSizeHint;
  763. case ZSTD_c_stableInBuffer:
  764. BOUNDCHECK(ZSTD_c_stableInBuffer, value);
  765. CCtxParams->inBufferMode = (ZSTD_bufferMode_e)value;
  766. return CCtxParams->inBufferMode;
  767. case ZSTD_c_stableOutBuffer:
  768. BOUNDCHECK(ZSTD_c_stableOutBuffer, value);
  769. CCtxParams->outBufferMode = (ZSTD_bufferMode_e)value;
  770. return CCtxParams->outBufferMode;
  771. case ZSTD_c_blockDelimiters:
  772. BOUNDCHECK(ZSTD_c_blockDelimiters, value);
  773. CCtxParams->blockDelimiters = (ZSTD_sequenceFormat_e)value;
  774. return CCtxParams->blockDelimiters;
  775. case ZSTD_c_validateSequences:
  776. BOUNDCHECK(ZSTD_c_validateSequences, value);
  777. CCtxParams->validateSequences = value;
  778. return CCtxParams->validateSequences;
  779. case ZSTD_c_splitBlocks:
  780. BOUNDCHECK(ZSTD_c_splitBlocks, value);
  781. CCtxParams->splitBlocks = value;
  782. return CCtxParams->splitBlocks;
  783. case ZSTD_c_useRowMatchFinder:
  784. BOUNDCHECK(ZSTD_c_useRowMatchFinder, value);
  785. CCtxParams->useRowMatchFinder = (ZSTD_useRowMatchFinderMode_e)value;
  786. return CCtxParams->useRowMatchFinder;
  787. case ZSTD_c_deterministicRefPrefix:
  788. BOUNDCHECK(ZSTD_c_deterministicRefPrefix, value);
  789. CCtxParams->deterministicRefPrefix = !!value;
  790. return CCtxParams->deterministicRefPrefix;
  791. default: RETURN_ERROR(parameter_unsupported, "unknown parameter");
  792. }
  793. }
  794. size_t ZSTD_CCtx_getParameter(ZSTD_CCtx const* cctx, ZSTD_cParameter param, int* value)
  795. {
  796. return ZSTD_CCtxParams_getParameter(&cctx->requestedParams, param, value);
  797. }
  798. size_t ZSTD_CCtxParams_getParameter(
  799. ZSTD_CCtx_params const* CCtxParams, ZSTD_cParameter param, int* value)
  800. {
  801. switch(param)
  802. {
  803. case ZSTD_c_format :
  804. *value = CCtxParams->format;
  805. break;
  806. case ZSTD_c_compressionLevel :
  807. *value = CCtxParams->compressionLevel;
  808. break;
  809. case ZSTD_c_windowLog :
  810. *value = (int)CCtxParams->cParams.windowLog;
  811. break;
  812. case ZSTD_c_hashLog :
  813. *value = (int)CCtxParams->cParams.hashLog;
  814. break;
  815. case ZSTD_c_chainLog :
  816. *value = (int)CCtxParams->cParams.chainLog;
  817. break;
  818. case ZSTD_c_searchLog :
  819. *value = CCtxParams->cParams.searchLog;
  820. break;
  821. case ZSTD_c_minMatch :
  822. *value = CCtxParams->cParams.minMatch;
  823. break;
  824. case ZSTD_c_targetLength :
  825. *value = CCtxParams->cParams.targetLength;
  826. break;
  827. case ZSTD_c_strategy :
  828. *value = (unsigned)CCtxParams->cParams.strategy;
  829. break;
  830. case ZSTD_c_contentSizeFlag :
  831. *value = CCtxParams->fParams.contentSizeFlag;
  832. break;
  833. case ZSTD_c_checksumFlag :
  834. *value = CCtxParams->fParams.checksumFlag;
  835. break;
  836. case ZSTD_c_dictIDFlag :
  837. *value = !CCtxParams->fParams.noDictIDFlag;
  838. break;
  839. case ZSTD_c_forceMaxWindow :
  840. *value = CCtxParams->forceWindow;
  841. break;
  842. case ZSTD_c_forceAttachDict :
  843. *value = CCtxParams->attachDictPref;
  844. break;
  845. case ZSTD_c_literalCompressionMode :
  846. *value = CCtxParams->literalCompressionMode;
  847. break;
  848. case ZSTD_c_nbWorkers :
  849. #ifndef ZSTD_MULTITHREAD
  850. assert(CCtxParams->nbWorkers == 0);
  851. #endif
  852. *value = CCtxParams->nbWorkers;
  853. break;
  854. case ZSTD_c_jobSize :
  855. #ifndef ZSTD_MULTITHREAD
  856. RETURN_ERROR(parameter_unsupported, "not compiled with multithreading");
  857. #else
  858. assert(CCtxParams->jobSize <= INT_MAX);
  859. *value = (int)CCtxParams->jobSize;
  860. break;
  861. #endif
  862. case ZSTD_c_overlapLog :
  863. #ifndef ZSTD_MULTITHREAD
  864. RETURN_ERROR(parameter_unsupported, "not compiled with multithreading");
  865. #else
  866. *value = CCtxParams->overlapLog;
  867. break;
  868. #endif
  869. case ZSTD_c_rsyncable :
  870. #ifndef ZSTD_MULTITHREAD
  871. RETURN_ERROR(parameter_unsupported, "not compiled with multithreading");
  872. #else
  873. *value = CCtxParams->rsyncable;
  874. break;
  875. #endif
  876. case ZSTD_c_enableDedicatedDictSearch :
  877. *value = CCtxParams->enableDedicatedDictSearch;
  878. break;
  879. case ZSTD_c_enableLongDistanceMatching :
  880. *value = CCtxParams->ldmParams.enableLdm;
  881. break;
  882. case ZSTD_c_ldmHashLog :
  883. *value = CCtxParams->ldmParams.hashLog;
  884. break;
  885. case ZSTD_c_ldmMinMatch :
  886. *value = CCtxParams->ldmParams.minMatchLength;
  887. break;
  888. case ZSTD_c_ldmBucketSizeLog :
  889. *value = CCtxParams->ldmParams.bucketSizeLog;
  890. break;
  891. case ZSTD_c_ldmHashRateLog :
  892. *value = CCtxParams->ldmParams.hashRateLog;
  893. break;
  894. case ZSTD_c_targetCBlockSize :
  895. *value = (int)CCtxParams->targetCBlockSize;
  896. break;
  897. case ZSTD_c_srcSizeHint :
  898. *value = (int)CCtxParams->srcSizeHint;
  899. break;
  900. case ZSTD_c_stableInBuffer :
  901. *value = (int)CCtxParams->inBufferMode;
  902. break;
  903. case ZSTD_c_stableOutBuffer :
  904. *value = (int)CCtxParams->outBufferMode;
  905. break;
  906. case ZSTD_c_blockDelimiters :
  907. *value = (int)CCtxParams->blockDelimiters;
  908. break;
  909. case ZSTD_c_validateSequences :
  910. *value = (int)CCtxParams->validateSequences;
  911. break;
  912. case ZSTD_c_splitBlocks :
  913. *value = (int)CCtxParams->splitBlocks;
  914. break;
  915. case ZSTD_c_useRowMatchFinder :
  916. *value = (int)CCtxParams->useRowMatchFinder;
  917. break;
  918. case ZSTD_c_deterministicRefPrefix:
  919. *value = (int)CCtxParams->deterministicRefPrefix;
  920. break;
  921. default: RETURN_ERROR(parameter_unsupported, "unknown parameter");
  922. }
  923. return 0;
  924. }
  925. /** ZSTD_CCtx_setParametersUsingCCtxParams() :
  926. * just applies `params` into `cctx`
  927. * no action is performed, parameters are merely stored.
  928. * If ZSTDMT is enabled, parameters are pushed to cctx->mtctx.
  929. * This is possible even if a compression is ongoing.
  930. * In which case, new parameters will be applied on the fly, starting with next compression job.
  931. */
  932. size_t ZSTD_CCtx_setParametersUsingCCtxParams(
  933. ZSTD_CCtx* cctx, const ZSTD_CCtx_params* params)
  934. {
  935. DEBUGLOG(4, "ZSTD_CCtx_setParametersUsingCCtxParams");
  936. RETURN_ERROR_IF(cctx->streamStage != zcss_init, stage_wrong,
  937. "The context is in the wrong stage!");
  938. RETURN_ERROR_IF(cctx->cdict, stage_wrong,
  939. "Can't override parameters with cdict attached (some must "
  940. "be inherited from the cdict).");
  941. cctx->requestedParams = *params;
  942. return 0;
  943. }
  944. ZSTDLIB_API size_t ZSTD_CCtx_setPledgedSrcSize(ZSTD_CCtx* cctx, unsigned long long pledgedSrcSize)
  945. {
  946. DEBUGLOG(4, "ZSTD_CCtx_setPledgedSrcSize to %u bytes", (U32)pledgedSrcSize);
  947. RETURN_ERROR_IF(cctx->streamStage != zcss_init, stage_wrong,
  948. "Can't set pledgedSrcSize when not in init stage.");
  949. cctx->pledgedSrcSizePlusOne = pledgedSrcSize+1;
  950. return 0;
  951. }
  952. static ZSTD_compressionParameters ZSTD_dedicatedDictSearch_getCParams(
  953. int const compressionLevel,
  954. size_t const dictSize);
  955. static int ZSTD_dedicatedDictSearch_isSupported(
  956. const ZSTD_compressionParameters* cParams);
  957. static void ZSTD_dedicatedDictSearch_revertCParams(
  958. ZSTD_compressionParameters* cParams);
  959. /**
  960. * Initializes the local dict using the requested parameters.
  961. * NOTE: This does not use the pledged src size, because it may be used for more
  962. * than one compression.
  963. */
  964. static size_t ZSTD_initLocalDict(ZSTD_CCtx* cctx)
  965. {
  966. ZSTD_localDict* const dl = &cctx->localDict;
  967. if (dl->dict == NULL) {
  968. /* No local dictionary. */
  969. assert(dl->dictBuffer == NULL);
  970. assert(dl->cdict == NULL);
  971. assert(dl->dictSize == 0);
  972. return 0;
  973. }
  974. if (dl->cdict != NULL) {
  975. assert(cctx->cdict == dl->cdict);
  976. /* Local dictionary already initialized. */
  977. return 0;
  978. }
  979. assert(dl->dictSize > 0);
  980. assert(cctx->cdict == NULL);
  981. assert(cctx->prefixDict.dict == NULL);
  982. dl->cdict = ZSTD_createCDict_advanced2(
  983. dl->dict,
  984. dl->dictSize,
  985. ZSTD_dlm_byRef,
  986. dl->dictContentType,
  987. &cctx->requestedParams,
  988. cctx->customMem);
  989. RETURN_ERROR_IF(!dl->cdict, memory_allocation, "ZSTD_createCDict_advanced failed");
  990. cctx->cdict = dl->cdict;
  991. return 0;
  992. }
  993. size_t ZSTD_CCtx_loadDictionary_advanced(
  994. ZSTD_CCtx* cctx, const void* dict, size_t dictSize,
  995. ZSTD_dictLoadMethod_e dictLoadMethod, ZSTD_dictContentType_e dictContentType)
  996. {
  997. RETURN_ERROR_IF(cctx->streamStage != zcss_init, stage_wrong,
  998. "Can't load a dictionary when ctx is not in init stage.");
  999. DEBUGLOG(4, "ZSTD_CCtx_loadDictionary_advanced (size: %u)", (U32)dictSize);
  1000. ZSTD_clearAllDicts(cctx); /* in case one already exists */
  1001. if (dict == NULL || dictSize == 0) /* no dictionary mode */
  1002. return 0;
  1003. if (dictLoadMethod == ZSTD_dlm_byRef) {
  1004. cctx->localDict.dict = dict;
  1005. } else {
  1006. void* dictBuffer;
  1007. RETURN_ERROR_IF(cctx->staticSize, memory_allocation,
  1008. "no malloc for static CCtx");
  1009. dictBuffer = ZSTD_customMalloc(dictSize, cctx->customMem);
  1010. RETURN_ERROR_IF(!dictBuffer, memory_allocation, "NULL pointer!");
  1011. ZSTD_memcpy(dictBuffer, dict, dictSize);
  1012. cctx->localDict.dictBuffer = dictBuffer;
  1013. cctx->localDict.dict = dictBuffer;
  1014. }
  1015. cctx->localDict.dictSize = dictSize;
  1016. cctx->localDict.dictContentType = dictContentType;
  1017. return 0;
  1018. }
  1019. ZSTDLIB_API size_t ZSTD_CCtx_loadDictionary_byReference(
  1020. ZSTD_CCtx* cctx, const void* dict, size_t dictSize)
  1021. {
  1022. return ZSTD_CCtx_loadDictionary_advanced(
  1023. cctx, dict, dictSize, ZSTD_dlm_byRef, ZSTD_dct_auto);
  1024. }
  1025. ZSTDLIB_API size_t ZSTD_CCtx_loadDictionary(ZSTD_CCtx* cctx, const void* dict, size_t dictSize)
  1026. {
  1027. return ZSTD_CCtx_loadDictionary_advanced(
  1028. cctx, dict, dictSize, ZSTD_dlm_byCopy, ZSTD_dct_auto);
  1029. }
  1030. size_t ZSTD_CCtx_refCDict(ZSTD_CCtx* cctx, const ZSTD_CDict* cdict)
  1031. {
  1032. RETURN_ERROR_IF(cctx->streamStage != zcss_init, stage_wrong,
  1033. "Can't ref a dict when ctx not in init stage.");
  1034. /* Free the existing local cdict (if any) to save memory. */
  1035. ZSTD_clearAllDicts(cctx);
  1036. cctx->cdict = cdict;
  1037. return 0;
  1038. }
  1039. size_t ZSTD_CCtx_refThreadPool(ZSTD_CCtx* cctx, ZSTD_threadPool* pool)
  1040. {
  1041. RETURN_ERROR_IF(cctx->streamStage != zcss_init, stage_wrong,
  1042. "Can't ref a pool when ctx not in init stage.");
  1043. cctx->pool = pool;
  1044. return 0;
  1045. }
  1046. size_t ZSTD_CCtx_refPrefix(ZSTD_CCtx* cctx, const void* prefix, size_t prefixSize)
  1047. {
  1048. return ZSTD_CCtx_refPrefix_advanced(cctx, prefix, prefixSize, ZSTD_dct_rawContent);
  1049. }
  1050. size_t ZSTD_CCtx_refPrefix_advanced(
  1051. ZSTD_CCtx* cctx, const void* prefix, size_t prefixSize, ZSTD_dictContentType_e dictContentType)
  1052. {
  1053. RETURN_ERROR_IF(cctx->streamStage != zcss_init, stage_wrong,
  1054. "Can't ref a prefix when ctx not in init stage.");
  1055. ZSTD_clearAllDicts(cctx);
  1056. if (prefix != NULL && prefixSize > 0) {
  1057. cctx->prefixDict.dict = prefix;
  1058. cctx->prefixDict.dictSize = prefixSize;
  1059. cctx->prefixDict.dictContentType = dictContentType;
  1060. }
  1061. return 0;
  1062. }
  1063. /*! ZSTD_CCtx_reset() :
  1064. * Also dumps dictionary */
  1065. size_t ZSTD_CCtx_reset(ZSTD_CCtx* cctx, ZSTD_ResetDirective reset)
  1066. {
  1067. if ( (reset == ZSTD_reset_session_only)
  1068. || (reset == ZSTD_reset_session_and_parameters) ) {
  1069. cctx->streamStage = zcss_init;
  1070. cctx->pledgedSrcSizePlusOne = 0;
  1071. }
  1072. if ( (reset == ZSTD_reset_parameters)
  1073. || (reset == ZSTD_reset_session_and_parameters) ) {
  1074. RETURN_ERROR_IF(cctx->streamStage != zcss_init, stage_wrong,
  1075. "Can't reset parameters only when not in init stage.");
  1076. ZSTD_clearAllDicts(cctx);
  1077. return ZSTD_CCtxParams_reset(&cctx->requestedParams);
  1078. }
  1079. return 0;
  1080. }
  1081. /** ZSTD_checkCParams() :
  1082. control CParam values remain within authorized range.
  1083. @return : 0, or an error code if one value is beyond authorized range */
  1084. size_t ZSTD_checkCParams(ZSTD_compressionParameters cParams)
  1085. {
  1086. BOUNDCHECK(ZSTD_c_windowLog, (int)cParams.windowLog);
  1087. BOUNDCHECK(ZSTD_c_chainLog, (int)cParams.chainLog);
  1088. BOUNDCHECK(ZSTD_c_hashLog, (int)cParams.hashLog);
  1089. BOUNDCHECK(ZSTD_c_searchLog, (int)cParams.searchLog);
  1090. BOUNDCHECK(ZSTD_c_minMatch, (int)cParams.minMatch);
  1091. BOUNDCHECK(ZSTD_c_targetLength,(int)cParams.targetLength);
  1092. BOUNDCHECK(ZSTD_c_strategy, cParams.strategy);
  1093. return 0;
  1094. }
  1095. /** ZSTD_clampCParams() :
  1096. * make CParam values within valid range.
  1097. * @return : valid CParams */
  1098. static ZSTD_compressionParameters
  1099. ZSTD_clampCParams(ZSTD_compressionParameters cParams)
  1100. {
  1101. # define CLAMP_TYPE(cParam, val, type) { \
  1102. ZSTD_bounds const bounds = ZSTD_cParam_getBounds(cParam); \
  1103. if ((int)val<bounds.lowerBound) val=(type)bounds.lowerBound; \
  1104. else if ((int)val>bounds.upperBound) val=(type)bounds.upperBound; \
  1105. }
  1106. # define CLAMP(cParam, val) CLAMP_TYPE(cParam, val, unsigned)
  1107. CLAMP(ZSTD_c_windowLog, cParams.windowLog);
  1108. CLAMP(ZSTD_c_chainLog, cParams.chainLog);
  1109. CLAMP(ZSTD_c_hashLog, cParams.hashLog);
  1110. CLAMP(ZSTD_c_searchLog, cParams.searchLog);
  1111. CLAMP(ZSTD_c_minMatch, cParams.minMatch);
  1112. CLAMP(ZSTD_c_targetLength,cParams.targetLength);
  1113. CLAMP_TYPE(ZSTD_c_strategy,cParams.strategy, ZSTD_strategy);
  1114. return cParams;
  1115. }
  1116. /** ZSTD_cycleLog() :
  1117. * condition for correct operation : hashLog > 1 */
  1118. U32 ZSTD_cycleLog(U32 hashLog, ZSTD_strategy strat)
  1119. {
  1120. U32 const btScale = ((U32)strat >= (U32)ZSTD_btlazy2);
  1121. return hashLog - btScale;
  1122. }
  1123. /** ZSTD_dictAndWindowLog() :
  1124. * Returns an adjusted window log that is large enough to fit the source and the dictionary.
  1125. * The zstd format says that the entire dictionary is valid if one byte of the dictionary
  1126. * is within the window. So the hashLog and chainLog should be large enough to reference both
  1127. * the dictionary and the window. So we must use this adjusted dictAndWindowLog when downsizing
  1128. * the hashLog and windowLog.
  1129. * NOTE: srcSize must not be ZSTD_CONTENTSIZE_UNKNOWN.
  1130. */
  1131. static U32 ZSTD_dictAndWindowLog(U32 windowLog, U64 srcSize, U64 dictSize)
  1132. {
  1133. const U64 maxWindowSize = 1ULL << ZSTD_WINDOWLOG_MAX;
  1134. /* No dictionary ==> No change */
  1135. if (dictSize == 0) {
  1136. return windowLog;
  1137. }
  1138. assert(windowLog <= ZSTD_WINDOWLOG_MAX);
  1139. assert(srcSize != ZSTD_CONTENTSIZE_UNKNOWN); /* Handled in ZSTD_adjustCParams_internal() */
  1140. {
  1141. U64 const windowSize = 1ULL << windowLog;
  1142. U64 const dictAndWindowSize = dictSize + windowSize;
  1143. /* If the window size is already large enough to fit both the source and the dictionary
  1144. * then just use the window size. Otherwise adjust so that it fits the dictionary and
  1145. * the window.
  1146. */
  1147. if (windowSize >= dictSize + srcSize) {
  1148. return windowLog; /* Window size large enough already */
  1149. } else if (dictAndWindowSize >= maxWindowSize) {
  1150. return ZSTD_WINDOWLOG_MAX; /* Larger than max window log */
  1151. } else {
  1152. return ZSTD_highbit32((U32)dictAndWindowSize - 1) + 1;
  1153. }
  1154. }
  1155. }
  1156. /** ZSTD_adjustCParams_internal() :
  1157. * optimize `cPar` for a specified input (`srcSize` and `dictSize`).
  1158. * mostly downsize to reduce memory consumption and initialization latency.
  1159. * `srcSize` can be ZSTD_CONTENTSIZE_UNKNOWN when not known.
  1160. * `mode` is the mode for parameter adjustment. See docs for `ZSTD_cParamMode_e`.
  1161. * note : `srcSize==0` means 0!
  1162. * condition : cPar is presumed validated (can be checked using ZSTD_checkCParams()). */
  1163. static ZSTD_compressionParameters
  1164. ZSTD_adjustCParams_internal(ZSTD_compressionParameters cPar,
  1165. unsigned long long srcSize,
  1166. size_t dictSize,
  1167. ZSTD_cParamMode_e mode)
  1168. {
  1169. const U64 minSrcSize = 513; /* (1<<9) + 1 */
  1170. const U64 maxWindowResize = 1ULL << (ZSTD_WINDOWLOG_MAX-1);
  1171. assert(ZSTD_checkCParams(cPar)==0);
  1172. switch (mode) {
  1173. case ZSTD_cpm_unknown:
  1174. case ZSTD_cpm_noAttachDict:
  1175. /* If we don't know the source size, don't make any
  1176. * assumptions about it. We will already have selected
  1177. * smaller parameters if a dictionary is in use.
  1178. */
  1179. break;
  1180. case ZSTD_cpm_createCDict:
  1181. /* Assume a small source size when creating a dictionary
  1182. * with an unkown source size.
  1183. */
  1184. if (dictSize && srcSize == ZSTD_CONTENTSIZE_UNKNOWN)
  1185. srcSize = minSrcSize;
  1186. break;
  1187. case ZSTD_cpm_attachDict:
  1188. /* Dictionary has its own dedicated parameters which have
  1189. * already been selected. We are selecting parameters
  1190. * for only the source.
  1191. */
  1192. dictSize = 0;
  1193. break;
  1194. default:
  1195. assert(0);
  1196. break;
  1197. }
  1198. /* resize windowLog if input is small enough, to use less memory */
  1199. if ( (srcSize < maxWindowResize)
  1200. && (dictSize < maxWindowResize) ) {
  1201. U32 const tSize = (U32)(srcSize + dictSize);
  1202. static U32 const hashSizeMin = 1 << ZSTD_HASHLOG_MIN;
  1203. U32 const srcLog = (tSize < hashSizeMin) ? ZSTD_HASHLOG_MIN :
  1204. ZSTD_highbit32(tSize-1) + 1;
  1205. if (cPar.windowLog > srcLog) cPar.windowLog = srcLog;
  1206. }
  1207. if (srcSize != ZSTD_CONTENTSIZE_UNKNOWN) {
  1208. U32 const dictAndWindowLog = ZSTD_dictAndWindowLog(cPar.windowLog, (U64)srcSize, (U64)dictSize);
  1209. U32 const cycleLog = ZSTD_cycleLog(cPar.chainLog, cPar.strategy);
  1210. if (cPar.hashLog > dictAndWindowLog+1) cPar.hashLog = dictAndWindowLog+1;
  1211. if (cycleLog > dictAndWindowLog)
  1212. cPar.chainLog -= (cycleLog - dictAndWindowLog);
  1213. }
  1214. if (cPar.windowLog < ZSTD_WINDOWLOG_ABSOLUTEMIN)
  1215. cPar.windowLog = ZSTD_WINDOWLOG_ABSOLUTEMIN; /* minimum wlog required for valid frame header */
  1216. return cPar;
  1217. }
  1218. ZSTD_compressionParameters
  1219. ZSTD_adjustCParams(ZSTD_compressionParameters cPar,
  1220. unsigned long long srcSize,
  1221. size_t dictSize)
  1222. {
  1223. cPar = ZSTD_clampCParams(cPar); /* resulting cPar is necessarily valid (all parameters within range) */
  1224. if (srcSize == 0) srcSize = ZSTD_CONTENTSIZE_UNKNOWN;
  1225. return ZSTD_adjustCParams_internal(cPar, srcSize, dictSize, ZSTD_cpm_unknown);
  1226. }
  1227. static ZSTD_compressionParameters ZSTD_getCParams_internal(int compressionLevel, unsigned long long srcSizeHint, size_t dictSize, ZSTD_cParamMode_e mode);
  1228. static ZSTD_parameters ZSTD_getParams_internal(int compressionLevel, unsigned long long srcSizeHint, size_t dictSize, ZSTD_cParamMode_e mode);
  1229. static void ZSTD_overrideCParams(
  1230. ZSTD_compressionParameters* cParams,
  1231. const ZSTD_compressionParameters* overrides)
  1232. {
  1233. if (overrides->windowLog) cParams->windowLog = overrides->windowLog;
  1234. if (overrides->hashLog) cParams->hashLog = overrides->hashLog;
  1235. if (overrides->chainLog) cParams->chainLog = overrides->chainLog;
  1236. if (overrides->searchLog) cParams->searchLog = overrides->searchLog;
  1237. if (overrides->minMatch) cParams->minMatch = overrides->minMatch;
  1238. if (overrides->targetLength) cParams->targetLength = overrides->targetLength;
  1239. if (overrides->strategy) cParams->strategy = overrides->strategy;
  1240. }
  1241. ZSTD_compressionParameters ZSTD_getCParamsFromCCtxParams(
  1242. const ZSTD_CCtx_params* CCtxParams, U64 srcSizeHint, size_t dictSize, ZSTD_cParamMode_e mode)
  1243. {
  1244. ZSTD_compressionParameters cParams;
  1245. if (srcSizeHint == ZSTD_CONTENTSIZE_UNKNOWN && CCtxParams->srcSizeHint > 0) {
  1246. srcSizeHint = CCtxParams->srcSizeHint;
  1247. }
  1248. cParams = ZSTD_getCParams_internal(CCtxParams->compressionLevel, srcSizeHint, dictSize, mode);
  1249. if (CCtxParams->ldmParams.enableLdm) cParams.windowLog = ZSTD_LDM_DEFAULT_WINDOW_LOG;
  1250. ZSTD_overrideCParams(&cParams, &CCtxParams->cParams);
  1251. assert(!ZSTD_checkCParams(cParams));
  1252. /* srcSizeHint == 0 means 0 */
  1253. return ZSTD_adjustCParams_internal(cParams, srcSizeHint, dictSize, mode);
  1254. }
  1255. static size_t
  1256. ZSTD_sizeof_matchState(const ZSTD_compressionParameters* const cParams,
  1257. const ZSTD_useRowMatchFinderMode_e useRowMatchFinder,
  1258. const U32 enableDedicatedDictSearch,
  1259. const U32 forCCtx)
  1260. {
  1261. /* chain table size should be 0 for fast or row-hash strategies */
  1262. size_t const chainSize = ZSTD_allocateChainTable(cParams->strategy, useRowMatchFinder, enableDedicatedDictSearch && !forCCtx)
  1263. ? ((size_t)1 << cParams->chainLog)
  1264. : 0;
  1265. size_t const hSize = ((size_t)1) << cParams->hashLog;
  1266. U32 const hashLog3 = (forCCtx && cParams->minMatch==3) ? MIN(ZSTD_HASHLOG3_MAX, cParams->windowLog) : 0;
  1267. size_t const h3Size = hashLog3 ? ((size_t)1) << hashLog3 : 0;
  1268. /* We don't use ZSTD_cwksp_alloc_size() here because the tables aren't
  1269. * surrounded by redzones in ASAN. */
  1270. size_t const tableSpace = chainSize * sizeof(U32)
  1271. + hSize * sizeof(U32)
  1272. + h3Size * sizeof(U32);
  1273. size_t const optPotentialSpace =
  1274. ZSTD_cwksp_aligned_alloc_size((MaxML+1) * sizeof(U32))
  1275. + ZSTD_cwksp_aligned_alloc_size((MaxLL+1) * sizeof(U32))
  1276. + ZSTD_cwksp_aligned_alloc_size((MaxOff+1) * sizeof(U32))
  1277. + ZSTD_cwksp_aligned_alloc_size((1<<Litbits) * sizeof(U32))
  1278. + ZSTD_cwksp_aligned_alloc_size((ZSTD_OPT_NUM+1) * sizeof(ZSTD_match_t))
  1279. + ZSTD_cwksp_aligned_alloc_size((ZSTD_OPT_NUM+1) * sizeof(ZSTD_optimal_t));
  1280. size_t const lazyAdditionalSpace = ZSTD_rowMatchFinderUsed(cParams->strategy, useRowMatchFinder)
  1281. ? ZSTD_cwksp_aligned_alloc_size(hSize*sizeof(U16))
  1282. : 0;
  1283. size_t const optSpace = (forCCtx && (cParams->strategy >= ZSTD_btopt))
  1284. ? optPotentialSpace
  1285. : 0;
  1286. size_t const slackSpace = ZSTD_cwksp_slack_space_required();
  1287. /* tables are guaranteed to be sized in multiples of 64 bytes (or 16 uint32_t) */
  1288. ZSTD_STATIC_ASSERT(ZSTD_HASHLOG_MIN >= 4 && ZSTD_WINDOWLOG_MIN >= 4 && ZSTD_CHAINLOG_MIN >= 4);
  1289. assert(useRowMatchFinder != ZSTD_urm_auto);
  1290. DEBUGLOG(4, "chainSize: %u - hSize: %u - h3Size: %u",
  1291. (U32)chainSize, (U32)hSize, (U32)h3Size);
  1292. return tableSpace + optSpace + slackSpace + lazyAdditionalSpace;
  1293. }
  1294. static size_t ZSTD_estimateCCtxSize_usingCCtxParams_internal(
  1295. const ZSTD_compressionParameters* cParams,
  1296. const ldmParams_t* ldmParams,
  1297. const int isStatic,
  1298. const ZSTD_useRowMatchFinderMode_e useRowMatchFinder,
  1299. const size_t buffInSize,
  1300. const size_t buffOutSize,
  1301. const U64 pledgedSrcSize)
  1302. {
  1303. size_t const windowSize = MAX(1, (size_t)MIN(((U64)1 << cParams->windowLog), pledgedSrcSize));
  1304. size_t const blockSize = MIN(ZSTD_BLOCKSIZE_MAX, windowSize);
  1305. U32 const divider = (cParams->minMatch==3) ? 3 : 4;
  1306. size_t const maxNbSeq = blockSize / divider;
  1307. size_t const tokenSpace = ZSTD_cwksp_alloc_size(WILDCOPY_OVERLENGTH + blockSize)
  1308. + ZSTD_cwksp_aligned_alloc_size(maxNbSeq * sizeof(seqDef))
  1309. + 3 * ZSTD_cwksp_alloc_size(maxNbSeq * sizeof(BYTE));
  1310. size_t const entropySpace = ZSTD_cwksp_alloc_size(ENTROPY_WORKSPACE_SIZE);
  1311. size_t const blockStateSpace = 2 * ZSTD_cwksp_alloc_size(sizeof(ZSTD_compressedBlockState_t));
  1312. size_t const matchStateSize = ZSTD_sizeof_matchState(cParams, useRowMatchFinder, /* enableDedicatedDictSearch */ 0, /* forCCtx */ 1);
  1313. size_t const ldmSpace = ZSTD_ldm_getTableSize(*ldmParams);
  1314. size_t const maxNbLdmSeq = ZSTD_ldm_getMaxNbSeq(*ldmParams, blockSize);
  1315. size_t const ldmSeqSpace = ldmParams->enableLdm ?
  1316. ZSTD_cwksp_aligned_alloc_size(maxNbLdmSeq * sizeof(rawSeq)) : 0;
  1317. size_t const bufferSpace = ZSTD_cwksp_alloc_size(buffInSize)
  1318. + ZSTD_cwksp_alloc_size(buffOutSize);
  1319. size_t const cctxSpace = isStatic ? ZSTD_cwksp_alloc_size(sizeof(ZSTD_CCtx)) : 0;
  1320. size_t const neededSpace =
  1321. cctxSpace +
  1322. entropySpace +
  1323. blockStateSpace +
  1324. ldmSpace +
  1325. ldmSeqSpace +
  1326. matchStateSize +
  1327. tokenSpace +
  1328. bufferSpace;
  1329. DEBUGLOG(5, "estimate workspace : %u", (U32)neededSpace);
  1330. return neededSpace;
  1331. }
  1332. size_t ZSTD_estimateCCtxSize_usingCCtxParams(const ZSTD_CCtx_params* params)
  1333. {
  1334. ZSTD_compressionParameters const cParams =
  1335. ZSTD_getCParamsFromCCtxParams(params, ZSTD_CONTENTSIZE_UNKNOWN, 0, ZSTD_cpm_noAttachDict);
  1336. ZSTD_useRowMatchFinderMode_e const useRowMatchFinder = ZSTD_resolveRowMatchFinderMode(params->useRowMatchFinder,
  1337. &cParams);
  1338. RETURN_ERROR_IF(params->nbWorkers > 0, GENERIC, "Estimate CCtx size is supported for single-threaded compression only.");
  1339. /* estimateCCtxSize is for one-shot compression. So no buffers should
  1340. * be needed. However, we still allocate two 0-sized buffers, which can
  1341. * take space under ASAN. */
  1342. return ZSTD_estimateCCtxSize_usingCCtxParams_internal(
  1343. &cParams, &params->ldmParams, 1, useRowMatchFinder, 0, 0, ZSTD_CONTENTSIZE_UNKNOWN);
  1344. }
  1345. size_t ZSTD_estimateCCtxSize_usingCParams(ZSTD_compressionParameters cParams)
  1346. {
  1347. ZSTD_CCtx_params initialParams = ZSTD_makeCCtxParamsFromCParams(cParams);
  1348. if (ZSTD_rowMatchFinderSupported(cParams.strategy)) {
  1349. /* Pick bigger of not using and using row-based matchfinder for greedy and lazy strategies */
  1350. size_t noRowCCtxSize;
  1351. size_t rowCCtxSize;
  1352. initialParams.useRowMatchFinder = ZSTD_urm_disableRowMatchFinder;
  1353. noRowCCtxSize = ZSTD_estimateCCtxSize_usingCCtxParams(&initialParams);
  1354. initialParams.useRowMatchFinder = ZSTD_urm_enableRowMatchFinder;
  1355. rowCCtxSize = ZSTD_estimateCCtxSize_usingCCtxParams(&initialParams);
  1356. return MAX(noRowCCtxSize, rowCCtxSize);
  1357. } else {
  1358. return ZSTD_estimateCCtxSize_usingCCtxParams(&initialParams);
  1359. }
  1360. }
  1361. static size_t ZSTD_estimateCCtxSize_internal(int compressionLevel)
  1362. {
  1363. int tier = 0;
  1364. size_t largestSize = 0;
  1365. static const unsigned long long srcSizeTiers[4] = {16 KB, 128 KB, 256 KB, ZSTD_CONTENTSIZE_UNKNOWN};
  1366. for (; tier < 4; ++tier) {
  1367. /* Choose the set of cParams for a given level across all srcSizes that give the largest cctxSize */
  1368. ZSTD_compressionParameters const cParams = ZSTD_getCParams_internal(compressionLevel, srcSizeTiers[tier], 0, ZSTD_cpm_noAttachDict);
  1369. largestSize = MAX(ZSTD_estimateCCtxSize_usingCParams(cParams), largestSize);
  1370. }
  1371. return largestSize;
  1372. }
  1373. size_t ZSTD_estimateCCtxSize(int compressionLevel)
  1374. {
  1375. int level;
  1376. size_t memBudget = 0;
  1377. for (level=MIN(compressionLevel, 1); level<=compressionLevel; level++) {
  1378. /* Ensure monotonically increasing memory usage as compression level increases */
  1379. size_t const newMB = ZSTD_estimateCCtxSize_internal(level);
  1380. if (newMB > memBudget) memBudget = newMB;
  1381. }
  1382. return memBudget;
  1383. }
  1384. size_t ZSTD_estimateCStreamSize_usingCCtxParams(const ZSTD_CCtx_params* params)
  1385. {
  1386. RETURN_ERROR_IF(params->nbWorkers > 0, GENERIC, "Estimate CCtx size is supported for single-threaded compression only.");
  1387. { ZSTD_compressionParameters const cParams =
  1388. ZSTD_getCParamsFromCCtxParams(params, ZSTD_CONTENTSIZE_UNKNOWN, 0, ZSTD_cpm_noAttachDict);
  1389. size_t const blockSize = MIN(ZSTD_BLOCKSIZE_MAX, (size_t)1 << cParams.windowLog);
  1390. size_t const inBuffSize = (params->inBufferMode == ZSTD_bm_buffered)
  1391. ? ((size_t)1 << cParams.windowLog) + blockSize
  1392. : 0;
  1393. size_t const outBuffSize = (params->outBufferMode == ZSTD_bm_buffered)
  1394. ? ZSTD_compressBound(blockSize) + 1
  1395. : 0;
  1396. ZSTD_useRowMatchFinderMode_e const useRowMatchFinder = ZSTD_resolveRowMatchFinderMode(params->useRowMatchFinder, &params->cParams);
  1397. return ZSTD_estimateCCtxSize_usingCCtxParams_internal(
  1398. &cParams, &params->ldmParams, 1, useRowMatchFinder, inBuffSize, outBuffSize,
  1399. ZSTD_CONTENTSIZE_UNKNOWN);
  1400. }
  1401. }
  1402. size_t ZSTD_estimateCStreamSize_usingCParams(ZSTD_compressionParameters cParams)
  1403. {
  1404. ZSTD_CCtx_params initialParams = ZSTD_makeCCtxParamsFromCParams(cParams);
  1405. if (ZSTD_rowMatchFinderSupported(cParams.strategy)) {
  1406. /* Pick bigger of not using and using row-based matchfinder for greedy and lazy strategies */
  1407. size_t noRowCCtxSize;
  1408. size_t rowCCtxSize;
  1409. initialParams.useRowMatchFinder = ZSTD_urm_disableRowMatchFinder;
  1410. noRowCCtxSize = ZSTD_estimateCStreamSize_usingCCtxParams(&initialParams);
  1411. initialParams.useRowMatchFinder = ZSTD_urm_enableRowMatchFinder;
  1412. rowCCtxSize = ZSTD_estimateCStreamSize_usingCCtxParams(&initialParams);
  1413. return MAX(noRowCCtxSize, rowCCtxSize);
  1414. } else {
  1415. return ZSTD_estimateCStreamSize_usingCCtxParams(&initialParams);
  1416. }
  1417. }
  1418. static size_t ZSTD_estimateCStreamSize_internal(int compressionLevel)
  1419. {
  1420. ZSTD_compressionParameters const cParams = ZSTD_getCParams_internal(compressionLevel, ZSTD_CONTENTSIZE_UNKNOWN, 0, ZSTD_cpm_noAttachDict);
  1421. return ZSTD_estimateCStreamSize_usingCParams(cParams);
  1422. }
  1423. size_t ZSTD_estimateCStreamSize(int compressionLevel)
  1424. {
  1425. int level;
  1426. size_t memBudget = 0;
  1427. for (level=MIN(compressionLevel, 1); level<=compressionLevel; level++) {
  1428. size_t const newMB = ZSTD_estimateCStreamSize_internal(level);
  1429. if (newMB > memBudget) memBudget = newMB;
  1430. }
  1431. return memBudget;
  1432. }
  1433. /* ZSTD_getFrameProgression():
  1434. * tells how much data has been consumed (input) and produced (output) for current frame.
  1435. * able to count progression inside worker threads (non-blocking mode).
  1436. */
  1437. ZSTD_frameProgression ZSTD_getFrameProgression(const ZSTD_CCtx* cctx)
  1438. {
  1439. #ifdef ZSTD_MULTITHREAD
  1440. if (cctx->appliedParams.nbWorkers > 0) {
  1441. return ZSTDMT_getFrameProgression(cctx->mtctx);
  1442. }
  1443. #endif
  1444. { ZSTD_frameProgression fp;
  1445. size_t const buffered = (cctx->inBuff == NULL) ? 0 :
  1446. cctx->inBuffPos - cctx->inToCompress;
  1447. if (buffered) assert(cctx->inBuffPos >= cctx->inToCompress);
  1448. assert(buffered <= ZSTD_BLOCKSIZE_MAX);
  1449. fp.ingested = cctx->consumedSrcSize + buffered;
  1450. fp.consumed = cctx->consumedSrcSize;
  1451. fp.produced = cctx->producedCSize;
  1452. fp.flushed = cctx->producedCSize; /* simplified; some data might still be left within streaming output buffer */
  1453. fp.currentJobID = 0;
  1454. fp.nbActiveWorkers = 0;
  1455. return fp;
  1456. } }
  1457. /*! ZSTD_toFlushNow()
  1458. * Only useful for multithreading scenarios currently (nbWorkers >= 1).
  1459. */
  1460. size_t ZSTD_toFlushNow(ZSTD_CCtx* cctx)
  1461. {
  1462. #ifdef ZSTD_MULTITHREAD
  1463. if (cctx->appliedParams.nbWorkers > 0) {
  1464. return ZSTDMT_toFlushNow(cctx->mtctx);
  1465. }
  1466. #endif
  1467. (void)cctx;
  1468. return 0; /* over-simplification; could also check if context is currently running in streaming mode, and in which case, report how many bytes are left to be flushed within output buffer */
  1469. }
  1470. static void ZSTD_assertEqualCParams(ZSTD_compressionParameters cParams1,
  1471. ZSTD_compressionParameters cParams2)
  1472. {
  1473. (void)cParams1;
  1474. (void)cParams2;
  1475. assert(cParams1.windowLog == cParams2.windowLog);
  1476. assert(cParams1.chainLog == cParams2.chainLog);
  1477. assert(cParams1.hashLog == cParams2.hashLog);
  1478. assert(cParams1.searchLog == cParams2.searchLog);
  1479. assert(cParams1.minMatch == cParams2.minMatch);
  1480. assert(cParams1.targetLength == cParams2.targetLength);
  1481. assert(cParams1.strategy == cParams2.strategy);
  1482. }
  1483. void ZSTD_reset_compressedBlockState(ZSTD_compressedBlockState_t* bs)
  1484. {
  1485. int i;
  1486. for (i = 0; i < ZSTD_REP_NUM; ++i)
  1487. bs->rep[i] = repStartValue[i];
  1488. bs->entropy.huf.repeatMode = HUF_repeat_none;
  1489. bs->entropy.fse.offcode_repeatMode = FSE_repeat_none;
  1490. bs->entropy.fse.matchlength_repeatMode = FSE_repeat_none;
  1491. bs->entropy.fse.litlength_repeatMode = FSE_repeat_none;
  1492. }
  1493. /*! ZSTD_invalidateMatchState()
  1494. * Invalidate all the matches in the match finder tables.
  1495. * Requires nextSrc and base to be set (can be NULL).
  1496. */
  1497. static void ZSTD_invalidateMatchState(ZSTD_matchState_t* ms)
  1498. {
  1499. ZSTD_window_clear(&ms->window);
  1500. ms->nextToUpdate = ms->window.dictLimit;
  1501. ms->loadedDictEnd = 0;
  1502. ms->opt.litLengthSum = 0; /* force reset of btopt stats */
  1503. ms->dictMatchState = NULL;
  1504. }
  1505. /**
  1506. * Controls, for this matchState reset, whether the tables need to be cleared /
  1507. * prepared for the coming compression (ZSTDcrp_makeClean), or whether the
  1508. * tables can be left unclean (ZSTDcrp_leaveDirty), because we know that a
  1509. * subsequent operation will overwrite the table space anyways (e.g., copying
  1510. * the matchState contents in from a CDict).
  1511. */
  1512. typedef enum {
  1513. ZSTDcrp_makeClean,
  1514. ZSTDcrp_leaveDirty
  1515. } ZSTD_compResetPolicy_e;
  1516. /**
  1517. * Controls, for this matchState reset, whether indexing can continue where it
  1518. * left off (ZSTDirp_continue), or whether it needs to be restarted from zero
  1519. * (ZSTDirp_reset).
  1520. */
  1521. typedef enum {
  1522. ZSTDirp_continue,
  1523. ZSTDirp_reset
  1524. } ZSTD_indexResetPolicy_e;
  1525. typedef enum {
  1526. ZSTD_resetTarget_CDict,
  1527. ZSTD_resetTarget_CCtx
  1528. } ZSTD_resetTarget_e;
  1529. static size_t
  1530. ZSTD_reset_matchState(ZSTD_matchState_t* ms,
  1531. ZSTD_cwksp* ws,
  1532. const ZSTD_compressionParameters* cParams,
  1533. const ZSTD_useRowMatchFinderMode_e useRowMatchFinder,
  1534. const ZSTD_compResetPolicy_e crp,
  1535. const ZSTD_indexResetPolicy_e forceResetIndex,
  1536. const ZSTD_resetTarget_e forWho)
  1537. {
  1538. /* disable chain table allocation for fast or row-based strategies */
  1539. size_t const chainSize = ZSTD_allocateChainTable(cParams->strategy, useRowMatchFinder,
  1540. ms->dedicatedDictSearch && (forWho == ZSTD_resetTarget_CDict))
  1541. ? ((size_t)1 << cParams->chainLog)
  1542. : 0;
  1543. size_t const hSize = ((size_t)1) << cParams->hashLog;
  1544. U32 const hashLog3 = ((forWho == ZSTD_resetTarget_CCtx) && cParams->minMatch==3) ? MIN(ZSTD_HASHLOG3_MAX, cParams->windowLog) : 0;
  1545. size_t const h3Size = hashLog3 ? ((size_t)1) << hashLog3 : 0;
  1546. DEBUGLOG(4, "reset indices : %u", forceResetIndex == ZSTDirp_reset);
  1547. assert(useRowMatchFinder != ZSTD_urm_auto);
  1548. if (forceResetIndex == ZSTDirp_reset) {
  1549. ZSTD_window_init(&ms->window);
  1550. ZSTD_cwksp_mark_tables_dirty(ws);
  1551. }
  1552. ms->hashLog3 = hashLog3;
  1553. ZSTD_invalidateMatchState(ms);
  1554. assert(!ZSTD_cwksp_reserve_failed(ws)); /* check that allocation hasn't already failed */
  1555. ZSTD_cwksp_clear_tables(ws);
  1556. DEBUGLOG(5, "reserving table space");
  1557. /* table Space */
  1558. ms->hashTable = (U32*)ZSTD_cwksp_reserve_table(ws, hSize * sizeof(U32));
  1559. ms->chainTable = (U32*)ZSTD_cwksp_reserve_table(ws, chainSize * sizeof(U32));
  1560. ms->hashTable3 = (U32*)ZSTD_cwksp_reserve_table(ws, h3Size * sizeof(U32));
  1561. RETURN_ERROR_IF(ZSTD_cwksp_reserve_failed(ws), memory_allocation,
  1562. "failed a workspace allocation in ZSTD_reset_matchState");
  1563. DEBUGLOG(4, "reset table : %u", crp!=ZSTDcrp_leaveDirty);
  1564. if (crp!=ZSTDcrp_leaveDirty) {
  1565. /* reset tables only */
  1566. ZSTD_cwksp_clean_tables(ws);
  1567. }
  1568. /* opt parser space */
  1569. if ((forWho == ZSTD_resetTarget_CCtx) && (cParams->strategy >= ZSTD_btopt)) {
  1570. DEBUGLOG(4, "reserving optimal parser space");
  1571. ms->opt.litFreq = (unsigned*)ZSTD_cwksp_reserve_aligned(ws, (1<<Litbits) * sizeof(unsigned));
  1572. ms->opt.litLengthFreq = (unsigned*)ZSTD_cwksp_reserve_aligned(ws, (MaxLL+1) * sizeof(unsigned));
  1573. ms->opt.matchLengthFreq = (unsigned*)ZSTD_cwksp_reserve_aligned(ws, (MaxML+1) * sizeof(unsigned));
  1574. ms->opt.offCodeFreq = (unsigned*)ZSTD_cwksp_reserve_aligned(ws, (MaxOff+1) * sizeof(unsigned));
  1575. ms->opt.matchTable = (ZSTD_match_t*)ZSTD_cwksp_reserve_aligned(ws, (ZSTD_OPT_NUM+1) * sizeof(ZSTD_match_t));
  1576. ms->opt.priceTable = (ZSTD_optimal_t*)ZSTD_cwksp_reserve_aligned(ws, (ZSTD_OPT_NUM+1) * sizeof(ZSTD_optimal_t));
  1577. }
  1578. if (ZSTD_rowMatchFinderUsed(cParams->strategy, useRowMatchFinder)) {
  1579. { /* Row match finder needs an additional table of hashes ("tags") */
  1580. size_t const tagTableSize = hSize*sizeof(U16);
  1581. ms->tagTable = (U16*)ZSTD_cwksp_reserve_aligned(ws, tagTableSize);
  1582. if (ms->tagTable) ZSTD_memset(ms->tagTable, 0, tagTableSize);
  1583. }
  1584. { /* Switch to 32-entry rows if searchLog is 5 (or more) */
  1585. U32 const rowLog = cParams->searchLog < 5 ? 4 : 5;
  1586. assert(cParams->hashLog > rowLog);
  1587. ms->rowHashLog = cParams->hashLog - rowLog;
  1588. }
  1589. }
  1590. ms->cParams = *cParams;
  1591. RETURN_ERROR_IF(ZSTD_cwksp_reserve_failed(ws), memory_allocation,
  1592. "failed a workspace allocation in ZSTD_reset_matchState");
  1593. return 0;
  1594. }
  1595. /* ZSTD_indexTooCloseToMax() :
  1596. * minor optimization : prefer memset() rather than reduceIndex()
  1597. * which is measurably slow in some circumstances (reported for Visual Studio).
  1598. * Works when re-using a context for a lot of smallish inputs :
  1599. * if all inputs are smaller than ZSTD_INDEXOVERFLOW_MARGIN,
  1600. * memset() will be triggered before reduceIndex().
  1601. */
  1602. #define ZSTD_INDEXOVERFLOW_MARGIN (16 MB)
  1603. static int ZSTD_indexTooCloseToMax(ZSTD_window_t w)
  1604. {
  1605. return (size_t)(w.nextSrc - w.base) > (ZSTD_CURRENT_MAX - ZSTD_INDEXOVERFLOW_MARGIN);
  1606. }
  1607. /** ZSTD_dictTooBig():
  1608. * When dictionaries are larger than ZSTD_CHUNKSIZE_MAX they can't be loaded in
  1609. * one go generically. So we ensure that in that case we reset the tables to zero,
  1610. * so that we can load as much of the dictionary as possible.
  1611. */
  1612. static int ZSTD_dictTooBig(size_t const loadedDictSize)
  1613. {
  1614. return loadedDictSize > ZSTD_CHUNKSIZE_MAX;
  1615. }
  1616. /*! ZSTD_resetCCtx_internal() :
  1617. * @param loadedDictSize The size of the dictionary to be loaded
  1618. * into the context, if any. If no dictionary is used, or the
  1619. * dictionary is being attached / copied, then pass 0.
  1620. * note : `params` are assumed fully validated at this stage.
  1621. */
  1622. static size_t ZSTD_resetCCtx_internal(ZSTD_CCtx* zc,
  1623. ZSTD_CCtx_params const* params,
  1624. U64 const pledgedSrcSize,
  1625. size_t const loadedDictSize,
  1626. ZSTD_compResetPolicy_e const crp,
  1627. ZSTD_buffered_policy_e const zbuff)
  1628. {
  1629. ZSTD_cwksp* const ws = &zc->workspace;
  1630. DEBUGLOG(4, "ZSTD_resetCCtx_internal: pledgedSrcSize=%u, wlog=%u, useRowMatchFinder=%d",
  1631. (U32)pledgedSrcSize, params->cParams.windowLog, (int)params->useRowMatchFinder);
  1632. assert(!ZSTD_isError(ZSTD_checkCParams(params->cParams)));
  1633. zc->isFirstBlock = 1;
  1634. /* Set applied params early so we can modify them for LDM,
  1635. * and point params at the applied params.
  1636. */
  1637. zc->appliedParams = *params;
  1638. params = &zc->appliedParams;
  1639. assert(params->useRowMatchFinder != ZSTD_urm_auto);
  1640. if (params->ldmParams.enableLdm) {
  1641. /* Adjust long distance matching parameters */
  1642. ZSTD_ldm_adjustParameters(&zc->appliedParams.ldmParams, &params->cParams);
  1643. assert(params->ldmParams.hashLog >= params->ldmParams.bucketSizeLog);
  1644. assert(params->ldmParams.hashRateLog < 32);
  1645. }
  1646. { size_t const windowSize = MAX(1, (size_t)MIN(((U64)1 << params->cParams.windowLog), pledgedSrcSize));
  1647. size_t const blockSize = MIN(ZSTD_BLOCKSIZE_MAX, windowSize);
  1648. U32 const divider = (params->cParams.minMatch==3) ? 3 : 4;
  1649. size_t const maxNbSeq = blockSize / divider;
  1650. size_t const buffOutSize = (zbuff == ZSTDb_buffered && params->outBufferMode == ZSTD_bm_buffered)
  1651. ? ZSTD_compressBound(blockSize) + 1
  1652. : 0;
  1653. size_t const buffInSize = (zbuff == ZSTDb_buffered && params->inBufferMode == ZSTD_bm_buffered)
  1654. ? windowSize + blockSize
  1655. : 0;
  1656. size_t const maxNbLdmSeq = ZSTD_ldm_getMaxNbSeq(params->ldmParams, blockSize);
  1657. int const indexTooClose = ZSTD_indexTooCloseToMax(zc->blockState.matchState.window);
  1658. int const dictTooBig = ZSTD_dictTooBig(loadedDictSize);
  1659. ZSTD_indexResetPolicy_e needsIndexReset =
  1660. (indexTooClose || dictTooBig || !zc->initialized) ? ZSTDirp_reset : ZSTDirp_continue;
  1661. size_t const neededSpace =
  1662. ZSTD_estimateCCtxSize_usingCCtxParams_internal(
  1663. &params->cParams, &params->ldmParams, zc->staticSize != 0, params->useRowMatchFinder,
  1664. buffInSize, buffOutSize, pledgedSrcSize);
  1665. int resizeWorkspace;
  1666. FORWARD_IF_ERROR(neededSpace, "cctx size estimate failed!");
  1667. if (!zc->staticSize) ZSTD_cwksp_bump_oversized_duration(ws, 0);
  1668. { /* Check if workspace is large enough, alloc a new one if needed */
  1669. int const workspaceTooSmall = ZSTD_cwksp_sizeof(ws) < neededSpace;
  1670. int const workspaceWasteful = ZSTD_cwksp_check_wasteful(ws, neededSpace);
  1671. resizeWorkspace = workspaceTooSmall || workspaceWasteful;
  1672. DEBUGLOG(4, "Need %zu B workspace", neededSpace);
  1673. DEBUGLOG(4, "windowSize: %zu - blockSize: %zu", windowSize, blockSize);
  1674. if (resizeWorkspace) {
  1675. DEBUGLOG(4, "Resize workspaceSize from %zuKB to %zuKB",
  1676. ZSTD_cwksp_sizeof(ws) >> 10,
  1677. neededSpace >> 10);
  1678. RETURN_ERROR_IF(zc->staticSize, memory_allocation, "static cctx : no resize");
  1679. needsIndexReset = ZSTDirp_reset;
  1680. ZSTD_cwksp_free(ws, zc->customMem);
  1681. FORWARD_IF_ERROR(ZSTD_cwksp_create(ws, neededSpace, zc->customMem), "");
  1682. DEBUGLOG(5, "reserving object space");
  1683. /* Statically sized space.
  1684. * entropyWorkspace never moves,
  1685. * though prev/next block swap places */
  1686. assert(ZSTD_cwksp_check_available(ws, 2 * sizeof(ZSTD_compressedBlockState_t)));
  1687. zc->blockState.prevCBlock = (ZSTD_compressedBlockState_t*) ZSTD_cwksp_reserve_object(ws, sizeof(ZSTD_compressedBlockState_t));
  1688. RETURN_ERROR_IF(zc->blockState.prevCBlock == NULL, memory_allocation, "couldn't allocate prevCBlock");
  1689. zc->blockState.nextCBlock = (ZSTD_compressedBlockState_t*) ZSTD_cwksp_reserve_object(ws, sizeof(ZSTD_compressedBlockState_t));
  1690. RETURN_ERROR_IF(zc->blockState.nextCBlock == NULL, memory_allocation, "couldn't allocate nextCBlock");
  1691. zc->entropyWorkspace = (U32*) ZSTD_cwksp_reserve_object(ws, ENTROPY_WORKSPACE_SIZE);
  1692. RETURN_ERROR_IF(zc->blockState.nextCBlock == NULL, memory_allocation, "couldn't allocate entropyWorkspace");
  1693. } }
  1694. ZSTD_cwksp_clear(ws);
  1695. /* init params */
  1696. zc->blockState.matchState.cParams = params->cParams;
  1697. zc->pledgedSrcSizePlusOne = pledgedSrcSize+1;
  1698. zc->consumedSrcSize = 0;
  1699. zc->producedCSize = 0;
  1700. if (pledgedSrcSize == ZSTD_CONTENTSIZE_UNKNOWN)
  1701. zc->appliedParams.fParams.contentSizeFlag = 0;
  1702. DEBUGLOG(4, "pledged content size : %u ; flag : %u",
  1703. (unsigned)pledgedSrcSize, zc->appliedParams.fParams.contentSizeFlag);
  1704. zc->blockSize = blockSize;
  1705. XXH64_reset(&zc->xxhState, 0);
  1706. zc->stage = ZSTDcs_init;
  1707. zc->dictID = 0;
  1708. zc->dictContentSize = 0;
  1709. ZSTD_reset_compressedBlockState(zc->blockState.prevCBlock);
  1710. /* ZSTD_wildcopy() is used to copy into the literals buffer,
  1711. * so we have to oversize the buffer by WILDCOPY_OVERLENGTH bytes.
  1712. */
  1713. zc->seqStore.litStart = ZSTD_cwksp_reserve_buffer(ws, blockSize + WILDCOPY_OVERLENGTH);
  1714. zc->seqStore.maxNbLit = blockSize;
  1715. /* buffers */
  1716. zc->bufferedPolicy = zbuff;
  1717. zc->inBuffSize = buffInSize;
  1718. zc->inBuff = (char*)ZSTD_cwksp_reserve_buffer(ws, buffInSize);
  1719. zc->outBuffSize = buffOutSize;
  1720. zc->outBuff = (char*)ZSTD_cwksp_reserve_buffer(ws, buffOutSize);
  1721. /* ldm bucketOffsets table */
  1722. if (params->ldmParams.enableLdm) {
  1723. /* TODO: avoid memset? */
  1724. size_t const numBuckets =
  1725. ((size_t)1) << (params->ldmParams.hashLog -
  1726. params->ldmParams.bucketSizeLog);
  1727. zc->ldmState.bucketOffsets = ZSTD_cwksp_reserve_buffer(ws, numBuckets);
  1728. ZSTD_memset(zc->ldmState.bucketOffsets, 0, numBuckets);
  1729. }
  1730. /* sequences storage */
  1731. ZSTD_referenceExternalSequences(zc, NULL, 0);
  1732. zc->seqStore.maxNbSeq = maxNbSeq;
  1733. zc->seqStore.llCode = ZSTD_cwksp_reserve_buffer(ws, maxNbSeq * sizeof(BYTE));
  1734. zc->seqStore.mlCode = ZSTD_cwksp_reserve_buffer(ws, maxNbSeq * sizeof(BYTE));
  1735. zc->seqStore.ofCode = ZSTD_cwksp_reserve_buffer(ws, maxNbSeq * sizeof(BYTE));
  1736. zc->seqStore.sequencesStart = (seqDef*)ZSTD_cwksp_reserve_aligned(ws, maxNbSeq * sizeof(seqDef));
  1737. FORWARD_IF_ERROR(ZSTD_reset_matchState(
  1738. &zc->blockState.matchState,
  1739. ws,
  1740. &params->cParams,
  1741. params->useRowMatchFinder,
  1742. crp,
  1743. needsIndexReset,
  1744. ZSTD_resetTarget_CCtx), "");
  1745. /* ldm hash table */
  1746. if (params->ldmParams.enableLdm) {
  1747. /* TODO: avoid memset? */
  1748. size_t const ldmHSize = ((size_t)1) << params->ldmParams.hashLog;
  1749. zc->ldmState.hashTable = (ldmEntry_t*)ZSTD_cwksp_reserve_aligned(ws, ldmHSize * sizeof(ldmEntry_t));
  1750. ZSTD_memset(zc->ldmState.hashTable, 0, ldmHSize * sizeof(ldmEntry_t));
  1751. zc->ldmSequences = (rawSeq*)ZSTD_cwksp_reserve_aligned(ws, maxNbLdmSeq * sizeof(rawSeq));
  1752. zc->maxNbLdmSequences = maxNbLdmSeq;
  1753. ZSTD_window_init(&zc->ldmState.window);
  1754. zc->ldmState.loadedDictEnd = 0;
  1755. }
  1756. assert(ZSTD_cwksp_estimated_space_within_bounds(ws, neededSpace, resizeWorkspace));
  1757. DEBUGLOG(3, "wksp: finished allocating, %zd bytes remain available", ZSTD_cwksp_available_space(ws));
  1758. zc->initialized = 1;
  1759. return 0;
  1760. }
  1761. }
  1762. /* ZSTD_invalidateRepCodes() :
  1763. * ensures next compression will not use repcodes from previous block.
  1764. * Note : only works with regular variant;
  1765. * do not use with extDict variant ! */
  1766. void ZSTD_invalidateRepCodes(ZSTD_CCtx* cctx) {
  1767. int i;
  1768. for (i=0; i<ZSTD_REP_NUM; i++) cctx->blockState.prevCBlock->rep[i] = 0;
  1769. assert(!ZSTD_window_hasExtDict(cctx->blockState.matchState.window));
  1770. }
  1771. /* These are the approximate sizes for each strategy past which copying the
  1772. * dictionary tables into the working context is faster than using them
  1773. * in-place.
  1774. */
  1775. static const size_t attachDictSizeCutoffs[ZSTD_STRATEGY_MAX+1] = {
  1776. 8 KB, /* unused */
  1777. 8 KB, /* ZSTD_fast */
  1778. 16 KB, /* ZSTD_dfast */
  1779. 32 KB, /* ZSTD_greedy */
  1780. 32 KB, /* ZSTD_lazy */
  1781. 32 KB, /* ZSTD_lazy2 */
  1782. 32 KB, /* ZSTD_btlazy2 */
  1783. 32 KB, /* ZSTD_btopt */
  1784. 8 KB, /* ZSTD_btultra */
  1785. 8 KB /* ZSTD_btultra2 */
  1786. };
  1787. static int ZSTD_shouldAttachDict(const ZSTD_CDict* cdict,
  1788. const ZSTD_CCtx_params* params,
  1789. U64 pledgedSrcSize)
  1790. {
  1791. size_t cutoff = attachDictSizeCutoffs[cdict->matchState.cParams.strategy];
  1792. int const dedicatedDictSearch = cdict->matchState.dedicatedDictSearch;
  1793. return dedicatedDictSearch
  1794. || ( ( pledgedSrcSize <= cutoff
  1795. || pledgedSrcSize == ZSTD_CONTENTSIZE_UNKNOWN
  1796. || params->attachDictPref == ZSTD_dictForceAttach )
  1797. && params->attachDictPref != ZSTD_dictForceCopy
  1798. && !params->forceWindow ); /* dictMatchState isn't correctly
  1799. * handled in _enforceMaxDist */
  1800. }
  1801. static size_t
  1802. ZSTD_resetCCtx_byAttachingCDict(ZSTD_CCtx* cctx,
  1803. const ZSTD_CDict* cdict,
  1804. ZSTD_CCtx_params params,
  1805. U64 pledgedSrcSize,
  1806. ZSTD_buffered_policy_e zbuff)
  1807. {
  1808. DEBUGLOG(4, "ZSTD_resetCCtx_byAttachingCDict() pledgedSrcSize=%llu",
  1809. (unsigned long long)pledgedSrcSize);
  1810. {
  1811. ZSTD_compressionParameters adjusted_cdict_cParams = cdict->matchState.cParams;
  1812. unsigned const windowLog = params.cParams.windowLog;
  1813. assert(windowLog != 0);
  1814. /* Resize working context table params for input only, since the dict
  1815. * has its own tables. */
  1816. /* pledgedSrcSize == 0 means 0! */
  1817. if (cdict->matchState.dedicatedDictSearch) {
  1818. ZSTD_dedicatedDictSearch_revertCParams(&adjusted_cdict_cParams);
  1819. }
  1820. params.cParams = ZSTD_adjustCParams_internal(adjusted_cdict_cParams, pledgedSrcSize,
  1821. cdict->dictContentSize, ZSTD_cpm_attachDict);
  1822. params.cParams.windowLog = windowLog;
  1823. params.useRowMatchFinder = cdict->useRowMatchFinder; /* cdict overrides */
  1824. FORWARD_IF_ERROR(ZSTD_resetCCtx_internal(cctx, &params, pledgedSrcSize,
  1825. /* loadedDictSize */ 0,
  1826. ZSTDcrp_makeClean, zbuff), "");
  1827. assert(cctx->appliedParams.cParams.strategy == adjusted_cdict_cParams.strategy);
  1828. }
  1829. { const U32 cdictEnd = (U32)( cdict->matchState.window.nextSrc
  1830. - cdict->matchState.window.base);
  1831. const U32 cdictLen = cdictEnd - cdict->matchState.window.dictLimit;
  1832. if (cdictLen == 0) {
  1833. /* don't even attach dictionaries with no contents */
  1834. DEBUGLOG(4, "skipping attaching empty dictionary");
  1835. } else {
  1836. DEBUGLOG(4, "attaching dictionary into context");
  1837. cctx->blockState.matchState.dictMatchState = &cdict->matchState;
  1838. /* prep working match state so dict matches never have negative indices
  1839. * when they are translated to the working context's index space. */
  1840. if (cctx->blockState.matchState.window.dictLimit < cdictEnd) {
  1841. cctx->blockState.matchState.window.nextSrc =
  1842. cctx->blockState.matchState.window.base + cdictEnd;
  1843. ZSTD_window_clear(&cctx->blockState.matchState.window);
  1844. }
  1845. /* loadedDictEnd is expressed within the referential of the active context */
  1846. cctx->blockState.matchState.loadedDictEnd = cctx->blockState.matchState.window.dictLimit;
  1847. } }
  1848. cctx->dictID = cdict->dictID;
  1849. cctx->dictContentSize = cdict->dictContentSize;
  1850. /* copy block state */
  1851. ZSTD_memcpy(cctx->blockState.prevCBlock, &cdict->cBlockState, sizeof(cdict->cBlockState));
  1852. return 0;
  1853. }
  1854. static size_t ZSTD_resetCCtx_byCopyingCDict(ZSTD_CCtx* cctx,
  1855. const ZSTD_CDict* cdict,
  1856. ZSTD_CCtx_params params,
  1857. U64 pledgedSrcSize,
  1858. ZSTD_buffered_policy_e zbuff)
  1859. {
  1860. const ZSTD_compressionParameters *cdict_cParams = &cdict->matchState.cParams;
  1861. assert(!cdict->matchState.dedicatedDictSearch);
  1862. DEBUGLOG(4, "ZSTD_resetCCtx_byCopyingCDict() pledgedSrcSize=%llu",
  1863. (unsigned long long)pledgedSrcSize);
  1864. { unsigned const windowLog = params.cParams.windowLog;
  1865. assert(windowLog != 0);
  1866. /* Copy only compression parameters related to tables. */
  1867. params.cParams = *cdict_cParams;
  1868. params.cParams.windowLog = windowLog;
  1869. params.useRowMatchFinder = cdict->useRowMatchFinder;
  1870. FORWARD_IF_ERROR(ZSTD_resetCCtx_internal(cctx, &params, pledgedSrcSize,
  1871. /* loadedDictSize */ 0,
  1872. ZSTDcrp_leaveDirty, zbuff), "");
  1873. assert(cctx->appliedParams.cParams.strategy == cdict_cParams->strategy);
  1874. assert(cctx->appliedParams.cParams.hashLog == cdict_cParams->hashLog);
  1875. assert(cctx->appliedParams.cParams.chainLog == cdict_cParams->chainLog);
  1876. }
  1877. ZSTD_cwksp_mark_tables_dirty(&cctx->workspace);
  1878. assert(params.useRowMatchFinder != ZSTD_urm_auto);
  1879. /* copy tables */
  1880. { size_t const chainSize = ZSTD_allocateChainTable(cdict_cParams->strategy, cdict->useRowMatchFinder, 0 /* DDS guaranteed disabled */)
  1881. ? ((size_t)1 << cdict_cParams->chainLog)
  1882. : 0;
  1883. size_t const hSize = (size_t)1 << cdict_cParams->hashLog;
  1884. ZSTD_memcpy(cctx->blockState.matchState.hashTable,
  1885. cdict->matchState.hashTable,
  1886. hSize * sizeof(U32));
  1887. /* Do not copy cdict's chainTable if cctx has parameters such that it would not use chainTable */
  1888. if (ZSTD_allocateChainTable(cctx->appliedParams.cParams.strategy, cctx->appliedParams.useRowMatchFinder, 0 /* forDDSDict */)) {
  1889. ZSTD_memcpy(cctx->blockState.matchState.chainTable,
  1890. cdict->matchState.chainTable,
  1891. chainSize * sizeof(U32));
  1892. }
  1893. /* copy tag table */
  1894. if (ZSTD_rowMatchFinderUsed(cdict_cParams->strategy, cdict->useRowMatchFinder)) {
  1895. size_t const tagTableSize = hSize*sizeof(U16);
  1896. ZSTD_memcpy(cctx->blockState.matchState.tagTable,
  1897. cdict->matchState.tagTable,
  1898. tagTableSize);
  1899. }
  1900. }
  1901. /* Zero the hashTable3, since the cdict never fills it */
  1902. { int const h3log = cctx->blockState.matchState.hashLog3;
  1903. size_t const h3Size = h3log ? ((size_t)1 << h3log) : 0;
  1904. assert(cdict->matchState.hashLog3 == 0);
  1905. ZSTD_memset(cctx->blockState.matchState.hashTable3, 0, h3Size * sizeof(U32));
  1906. }
  1907. ZSTD_cwksp_mark_tables_clean(&cctx->workspace);
  1908. /* copy dictionary offsets */
  1909. { ZSTD_matchState_t const* srcMatchState = &cdict->matchState;
  1910. ZSTD_matchState_t* dstMatchState = &cctx->blockState.matchState;
  1911. dstMatchState->window = srcMatchState->window;
  1912. dstMatchState->nextToUpdate = srcMatchState->nextToUpdate;
  1913. dstMatchState->loadedDictEnd= srcMatchState->loadedDictEnd;
  1914. }
  1915. cctx->dictID = cdict->dictID;
  1916. cctx->dictContentSize = cdict->dictContentSize;
  1917. /* copy block state */
  1918. ZSTD_memcpy(cctx->blockState.prevCBlock, &cdict->cBlockState, sizeof(cdict->cBlockState));
  1919. return 0;
  1920. }
  1921. /* We have a choice between copying the dictionary context into the working
  1922. * context, or referencing the dictionary context from the working context
  1923. * in-place. We decide here which strategy to use. */
  1924. static size_t ZSTD_resetCCtx_usingCDict(ZSTD_CCtx* cctx,
  1925. const ZSTD_CDict* cdict,
  1926. const ZSTD_CCtx_params* params,
  1927. U64 pledgedSrcSize,
  1928. ZSTD_buffered_policy_e zbuff)
  1929. {
  1930. DEBUGLOG(4, "ZSTD_resetCCtx_usingCDict (pledgedSrcSize=%u)",
  1931. (unsigned)pledgedSrcSize);
  1932. if (ZSTD_shouldAttachDict(cdict, params, pledgedSrcSize)) {
  1933. return ZSTD_resetCCtx_byAttachingCDict(
  1934. cctx, cdict, *params, pledgedSrcSize, zbuff);
  1935. } else {
  1936. return ZSTD_resetCCtx_byCopyingCDict(
  1937. cctx, cdict, *params, pledgedSrcSize, zbuff);
  1938. }
  1939. }
  1940. /*! ZSTD_copyCCtx_internal() :
  1941. * Duplicate an existing context `srcCCtx` into another one `dstCCtx`.
  1942. * Only works during stage ZSTDcs_init (i.e. after creation, but before first call to ZSTD_compressContinue()).
  1943. * The "context", in this case, refers to the hash and chain tables,
  1944. * entropy tables, and dictionary references.
  1945. * `windowLog` value is enforced if != 0, otherwise value is copied from srcCCtx.
  1946. * @return : 0, or an error code */
  1947. static size_t ZSTD_copyCCtx_internal(ZSTD_CCtx* dstCCtx,
  1948. const ZSTD_CCtx* srcCCtx,
  1949. ZSTD_frameParameters fParams,
  1950. U64 pledgedSrcSize,
  1951. ZSTD_buffered_policy_e zbuff)
  1952. {
  1953. RETURN_ERROR_IF(srcCCtx->stage!=ZSTDcs_init, stage_wrong,
  1954. "Can't copy a ctx that's not in init stage.");
  1955. DEBUGLOG(5, "ZSTD_copyCCtx_internal");
  1956. ZSTD_memcpy(&dstCCtx->customMem, &srcCCtx->customMem, sizeof(ZSTD_customMem));
  1957. { ZSTD_CCtx_params params = dstCCtx->requestedParams;
  1958. /* Copy only compression parameters related to tables. */
  1959. params.cParams = srcCCtx->appliedParams.cParams;
  1960. assert(srcCCtx->appliedParams.useRowMatchFinder != ZSTD_urm_auto);
  1961. params.useRowMatchFinder = srcCCtx->appliedParams.useRowMatchFinder;
  1962. params.fParams = fParams;
  1963. ZSTD_resetCCtx_internal(dstCCtx, &params, pledgedSrcSize,
  1964. /* loadedDictSize */ 0,
  1965. ZSTDcrp_leaveDirty, zbuff);
  1966. assert(dstCCtx->appliedParams.cParams.windowLog == srcCCtx->appliedParams.cParams.windowLog);
  1967. assert(dstCCtx->appliedParams.cParams.strategy == srcCCtx->appliedParams.cParams.strategy);
  1968. assert(dstCCtx->appliedParams.cParams.hashLog == srcCCtx->appliedParams.cParams.hashLog);
  1969. assert(dstCCtx->appliedParams.cParams.chainLog == srcCCtx->appliedParams.cParams.chainLog);
  1970. assert(dstCCtx->blockState.matchState.hashLog3 == srcCCtx->blockState.matchState.hashLog3);
  1971. }
  1972. ZSTD_cwksp_mark_tables_dirty(&dstCCtx->workspace);
  1973. /* copy tables */
  1974. { size_t const chainSize = ZSTD_allocateChainTable(srcCCtx->appliedParams.cParams.strategy,
  1975. srcCCtx->appliedParams.useRowMatchFinder,
  1976. 0 /* forDDSDict */)
  1977. ? ((size_t)1 << srcCCtx->appliedParams.cParams.chainLog)
  1978. : 0;
  1979. size_t const hSize = (size_t)1 << srcCCtx->appliedParams.cParams.hashLog;
  1980. int const h3log = srcCCtx->blockState.matchState.hashLog3;
  1981. size_t const h3Size = h3log ? ((size_t)1 << h3log) : 0;
  1982. ZSTD_memcpy(dstCCtx->blockState.matchState.hashTable,
  1983. srcCCtx->blockState.matchState.hashTable,
  1984. hSize * sizeof(U32));
  1985. ZSTD_memcpy(dstCCtx->blockState.matchState.chainTable,
  1986. srcCCtx->blockState.matchState.chainTable,
  1987. chainSize * sizeof(U32));
  1988. ZSTD_memcpy(dstCCtx->blockState.matchState.hashTable3,
  1989. srcCCtx->blockState.matchState.hashTable3,
  1990. h3Size * sizeof(U32));
  1991. }
  1992. ZSTD_cwksp_mark_tables_clean(&dstCCtx->workspace);
  1993. /* copy dictionary offsets */
  1994. {
  1995. const ZSTD_matchState_t* srcMatchState = &srcCCtx->blockState.matchState;
  1996. ZSTD_matchState_t* dstMatchState = &dstCCtx->blockState.matchState;
  1997. dstMatchState->window = srcMatchState->window;
  1998. dstMatchState->nextToUpdate = srcMatchState->nextToUpdate;
  1999. dstMatchState->loadedDictEnd= srcMatchState->loadedDictEnd;
  2000. }
  2001. dstCCtx->dictID = srcCCtx->dictID;
  2002. dstCCtx->dictContentSize = srcCCtx->dictContentSize;
  2003. /* copy block state */
  2004. ZSTD_memcpy(dstCCtx->blockState.prevCBlock, srcCCtx->blockState.prevCBlock, sizeof(*srcCCtx->blockState.prevCBlock));
  2005. return 0;
  2006. }
  2007. /*! ZSTD_copyCCtx() :
  2008. * Duplicate an existing context `srcCCtx` into another one `dstCCtx`.
  2009. * Only works during stage ZSTDcs_init (i.e. after creation, but before first call to ZSTD_compressContinue()).
  2010. * pledgedSrcSize==0 means "unknown".
  2011. * @return : 0, or an error code */
  2012. size_t ZSTD_copyCCtx(ZSTD_CCtx* dstCCtx, const ZSTD_CCtx* srcCCtx, unsigned long long pledgedSrcSize)
  2013. {
  2014. ZSTD_frameParameters fParams = { 1 /*content*/, 0 /*checksum*/, 0 /*noDictID*/ };
  2015. ZSTD_buffered_policy_e const zbuff = srcCCtx->bufferedPolicy;
  2016. ZSTD_STATIC_ASSERT((U32)ZSTDb_buffered==1);
  2017. if (pledgedSrcSize==0) pledgedSrcSize = ZSTD_CONTENTSIZE_UNKNOWN;
  2018. fParams.contentSizeFlag = (pledgedSrcSize != ZSTD_CONTENTSIZE_UNKNOWN);
  2019. return ZSTD_copyCCtx_internal(dstCCtx, srcCCtx,
  2020. fParams, pledgedSrcSize,
  2021. zbuff);
  2022. }
  2023. #define ZSTD_ROWSIZE 16
  2024. /*! ZSTD_reduceTable() :
  2025. * reduce table indexes by `reducerValue`, or squash to zero.
  2026. * PreserveMark preserves "unsorted mark" for btlazy2 strategy.
  2027. * It must be set to a clear 0/1 value, to remove branch during inlining.
  2028. * Presume table size is a multiple of ZSTD_ROWSIZE
  2029. * to help auto-vectorization */
  2030. FORCE_INLINE_TEMPLATE void
  2031. ZSTD_reduceTable_internal (U32* const table, U32 const size, U32 const reducerValue, int const preserveMark)
  2032. {
  2033. int const nbRows = (int)size / ZSTD_ROWSIZE;
  2034. int cellNb = 0;
  2035. int rowNb;
  2036. assert((size & (ZSTD_ROWSIZE-1)) == 0); /* multiple of ZSTD_ROWSIZE */
  2037. assert(size < (1U<<31)); /* can be casted to int */
  2038. #if ZSTD_MEMORY_SANITIZER && !defined (ZSTD_MSAN_DONT_POISON_WORKSPACE)
  2039. /* To validate that the table re-use logic is sound, and that we don't
  2040. * access table space that we haven't cleaned, we re-"poison" the table
  2041. * space every time we mark it dirty.
  2042. *
  2043. * This function however is intended to operate on those dirty tables and
  2044. * re-clean them. So when this function is used correctly, we can unpoison
  2045. * the memory it operated on. This introduces a blind spot though, since
  2046. * if we now try to operate on __actually__ poisoned memory, we will not
  2047. * detect that. */
  2048. __msan_unpoison(table, size * sizeof(U32));
  2049. #endif
  2050. for (rowNb=0 ; rowNb < nbRows ; rowNb++) {
  2051. int column;
  2052. for (column=0; column<ZSTD_ROWSIZE; column++) {
  2053. if (preserveMark) {
  2054. U32 const adder = (table[cellNb] == ZSTD_DUBT_UNSORTED_MARK) ? reducerValue : 0;
  2055. table[cellNb] += adder;
  2056. }
  2057. if (table[cellNb] < reducerValue) table[cellNb] = 0;
  2058. else table[cellNb] -= reducerValue;
  2059. cellNb++;
  2060. } }
  2061. }
  2062. static void ZSTD_reduceTable(U32* const table, U32 const size, U32 const reducerValue)
  2063. {
  2064. ZSTD_reduceTable_internal(table, size, reducerValue, 0);
  2065. }
  2066. static void ZSTD_reduceTable_btlazy2(U32* const table, U32 const size, U32 const reducerValue)
  2067. {
  2068. ZSTD_reduceTable_internal(table, size, reducerValue, 1);
  2069. }
  2070. /*! ZSTD_reduceIndex() :
  2071. * rescale all indexes to avoid future overflow (indexes are U32) */
  2072. static void ZSTD_reduceIndex (ZSTD_matchState_t* ms, ZSTD_CCtx_params const* params, const U32 reducerValue)
  2073. {
  2074. { U32 const hSize = (U32)1 << params->cParams.hashLog;
  2075. ZSTD_reduceTable(ms->hashTable, hSize, reducerValue);
  2076. }
  2077. if (ZSTD_allocateChainTable(params->cParams.strategy, params->useRowMatchFinder, (U32)ms->dedicatedDictSearch)) {
  2078. U32 const chainSize = (U32)1 << params->cParams.chainLog;
  2079. if (params->cParams.strategy == ZSTD_btlazy2)
  2080. ZSTD_reduceTable_btlazy2(ms->chainTable, chainSize, reducerValue);
  2081. else
  2082. ZSTD_reduceTable(ms->chainTable, chainSize, reducerValue);
  2083. }
  2084. if (ms->hashLog3) {
  2085. U32 const h3Size = (U32)1 << ms->hashLog3;
  2086. ZSTD_reduceTable(ms->hashTable3, h3Size, reducerValue);
  2087. }
  2088. }
  2089. /*-*******************************************************
  2090. * Block entropic compression
  2091. *********************************************************/
  2092. /* See doc/zstd_compression_format.md for detailed format description */
  2093. void ZSTD_seqToCodes(const seqStore_t* seqStorePtr)
  2094. {
  2095. const seqDef* const sequences = seqStorePtr->sequencesStart;
  2096. BYTE* const llCodeTable = seqStorePtr->llCode;
  2097. BYTE* const ofCodeTable = seqStorePtr->ofCode;
  2098. BYTE* const mlCodeTable = seqStorePtr->mlCode;
  2099. U32 const nbSeq = (U32)(seqStorePtr->sequences - seqStorePtr->sequencesStart);
  2100. U32 u;
  2101. assert(nbSeq <= seqStorePtr->maxNbSeq);
  2102. for (u=0; u<nbSeq; u++) {
  2103. U32 const llv = sequences[u].litLength;
  2104. U32 const mlv = sequences[u].matchLength;
  2105. llCodeTable[u] = (BYTE)ZSTD_LLcode(llv);
  2106. ofCodeTable[u] = (BYTE)ZSTD_highbit32(sequences[u].offset);
  2107. mlCodeTable[u] = (BYTE)ZSTD_MLcode(mlv);
  2108. }
  2109. if (seqStorePtr->longLengthType==ZSTD_llt_literalLength)
  2110. llCodeTable[seqStorePtr->longLengthPos] = MaxLL;
  2111. if (seqStorePtr->longLengthType==ZSTD_llt_matchLength)
  2112. mlCodeTable[seqStorePtr->longLengthPos] = MaxML;
  2113. }
  2114. /* ZSTD_useTargetCBlockSize():
  2115. * Returns if target compressed block size param is being used.
  2116. * If used, compression will do best effort to make a compressed block size to be around targetCBlockSize.
  2117. * Returns 1 if true, 0 otherwise. */
  2118. static int ZSTD_useTargetCBlockSize(const ZSTD_CCtx_params* cctxParams)
  2119. {
  2120. DEBUGLOG(5, "ZSTD_useTargetCBlockSize (targetCBlockSize=%zu)", cctxParams->targetCBlockSize);
  2121. return (cctxParams->targetCBlockSize != 0);
  2122. }
  2123. /* ZSTD_blockSplitterEnabled():
  2124. * Returns if block splitting param is being used
  2125. * If used, compression will do best effort to split a block in order to improve compression ratio.
  2126. * Returns 1 if true, 0 otherwise. */
  2127. static int ZSTD_blockSplitterEnabled(ZSTD_CCtx_params* cctxParams)
  2128. {
  2129. DEBUGLOG(5, "ZSTD_blockSplitterEnabled(splitBlocks=%d)", cctxParams->splitBlocks);
  2130. return (cctxParams->splitBlocks != 0);
  2131. }
  2132. /* Type returned by ZSTD_buildSequencesStatistics containing finalized symbol encoding types
  2133. * and size of the sequences statistics
  2134. */
  2135. typedef struct {
  2136. U32 LLtype;
  2137. U32 Offtype;
  2138. U32 MLtype;
  2139. size_t size;
  2140. size_t lastCountSize; /* Accounts for bug in 1.3.4. More detail in ZSTD_entropyCompressSeqStore_internal() */
  2141. } ZSTD_symbolEncodingTypeStats_t;
  2142. /* ZSTD_buildSequencesStatistics():
  2143. * Returns a ZSTD_symbolEncodingTypeStats_t, or a zstd error code in the `size` field.
  2144. * Modifies `nextEntropy` to have the appropriate values as a side effect.
  2145. * nbSeq must be greater than 0.
  2146. *
  2147. * entropyWkspSize must be of size at least ENTROPY_WORKSPACE_SIZE - (MaxSeq + 1)*sizeof(U32)
  2148. */
  2149. static ZSTD_symbolEncodingTypeStats_t
  2150. ZSTD_buildSequencesStatistics(seqStore_t* seqStorePtr, size_t nbSeq,
  2151. const ZSTD_fseCTables_t* prevEntropy, ZSTD_fseCTables_t* nextEntropy,
  2152. BYTE* dst, const BYTE* const dstEnd,
  2153. ZSTD_strategy strategy, unsigned* countWorkspace,
  2154. void* entropyWorkspace, size_t entropyWkspSize) {
  2155. BYTE* const ostart = dst;
  2156. const BYTE* const oend = dstEnd;
  2157. BYTE* op = ostart;
  2158. FSE_CTable* CTable_LitLength = nextEntropy->litlengthCTable;
  2159. FSE_CTable* CTable_OffsetBits = nextEntropy->offcodeCTable;
  2160. FSE_CTable* CTable_MatchLength = nextEntropy->matchlengthCTable;
  2161. const BYTE* const ofCodeTable = seqStorePtr->ofCode;
  2162. const BYTE* const llCodeTable = seqStorePtr->llCode;
  2163. const BYTE* const mlCodeTable = seqStorePtr->mlCode;
  2164. ZSTD_symbolEncodingTypeStats_t stats;
  2165. stats.lastCountSize = 0;
  2166. /* convert length/distances into codes */
  2167. ZSTD_seqToCodes(seqStorePtr);
  2168. assert(op <= oend);
  2169. assert(nbSeq != 0); /* ZSTD_selectEncodingType() divides by nbSeq */
  2170. /* build CTable for Literal Lengths */
  2171. { unsigned max = MaxLL;
  2172. size_t const mostFrequent = HIST_countFast_wksp(countWorkspace, &max, llCodeTable, nbSeq, entropyWorkspace, entropyWkspSize); /* can't fail */
  2173. DEBUGLOG(5, "Building LL table");
  2174. nextEntropy->litlength_repeatMode = prevEntropy->litlength_repeatMode;
  2175. stats.LLtype = ZSTD_selectEncodingType(&nextEntropy->litlength_repeatMode,
  2176. countWorkspace, max, mostFrequent, nbSeq,
  2177. LLFSELog, prevEntropy->litlengthCTable,
  2178. LL_defaultNorm, LL_defaultNormLog,
  2179. ZSTD_defaultAllowed, strategy);
  2180. assert(set_basic < set_compressed && set_rle < set_compressed);
  2181. assert(!(stats.LLtype < set_compressed && nextEntropy->litlength_repeatMode != FSE_repeat_none)); /* We don't copy tables */
  2182. { size_t const countSize = ZSTD_buildCTable(
  2183. op, (size_t)(oend - op),
  2184. CTable_LitLength, LLFSELog, (symbolEncodingType_e)stats.LLtype,
  2185. countWorkspace, max, llCodeTable, nbSeq,
  2186. LL_defaultNorm, LL_defaultNormLog, MaxLL,
  2187. prevEntropy->litlengthCTable,
  2188. sizeof(prevEntropy->litlengthCTable),
  2189. entropyWorkspace, entropyWkspSize);
  2190. if (ZSTD_isError(countSize)) {
  2191. DEBUGLOG(3, "ZSTD_buildCTable for LitLens failed");
  2192. stats.size = countSize;
  2193. return stats;
  2194. }
  2195. if (stats.LLtype == set_compressed)
  2196. stats.lastCountSize = countSize;
  2197. op += countSize;
  2198. assert(op <= oend);
  2199. } }
  2200. /* build CTable for Offsets */
  2201. { unsigned max = MaxOff;
  2202. size_t const mostFrequent = HIST_countFast_wksp(
  2203. countWorkspace, &max, ofCodeTable, nbSeq, entropyWorkspace, entropyWkspSize); /* can't fail */
  2204. /* We can only use the basic table if max <= DefaultMaxOff, otherwise the offsets are too large */
  2205. ZSTD_defaultPolicy_e const defaultPolicy = (max <= DefaultMaxOff) ? ZSTD_defaultAllowed : ZSTD_defaultDisallowed;
  2206. DEBUGLOG(5, "Building OF table");
  2207. nextEntropy->offcode_repeatMode = prevEntropy->offcode_repeatMode;
  2208. stats.Offtype = ZSTD_selectEncodingType(&nextEntropy->offcode_repeatMode,
  2209. countWorkspace, max, mostFrequent, nbSeq,
  2210. OffFSELog, prevEntropy->offcodeCTable,
  2211. OF_defaultNorm, OF_defaultNormLog,
  2212. defaultPolicy, strategy);
  2213. assert(!(stats.Offtype < set_compressed && nextEntropy->offcode_repeatMode != FSE_repeat_none)); /* We don't copy tables */
  2214. { size_t const countSize = ZSTD_buildCTable(
  2215. op, (size_t)(oend - op),
  2216. CTable_OffsetBits, OffFSELog, (symbolEncodingType_e)stats.Offtype,
  2217. countWorkspace, max, ofCodeTable, nbSeq,
  2218. OF_defaultNorm, OF_defaultNormLog, DefaultMaxOff,
  2219. prevEntropy->offcodeCTable,
  2220. sizeof(prevEntropy->offcodeCTable),
  2221. entropyWorkspace, entropyWkspSize);
  2222. if (ZSTD_isError(countSize)) {
  2223. DEBUGLOG(3, "ZSTD_buildCTable for Offsets failed");
  2224. stats.size = countSize;
  2225. return stats;
  2226. }
  2227. if (stats.Offtype == set_compressed)
  2228. stats.lastCountSize = countSize;
  2229. op += countSize;
  2230. assert(op <= oend);
  2231. } }
  2232. /* build CTable for MatchLengths */
  2233. { unsigned max = MaxML;
  2234. size_t const mostFrequent = HIST_countFast_wksp(
  2235. countWorkspace, &max, mlCodeTable, nbSeq, entropyWorkspace, entropyWkspSize); /* can't fail */
  2236. DEBUGLOG(5, "Building ML table (remaining space : %i)", (int)(oend-op));
  2237. nextEntropy->matchlength_repeatMode = prevEntropy->matchlength_repeatMode;
  2238. stats.MLtype = ZSTD_selectEncodingType(&nextEntropy->matchlength_repeatMode,
  2239. countWorkspace, max, mostFrequent, nbSeq,
  2240. MLFSELog, prevEntropy->matchlengthCTable,
  2241. ML_defaultNorm, ML_defaultNormLog,
  2242. ZSTD_defaultAllowed, strategy);
  2243. assert(!(stats.MLtype < set_compressed && nextEntropy->matchlength_repeatMode != FSE_repeat_none)); /* We don't copy tables */
  2244. { size_t const countSize = ZSTD_buildCTable(
  2245. op, (size_t)(oend - op),
  2246. CTable_MatchLength, MLFSELog, (symbolEncodingType_e)stats.MLtype,
  2247. countWorkspace, max, mlCodeTable, nbSeq,
  2248. ML_defaultNorm, ML_defaultNormLog, MaxML,
  2249. prevEntropy->matchlengthCTable,
  2250. sizeof(prevEntropy->matchlengthCTable),
  2251. entropyWorkspace, entropyWkspSize);
  2252. if (ZSTD_isError(countSize)) {
  2253. DEBUGLOG(3, "ZSTD_buildCTable for MatchLengths failed");
  2254. stats.size = countSize;
  2255. return stats;
  2256. }
  2257. if (stats.MLtype == set_compressed)
  2258. stats.lastCountSize = countSize;
  2259. op += countSize;
  2260. assert(op <= oend);
  2261. } }
  2262. stats.size = (size_t)(op-ostart);
  2263. return stats;
  2264. }
  2265. /* ZSTD_entropyCompressSeqStore_internal():
  2266. * compresses both literals and sequences
  2267. * Returns compressed size of block, or a zstd error.
  2268. */
  2269. MEM_STATIC size_t
  2270. ZSTD_entropyCompressSeqStore_internal(seqStore_t* seqStorePtr,
  2271. const ZSTD_entropyCTables_t* prevEntropy,
  2272. ZSTD_entropyCTables_t* nextEntropy,
  2273. const ZSTD_CCtx_params* cctxParams,
  2274. void* dst, size_t dstCapacity,
  2275. void* entropyWorkspace, size_t entropyWkspSize,
  2276. const int bmi2)
  2277. {
  2278. const int longOffsets = cctxParams->cParams.windowLog > STREAM_ACCUMULATOR_MIN;
  2279. ZSTD_strategy const strategy = cctxParams->cParams.strategy;
  2280. unsigned* count = (unsigned*)entropyWorkspace;
  2281. FSE_CTable* CTable_LitLength = nextEntropy->fse.litlengthCTable;
  2282. FSE_CTable* CTable_OffsetBits = nextEntropy->fse.offcodeCTable;
  2283. FSE_CTable* CTable_MatchLength = nextEntropy->fse.matchlengthCTable;
  2284. const seqDef* const sequences = seqStorePtr->sequencesStart;
  2285. const size_t nbSeq = seqStorePtr->sequences - seqStorePtr->sequencesStart;
  2286. const BYTE* const ofCodeTable = seqStorePtr->ofCode;
  2287. const BYTE* const llCodeTable = seqStorePtr->llCode;
  2288. const BYTE* const mlCodeTable = seqStorePtr->mlCode;
  2289. BYTE* const ostart = (BYTE*)dst;
  2290. BYTE* const oend = ostart + dstCapacity;
  2291. BYTE* op = ostart;
  2292. size_t lastCountSize;
  2293. entropyWorkspace = count + (MaxSeq + 1);
  2294. entropyWkspSize -= (MaxSeq + 1) * sizeof(*count);
  2295. DEBUGLOG(4, "ZSTD_entropyCompressSeqStore_internal (nbSeq=%zu)", nbSeq);
  2296. ZSTD_STATIC_ASSERT(HUF_WORKSPACE_SIZE >= (1<<MAX(MLFSELog,LLFSELog)));
  2297. assert(entropyWkspSize >= HUF_WORKSPACE_SIZE);
  2298. /* Compress literals */
  2299. { const BYTE* const literals = seqStorePtr->litStart;
  2300. size_t const litSize = (size_t)(seqStorePtr->lit - literals);
  2301. size_t const cSize = ZSTD_compressLiterals(
  2302. &prevEntropy->huf, &nextEntropy->huf,
  2303. cctxParams->cParams.strategy,
  2304. ZSTD_disableLiteralsCompression(cctxParams),
  2305. op, dstCapacity,
  2306. literals, litSize,
  2307. entropyWorkspace, entropyWkspSize,
  2308. bmi2);
  2309. FORWARD_IF_ERROR(cSize, "ZSTD_compressLiterals failed");
  2310. assert(cSize <= dstCapacity);
  2311. op += cSize;
  2312. }
  2313. /* Sequences Header */
  2314. RETURN_ERROR_IF((oend-op) < 3 /*max nbSeq Size*/ + 1 /*seqHead*/,
  2315. dstSize_tooSmall, "Can't fit seq hdr in output buf!");
  2316. if (nbSeq < 128) {
  2317. *op++ = (BYTE)nbSeq;
  2318. } else if (nbSeq < LONGNBSEQ) {
  2319. op[0] = (BYTE)((nbSeq>>8) + 0x80);
  2320. op[1] = (BYTE)nbSeq;
  2321. op+=2;
  2322. } else {
  2323. op[0]=0xFF;
  2324. MEM_writeLE16(op+1, (U16)(nbSeq - LONGNBSEQ));
  2325. op+=3;
  2326. }
  2327. assert(op <= oend);
  2328. if (nbSeq==0) {
  2329. /* Copy the old tables over as if we repeated them */
  2330. ZSTD_memcpy(&nextEntropy->fse, &prevEntropy->fse, sizeof(prevEntropy->fse));
  2331. return (size_t)(op - ostart);
  2332. }
  2333. {
  2334. ZSTD_symbolEncodingTypeStats_t stats;
  2335. BYTE* seqHead = op++;
  2336. /* build stats for sequences */
  2337. stats = ZSTD_buildSequencesStatistics(seqStorePtr, nbSeq,
  2338. &prevEntropy->fse, &nextEntropy->fse,
  2339. op, oend,
  2340. strategy, count,
  2341. entropyWorkspace, entropyWkspSize);
  2342. FORWARD_IF_ERROR(stats.size, "ZSTD_buildSequencesStatistics failed!");
  2343. *seqHead = (BYTE)((stats.LLtype<<6) + (stats.Offtype<<4) + (stats.MLtype<<2));
  2344. lastCountSize = stats.lastCountSize;
  2345. op += stats.size;
  2346. }
  2347. { size_t const bitstreamSize = ZSTD_encodeSequences(
  2348. op, (size_t)(oend - op),
  2349. CTable_MatchLength, mlCodeTable,
  2350. CTable_OffsetBits, ofCodeTable,
  2351. CTable_LitLength, llCodeTable,
  2352. sequences, nbSeq,
  2353. longOffsets, bmi2);
  2354. FORWARD_IF_ERROR(bitstreamSize, "ZSTD_encodeSequences failed");
  2355. op += bitstreamSize;
  2356. assert(op <= oend);
  2357. /* zstd versions <= 1.3.4 mistakenly report corruption when
  2358. * FSE_readNCount() receives a buffer < 4 bytes.
  2359. * Fixed by https://github.com/facebook/zstd/pull/1146.
  2360. * This can happen when the last set_compressed table present is 2
  2361. * bytes and the bitstream is only one byte.
  2362. * In this exceedingly rare case, we will simply emit an uncompressed
  2363. * block, since it isn't worth optimizing.
  2364. */
  2365. if (lastCountSize && (lastCountSize + bitstreamSize) < 4) {
  2366. /* lastCountSize >= 2 && bitstreamSize > 0 ==> lastCountSize == 3 */
  2367. assert(lastCountSize + bitstreamSize == 3);
  2368. DEBUGLOG(5, "Avoiding bug in zstd decoder in versions <= 1.3.4 by "
  2369. "emitting an uncompressed block.");
  2370. return 0;
  2371. }
  2372. }
  2373. DEBUGLOG(5, "compressed block size : %u", (unsigned)(op - ostart));
  2374. return (size_t)(op - ostart);
  2375. }
  2376. MEM_STATIC size_t
  2377. ZSTD_entropyCompressSeqStore(seqStore_t* seqStorePtr,
  2378. const ZSTD_entropyCTables_t* prevEntropy,
  2379. ZSTD_entropyCTables_t* nextEntropy,
  2380. const ZSTD_CCtx_params* cctxParams,
  2381. void* dst, size_t dstCapacity,
  2382. size_t srcSize,
  2383. void* entropyWorkspace, size_t entropyWkspSize,
  2384. int bmi2)
  2385. {
  2386. size_t const cSize = ZSTD_entropyCompressSeqStore_internal(
  2387. seqStorePtr, prevEntropy, nextEntropy, cctxParams,
  2388. dst, dstCapacity,
  2389. entropyWorkspace, entropyWkspSize, bmi2);
  2390. if (cSize == 0) return 0;
  2391. /* When srcSize <= dstCapacity, there is enough space to write a raw uncompressed block.
  2392. * Since we ran out of space, block must be not compressible, so fall back to raw uncompressed block.
  2393. */
  2394. if ((cSize == ERROR(dstSize_tooSmall)) & (srcSize <= dstCapacity))
  2395. return 0; /* block not compressed */
  2396. FORWARD_IF_ERROR(cSize, "ZSTD_entropyCompressSeqStore_internal failed");
  2397. /* Check compressibility */
  2398. { size_t const maxCSize = srcSize - ZSTD_minGain(srcSize, cctxParams->cParams.strategy);
  2399. if (cSize >= maxCSize) return 0; /* block not compressed */
  2400. }
  2401. DEBUGLOG(4, "ZSTD_entropyCompressSeqStore() cSize: %zu", cSize);
  2402. return cSize;
  2403. }
  2404. /* ZSTD_selectBlockCompressor() :
  2405. * Not static, but internal use only (used by long distance matcher)
  2406. * assumption : strat is a valid strategy */
  2407. ZSTD_blockCompressor ZSTD_selectBlockCompressor(ZSTD_strategy strat, ZSTD_useRowMatchFinderMode_e useRowMatchFinder, ZSTD_dictMode_e dictMode)
  2408. {
  2409. static const ZSTD_blockCompressor blockCompressor[4][ZSTD_STRATEGY_MAX+1] = {
  2410. { ZSTD_compressBlock_fast /* default for 0 */,
  2411. ZSTD_compressBlock_fast,
  2412. ZSTD_compressBlock_doubleFast,
  2413. ZSTD_compressBlock_greedy,
  2414. ZSTD_compressBlock_lazy,
  2415. ZSTD_compressBlock_lazy2,
  2416. ZSTD_compressBlock_btlazy2,
  2417. ZSTD_compressBlock_btopt,
  2418. ZSTD_compressBlock_btultra,
  2419. ZSTD_compressBlock_btultra2 },
  2420. { ZSTD_compressBlock_fast_extDict /* default for 0 */,
  2421. ZSTD_compressBlock_fast_extDict,
  2422. ZSTD_compressBlock_doubleFast_extDict,
  2423. ZSTD_compressBlock_greedy_extDict,
  2424. ZSTD_compressBlock_lazy_extDict,
  2425. ZSTD_compressBlock_lazy2_extDict,
  2426. ZSTD_compressBlock_btlazy2_extDict,
  2427. ZSTD_compressBlock_btopt_extDict,
  2428. ZSTD_compressBlock_btultra_extDict,
  2429. ZSTD_compressBlock_btultra_extDict },
  2430. { ZSTD_compressBlock_fast_dictMatchState /* default for 0 */,
  2431. ZSTD_compressBlock_fast_dictMatchState,
  2432. ZSTD_compressBlock_doubleFast_dictMatchState,
  2433. ZSTD_compressBlock_greedy_dictMatchState,
  2434. ZSTD_compressBlock_lazy_dictMatchState,
  2435. ZSTD_compressBlock_lazy2_dictMatchState,
  2436. ZSTD_compressBlock_btlazy2_dictMatchState,
  2437. ZSTD_compressBlock_btopt_dictMatchState,
  2438. ZSTD_compressBlock_btultra_dictMatchState,
  2439. ZSTD_compressBlock_btultra_dictMatchState },
  2440. { NULL /* default for 0 */,
  2441. NULL,
  2442. NULL,
  2443. ZSTD_compressBlock_greedy_dedicatedDictSearch,
  2444. ZSTD_compressBlock_lazy_dedicatedDictSearch,
  2445. ZSTD_compressBlock_lazy2_dedicatedDictSearch,
  2446. NULL,
  2447. NULL,
  2448. NULL,
  2449. NULL }
  2450. };
  2451. ZSTD_blockCompressor selectedCompressor;
  2452. ZSTD_STATIC_ASSERT((unsigned)ZSTD_fast == 1);
  2453. assert(ZSTD_cParam_withinBounds(ZSTD_c_strategy, strat));
  2454. DEBUGLOG(4, "Selected block compressor: dictMode=%d strat=%d rowMatchfinder=%d", (int)dictMode, (int)strat, (int)useRowMatchFinder);
  2455. if (ZSTD_rowMatchFinderUsed(strat, useRowMatchFinder)) {
  2456. static const ZSTD_blockCompressor rowBasedBlockCompressors[4][3] = {
  2457. { ZSTD_compressBlock_greedy_row,
  2458. ZSTD_compressBlock_lazy_row,
  2459. ZSTD_compressBlock_lazy2_row },
  2460. { ZSTD_compressBlock_greedy_extDict_row,
  2461. ZSTD_compressBlock_lazy_extDict_row,
  2462. ZSTD_compressBlock_lazy2_extDict_row },
  2463. { ZSTD_compressBlock_greedy_dictMatchState_row,
  2464. ZSTD_compressBlock_lazy_dictMatchState_row,
  2465. ZSTD_compressBlock_lazy2_dictMatchState_row },
  2466. { ZSTD_compressBlock_greedy_dedicatedDictSearch_row,
  2467. ZSTD_compressBlock_lazy_dedicatedDictSearch_row,
  2468. ZSTD_compressBlock_lazy2_dedicatedDictSearch_row }
  2469. };
  2470. DEBUGLOG(4, "Selecting a row-based matchfinder");
  2471. assert(useRowMatchFinder != ZSTD_urm_auto);
  2472. selectedCompressor = rowBasedBlockCompressors[(int)dictMode][(int)strat - (int)ZSTD_greedy];
  2473. } else {
  2474. selectedCompressor = blockCompressor[(int)dictMode][(int)strat];
  2475. }
  2476. assert(selectedCompressor != NULL);
  2477. return selectedCompressor;
  2478. }
  2479. static void ZSTD_storeLastLiterals(seqStore_t* seqStorePtr,
  2480. const BYTE* anchor, size_t lastLLSize)
  2481. {
  2482. ZSTD_memcpy(seqStorePtr->lit, anchor, lastLLSize);
  2483. seqStorePtr->lit += lastLLSize;
  2484. }
  2485. void ZSTD_resetSeqStore(seqStore_t* ssPtr)
  2486. {
  2487. ssPtr->lit = ssPtr->litStart;
  2488. ssPtr->sequences = ssPtr->sequencesStart;
  2489. ssPtr->longLengthType = ZSTD_llt_none;
  2490. }
  2491. typedef enum { ZSTDbss_compress, ZSTDbss_noCompress } ZSTD_buildSeqStore_e;
  2492. static size_t ZSTD_buildSeqStore(ZSTD_CCtx* zc, const void* src, size_t srcSize)
  2493. {
  2494. ZSTD_matchState_t* const ms = &zc->blockState.matchState;
  2495. DEBUGLOG(5, "ZSTD_buildSeqStore (srcSize=%zu)", srcSize);
  2496. assert(srcSize <= ZSTD_BLOCKSIZE_MAX);
  2497. /* Assert that we have correctly flushed the ctx params into the ms's copy */
  2498. ZSTD_assertEqualCParams(zc->appliedParams.cParams, ms->cParams);
  2499. if (srcSize < MIN_CBLOCK_SIZE+ZSTD_blockHeaderSize+1) {
  2500. if (zc->appliedParams.cParams.strategy >= ZSTD_btopt) {
  2501. ZSTD_ldm_skipRawSeqStoreBytes(&zc->externSeqStore, srcSize);
  2502. } else {
  2503. ZSTD_ldm_skipSequences(&zc->externSeqStore, srcSize, zc->appliedParams.cParams.minMatch);
  2504. }
  2505. return ZSTDbss_noCompress; /* don't even attempt compression below a certain srcSize */
  2506. }
  2507. ZSTD_resetSeqStore(&(zc->seqStore));
  2508. /* required for optimal parser to read stats from dictionary */
  2509. ms->opt.symbolCosts = &zc->blockState.prevCBlock->entropy;
  2510. /* tell the optimal parser how we expect to compress literals */
  2511. ms->opt.literalCompressionMode = zc->appliedParams.literalCompressionMode;
  2512. /* a gap between an attached dict and the current window is not safe,
  2513. * they must remain adjacent,
  2514. * and when that stops being the case, the dict must be unset */
  2515. assert(ms->dictMatchState == NULL || ms->loadedDictEnd == ms->window.dictLimit);
  2516. /* limited update after a very long match */
  2517. { const BYTE* const base = ms->window.base;
  2518. const BYTE* const istart = (const BYTE*)src;
  2519. const U32 curr = (U32)(istart-base);
  2520. if (sizeof(ptrdiff_t)==8) assert(istart - base < (ptrdiff_t)(U32)(-1)); /* ensure no overflow */
  2521. if (curr > ms->nextToUpdate + 384)
  2522. ms->nextToUpdate = curr - MIN(192, (U32)(curr - ms->nextToUpdate - 384));
  2523. }
  2524. /* select and store sequences */
  2525. { ZSTD_dictMode_e const dictMode = ZSTD_matchState_dictMode(ms);
  2526. size_t lastLLSize;
  2527. { int i;
  2528. for (i = 0; i < ZSTD_REP_NUM; ++i)
  2529. zc->blockState.nextCBlock->rep[i] = zc->blockState.prevCBlock->rep[i];
  2530. }
  2531. if (zc->externSeqStore.pos < zc->externSeqStore.size) {
  2532. assert(!zc->appliedParams.ldmParams.enableLdm);
  2533. /* Updates ldmSeqStore.pos */
  2534. lastLLSize =
  2535. ZSTD_ldm_blockCompress(&zc->externSeqStore,
  2536. ms, &zc->seqStore,
  2537. zc->blockState.nextCBlock->rep,
  2538. zc->appliedParams.useRowMatchFinder,
  2539. src, srcSize);
  2540. assert(zc->externSeqStore.pos <= zc->externSeqStore.size);
  2541. } else if (zc->appliedParams.ldmParams.enableLdm) {
  2542. rawSeqStore_t ldmSeqStore = kNullRawSeqStore;
  2543. ldmSeqStore.seq = zc->ldmSequences;
  2544. ldmSeqStore.capacity = zc->maxNbLdmSequences;
  2545. /* Updates ldmSeqStore.size */
  2546. FORWARD_IF_ERROR(ZSTD_ldm_generateSequences(&zc->ldmState, &ldmSeqStore,
  2547. &zc->appliedParams.ldmParams,
  2548. src, srcSize), "");
  2549. /* Updates ldmSeqStore.pos */
  2550. lastLLSize =
  2551. ZSTD_ldm_blockCompress(&ldmSeqStore,
  2552. ms, &zc->seqStore,
  2553. zc->blockState.nextCBlock->rep,
  2554. zc->appliedParams.useRowMatchFinder,
  2555. src, srcSize);
  2556. assert(ldmSeqStore.pos == ldmSeqStore.size);
  2557. } else { /* not long range mode */
  2558. ZSTD_blockCompressor const blockCompressor = ZSTD_selectBlockCompressor(zc->appliedParams.cParams.strategy,
  2559. zc->appliedParams.useRowMatchFinder,
  2560. dictMode);
  2561. ms->ldmSeqStore = NULL;
  2562. lastLLSize = blockCompressor(ms, &zc->seqStore, zc->blockState.nextCBlock->rep, src, srcSize);
  2563. }
  2564. { const BYTE* const lastLiterals = (const BYTE*)src + srcSize - lastLLSize;
  2565. ZSTD_storeLastLiterals(&zc->seqStore, lastLiterals, lastLLSize);
  2566. } }
  2567. return ZSTDbss_compress;
  2568. }
  2569. static void ZSTD_copyBlockSequences(ZSTD_CCtx* zc)
  2570. {
  2571. const seqStore_t* seqStore = ZSTD_getSeqStore(zc);
  2572. const seqDef* seqStoreSeqs = seqStore->sequencesStart;
  2573. size_t seqStoreSeqSize = seqStore->sequences - seqStoreSeqs;
  2574. size_t seqStoreLiteralsSize = (size_t)(seqStore->lit - seqStore->litStart);
  2575. size_t literalsRead = 0;
  2576. size_t lastLLSize;
  2577. ZSTD_Sequence* outSeqs = &zc->seqCollector.seqStart[zc->seqCollector.seqIndex];
  2578. size_t i;
  2579. repcodes_t updatedRepcodes;
  2580. assert(zc->seqCollector.seqIndex + 1 < zc->seqCollector.maxSequences);
  2581. /* Ensure we have enough space for last literals "sequence" */
  2582. assert(zc->seqCollector.maxSequences >= seqStoreSeqSize + 1);
  2583. ZSTD_memcpy(updatedRepcodes.rep, zc->blockState.prevCBlock->rep, sizeof(repcodes_t));
  2584. for (i = 0; i < seqStoreSeqSize; ++i) {
  2585. U32 rawOffset = seqStoreSeqs[i].offset - ZSTD_REP_NUM;
  2586. outSeqs[i].litLength = seqStoreSeqs[i].litLength;
  2587. outSeqs[i].matchLength = seqStoreSeqs[i].matchLength + MINMATCH;
  2588. outSeqs[i].rep = 0;
  2589. if (i == seqStore->longLengthPos) {
  2590. if (seqStore->longLengthType == ZSTD_llt_literalLength) {
  2591. outSeqs[i].litLength += 0x10000;
  2592. } else if (seqStore->longLengthType == ZSTD_llt_matchLength) {
  2593. outSeqs[i].matchLength += 0x10000;
  2594. }
  2595. }
  2596. if (seqStoreSeqs[i].offset <= ZSTD_REP_NUM) {
  2597. /* Derive the correct offset corresponding to a repcode */
  2598. outSeqs[i].rep = seqStoreSeqs[i].offset;
  2599. if (outSeqs[i].litLength != 0) {
  2600. rawOffset = updatedRepcodes.rep[outSeqs[i].rep - 1];
  2601. } else {
  2602. if (outSeqs[i].rep == 3) {
  2603. rawOffset = updatedRepcodes.rep[0] - 1;
  2604. } else {
  2605. rawOffset = updatedRepcodes.rep[outSeqs[i].rep];
  2606. }
  2607. }
  2608. }
  2609. outSeqs[i].offset = rawOffset;
  2610. /* seqStoreSeqs[i].offset == offCode+1, and ZSTD_updateRep() expects offCode
  2611. so we provide seqStoreSeqs[i].offset - 1 */
  2612. updatedRepcodes = ZSTD_updateRep(updatedRepcodes.rep,
  2613. seqStoreSeqs[i].offset - 1,
  2614. seqStoreSeqs[i].litLength == 0);
  2615. literalsRead += outSeqs[i].litLength;
  2616. }
  2617. /* Insert last literals (if any exist) in the block as a sequence with ml == off == 0.
  2618. * If there are no last literals, then we'll emit (of: 0, ml: 0, ll: 0), which is a marker
  2619. * for the block boundary, according to the API.
  2620. */
  2621. assert(seqStoreLiteralsSize >= literalsRead);
  2622. lastLLSize = seqStoreLiteralsSize - literalsRead;
  2623. outSeqs[i].litLength = (U32)lastLLSize;
  2624. outSeqs[i].matchLength = outSeqs[i].offset = outSeqs[i].rep = 0;
  2625. seqStoreSeqSize++;
  2626. zc->seqCollector.seqIndex += seqStoreSeqSize;
  2627. }
  2628. size_t ZSTD_generateSequences(ZSTD_CCtx* zc, ZSTD_Sequence* outSeqs,
  2629. size_t outSeqsSize, const void* src, size_t srcSize)
  2630. {
  2631. const size_t dstCapacity = ZSTD_compressBound(srcSize);
  2632. void* dst = ZSTD_customMalloc(dstCapacity, ZSTD_defaultCMem);
  2633. SeqCollector seqCollector;
  2634. RETURN_ERROR_IF(dst == NULL, memory_allocation, "NULL pointer!");
  2635. seqCollector.collectSequences = 1;
  2636. seqCollector.seqStart = outSeqs;
  2637. seqCollector.seqIndex = 0;
  2638. seqCollector.maxSequences = outSeqsSize;
  2639. zc->seqCollector = seqCollector;
  2640. ZSTD_compress2(zc, dst, dstCapacity, src, srcSize);
  2641. ZSTD_customFree(dst, ZSTD_defaultCMem);
  2642. return zc->seqCollector.seqIndex;
  2643. }
  2644. size_t ZSTD_mergeBlockDelimiters(ZSTD_Sequence* sequences, size_t seqsSize) {
  2645. size_t in = 0;
  2646. size_t out = 0;
  2647. for (; in < seqsSize; ++in) {
  2648. if (sequences[in].offset == 0 && sequences[in].matchLength == 0) {
  2649. if (in != seqsSize - 1) {
  2650. sequences[in+1].litLength += sequences[in].litLength;
  2651. }
  2652. } else {
  2653. sequences[out] = sequences[in];
  2654. ++out;
  2655. }
  2656. }
  2657. return out;
  2658. }
  2659. /* Unrolled loop to read four size_ts of input at a time. Returns 1 if is RLE, 0 if not. */
  2660. static int ZSTD_isRLE(const BYTE* src, size_t length) {
  2661. const BYTE* ip = src;
  2662. const BYTE value = ip[0];
  2663. const size_t valueST = (size_t)((U64)value * 0x0101010101010101ULL);
  2664. const size_t unrollSize = sizeof(size_t) * 4;
  2665. const size_t unrollMask = unrollSize - 1;
  2666. const size_t prefixLength = length & unrollMask;
  2667. size_t i;
  2668. size_t u;
  2669. if (length == 1) return 1;
  2670. /* Check if prefix is RLE first before using unrolled loop */
  2671. if (prefixLength && ZSTD_count(ip+1, ip, ip+prefixLength) != prefixLength-1) {
  2672. return 0;
  2673. }
  2674. for (i = prefixLength; i != length; i += unrollSize) {
  2675. for (u = 0; u < unrollSize; u += sizeof(size_t)) {
  2676. if (MEM_readST(ip + i + u) != valueST) {
  2677. return 0;
  2678. }
  2679. }
  2680. }
  2681. return 1;
  2682. }
  2683. /* Returns true if the given block may be RLE.
  2684. * This is just a heuristic based on the compressibility.
  2685. * It may return both false positives and false negatives.
  2686. */
  2687. static int ZSTD_maybeRLE(seqStore_t const* seqStore)
  2688. {
  2689. size_t const nbSeqs = (size_t)(seqStore->sequences - seqStore->sequencesStart);
  2690. size_t const nbLits = (size_t)(seqStore->lit - seqStore->litStart);
  2691. return nbSeqs < 4 && nbLits < 10;
  2692. }
  2693. static void ZSTD_blockState_confirmRepcodesAndEntropyTables(ZSTD_blockState_t* const bs)
  2694. {
  2695. ZSTD_compressedBlockState_t* const tmp = bs->prevCBlock;
  2696. bs->prevCBlock = bs->nextCBlock;
  2697. bs->nextCBlock = tmp;
  2698. }
  2699. /* Writes the block header */
  2700. static void writeBlockHeader(void* op, size_t cSize, size_t blockSize, U32 lastBlock) {
  2701. U32 const cBlockHeader = cSize == 1 ?
  2702. lastBlock + (((U32)bt_rle)<<1) + (U32)(blockSize << 3) :
  2703. lastBlock + (((U32)bt_compressed)<<1) + (U32)(cSize << 3);
  2704. MEM_writeLE24(op, cBlockHeader);
  2705. DEBUGLOG(3, "writeBlockHeader: cSize: %zu blockSize: %zu lastBlock: %u", cSize, blockSize, lastBlock);
  2706. }
  2707. /** ZSTD_buildBlockEntropyStats_literals() :
  2708. * Builds entropy for the literals.
  2709. * Stores literals block type (raw, rle, compressed, repeat) and
  2710. * huffman description table to hufMetadata.
  2711. * Requires ENTROPY_WORKSPACE_SIZE workspace
  2712. * @return : size of huffman description table or error code */
  2713. static size_t ZSTD_buildBlockEntropyStats_literals(void* const src, size_t srcSize,
  2714. const ZSTD_hufCTables_t* prevHuf,
  2715. ZSTD_hufCTables_t* nextHuf,
  2716. ZSTD_hufCTablesMetadata_t* hufMetadata,
  2717. const int disableLiteralsCompression,
  2718. void* workspace, size_t wkspSize)
  2719. {
  2720. BYTE* const wkspStart = (BYTE*)workspace;
  2721. BYTE* const wkspEnd = wkspStart + wkspSize;
  2722. BYTE* const countWkspStart = wkspStart;
  2723. unsigned* const countWksp = (unsigned*)workspace;
  2724. const size_t countWkspSize = (HUF_SYMBOLVALUE_MAX + 1) * sizeof(unsigned);
  2725. BYTE* const nodeWksp = countWkspStart + countWkspSize;
  2726. const size_t nodeWkspSize = wkspEnd-nodeWksp;
  2727. unsigned maxSymbolValue = HUF_SYMBOLVALUE_MAX;
  2728. unsigned huffLog = HUF_TABLELOG_DEFAULT;
  2729. HUF_repeat repeat = prevHuf->repeatMode;
  2730. DEBUGLOG(5, "ZSTD_buildBlockEntropyStats_literals (srcSize=%zu)", srcSize);
  2731. /* Prepare nextEntropy assuming reusing the existing table */
  2732. ZSTD_memcpy(nextHuf, prevHuf, sizeof(*prevHuf));
  2733. if (disableLiteralsCompression) {
  2734. DEBUGLOG(5, "set_basic - disabled");
  2735. hufMetadata->hType = set_basic;
  2736. return 0;
  2737. }
  2738. /* small ? don't even attempt compression (speed opt) */
  2739. #ifndef COMPRESS_LITERALS_SIZE_MIN
  2740. #define COMPRESS_LITERALS_SIZE_MIN 63
  2741. #endif
  2742. { size_t const minLitSize = (prevHuf->repeatMode == HUF_repeat_valid) ? 6 : COMPRESS_LITERALS_SIZE_MIN;
  2743. if (srcSize <= minLitSize) {
  2744. DEBUGLOG(5, "set_basic - too small");
  2745. hufMetadata->hType = set_basic;
  2746. return 0;
  2747. }
  2748. }
  2749. /* Scan input and build symbol stats */
  2750. { size_t const largest = HIST_count_wksp (countWksp, &maxSymbolValue, (const BYTE*)src, srcSize, workspace, wkspSize);
  2751. FORWARD_IF_ERROR(largest, "HIST_count_wksp failed");
  2752. if (largest == srcSize) {
  2753. DEBUGLOG(5, "set_rle");
  2754. hufMetadata->hType = set_rle;
  2755. return 0;
  2756. }
  2757. if (largest <= (srcSize >> 7)+4) {
  2758. DEBUGLOG(5, "set_basic - no gain");
  2759. hufMetadata->hType = set_basic;
  2760. return 0;
  2761. }
  2762. }
  2763. /* Validate the previous Huffman table */
  2764. if (repeat == HUF_repeat_check && !HUF_validateCTable((HUF_CElt const*)prevHuf->CTable, countWksp, maxSymbolValue)) {
  2765. repeat = HUF_repeat_none;
  2766. }
  2767. /* Build Huffman Tree */
  2768. ZSTD_memset(nextHuf->CTable, 0, sizeof(nextHuf->CTable));
  2769. huffLog = HUF_optimalTableLog(huffLog, srcSize, maxSymbolValue);
  2770. { size_t const maxBits = HUF_buildCTable_wksp((HUF_CElt*)nextHuf->CTable, countWksp,
  2771. maxSymbolValue, huffLog,
  2772. nodeWksp, nodeWkspSize);
  2773. FORWARD_IF_ERROR(maxBits, "HUF_buildCTable_wksp");
  2774. huffLog = (U32)maxBits;
  2775. { /* Build and write the CTable */
  2776. size_t const newCSize = HUF_estimateCompressedSize(
  2777. (HUF_CElt*)nextHuf->CTable, countWksp, maxSymbolValue);
  2778. size_t const hSize = HUF_writeCTable_wksp(
  2779. hufMetadata->hufDesBuffer, sizeof(hufMetadata->hufDesBuffer),
  2780. (HUF_CElt*)nextHuf->CTable, maxSymbolValue, huffLog,
  2781. nodeWksp, nodeWkspSize);
  2782. /* Check against repeating the previous CTable */
  2783. if (repeat != HUF_repeat_none) {
  2784. size_t const oldCSize = HUF_estimateCompressedSize(
  2785. (HUF_CElt const*)prevHuf->CTable, countWksp, maxSymbolValue);
  2786. if (oldCSize < srcSize && (oldCSize <= hSize + newCSize || hSize + 12 >= srcSize)) {
  2787. DEBUGLOG(5, "set_repeat - smaller");
  2788. ZSTD_memcpy(nextHuf, prevHuf, sizeof(*prevHuf));
  2789. hufMetadata->hType = set_repeat;
  2790. return 0;
  2791. }
  2792. }
  2793. if (newCSize + hSize >= srcSize) {
  2794. DEBUGLOG(5, "set_basic - no gains");
  2795. ZSTD_memcpy(nextHuf, prevHuf, sizeof(*prevHuf));
  2796. hufMetadata->hType = set_basic;
  2797. return 0;
  2798. }
  2799. DEBUGLOG(5, "set_compressed (hSize=%u)", (U32)hSize);
  2800. hufMetadata->hType = set_compressed;
  2801. nextHuf->repeatMode = HUF_repeat_check;
  2802. return hSize;
  2803. }
  2804. }
  2805. }
  2806. /* ZSTD_buildDummySequencesStatistics():
  2807. * Returns a ZSTD_symbolEncodingTypeStats_t with all encoding types as set_basic,
  2808. * and updates nextEntropy to the appropriate repeatMode.
  2809. */
  2810. static ZSTD_symbolEncodingTypeStats_t
  2811. ZSTD_buildDummySequencesStatistics(ZSTD_fseCTables_t* nextEntropy) {
  2812. ZSTD_symbolEncodingTypeStats_t stats = {set_basic, set_basic, set_basic, 0, 0};
  2813. nextEntropy->litlength_repeatMode = FSE_repeat_none;
  2814. nextEntropy->offcode_repeatMode = FSE_repeat_none;
  2815. nextEntropy->matchlength_repeatMode = FSE_repeat_none;
  2816. return stats;
  2817. }
  2818. /** ZSTD_buildBlockEntropyStats_sequences() :
  2819. * Builds entropy for the sequences.
  2820. * Stores symbol compression modes and fse table to fseMetadata.
  2821. * Requires ENTROPY_WORKSPACE_SIZE wksp.
  2822. * @return : size of fse tables or error code */
  2823. static size_t ZSTD_buildBlockEntropyStats_sequences(seqStore_t* seqStorePtr,
  2824. const ZSTD_fseCTables_t* prevEntropy,
  2825. ZSTD_fseCTables_t* nextEntropy,
  2826. const ZSTD_CCtx_params* cctxParams,
  2827. ZSTD_fseCTablesMetadata_t* fseMetadata,
  2828. void* workspace, size_t wkspSize)
  2829. {
  2830. ZSTD_strategy const strategy = cctxParams->cParams.strategy;
  2831. size_t const nbSeq = seqStorePtr->sequences - seqStorePtr->sequencesStart;
  2832. BYTE* const ostart = fseMetadata->fseTablesBuffer;
  2833. BYTE* const oend = ostart + sizeof(fseMetadata->fseTablesBuffer);
  2834. BYTE* op = ostart;
  2835. unsigned* countWorkspace = (unsigned*)workspace;
  2836. unsigned* entropyWorkspace = countWorkspace + (MaxSeq + 1);
  2837. size_t entropyWorkspaceSize = wkspSize - (MaxSeq + 1) * sizeof(*countWorkspace);
  2838. ZSTD_symbolEncodingTypeStats_t stats;
  2839. DEBUGLOG(5, "ZSTD_buildBlockEntropyStats_sequences (nbSeq=%zu)", nbSeq);
  2840. stats = nbSeq != 0 ? ZSTD_buildSequencesStatistics(seqStorePtr, nbSeq,
  2841. prevEntropy, nextEntropy, op, oend,
  2842. strategy, countWorkspace,
  2843. entropyWorkspace, entropyWorkspaceSize)
  2844. : ZSTD_buildDummySequencesStatistics(nextEntropy);
  2845. FORWARD_IF_ERROR(stats.size, "ZSTD_buildSequencesStatistics failed!");
  2846. fseMetadata->llType = (symbolEncodingType_e) stats.LLtype;
  2847. fseMetadata->ofType = (symbolEncodingType_e) stats.Offtype;
  2848. fseMetadata->mlType = (symbolEncodingType_e) stats.MLtype;
  2849. fseMetadata->lastCountSize = stats.lastCountSize;
  2850. return stats.size;
  2851. }
  2852. /** ZSTD_buildBlockEntropyStats() :
  2853. * Builds entropy for the block.
  2854. * Requires workspace size ENTROPY_WORKSPACE_SIZE
  2855. *
  2856. * @return : 0 on success or error code
  2857. */
  2858. size_t ZSTD_buildBlockEntropyStats(seqStore_t* seqStorePtr,
  2859. const ZSTD_entropyCTables_t* prevEntropy,
  2860. ZSTD_entropyCTables_t* nextEntropy,
  2861. const ZSTD_CCtx_params* cctxParams,
  2862. ZSTD_entropyCTablesMetadata_t* entropyMetadata,
  2863. void* workspace, size_t wkspSize)
  2864. {
  2865. size_t const litSize = seqStorePtr->lit - seqStorePtr->litStart;
  2866. entropyMetadata->hufMetadata.hufDesSize =
  2867. ZSTD_buildBlockEntropyStats_literals(seqStorePtr->litStart, litSize,
  2868. &prevEntropy->huf, &nextEntropy->huf,
  2869. &entropyMetadata->hufMetadata,
  2870. ZSTD_disableLiteralsCompression(cctxParams),
  2871. workspace, wkspSize);
  2872. FORWARD_IF_ERROR(entropyMetadata->hufMetadata.hufDesSize, "ZSTD_buildBlockEntropyStats_literals failed");
  2873. entropyMetadata->fseMetadata.fseTablesSize =
  2874. ZSTD_buildBlockEntropyStats_sequences(seqStorePtr,
  2875. &prevEntropy->fse, &nextEntropy->fse,
  2876. cctxParams,
  2877. &entropyMetadata->fseMetadata,
  2878. workspace, wkspSize);
  2879. FORWARD_IF_ERROR(entropyMetadata->fseMetadata.fseTablesSize, "ZSTD_buildBlockEntropyStats_sequences failed");
  2880. return 0;
  2881. }
  2882. /* Returns the size estimate for the literals section (header + content) of a block */
  2883. static size_t ZSTD_estimateBlockSize_literal(const BYTE* literals, size_t litSize,
  2884. const ZSTD_hufCTables_t* huf,
  2885. const ZSTD_hufCTablesMetadata_t* hufMetadata,
  2886. void* workspace, size_t wkspSize,
  2887. int writeEntropy)
  2888. {
  2889. unsigned* const countWksp = (unsigned*)workspace;
  2890. unsigned maxSymbolValue = HUF_SYMBOLVALUE_MAX;
  2891. size_t literalSectionHeaderSize = 3 + (litSize >= 1 KB) + (litSize >= 16 KB);
  2892. U32 singleStream = litSize < 256;
  2893. if (hufMetadata->hType == set_basic) return litSize;
  2894. else if (hufMetadata->hType == set_rle) return 1;
  2895. else if (hufMetadata->hType == set_compressed || hufMetadata->hType == set_repeat) {
  2896. size_t const largest = HIST_count_wksp (countWksp, &maxSymbolValue, (const BYTE*)literals, litSize, workspace, wkspSize);
  2897. if (ZSTD_isError(largest)) return litSize;
  2898. { size_t cLitSizeEstimate = HUF_estimateCompressedSize((const HUF_CElt*)huf->CTable, countWksp, maxSymbolValue);
  2899. if (writeEntropy) cLitSizeEstimate += hufMetadata->hufDesSize;
  2900. if (!singleStream) cLitSizeEstimate += 6; /* multi-stream huffman uses 6-byte jump table */
  2901. return cLitSizeEstimate + literalSectionHeaderSize;
  2902. } }
  2903. assert(0); /* impossible */
  2904. return 0;
  2905. }
  2906. /* Returns the size estimate for the FSE-compressed symbols (of, ml, ll) of a block */
  2907. static size_t ZSTD_estimateBlockSize_symbolType(symbolEncodingType_e type,
  2908. const BYTE* codeTable, size_t nbSeq, unsigned maxCode,
  2909. const FSE_CTable* fseCTable,
  2910. const U32* additionalBits,
  2911. short const* defaultNorm, U32 defaultNormLog, U32 defaultMax,
  2912. void* workspace, size_t wkspSize)
  2913. {
  2914. unsigned* const countWksp = (unsigned*)workspace;
  2915. const BYTE* ctp = codeTable;
  2916. const BYTE* const ctStart = ctp;
  2917. const BYTE* const ctEnd = ctStart + nbSeq;
  2918. size_t cSymbolTypeSizeEstimateInBits = 0;
  2919. unsigned max = maxCode;
  2920. HIST_countFast_wksp(countWksp, &max, codeTable, nbSeq, workspace, wkspSize); /* can't fail */
  2921. if (type == set_basic) {
  2922. /* We selected this encoding type, so it must be valid. */
  2923. assert(max <= defaultMax);
  2924. (void)defaultMax;
  2925. cSymbolTypeSizeEstimateInBits = ZSTD_crossEntropyCost(defaultNorm, defaultNormLog, countWksp, max);
  2926. } else if (type == set_rle) {
  2927. cSymbolTypeSizeEstimateInBits = 0;
  2928. } else if (type == set_compressed || type == set_repeat) {
  2929. cSymbolTypeSizeEstimateInBits = ZSTD_fseBitCost(fseCTable, countWksp, max);
  2930. }
  2931. if (ZSTD_isError(cSymbolTypeSizeEstimateInBits)) {
  2932. return nbSeq * 10;
  2933. }
  2934. while (ctp < ctEnd) {
  2935. if (additionalBits) cSymbolTypeSizeEstimateInBits += additionalBits[*ctp];
  2936. else cSymbolTypeSizeEstimateInBits += *ctp; /* for offset, offset code is also the number of additional bits */
  2937. ctp++;
  2938. }
  2939. return cSymbolTypeSizeEstimateInBits >> 3;
  2940. }
  2941. /* Returns the size estimate for the sequences section (header + content) of a block */
  2942. static size_t ZSTD_estimateBlockSize_sequences(const BYTE* ofCodeTable,
  2943. const BYTE* llCodeTable,
  2944. const BYTE* mlCodeTable,
  2945. size_t nbSeq,
  2946. const ZSTD_fseCTables_t* fseTables,
  2947. const ZSTD_fseCTablesMetadata_t* fseMetadata,
  2948. void* workspace, size_t wkspSize,
  2949. int writeEntropy)
  2950. {
  2951. size_t sequencesSectionHeaderSize = 1 /* seqHead */ + 1 /* min seqSize size */ + (nbSeq >= 128) + (nbSeq >= LONGNBSEQ);
  2952. size_t cSeqSizeEstimate = 0;
  2953. cSeqSizeEstimate += ZSTD_estimateBlockSize_symbolType(fseMetadata->ofType, ofCodeTable, nbSeq, MaxOff,
  2954. fseTables->offcodeCTable, NULL,
  2955. OF_defaultNorm, OF_defaultNormLog, DefaultMaxOff,
  2956. workspace, wkspSize);
  2957. cSeqSizeEstimate += ZSTD_estimateBlockSize_symbolType(fseMetadata->llType, llCodeTable, nbSeq, MaxLL,
  2958. fseTables->litlengthCTable, LL_bits,
  2959. LL_defaultNorm, LL_defaultNormLog, MaxLL,
  2960. workspace, wkspSize);
  2961. cSeqSizeEstimate += ZSTD_estimateBlockSize_symbolType(fseMetadata->mlType, mlCodeTable, nbSeq, MaxML,
  2962. fseTables->matchlengthCTable, ML_bits,
  2963. ML_defaultNorm, ML_defaultNormLog, MaxML,
  2964. workspace, wkspSize);
  2965. if (writeEntropy) cSeqSizeEstimate += fseMetadata->fseTablesSize;
  2966. return cSeqSizeEstimate + sequencesSectionHeaderSize;
  2967. }
  2968. /* Returns the size estimate for a given stream of literals, of, ll, ml */
  2969. static size_t ZSTD_estimateBlockSize(const BYTE* literals, size_t litSize,
  2970. const BYTE* ofCodeTable,
  2971. const BYTE* llCodeTable,
  2972. const BYTE* mlCodeTable,
  2973. size_t nbSeq,
  2974. const ZSTD_entropyCTables_t* entropy,
  2975. const ZSTD_entropyCTablesMetadata_t* entropyMetadata,
  2976. void* workspace, size_t wkspSize,
  2977. int writeLitEntropy, int writeSeqEntropy) {
  2978. size_t const literalsSize = ZSTD_estimateBlockSize_literal(literals, litSize,
  2979. &entropy->huf, &entropyMetadata->hufMetadata,
  2980. workspace, wkspSize, writeLitEntropy);
  2981. size_t const seqSize = ZSTD_estimateBlockSize_sequences(ofCodeTable, llCodeTable, mlCodeTable,
  2982. nbSeq, &entropy->fse, &entropyMetadata->fseMetadata,
  2983. workspace, wkspSize, writeSeqEntropy);
  2984. return seqSize + literalsSize + ZSTD_blockHeaderSize;
  2985. }
  2986. /* Builds entropy statistics and uses them for blocksize estimation.
  2987. *
  2988. * Returns the estimated compressed size of the seqStore, or a zstd error.
  2989. */
  2990. static size_t ZSTD_buildEntropyStatisticsAndEstimateSubBlockSize(seqStore_t* seqStore, const ZSTD_CCtx* zc) {
  2991. ZSTD_entropyCTablesMetadata_t entropyMetadata;
  2992. FORWARD_IF_ERROR(ZSTD_buildBlockEntropyStats(seqStore,
  2993. &zc->blockState.prevCBlock->entropy,
  2994. &zc->blockState.nextCBlock->entropy,
  2995. &zc->appliedParams,
  2996. &entropyMetadata,
  2997. zc->entropyWorkspace, ENTROPY_WORKSPACE_SIZE /* statically allocated in resetCCtx */), "");
  2998. return ZSTD_estimateBlockSize(seqStore->litStart, (size_t)(seqStore->lit - seqStore->litStart),
  2999. seqStore->ofCode, seqStore->llCode, seqStore->mlCode,
  3000. (size_t)(seqStore->sequences - seqStore->sequencesStart),
  3001. &zc->blockState.nextCBlock->entropy, &entropyMetadata, zc->entropyWorkspace, ENTROPY_WORKSPACE_SIZE,
  3002. (int)(entropyMetadata.hufMetadata.hType == set_compressed), 1);
  3003. }
  3004. /* Returns literals bytes represented in a seqStore */
  3005. static size_t ZSTD_countSeqStoreLiteralsBytes(const seqStore_t* const seqStore) {
  3006. size_t literalsBytes = 0;
  3007. size_t const nbSeqs = seqStore->sequences - seqStore->sequencesStart;
  3008. size_t i;
  3009. for (i = 0; i < nbSeqs; ++i) {
  3010. seqDef seq = seqStore->sequencesStart[i];
  3011. literalsBytes += seq.litLength;
  3012. if (i == seqStore->longLengthPos && seqStore->longLengthType == ZSTD_llt_literalLength) {
  3013. literalsBytes += 0x10000;
  3014. }
  3015. }
  3016. return literalsBytes;
  3017. }
  3018. /* Returns match bytes represented in a seqStore */
  3019. static size_t ZSTD_countSeqStoreMatchBytes(const seqStore_t* const seqStore) {
  3020. size_t matchBytes = 0;
  3021. size_t const nbSeqs = seqStore->sequences - seqStore->sequencesStart;
  3022. size_t i;
  3023. for (i = 0; i < nbSeqs; ++i) {
  3024. seqDef seq = seqStore->sequencesStart[i];
  3025. matchBytes += seq.matchLength + MINMATCH;
  3026. if (i == seqStore->longLengthPos && seqStore->longLengthType == ZSTD_llt_matchLength) {
  3027. matchBytes += 0x10000;
  3028. }
  3029. }
  3030. return matchBytes;
  3031. }
  3032. /* Derives the seqStore that is a chunk of the originalSeqStore from [startIdx, endIdx).
  3033. * Stores the result in resultSeqStore.
  3034. */
  3035. static void ZSTD_deriveSeqStoreChunk(seqStore_t* resultSeqStore,
  3036. const seqStore_t* originalSeqStore,
  3037. size_t startIdx, size_t endIdx) {
  3038. BYTE* const litEnd = originalSeqStore->lit;
  3039. size_t literalsBytes;
  3040. size_t literalsBytesPreceding = 0;
  3041. *resultSeqStore = *originalSeqStore;
  3042. if (startIdx > 0) {
  3043. resultSeqStore->sequences = originalSeqStore->sequencesStart + startIdx;
  3044. literalsBytesPreceding = ZSTD_countSeqStoreLiteralsBytes(resultSeqStore);
  3045. }
  3046. /* Move longLengthPos into the correct position if necessary */
  3047. if (originalSeqStore->longLengthType != ZSTD_llt_none) {
  3048. if (originalSeqStore->longLengthPos < startIdx || originalSeqStore->longLengthPos > endIdx) {
  3049. resultSeqStore->longLengthType = ZSTD_llt_none;
  3050. } else {
  3051. resultSeqStore->longLengthPos -= (U32)startIdx;
  3052. }
  3053. }
  3054. resultSeqStore->sequencesStart = originalSeqStore->sequencesStart + startIdx;
  3055. resultSeqStore->sequences = originalSeqStore->sequencesStart + endIdx;
  3056. literalsBytes = ZSTD_countSeqStoreLiteralsBytes(resultSeqStore);
  3057. resultSeqStore->litStart += literalsBytesPreceding;
  3058. if (endIdx == (size_t)(originalSeqStore->sequences - originalSeqStore->sequencesStart)) {
  3059. /* This accounts for possible last literals if the derived chunk reaches the end of the block */
  3060. resultSeqStore->lit = litEnd;
  3061. } else {
  3062. resultSeqStore->lit = resultSeqStore->litStart+literalsBytes;
  3063. }
  3064. resultSeqStore->llCode += startIdx;
  3065. resultSeqStore->mlCode += startIdx;
  3066. resultSeqStore->ofCode += startIdx;
  3067. }
  3068. /**
  3069. * Returns the raw offset represented by the combination of offCode, ll0, and repcode history.
  3070. * offCode must be an offCode representing a repcode, therefore in the range of [0, 2].
  3071. */
  3072. static U32 ZSTD_resolveRepcodeToRawOffset(const U32 rep[ZSTD_REP_NUM], const U32 offCode, const U32 ll0) {
  3073. U32 const adjustedOffCode = offCode + ll0;
  3074. assert(offCode < ZSTD_REP_NUM);
  3075. if (adjustedOffCode == ZSTD_REP_NUM) {
  3076. /* litlength == 0 and offCode == 2 implies selection of first repcode - 1 */
  3077. assert(rep[0] > 0);
  3078. return rep[0] - 1;
  3079. }
  3080. return rep[adjustedOffCode];
  3081. }
  3082. /**
  3083. * ZSTD_seqStore_resolveOffCodes() reconciles any possible divergences in offset history that may arise
  3084. * due to emission of RLE/raw blocks that disturb the offset history, and replaces any repcodes within
  3085. * the seqStore that may be invalid.
  3086. *
  3087. * dRepcodes are updated as would be on the decompression side. cRepcodes are updated exactly in
  3088. * accordance with the seqStore.
  3089. */
  3090. static void ZSTD_seqStore_resolveOffCodes(repcodes_t* const dRepcodes, repcodes_t* const cRepcodes,
  3091. seqStore_t* const seqStore, U32 const nbSeq) {
  3092. U32 idx = 0;
  3093. for (; idx < nbSeq; ++idx) {
  3094. seqDef* const seq = seqStore->sequencesStart + idx;
  3095. U32 const ll0 = (seq->litLength == 0);
  3096. U32 offCode = seq->offset - 1;
  3097. assert(seq->offset > 0);
  3098. if (offCode <= ZSTD_REP_MOVE) {
  3099. U32 const dRawOffset = ZSTD_resolveRepcodeToRawOffset(dRepcodes->rep, offCode, ll0);
  3100. U32 const cRawOffset = ZSTD_resolveRepcodeToRawOffset(cRepcodes->rep, offCode, ll0);
  3101. /* Adjust simulated decompression repcode history if we come across a mismatch. Replace
  3102. * the repcode with the offset it actually references, determined by the compression
  3103. * repcode history.
  3104. */
  3105. if (dRawOffset != cRawOffset) {
  3106. seq->offset = cRawOffset + ZSTD_REP_NUM;
  3107. }
  3108. }
  3109. /* Compression repcode history is always updated with values directly from the unmodified seqStore.
  3110. * Decompression repcode history may use modified seq->offset value taken from compression repcode history.
  3111. */
  3112. *dRepcodes = ZSTD_updateRep(dRepcodes->rep, seq->offset - 1, ll0);
  3113. *cRepcodes = ZSTD_updateRep(cRepcodes->rep, offCode, ll0);
  3114. }
  3115. }
  3116. /* ZSTD_compressSeqStore_singleBlock():
  3117. * Compresses a seqStore into a block with a block header, into the buffer dst.
  3118. *
  3119. * Returns the total size of that block (including header) or a ZSTD error code.
  3120. */
  3121. static size_t ZSTD_compressSeqStore_singleBlock(ZSTD_CCtx* zc, seqStore_t* const seqStore,
  3122. repcodes_t* const dRep, repcodes_t* const cRep,
  3123. void* dst, size_t dstCapacity,
  3124. const void* src, size_t srcSize,
  3125. U32 lastBlock, U32 isPartition) {
  3126. const U32 rleMaxLength = 25;
  3127. BYTE* op = (BYTE*)dst;
  3128. const BYTE* ip = (const BYTE*)src;
  3129. size_t cSize;
  3130. size_t cSeqsSize;
  3131. /* In case of an RLE or raw block, the simulated decompression repcode history must be reset */
  3132. repcodes_t const dRepOriginal = *dRep;
  3133. if (isPartition)
  3134. ZSTD_seqStore_resolveOffCodes(dRep, cRep, seqStore, (U32)(seqStore->sequences - seqStore->sequencesStart));
  3135. cSeqsSize = ZSTD_entropyCompressSeqStore(seqStore,
  3136. &zc->blockState.prevCBlock->entropy, &zc->blockState.nextCBlock->entropy,
  3137. &zc->appliedParams,
  3138. op + ZSTD_blockHeaderSize, dstCapacity - ZSTD_blockHeaderSize,
  3139. srcSize,
  3140. zc->entropyWorkspace, ENTROPY_WORKSPACE_SIZE /* statically allocated in resetCCtx */,
  3141. zc->bmi2);
  3142. FORWARD_IF_ERROR(cSeqsSize, "ZSTD_entropyCompressSeqStore failed!");
  3143. if (!zc->isFirstBlock &&
  3144. cSeqsSize < rleMaxLength &&
  3145. ZSTD_isRLE((BYTE const*)src, srcSize)) {
  3146. /* We don't want to emit our first block as a RLE even if it qualifies because
  3147. * doing so will cause the decoder (cli only) to throw a "should consume all input error."
  3148. * This is only an issue for zstd <= v1.4.3
  3149. */
  3150. cSeqsSize = 1;
  3151. }
  3152. if (zc->seqCollector.collectSequences) {
  3153. ZSTD_copyBlockSequences(zc);
  3154. ZSTD_blockState_confirmRepcodesAndEntropyTables(&zc->blockState);
  3155. return 0;
  3156. }
  3157. if (zc->blockState.prevCBlock->entropy.fse.offcode_repeatMode == FSE_repeat_valid)
  3158. zc->blockState.prevCBlock->entropy.fse.offcode_repeatMode = FSE_repeat_check;
  3159. if (cSeqsSize == 0) {
  3160. cSize = ZSTD_noCompressBlock(op, dstCapacity, ip, srcSize, lastBlock);
  3161. FORWARD_IF_ERROR(cSize, "Nocompress block failed");
  3162. DEBUGLOG(4, "Writing out nocompress block, size: %zu", cSize);
  3163. *dRep = dRepOriginal; /* reset simulated decompression repcode history */
  3164. } else if (cSeqsSize == 1) {
  3165. cSize = ZSTD_rleCompressBlock(op, dstCapacity, *ip, srcSize, lastBlock);
  3166. FORWARD_IF_ERROR(cSize, "RLE compress block failed");
  3167. DEBUGLOG(4, "Writing out RLE block, size: %zu", cSize);
  3168. *dRep = dRepOriginal; /* reset simulated decompression repcode history */
  3169. } else {
  3170. ZSTD_blockState_confirmRepcodesAndEntropyTables(&zc->blockState);
  3171. writeBlockHeader(op, cSeqsSize, srcSize, lastBlock);
  3172. cSize = ZSTD_blockHeaderSize + cSeqsSize;
  3173. DEBUGLOG(4, "Writing out compressed block, size: %zu", cSize);
  3174. }
  3175. return cSize;
  3176. }
  3177. /* Struct to keep track of where we are in our recursive calls. */
  3178. typedef struct {
  3179. U32* splitLocations; /* Array of split indices */
  3180. size_t idx; /* The current index within splitLocations being worked on */
  3181. } seqStoreSplits;
  3182. #define MIN_SEQUENCES_BLOCK_SPLITTING 300
  3183. #define MAX_NB_SPLITS 196
  3184. /* Helper function to perform the recursive search for block splits.
  3185. * Estimates the cost of seqStore prior to split, and estimates the cost of splitting the sequences in half.
  3186. * If advantageous to split, then we recurse down the two sub-blocks. If not, or if an error occurred in estimation, then
  3187. * we do not recurse.
  3188. *
  3189. * Note: The recursion depth is capped by a heuristic minimum number of sequences, defined by MIN_SEQUENCES_BLOCK_SPLITTING.
  3190. * In theory, this means the absolute largest recursion depth is 10 == log2(maxNbSeqInBlock/MIN_SEQUENCES_BLOCK_SPLITTING).
  3191. * In practice, recursion depth usually doesn't go beyond 4.
  3192. *
  3193. * Furthermore, the number of splits is capped by MAX_NB_SPLITS. At MAX_NB_SPLITS == 196 with the current existing blockSize
  3194. * maximum of 128 KB, this value is actually impossible to reach.
  3195. */
  3196. static void ZSTD_deriveBlockSplitsHelper(seqStoreSplits* splits, size_t startIdx, size_t endIdx,
  3197. const ZSTD_CCtx* zc, const seqStore_t* origSeqStore) {
  3198. seqStore_t fullSeqStoreChunk;
  3199. seqStore_t firstHalfSeqStore;
  3200. seqStore_t secondHalfSeqStore;
  3201. size_t estimatedOriginalSize;
  3202. size_t estimatedFirstHalfSize;
  3203. size_t estimatedSecondHalfSize;
  3204. size_t midIdx = (startIdx + endIdx)/2;
  3205. if (endIdx - startIdx < MIN_SEQUENCES_BLOCK_SPLITTING || splits->idx >= MAX_NB_SPLITS) {
  3206. return;
  3207. }
  3208. ZSTD_deriveSeqStoreChunk(&fullSeqStoreChunk, origSeqStore, startIdx, endIdx);
  3209. ZSTD_deriveSeqStoreChunk(&firstHalfSeqStore, origSeqStore, startIdx, midIdx);
  3210. ZSTD_deriveSeqStoreChunk(&secondHalfSeqStore, origSeqStore, midIdx, endIdx);
  3211. estimatedOriginalSize = ZSTD_buildEntropyStatisticsAndEstimateSubBlockSize(&fullSeqStoreChunk, zc);
  3212. estimatedFirstHalfSize = ZSTD_buildEntropyStatisticsAndEstimateSubBlockSize(&firstHalfSeqStore, zc);
  3213. estimatedSecondHalfSize = ZSTD_buildEntropyStatisticsAndEstimateSubBlockSize(&secondHalfSeqStore, zc);
  3214. DEBUGLOG(5, "Estimated original block size: %zu -- First half split: %zu -- Second half split: %zu",
  3215. estimatedOriginalSize, estimatedFirstHalfSize, estimatedSecondHalfSize);
  3216. if (ZSTD_isError(estimatedOriginalSize) || ZSTD_isError(estimatedFirstHalfSize) || ZSTD_isError(estimatedSecondHalfSize)) {
  3217. return;
  3218. }
  3219. if (estimatedFirstHalfSize + estimatedSecondHalfSize < estimatedOriginalSize) {
  3220. ZSTD_deriveBlockSplitsHelper(splits, startIdx, midIdx, zc, origSeqStore);
  3221. splits->splitLocations[splits->idx] = (U32)midIdx;
  3222. splits->idx++;
  3223. ZSTD_deriveBlockSplitsHelper(splits, midIdx, endIdx, zc, origSeqStore);
  3224. }
  3225. }
  3226. /* Base recursive function. Populates a table with intra-block partition indices that can improve compression ratio.
  3227. *
  3228. * Returns the number of splits made (which equals the size of the partition table - 1).
  3229. */
  3230. static size_t ZSTD_deriveBlockSplits(ZSTD_CCtx* zc, U32 partitions[], U32 nbSeq) {
  3231. seqStoreSplits splits = {partitions, 0};
  3232. if (nbSeq <= 4) {
  3233. DEBUGLOG(4, "ZSTD_deriveBlockSplits: Too few sequences to split");
  3234. /* Refuse to try and split anything with less than 4 sequences */
  3235. return 0;
  3236. }
  3237. ZSTD_deriveBlockSplitsHelper(&splits, 0, nbSeq, zc, &zc->seqStore);
  3238. splits.splitLocations[splits.idx] = nbSeq;
  3239. DEBUGLOG(5, "ZSTD_deriveBlockSplits: final nb partitions: %zu", splits.idx+1);
  3240. return splits.idx;
  3241. }
  3242. /* ZSTD_compressBlock_splitBlock():
  3243. * Attempts to split a given block into multiple blocks to improve compression ratio.
  3244. *
  3245. * Returns combined size of all blocks (which includes headers), or a ZSTD error code.
  3246. */
  3247. static size_t ZSTD_compressBlock_splitBlock_internal(ZSTD_CCtx* zc, void* dst, size_t dstCapacity,
  3248. const void* src, size_t blockSize, U32 lastBlock, U32 nbSeq) {
  3249. size_t cSize = 0;
  3250. const BYTE* ip = (const BYTE*)src;
  3251. BYTE* op = (BYTE*)dst;
  3252. U32 partitions[MAX_NB_SPLITS];
  3253. size_t i = 0;
  3254. size_t srcBytesTotal = 0;
  3255. size_t numSplits = ZSTD_deriveBlockSplits(zc, partitions, nbSeq);
  3256. seqStore_t nextSeqStore;
  3257. seqStore_t currSeqStore;
  3258. /* If a block is split and some partitions are emitted as RLE/uncompressed, then repcode history
  3259. * may become invalid. In order to reconcile potentially invalid repcodes, we keep track of two
  3260. * separate repcode histories that simulate repcode history on compression and decompression side,
  3261. * and use the histories to determine whether we must replace a particular repcode with its raw offset.
  3262. *
  3263. * 1) cRep gets updated for each partition, regardless of whether the block was emitted as uncompressed
  3264. * or RLE. This allows us to retrieve the offset value that an invalid repcode references within
  3265. * a nocompress/RLE block.
  3266. * 2) dRep gets updated only for compressed partitions, and when a repcode gets replaced, will use
  3267. * the replacement offset value rather than the original repcode to update the repcode history.
  3268. * dRep also will be the final repcode history sent to the next block.
  3269. *
  3270. * See ZSTD_seqStore_resolveOffCodes() for more details.
  3271. */
  3272. repcodes_t dRep;
  3273. repcodes_t cRep;
  3274. ZSTD_memcpy(dRep.rep, zc->blockState.prevCBlock->rep, sizeof(repcodes_t));
  3275. ZSTD_memcpy(cRep.rep, zc->blockState.prevCBlock->rep, sizeof(repcodes_t));
  3276. DEBUGLOG(4, "ZSTD_compressBlock_splitBlock_internal (dstCapacity=%u, dictLimit=%u, nextToUpdate=%u)",
  3277. (unsigned)dstCapacity, (unsigned)zc->blockState.matchState.window.dictLimit,
  3278. (unsigned)zc->blockState.matchState.nextToUpdate);
  3279. if (numSplits == 0) {
  3280. size_t cSizeSingleBlock = ZSTD_compressSeqStore_singleBlock(zc, &zc->seqStore,
  3281. &dRep, &cRep,
  3282. op, dstCapacity,
  3283. ip, blockSize,
  3284. lastBlock, 0 /* isPartition */);
  3285. FORWARD_IF_ERROR(cSizeSingleBlock, "Compressing single block from splitBlock_internal() failed!");
  3286. DEBUGLOG(5, "ZSTD_compressBlock_splitBlock_internal: No splits");
  3287. assert(cSizeSingleBlock <= ZSTD_BLOCKSIZE_MAX + ZSTD_blockHeaderSize);
  3288. return cSizeSingleBlock;
  3289. }
  3290. ZSTD_deriveSeqStoreChunk(&currSeqStore, &zc->seqStore, 0, partitions[0]);
  3291. for (i = 0; i <= numSplits; ++i) {
  3292. size_t srcBytes;
  3293. size_t cSizeChunk;
  3294. U32 const lastPartition = (i == numSplits);
  3295. U32 lastBlockEntireSrc = 0;
  3296. srcBytes = ZSTD_countSeqStoreLiteralsBytes(&currSeqStore) + ZSTD_countSeqStoreMatchBytes(&currSeqStore);
  3297. srcBytesTotal += srcBytes;
  3298. if (lastPartition) {
  3299. /* This is the final partition, need to account for possible last literals */
  3300. srcBytes += blockSize - srcBytesTotal;
  3301. lastBlockEntireSrc = lastBlock;
  3302. } else {
  3303. ZSTD_deriveSeqStoreChunk(&nextSeqStore, &zc->seqStore, partitions[i], partitions[i+1]);
  3304. }
  3305. cSizeChunk = ZSTD_compressSeqStore_singleBlock(zc, &currSeqStore,
  3306. &dRep, &cRep,
  3307. op, dstCapacity,
  3308. ip, srcBytes,
  3309. lastBlockEntireSrc, 1 /* isPartition */);
  3310. DEBUGLOG(5, "Estimated size: %zu actual size: %zu", ZSTD_buildEntropyStatisticsAndEstimateSubBlockSize(&currSeqStore, zc), cSizeChunk);
  3311. FORWARD_IF_ERROR(cSizeChunk, "Compressing chunk failed!");
  3312. ip += srcBytes;
  3313. op += cSizeChunk;
  3314. dstCapacity -= cSizeChunk;
  3315. cSize += cSizeChunk;
  3316. currSeqStore = nextSeqStore;
  3317. assert(cSizeChunk <= ZSTD_BLOCKSIZE_MAX + ZSTD_blockHeaderSize);
  3318. }
  3319. /* cRep and dRep may have diverged during the compression. If so, we use the dRep repcodes
  3320. * for the next block.
  3321. */
  3322. ZSTD_memcpy(zc->blockState.prevCBlock->rep, dRep.rep, sizeof(repcodes_t));
  3323. return cSize;
  3324. }
  3325. static size_t ZSTD_compressBlock_splitBlock(ZSTD_CCtx* zc,
  3326. void* dst, size_t dstCapacity,
  3327. const void* src, size_t srcSize, U32 lastBlock) {
  3328. const BYTE* ip = (const BYTE*)src;
  3329. BYTE* op = (BYTE*)dst;
  3330. U32 nbSeq;
  3331. size_t cSize;
  3332. DEBUGLOG(4, "ZSTD_compressBlock_splitBlock");
  3333. { const size_t bss = ZSTD_buildSeqStore(zc, src, srcSize);
  3334. FORWARD_IF_ERROR(bss, "ZSTD_buildSeqStore failed");
  3335. if (bss == ZSTDbss_noCompress) {
  3336. if (zc->blockState.prevCBlock->entropy.fse.offcode_repeatMode == FSE_repeat_valid)
  3337. zc->blockState.prevCBlock->entropy.fse.offcode_repeatMode = FSE_repeat_check;
  3338. cSize = ZSTD_noCompressBlock(op, dstCapacity, ip, srcSize, lastBlock);
  3339. FORWARD_IF_ERROR(cSize, "ZSTD_noCompressBlock failed");
  3340. DEBUGLOG(4, "ZSTD_compressBlock_splitBlock: Nocompress block");
  3341. return cSize;
  3342. }
  3343. nbSeq = (U32)(zc->seqStore.sequences - zc->seqStore.sequencesStart);
  3344. }
  3345. assert(zc->appliedParams.splitBlocks == 1);
  3346. cSize = ZSTD_compressBlock_splitBlock_internal(zc, dst, dstCapacity, src, srcSize, lastBlock, nbSeq);
  3347. FORWARD_IF_ERROR(cSize, "Splitting blocks failed!");
  3348. return cSize;
  3349. }
  3350. static size_t ZSTD_compressBlock_internal(ZSTD_CCtx* zc,
  3351. void* dst, size_t dstCapacity,
  3352. const void* src, size_t srcSize, U32 frame)
  3353. {
  3354. /* This the upper bound for the length of an rle block.
  3355. * This isn't the actual upper bound. Finding the real threshold
  3356. * needs further investigation.
  3357. */
  3358. const U32 rleMaxLength = 25;
  3359. size_t cSize;
  3360. const BYTE* ip = (const BYTE*)src;
  3361. BYTE* op = (BYTE*)dst;
  3362. DEBUGLOG(5, "ZSTD_compressBlock_internal (dstCapacity=%u, dictLimit=%u, nextToUpdate=%u)",
  3363. (unsigned)dstCapacity, (unsigned)zc->blockState.matchState.window.dictLimit,
  3364. (unsigned)zc->blockState.matchState.nextToUpdate);
  3365. { const size_t bss = ZSTD_buildSeqStore(zc, src, srcSize);
  3366. FORWARD_IF_ERROR(bss, "ZSTD_buildSeqStore failed");
  3367. if (bss == ZSTDbss_noCompress) { cSize = 0; goto out; }
  3368. }
  3369. if (zc->seqCollector.collectSequences) {
  3370. ZSTD_copyBlockSequences(zc);
  3371. ZSTD_blockState_confirmRepcodesAndEntropyTables(&zc->blockState);
  3372. return 0;
  3373. }
  3374. /* encode sequences and literals */
  3375. cSize = ZSTD_entropyCompressSeqStore(&zc->seqStore,
  3376. &zc->blockState.prevCBlock->entropy, &zc->blockState.nextCBlock->entropy,
  3377. &zc->appliedParams,
  3378. dst, dstCapacity,
  3379. srcSize,
  3380. zc->entropyWorkspace, ENTROPY_WORKSPACE_SIZE /* statically allocated in resetCCtx */,
  3381. zc->bmi2);
  3382. if (zc->seqCollector.collectSequences) {
  3383. ZSTD_copyBlockSequences(zc);
  3384. return 0;
  3385. }
  3386. if (frame &&
  3387. /* We don't want to emit our first block as a RLE even if it qualifies because
  3388. * doing so will cause the decoder (cli only) to throw a "should consume all input error."
  3389. * This is only an issue for zstd <= v1.4.3
  3390. */
  3391. !zc->isFirstBlock &&
  3392. cSize < rleMaxLength &&
  3393. ZSTD_isRLE(ip, srcSize))
  3394. {
  3395. cSize = 1;
  3396. op[0] = ip[0];
  3397. }
  3398. out:
  3399. if (!ZSTD_isError(cSize) && cSize > 1) {
  3400. ZSTD_blockState_confirmRepcodesAndEntropyTables(&zc->blockState);
  3401. }
  3402. /* We check that dictionaries have offset codes available for the first
  3403. * block. After the first block, the offcode table might not have large
  3404. * enough codes to represent the offsets in the data.
  3405. */
  3406. if (zc->blockState.prevCBlock->entropy.fse.offcode_repeatMode == FSE_repeat_valid)
  3407. zc->blockState.prevCBlock->entropy.fse.offcode_repeatMode = FSE_repeat_check;
  3408. return cSize;
  3409. }
  3410. static size_t ZSTD_compressBlock_targetCBlockSize_body(ZSTD_CCtx* zc,
  3411. void* dst, size_t dstCapacity,
  3412. const void* src, size_t srcSize,
  3413. const size_t bss, U32 lastBlock)
  3414. {
  3415. DEBUGLOG(6, "Attempting ZSTD_compressSuperBlock()");
  3416. if (bss == ZSTDbss_compress) {
  3417. if (/* We don't want to emit our first block as a RLE even if it qualifies because
  3418. * doing so will cause the decoder (cli only) to throw a "should consume all input error."
  3419. * This is only an issue for zstd <= v1.4.3
  3420. */
  3421. !zc->isFirstBlock &&
  3422. ZSTD_maybeRLE(&zc->seqStore) &&
  3423. ZSTD_isRLE((BYTE const*)src, srcSize))
  3424. {
  3425. return ZSTD_rleCompressBlock(dst, dstCapacity, *(BYTE const*)src, srcSize, lastBlock);
  3426. }
  3427. /* Attempt superblock compression.
  3428. *
  3429. * Note that compressed size of ZSTD_compressSuperBlock() is not bound by the
  3430. * standard ZSTD_compressBound(). This is a problem, because even if we have
  3431. * space now, taking an extra byte now could cause us to run out of space later
  3432. * and violate ZSTD_compressBound().
  3433. *
  3434. * Define blockBound(blockSize) = blockSize + ZSTD_blockHeaderSize.
  3435. *
  3436. * In order to respect ZSTD_compressBound() we must attempt to emit a raw
  3437. * uncompressed block in these cases:
  3438. * * cSize == 0: Return code for an uncompressed block.
  3439. * * cSize == dstSize_tooSmall: We may have expanded beyond blockBound(srcSize).
  3440. * ZSTD_noCompressBlock() will return dstSize_tooSmall if we are really out of
  3441. * output space.
  3442. * * cSize >= blockBound(srcSize): We have expanded the block too much so
  3443. * emit an uncompressed block.
  3444. */
  3445. {
  3446. size_t const cSize = ZSTD_compressSuperBlock(zc, dst, dstCapacity, src, srcSize, lastBlock);
  3447. if (cSize != ERROR(dstSize_tooSmall)) {
  3448. size_t const maxCSize = srcSize - ZSTD_minGain(srcSize, zc->appliedParams.cParams.strategy);
  3449. FORWARD_IF_ERROR(cSize, "ZSTD_compressSuperBlock failed");
  3450. if (cSize != 0 && cSize < maxCSize + ZSTD_blockHeaderSize) {
  3451. ZSTD_blockState_confirmRepcodesAndEntropyTables(&zc->blockState);
  3452. return cSize;
  3453. }
  3454. }
  3455. }
  3456. }
  3457. DEBUGLOG(6, "Resorting to ZSTD_noCompressBlock()");
  3458. /* Superblock compression failed, attempt to emit a single no compress block.
  3459. * The decoder will be able to stream this block since it is uncompressed.
  3460. */
  3461. return ZSTD_noCompressBlock(dst, dstCapacity, src, srcSize, lastBlock);
  3462. }
  3463. static size_t ZSTD_compressBlock_targetCBlockSize(ZSTD_CCtx* zc,
  3464. void* dst, size_t dstCapacity,
  3465. const void* src, size_t srcSize,
  3466. U32 lastBlock)
  3467. {
  3468. size_t cSize = 0;
  3469. const size_t bss = ZSTD_buildSeqStore(zc, src, srcSize);
  3470. DEBUGLOG(5, "ZSTD_compressBlock_targetCBlockSize (dstCapacity=%u, dictLimit=%u, nextToUpdate=%u, srcSize=%zu)",
  3471. (unsigned)dstCapacity, (unsigned)zc->blockState.matchState.window.dictLimit, (unsigned)zc->blockState.matchState.nextToUpdate, srcSize);
  3472. FORWARD_IF_ERROR(bss, "ZSTD_buildSeqStore failed");
  3473. cSize = ZSTD_compressBlock_targetCBlockSize_body(zc, dst, dstCapacity, src, srcSize, bss, lastBlock);
  3474. FORWARD_IF_ERROR(cSize, "ZSTD_compressBlock_targetCBlockSize_body failed");
  3475. if (zc->blockState.prevCBlock->entropy.fse.offcode_repeatMode == FSE_repeat_valid)
  3476. zc->blockState.prevCBlock->entropy.fse.offcode_repeatMode = FSE_repeat_check;
  3477. return cSize;
  3478. }
  3479. static void ZSTD_overflowCorrectIfNeeded(ZSTD_matchState_t* ms,
  3480. ZSTD_cwksp* ws,
  3481. ZSTD_CCtx_params const* params,
  3482. void const* ip,
  3483. void const* iend)
  3484. {
  3485. U32 const cycleLog = ZSTD_cycleLog(params->cParams.chainLog, params->cParams.strategy);
  3486. U32 const maxDist = (U32)1 << params->cParams.windowLog;
  3487. if (ZSTD_window_needOverflowCorrection(ms->window, cycleLog, maxDist, ms->loadedDictEnd, ip, iend)) {
  3488. U32 const correction = ZSTD_window_correctOverflow(&ms->window, cycleLog, maxDist, ip);
  3489. ZSTD_STATIC_ASSERT(ZSTD_CHAINLOG_MAX <= 30);
  3490. ZSTD_STATIC_ASSERT(ZSTD_WINDOWLOG_MAX_32 <= 30);
  3491. ZSTD_STATIC_ASSERT(ZSTD_WINDOWLOG_MAX <= 31);
  3492. ZSTD_cwksp_mark_tables_dirty(ws);
  3493. ZSTD_reduceIndex(ms, params, correction);
  3494. ZSTD_cwksp_mark_tables_clean(ws);
  3495. if (ms->nextToUpdate < correction) ms->nextToUpdate = 0;
  3496. else ms->nextToUpdate -= correction;
  3497. /* invalidate dictionaries on overflow correction */
  3498. ms->loadedDictEnd = 0;
  3499. ms->dictMatchState = NULL;
  3500. }
  3501. }
  3502. /*! ZSTD_compress_frameChunk() :
  3503. * Compress a chunk of data into one or multiple blocks.
  3504. * All blocks will be terminated, all input will be consumed.
  3505. * Function will issue an error if there is not enough `dstCapacity` to hold the compressed content.
  3506. * Frame is supposed already started (header already produced)
  3507. * @return : compressed size, or an error code
  3508. */
  3509. static size_t ZSTD_compress_frameChunk(ZSTD_CCtx* cctx,
  3510. void* dst, size_t dstCapacity,
  3511. const void* src, size_t srcSize,
  3512. U32 lastFrameChunk)
  3513. {
  3514. size_t blockSize = cctx->blockSize;
  3515. size_t remaining = srcSize;
  3516. const BYTE* ip = (const BYTE*)src;
  3517. BYTE* const ostart = (BYTE*)dst;
  3518. BYTE* op = ostart;
  3519. U32 const maxDist = (U32)1 << cctx->appliedParams.cParams.windowLog;
  3520. assert(cctx->appliedParams.cParams.windowLog <= ZSTD_WINDOWLOG_MAX);
  3521. DEBUGLOG(4, "ZSTD_compress_frameChunk (blockSize=%u)", (unsigned)blockSize);
  3522. if (cctx->appliedParams.fParams.checksumFlag && srcSize)
  3523. XXH64_update(&cctx->xxhState, src, srcSize);
  3524. while (remaining) {
  3525. ZSTD_matchState_t* const ms = &cctx->blockState.matchState;
  3526. U32 const lastBlock = lastFrameChunk & (blockSize >= remaining);
  3527. RETURN_ERROR_IF(dstCapacity < ZSTD_blockHeaderSize + MIN_CBLOCK_SIZE,
  3528. dstSize_tooSmall,
  3529. "not enough space to store compressed block");
  3530. if (remaining < blockSize) blockSize = remaining;
  3531. ZSTD_overflowCorrectIfNeeded(
  3532. ms, &cctx->workspace, &cctx->appliedParams, ip, ip + blockSize);
  3533. ZSTD_checkDictValidity(&ms->window, ip + blockSize, maxDist, &ms->loadedDictEnd, &ms->dictMatchState);
  3534. /* Ensure hash/chain table insertion resumes no sooner than lowlimit */
  3535. if (ms->nextToUpdate < ms->window.lowLimit) ms->nextToUpdate = ms->window.lowLimit;
  3536. { size_t cSize;
  3537. if (ZSTD_useTargetCBlockSize(&cctx->appliedParams)) {
  3538. cSize = ZSTD_compressBlock_targetCBlockSize(cctx, op, dstCapacity, ip, blockSize, lastBlock);
  3539. FORWARD_IF_ERROR(cSize, "ZSTD_compressBlock_targetCBlockSize failed");
  3540. assert(cSize > 0);
  3541. assert(cSize <= blockSize + ZSTD_blockHeaderSize);
  3542. } else if (ZSTD_blockSplitterEnabled(&cctx->appliedParams)) {
  3543. cSize = ZSTD_compressBlock_splitBlock(cctx, op, dstCapacity, ip, blockSize, lastBlock);
  3544. FORWARD_IF_ERROR(cSize, "ZSTD_compressBlock_splitBlock failed");
  3545. assert(cSize > 0 || cctx->seqCollector.collectSequences == 1);
  3546. } else {
  3547. cSize = ZSTD_compressBlock_internal(cctx,
  3548. op+ZSTD_blockHeaderSize, dstCapacity-ZSTD_blockHeaderSize,
  3549. ip, blockSize, 1 /* frame */);
  3550. FORWARD_IF_ERROR(cSize, "ZSTD_compressBlock_internal failed");
  3551. if (cSize == 0) { /* block is not compressible */
  3552. cSize = ZSTD_noCompressBlock(op, dstCapacity, ip, blockSize, lastBlock);
  3553. FORWARD_IF_ERROR(cSize, "ZSTD_noCompressBlock failed");
  3554. } else {
  3555. U32 const cBlockHeader = cSize == 1 ?
  3556. lastBlock + (((U32)bt_rle)<<1) + (U32)(blockSize << 3) :
  3557. lastBlock + (((U32)bt_compressed)<<1) + (U32)(cSize << 3);
  3558. MEM_writeLE24(op, cBlockHeader);
  3559. cSize += ZSTD_blockHeaderSize;
  3560. }
  3561. }
  3562. ip += blockSize;
  3563. assert(remaining >= blockSize);
  3564. remaining -= blockSize;
  3565. op += cSize;
  3566. assert(dstCapacity >= cSize);
  3567. dstCapacity -= cSize;
  3568. cctx->isFirstBlock = 0;
  3569. DEBUGLOG(5, "ZSTD_compress_frameChunk: adding a block of size %u",
  3570. (unsigned)cSize);
  3571. } }
  3572. if (lastFrameChunk && (op>ostart)) cctx->stage = ZSTDcs_ending;
  3573. return (size_t)(op-ostart);
  3574. }
  3575. static size_t ZSTD_writeFrameHeader(void* dst, size_t dstCapacity,
  3576. const ZSTD_CCtx_params* params, U64 pledgedSrcSize, U32 dictID)
  3577. { BYTE* const op = (BYTE*)dst;
  3578. U32 const dictIDSizeCodeLength = (dictID>0) + (dictID>=256) + (dictID>=65536); /* 0-3 */
  3579. U32 const dictIDSizeCode = params->fParams.noDictIDFlag ? 0 : dictIDSizeCodeLength; /* 0-3 */
  3580. U32 const checksumFlag = params->fParams.checksumFlag>0;
  3581. U32 const windowSize = (U32)1 << params->cParams.windowLog;
  3582. U32 const singleSegment = params->fParams.contentSizeFlag && (windowSize >= pledgedSrcSize);
  3583. BYTE const windowLogByte = (BYTE)((params->cParams.windowLog - ZSTD_WINDOWLOG_ABSOLUTEMIN) << 3);
  3584. U32 const fcsCode = params->fParams.contentSizeFlag ?
  3585. (pledgedSrcSize>=256) + (pledgedSrcSize>=65536+256) + (pledgedSrcSize>=0xFFFFFFFFU) : 0; /* 0-3 */
  3586. BYTE const frameHeaderDescriptionByte = (BYTE)(dictIDSizeCode + (checksumFlag<<2) + (singleSegment<<5) + (fcsCode<<6) );
  3587. size_t pos=0;
  3588. assert(!(params->fParams.contentSizeFlag && pledgedSrcSize == ZSTD_CONTENTSIZE_UNKNOWN));
  3589. RETURN_ERROR_IF(dstCapacity < ZSTD_FRAMEHEADERSIZE_MAX, dstSize_tooSmall,
  3590. "dst buf is too small to fit worst-case frame header size.");
  3591. DEBUGLOG(4, "ZSTD_writeFrameHeader : dictIDFlag : %u ; dictID : %u ; dictIDSizeCode : %u",
  3592. !params->fParams.noDictIDFlag, (unsigned)dictID, (unsigned)dictIDSizeCode);
  3593. if (params->format == ZSTD_f_zstd1) {
  3594. MEM_writeLE32(dst, ZSTD_MAGICNUMBER);
  3595. pos = 4;
  3596. }
  3597. op[pos++] = frameHeaderDescriptionByte;
  3598. if (!singleSegment) op[pos++] = windowLogByte;
  3599. switch(dictIDSizeCode)
  3600. {
  3601. default: assert(0); /* impossible */
  3602. case 0 : break;
  3603. case 1 : op[pos] = (BYTE)(dictID); pos++; break;
  3604. case 2 : MEM_writeLE16(op+pos, (U16)dictID); pos+=2; break;
  3605. case 3 : MEM_writeLE32(op+pos, dictID); pos+=4; break;
  3606. }
  3607. switch(fcsCode)
  3608. {
  3609. default: assert(0); /* impossible */
  3610. case 0 : if (singleSegment) op[pos++] = (BYTE)(pledgedSrcSize); break;
  3611. case 1 : MEM_writeLE16(op+pos, (U16)(pledgedSrcSize-256)); pos+=2; break;
  3612. case 2 : MEM_writeLE32(op+pos, (U32)(pledgedSrcSize)); pos+=4; break;
  3613. case 3 : MEM_writeLE64(op+pos, (U64)(pledgedSrcSize)); pos+=8; break;
  3614. }
  3615. return pos;
  3616. }
  3617. /* ZSTD_writeSkippableFrame_advanced() :
  3618. * Writes out a skippable frame with the specified magic number variant (16 are supported),
  3619. * from ZSTD_MAGIC_SKIPPABLE_START to ZSTD_MAGIC_SKIPPABLE_START+15, and the desired source data.
  3620. *
  3621. * Returns the total number of bytes written, or a ZSTD error code.
  3622. */
  3623. size_t ZSTD_writeSkippableFrame(void* dst, size_t dstCapacity,
  3624. const void* src, size_t srcSize, unsigned magicVariant) {
  3625. BYTE* op = (BYTE*)dst;
  3626. RETURN_ERROR_IF(dstCapacity < srcSize + ZSTD_SKIPPABLEHEADERSIZE /* Skippable frame overhead */,
  3627. dstSize_tooSmall, "Not enough room for skippable frame");
  3628. RETURN_ERROR_IF(srcSize > (unsigned)0xFFFFFFFF, srcSize_wrong, "Src size too large for skippable frame");
  3629. RETURN_ERROR_IF(magicVariant > 15, parameter_outOfBound, "Skippable frame magic number variant not supported");
  3630. MEM_writeLE32(op, (U32)(ZSTD_MAGIC_SKIPPABLE_START + magicVariant));
  3631. MEM_writeLE32(op+4, (U32)srcSize);
  3632. ZSTD_memcpy(op+8, src, srcSize);
  3633. return srcSize + ZSTD_SKIPPABLEHEADERSIZE;
  3634. }
  3635. /* ZSTD_writeLastEmptyBlock() :
  3636. * output an empty Block with end-of-frame mark to complete a frame
  3637. * @return : size of data written into `dst` (== ZSTD_blockHeaderSize (defined in zstd_internal.h))
  3638. * or an error code if `dstCapacity` is too small (<ZSTD_blockHeaderSize)
  3639. */
  3640. size_t ZSTD_writeLastEmptyBlock(void* dst, size_t dstCapacity)
  3641. {
  3642. RETURN_ERROR_IF(dstCapacity < ZSTD_blockHeaderSize, dstSize_tooSmall,
  3643. "dst buf is too small to write frame trailer empty block.");
  3644. { U32 const cBlockHeader24 = 1 /*lastBlock*/ + (((U32)bt_raw)<<1); /* 0 size */
  3645. MEM_writeLE24(dst, cBlockHeader24);
  3646. return ZSTD_blockHeaderSize;
  3647. }
  3648. }
  3649. size_t ZSTD_referenceExternalSequences(ZSTD_CCtx* cctx, rawSeq* seq, size_t nbSeq)
  3650. {
  3651. RETURN_ERROR_IF(cctx->stage != ZSTDcs_init, stage_wrong,
  3652. "wrong cctx stage");
  3653. RETURN_ERROR_IF(cctx->appliedParams.ldmParams.enableLdm,
  3654. parameter_unsupported,
  3655. "incompatible with ldm");
  3656. cctx->externSeqStore.seq = seq;
  3657. cctx->externSeqStore.size = nbSeq;
  3658. cctx->externSeqStore.capacity = nbSeq;
  3659. cctx->externSeqStore.pos = 0;
  3660. cctx->externSeqStore.posInSequence = 0;
  3661. return 0;
  3662. }
  3663. static size_t ZSTD_compressContinue_internal (ZSTD_CCtx* cctx,
  3664. void* dst, size_t dstCapacity,
  3665. const void* src, size_t srcSize,
  3666. U32 frame, U32 lastFrameChunk)
  3667. {
  3668. ZSTD_matchState_t* const ms = &cctx->blockState.matchState;
  3669. size_t fhSize = 0;
  3670. DEBUGLOG(5, "ZSTD_compressContinue_internal, stage: %u, srcSize: %u",
  3671. cctx->stage, (unsigned)srcSize);
  3672. RETURN_ERROR_IF(cctx->stage==ZSTDcs_created, stage_wrong,
  3673. "missing init (ZSTD_compressBegin)");
  3674. if (frame && (cctx->stage==ZSTDcs_init)) {
  3675. fhSize = ZSTD_writeFrameHeader(dst, dstCapacity, &cctx->appliedParams,
  3676. cctx->pledgedSrcSizePlusOne-1, cctx->dictID);
  3677. FORWARD_IF_ERROR(fhSize, "ZSTD_writeFrameHeader failed");
  3678. assert(fhSize <= dstCapacity);
  3679. dstCapacity -= fhSize;
  3680. dst = (char*)dst + fhSize;
  3681. cctx->stage = ZSTDcs_ongoing;
  3682. }
  3683. if (!srcSize) return fhSize; /* do not generate an empty block if no input */
  3684. if (!ZSTD_window_update(&ms->window, src, srcSize, ms->forceNonContiguous)) {
  3685. ms->forceNonContiguous = 0;
  3686. ms->nextToUpdate = ms->window.dictLimit;
  3687. }
  3688. if (cctx->appliedParams.ldmParams.enableLdm) {
  3689. ZSTD_window_update(&cctx->ldmState.window, src, srcSize, /* forceNonContiguous */ 0);
  3690. }
  3691. if (!frame) {
  3692. /* overflow check and correction for block mode */
  3693. ZSTD_overflowCorrectIfNeeded(
  3694. ms, &cctx->workspace, &cctx->appliedParams,
  3695. src, (BYTE const*)src + srcSize);
  3696. }
  3697. DEBUGLOG(5, "ZSTD_compressContinue_internal (blockSize=%u)", (unsigned)cctx->blockSize);
  3698. { size_t const cSize = frame ?
  3699. ZSTD_compress_frameChunk (cctx, dst, dstCapacity, src, srcSize, lastFrameChunk) :
  3700. ZSTD_compressBlock_internal (cctx, dst, dstCapacity, src, srcSize, 0 /* frame */);
  3701. FORWARD_IF_ERROR(cSize, "%s", frame ? "ZSTD_compress_frameChunk failed" : "ZSTD_compressBlock_internal failed");
  3702. cctx->consumedSrcSize += srcSize;
  3703. cctx->producedCSize += (cSize + fhSize);
  3704. assert(!(cctx->appliedParams.fParams.contentSizeFlag && cctx->pledgedSrcSizePlusOne == 0));
  3705. if (cctx->pledgedSrcSizePlusOne != 0) { /* control src size */
  3706. ZSTD_STATIC_ASSERT(ZSTD_CONTENTSIZE_UNKNOWN == (unsigned long long)-1);
  3707. RETURN_ERROR_IF(
  3708. cctx->consumedSrcSize+1 > cctx->pledgedSrcSizePlusOne,
  3709. srcSize_wrong,
  3710. "error : pledgedSrcSize = %u, while realSrcSize >= %u",
  3711. (unsigned)cctx->pledgedSrcSizePlusOne-1,
  3712. (unsigned)cctx->consumedSrcSize);
  3713. }
  3714. return cSize + fhSize;
  3715. }
  3716. }
  3717. size_t ZSTD_compressContinue (ZSTD_CCtx* cctx,
  3718. void* dst, size_t dstCapacity,
  3719. const void* src, size_t srcSize)
  3720. {
  3721. DEBUGLOG(5, "ZSTD_compressContinue (srcSize=%u)", (unsigned)srcSize);
  3722. return ZSTD_compressContinue_internal(cctx, dst, dstCapacity, src, srcSize, 1 /* frame mode */, 0 /* last chunk */);
  3723. }
  3724. size_t ZSTD_getBlockSize(const ZSTD_CCtx* cctx)
  3725. {
  3726. ZSTD_compressionParameters const cParams = cctx->appliedParams.cParams;
  3727. assert(!ZSTD_checkCParams(cParams));
  3728. return MIN (ZSTD_BLOCKSIZE_MAX, (U32)1 << cParams.windowLog);
  3729. }
  3730. size_t ZSTD_compressBlock(ZSTD_CCtx* cctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize)
  3731. {
  3732. DEBUGLOG(5, "ZSTD_compressBlock: srcSize = %u", (unsigned)srcSize);
  3733. { size_t const blockSizeMax = ZSTD_getBlockSize(cctx);
  3734. RETURN_ERROR_IF(srcSize > blockSizeMax, srcSize_wrong, "input is larger than a block"); }
  3735. return ZSTD_compressContinue_internal(cctx, dst, dstCapacity, src, srcSize, 0 /* frame mode */, 0 /* last chunk */);
  3736. }
  3737. /*! ZSTD_loadDictionaryContent() :
  3738. * @return : 0, or an error code
  3739. */
  3740. static size_t ZSTD_loadDictionaryContent(ZSTD_matchState_t* ms,
  3741. ldmState_t* ls,
  3742. ZSTD_cwksp* ws,
  3743. ZSTD_CCtx_params const* params,
  3744. const void* src, size_t srcSize,
  3745. ZSTD_dictTableLoadMethod_e dtlm)
  3746. {
  3747. const BYTE* ip = (const BYTE*) src;
  3748. const BYTE* const iend = ip + srcSize;
  3749. int const loadLdmDict = params->ldmParams.enableLdm && ls != NULL;
  3750. /* Assert that we the ms params match the params we're being given */
  3751. ZSTD_assertEqualCParams(params->cParams, ms->cParams);
  3752. if (srcSize > ZSTD_CHUNKSIZE_MAX) {
  3753. /* Allow the dictionary to set indices up to exactly ZSTD_CURRENT_MAX.
  3754. * Dictionaries right at the edge will immediately trigger overflow
  3755. * correction, but I don't want to insert extra constraints here.
  3756. */
  3757. U32 const maxDictSize = ZSTD_CURRENT_MAX - 1;
  3758. /* We must have cleared our windows when our source is this large. */
  3759. assert(ZSTD_window_isEmpty(ms->window));
  3760. if (loadLdmDict)
  3761. assert(ZSTD_window_isEmpty(ls->window));
  3762. /* If the dictionary is too large, only load the suffix of the dictionary. */
  3763. if (srcSize > maxDictSize) {
  3764. ip = iend - maxDictSize;
  3765. src = ip;
  3766. srcSize = maxDictSize;
  3767. }
  3768. }
  3769. DEBUGLOG(4, "ZSTD_loadDictionaryContent(): useRowMatchFinder=%d", (int)params->useRowMatchFinder);
  3770. ZSTD_window_update(&ms->window, src, srcSize, /* forceNonContiguous */ 0);
  3771. ms->loadedDictEnd = params->forceWindow ? 0 : (U32)(iend - ms->window.base);
  3772. ms->forceNonContiguous = params->deterministicRefPrefix;
  3773. if (loadLdmDict) {
  3774. ZSTD_window_update(&ls->window, src, srcSize, /* forceNonContiguous */ 0);
  3775. ls->loadedDictEnd = params->forceWindow ? 0 : (U32)(iend - ls->window.base);
  3776. }
  3777. if (srcSize <= HASH_READ_SIZE) return 0;
  3778. ZSTD_overflowCorrectIfNeeded(ms, ws, params, ip, iend);
  3779. if (loadLdmDict)
  3780. ZSTD_ldm_fillHashTable(ls, ip, iend, &params->ldmParams);
  3781. switch(params->cParams.strategy)
  3782. {
  3783. case ZSTD_fast:
  3784. ZSTD_fillHashTable(ms, iend, dtlm);
  3785. break;
  3786. case ZSTD_dfast:
  3787. ZSTD_fillDoubleHashTable(ms, iend, dtlm);
  3788. break;
  3789. case ZSTD_greedy:
  3790. case ZSTD_lazy:
  3791. case ZSTD_lazy2:
  3792. assert(srcSize >= HASH_READ_SIZE);
  3793. if (ms->dedicatedDictSearch) {
  3794. assert(ms->chainTable != NULL);
  3795. ZSTD_dedicatedDictSearch_lazy_loadDictionary(ms, iend-HASH_READ_SIZE);
  3796. } else {
  3797. assert(params->useRowMatchFinder != ZSTD_urm_auto);
  3798. if (params->useRowMatchFinder == ZSTD_urm_enableRowMatchFinder) {
  3799. size_t const tagTableSize = ((size_t)1 << params->cParams.hashLog) * sizeof(U16);
  3800. ZSTD_memset(ms->tagTable, 0, tagTableSize);
  3801. ZSTD_row_update(ms, iend-HASH_READ_SIZE);
  3802. DEBUGLOG(4, "Using row-based hash table for lazy dict");
  3803. } else {
  3804. ZSTD_insertAndFindFirstIndex(ms, iend-HASH_READ_SIZE);
  3805. DEBUGLOG(4, "Using chain-based hash table for lazy dict");
  3806. }
  3807. }
  3808. break;
  3809. case ZSTD_btlazy2: /* we want the dictionary table fully sorted */
  3810. case ZSTD_btopt:
  3811. case ZSTD_btultra:
  3812. case ZSTD_btultra2:
  3813. assert(srcSize >= HASH_READ_SIZE);
  3814. ZSTD_updateTree(ms, iend-HASH_READ_SIZE, iend);
  3815. break;
  3816. default:
  3817. assert(0); /* not possible : not a valid strategy id */
  3818. }
  3819. ms->nextToUpdate = (U32)(iend - ms->window.base);
  3820. return 0;
  3821. }
  3822. /* Dictionaries that assign zero probability to symbols that show up causes problems
  3823. * when FSE encoding. Mark dictionaries with zero probability symbols as FSE_repeat_check
  3824. * and only dictionaries with 100% valid symbols can be assumed valid.
  3825. */
  3826. static FSE_repeat ZSTD_dictNCountRepeat(short* normalizedCounter, unsigned dictMaxSymbolValue, unsigned maxSymbolValue)
  3827. {
  3828. U32 s;
  3829. if (dictMaxSymbolValue < maxSymbolValue) {
  3830. return FSE_repeat_check;
  3831. }
  3832. for (s = 0; s <= maxSymbolValue; ++s) {
  3833. if (normalizedCounter[s] == 0) {
  3834. return FSE_repeat_check;
  3835. }
  3836. }
  3837. return FSE_repeat_valid;
  3838. }
  3839. size_t ZSTD_loadCEntropy(ZSTD_compressedBlockState_t* bs, void* workspace,
  3840. const void* const dict, size_t dictSize)
  3841. {
  3842. short offcodeNCount[MaxOff+1];
  3843. unsigned offcodeMaxValue = MaxOff;
  3844. const BYTE* dictPtr = (const BYTE*)dict; /* skip magic num and dict ID */
  3845. const BYTE* const dictEnd = dictPtr + dictSize;
  3846. dictPtr += 8;
  3847. bs->entropy.huf.repeatMode = HUF_repeat_check;
  3848. { unsigned maxSymbolValue = 255;
  3849. unsigned hasZeroWeights = 1;
  3850. size_t const hufHeaderSize = HUF_readCTable((HUF_CElt*)bs->entropy.huf.CTable, &maxSymbolValue, dictPtr,
  3851. dictEnd-dictPtr, &hasZeroWeights);
  3852. /* We only set the loaded table as valid if it contains all non-zero
  3853. * weights. Otherwise, we set it to check */
  3854. if (!hasZeroWeights)
  3855. bs->entropy.huf.repeatMode = HUF_repeat_valid;
  3856. RETURN_ERROR_IF(HUF_isError(hufHeaderSize), dictionary_corrupted, "");
  3857. RETURN_ERROR_IF(maxSymbolValue < 255, dictionary_corrupted, "");
  3858. dictPtr += hufHeaderSize;
  3859. }
  3860. { unsigned offcodeLog;
  3861. size_t const offcodeHeaderSize = FSE_readNCount(offcodeNCount, &offcodeMaxValue, &offcodeLog, dictPtr, dictEnd-dictPtr);
  3862. RETURN_ERROR_IF(FSE_isError(offcodeHeaderSize), dictionary_corrupted, "");
  3863. RETURN_ERROR_IF(offcodeLog > OffFSELog, dictionary_corrupted, "");
  3864. /* fill all offset symbols to avoid garbage at end of table */
  3865. RETURN_ERROR_IF(FSE_isError(FSE_buildCTable_wksp(
  3866. bs->entropy.fse.offcodeCTable,
  3867. offcodeNCount, MaxOff, offcodeLog,
  3868. workspace, HUF_WORKSPACE_SIZE)),
  3869. dictionary_corrupted, "");
  3870. /* Defer checking offcodeMaxValue because we need to know the size of the dictionary content */
  3871. dictPtr += offcodeHeaderSize;
  3872. }
  3873. { short matchlengthNCount[MaxML+1];
  3874. unsigned matchlengthMaxValue = MaxML, matchlengthLog;
  3875. size_t const matchlengthHeaderSize = FSE_readNCount(matchlengthNCount, &matchlengthMaxValue, &matchlengthLog, dictPtr, dictEnd-dictPtr);
  3876. RETURN_ERROR_IF(FSE_isError(matchlengthHeaderSize), dictionary_corrupted, "");
  3877. RETURN_ERROR_IF(matchlengthLog > MLFSELog, dictionary_corrupted, "");
  3878. RETURN_ERROR_IF(FSE_isError(FSE_buildCTable_wksp(
  3879. bs->entropy.fse.matchlengthCTable,
  3880. matchlengthNCount, matchlengthMaxValue, matchlengthLog,
  3881. workspace, HUF_WORKSPACE_SIZE)),
  3882. dictionary_corrupted, "");
  3883. bs->entropy.fse.matchlength_repeatMode = ZSTD_dictNCountRepeat(matchlengthNCount, matchlengthMaxValue, MaxML);
  3884. dictPtr += matchlengthHeaderSize;
  3885. }
  3886. { short litlengthNCount[MaxLL+1];
  3887. unsigned litlengthMaxValue = MaxLL, litlengthLog;
  3888. size_t const litlengthHeaderSize = FSE_readNCount(litlengthNCount, &litlengthMaxValue, &litlengthLog, dictPtr, dictEnd-dictPtr);
  3889. RETURN_ERROR_IF(FSE_isError(litlengthHeaderSize), dictionary_corrupted, "");
  3890. RETURN_ERROR_IF(litlengthLog > LLFSELog, dictionary_corrupted, "");
  3891. RETURN_ERROR_IF(FSE_isError(FSE_buildCTable_wksp(
  3892. bs->entropy.fse.litlengthCTable,
  3893. litlengthNCount, litlengthMaxValue, litlengthLog,
  3894. workspace, HUF_WORKSPACE_SIZE)),
  3895. dictionary_corrupted, "");
  3896. bs->entropy.fse.litlength_repeatMode = ZSTD_dictNCountRepeat(litlengthNCount, litlengthMaxValue, MaxLL);
  3897. dictPtr += litlengthHeaderSize;
  3898. }
  3899. RETURN_ERROR_IF(dictPtr+12 > dictEnd, dictionary_corrupted, "");
  3900. bs->rep[0] = MEM_readLE32(dictPtr+0);
  3901. bs->rep[1] = MEM_readLE32(dictPtr+4);
  3902. bs->rep[2] = MEM_readLE32(dictPtr+8);
  3903. dictPtr += 12;
  3904. { size_t const dictContentSize = (size_t)(dictEnd - dictPtr);
  3905. U32 offcodeMax = MaxOff;
  3906. if (dictContentSize <= ((U32)-1) - 128 KB) {
  3907. U32 const maxOffset = (U32)dictContentSize + 128 KB; /* The maximum offset that must be supported */
  3908. offcodeMax = ZSTD_highbit32(maxOffset); /* Calculate minimum offset code required to represent maxOffset */
  3909. }
  3910. /* All offset values <= dictContentSize + 128 KB must be representable for a valid table */
  3911. bs->entropy.fse.offcode_repeatMode = ZSTD_dictNCountRepeat(offcodeNCount, offcodeMaxValue, MIN(offcodeMax, MaxOff));
  3912. /* All repCodes must be <= dictContentSize and != 0 */
  3913. { U32 u;
  3914. for (u=0; u<3; u++) {
  3915. RETURN_ERROR_IF(bs->rep[u] == 0, dictionary_corrupted, "");
  3916. RETURN_ERROR_IF(bs->rep[u] > dictContentSize, dictionary_corrupted, "");
  3917. } } }
  3918. return dictPtr - (const BYTE*)dict;
  3919. }
  3920. /* Dictionary format :
  3921. * See :
  3922. * https://github.com/facebook/zstd/blob/release/doc/zstd_compression_format.md#dictionary-format
  3923. */
  3924. /*! ZSTD_loadZstdDictionary() :
  3925. * @return : dictID, or an error code
  3926. * assumptions : magic number supposed already checked
  3927. * dictSize supposed >= 8
  3928. */
  3929. static size_t ZSTD_loadZstdDictionary(ZSTD_compressedBlockState_t* bs,
  3930. ZSTD_matchState_t* ms,
  3931. ZSTD_cwksp* ws,
  3932. ZSTD_CCtx_params const* params,
  3933. const void* dict, size_t dictSize,
  3934. ZSTD_dictTableLoadMethod_e dtlm,
  3935. void* workspace)
  3936. {
  3937. const BYTE* dictPtr = (const BYTE*)dict;
  3938. const BYTE* const dictEnd = dictPtr + dictSize;
  3939. size_t dictID;
  3940. size_t eSize;
  3941. ZSTD_STATIC_ASSERT(HUF_WORKSPACE_SIZE >= (1<<MAX(MLFSELog,LLFSELog)));
  3942. assert(dictSize >= 8);
  3943. assert(MEM_readLE32(dictPtr) == ZSTD_MAGIC_DICTIONARY);
  3944. dictID = params->fParams.noDictIDFlag ? 0 : MEM_readLE32(dictPtr + 4 /* skip magic number */ );
  3945. eSize = ZSTD_loadCEntropy(bs, workspace, dict, dictSize);
  3946. FORWARD_IF_ERROR(eSize, "ZSTD_loadCEntropy failed");
  3947. dictPtr += eSize;
  3948. {
  3949. size_t const dictContentSize = (size_t)(dictEnd - dictPtr);
  3950. FORWARD_IF_ERROR(ZSTD_loadDictionaryContent(
  3951. ms, NULL, ws, params, dictPtr, dictContentSize, dtlm), "");
  3952. }
  3953. return dictID;
  3954. }
  3955. /** ZSTD_compress_insertDictionary() :
  3956. * @return : dictID, or an error code */
  3957. static size_t
  3958. ZSTD_compress_insertDictionary(ZSTD_compressedBlockState_t* bs,
  3959. ZSTD_matchState_t* ms,
  3960. ldmState_t* ls,
  3961. ZSTD_cwksp* ws,
  3962. const ZSTD_CCtx_params* params,
  3963. const void* dict, size_t dictSize,
  3964. ZSTD_dictContentType_e dictContentType,
  3965. ZSTD_dictTableLoadMethod_e dtlm,
  3966. void* workspace)
  3967. {
  3968. DEBUGLOG(4, "ZSTD_compress_insertDictionary (dictSize=%u)", (U32)dictSize);
  3969. if ((dict==NULL) || (dictSize<8)) {
  3970. RETURN_ERROR_IF(dictContentType == ZSTD_dct_fullDict, dictionary_wrong, "");
  3971. return 0;
  3972. }
  3973. ZSTD_reset_compressedBlockState(bs);
  3974. /* dict restricted modes */
  3975. if (dictContentType == ZSTD_dct_rawContent)
  3976. return ZSTD_loadDictionaryContent(ms, ls, ws, params, dict, dictSize, dtlm);
  3977. if (MEM_readLE32(dict) != ZSTD_MAGIC_DICTIONARY) {
  3978. if (dictContentType == ZSTD_dct_auto) {
  3979. DEBUGLOG(4, "raw content dictionary detected");
  3980. return ZSTD_loadDictionaryContent(
  3981. ms, ls, ws, params, dict, dictSize, dtlm);
  3982. }
  3983. RETURN_ERROR_IF(dictContentType == ZSTD_dct_fullDict, dictionary_wrong, "");
  3984. assert(0); /* impossible */
  3985. }
  3986. /* dict as full zstd dictionary */
  3987. return ZSTD_loadZstdDictionary(
  3988. bs, ms, ws, params, dict, dictSize, dtlm, workspace);
  3989. }
  3990. #define ZSTD_USE_CDICT_PARAMS_SRCSIZE_CUTOFF (128 KB)
  3991. #define ZSTD_USE_CDICT_PARAMS_DICTSIZE_MULTIPLIER (6ULL)
  3992. /*! ZSTD_compressBegin_internal() :
  3993. * @return : 0, or an error code */
  3994. static size_t ZSTD_compressBegin_internal(ZSTD_CCtx* cctx,
  3995. const void* dict, size_t dictSize,
  3996. ZSTD_dictContentType_e dictContentType,
  3997. ZSTD_dictTableLoadMethod_e dtlm,
  3998. const ZSTD_CDict* cdict,
  3999. const ZSTD_CCtx_params* params, U64 pledgedSrcSize,
  4000. ZSTD_buffered_policy_e zbuff)
  4001. {
  4002. size_t const dictContentSize = cdict ? cdict->dictContentSize : dictSize;
  4003. #if ZSTD_TRACE
  4004. cctx->traceCtx = (ZSTD_trace_compress_begin != NULL) ? ZSTD_trace_compress_begin(cctx) : 0;
  4005. #endif
  4006. DEBUGLOG(4, "ZSTD_compressBegin_internal: wlog=%u", params->cParams.windowLog);
  4007. /* params are supposed to be fully validated at this point */
  4008. assert(!ZSTD_isError(ZSTD_checkCParams(params->cParams)));
  4009. assert(!((dict) && (cdict))); /* either dict or cdict, not both */
  4010. if ( (cdict)
  4011. && (cdict->dictContentSize > 0)
  4012. && ( pledgedSrcSize < ZSTD_USE_CDICT_PARAMS_SRCSIZE_CUTOFF
  4013. || pledgedSrcSize < cdict->dictContentSize * ZSTD_USE_CDICT_PARAMS_DICTSIZE_MULTIPLIER
  4014. || pledgedSrcSize == ZSTD_CONTENTSIZE_UNKNOWN
  4015. || cdict->compressionLevel == 0)
  4016. && (params->attachDictPref != ZSTD_dictForceLoad) ) {
  4017. return ZSTD_resetCCtx_usingCDict(cctx, cdict, params, pledgedSrcSize, zbuff);
  4018. }
  4019. FORWARD_IF_ERROR( ZSTD_resetCCtx_internal(cctx, params, pledgedSrcSize,
  4020. dictContentSize,
  4021. ZSTDcrp_makeClean, zbuff) , "");
  4022. { size_t const dictID = cdict ?
  4023. ZSTD_compress_insertDictionary(
  4024. cctx->blockState.prevCBlock, &cctx->blockState.matchState,
  4025. &cctx->ldmState, &cctx->workspace, &cctx->appliedParams, cdict->dictContent,
  4026. cdict->dictContentSize, cdict->dictContentType, dtlm,
  4027. cctx->entropyWorkspace)
  4028. : ZSTD_compress_insertDictionary(
  4029. cctx->blockState.prevCBlock, &cctx->blockState.matchState,
  4030. &cctx->ldmState, &cctx->workspace, &cctx->appliedParams, dict, dictSize,
  4031. dictContentType, dtlm, cctx->entropyWorkspace);
  4032. FORWARD_IF_ERROR(dictID, "ZSTD_compress_insertDictionary failed");
  4033. assert(dictID <= UINT_MAX);
  4034. cctx->dictID = (U32)dictID;
  4035. cctx->dictContentSize = dictContentSize;
  4036. }
  4037. return 0;
  4038. }
  4039. size_t ZSTD_compressBegin_advanced_internal(ZSTD_CCtx* cctx,
  4040. const void* dict, size_t dictSize,
  4041. ZSTD_dictContentType_e dictContentType,
  4042. ZSTD_dictTableLoadMethod_e dtlm,
  4043. const ZSTD_CDict* cdict,
  4044. const ZSTD_CCtx_params* params,
  4045. unsigned long long pledgedSrcSize)
  4046. {
  4047. DEBUGLOG(4, "ZSTD_compressBegin_advanced_internal: wlog=%u", params->cParams.windowLog);
  4048. /* compression parameters verification and optimization */
  4049. FORWARD_IF_ERROR( ZSTD_checkCParams(params->cParams) , "");
  4050. return ZSTD_compressBegin_internal(cctx,
  4051. dict, dictSize, dictContentType, dtlm,
  4052. cdict,
  4053. params, pledgedSrcSize,
  4054. ZSTDb_not_buffered);
  4055. }
  4056. /*! ZSTD_compressBegin_advanced() :
  4057. * @return : 0, or an error code */
  4058. size_t ZSTD_compressBegin_advanced(ZSTD_CCtx* cctx,
  4059. const void* dict, size_t dictSize,
  4060. ZSTD_parameters params, unsigned long long pledgedSrcSize)
  4061. {
  4062. ZSTD_CCtx_params cctxParams;
  4063. ZSTD_CCtxParams_init_internal(&cctxParams, &params, ZSTD_NO_CLEVEL);
  4064. return ZSTD_compressBegin_advanced_internal(cctx,
  4065. dict, dictSize, ZSTD_dct_auto, ZSTD_dtlm_fast,
  4066. NULL /*cdict*/,
  4067. &cctxParams, pledgedSrcSize);
  4068. }
  4069. size_t ZSTD_compressBegin_usingDict(ZSTD_CCtx* cctx, const void* dict, size_t dictSize, int compressionLevel)
  4070. {
  4071. ZSTD_CCtx_params cctxParams;
  4072. {
  4073. ZSTD_parameters const params = ZSTD_getParams_internal(compressionLevel, ZSTD_CONTENTSIZE_UNKNOWN, dictSize, ZSTD_cpm_noAttachDict);
  4074. ZSTD_CCtxParams_init_internal(&cctxParams, &params, (compressionLevel == 0) ? ZSTD_CLEVEL_DEFAULT : compressionLevel);
  4075. }
  4076. DEBUGLOG(4, "ZSTD_compressBegin_usingDict (dictSize=%u)", (unsigned)dictSize);
  4077. return ZSTD_compressBegin_internal(cctx, dict, dictSize, ZSTD_dct_auto, ZSTD_dtlm_fast, NULL,
  4078. &cctxParams, ZSTD_CONTENTSIZE_UNKNOWN, ZSTDb_not_buffered);
  4079. }
  4080. size_t ZSTD_compressBegin(ZSTD_CCtx* cctx, int compressionLevel)
  4081. {
  4082. return ZSTD_compressBegin_usingDict(cctx, NULL, 0, compressionLevel);
  4083. }
  4084. /*! ZSTD_writeEpilogue() :
  4085. * Ends a frame.
  4086. * @return : nb of bytes written into dst (or an error code) */
  4087. static size_t ZSTD_writeEpilogue(ZSTD_CCtx* cctx, void* dst, size_t dstCapacity)
  4088. {
  4089. BYTE* const ostart = (BYTE*)dst;
  4090. BYTE* op = ostart;
  4091. size_t fhSize = 0;
  4092. DEBUGLOG(4, "ZSTD_writeEpilogue");
  4093. RETURN_ERROR_IF(cctx->stage == ZSTDcs_created, stage_wrong, "init missing");
  4094. /* special case : empty frame */
  4095. if (cctx->stage == ZSTDcs_init) {
  4096. fhSize = ZSTD_writeFrameHeader(dst, dstCapacity, &cctx->appliedParams, 0, 0);
  4097. FORWARD_IF_ERROR(fhSize, "ZSTD_writeFrameHeader failed");
  4098. dstCapacity -= fhSize;
  4099. op += fhSize;
  4100. cctx->stage = ZSTDcs_ongoing;
  4101. }
  4102. if (cctx->stage != ZSTDcs_ending) {
  4103. /* write one last empty block, make it the "last" block */
  4104. U32 const cBlockHeader24 = 1 /* last block */ + (((U32)bt_raw)<<1) + 0;
  4105. RETURN_ERROR_IF(dstCapacity<4, dstSize_tooSmall, "no room for epilogue");
  4106. MEM_writeLE32(op, cBlockHeader24);
  4107. op += ZSTD_blockHeaderSize;
  4108. dstCapacity -= ZSTD_blockHeaderSize;
  4109. }
  4110. if (cctx->appliedParams.fParams.checksumFlag) {
  4111. U32 const checksum = (U32) XXH64_digest(&cctx->xxhState);
  4112. RETURN_ERROR_IF(dstCapacity<4, dstSize_tooSmall, "no room for checksum");
  4113. DEBUGLOG(4, "ZSTD_writeEpilogue: write checksum : %08X", (unsigned)checksum);
  4114. MEM_writeLE32(op, checksum);
  4115. op += 4;
  4116. }
  4117. cctx->stage = ZSTDcs_created; /* return to "created but no init" status */
  4118. return op-ostart;
  4119. }
  4120. void ZSTD_CCtx_trace(ZSTD_CCtx* cctx, size_t extraCSize)
  4121. {
  4122. #if ZSTD_TRACE
  4123. if (cctx->traceCtx && ZSTD_trace_compress_end != NULL) {
  4124. int const streaming = cctx->inBuffSize > 0 || cctx->outBuffSize > 0 || cctx->appliedParams.nbWorkers > 0;
  4125. ZSTD_Trace trace;
  4126. ZSTD_memset(&trace, 0, sizeof(trace));
  4127. trace.version = ZSTD_VERSION_NUMBER;
  4128. trace.streaming = streaming;
  4129. trace.dictionaryID = cctx->dictID;
  4130. trace.dictionarySize = cctx->dictContentSize;
  4131. trace.uncompressedSize = cctx->consumedSrcSize;
  4132. trace.compressedSize = cctx->producedCSize + extraCSize;
  4133. trace.params = &cctx->appliedParams;
  4134. trace.cctx = cctx;
  4135. ZSTD_trace_compress_end(cctx->traceCtx, &trace);
  4136. }
  4137. cctx->traceCtx = 0;
  4138. #else
  4139. (void)cctx;
  4140. (void)extraCSize;
  4141. #endif
  4142. }
  4143. size_t ZSTD_compressEnd (ZSTD_CCtx* cctx,
  4144. void* dst, size_t dstCapacity,
  4145. const void* src, size_t srcSize)
  4146. {
  4147. size_t endResult;
  4148. size_t const cSize = ZSTD_compressContinue_internal(cctx,
  4149. dst, dstCapacity, src, srcSize,
  4150. 1 /* frame mode */, 1 /* last chunk */);
  4151. FORWARD_IF_ERROR(cSize, "ZSTD_compressContinue_internal failed");
  4152. endResult = ZSTD_writeEpilogue(cctx, (char*)dst + cSize, dstCapacity-cSize);
  4153. FORWARD_IF_ERROR(endResult, "ZSTD_writeEpilogue failed");
  4154. assert(!(cctx->appliedParams.fParams.contentSizeFlag && cctx->pledgedSrcSizePlusOne == 0));
  4155. if (cctx->pledgedSrcSizePlusOne != 0) { /* control src size */
  4156. ZSTD_STATIC_ASSERT(ZSTD_CONTENTSIZE_UNKNOWN == (unsigned long long)-1);
  4157. DEBUGLOG(4, "end of frame : controlling src size");
  4158. RETURN_ERROR_IF(
  4159. cctx->pledgedSrcSizePlusOne != cctx->consumedSrcSize+1,
  4160. srcSize_wrong,
  4161. "error : pledgedSrcSize = %u, while realSrcSize = %u",
  4162. (unsigned)cctx->pledgedSrcSizePlusOne-1,
  4163. (unsigned)cctx->consumedSrcSize);
  4164. }
  4165. ZSTD_CCtx_trace(cctx, endResult);
  4166. return cSize + endResult;
  4167. }
  4168. size_t ZSTD_compress_advanced (ZSTD_CCtx* cctx,
  4169. void* dst, size_t dstCapacity,
  4170. const void* src, size_t srcSize,
  4171. const void* dict,size_t dictSize,
  4172. ZSTD_parameters params)
  4173. {
  4174. DEBUGLOG(4, "ZSTD_compress_advanced");
  4175. FORWARD_IF_ERROR(ZSTD_checkCParams(params.cParams), "");
  4176. ZSTD_CCtxParams_init_internal(&cctx->simpleApiParams, &params, ZSTD_NO_CLEVEL);
  4177. return ZSTD_compress_advanced_internal(cctx,
  4178. dst, dstCapacity,
  4179. src, srcSize,
  4180. dict, dictSize,
  4181. &cctx->simpleApiParams);
  4182. }
  4183. /* Internal */
  4184. size_t ZSTD_compress_advanced_internal(
  4185. ZSTD_CCtx* cctx,
  4186. void* dst, size_t dstCapacity,
  4187. const void* src, size_t srcSize,
  4188. const void* dict,size_t dictSize,
  4189. const ZSTD_CCtx_params* params)
  4190. {
  4191. DEBUGLOG(4, "ZSTD_compress_advanced_internal (srcSize:%u)", (unsigned)srcSize);
  4192. FORWARD_IF_ERROR( ZSTD_compressBegin_internal(cctx,
  4193. dict, dictSize, ZSTD_dct_auto, ZSTD_dtlm_fast, NULL,
  4194. params, srcSize, ZSTDb_not_buffered) , "");
  4195. return ZSTD_compressEnd(cctx, dst, dstCapacity, src, srcSize);
  4196. }
  4197. size_t ZSTD_compress_usingDict(ZSTD_CCtx* cctx,
  4198. void* dst, size_t dstCapacity,
  4199. const void* src, size_t srcSize,
  4200. const void* dict, size_t dictSize,
  4201. int compressionLevel)
  4202. {
  4203. {
  4204. ZSTD_parameters const params = ZSTD_getParams_internal(compressionLevel, srcSize, dict ? dictSize : 0, ZSTD_cpm_noAttachDict);
  4205. assert(params.fParams.contentSizeFlag == 1);
  4206. ZSTD_CCtxParams_init_internal(&cctx->simpleApiParams, &params, (compressionLevel == 0) ? ZSTD_CLEVEL_DEFAULT: compressionLevel);
  4207. }
  4208. DEBUGLOG(4, "ZSTD_compress_usingDict (srcSize=%u)", (unsigned)srcSize);
  4209. return ZSTD_compress_advanced_internal(cctx, dst, dstCapacity, src, srcSize, dict, dictSize, &cctx->simpleApiParams);
  4210. }
  4211. size_t ZSTD_compressCCtx(ZSTD_CCtx* cctx,
  4212. void* dst, size_t dstCapacity,
  4213. const void* src, size_t srcSize,
  4214. int compressionLevel)
  4215. {
  4216. DEBUGLOG(4, "ZSTD_compressCCtx (srcSize=%u)", (unsigned)srcSize);
  4217. assert(cctx != NULL);
  4218. return ZSTD_compress_usingDict(cctx, dst, dstCapacity, src, srcSize, NULL, 0, compressionLevel);
  4219. }
  4220. size_t ZSTD_compress(void* dst, size_t dstCapacity,
  4221. const void* src, size_t srcSize,
  4222. int compressionLevel)
  4223. {
  4224. size_t result;
  4225. #if ZSTD_COMPRESS_HEAPMODE
  4226. ZSTD_CCtx* cctx = ZSTD_createCCtx();
  4227. RETURN_ERROR_IF(!cctx, memory_allocation, "ZSTD_createCCtx failed");
  4228. result = ZSTD_compressCCtx(cctx, dst, dstCapacity, src, srcSize, compressionLevel);
  4229. ZSTD_freeCCtx(cctx);
  4230. #else
  4231. ZSTD_CCtx ctxBody;
  4232. ZSTD_initCCtx(&ctxBody, ZSTD_defaultCMem);
  4233. result = ZSTD_compressCCtx(&ctxBody, dst, dstCapacity, src, srcSize, compressionLevel);
  4234. ZSTD_freeCCtxContent(&ctxBody); /* can't free ctxBody itself, as it's on stack; free only heap content */
  4235. #endif
  4236. return result;
  4237. }
  4238. /* ===== Dictionary API ===== */
  4239. /*! ZSTD_estimateCDictSize_advanced() :
  4240. * Estimate amount of memory that will be needed to create a dictionary with following arguments */
  4241. size_t ZSTD_estimateCDictSize_advanced(
  4242. size_t dictSize, ZSTD_compressionParameters cParams,
  4243. ZSTD_dictLoadMethod_e dictLoadMethod)
  4244. {
  4245. DEBUGLOG(5, "sizeof(ZSTD_CDict) : %u", (unsigned)sizeof(ZSTD_CDict));
  4246. return ZSTD_cwksp_alloc_size(sizeof(ZSTD_CDict))
  4247. + ZSTD_cwksp_alloc_size(HUF_WORKSPACE_SIZE)
  4248. /* enableDedicatedDictSearch == 1 ensures that CDict estimation will not be too small
  4249. * in case we are using DDS with row-hash. */
  4250. + ZSTD_sizeof_matchState(&cParams, ZSTD_resolveRowMatchFinderMode(ZSTD_urm_auto, &cParams),
  4251. /* enableDedicatedDictSearch */ 1, /* forCCtx */ 0)
  4252. + (dictLoadMethod == ZSTD_dlm_byRef ? 0
  4253. : ZSTD_cwksp_alloc_size(ZSTD_cwksp_align(dictSize, sizeof(void *))));
  4254. }
  4255. size_t ZSTD_estimateCDictSize(size_t dictSize, int compressionLevel)
  4256. {
  4257. ZSTD_compressionParameters const cParams = ZSTD_getCParams_internal(compressionLevel, ZSTD_CONTENTSIZE_UNKNOWN, dictSize, ZSTD_cpm_createCDict);
  4258. return ZSTD_estimateCDictSize_advanced(dictSize, cParams, ZSTD_dlm_byCopy);
  4259. }
  4260. size_t ZSTD_sizeof_CDict(const ZSTD_CDict* cdict)
  4261. {
  4262. if (cdict==NULL) return 0; /* support sizeof on NULL */
  4263. DEBUGLOG(5, "sizeof(*cdict) : %u", (unsigned)sizeof(*cdict));
  4264. /* cdict may be in the workspace */
  4265. return (cdict->workspace.workspace == cdict ? 0 : sizeof(*cdict))
  4266. + ZSTD_cwksp_sizeof(&cdict->workspace);
  4267. }
  4268. static size_t ZSTD_initCDict_internal(
  4269. ZSTD_CDict* cdict,
  4270. const void* dictBuffer, size_t dictSize,
  4271. ZSTD_dictLoadMethod_e dictLoadMethod,
  4272. ZSTD_dictContentType_e dictContentType,
  4273. ZSTD_CCtx_params params)
  4274. {
  4275. DEBUGLOG(3, "ZSTD_initCDict_internal (dictContentType:%u)", (unsigned)dictContentType);
  4276. assert(!ZSTD_checkCParams(params.cParams));
  4277. cdict->matchState.cParams = params.cParams;
  4278. cdict->matchState.dedicatedDictSearch = params.enableDedicatedDictSearch;
  4279. if ((dictLoadMethod == ZSTD_dlm_byRef) || (!dictBuffer) || (!dictSize)) {
  4280. cdict->dictContent = dictBuffer;
  4281. } else {
  4282. void *internalBuffer = ZSTD_cwksp_reserve_object(&cdict->workspace, ZSTD_cwksp_align(dictSize, sizeof(void*)));
  4283. RETURN_ERROR_IF(!internalBuffer, memory_allocation, "NULL pointer!");
  4284. cdict->dictContent = internalBuffer;
  4285. ZSTD_memcpy(internalBuffer, dictBuffer, dictSize);
  4286. }
  4287. cdict->dictContentSize = dictSize;
  4288. cdict->dictContentType = dictContentType;
  4289. cdict->entropyWorkspace = (U32*)ZSTD_cwksp_reserve_object(&cdict->workspace, HUF_WORKSPACE_SIZE);
  4290. /* Reset the state to no dictionary */
  4291. ZSTD_reset_compressedBlockState(&cdict->cBlockState);
  4292. FORWARD_IF_ERROR(ZSTD_reset_matchState(
  4293. &cdict->matchState,
  4294. &cdict->workspace,
  4295. &params.cParams,
  4296. params.useRowMatchFinder,
  4297. ZSTDcrp_makeClean,
  4298. ZSTDirp_reset,
  4299. ZSTD_resetTarget_CDict), "");
  4300. /* (Maybe) load the dictionary
  4301. * Skips loading the dictionary if it is < 8 bytes.
  4302. */
  4303. { params.compressionLevel = ZSTD_CLEVEL_DEFAULT;
  4304. params.fParams.contentSizeFlag = 1;
  4305. { size_t const dictID = ZSTD_compress_insertDictionary(
  4306. &cdict->cBlockState, &cdict->matchState, NULL, &cdict->workspace,
  4307. &params, cdict->dictContent, cdict->dictContentSize,
  4308. dictContentType, ZSTD_dtlm_full, cdict->entropyWorkspace);
  4309. FORWARD_IF_ERROR(dictID, "ZSTD_compress_insertDictionary failed");
  4310. assert(dictID <= (size_t)(U32)-1);
  4311. cdict->dictID = (U32)dictID;
  4312. }
  4313. }
  4314. return 0;
  4315. }
  4316. static ZSTD_CDict* ZSTD_createCDict_advanced_internal(size_t dictSize,
  4317. ZSTD_dictLoadMethod_e dictLoadMethod,
  4318. ZSTD_compressionParameters cParams,
  4319. ZSTD_useRowMatchFinderMode_e useRowMatchFinder,
  4320. U32 enableDedicatedDictSearch,
  4321. ZSTD_customMem customMem)
  4322. {
  4323. if ((!customMem.customAlloc) ^ (!customMem.customFree)) return NULL;
  4324. { size_t const workspaceSize =
  4325. ZSTD_cwksp_alloc_size(sizeof(ZSTD_CDict)) +
  4326. ZSTD_cwksp_alloc_size(HUF_WORKSPACE_SIZE) +
  4327. ZSTD_sizeof_matchState(&cParams, useRowMatchFinder, enableDedicatedDictSearch, /* forCCtx */ 0) +
  4328. (dictLoadMethod == ZSTD_dlm_byRef ? 0
  4329. : ZSTD_cwksp_alloc_size(ZSTD_cwksp_align(dictSize, sizeof(void*))));
  4330. void* const workspace = ZSTD_customMalloc(workspaceSize, customMem);
  4331. ZSTD_cwksp ws;
  4332. ZSTD_CDict* cdict;
  4333. if (!workspace) {
  4334. ZSTD_customFree(workspace, customMem);
  4335. return NULL;
  4336. }
  4337. ZSTD_cwksp_init(&ws, workspace, workspaceSize, ZSTD_cwksp_dynamic_alloc);
  4338. cdict = (ZSTD_CDict*)ZSTD_cwksp_reserve_object(&ws, sizeof(ZSTD_CDict));
  4339. assert(cdict != NULL);
  4340. ZSTD_cwksp_move(&cdict->workspace, &ws);
  4341. cdict->customMem = customMem;
  4342. cdict->compressionLevel = ZSTD_NO_CLEVEL; /* signals advanced API usage */
  4343. cdict->useRowMatchFinder = useRowMatchFinder;
  4344. return cdict;
  4345. }
  4346. }
  4347. ZSTD_CDict* ZSTD_createCDict_advanced(const void* dictBuffer, size_t dictSize,
  4348. ZSTD_dictLoadMethod_e dictLoadMethod,
  4349. ZSTD_dictContentType_e dictContentType,
  4350. ZSTD_compressionParameters cParams,
  4351. ZSTD_customMem customMem)
  4352. {
  4353. ZSTD_CCtx_params cctxParams;
  4354. ZSTD_memset(&cctxParams, 0, sizeof(cctxParams));
  4355. ZSTD_CCtxParams_init(&cctxParams, 0);
  4356. cctxParams.cParams = cParams;
  4357. cctxParams.customMem = customMem;
  4358. return ZSTD_createCDict_advanced2(
  4359. dictBuffer, dictSize,
  4360. dictLoadMethod, dictContentType,
  4361. &cctxParams, customMem);
  4362. }
  4363. ZSTDLIB_API ZSTD_CDict* ZSTD_createCDict_advanced2(
  4364. const void* dict, size_t dictSize,
  4365. ZSTD_dictLoadMethod_e dictLoadMethod,
  4366. ZSTD_dictContentType_e dictContentType,
  4367. const ZSTD_CCtx_params* originalCctxParams,
  4368. ZSTD_customMem customMem)
  4369. {
  4370. ZSTD_CCtx_params cctxParams = *originalCctxParams;
  4371. ZSTD_compressionParameters cParams;
  4372. ZSTD_CDict* cdict;
  4373. DEBUGLOG(3, "ZSTD_createCDict_advanced2, mode %u", (unsigned)dictContentType);
  4374. if (!customMem.customAlloc ^ !customMem.customFree) return NULL;
  4375. if (cctxParams.enableDedicatedDictSearch) {
  4376. cParams = ZSTD_dedicatedDictSearch_getCParams(
  4377. cctxParams.compressionLevel, dictSize);
  4378. ZSTD_overrideCParams(&cParams, &cctxParams.cParams);
  4379. } else {
  4380. cParams = ZSTD_getCParamsFromCCtxParams(
  4381. &cctxParams, ZSTD_CONTENTSIZE_UNKNOWN, dictSize, ZSTD_cpm_createCDict);
  4382. }
  4383. if (!ZSTD_dedicatedDictSearch_isSupported(&cParams)) {
  4384. /* Fall back to non-DDSS params */
  4385. cctxParams.enableDedicatedDictSearch = 0;
  4386. cParams = ZSTD_getCParamsFromCCtxParams(
  4387. &cctxParams, ZSTD_CONTENTSIZE_UNKNOWN, dictSize, ZSTD_cpm_createCDict);
  4388. }
  4389. DEBUGLOG(3, "ZSTD_createCDict_advanced2: DDS: %u", cctxParams.enableDedicatedDictSearch);
  4390. cctxParams.cParams = cParams;
  4391. cctxParams.useRowMatchFinder = ZSTD_resolveRowMatchFinderMode(cctxParams.useRowMatchFinder, &cParams);
  4392. cdict = ZSTD_createCDict_advanced_internal(dictSize,
  4393. dictLoadMethod, cctxParams.cParams,
  4394. cctxParams.useRowMatchFinder, cctxParams.enableDedicatedDictSearch,
  4395. customMem);
  4396. if (ZSTD_isError( ZSTD_initCDict_internal(cdict,
  4397. dict, dictSize,
  4398. dictLoadMethod, dictContentType,
  4399. cctxParams) )) {
  4400. ZSTD_freeCDict(cdict);
  4401. return NULL;
  4402. }
  4403. return cdict;
  4404. }
  4405. ZSTD_CDict* ZSTD_createCDict(const void* dict, size_t dictSize, int compressionLevel)
  4406. {
  4407. ZSTD_compressionParameters cParams = ZSTD_getCParams_internal(compressionLevel, ZSTD_CONTENTSIZE_UNKNOWN, dictSize, ZSTD_cpm_createCDict);
  4408. ZSTD_CDict* const cdict = ZSTD_createCDict_advanced(dict, dictSize,
  4409. ZSTD_dlm_byCopy, ZSTD_dct_auto,
  4410. cParams, ZSTD_defaultCMem);
  4411. if (cdict)
  4412. cdict->compressionLevel = (compressionLevel == 0) ? ZSTD_CLEVEL_DEFAULT : compressionLevel;
  4413. return cdict;
  4414. }
  4415. ZSTD_CDict* ZSTD_createCDict_byReference(const void* dict, size_t dictSize, int compressionLevel)
  4416. {
  4417. ZSTD_compressionParameters cParams = ZSTD_getCParams_internal(compressionLevel, ZSTD_CONTENTSIZE_UNKNOWN, dictSize, ZSTD_cpm_createCDict);
  4418. ZSTD_CDict* const cdict = ZSTD_createCDict_advanced(dict, dictSize,
  4419. ZSTD_dlm_byRef, ZSTD_dct_auto,
  4420. cParams, ZSTD_defaultCMem);
  4421. if (cdict)
  4422. cdict->compressionLevel = (compressionLevel == 0) ? ZSTD_CLEVEL_DEFAULT : compressionLevel;
  4423. return cdict;
  4424. }
  4425. size_t ZSTD_freeCDict(ZSTD_CDict* cdict)
  4426. {
  4427. if (cdict==NULL) return 0; /* support free on NULL */
  4428. { ZSTD_customMem const cMem = cdict->customMem;
  4429. int cdictInWorkspace = ZSTD_cwksp_owns_buffer(&cdict->workspace, cdict);
  4430. ZSTD_cwksp_free(&cdict->workspace, cMem);
  4431. if (!cdictInWorkspace) {
  4432. ZSTD_customFree(cdict, cMem);
  4433. }
  4434. return 0;
  4435. }
  4436. }
  4437. /*! ZSTD_initStaticCDict_advanced() :
  4438. * Generate a digested dictionary in provided memory area.
  4439. * workspace: The memory area to emplace the dictionary into.
  4440. * Provided pointer must 8-bytes aligned.
  4441. * It must outlive dictionary usage.
  4442. * workspaceSize: Use ZSTD_estimateCDictSize()
  4443. * to determine how large workspace must be.
  4444. * cParams : use ZSTD_getCParams() to transform a compression level
  4445. * into its relevants cParams.
  4446. * @return : pointer to ZSTD_CDict*, or NULL if error (size too small)
  4447. * Note : there is no corresponding "free" function.
  4448. * Since workspace was allocated externally, it must be freed externally.
  4449. */
  4450. const ZSTD_CDict* ZSTD_initStaticCDict(
  4451. void* workspace, size_t workspaceSize,
  4452. const void* dict, size_t dictSize,
  4453. ZSTD_dictLoadMethod_e dictLoadMethod,
  4454. ZSTD_dictContentType_e dictContentType,
  4455. ZSTD_compressionParameters cParams)
  4456. {
  4457. ZSTD_useRowMatchFinderMode_e const useRowMatchFinder = ZSTD_resolveRowMatchFinderMode(ZSTD_urm_auto, &cParams);
  4458. /* enableDedicatedDictSearch == 1 ensures matchstate is not too small in case this CDict will be used for DDS + row hash */
  4459. size_t const matchStateSize = ZSTD_sizeof_matchState(&cParams, useRowMatchFinder, /* enableDedicatedDictSearch */ 1, /* forCCtx */ 0);
  4460. size_t const neededSize = ZSTD_cwksp_alloc_size(sizeof(ZSTD_CDict))
  4461. + (dictLoadMethod == ZSTD_dlm_byRef ? 0
  4462. : ZSTD_cwksp_alloc_size(ZSTD_cwksp_align(dictSize, sizeof(void*))))
  4463. + ZSTD_cwksp_alloc_size(HUF_WORKSPACE_SIZE)
  4464. + matchStateSize;
  4465. ZSTD_CDict* cdict;
  4466. ZSTD_CCtx_params params;
  4467. if ((size_t)workspace & 7) return NULL; /* 8-aligned */
  4468. {
  4469. ZSTD_cwksp ws;
  4470. ZSTD_cwksp_init(&ws, workspace, workspaceSize, ZSTD_cwksp_static_alloc);
  4471. cdict = (ZSTD_CDict*)ZSTD_cwksp_reserve_object(&ws, sizeof(ZSTD_CDict));
  4472. if (cdict == NULL) return NULL;
  4473. ZSTD_cwksp_move(&cdict->workspace, &ws);
  4474. }
  4475. DEBUGLOG(4, "(workspaceSize < neededSize) : (%u < %u) => %u",
  4476. (unsigned)workspaceSize, (unsigned)neededSize, (unsigned)(workspaceSize < neededSize));
  4477. if (workspaceSize < neededSize) return NULL;
  4478. ZSTD_CCtxParams_init(&params, 0);
  4479. params.cParams = cParams;
  4480. params.useRowMatchFinder = useRowMatchFinder;
  4481. cdict->useRowMatchFinder = useRowMatchFinder;
  4482. if (ZSTD_isError( ZSTD_initCDict_internal(cdict,
  4483. dict, dictSize,
  4484. dictLoadMethod, dictContentType,
  4485. params) ))
  4486. return NULL;
  4487. return cdict;
  4488. }
  4489. ZSTD_compressionParameters ZSTD_getCParamsFromCDict(const ZSTD_CDict* cdict)
  4490. {
  4491. assert(cdict != NULL);
  4492. return cdict->matchState.cParams;
  4493. }
  4494. /*! ZSTD_getDictID_fromCDict() :
  4495. * Provides the dictID of the dictionary loaded into `cdict`.
  4496. * If @return == 0, the dictionary is not conformant to Zstandard specification, or empty.
  4497. * Non-conformant dictionaries can still be loaded, but as content-only dictionaries. */
  4498. unsigned ZSTD_getDictID_fromCDict(const ZSTD_CDict* cdict)
  4499. {
  4500. if (cdict==NULL) return 0;
  4501. return cdict->dictID;
  4502. }
  4503. /* ZSTD_compressBegin_usingCDict_internal() :
  4504. * Implementation of various ZSTD_compressBegin_usingCDict* functions.
  4505. */
  4506. static size_t ZSTD_compressBegin_usingCDict_internal(
  4507. ZSTD_CCtx* const cctx, const ZSTD_CDict* const cdict,
  4508. ZSTD_frameParameters const fParams, unsigned long long const pledgedSrcSize)
  4509. {
  4510. ZSTD_CCtx_params cctxParams;
  4511. DEBUGLOG(4, "ZSTD_compressBegin_usingCDict_internal");
  4512. RETURN_ERROR_IF(cdict==NULL, dictionary_wrong, "NULL pointer!");
  4513. /* Initialize the cctxParams from the cdict */
  4514. {
  4515. ZSTD_parameters params;
  4516. params.fParams = fParams;
  4517. params.cParams = ( pledgedSrcSize < ZSTD_USE_CDICT_PARAMS_SRCSIZE_CUTOFF
  4518. || pledgedSrcSize < cdict->dictContentSize * ZSTD_USE_CDICT_PARAMS_DICTSIZE_MULTIPLIER
  4519. || pledgedSrcSize == ZSTD_CONTENTSIZE_UNKNOWN
  4520. || cdict->compressionLevel == 0 ) ?
  4521. ZSTD_getCParamsFromCDict(cdict)
  4522. : ZSTD_getCParams(cdict->compressionLevel,
  4523. pledgedSrcSize,
  4524. cdict->dictContentSize);
  4525. ZSTD_CCtxParams_init_internal(&cctxParams, &params, cdict->compressionLevel);
  4526. }
  4527. /* Increase window log to fit the entire dictionary and source if the
  4528. * source size is known. Limit the increase to 19, which is the
  4529. * window log for compression level 1 with the largest source size.
  4530. */
  4531. if (pledgedSrcSize != ZSTD_CONTENTSIZE_UNKNOWN) {
  4532. U32 const limitedSrcSize = (U32)MIN(pledgedSrcSize, 1U << 19);
  4533. U32 const limitedSrcLog = limitedSrcSize > 1 ? ZSTD_highbit32(limitedSrcSize - 1) + 1 : 1;
  4534. cctxParams.cParams.windowLog = MAX(cctxParams.cParams.windowLog, limitedSrcLog);
  4535. }
  4536. return ZSTD_compressBegin_internal(cctx,
  4537. NULL, 0, ZSTD_dct_auto, ZSTD_dtlm_fast,
  4538. cdict,
  4539. &cctxParams, pledgedSrcSize,
  4540. ZSTDb_not_buffered);
  4541. }
  4542. /* ZSTD_compressBegin_usingCDict_advanced() :
  4543. * This function is DEPRECATED.
  4544. * cdict must be != NULL */
  4545. size_t ZSTD_compressBegin_usingCDict_advanced(
  4546. ZSTD_CCtx* const cctx, const ZSTD_CDict* const cdict,
  4547. ZSTD_frameParameters const fParams, unsigned long long const pledgedSrcSize)
  4548. {
  4549. return ZSTD_compressBegin_usingCDict_internal(cctx, cdict, fParams, pledgedSrcSize);
  4550. }
  4551. /* ZSTD_compressBegin_usingCDict() :
  4552. * cdict must be != NULL */
  4553. size_t ZSTD_compressBegin_usingCDict(ZSTD_CCtx* cctx, const ZSTD_CDict* cdict)
  4554. {
  4555. ZSTD_frameParameters const fParams = { 0 /*content*/, 0 /*checksum*/, 0 /*noDictID*/ };
  4556. return ZSTD_compressBegin_usingCDict_internal(cctx, cdict, fParams, ZSTD_CONTENTSIZE_UNKNOWN);
  4557. }
  4558. /*! ZSTD_compress_usingCDict_internal():
  4559. * Implementation of various ZSTD_compress_usingCDict* functions.
  4560. */
  4561. static size_t ZSTD_compress_usingCDict_internal(ZSTD_CCtx* cctx,
  4562. void* dst, size_t dstCapacity,
  4563. const void* src, size_t srcSize,
  4564. const ZSTD_CDict* cdict, ZSTD_frameParameters fParams)
  4565. {
  4566. FORWARD_IF_ERROR(ZSTD_compressBegin_usingCDict_internal(cctx, cdict, fParams, srcSize), ""); /* will check if cdict != NULL */
  4567. return ZSTD_compressEnd(cctx, dst, dstCapacity, src, srcSize);
  4568. }
  4569. /*! ZSTD_compress_usingCDict_advanced():
  4570. * This function is DEPRECATED.
  4571. */
  4572. size_t ZSTD_compress_usingCDict_advanced(ZSTD_CCtx* cctx,
  4573. void* dst, size_t dstCapacity,
  4574. const void* src, size_t srcSize,
  4575. const ZSTD_CDict* cdict, ZSTD_frameParameters fParams)
  4576. {
  4577. return ZSTD_compress_usingCDict_internal(cctx, dst, dstCapacity, src, srcSize, cdict, fParams);
  4578. }
  4579. /*! ZSTD_compress_usingCDict() :
  4580. * Compression using a digested Dictionary.
  4581. * Faster startup than ZSTD_compress_usingDict(), recommended when same dictionary is used multiple times.
  4582. * Note that compression parameters are decided at CDict creation time
  4583. * while frame parameters are hardcoded */
  4584. size_t ZSTD_compress_usingCDict(ZSTD_CCtx* cctx,
  4585. void* dst, size_t dstCapacity,
  4586. const void* src, size_t srcSize,
  4587. const ZSTD_CDict* cdict)
  4588. {
  4589. ZSTD_frameParameters const fParams = { 1 /*content*/, 0 /*checksum*/, 0 /*noDictID*/ };
  4590. return ZSTD_compress_usingCDict_internal(cctx, dst, dstCapacity, src, srcSize, cdict, fParams);
  4591. }
  4592. /* ******************************************************************
  4593. * Streaming
  4594. ********************************************************************/
  4595. ZSTD_CStream* ZSTD_createCStream(void)
  4596. {
  4597. DEBUGLOG(3, "ZSTD_createCStream");
  4598. return ZSTD_createCStream_advanced(ZSTD_defaultCMem);
  4599. }
  4600. ZSTD_CStream* ZSTD_initStaticCStream(void *workspace, size_t workspaceSize)
  4601. {
  4602. return ZSTD_initStaticCCtx(workspace, workspaceSize);
  4603. }
  4604. ZSTD_CStream* ZSTD_createCStream_advanced(ZSTD_customMem customMem)
  4605. { /* CStream and CCtx are now same object */
  4606. return ZSTD_createCCtx_advanced(customMem);
  4607. }
  4608. size_t ZSTD_freeCStream(ZSTD_CStream* zcs)
  4609. {
  4610. return ZSTD_freeCCtx(zcs); /* same object */
  4611. }
  4612. /*====== Initialization ======*/
  4613. size_t ZSTD_CStreamInSize(void) { return ZSTD_BLOCKSIZE_MAX; }
  4614. size_t ZSTD_CStreamOutSize(void)
  4615. {
  4616. return ZSTD_compressBound(ZSTD_BLOCKSIZE_MAX) + ZSTD_blockHeaderSize + 4 /* 32-bits hash */ ;
  4617. }
  4618. static ZSTD_cParamMode_e ZSTD_getCParamMode(ZSTD_CDict const* cdict, ZSTD_CCtx_params const* params, U64 pledgedSrcSize)
  4619. {
  4620. if (cdict != NULL && ZSTD_shouldAttachDict(cdict, params, pledgedSrcSize))
  4621. return ZSTD_cpm_attachDict;
  4622. else
  4623. return ZSTD_cpm_noAttachDict;
  4624. }
  4625. /* ZSTD_resetCStream():
  4626. * pledgedSrcSize == 0 means "unknown" */
  4627. size_t ZSTD_resetCStream(ZSTD_CStream* zcs, unsigned long long pss)
  4628. {
  4629. /* temporary : 0 interpreted as "unknown" during transition period.
  4630. * Users willing to specify "unknown" **must** use ZSTD_CONTENTSIZE_UNKNOWN.
  4631. * 0 will be interpreted as "empty" in the future.
  4632. */
  4633. U64 const pledgedSrcSize = (pss==0) ? ZSTD_CONTENTSIZE_UNKNOWN : pss;
  4634. DEBUGLOG(4, "ZSTD_resetCStream: pledgedSrcSize = %u", (unsigned)pledgedSrcSize);
  4635. FORWARD_IF_ERROR( ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only) , "");
  4636. FORWARD_IF_ERROR( ZSTD_CCtx_setPledgedSrcSize(zcs, pledgedSrcSize) , "");
  4637. return 0;
  4638. }
  4639. /*! ZSTD_initCStream_internal() :
  4640. * Note : for lib/compress only. Used by zstdmt_compress.c.
  4641. * Assumption 1 : params are valid
  4642. * Assumption 2 : either dict, or cdict, is defined, not both */
  4643. size_t ZSTD_initCStream_internal(ZSTD_CStream* zcs,
  4644. const void* dict, size_t dictSize, const ZSTD_CDict* cdict,
  4645. const ZSTD_CCtx_params* params,
  4646. unsigned long long pledgedSrcSize)
  4647. {
  4648. DEBUGLOG(4, "ZSTD_initCStream_internal");
  4649. FORWARD_IF_ERROR( ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only) , "");
  4650. FORWARD_IF_ERROR( ZSTD_CCtx_setPledgedSrcSize(zcs, pledgedSrcSize) , "");
  4651. assert(!ZSTD_isError(ZSTD_checkCParams(params->cParams)));
  4652. zcs->requestedParams = *params;
  4653. assert(!((dict) && (cdict))); /* either dict or cdict, not both */
  4654. if (dict) {
  4655. FORWARD_IF_ERROR( ZSTD_CCtx_loadDictionary(zcs, dict, dictSize) , "");
  4656. } else {
  4657. /* Dictionary is cleared if !cdict */
  4658. FORWARD_IF_ERROR( ZSTD_CCtx_refCDict(zcs, cdict) , "");
  4659. }
  4660. return 0;
  4661. }
  4662. /* ZSTD_initCStream_usingCDict_advanced() :
  4663. * same as ZSTD_initCStream_usingCDict(), with control over frame parameters */
  4664. size_t ZSTD_initCStream_usingCDict_advanced(ZSTD_CStream* zcs,
  4665. const ZSTD_CDict* cdict,
  4666. ZSTD_frameParameters fParams,
  4667. unsigned long long pledgedSrcSize)
  4668. {
  4669. DEBUGLOG(4, "ZSTD_initCStream_usingCDict_advanced");
  4670. FORWARD_IF_ERROR( ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only) , "");
  4671. FORWARD_IF_ERROR( ZSTD_CCtx_setPledgedSrcSize(zcs, pledgedSrcSize) , "");
  4672. zcs->requestedParams.fParams = fParams;
  4673. FORWARD_IF_ERROR( ZSTD_CCtx_refCDict(zcs, cdict) , "");
  4674. return 0;
  4675. }
  4676. /* note : cdict must outlive compression session */
  4677. size_t ZSTD_initCStream_usingCDict(ZSTD_CStream* zcs, const ZSTD_CDict* cdict)
  4678. {
  4679. DEBUGLOG(4, "ZSTD_initCStream_usingCDict");
  4680. FORWARD_IF_ERROR( ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only) , "");
  4681. FORWARD_IF_ERROR( ZSTD_CCtx_refCDict(zcs, cdict) , "");
  4682. return 0;
  4683. }
  4684. /* ZSTD_initCStream_advanced() :
  4685. * pledgedSrcSize must be exact.
  4686. * if srcSize is not known at init time, use value ZSTD_CONTENTSIZE_UNKNOWN.
  4687. * dict is loaded with default parameters ZSTD_dct_auto and ZSTD_dlm_byCopy. */
  4688. size_t ZSTD_initCStream_advanced(ZSTD_CStream* zcs,
  4689. const void* dict, size_t dictSize,
  4690. ZSTD_parameters params, unsigned long long pss)
  4691. {
  4692. /* for compatibility with older programs relying on this behavior.
  4693. * Users should now specify ZSTD_CONTENTSIZE_UNKNOWN.
  4694. * This line will be removed in the future.
  4695. */
  4696. U64 const pledgedSrcSize = (pss==0 && params.fParams.contentSizeFlag==0) ? ZSTD_CONTENTSIZE_UNKNOWN : pss;
  4697. DEBUGLOG(4, "ZSTD_initCStream_advanced");
  4698. FORWARD_IF_ERROR( ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only) , "");
  4699. FORWARD_IF_ERROR( ZSTD_CCtx_setPledgedSrcSize(zcs, pledgedSrcSize) , "");
  4700. FORWARD_IF_ERROR( ZSTD_checkCParams(params.cParams) , "");
  4701. ZSTD_CCtxParams_setZstdParams(&zcs->requestedParams, &params);
  4702. FORWARD_IF_ERROR( ZSTD_CCtx_loadDictionary(zcs, dict, dictSize) , "");
  4703. return 0;
  4704. }
  4705. size_t ZSTD_initCStream_usingDict(ZSTD_CStream* zcs, const void* dict, size_t dictSize, int compressionLevel)
  4706. {
  4707. DEBUGLOG(4, "ZSTD_initCStream_usingDict");
  4708. FORWARD_IF_ERROR( ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only) , "");
  4709. FORWARD_IF_ERROR( ZSTD_CCtx_setParameter(zcs, ZSTD_c_compressionLevel, compressionLevel) , "");
  4710. FORWARD_IF_ERROR( ZSTD_CCtx_loadDictionary(zcs, dict, dictSize) , "");
  4711. return 0;
  4712. }
  4713. size_t ZSTD_initCStream_srcSize(ZSTD_CStream* zcs, int compressionLevel, unsigned long long pss)
  4714. {
  4715. /* temporary : 0 interpreted as "unknown" during transition period.
  4716. * Users willing to specify "unknown" **must** use ZSTD_CONTENTSIZE_UNKNOWN.
  4717. * 0 will be interpreted as "empty" in the future.
  4718. */
  4719. U64 const pledgedSrcSize = (pss==0) ? ZSTD_CONTENTSIZE_UNKNOWN : pss;
  4720. DEBUGLOG(4, "ZSTD_initCStream_srcSize");
  4721. FORWARD_IF_ERROR( ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only) , "");
  4722. FORWARD_IF_ERROR( ZSTD_CCtx_refCDict(zcs, NULL) , "");
  4723. FORWARD_IF_ERROR( ZSTD_CCtx_setParameter(zcs, ZSTD_c_compressionLevel, compressionLevel) , "");
  4724. FORWARD_IF_ERROR( ZSTD_CCtx_setPledgedSrcSize(zcs, pledgedSrcSize) , "");
  4725. return 0;
  4726. }
  4727. size_t ZSTD_initCStream(ZSTD_CStream* zcs, int compressionLevel)
  4728. {
  4729. DEBUGLOG(4, "ZSTD_initCStream");
  4730. FORWARD_IF_ERROR( ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only) , "");
  4731. FORWARD_IF_ERROR( ZSTD_CCtx_refCDict(zcs, NULL) , "");
  4732. FORWARD_IF_ERROR( ZSTD_CCtx_setParameter(zcs, ZSTD_c_compressionLevel, compressionLevel) , "");
  4733. return 0;
  4734. }
  4735. /*====== Compression ======*/
  4736. static size_t ZSTD_nextInputSizeHint(const ZSTD_CCtx* cctx)
  4737. {
  4738. size_t hintInSize = cctx->inBuffTarget - cctx->inBuffPos;
  4739. if (hintInSize==0) hintInSize = cctx->blockSize;
  4740. return hintInSize;
  4741. }
  4742. /** ZSTD_compressStream_generic():
  4743. * internal function for all *compressStream*() variants
  4744. * non-static, because can be called from zstdmt_compress.c
  4745. * @return : hint size for next input */
  4746. static size_t ZSTD_compressStream_generic(ZSTD_CStream* zcs,
  4747. ZSTD_outBuffer* output,
  4748. ZSTD_inBuffer* input,
  4749. ZSTD_EndDirective const flushMode)
  4750. {
  4751. const char* const istart = (const char*)input->src;
  4752. const char* const iend = input->size != 0 ? istart + input->size : istart;
  4753. const char* ip = input->pos != 0 ? istart + input->pos : istart;
  4754. char* const ostart = (char*)output->dst;
  4755. char* const oend = output->size != 0 ? ostart + output->size : ostart;
  4756. char* op = output->pos != 0 ? ostart + output->pos : ostart;
  4757. U32 someMoreWork = 1;
  4758. /* check expectations */
  4759. DEBUGLOG(5, "ZSTD_compressStream_generic, flush=%u", (unsigned)flushMode);
  4760. if (zcs->appliedParams.inBufferMode == ZSTD_bm_buffered) {
  4761. assert(zcs->inBuff != NULL);
  4762. assert(zcs->inBuffSize > 0);
  4763. }
  4764. if (zcs->appliedParams.outBufferMode == ZSTD_bm_buffered) {
  4765. assert(zcs->outBuff != NULL);
  4766. assert(zcs->outBuffSize > 0);
  4767. }
  4768. assert(output->pos <= output->size);
  4769. assert(input->pos <= input->size);
  4770. assert((U32)flushMode <= (U32)ZSTD_e_end);
  4771. while (someMoreWork) {
  4772. switch(zcs->streamStage)
  4773. {
  4774. case zcss_init:
  4775. RETURN_ERROR(init_missing, "call ZSTD_initCStream() first!");
  4776. case zcss_load:
  4777. if ( (flushMode == ZSTD_e_end)
  4778. && ( (size_t)(oend-op) >= ZSTD_compressBound(iend-ip) /* Enough output space */
  4779. || zcs->appliedParams.outBufferMode == ZSTD_bm_stable) /* OR we are allowed to return dstSizeTooSmall */
  4780. && (zcs->inBuffPos == 0) ) {
  4781. /* shortcut to compression pass directly into output buffer */
  4782. size_t const cSize = ZSTD_compressEnd(zcs,
  4783. op, oend-op, ip, iend-ip);
  4784. DEBUGLOG(4, "ZSTD_compressEnd : cSize=%u", (unsigned)cSize);
  4785. FORWARD_IF_ERROR(cSize, "ZSTD_compressEnd failed");
  4786. ip = iend;
  4787. op += cSize;
  4788. zcs->frameEnded = 1;
  4789. ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only);
  4790. someMoreWork = 0; break;
  4791. }
  4792. /* complete loading into inBuffer in buffered mode */
  4793. if (zcs->appliedParams.inBufferMode == ZSTD_bm_buffered) {
  4794. size_t const toLoad = zcs->inBuffTarget - zcs->inBuffPos;
  4795. size_t const loaded = ZSTD_limitCopy(
  4796. zcs->inBuff + zcs->inBuffPos, toLoad,
  4797. ip, iend-ip);
  4798. zcs->inBuffPos += loaded;
  4799. if (loaded != 0)
  4800. ip += loaded;
  4801. if ( (flushMode == ZSTD_e_continue)
  4802. && (zcs->inBuffPos < zcs->inBuffTarget) ) {
  4803. /* not enough input to fill full block : stop here */
  4804. someMoreWork = 0; break;
  4805. }
  4806. if ( (flushMode == ZSTD_e_flush)
  4807. && (zcs->inBuffPos == zcs->inToCompress) ) {
  4808. /* empty */
  4809. someMoreWork = 0; break;
  4810. }
  4811. }
  4812. /* compress current block (note : this stage cannot be stopped in the middle) */
  4813. DEBUGLOG(5, "stream compression stage (flushMode==%u)", flushMode);
  4814. { int const inputBuffered = (zcs->appliedParams.inBufferMode == ZSTD_bm_buffered);
  4815. void* cDst;
  4816. size_t cSize;
  4817. size_t oSize = oend-op;
  4818. size_t const iSize = inputBuffered
  4819. ? zcs->inBuffPos - zcs->inToCompress
  4820. : MIN((size_t)(iend - ip), zcs->blockSize);
  4821. if (oSize >= ZSTD_compressBound(iSize) || zcs->appliedParams.outBufferMode == ZSTD_bm_stable)
  4822. cDst = op; /* compress into output buffer, to skip flush stage */
  4823. else
  4824. cDst = zcs->outBuff, oSize = zcs->outBuffSize;
  4825. if (inputBuffered) {
  4826. unsigned const lastBlock = (flushMode == ZSTD_e_end) && (ip==iend);
  4827. cSize = lastBlock ?
  4828. ZSTD_compressEnd(zcs, cDst, oSize,
  4829. zcs->inBuff + zcs->inToCompress, iSize) :
  4830. ZSTD_compressContinue(zcs, cDst, oSize,
  4831. zcs->inBuff + zcs->inToCompress, iSize);
  4832. FORWARD_IF_ERROR(cSize, "%s", lastBlock ? "ZSTD_compressEnd failed" : "ZSTD_compressContinue failed");
  4833. zcs->frameEnded = lastBlock;
  4834. /* prepare next block */
  4835. zcs->inBuffTarget = zcs->inBuffPos + zcs->blockSize;
  4836. if (zcs->inBuffTarget > zcs->inBuffSize)
  4837. zcs->inBuffPos = 0, zcs->inBuffTarget = zcs->blockSize;
  4838. DEBUGLOG(5, "inBuffTarget:%u / inBuffSize:%u",
  4839. (unsigned)zcs->inBuffTarget, (unsigned)zcs->inBuffSize);
  4840. if (!lastBlock)
  4841. assert(zcs->inBuffTarget <= zcs->inBuffSize);
  4842. zcs->inToCompress = zcs->inBuffPos;
  4843. } else {
  4844. unsigned const lastBlock = (ip + iSize == iend);
  4845. assert(flushMode == ZSTD_e_end /* Already validated */);
  4846. cSize = lastBlock ?
  4847. ZSTD_compressEnd(zcs, cDst, oSize, ip, iSize) :
  4848. ZSTD_compressContinue(zcs, cDst, oSize, ip, iSize);
  4849. /* Consume the input prior to error checking to mirror buffered mode. */
  4850. if (iSize > 0)
  4851. ip += iSize;
  4852. FORWARD_IF_ERROR(cSize, "%s", lastBlock ? "ZSTD_compressEnd failed" : "ZSTD_compressContinue failed");
  4853. zcs->frameEnded = lastBlock;
  4854. if (lastBlock)
  4855. assert(ip == iend);
  4856. }
  4857. if (cDst == op) { /* no need to flush */
  4858. op += cSize;
  4859. if (zcs->frameEnded) {
  4860. DEBUGLOG(5, "Frame completed directly in outBuffer");
  4861. someMoreWork = 0;
  4862. ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only);
  4863. }
  4864. break;
  4865. }
  4866. zcs->outBuffContentSize = cSize;
  4867. zcs->outBuffFlushedSize = 0;
  4868. zcs->streamStage = zcss_flush; /* pass-through to flush stage */
  4869. }
  4870. /* fall-through */
  4871. case zcss_flush:
  4872. DEBUGLOG(5, "flush stage");
  4873. assert(zcs->appliedParams.outBufferMode == ZSTD_bm_buffered);
  4874. { size_t const toFlush = zcs->outBuffContentSize - zcs->outBuffFlushedSize;
  4875. size_t const flushed = ZSTD_limitCopy(op, (size_t)(oend-op),
  4876. zcs->outBuff + zcs->outBuffFlushedSize, toFlush);
  4877. DEBUGLOG(5, "toFlush: %u into %u ==> flushed: %u",
  4878. (unsigned)toFlush, (unsigned)(oend-op), (unsigned)flushed);
  4879. if (flushed)
  4880. op += flushed;
  4881. zcs->outBuffFlushedSize += flushed;
  4882. if (toFlush!=flushed) {
  4883. /* flush not fully completed, presumably because dst is too small */
  4884. assert(op==oend);
  4885. someMoreWork = 0;
  4886. break;
  4887. }
  4888. zcs->outBuffContentSize = zcs->outBuffFlushedSize = 0;
  4889. if (zcs->frameEnded) {
  4890. DEBUGLOG(5, "Frame completed on flush");
  4891. someMoreWork = 0;
  4892. ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only);
  4893. break;
  4894. }
  4895. zcs->streamStage = zcss_load;
  4896. break;
  4897. }
  4898. default: /* impossible */
  4899. assert(0);
  4900. }
  4901. }
  4902. input->pos = ip - istart;
  4903. output->pos = op - ostart;
  4904. if (zcs->frameEnded) return 0;
  4905. return ZSTD_nextInputSizeHint(zcs);
  4906. }
  4907. static size_t ZSTD_nextInputSizeHint_MTorST(const ZSTD_CCtx* cctx)
  4908. {
  4909. #ifdef ZSTD_MULTITHREAD
  4910. if (cctx->appliedParams.nbWorkers >= 1) {
  4911. assert(cctx->mtctx != NULL);
  4912. return ZSTDMT_nextInputSizeHint(cctx->mtctx);
  4913. }
  4914. #endif
  4915. return ZSTD_nextInputSizeHint(cctx);
  4916. }
  4917. size_t ZSTD_compressStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output, ZSTD_inBuffer* input)
  4918. {
  4919. FORWARD_IF_ERROR( ZSTD_compressStream2(zcs, output, input, ZSTD_e_continue) , "");
  4920. return ZSTD_nextInputSizeHint_MTorST(zcs);
  4921. }
  4922. /* After a compression call set the expected input/output buffer.
  4923. * This is validated at the start of the next compression call.
  4924. */
  4925. static void ZSTD_setBufferExpectations(ZSTD_CCtx* cctx, ZSTD_outBuffer const* output, ZSTD_inBuffer const* input)
  4926. {
  4927. if (cctx->appliedParams.inBufferMode == ZSTD_bm_stable) {
  4928. cctx->expectedInBuffer = *input;
  4929. }
  4930. if (cctx->appliedParams.outBufferMode == ZSTD_bm_stable) {
  4931. cctx->expectedOutBufferSize = output->size - output->pos;
  4932. }
  4933. }
  4934. /* Validate that the input/output buffers match the expectations set by
  4935. * ZSTD_setBufferExpectations.
  4936. */
  4937. static size_t ZSTD_checkBufferStability(ZSTD_CCtx const* cctx,
  4938. ZSTD_outBuffer const* output,
  4939. ZSTD_inBuffer const* input,
  4940. ZSTD_EndDirective endOp)
  4941. {
  4942. if (cctx->appliedParams.inBufferMode == ZSTD_bm_stable) {
  4943. ZSTD_inBuffer const expect = cctx->expectedInBuffer;
  4944. if (expect.src != input->src || expect.pos != input->pos || expect.size != input->size)
  4945. RETURN_ERROR(srcBuffer_wrong, "ZSTD_c_stableInBuffer enabled but input differs!");
  4946. if (endOp != ZSTD_e_end)
  4947. RETURN_ERROR(srcBuffer_wrong, "ZSTD_c_stableInBuffer can only be used with ZSTD_e_end!");
  4948. }
  4949. if (cctx->appliedParams.outBufferMode == ZSTD_bm_stable) {
  4950. size_t const outBufferSize = output->size - output->pos;
  4951. if (cctx->expectedOutBufferSize != outBufferSize)
  4952. RETURN_ERROR(dstBuffer_wrong, "ZSTD_c_stableOutBuffer enabled but output size differs!");
  4953. }
  4954. return 0;
  4955. }
  4956. static size_t ZSTD_CCtx_init_compressStream2(ZSTD_CCtx* cctx,
  4957. ZSTD_EndDirective endOp,
  4958. size_t inSize) {
  4959. ZSTD_CCtx_params params = cctx->requestedParams;
  4960. ZSTD_prefixDict const prefixDict = cctx->prefixDict;
  4961. FORWARD_IF_ERROR( ZSTD_initLocalDict(cctx) , ""); /* Init the local dict if present. */
  4962. ZSTD_memset(&cctx->prefixDict, 0, sizeof(cctx->prefixDict)); /* single usage */
  4963. assert(prefixDict.dict==NULL || cctx->cdict==NULL); /* only one can be set */
  4964. if (cctx->cdict && !cctx->localDict.cdict) {
  4965. /* Let the cdict's compression level take priority over the requested params.
  4966. * But do not take the cdict's compression level if the "cdict" is actually a localDict
  4967. * generated from ZSTD_initLocalDict().
  4968. */
  4969. params.compressionLevel = cctx->cdict->compressionLevel;
  4970. }
  4971. DEBUGLOG(4, "ZSTD_compressStream2 : transparent init stage");
  4972. if (endOp == ZSTD_e_end) cctx->pledgedSrcSizePlusOne = inSize + 1; /* auto-fix pledgedSrcSize */
  4973. {
  4974. size_t const dictSize = prefixDict.dict
  4975. ? prefixDict.dictSize
  4976. : (cctx->cdict ? cctx->cdict->dictContentSize : 0);
  4977. ZSTD_cParamMode_e const mode = ZSTD_getCParamMode(cctx->cdict, &params, cctx->pledgedSrcSizePlusOne - 1);
  4978. params.cParams = ZSTD_getCParamsFromCCtxParams(
  4979. &params, cctx->pledgedSrcSizePlusOne-1,
  4980. dictSize, mode);
  4981. }
  4982. if (ZSTD_CParams_shouldEnableLdm(&params.cParams)) {
  4983. /* Enable LDM by default for optimal parser and window size >= 128MB */
  4984. DEBUGLOG(4, "LDM enabled by default (window size >= 128MB, strategy >= btopt)");
  4985. params.ldmParams.enableLdm = 1;
  4986. }
  4987. if (ZSTD_CParams_useBlockSplitter(&params.cParams)) {
  4988. DEBUGLOG(4, "Block splitter enabled by default (window size >= 128K, strategy >= btopt)");
  4989. params.splitBlocks = 1;
  4990. }
  4991. params.useRowMatchFinder = ZSTD_resolveRowMatchFinderMode(params.useRowMatchFinder, &params.cParams);
  4992. #ifdef ZSTD_MULTITHREAD
  4993. if ((cctx->pledgedSrcSizePlusOne-1) <= ZSTDMT_JOBSIZE_MIN) {
  4994. params.nbWorkers = 0; /* do not invoke multi-threading when src size is too small */
  4995. }
  4996. if (params.nbWorkers > 0) {
  4997. #if ZSTD_TRACE
  4998. cctx->traceCtx = (ZSTD_trace_compress_begin != NULL) ? ZSTD_trace_compress_begin(cctx) : 0;
  4999. #endif
  5000. /* mt context creation */
  5001. if (cctx->mtctx == NULL) {
  5002. DEBUGLOG(4, "ZSTD_compressStream2: creating new mtctx for nbWorkers=%u",
  5003. params.nbWorkers);
  5004. cctx->mtctx = ZSTDMT_createCCtx_advanced((U32)params.nbWorkers, cctx->customMem, cctx->pool);
  5005. RETURN_ERROR_IF(cctx->mtctx == NULL, memory_allocation, "NULL pointer!");
  5006. }
  5007. /* mt compression */
  5008. DEBUGLOG(4, "call ZSTDMT_initCStream_internal as nbWorkers=%u", params.nbWorkers);
  5009. FORWARD_IF_ERROR( ZSTDMT_initCStream_internal(
  5010. cctx->mtctx,
  5011. prefixDict.dict, prefixDict.dictSize, prefixDict.dictContentType,
  5012. cctx->cdict, params, cctx->pledgedSrcSizePlusOne-1) , "");
  5013. cctx->dictID = cctx->cdict ? cctx->cdict->dictID : 0;
  5014. cctx->dictContentSize = cctx->cdict ? cctx->cdict->dictContentSize : prefixDict.dictSize;
  5015. cctx->consumedSrcSize = 0;
  5016. cctx->producedCSize = 0;
  5017. cctx->streamStage = zcss_load;
  5018. cctx->appliedParams = params;
  5019. } else
  5020. #endif
  5021. { U64 const pledgedSrcSize = cctx->pledgedSrcSizePlusOne - 1;
  5022. assert(!ZSTD_isError(ZSTD_checkCParams(params.cParams)));
  5023. FORWARD_IF_ERROR( ZSTD_compressBegin_internal(cctx,
  5024. prefixDict.dict, prefixDict.dictSize, prefixDict.dictContentType, ZSTD_dtlm_fast,
  5025. cctx->cdict,
  5026. &params, pledgedSrcSize,
  5027. ZSTDb_buffered) , "");
  5028. assert(cctx->appliedParams.nbWorkers == 0);
  5029. cctx->inToCompress = 0;
  5030. cctx->inBuffPos = 0;
  5031. if (cctx->appliedParams.inBufferMode == ZSTD_bm_buffered) {
  5032. /* for small input: avoid automatic flush on reaching end of block, since
  5033. * it would require to add a 3-bytes null block to end frame
  5034. */
  5035. cctx->inBuffTarget = cctx->blockSize + (cctx->blockSize == pledgedSrcSize);
  5036. } else {
  5037. cctx->inBuffTarget = 0;
  5038. }
  5039. cctx->outBuffContentSize = cctx->outBuffFlushedSize = 0;
  5040. cctx->streamStage = zcss_load;
  5041. cctx->frameEnded = 0;
  5042. }
  5043. return 0;
  5044. }
  5045. size_t ZSTD_compressStream2( ZSTD_CCtx* cctx,
  5046. ZSTD_outBuffer* output,
  5047. ZSTD_inBuffer* input,
  5048. ZSTD_EndDirective endOp)
  5049. {
  5050. DEBUGLOG(5, "ZSTD_compressStream2, endOp=%u ", (unsigned)endOp);
  5051. /* check conditions */
  5052. RETURN_ERROR_IF(output->pos > output->size, dstSize_tooSmall, "invalid output buffer");
  5053. RETURN_ERROR_IF(input->pos > input->size, srcSize_wrong, "invalid input buffer");
  5054. RETURN_ERROR_IF((U32)endOp > (U32)ZSTD_e_end, parameter_outOfBound, "invalid endDirective");
  5055. assert(cctx != NULL);
  5056. /* transparent initialization stage */
  5057. if (cctx->streamStage == zcss_init) {
  5058. FORWARD_IF_ERROR(ZSTD_CCtx_init_compressStream2(cctx, endOp, input->size), "CompressStream2 initialization failed");
  5059. ZSTD_setBufferExpectations(cctx, output, input); /* Set initial buffer expectations now that we've initialized */
  5060. }
  5061. /* end of transparent initialization stage */
  5062. FORWARD_IF_ERROR(ZSTD_checkBufferStability(cctx, output, input, endOp), "invalid buffers");
  5063. /* compression stage */
  5064. #ifdef ZSTD_MULTITHREAD
  5065. if (cctx->appliedParams.nbWorkers > 0) {
  5066. size_t flushMin;
  5067. if (cctx->cParamsChanged) {
  5068. ZSTDMT_updateCParams_whileCompressing(cctx->mtctx, &cctx->requestedParams);
  5069. cctx->cParamsChanged = 0;
  5070. }
  5071. for (;;) {
  5072. size_t const ipos = input->pos;
  5073. size_t const opos = output->pos;
  5074. flushMin = ZSTDMT_compressStream_generic(cctx->mtctx, output, input, endOp);
  5075. cctx->consumedSrcSize += (U64)(input->pos - ipos);
  5076. cctx->producedCSize += (U64)(output->pos - opos);
  5077. if ( ZSTD_isError(flushMin)
  5078. || (endOp == ZSTD_e_end && flushMin == 0) ) { /* compression completed */
  5079. if (flushMin == 0)
  5080. ZSTD_CCtx_trace(cctx, 0);
  5081. ZSTD_CCtx_reset(cctx, ZSTD_reset_session_only);
  5082. }
  5083. FORWARD_IF_ERROR(flushMin, "ZSTDMT_compressStream_generic failed");
  5084. if (endOp == ZSTD_e_continue) {
  5085. /* We only require some progress with ZSTD_e_continue, not maximal progress.
  5086. * We're done if we've consumed or produced any bytes, or either buffer is
  5087. * full.
  5088. */
  5089. if (input->pos != ipos || output->pos != opos || input->pos == input->size || output->pos == output->size)
  5090. break;
  5091. } else {
  5092. assert(endOp == ZSTD_e_flush || endOp == ZSTD_e_end);
  5093. /* We require maximal progress. We're done when the flush is complete or the
  5094. * output buffer is full.
  5095. */
  5096. if (flushMin == 0 || output->pos == output->size)
  5097. break;
  5098. }
  5099. }
  5100. DEBUGLOG(5, "completed ZSTD_compressStream2 delegating to ZSTDMT_compressStream_generic");
  5101. /* Either we don't require maximum forward progress, we've finished the
  5102. * flush, or we are out of output space.
  5103. */
  5104. assert(endOp == ZSTD_e_continue || flushMin == 0 || output->pos == output->size);
  5105. ZSTD_setBufferExpectations(cctx, output, input);
  5106. return flushMin;
  5107. }
  5108. #endif
  5109. FORWARD_IF_ERROR( ZSTD_compressStream_generic(cctx, output, input, endOp) , "");
  5110. DEBUGLOG(5, "completed ZSTD_compressStream2");
  5111. ZSTD_setBufferExpectations(cctx, output, input);
  5112. return cctx->outBuffContentSize - cctx->outBuffFlushedSize; /* remaining to flush */
  5113. }
  5114. size_t ZSTD_compressStream2_simpleArgs (
  5115. ZSTD_CCtx* cctx,
  5116. void* dst, size_t dstCapacity, size_t* dstPos,
  5117. const void* src, size_t srcSize, size_t* srcPos,
  5118. ZSTD_EndDirective endOp)
  5119. {
  5120. ZSTD_outBuffer output = { dst, dstCapacity, *dstPos };
  5121. ZSTD_inBuffer input = { src, srcSize, *srcPos };
  5122. /* ZSTD_compressStream2() will check validity of dstPos and srcPos */
  5123. size_t const cErr = ZSTD_compressStream2(cctx, &output, &input, endOp);
  5124. *dstPos = output.pos;
  5125. *srcPos = input.pos;
  5126. return cErr;
  5127. }
  5128. size_t ZSTD_compress2(ZSTD_CCtx* cctx,
  5129. void* dst, size_t dstCapacity,
  5130. const void* src, size_t srcSize)
  5131. {
  5132. ZSTD_bufferMode_e const originalInBufferMode = cctx->requestedParams.inBufferMode;
  5133. ZSTD_bufferMode_e const originalOutBufferMode = cctx->requestedParams.outBufferMode;
  5134. DEBUGLOG(4, "ZSTD_compress2 (srcSize=%u)", (unsigned)srcSize);
  5135. ZSTD_CCtx_reset(cctx, ZSTD_reset_session_only);
  5136. /* Enable stable input/output buffers. */
  5137. cctx->requestedParams.inBufferMode = ZSTD_bm_stable;
  5138. cctx->requestedParams.outBufferMode = ZSTD_bm_stable;
  5139. { size_t oPos = 0;
  5140. size_t iPos = 0;
  5141. size_t const result = ZSTD_compressStream2_simpleArgs(cctx,
  5142. dst, dstCapacity, &oPos,
  5143. src, srcSize, &iPos,
  5144. ZSTD_e_end);
  5145. /* Reset to the original values. */
  5146. cctx->requestedParams.inBufferMode = originalInBufferMode;
  5147. cctx->requestedParams.outBufferMode = originalOutBufferMode;
  5148. FORWARD_IF_ERROR(result, "ZSTD_compressStream2_simpleArgs failed");
  5149. if (result != 0) { /* compression not completed, due to lack of output space */
  5150. assert(oPos == dstCapacity);
  5151. RETURN_ERROR(dstSize_tooSmall, "");
  5152. }
  5153. assert(iPos == srcSize); /* all input is expected consumed */
  5154. return oPos;
  5155. }
  5156. }
  5157. typedef struct {
  5158. U32 idx; /* Index in array of ZSTD_Sequence */
  5159. U32 posInSequence; /* Position within sequence at idx */
  5160. size_t posInSrc; /* Number of bytes given by sequences provided so far */
  5161. } ZSTD_sequencePosition;
  5162. /* Returns a ZSTD error code if sequence is not valid */
  5163. static size_t ZSTD_validateSequence(U32 offCode, U32 matchLength,
  5164. size_t posInSrc, U32 windowLog, size_t dictSize, U32 minMatch) {
  5165. size_t offsetBound;
  5166. U32 windowSize = 1 << windowLog;
  5167. /* posInSrc represents the amount of data the the decoder would decode up to this point.
  5168. * As long as the amount of data decoded is less than or equal to window size, offsets may be
  5169. * larger than the total length of output decoded in order to reference the dict, even larger than
  5170. * window size. After output surpasses windowSize, we're limited to windowSize offsets again.
  5171. */
  5172. offsetBound = posInSrc > windowSize ? (size_t)windowSize : posInSrc + (size_t)dictSize;
  5173. RETURN_ERROR_IF(offCode > offsetBound + ZSTD_REP_MOVE, corruption_detected, "Offset too large!");
  5174. RETURN_ERROR_IF(matchLength < minMatch, corruption_detected, "Matchlength too small");
  5175. return 0;
  5176. }
  5177. /* Returns an offset code, given a sequence's raw offset, the ongoing repcode array, and whether litLength == 0 */
  5178. static U32 ZSTD_finalizeOffCode(U32 rawOffset, const U32 rep[ZSTD_REP_NUM], U32 ll0) {
  5179. U32 offCode = rawOffset + ZSTD_REP_MOVE;
  5180. U32 repCode = 0;
  5181. if (!ll0 && rawOffset == rep[0]) {
  5182. repCode = 1;
  5183. } else if (rawOffset == rep[1]) {
  5184. repCode = 2 - ll0;
  5185. } else if (rawOffset == rep[2]) {
  5186. repCode = 3 - ll0;
  5187. } else if (ll0 && rawOffset == rep[0] - 1) {
  5188. repCode = 3;
  5189. }
  5190. if (repCode) {
  5191. /* ZSTD_storeSeq expects a number in the range [0, 2] to represent a repcode */
  5192. offCode = repCode - 1;
  5193. }
  5194. return offCode;
  5195. }
  5196. /* Returns 0 on success, and a ZSTD_error otherwise. This function scans through an array of
  5197. * ZSTD_Sequence, storing the sequences it finds, until it reaches a block delimiter.
  5198. */
  5199. static size_t ZSTD_copySequencesToSeqStoreExplicitBlockDelim(ZSTD_CCtx* cctx, ZSTD_sequencePosition* seqPos,
  5200. const ZSTD_Sequence* const inSeqs, size_t inSeqsSize,
  5201. const void* src, size_t blockSize) {
  5202. U32 idx = seqPos->idx;
  5203. BYTE const* ip = (BYTE const*)(src);
  5204. const BYTE* const iend = ip + blockSize;
  5205. repcodes_t updatedRepcodes;
  5206. U32 dictSize;
  5207. U32 litLength;
  5208. U32 matchLength;
  5209. U32 ll0;
  5210. U32 offCode;
  5211. if (cctx->cdict) {
  5212. dictSize = (U32)cctx->cdict->dictContentSize;
  5213. } else if (cctx->prefixDict.dict) {
  5214. dictSize = (U32)cctx->prefixDict.dictSize;
  5215. } else {
  5216. dictSize = 0;
  5217. }
  5218. ZSTD_memcpy(updatedRepcodes.rep, cctx->blockState.prevCBlock->rep, sizeof(repcodes_t));
  5219. for (; (inSeqs[idx].matchLength != 0 || inSeqs[idx].offset != 0) && idx < inSeqsSize; ++idx) {
  5220. litLength = inSeqs[idx].litLength;
  5221. matchLength = inSeqs[idx].matchLength;
  5222. ll0 = litLength == 0;
  5223. offCode = ZSTD_finalizeOffCode(inSeqs[idx].offset, updatedRepcodes.rep, ll0);
  5224. updatedRepcodes = ZSTD_updateRep(updatedRepcodes.rep, offCode, ll0);
  5225. DEBUGLOG(6, "Storing sequence: (of: %u, ml: %u, ll: %u)", offCode, matchLength, litLength);
  5226. if (cctx->appliedParams.validateSequences) {
  5227. seqPos->posInSrc += litLength + matchLength;
  5228. FORWARD_IF_ERROR(ZSTD_validateSequence(offCode, matchLength, seqPos->posInSrc,
  5229. cctx->appliedParams.cParams.windowLog, dictSize,
  5230. cctx->appliedParams.cParams.minMatch),
  5231. "Sequence validation failed");
  5232. }
  5233. RETURN_ERROR_IF(idx - seqPos->idx > cctx->seqStore.maxNbSeq, memory_allocation,
  5234. "Not enough memory allocated. Try adjusting ZSTD_c_minMatch.");
  5235. ZSTD_storeSeq(&cctx->seqStore, litLength, ip, iend, offCode, matchLength - MINMATCH);
  5236. ip += matchLength + litLength;
  5237. }
  5238. ZSTD_memcpy(cctx->blockState.nextCBlock->rep, updatedRepcodes.rep, sizeof(repcodes_t));
  5239. if (inSeqs[idx].litLength) {
  5240. DEBUGLOG(6, "Storing last literals of size: %u", inSeqs[idx].litLength);
  5241. ZSTD_storeLastLiterals(&cctx->seqStore, ip, inSeqs[idx].litLength);
  5242. ip += inSeqs[idx].litLength;
  5243. seqPos->posInSrc += inSeqs[idx].litLength;
  5244. }
  5245. RETURN_ERROR_IF(ip != iend, corruption_detected, "Blocksize doesn't agree with block delimiter!");
  5246. seqPos->idx = idx+1;
  5247. return 0;
  5248. }
  5249. /* Returns the number of bytes to move the current read position back by. Only non-zero
  5250. * if we ended up splitting a sequence. Otherwise, it may return a ZSTD error if something
  5251. * went wrong.
  5252. *
  5253. * This function will attempt to scan through blockSize bytes represented by the sequences
  5254. * in inSeqs, storing any (partial) sequences.
  5255. *
  5256. * Occasionally, we may want to change the actual number of bytes we consumed from inSeqs to
  5257. * avoid splitting a match, or to avoid splitting a match such that it would produce a match
  5258. * smaller than MINMATCH. In this case, we return the number of bytes that we didn't read from this block.
  5259. */
  5260. static size_t ZSTD_copySequencesToSeqStoreNoBlockDelim(ZSTD_CCtx* cctx, ZSTD_sequencePosition* seqPos,
  5261. const ZSTD_Sequence* const inSeqs, size_t inSeqsSize,
  5262. const void* src, size_t blockSize) {
  5263. U32 idx = seqPos->idx;
  5264. U32 startPosInSequence = seqPos->posInSequence;
  5265. U32 endPosInSequence = seqPos->posInSequence + (U32)blockSize;
  5266. size_t dictSize;
  5267. BYTE const* ip = (BYTE const*)(src);
  5268. BYTE const* iend = ip + blockSize; /* May be adjusted if we decide to process fewer than blockSize bytes */
  5269. repcodes_t updatedRepcodes;
  5270. U32 bytesAdjustment = 0;
  5271. U32 finalMatchSplit = 0;
  5272. U32 litLength;
  5273. U32 matchLength;
  5274. U32 rawOffset;
  5275. U32 offCode;
  5276. if (cctx->cdict) {
  5277. dictSize = cctx->cdict->dictContentSize;
  5278. } else if (cctx->prefixDict.dict) {
  5279. dictSize = cctx->prefixDict.dictSize;
  5280. } else {
  5281. dictSize = 0;
  5282. }
  5283. DEBUGLOG(5, "ZSTD_copySequencesToSeqStore: idx: %u PIS: %u blockSize: %zu", idx, startPosInSequence, blockSize);
  5284. DEBUGLOG(5, "Start seq: idx: %u (of: %u ml: %u ll: %u)", idx, inSeqs[idx].offset, inSeqs[idx].matchLength, inSeqs[idx].litLength);
  5285. ZSTD_memcpy(updatedRepcodes.rep, cctx->blockState.prevCBlock->rep, sizeof(repcodes_t));
  5286. while (endPosInSequence && idx < inSeqsSize && !finalMatchSplit) {
  5287. const ZSTD_Sequence currSeq = inSeqs[idx];
  5288. litLength = currSeq.litLength;
  5289. matchLength = currSeq.matchLength;
  5290. rawOffset = currSeq.offset;
  5291. /* Modify the sequence depending on where endPosInSequence lies */
  5292. if (endPosInSequence >= currSeq.litLength + currSeq.matchLength) {
  5293. if (startPosInSequence >= litLength) {
  5294. startPosInSequence -= litLength;
  5295. litLength = 0;
  5296. matchLength -= startPosInSequence;
  5297. } else {
  5298. litLength -= startPosInSequence;
  5299. }
  5300. /* Move to the next sequence */
  5301. endPosInSequence -= currSeq.litLength + currSeq.matchLength;
  5302. startPosInSequence = 0;
  5303. idx++;
  5304. } else {
  5305. /* This is the final (partial) sequence we're adding from inSeqs, and endPosInSequence
  5306. does not reach the end of the match. So, we have to split the sequence */
  5307. DEBUGLOG(6, "Require a split: diff: %u, idx: %u PIS: %u",
  5308. currSeq.litLength + currSeq.matchLength - endPosInSequence, idx, endPosInSequence);
  5309. if (endPosInSequence > litLength) {
  5310. U32 firstHalfMatchLength;
  5311. litLength = startPosInSequence >= litLength ? 0 : litLength - startPosInSequence;
  5312. firstHalfMatchLength = endPosInSequence - startPosInSequence - litLength;
  5313. if (matchLength > blockSize && firstHalfMatchLength >= cctx->appliedParams.cParams.minMatch) {
  5314. /* Only ever split the match if it is larger than the block size */
  5315. U32 secondHalfMatchLength = currSeq.matchLength + currSeq.litLength - endPosInSequence;
  5316. if (secondHalfMatchLength < cctx->appliedParams.cParams.minMatch) {
  5317. /* Move the endPosInSequence backward so that it creates match of minMatch length */
  5318. endPosInSequence -= cctx->appliedParams.cParams.minMatch - secondHalfMatchLength;
  5319. bytesAdjustment = cctx->appliedParams.cParams.minMatch - secondHalfMatchLength;
  5320. firstHalfMatchLength -= bytesAdjustment;
  5321. }
  5322. matchLength = firstHalfMatchLength;
  5323. /* Flag that we split the last match - after storing the sequence, exit the loop,
  5324. but keep the value of endPosInSequence */
  5325. finalMatchSplit = 1;
  5326. } else {
  5327. /* Move the position in sequence backwards so that we don't split match, and break to store
  5328. * the last literals. We use the original currSeq.litLength as a marker for where endPosInSequence
  5329. * should go. We prefer to do this whenever it is not necessary to split the match, or if doing so
  5330. * would cause the first half of the match to be too small
  5331. */
  5332. bytesAdjustment = endPosInSequence - currSeq.litLength;
  5333. endPosInSequence = currSeq.litLength;
  5334. break;
  5335. }
  5336. } else {
  5337. /* This sequence ends inside the literals, break to store the last literals */
  5338. break;
  5339. }
  5340. }
  5341. /* Check if this offset can be represented with a repcode */
  5342. { U32 ll0 = (litLength == 0);
  5343. offCode = ZSTD_finalizeOffCode(rawOffset, updatedRepcodes.rep, ll0);
  5344. updatedRepcodes = ZSTD_updateRep(updatedRepcodes.rep, offCode, ll0);
  5345. }
  5346. if (cctx->appliedParams.validateSequences) {
  5347. seqPos->posInSrc += litLength + matchLength;
  5348. FORWARD_IF_ERROR(ZSTD_validateSequence(offCode, matchLength, seqPos->posInSrc,
  5349. cctx->appliedParams.cParams.windowLog, dictSize,
  5350. cctx->appliedParams.cParams.minMatch),
  5351. "Sequence validation failed");
  5352. }
  5353. DEBUGLOG(6, "Storing sequence: (of: %u, ml: %u, ll: %u)", offCode, matchLength, litLength);
  5354. RETURN_ERROR_IF(idx - seqPos->idx > cctx->seqStore.maxNbSeq, memory_allocation,
  5355. "Not enough memory allocated. Try adjusting ZSTD_c_minMatch.");
  5356. ZSTD_storeSeq(&cctx->seqStore, litLength, ip, iend, offCode, matchLength - MINMATCH);
  5357. ip += matchLength + litLength;
  5358. }
  5359. DEBUGLOG(5, "Ending seq: idx: %u (of: %u ml: %u ll: %u)", idx, inSeqs[idx].offset, inSeqs[idx].matchLength, inSeqs[idx].litLength);
  5360. assert(idx == inSeqsSize || endPosInSequence <= inSeqs[idx].litLength + inSeqs[idx].matchLength);
  5361. seqPos->idx = idx;
  5362. seqPos->posInSequence = endPosInSequence;
  5363. ZSTD_memcpy(cctx->blockState.nextCBlock->rep, updatedRepcodes.rep, sizeof(repcodes_t));
  5364. iend -= bytesAdjustment;
  5365. if (ip != iend) {
  5366. /* Store any last literals */
  5367. U32 lastLLSize = (U32)(iend - ip);
  5368. assert(ip <= iend);
  5369. DEBUGLOG(6, "Storing last literals of size: %u", lastLLSize);
  5370. ZSTD_storeLastLiterals(&cctx->seqStore, ip, lastLLSize);
  5371. seqPos->posInSrc += lastLLSize;
  5372. }
  5373. return bytesAdjustment;
  5374. }
  5375. typedef size_t (*ZSTD_sequenceCopier) (ZSTD_CCtx* cctx, ZSTD_sequencePosition* seqPos,
  5376. const ZSTD_Sequence* const inSeqs, size_t inSeqsSize,
  5377. const void* src, size_t blockSize);
  5378. static ZSTD_sequenceCopier ZSTD_selectSequenceCopier(ZSTD_sequenceFormat_e mode) {
  5379. ZSTD_sequenceCopier sequenceCopier = NULL;
  5380. assert(ZSTD_cParam_withinBounds(ZSTD_c_blockDelimiters, mode));
  5381. if (mode == ZSTD_sf_explicitBlockDelimiters) {
  5382. return ZSTD_copySequencesToSeqStoreExplicitBlockDelim;
  5383. } else if (mode == ZSTD_sf_noBlockDelimiters) {
  5384. return ZSTD_copySequencesToSeqStoreNoBlockDelim;
  5385. }
  5386. assert(sequenceCopier != NULL);
  5387. return sequenceCopier;
  5388. }
  5389. /* Compress, block-by-block, all of the sequences given.
  5390. *
  5391. * Returns the cumulative size of all compressed blocks (including their headers), otherwise a ZSTD error.
  5392. */
  5393. static size_t ZSTD_compressSequences_internal(ZSTD_CCtx* cctx,
  5394. void* dst, size_t dstCapacity,
  5395. const ZSTD_Sequence* inSeqs, size_t inSeqsSize,
  5396. const void* src, size_t srcSize) {
  5397. size_t cSize = 0;
  5398. U32 lastBlock;
  5399. size_t blockSize;
  5400. size_t compressedSeqsSize;
  5401. size_t remaining = srcSize;
  5402. ZSTD_sequencePosition seqPos = {0, 0, 0};
  5403. BYTE const* ip = (BYTE const*)src;
  5404. BYTE* op = (BYTE*)dst;
  5405. ZSTD_sequenceCopier sequenceCopier = ZSTD_selectSequenceCopier(cctx->appliedParams.blockDelimiters);
  5406. DEBUGLOG(4, "ZSTD_compressSequences_internal srcSize: %zu, inSeqsSize: %zu", srcSize, inSeqsSize);
  5407. /* Special case: empty frame */
  5408. if (remaining == 0) {
  5409. U32 const cBlockHeader24 = 1 /* last block */ + (((U32)bt_raw)<<1);
  5410. RETURN_ERROR_IF(dstCapacity<4, dstSize_tooSmall, "No room for empty frame block header");
  5411. MEM_writeLE32(op, cBlockHeader24);
  5412. op += ZSTD_blockHeaderSize;
  5413. dstCapacity -= ZSTD_blockHeaderSize;
  5414. cSize += ZSTD_blockHeaderSize;
  5415. }
  5416. while (remaining) {
  5417. size_t cBlockSize;
  5418. size_t additionalByteAdjustment;
  5419. lastBlock = remaining <= cctx->blockSize;
  5420. blockSize = lastBlock ? (U32)remaining : (U32)cctx->blockSize;
  5421. ZSTD_resetSeqStore(&cctx->seqStore);
  5422. DEBUGLOG(4, "Working on new block. Blocksize: %zu", blockSize);
  5423. additionalByteAdjustment = sequenceCopier(cctx, &seqPos, inSeqs, inSeqsSize, ip, blockSize);
  5424. FORWARD_IF_ERROR(additionalByteAdjustment, "Bad sequence copy");
  5425. blockSize -= additionalByteAdjustment;
  5426. /* If blocks are too small, emit as a nocompress block */
  5427. if (blockSize < MIN_CBLOCK_SIZE+ZSTD_blockHeaderSize+1) {
  5428. cBlockSize = ZSTD_noCompressBlock(op, dstCapacity, ip, blockSize, lastBlock);
  5429. FORWARD_IF_ERROR(cBlockSize, "Nocompress block failed");
  5430. DEBUGLOG(4, "Block too small, writing out nocompress block: cSize: %zu", cBlockSize);
  5431. cSize += cBlockSize;
  5432. ip += blockSize;
  5433. op += cBlockSize;
  5434. remaining -= blockSize;
  5435. dstCapacity -= cBlockSize;
  5436. continue;
  5437. }
  5438. compressedSeqsSize = ZSTD_entropyCompressSeqStore(&cctx->seqStore,
  5439. &cctx->blockState.prevCBlock->entropy, &cctx->blockState.nextCBlock->entropy,
  5440. &cctx->appliedParams,
  5441. op + ZSTD_blockHeaderSize /* Leave space for block header */, dstCapacity - ZSTD_blockHeaderSize,
  5442. blockSize,
  5443. cctx->entropyWorkspace, ENTROPY_WORKSPACE_SIZE /* statically allocated in resetCCtx */,
  5444. cctx->bmi2);
  5445. FORWARD_IF_ERROR(compressedSeqsSize, "Compressing sequences of block failed");
  5446. DEBUGLOG(4, "Compressed sequences size: %zu", compressedSeqsSize);
  5447. if (!cctx->isFirstBlock &&
  5448. ZSTD_maybeRLE(&cctx->seqStore) &&
  5449. ZSTD_isRLE((BYTE const*)src, srcSize)) {
  5450. /* We don't want to emit our first block as a RLE even if it qualifies because
  5451. * doing so will cause the decoder (cli only) to throw a "should consume all input error."
  5452. * This is only an issue for zstd <= v1.4.3
  5453. */
  5454. compressedSeqsSize = 1;
  5455. }
  5456. if (compressedSeqsSize == 0) {
  5457. /* ZSTD_noCompressBlock writes the block header as well */
  5458. cBlockSize = ZSTD_noCompressBlock(op, dstCapacity, ip, blockSize, lastBlock);
  5459. FORWARD_IF_ERROR(cBlockSize, "Nocompress block failed");
  5460. DEBUGLOG(4, "Writing out nocompress block, size: %zu", cBlockSize);
  5461. } else if (compressedSeqsSize == 1) {
  5462. cBlockSize = ZSTD_rleCompressBlock(op, dstCapacity, *ip, blockSize, lastBlock);
  5463. FORWARD_IF_ERROR(cBlockSize, "RLE compress block failed");
  5464. DEBUGLOG(4, "Writing out RLE block, size: %zu", cBlockSize);
  5465. } else {
  5466. U32 cBlockHeader;
  5467. /* Error checking and repcodes update */
  5468. ZSTD_blockState_confirmRepcodesAndEntropyTables(&cctx->blockState);
  5469. if (cctx->blockState.prevCBlock->entropy.fse.offcode_repeatMode == FSE_repeat_valid)
  5470. cctx->blockState.prevCBlock->entropy.fse.offcode_repeatMode = FSE_repeat_check;
  5471. /* Write block header into beginning of block*/
  5472. cBlockHeader = lastBlock + (((U32)bt_compressed)<<1) + (U32)(compressedSeqsSize << 3);
  5473. MEM_writeLE24(op, cBlockHeader);
  5474. cBlockSize = ZSTD_blockHeaderSize + compressedSeqsSize;
  5475. DEBUGLOG(4, "Writing out compressed block, size: %zu", cBlockSize);
  5476. }
  5477. cSize += cBlockSize;
  5478. DEBUGLOG(4, "cSize running total: %zu", cSize);
  5479. if (lastBlock) {
  5480. break;
  5481. } else {
  5482. ip += blockSize;
  5483. op += cBlockSize;
  5484. remaining -= blockSize;
  5485. dstCapacity -= cBlockSize;
  5486. cctx->isFirstBlock = 0;
  5487. }
  5488. }
  5489. return cSize;
  5490. }
  5491. size_t ZSTD_compressSequences(ZSTD_CCtx* const cctx, void* dst, size_t dstCapacity,
  5492. const ZSTD_Sequence* inSeqs, size_t inSeqsSize,
  5493. const void* src, size_t srcSize) {
  5494. BYTE* op = (BYTE*)dst;
  5495. size_t cSize = 0;
  5496. size_t compressedBlocksSize = 0;
  5497. size_t frameHeaderSize = 0;
  5498. /* Transparent initialization stage, same as compressStream2() */
  5499. DEBUGLOG(3, "ZSTD_compressSequences()");
  5500. assert(cctx != NULL);
  5501. FORWARD_IF_ERROR(ZSTD_CCtx_init_compressStream2(cctx, ZSTD_e_end, srcSize), "CCtx initialization failed");
  5502. /* Begin writing output, starting with frame header */
  5503. frameHeaderSize = ZSTD_writeFrameHeader(op, dstCapacity, &cctx->appliedParams, srcSize, cctx->dictID);
  5504. op += frameHeaderSize;
  5505. dstCapacity -= frameHeaderSize;
  5506. cSize += frameHeaderSize;
  5507. if (cctx->appliedParams.fParams.checksumFlag && srcSize) {
  5508. XXH64_update(&cctx->xxhState, src, srcSize);
  5509. }
  5510. /* cSize includes block header size and compressed sequences size */
  5511. compressedBlocksSize = ZSTD_compressSequences_internal(cctx,
  5512. op, dstCapacity,
  5513. inSeqs, inSeqsSize,
  5514. src, srcSize);
  5515. FORWARD_IF_ERROR(compressedBlocksSize, "Compressing blocks failed!");
  5516. cSize += compressedBlocksSize;
  5517. dstCapacity -= compressedBlocksSize;
  5518. if (cctx->appliedParams.fParams.checksumFlag) {
  5519. U32 const checksum = (U32) XXH64_digest(&cctx->xxhState);
  5520. RETURN_ERROR_IF(dstCapacity<4, dstSize_tooSmall, "no room for checksum");
  5521. DEBUGLOG(4, "Write checksum : %08X", (unsigned)checksum);
  5522. MEM_writeLE32((char*)dst + cSize, checksum);
  5523. cSize += 4;
  5524. }
  5525. DEBUGLOG(3, "Final compressed size: %zu", cSize);
  5526. return cSize;
  5527. }
  5528. /*====== Finalize ======*/
  5529. /*! ZSTD_flushStream() :
  5530. * @return : amount of data remaining to flush */
  5531. size_t ZSTD_flushStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output)
  5532. {
  5533. ZSTD_inBuffer input = { NULL, 0, 0 };
  5534. return ZSTD_compressStream2(zcs, output, &input, ZSTD_e_flush);
  5535. }
  5536. size_t ZSTD_endStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output)
  5537. {
  5538. ZSTD_inBuffer input = { NULL, 0, 0 };
  5539. size_t const remainingToFlush = ZSTD_compressStream2(zcs, output, &input, ZSTD_e_end);
  5540. FORWARD_IF_ERROR( remainingToFlush , "ZSTD_compressStream2 failed");
  5541. if (zcs->appliedParams.nbWorkers > 0) return remainingToFlush; /* minimal estimation */
  5542. /* single thread mode : attempt to calculate remaining to flush more precisely */
  5543. { size_t const lastBlockSize = zcs->frameEnded ? 0 : ZSTD_BLOCKHEADERSIZE;
  5544. size_t const checksumSize = (size_t)(zcs->frameEnded ? 0 : zcs->appliedParams.fParams.checksumFlag * 4);
  5545. size_t const toFlush = remainingToFlush + lastBlockSize + checksumSize;
  5546. DEBUGLOG(4, "ZSTD_endStream : remaining to flush : %u", (unsigned)toFlush);
  5547. return toFlush;
  5548. }
  5549. }
  5550. /*-===== Pre-defined compression levels =====-*/
  5551. #define ZSTD_MAX_CLEVEL 22
  5552. int ZSTD_maxCLevel(void) { return ZSTD_MAX_CLEVEL; }
  5553. int ZSTD_minCLevel(void) { return (int)-ZSTD_TARGETLENGTH_MAX; }
  5554. int ZSTD_defaultCLevel(void) { return ZSTD_CLEVEL_DEFAULT; }
  5555. static const ZSTD_compressionParameters ZSTD_defaultCParameters[4][ZSTD_MAX_CLEVEL+1] = {
  5556. { /* "default" - for any srcSize > 256 KB */
  5557. /* W, C, H, S, L, TL, strat */
  5558. { 19, 12, 13, 1, 6, 1, ZSTD_fast }, /* base for negative levels */
  5559. { 19, 13, 14, 1, 7, 0, ZSTD_fast }, /* level 1 */
  5560. { 20, 15, 16, 1, 6, 0, ZSTD_fast }, /* level 2 */
  5561. { 21, 16, 17, 1, 5, 0, ZSTD_dfast }, /* level 3 */
  5562. { 21, 18, 18, 1, 5, 0, ZSTD_dfast }, /* level 4 */
  5563. { 21, 18, 19, 2, 5, 2, ZSTD_greedy }, /* level 5 */
  5564. { 21, 19, 19, 3, 5, 4, ZSTD_greedy }, /* level 6 */
  5565. { 21, 19, 19, 3, 5, 8, ZSTD_lazy }, /* level 7 */
  5566. { 21, 19, 19, 3, 5, 16, ZSTD_lazy2 }, /* level 8 */
  5567. { 21, 19, 20, 4, 5, 16, ZSTD_lazy2 }, /* level 9 */
  5568. { 22, 20, 21, 4, 5, 16, ZSTD_lazy2 }, /* level 10 */
  5569. { 22, 21, 22, 4, 5, 16, ZSTD_lazy2 }, /* level 11 */
  5570. { 22, 21, 22, 5, 5, 16, ZSTD_lazy2 }, /* level 12 */
  5571. { 22, 21, 22, 5, 5, 32, ZSTD_btlazy2 }, /* level 13 */
  5572. { 22, 22, 23, 5, 5, 32, ZSTD_btlazy2 }, /* level 14 */
  5573. { 22, 23, 23, 6, 5, 32, ZSTD_btlazy2 }, /* level 15 */
  5574. { 22, 22, 22, 5, 5, 48, ZSTD_btopt }, /* level 16 */
  5575. { 23, 23, 22, 5, 4, 64, ZSTD_btopt }, /* level 17 */
  5576. { 23, 23, 22, 6, 3, 64, ZSTD_btultra }, /* level 18 */
  5577. { 23, 24, 22, 7, 3,256, ZSTD_btultra2}, /* level 19 */
  5578. { 25, 25, 23, 7, 3,256, ZSTD_btultra2}, /* level 20 */
  5579. { 26, 26, 24, 7, 3,512, ZSTD_btultra2}, /* level 21 */
  5580. { 27, 27, 25, 9, 3,999, ZSTD_btultra2}, /* level 22 */
  5581. },
  5582. { /* for srcSize <= 256 KB */
  5583. /* W, C, H, S, L, T, strat */
  5584. { 18, 12, 13, 1, 5, 1, ZSTD_fast }, /* base for negative levels */
  5585. { 18, 13, 14, 1, 6, 0, ZSTD_fast }, /* level 1 */
  5586. { 18, 14, 14, 1, 5, 0, ZSTD_dfast }, /* level 2 */
  5587. { 18, 16, 16, 1, 4, 0, ZSTD_dfast }, /* level 3 */
  5588. { 18, 16, 17, 2, 5, 2, ZSTD_greedy }, /* level 4.*/
  5589. { 18, 18, 18, 3, 5, 2, ZSTD_greedy }, /* level 5.*/
  5590. { 18, 18, 19, 3, 5, 4, ZSTD_lazy }, /* level 6.*/
  5591. { 18, 18, 19, 4, 4, 4, ZSTD_lazy }, /* level 7 */
  5592. { 18, 18, 19, 4, 4, 8, ZSTD_lazy2 }, /* level 8 */
  5593. { 18, 18, 19, 5, 4, 8, ZSTD_lazy2 }, /* level 9 */
  5594. { 18, 18, 19, 6, 4, 8, ZSTD_lazy2 }, /* level 10 */
  5595. { 18, 18, 19, 5, 4, 12, ZSTD_btlazy2 }, /* level 11.*/
  5596. { 18, 19, 19, 7, 4, 12, ZSTD_btlazy2 }, /* level 12.*/
  5597. { 18, 18, 19, 4, 4, 16, ZSTD_btopt }, /* level 13 */
  5598. { 18, 18, 19, 4, 3, 32, ZSTD_btopt }, /* level 14.*/
  5599. { 18, 18, 19, 6, 3,128, ZSTD_btopt }, /* level 15.*/
  5600. { 18, 19, 19, 6, 3,128, ZSTD_btultra }, /* level 16.*/
  5601. { 18, 19, 19, 8, 3,256, ZSTD_btultra }, /* level 17.*/
  5602. { 18, 19, 19, 6, 3,128, ZSTD_btultra2}, /* level 18.*/
  5603. { 18, 19, 19, 8, 3,256, ZSTD_btultra2}, /* level 19.*/
  5604. { 18, 19, 19, 10, 3,512, ZSTD_btultra2}, /* level 20.*/
  5605. { 18, 19, 19, 12, 3,512, ZSTD_btultra2}, /* level 21.*/
  5606. { 18, 19, 19, 13, 3,999, ZSTD_btultra2}, /* level 22.*/
  5607. },
  5608. { /* for srcSize <= 128 KB */
  5609. /* W, C, H, S, L, T, strat */
  5610. { 17, 12, 12, 1, 5, 1, ZSTD_fast }, /* base for negative levels */
  5611. { 17, 12, 13, 1, 6, 0, ZSTD_fast }, /* level 1 */
  5612. { 17, 13, 15, 1, 5, 0, ZSTD_fast }, /* level 2 */
  5613. { 17, 15, 16, 2, 5, 0, ZSTD_dfast }, /* level 3 */
  5614. { 17, 17, 17, 2, 4, 0, ZSTD_dfast }, /* level 4 */
  5615. { 17, 16, 17, 3, 4, 2, ZSTD_greedy }, /* level 5 */
  5616. { 17, 17, 17, 3, 4, 4, ZSTD_lazy }, /* level 6 */
  5617. { 17, 17, 17, 3, 4, 8, ZSTD_lazy2 }, /* level 7 */
  5618. { 17, 17, 17, 4, 4, 8, ZSTD_lazy2 }, /* level 8 */
  5619. { 17, 17, 17, 5, 4, 8, ZSTD_lazy2 }, /* level 9 */
  5620. { 17, 17, 17, 6, 4, 8, ZSTD_lazy2 }, /* level 10 */
  5621. { 17, 17, 17, 5, 4, 8, ZSTD_btlazy2 }, /* level 11 */
  5622. { 17, 18, 17, 7, 4, 12, ZSTD_btlazy2 }, /* level 12 */
  5623. { 17, 18, 17, 3, 4, 12, ZSTD_btopt }, /* level 13.*/
  5624. { 17, 18, 17, 4, 3, 32, ZSTD_btopt }, /* level 14.*/
  5625. { 17, 18, 17, 6, 3,256, ZSTD_btopt }, /* level 15.*/
  5626. { 17, 18, 17, 6, 3,128, ZSTD_btultra }, /* level 16.*/
  5627. { 17, 18, 17, 8, 3,256, ZSTD_btultra }, /* level 17.*/
  5628. { 17, 18, 17, 10, 3,512, ZSTD_btultra }, /* level 18.*/
  5629. { 17, 18, 17, 5, 3,256, ZSTD_btultra2}, /* level 19.*/
  5630. { 17, 18, 17, 7, 3,512, ZSTD_btultra2}, /* level 20.*/
  5631. { 17, 18, 17, 9, 3,512, ZSTD_btultra2}, /* level 21.*/
  5632. { 17, 18, 17, 11, 3,999, ZSTD_btultra2}, /* level 22.*/
  5633. },
  5634. { /* for srcSize <= 16 KB */
  5635. /* W, C, H, S, L, T, strat */
  5636. { 14, 12, 13, 1, 5, 1, ZSTD_fast }, /* base for negative levels */
  5637. { 14, 14, 15, 1, 5, 0, ZSTD_fast }, /* level 1 */
  5638. { 14, 14, 15, 1, 4, 0, ZSTD_fast }, /* level 2 */
  5639. { 14, 14, 15, 2, 4, 0, ZSTD_dfast }, /* level 3 */
  5640. { 14, 14, 14, 4, 4, 2, ZSTD_greedy }, /* level 4 */
  5641. { 14, 14, 14, 3, 4, 4, ZSTD_lazy }, /* level 5.*/
  5642. { 14, 14, 14, 4, 4, 8, ZSTD_lazy2 }, /* level 6 */
  5643. { 14, 14, 14, 6, 4, 8, ZSTD_lazy2 }, /* level 7 */
  5644. { 14, 14, 14, 8, 4, 8, ZSTD_lazy2 }, /* level 8.*/
  5645. { 14, 15, 14, 5, 4, 8, ZSTD_btlazy2 }, /* level 9.*/
  5646. { 14, 15, 14, 9, 4, 8, ZSTD_btlazy2 }, /* level 10.*/
  5647. { 14, 15, 14, 3, 4, 12, ZSTD_btopt }, /* level 11.*/
  5648. { 14, 15, 14, 4, 3, 24, ZSTD_btopt }, /* level 12.*/
  5649. { 14, 15, 14, 5, 3, 32, ZSTD_btultra }, /* level 13.*/
  5650. { 14, 15, 15, 6, 3, 64, ZSTD_btultra }, /* level 14.*/
  5651. { 14, 15, 15, 7, 3,256, ZSTD_btultra }, /* level 15.*/
  5652. { 14, 15, 15, 5, 3, 48, ZSTD_btultra2}, /* level 16.*/
  5653. { 14, 15, 15, 6, 3,128, ZSTD_btultra2}, /* level 17.*/
  5654. { 14, 15, 15, 7, 3,256, ZSTD_btultra2}, /* level 18.*/
  5655. { 14, 15, 15, 8, 3,256, ZSTD_btultra2}, /* level 19.*/
  5656. { 14, 15, 15, 8, 3,512, ZSTD_btultra2}, /* level 20.*/
  5657. { 14, 15, 15, 9, 3,512, ZSTD_btultra2}, /* level 21.*/
  5658. { 14, 15, 15, 10, 3,999, ZSTD_btultra2}, /* level 22.*/
  5659. },
  5660. };
  5661. static ZSTD_compressionParameters ZSTD_dedicatedDictSearch_getCParams(int const compressionLevel, size_t const dictSize)
  5662. {
  5663. ZSTD_compressionParameters cParams = ZSTD_getCParams_internal(compressionLevel, 0, dictSize, ZSTD_cpm_createCDict);
  5664. switch (cParams.strategy) {
  5665. case ZSTD_fast:
  5666. case ZSTD_dfast:
  5667. break;
  5668. case ZSTD_greedy:
  5669. case ZSTD_lazy:
  5670. case ZSTD_lazy2:
  5671. cParams.hashLog += ZSTD_LAZY_DDSS_BUCKET_LOG;
  5672. break;
  5673. case ZSTD_btlazy2:
  5674. case ZSTD_btopt:
  5675. case ZSTD_btultra:
  5676. case ZSTD_btultra2:
  5677. break;
  5678. }
  5679. return cParams;
  5680. }
  5681. static int ZSTD_dedicatedDictSearch_isSupported(
  5682. ZSTD_compressionParameters const* cParams)
  5683. {
  5684. return (cParams->strategy >= ZSTD_greedy)
  5685. && (cParams->strategy <= ZSTD_lazy2)
  5686. && (cParams->hashLog > cParams->chainLog)
  5687. && (cParams->chainLog <= 24);
  5688. }
  5689. /**
  5690. * Reverses the adjustment applied to cparams when enabling dedicated dict
  5691. * search. This is used to recover the params set to be used in the working
  5692. * context. (Otherwise, those tables would also grow.)
  5693. */
  5694. static void ZSTD_dedicatedDictSearch_revertCParams(
  5695. ZSTD_compressionParameters* cParams) {
  5696. switch (cParams->strategy) {
  5697. case ZSTD_fast:
  5698. case ZSTD_dfast:
  5699. break;
  5700. case ZSTD_greedy:
  5701. case ZSTD_lazy:
  5702. case ZSTD_lazy2:
  5703. cParams->hashLog -= ZSTD_LAZY_DDSS_BUCKET_LOG;
  5704. if (cParams->hashLog < ZSTD_HASHLOG_MIN) {
  5705. cParams->hashLog = ZSTD_HASHLOG_MIN;
  5706. }
  5707. break;
  5708. case ZSTD_btlazy2:
  5709. case ZSTD_btopt:
  5710. case ZSTD_btultra:
  5711. case ZSTD_btultra2:
  5712. break;
  5713. }
  5714. }
  5715. static U64 ZSTD_getCParamRowSize(U64 srcSizeHint, size_t dictSize, ZSTD_cParamMode_e mode)
  5716. {
  5717. switch (mode) {
  5718. case ZSTD_cpm_unknown:
  5719. case ZSTD_cpm_noAttachDict:
  5720. case ZSTD_cpm_createCDict:
  5721. break;
  5722. case ZSTD_cpm_attachDict:
  5723. dictSize = 0;
  5724. break;
  5725. default:
  5726. assert(0);
  5727. break;
  5728. }
  5729. { int const unknown = srcSizeHint == ZSTD_CONTENTSIZE_UNKNOWN;
  5730. size_t const addedSize = unknown && dictSize > 0 ? 500 : 0;
  5731. return unknown && dictSize == 0 ? ZSTD_CONTENTSIZE_UNKNOWN : srcSizeHint+dictSize+addedSize;
  5732. }
  5733. }
  5734. /*! ZSTD_getCParams_internal() :
  5735. * @return ZSTD_compressionParameters structure for a selected compression level, srcSize and dictSize.
  5736. * Note: srcSizeHint 0 means 0, use ZSTD_CONTENTSIZE_UNKNOWN for unknown.
  5737. * Use dictSize == 0 for unknown or unused.
  5738. * Note: `mode` controls how we treat the `dictSize`. See docs for `ZSTD_cParamMode_e`. */
  5739. static ZSTD_compressionParameters ZSTD_getCParams_internal(int compressionLevel, unsigned long long srcSizeHint, size_t dictSize, ZSTD_cParamMode_e mode)
  5740. {
  5741. U64 const rSize = ZSTD_getCParamRowSize(srcSizeHint, dictSize, mode);
  5742. U32 const tableID = (rSize <= 256 KB) + (rSize <= 128 KB) + (rSize <= 16 KB);
  5743. int row;
  5744. DEBUGLOG(5, "ZSTD_getCParams_internal (cLevel=%i)", compressionLevel);
  5745. /* row */
  5746. if (compressionLevel == 0) row = ZSTD_CLEVEL_DEFAULT; /* 0 == default */
  5747. else if (compressionLevel < 0) row = 0; /* entry 0 is baseline for fast mode */
  5748. else if (compressionLevel > ZSTD_MAX_CLEVEL) row = ZSTD_MAX_CLEVEL;
  5749. else row = compressionLevel;
  5750. { ZSTD_compressionParameters cp = ZSTD_defaultCParameters[tableID][row];
  5751. DEBUGLOG(5, "ZSTD_getCParams_internal selected tableID: %u row: %u strat: %u", tableID, row, (U32)cp.strategy);
  5752. /* acceleration factor */
  5753. if (compressionLevel < 0) {
  5754. int const clampedCompressionLevel = MAX(ZSTD_minCLevel(), compressionLevel);
  5755. cp.targetLength = (unsigned)(-clampedCompressionLevel);
  5756. }
  5757. /* refine parameters based on srcSize & dictSize */
  5758. return ZSTD_adjustCParams_internal(cp, srcSizeHint, dictSize, mode);
  5759. }
  5760. }
  5761. /*! ZSTD_getCParams() :
  5762. * @return ZSTD_compressionParameters structure for a selected compression level, srcSize and dictSize.
  5763. * Size values are optional, provide 0 if not known or unused */
  5764. ZSTD_compressionParameters ZSTD_getCParams(int compressionLevel, unsigned long long srcSizeHint, size_t dictSize)
  5765. {
  5766. if (srcSizeHint == 0) srcSizeHint = ZSTD_CONTENTSIZE_UNKNOWN;
  5767. return ZSTD_getCParams_internal(compressionLevel, srcSizeHint, dictSize, ZSTD_cpm_unknown);
  5768. }
  5769. /*! ZSTD_getParams() :
  5770. * same idea as ZSTD_getCParams()
  5771. * @return a `ZSTD_parameters` structure (instead of `ZSTD_compressionParameters`).
  5772. * Fields of `ZSTD_frameParameters` are set to default values */
  5773. static ZSTD_parameters ZSTD_getParams_internal(int compressionLevel, unsigned long long srcSizeHint, size_t dictSize, ZSTD_cParamMode_e mode) {
  5774. ZSTD_parameters params;
  5775. ZSTD_compressionParameters const cParams = ZSTD_getCParams_internal(compressionLevel, srcSizeHint, dictSize, mode);
  5776. DEBUGLOG(5, "ZSTD_getParams (cLevel=%i)", compressionLevel);
  5777. ZSTD_memset(&params, 0, sizeof(params));
  5778. params.cParams = cParams;
  5779. params.fParams.contentSizeFlag = 1;
  5780. return params;
  5781. }
  5782. /*! ZSTD_getParams() :
  5783. * same idea as ZSTD_getCParams()
  5784. * @return a `ZSTD_parameters` structure (instead of `ZSTD_compressionParameters`).
  5785. * Fields of `ZSTD_frameParameters` are set to default values */
  5786. ZSTD_parameters ZSTD_getParams(int compressionLevel, unsigned long long srcSizeHint, size_t dictSize) {
  5787. if (srcSizeHint == 0) srcSizeHint = ZSTD_CONTENTSIZE_UNKNOWN;
  5788. return ZSTD_getParams_internal(compressionLevel, srcSizeHint, dictSize, ZSTD_cpm_unknown);
  5789. }