zstd_compress.c 329 KB

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