zstd_compress.c 305 KB

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