zstd_compress.c 309 KB

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