zstd_compress.c 337 KB

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