zstd_compress.c 181 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291
  1. /*
  2. * Copyright (c) 2016-present, Yann Collet, Facebook, Inc.
  3. * All rights reserved.
  4. *
  5. * This source code is licensed under both the BSD-style license (found in the
  6. * LICENSE file in the root directory of this source tree) and the GPLv2 (found
  7. * in the COPYING file in the root directory of this source tree).
  8. * You may select, at your option, one of the above-listed licenses.
  9. */
  10. /*-*************************************
  11. * Dependencies
  12. ***************************************/
  13. #include <limits.h> /* INT_MAX */
  14. #include <string.h> /* memset */
  15. #include "cpu.h"
  16. #include "mem.h"
  17. #include "hist.h" /* HIST_countFast_wksp */
  18. #define FSE_STATIC_LINKING_ONLY /* FSE_encodeSymbol */
  19. #include "fse.h"
  20. #define HUF_STATIC_LINKING_ONLY
  21. #include "huf.h"
  22. #include "zstd_compress_internal.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. /*-*************************************
  29. * Helper functions
  30. ***************************************/
  31. size_t ZSTD_compressBound(size_t srcSize) {
  32. return ZSTD_COMPRESSBOUND(srcSize);
  33. }
  34. /*-*************************************
  35. * Context memory management
  36. ***************************************/
  37. struct ZSTD_CDict_s {
  38. void* dictBuffer;
  39. const void* dictContent;
  40. size_t dictContentSize;
  41. void* workspace;
  42. size_t workspaceSize;
  43. ZSTD_matchState_t matchState;
  44. ZSTD_compressedBlockState_t cBlockState;
  45. ZSTD_customMem customMem;
  46. U32 dictID;
  47. }; /* typedef'd to ZSTD_CDict within "zstd.h" */
  48. ZSTD_CCtx* ZSTD_createCCtx(void)
  49. {
  50. return ZSTD_createCCtx_advanced(ZSTD_defaultCMem);
  51. }
  52. static void ZSTD_initCCtx(ZSTD_CCtx* cctx, ZSTD_customMem memManager)
  53. {
  54. assert(cctx != NULL);
  55. memset(cctx, 0, sizeof(*cctx));
  56. cctx->customMem = memManager;
  57. cctx->bmi2 = ZSTD_cpuid_bmi2(ZSTD_cpuid());
  58. { size_t const err = ZSTD_CCtx_reset(cctx, ZSTD_reset_parameters);
  59. assert(!ZSTD_isError(err));
  60. (void)err;
  61. }
  62. }
  63. ZSTD_CCtx* ZSTD_createCCtx_advanced(ZSTD_customMem customMem)
  64. {
  65. ZSTD_STATIC_ASSERT(zcss_init==0);
  66. ZSTD_STATIC_ASSERT(ZSTD_CONTENTSIZE_UNKNOWN==(0ULL - 1));
  67. if (!customMem.customAlloc ^ !customMem.customFree) return NULL;
  68. { ZSTD_CCtx* const cctx = (ZSTD_CCtx*)ZSTD_malloc(sizeof(ZSTD_CCtx), customMem);
  69. if (!cctx) return NULL;
  70. ZSTD_initCCtx(cctx, customMem);
  71. return cctx;
  72. }
  73. }
  74. ZSTD_CCtx* ZSTD_initStaticCCtx(void *workspace, size_t workspaceSize)
  75. {
  76. ZSTD_CCtx* const cctx = (ZSTD_CCtx*) workspace;
  77. if (workspaceSize <= sizeof(ZSTD_CCtx)) return NULL; /* minimum size */
  78. if ((size_t)workspace & 7) return NULL; /* must be 8-aligned */
  79. memset(workspace, 0, workspaceSize); /* may be a bit generous, could memset be smaller ? */
  80. cctx->staticSize = workspaceSize;
  81. cctx->workSpace = (void*)(cctx+1);
  82. cctx->workSpaceSize = workspaceSize - sizeof(ZSTD_CCtx);
  83. /* statically sized space. entropyWorkspace never moves (but prev/next block swap places) */
  84. if (cctx->workSpaceSize < HUF_WORKSPACE_SIZE + 2 * sizeof(ZSTD_compressedBlockState_t)) return NULL;
  85. assert(((size_t)cctx->workSpace & (sizeof(void*)-1)) == 0); /* ensure correct alignment */
  86. cctx->blockState.prevCBlock = (ZSTD_compressedBlockState_t*)cctx->workSpace;
  87. cctx->blockState.nextCBlock = cctx->blockState.prevCBlock + 1;
  88. {
  89. void* const ptr = cctx->blockState.nextCBlock + 1;
  90. cctx->entropyWorkspace = (U32*)ptr;
  91. }
  92. cctx->bmi2 = ZSTD_cpuid_bmi2(ZSTD_cpuid());
  93. return cctx;
  94. }
  95. static void ZSTD_freeCCtxContent(ZSTD_CCtx* cctx)
  96. {
  97. assert(cctx != NULL);
  98. assert(cctx->staticSize == 0);
  99. ZSTD_free(cctx->workSpace, cctx->customMem); cctx->workSpace = NULL;
  100. ZSTD_freeCDict(cctx->cdictLocal); cctx->cdictLocal = NULL;
  101. #ifdef ZSTD_MULTITHREAD
  102. ZSTDMT_freeCCtx(cctx->mtctx); cctx->mtctx = NULL;
  103. #endif
  104. }
  105. size_t ZSTD_freeCCtx(ZSTD_CCtx* cctx)
  106. {
  107. if (cctx==NULL) return 0; /* support free on NULL */
  108. if (cctx->staticSize) return ERROR(memory_allocation); /* not compatible with static CCtx */
  109. ZSTD_freeCCtxContent(cctx);
  110. ZSTD_free(cctx, cctx->customMem);
  111. return 0;
  112. }
  113. static size_t ZSTD_sizeof_mtctx(const ZSTD_CCtx* cctx)
  114. {
  115. #ifdef ZSTD_MULTITHREAD
  116. return ZSTDMT_sizeof_CCtx(cctx->mtctx);
  117. #else
  118. (void)cctx;
  119. return 0;
  120. #endif
  121. }
  122. size_t ZSTD_sizeof_CCtx(const ZSTD_CCtx* cctx)
  123. {
  124. if (cctx==NULL) return 0; /* support sizeof on NULL */
  125. return sizeof(*cctx) + cctx->workSpaceSize
  126. + ZSTD_sizeof_CDict(cctx->cdictLocal)
  127. + ZSTD_sizeof_mtctx(cctx);
  128. }
  129. size_t ZSTD_sizeof_CStream(const ZSTD_CStream* zcs)
  130. {
  131. return ZSTD_sizeof_CCtx(zcs); /* same object */
  132. }
  133. /* private API call, for dictBuilder only */
  134. const seqStore_t* ZSTD_getSeqStore(const ZSTD_CCtx* ctx) { return &(ctx->seqStore); }
  135. static ZSTD_CCtx_params ZSTD_makeCCtxParamsFromCParams(
  136. ZSTD_compressionParameters cParams)
  137. {
  138. ZSTD_CCtx_params cctxParams;
  139. memset(&cctxParams, 0, sizeof(cctxParams));
  140. cctxParams.cParams = cParams;
  141. cctxParams.compressionLevel = ZSTD_CLEVEL_DEFAULT; /* should not matter, as all cParams are presumed properly defined */
  142. assert(!ZSTD_checkCParams(cParams));
  143. cctxParams.fParams.contentSizeFlag = 1;
  144. return cctxParams;
  145. }
  146. static ZSTD_CCtx_params* ZSTD_createCCtxParams_advanced(
  147. ZSTD_customMem customMem)
  148. {
  149. ZSTD_CCtx_params* params;
  150. if (!customMem.customAlloc ^ !customMem.customFree) return NULL;
  151. params = (ZSTD_CCtx_params*)ZSTD_calloc(
  152. sizeof(ZSTD_CCtx_params), customMem);
  153. if (!params) { return NULL; }
  154. params->customMem = customMem;
  155. params->compressionLevel = ZSTD_CLEVEL_DEFAULT;
  156. params->fParams.contentSizeFlag = 1;
  157. return params;
  158. }
  159. ZSTD_CCtx_params* ZSTD_createCCtxParams(void)
  160. {
  161. return ZSTD_createCCtxParams_advanced(ZSTD_defaultCMem);
  162. }
  163. size_t ZSTD_freeCCtxParams(ZSTD_CCtx_params* params)
  164. {
  165. if (params == NULL) { return 0; }
  166. ZSTD_free(params, params->customMem);
  167. return 0;
  168. }
  169. size_t ZSTD_CCtxParams_reset(ZSTD_CCtx_params* params)
  170. {
  171. return ZSTD_CCtxParams_init(params, ZSTD_CLEVEL_DEFAULT);
  172. }
  173. size_t ZSTD_CCtxParams_init(ZSTD_CCtx_params* cctxParams, int compressionLevel) {
  174. if (!cctxParams) { return ERROR(GENERIC); }
  175. memset(cctxParams, 0, sizeof(*cctxParams));
  176. cctxParams->compressionLevel = compressionLevel;
  177. cctxParams->fParams.contentSizeFlag = 1;
  178. return 0;
  179. }
  180. size_t ZSTD_CCtxParams_init_advanced(ZSTD_CCtx_params* cctxParams, ZSTD_parameters params)
  181. {
  182. if (!cctxParams) { return ERROR(GENERIC); }
  183. CHECK_F( ZSTD_checkCParams(params.cParams) );
  184. memset(cctxParams, 0, sizeof(*cctxParams));
  185. cctxParams->cParams = params.cParams;
  186. cctxParams->fParams = params.fParams;
  187. cctxParams->compressionLevel = ZSTD_CLEVEL_DEFAULT; /* should not matter, as all cParams are presumed properly defined */
  188. assert(!ZSTD_checkCParams(params.cParams));
  189. return 0;
  190. }
  191. /* ZSTD_assignParamsToCCtxParams() :
  192. * params is presumed valid at this stage */
  193. static ZSTD_CCtx_params ZSTD_assignParamsToCCtxParams(
  194. ZSTD_CCtx_params cctxParams, ZSTD_parameters params)
  195. {
  196. ZSTD_CCtx_params ret = cctxParams;
  197. ret.cParams = params.cParams;
  198. ret.fParams = params.fParams;
  199. ret.compressionLevel = ZSTD_CLEVEL_DEFAULT; /* should not matter, as all cParams are presumed properly defined */
  200. assert(!ZSTD_checkCParams(params.cParams));
  201. return ret;
  202. }
  203. ZSTD_bounds ZSTD_cParam_getBounds(ZSTD_cParameter param)
  204. {
  205. ZSTD_bounds bounds = { 0, 0, 0 };
  206. switch(param)
  207. {
  208. case ZSTD_c_compressionLevel:
  209. bounds.lowerBound = ZSTD_minCLevel();
  210. bounds.upperBound = ZSTD_maxCLevel();
  211. return bounds;
  212. case ZSTD_c_windowLog:
  213. bounds.lowerBound = ZSTD_WINDOWLOG_MIN;
  214. bounds.upperBound = ZSTD_WINDOWLOG_MAX;
  215. return bounds;
  216. case ZSTD_c_hashLog:
  217. bounds.lowerBound = ZSTD_HASHLOG_MIN;
  218. bounds.upperBound = ZSTD_HASHLOG_MAX;
  219. return bounds;
  220. case ZSTD_c_chainLog:
  221. bounds.lowerBound = ZSTD_CHAINLOG_MIN;
  222. bounds.upperBound = ZSTD_CHAINLOG_MAX;
  223. return bounds;
  224. case ZSTD_c_searchLog:
  225. bounds.lowerBound = ZSTD_SEARCHLOG_MIN;
  226. bounds.upperBound = ZSTD_SEARCHLOG_MAX;
  227. return bounds;
  228. case ZSTD_c_minMatch:
  229. bounds.lowerBound = ZSTD_MINMATCH_MIN;
  230. bounds.upperBound = ZSTD_MINMATCH_MAX;
  231. return bounds;
  232. case ZSTD_c_targetLength:
  233. bounds.lowerBound = ZSTD_TARGETLENGTH_MIN;
  234. bounds.upperBound = ZSTD_TARGETLENGTH_MAX;
  235. return bounds;
  236. case ZSTD_c_strategy:
  237. bounds.lowerBound = ZSTD_STRATEGY_MIN;
  238. bounds.upperBound = ZSTD_STRATEGY_MAX;
  239. return bounds;
  240. case ZSTD_c_contentSizeFlag:
  241. bounds.lowerBound = 0;
  242. bounds.upperBound = 1;
  243. return bounds;
  244. case ZSTD_c_checksumFlag:
  245. bounds.lowerBound = 0;
  246. bounds.upperBound = 1;
  247. return bounds;
  248. case ZSTD_c_dictIDFlag:
  249. bounds.lowerBound = 0;
  250. bounds.upperBound = 1;
  251. return bounds;
  252. case ZSTD_c_nbWorkers:
  253. bounds.lowerBound = 0;
  254. #ifdef ZSTD_MULTITHREAD
  255. bounds.upperBound = ZSTDMT_NBWORKERS_MAX;
  256. #else
  257. bounds.upperBound = 0;
  258. #endif
  259. return bounds;
  260. case ZSTD_c_jobSize:
  261. bounds.lowerBound = 0;
  262. #ifdef ZSTD_MULTITHREAD
  263. bounds.upperBound = ZSTDMT_JOBSIZE_MAX;
  264. #else
  265. bounds.upperBound = 0;
  266. #endif
  267. return bounds;
  268. case ZSTD_c_overlapLog:
  269. bounds.lowerBound = ZSTD_OVERLAPLOG_MIN;
  270. bounds.upperBound = ZSTD_OVERLAPLOG_MAX;
  271. return bounds;
  272. case ZSTD_c_enableLongDistanceMatching:
  273. bounds.lowerBound = 0;
  274. bounds.upperBound = 1;
  275. return bounds;
  276. case ZSTD_c_ldmHashLog:
  277. bounds.lowerBound = ZSTD_LDM_HASHLOG_MIN;
  278. bounds.upperBound = ZSTD_LDM_HASHLOG_MAX;
  279. return bounds;
  280. case ZSTD_c_ldmMinMatch:
  281. bounds.lowerBound = ZSTD_LDM_MINMATCH_MIN;
  282. bounds.upperBound = ZSTD_LDM_MINMATCH_MAX;
  283. return bounds;
  284. case ZSTD_c_ldmBucketSizeLog:
  285. bounds.lowerBound = ZSTD_LDM_BUCKETSIZELOG_MIN;
  286. bounds.upperBound = ZSTD_LDM_BUCKETSIZELOG_MAX;
  287. return bounds;
  288. case ZSTD_c_ldmHashRateLog:
  289. bounds.lowerBound = ZSTD_LDM_HASHRATELOG_MIN;
  290. bounds.upperBound = ZSTD_LDM_HASHRATELOG_MAX;
  291. return bounds;
  292. /* experimental parameters */
  293. case ZSTD_c_rsyncable:
  294. bounds.lowerBound = 0;
  295. bounds.upperBound = 1;
  296. return bounds;
  297. case ZSTD_c_forceMaxWindow :
  298. bounds.lowerBound = 0;
  299. bounds.upperBound = 1;
  300. return bounds;
  301. case ZSTD_c_format:
  302. ZSTD_STATIC_ASSERT(ZSTD_f_zstd1 < ZSTD_f_zstd1_magicless);
  303. bounds.lowerBound = ZSTD_f_zstd1;
  304. bounds.upperBound = ZSTD_f_zstd1_magicless; /* note : how to ensure at compile time that this is the highest value enum ? */
  305. return bounds;
  306. case ZSTD_c_forceAttachDict:
  307. ZSTD_STATIC_ASSERT(ZSTD_dictDefaultAttach < ZSTD_dictForceCopy);
  308. bounds.lowerBound = ZSTD_dictDefaultAttach;
  309. bounds.upperBound = ZSTD_dictForceCopy; /* note : how to ensure at compile time that this is the highest value enum ? */
  310. return bounds;
  311. default:
  312. { ZSTD_bounds const boundError = { ERROR(parameter_unsupported), 0, 0 };
  313. return boundError;
  314. }
  315. }
  316. }
  317. /* ZSTD_cParam_withinBounds:
  318. * @return 1 if value is within cParam bounds,
  319. * 0 otherwise */
  320. static int ZSTD_cParam_withinBounds(ZSTD_cParameter cParam, int value)
  321. {
  322. ZSTD_bounds const bounds = ZSTD_cParam_getBounds(cParam);
  323. if (ZSTD_isError(bounds.error)) return 0;
  324. if (value < bounds.lowerBound) return 0;
  325. if (value > bounds.upperBound) return 0;
  326. return 1;
  327. }
  328. #define BOUNDCHECK(cParam, val) { \
  329. if (!ZSTD_cParam_withinBounds(cParam,val)) { \
  330. return ERROR(parameter_outOfBound); \
  331. } }
  332. static int ZSTD_isUpdateAuthorized(ZSTD_cParameter param)
  333. {
  334. switch(param)
  335. {
  336. case ZSTD_c_compressionLevel:
  337. case ZSTD_c_hashLog:
  338. case ZSTD_c_chainLog:
  339. case ZSTD_c_searchLog:
  340. case ZSTD_c_minMatch:
  341. case ZSTD_c_targetLength:
  342. case ZSTD_c_strategy:
  343. return 1;
  344. case ZSTD_c_format:
  345. case ZSTD_c_windowLog:
  346. case ZSTD_c_contentSizeFlag:
  347. case ZSTD_c_checksumFlag:
  348. case ZSTD_c_dictIDFlag:
  349. case ZSTD_c_forceMaxWindow :
  350. case ZSTD_c_nbWorkers:
  351. case ZSTD_c_jobSize:
  352. case ZSTD_c_overlapLog:
  353. case ZSTD_c_rsyncable:
  354. case ZSTD_c_enableLongDistanceMatching:
  355. case ZSTD_c_ldmHashLog:
  356. case ZSTD_c_ldmMinMatch:
  357. case ZSTD_c_ldmBucketSizeLog:
  358. case ZSTD_c_ldmHashRateLog:
  359. case ZSTD_c_forceAttachDict:
  360. default:
  361. return 0;
  362. }
  363. }
  364. size_t ZSTD_CCtx_setParameter(ZSTD_CCtx* cctx, ZSTD_cParameter param, int value)
  365. {
  366. DEBUGLOG(4, "ZSTD_CCtx_setParameter (%i, %i)", (int)param, value);
  367. if (cctx->streamStage != zcss_init) {
  368. if (ZSTD_isUpdateAuthorized(param)) {
  369. cctx->cParamsChanged = 1;
  370. } else {
  371. return ERROR(stage_wrong);
  372. } }
  373. switch(param)
  374. {
  375. case ZSTD_c_format :
  376. return ZSTD_CCtxParam_setParameter(&cctx->requestedParams, param, value);
  377. case ZSTD_c_compressionLevel:
  378. if (cctx->cdict) return ERROR(stage_wrong);
  379. return ZSTD_CCtxParam_setParameter(&cctx->requestedParams, param, value);
  380. case ZSTD_c_windowLog:
  381. case ZSTD_c_hashLog:
  382. case ZSTD_c_chainLog:
  383. case ZSTD_c_searchLog:
  384. case ZSTD_c_minMatch:
  385. case ZSTD_c_targetLength:
  386. case ZSTD_c_strategy:
  387. if (cctx->cdict) return ERROR(stage_wrong);
  388. return ZSTD_CCtxParam_setParameter(&cctx->requestedParams, param, value);
  389. case ZSTD_c_contentSizeFlag:
  390. case ZSTD_c_checksumFlag:
  391. case ZSTD_c_dictIDFlag:
  392. return ZSTD_CCtxParam_setParameter(&cctx->requestedParams, param, value);
  393. case ZSTD_c_forceMaxWindow : /* Force back-references to remain < windowSize,
  394. * even when referencing into Dictionary content.
  395. * default : 0 when using a CDict, 1 when using a Prefix */
  396. return ZSTD_CCtxParam_setParameter(&cctx->requestedParams, param, value);
  397. case ZSTD_c_forceAttachDict:
  398. return ZSTD_CCtxParam_setParameter(&cctx->requestedParams, param, value);
  399. case ZSTD_c_nbWorkers:
  400. if ((value!=0) && cctx->staticSize) {
  401. return ERROR(parameter_unsupported); /* MT not compatible with static alloc */
  402. }
  403. return ZSTD_CCtxParam_setParameter(&cctx->requestedParams, param, value);
  404. case ZSTD_c_jobSize:
  405. case ZSTD_c_overlapLog:
  406. case ZSTD_c_rsyncable:
  407. return ZSTD_CCtxParam_setParameter(&cctx->requestedParams, param, value);
  408. case ZSTD_c_enableLongDistanceMatching:
  409. case ZSTD_c_ldmHashLog:
  410. case ZSTD_c_ldmMinMatch:
  411. case ZSTD_c_ldmBucketSizeLog:
  412. case ZSTD_c_ldmHashRateLog:
  413. if (cctx->cdict) return ERROR(stage_wrong);
  414. return ZSTD_CCtxParam_setParameter(&cctx->requestedParams, param, value);
  415. default: return ERROR(parameter_unsupported);
  416. }
  417. }
  418. size_t ZSTD_CCtxParam_setParameter(ZSTD_CCtx_params* CCtxParams,
  419. ZSTD_cParameter param, int value)
  420. {
  421. DEBUGLOG(4, "ZSTD_CCtxParam_setParameter (%i, %i)", (int)param, value);
  422. switch(param)
  423. {
  424. case ZSTD_c_format :
  425. BOUNDCHECK(ZSTD_c_format, value);
  426. CCtxParams->format = (ZSTD_format_e)value;
  427. return (size_t)CCtxParams->format;
  428. case ZSTD_c_compressionLevel : {
  429. int cLevel = value;
  430. if (cLevel > ZSTD_maxCLevel()) cLevel = ZSTD_maxCLevel();
  431. if (cLevel < ZSTD_minCLevel()) cLevel = ZSTD_minCLevel();
  432. if (cLevel) { /* 0 : does not change current level */
  433. CCtxParams->compressionLevel = cLevel;
  434. }
  435. if (CCtxParams->compressionLevel >= 0) return CCtxParams->compressionLevel;
  436. return 0; /* return type (size_t) cannot represent negative values */
  437. }
  438. case ZSTD_c_windowLog :
  439. if (value!=0) /* 0 => use default */
  440. BOUNDCHECK(ZSTD_c_windowLog, value);
  441. CCtxParams->cParams.windowLog = value;
  442. return CCtxParams->cParams.windowLog;
  443. case ZSTD_c_hashLog :
  444. if (value!=0) /* 0 => use default */
  445. BOUNDCHECK(ZSTD_c_hashLog, value);
  446. CCtxParams->cParams.hashLog = value;
  447. return CCtxParams->cParams.hashLog;
  448. case ZSTD_c_chainLog :
  449. if (value!=0) /* 0 => use default */
  450. BOUNDCHECK(ZSTD_c_chainLog, value);
  451. CCtxParams->cParams.chainLog = value;
  452. return CCtxParams->cParams.chainLog;
  453. case ZSTD_c_searchLog :
  454. if (value!=0) /* 0 => use default */
  455. BOUNDCHECK(ZSTD_c_searchLog, value);
  456. CCtxParams->cParams.searchLog = value;
  457. return value;
  458. case ZSTD_c_minMatch :
  459. if (value!=0) /* 0 => use default */
  460. BOUNDCHECK(ZSTD_c_minMatch, value);
  461. CCtxParams->cParams.minMatch = value;
  462. return CCtxParams->cParams.minMatch;
  463. case ZSTD_c_targetLength :
  464. BOUNDCHECK(ZSTD_c_targetLength, value);
  465. CCtxParams->cParams.targetLength = value;
  466. return CCtxParams->cParams.targetLength;
  467. case ZSTD_c_strategy :
  468. if (value!=0) /* 0 => use default */
  469. BOUNDCHECK(ZSTD_c_strategy, value);
  470. CCtxParams->cParams.strategy = (ZSTD_strategy)value;
  471. return (size_t)CCtxParams->cParams.strategy;
  472. case ZSTD_c_contentSizeFlag :
  473. /* Content size written in frame header _when known_ (default:1) */
  474. DEBUGLOG(4, "set content size flag = %u", (value!=0));
  475. CCtxParams->fParams.contentSizeFlag = value != 0;
  476. return CCtxParams->fParams.contentSizeFlag;
  477. case ZSTD_c_checksumFlag :
  478. /* A 32-bits content checksum will be calculated and written at end of frame (default:0) */
  479. CCtxParams->fParams.checksumFlag = value != 0;
  480. return CCtxParams->fParams.checksumFlag;
  481. case ZSTD_c_dictIDFlag : /* When applicable, dictionary's dictID is provided in frame header (default:1) */
  482. DEBUGLOG(4, "set dictIDFlag = %u", (value!=0));
  483. CCtxParams->fParams.noDictIDFlag = !value;
  484. return !CCtxParams->fParams.noDictIDFlag;
  485. case ZSTD_c_forceMaxWindow :
  486. CCtxParams->forceWindow = (value != 0);
  487. return CCtxParams->forceWindow;
  488. case ZSTD_c_forceAttachDict : {
  489. const ZSTD_dictAttachPref_e pref = (ZSTD_dictAttachPref_e)value;
  490. BOUNDCHECK(ZSTD_c_forceAttachDict, pref);
  491. CCtxParams->attachDictPref = pref;
  492. return CCtxParams->attachDictPref;
  493. }
  494. case ZSTD_c_nbWorkers :
  495. #ifndef ZSTD_MULTITHREAD
  496. if (value!=0) return ERROR(parameter_unsupported);
  497. return 0;
  498. #else
  499. return ZSTDMT_CCtxParam_setNbWorkers(CCtxParams, value);
  500. #endif
  501. case ZSTD_c_jobSize :
  502. #ifndef ZSTD_MULTITHREAD
  503. return ERROR(parameter_unsupported);
  504. #else
  505. return ZSTDMT_CCtxParam_setMTCtxParameter(CCtxParams, ZSTDMT_p_jobSize, value);
  506. #endif
  507. case ZSTD_c_overlapLog :
  508. #ifndef ZSTD_MULTITHREAD
  509. return ERROR(parameter_unsupported);
  510. #else
  511. return ZSTDMT_CCtxParam_setMTCtxParameter(CCtxParams, ZSTDMT_p_overlapLog, value);
  512. #endif
  513. case ZSTD_c_rsyncable :
  514. #ifndef ZSTD_MULTITHREAD
  515. return ERROR(parameter_unsupported);
  516. #else
  517. return ZSTDMT_CCtxParam_setMTCtxParameter(CCtxParams, ZSTDMT_p_rsyncable, value);
  518. #endif
  519. case ZSTD_c_enableLongDistanceMatching :
  520. CCtxParams->ldmParams.enableLdm = (value!=0);
  521. return CCtxParams->ldmParams.enableLdm;
  522. case ZSTD_c_ldmHashLog :
  523. if (value!=0) /* 0 ==> auto */
  524. BOUNDCHECK(ZSTD_c_ldmHashLog, value);
  525. CCtxParams->ldmParams.hashLog = value;
  526. return CCtxParams->ldmParams.hashLog;
  527. case ZSTD_c_ldmMinMatch :
  528. if (value!=0) /* 0 ==> default */
  529. BOUNDCHECK(ZSTD_c_ldmMinMatch, value);
  530. CCtxParams->ldmParams.minMatchLength = value;
  531. return CCtxParams->ldmParams.minMatchLength;
  532. case ZSTD_c_ldmBucketSizeLog :
  533. if (value!=0) /* 0 ==> default */
  534. BOUNDCHECK(ZSTD_c_ldmBucketSizeLog, value);
  535. CCtxParams->ldmParams.bucketSizeLog = value;
  536. return CCtxParams->ldmParams.bucketSizeLog;
  537. case ZSTD_c_ldmHashRateLog :
  538. if (value > ZSTD_WINDOWLOG_MAX - ZSTD_HASHLOG_MIN)
  539. return ERROR(parameter_outOfBound);
  540. CCtxParams->ldmParams.hashRateLog = value;
  541. return CCtxParams->ldmParams.hashRateLog;
  542. default: return ERROR(parameter_unsupported);
  543. }
  544. }
  545. size_t ZSTD_CCtx_getParameter(ZSTD_CCtx* cctx, ZSTD_cParameter param, int* value)
  546. {
  547. return ZSTD_CCtxParam_getParameter(&cctx->requestedParams, param, value);
  548. }
  549. size_t ZSTD_CCtxParam_getParameter(
  550. ZSTD_CCtx_params* CCtxParams, ZSTD_cParameter param, int* value)
  551. {
  552. switch(param)
  553. {
  554. case ZSTD_c_format :
  555. *value = CCtxParams->format;
  556. break;
  557. case ZSTD_c_compressionLevel :
  558. *value = CCtxParams->compressionLevel;
  559. break;
  560. case ZSTD_c_windowLog :
  561. *value = CCtxParams->cParams.windowLog;
  562. break;
  563. case ZSTD_c_hashLog :
  564. *value = CCtxParams->cParams.hashLog;
  565. break;
  566. case ZSTD_c_chainLog :
  567. *value = CCtxParams->cParams.chainLog;
  568. break;
  569. case ZSTD_c_searchLog :
  570. *value = CCtxParams->cParams.searchLog;
  571. break;
  572. case ZSTD_c_minMatch :
  573. *value = CCtxParams->cParams.minMatch;
  574. break;
  575. case ZSTD_c_targetLength :
  576. *value = CCtxParams->cParams.targetLength;
  577. break;
  578. case ZSTD_c_strategy :
  579. *value = (unsigned)CCtxParams->cParams.strategy;
  580. break;
  581. case ZSTD_c_contentSizeFlag :
  582. *value = CCtxParams->fParams.contentSizeFlag;
  583. break;
  584. case ZSTD_c_checksumFlag :
  585. *value = CCtxParams->fParams.checksumFlag;
  586. break;
  587. case ZSTD_c_dictIDFlag :
  588. *value = !CCtxParams->fParams.noDictIDFlag;
  589. break;
  590. case ZSTD_c_forceMaxWindow :
  591. *value = CCtxParams->forceWindow;
  592. break;
  593. case ZSTD_c_forceAttachDict :
  594. *value = CCtxParams->attachDictPref;
  595. break;
  596. case ZSTD_c_nbWorkers :
  597. #ifndef ZSTD_MULTITHREAD
  598. assert(CCtxParams->nbWorkers == 0);
  599. #endif
  600. *value = CCtxParams->nbWorkers;
  601. break;
  602. case ZSTD_c_jobSize :
  603. #ifndef ZSTD_MULTITHREAD
  604. return ERROR(parameter_unsupported);
  605. #else
  606. assert(CCtxParams->jobSize <= INT_MAX);
  607. *value = (int)CCtxParams->jobSize;
  608. break;
  609. #endif
  610. case ZSTD_c_overlapLog :
  611. #ifndef ZSTD_MULTITHREAD
  612. return ERROR(parameter_unsupported);
  613. #else
  614. *value = CCtxParams->overlapLog;
  615. break;
  616. #endif
  617. case ZSTD_c_rsyncable :
  618. #ifndef ZSTD_MULTITHREAD
  619. return ERROR(parameter_unsupported);
  620. #else
  621. *value = CCtxParams->rsyncable;
  622. break;
  623. #endif
  624. case ZSTD_c_enableLongDistanceMatching :
  625. *value = CCtxParams->ldmParams.enableLdm;
  626. break;
  627. case ZSTD_c_ldmHashLog :
  628. *value = CCtxParams->ldmParams.hashLog;
  629. break;
  630. case ZSTD_c_ldmMinMatch :
  631. *value = CCtxParams->ldmParams.minMatchLength;
  632. break;
  633. case ZSTD_c_ldmBucketSizeLog :
  634. *value = CCtxParams->ldmParams.bucketSizeLog;
  635. break;
  636. case ZSTD_c_ldmHashRateLog :
  637. *value = CCtxParams->ldmParams.hashRateLog;
  638. break;
  639. default: return ERROR(parameter_unsupported);
  640. }
  641. return 0;
  642. }
  643. /** ZSTD_CCtx_setParametersUsingCCtxParams() :
  644. * just applies `params` into `cctx`
  645. * no action is performed, parameters are merely stored.
  646. * If ZSTDMT is enabled, parameters are pushed to cctx->mtctx.
  647. * This is possible even if a compression is ongoing.
  648. * In which case, new parameters will be applied on the fly, starting with next compression job.
  649. */
  650. size_t ZSTD_CCtx_setParametersUsingCCtxParams(
  651. ZSTD_CCtx* cctx, const ZSTD_CCtx_params* params)
  652. {
  653. DEBUGLOG(4, "ZSTD_CCtx_setParametersUsingCCtxParams");
  654. if (cctx->streamStage != zcss_init) return ERROR(stage_wrong);
  655. if (cctx->cdict) return ERROR(stage_wrong);
  656. cctx->requestedParams = *params;
  657. return 0;
  658. }
  659. ZSTDLIB_API size_t ZSTD_CCtx_setPledgedSrcSize(ZSTD_CCtx* cctx, unsigned long long pledgedSrcSize)
  660. {
  661. DEBUGLOG(4, "ZSTD_CCtx_setPledgedSrcSize to %u bytes", (U32)pledgedSrcSize);
  662. if (cctx->streamStage != zcss_init) return ERROR(stage_wrong);
  663. cctx->pledgedSrcSizePlusOne = pledgedSrcSize+1;
  664. return 0;
  665. }
  666. size_t ZSTD_CCtx_loadDictionary_advanced(
  667. ZSTD_CCtx* cctx, const void* dict, size_t dictSize,
  668. ZSTD_dictLoadMethod_e dictLoadMethod, ZSTD_dictContentType_e dictContentType)
  669. {
  670. if (cctx->streamStage != zcss_init) return ERROR(stage_wrong);
  671. if (cctx->staticSize) return ERROR(memory_allocation); /* no malloc for static CCtx */
  672. DEBUGLOG(4, "ZSTD_CCtx_loadDictionary_advanced (size: %u)", (U32)dictSize);
  673. ZSTD_freeCDict(cctx->cdictLocal); /* in case one already exists */
  674. if (dict==NULL || dictSize==0) { /* no dictionary mode */
  675. cctx->cdictLocal = NULL;
  676. cctx->cdict = NULL;
  677. } else {
  678. ZSTD_compressionParameters const cParams =
  679. ZSTD_getCParamsFromCCtxParams(&cctx->requestedParams, cctx->pledgedSrcSizePlusOne-1, dictSize);
  680. cctx->cdictLocal = ZSTD_createCDict_advanced(
  681. dict, dictSize,
  682. dictLoadMethod, dictContentType,
  683. cParams, cctx->customMem);
  684. cctx->cdict = cctx->cdictLocal;
  685. if (cctx->cdictLocal == NULL)
  686. return ERROR(memory_allocation);
  687. }
  688. return 0;
  689. }
  690. ZSTDLIB_API size_t ZSTD_CCtx_loadDictionary_byReference(
  691. ZSTD_CCtx* cctx, const void* dict, size_t dictSize)
  692. {
  693. return ZSTD_CCtx_loadDictionary_advanced(
  694. cctx, dict, dictSize, ZSTD_dlm_byRef, ZSTD_dct_auto);
  695. }
  696. ZSTDLIB_API size_t ZSTD_CCtx_loadDictionary(ZSTD_CCtx* cctx, const void* dict, size_t dictSize)
  697. {
  698. return ZSTD_CCtx_loadDictionary_advanced(
  699. cctx, dict, dictSize, ZSTD_dlm_byCopy, ZSTD_dct_auto);
  700. }
  701. size_t ZSTD_CCtx_refCDict(ZSTD_CCtx* cctx, const ZSTD_CDict* cdict)
  702. {
  703. if (cctx->streamStage != zcss_init) return ERROR(stage_wrong);
  704. cctx->cdict = cdict;
  705. memset(&cctx->prefixDict, 0, sizeof(cctx->prefixDict)); /* exclusive */
  706. return 0;
  707. }
  708. size_t ZSTD_CCtx_refPrefix(ZSTD_CCtx* cctx, const void* prefix, size_t prefixSize)
  709. {
  710. return ZSTD_CCtx_refPrefix_advanced(cctx, prefix, prefixSize, ZSTD_dct_rawContent);
  711. }
  712. size_t ZSTD_CCtx_refPrefix_advanced(
  713. ZSTD_CCtx* cctx, const void* prefix, size_t prefixSize, ZSTD_dictContentType_e dictContentType)
  714. {
  715. if (cctx->streamStage != zcss_init) return ERROR(stage_wrong);
  716. cctx->cdict = NULL; /* prefix discards any prior cdict */
  717. cctx->prefixDict.dict = prefix;
  718. cctx->prefixDict.dictSize = prefixSize;
  719. cctx->prefixDict.dictContentType = dictContentType;
  720. return 0;
  721. }
  722. /*! ZSTD_CCtx_reset() :
  723. * Also dumps dictionary */
  724. size_t ZSTD_CCtx_reset(ZSTD_CCtx* cctx, ZSTD_ResetDirective reset)
  725. {
  726. if ( (reset == ZSTD_reset_session_only)
  727. || (reset == ZSTD_reset_session_and_parameters) ) {
  728. cctx->streamStage = zcss_init;
  729. cctx->pledgedSrcSizePlusOne = 0;
  730. }
  731. if ( (reset == ZSTD_reset_parameters)
  732. || (reset == ZSTD_reset_session_and_parameters) ) {
  733. if (cctx->streamStage != zcss_init) return ERROR(stage_wrong);
  734. cctx->cdict = NULL;
  735. return ZSTD_CCtxParams_reset(&cctx->requestedParams);
  736. }
  737. return 0;
  738. }
  739. /** ZSTD_checkCParams() :
  740. control CParam values remain within authorized range.
  741. @return : 0, or an error code if one value is beyond authorized range */
  742. size_t ZSTD_checkCParams(ZSTD_compressionParameters cParams)
  743. {
  744. BOUNDCHECK(ZSTD_c_windowLog, cParams.windowLog);
  745. BOUNDCHECK(ZSTD_c_chainLog, cParams.chainLog);
  746. BOUNDCHECK(ZSTD_c_hashLog, cParams.hashLog);
  747. BOUNDCHECK(ZSTD_c_searchLog, cParams.searchLog);
  748. BOUNDCHECK(ZSTD_c_minMatch, cParams.minMatch);
  749. BOUNDCHECK(ZSTD_c_targetLength,cParams.targetLength);
  750. BOUNDCHECK(ZSTD_c_strategy, cParams.strategy);
  751. return 0;
  752. }
  753. /** ZSTD_clampCParams() :
  754. * make CParam values within valid range.
  755. * @return : valid CParams */
  756. static ZSTD_compressionParameters
  757. ZSTD_clampCParams(ZSTD_compressionParameters cParams)
  758. {
  759. # define CLAMP_TYPE(cParam, val, type) { \
  760. ZSTD_bounds const bounds = ZSTD_cParam_getBounds(cParam); \
  761. if ((int)val<bounds.lowerBound) val=(type)bounds.lowerBound; \
  762. else if ((int)val>bounds.upperBound) val=(type)bounds.upperBound; \
  763. }
  764. # define CLAMP(cParam, val) CLAMP_TYPE(cParam, val, int)
  765. CLAMP(ZSTD_c_windowLog, cParams.windowLog);
  766. CLAMP(ZSTD_c_chainLog, cParams.chainLog);
  767. CLAMP(ZSTD_c_hashLog, cParams.hashLog);
  768. CLAMP(ZSTD_c_searchLog, cParams.searchLog);
  769. CLAMP(ZSTD_c_minMatch, cParams.minMatch);
  770. CLAMP(ZSTD_c_targetLength,cParams.targetLength);
  771. CLAMP_TYPE(ZSTD_c_strategy,cParams.strategy, ZSTD_strategy);
  772. return cParams;
  773. }
  774. /** ZSTD_cycleLog() :
  775. * condition for correct operation : hashLog > 1 */
  776. static U32 ZSTD_cycleLog(U32 hashLog, ZSTD_strategy strat)
  777. {
  778. U32 const btScale = ((U32)strat >= (U32)ZSTD_btlazy2);
  779. return hashLog - btScale;
  780. }
  781. /** ZSTD_adjustCParams_internal() :
  782. optimize `cPar` for a given input (`srcSize` and `dictSize`).
  783. mostly downsizing to reduce memory consumption and initialization latency.
  784. Both `srcSize` and `dictSize` are optional (use 0 if unknown).
  785. Note : cPar is assumed validated. Use ZSTD_checkCParams() to ensure this condition. */
  786. static ZSTD_compressionParameters
  787. ZSTD_adjustCParams_internal(ZSTD_compressionParameters cPar,
  788. unsigned long long srcSize,
  789. size_t dictSize)
  790. {
  791. static const U64 minSrcSize = 513; /* (1<<9) + 1 */
  792. static const U64 maxWindowResize = 1ULL << (ZSTD_WINDOWLOG_MAX-1);
  793. assert(ZSTD_checkCParams(cPar)==0);
  794. if (dictSize && (srcSize+1<2) /* srcSize unknown */ )
  795. srcSize = minSrcSize; /* presumed small when there is a dictionary */
  796. else if (srcSize == 0)
  797. srcSize = ZSTD_CONTENTSIZE_UNKNOWN; /* 0 == unknown : presumed large */
  798. /* resize windowLog if input is small enough, to use less memory */
  799. if ( (srcSize < maxWindowResize)
  800. && (dictSize < maxWindowResize) ) {
  801. U32 const tSize = (U32)(srcSize + dictSize);
  802. static U32 const hashSizeMin = 1 << ZSTD_HASHLOG_MIN;
  803. U32 const srcLog = (tSize < hashSizeMin) ? ZSTD_HASHLOG_MIN :
  804. ZSTD_highbit32(tSize-1) + 1;
  805. if (cPar.windowLog > srcLog) cPar.windowLog = srcLog;
  806. }
  807. if (cPar.hashLog > cPar.windowLog+1) cPar.hashLog = cPar.windowLog+1;
  808. { U32 const cycleLog = ZSTD_cycleLog(cPar.chainLog, cPar.strategy);
  809. if (cycleLog > cPar.windowLog)
  810. cPar.chainLog -= (cycleLog - cPar.windowLog);
  811. }
  812. if (cPar.windowLog < ZSTD_WINDOWLOG_ABSOLUTEMIN)
  813. cPar.windowLog = ZSTD_WINDOWLOG_ABSOLUTEMIN; /* required for frame header */
  814. return cPar;
  815. }
  816. ZSTD_compressionParameters
  817. ZSTD_adjustCParams(ZSTD_compressionParameters cPar,
  818. unsigned long long srcSize,
  819. size_t dictSize)
  820. {
  821. cPar = ZSTD_clampCParams(cPar);
  822. return ZSTD_adjustCParams_internal(cPar, srcSize, dictSize);
  823. }
  824. ZSTD_compressionParameters ZSTD_getCParamsFromCCtxParams(
  825. const ZSTD_CCtx_params* CCtxParams, U64 srcSizeHint, size_t dictSize)
  826. {
  827. ZSTD_compressionParameters cParams = ZSTD_getCParams(CCtxParams->compressionLevel, srcSizeHint, dictSize);
  828. if (CCtxParams->ldmParams.enableLdm) cParams.windowLog = ZSTD_LDM_DEFAULT_WINDOW_LOG;
  829. if (CCtxParams->cParams.windowLog) cParams.windowLog = CCtxParams->cParams.windowLog;
  830. if (CCtxParams->cParams.hashLog) cParams.hashLog = CCtxParams->cParams.hashLog;
  831. if (CCtxParams->cParams.chainLog) cParams.chainLog = CCtxParams->cParams.chainLog;
  832. if (CCtxParams->cParams.searchLog) cParams.searchLog = CCtxParams->cParams.searchLog;
  833. if (CCtxParams->cParams.minMatch) cParams.minMatch = CCtxParams->cParams.minMatch;
  834. if (CCtxParams->cParams.targetLength) cParams.targetLength = CCtxParams->cParams.targetLength;
  835. if (CCtxParams->cParams.strategy) cParams.strategy = CCtxParams->cParams.strategy;
  836. assert(!ZSTD_checkCParams(cParams));
  837. return ZSTD_adjustCParams_internal(cParams, srcSizeHint, dictSize);
  838. }
  839. static size_t
  840. ZSTD_sizeof_matchState(const ZSTD_compressionParameters* const cParams,
  841. const U32 forCCtx)
  842. {
  843. size_t const chainSize = (cParams->strategy == ZSTD_fast) ? 0 : ((size_t)1 << cParams->chainLog);
  844. size_t const hSize = ((size_t)1) << cParams->hashLog;
  845. U32 const hashLog3 = (forCCtx && cParams->minMatch==3) ? MIN(ZSTD_HASHLOG3_MAX, cParams->windowLog) : 0;
  846. size_t const h3Size = ((size_t)1) << hashLog3;
  847. size_t const tableSpace = (chainSize + hSize + h3Size) * sizeof(U32);
  848. size_t const optPotentialSpace = ((MaxML+1) + (MaxLL+1) + (MaxOff+1) + (1<<Litbits)) * sizeof(U32)
  849. + (ZSTD_OPT_NUM+1) * (sizeof(ZSTD_match_t)+sizeof(ZSTD_optimal_t));
  850. size_t const optSpace = (forCCtx && (cParams->strategy >= ZSTD_btopt))
  851. ? optPotentialSpace
  852. : 0;
  853. DEBUGLOG(4, "chainSize: %u - hSize: %u - h3Size: %u",
  854. (U32)chainSize, (U32)hSize, (U32)h3Size);
  855. return tableSpace + optSpace;
  856. }
  857. size_t ZSTD_estimateCCtxSize_usingCCtxParams(const ZSTD_CCtx_params* params)
  858. {
  859. /* Estimate CCtx size is supported for single-threaded compression only. */
  860. if (params->nbWorkers > 0) { return ERROR(GENERIC); }
  861. { ZSTD_compressionParameters const cParams =
  862. ZSTD_getCParamsFromCCtxParams(params, 0, 0);
  863. size_t const blockSize = MIN(ZSTD_BLOCKSIZE_MAX, (size_t)1 << cParams.windowLog);
  864. U32 const divider = (cParams.minMatch==3) ? 3 : 4;
  865. size_t const maxNbSeq = blockSize / divider;
  866. size_t const tokenSpace = WILDCOPY_OVERLENGTH + blockSize + 11*maxNbSeq;
  867. size_t const entropySpace = HUF_WORKSPACE_SIZE;
  868. size_t const blockStateSpace = 2 * sizeof(ZSTD_compressedBlockState_t);
  869. size_t const matchStateSize = ZSTD_sizeof_matchState(&cParams, /* forCCtx */ 1);
  870. size_t const ldmSpace = ZSTD_ldm_getTableSize(params->ldmParams);
  871. size_t const ldmSeqSpace = ZSTD_ldm_getMaxNbSeq(params->ldmParams, blockSize) * sizeof(rawSeq);
  872. size_t const neededSpace = entropySpace + blockStateSpace + tokenSpace +
  873. matchStateSize + ldmSpace + ldmSeqSpace;
  874. DEBUGLOG(5, "sizeof(ZSTD_CCtx) : %u", (U32)sizeof(ZSTD_CCtx));
  875. DEBUGLOG(5, "estimate workSpace : %u", (U32)neededSpace);
  876. return sizeof(ZSTD_CCtx) + neededSpace;
  877. }
  878. }
  879. size_t ZSTD_estimateCCtxSize_usingCParams(ZSTD_compressionParameters cParams)
  880. {
  881. ZSTD_CCtx_params const params = ZSTD_makeCCtxParamsFromCParams(cParams);
  882. return ZSTD_estimateCCtxSize_usingCCtxParams(&params);
  883. }
  884. static size_t ZSTD_estimateCCtxSize_internal(int compressionLevel)
  885. {
  886. ZSTD_compressionParameters const cParams = ZSTD_getCParams(compressionLevel, 0, 0);
  887. return ZSTD_estimateCCtxSize_usingCParams(cParams);
  888. }
  889. size_t ZSTD_estimateCCtxSize(int compressionLevel)
  890. {
  891. int level;
  892. size_t memBudget = 0;
  893. for (level=MIN(compressionLevel, 1); level<=compressionLevel; level++) {
  894. size_t const newMB = ZSTD_estimateCCtxSize_internal(level);
  895. if (newMB > memBudget) memBudget = newMB;
  896. }
  897. return memBudget;
  898. }
  899. size_t ZSTD_estimateCStreamSize_usingCCtxParams(const ZSTD_CCtx_params* params)
  900. {
  901. if (params->nbWorkers > 0) { return ERROR(GENERIC); }
  902. { size_t const CCtxSize = ZSTD_estimateCCtxSize_usingCCtxParams(params);
  903. size_t const blockSize = MIN(ZSTD_BLOCKSIZE_MAX, (size_t)1 << params->cParams.windowLog);
  904. size_t const inBuffSize = ((size_t)1 << params->cParams.windowLog) + blockSize;
  905. size_t const outBuffSize = ZSTD_compressBound(blockSize) + 1;
  906. size_t const streamingSize = inBuffSize + outBuffSize;
  907. return CCtxSize + streamingSize;
  908. }
  909. }
  910. size_t ZSTD_estimateCStreamSize_usingCParams(ZSTD_compressionParameters cParams)
  911. {
  912. ZSTD_CCtx_params const params = ZSTD_makeCCtxParamsFromCParams(cParams);
  913. return ZSTD_estimateCStreamSize_usingCCtxParams(&params);
  914. }
  915. static size_t ZSTD_estimateCStreamSize_internal(int compressionLevel)
  916. {
  917. ZSTD_compressionParameters const cParams = ZSTD_getCParams(compressionLevel, 0, 0);
  918. return ZSTD_estimateCStreamSize_usingCParams(cParams);
  919. }
  920. size_t ZSTD_estimateCStreamSize(int compressionLevel)
  921. {
  922. int level;
  923. size_t memBudget = 0;
  924. for (level=MIN(compressionLevel, 1); level<=compressionLevel; level++) {
  925. size_t const newMB = ZSTD_estimateCStreamSize_internal(level);
  926. if (newMB > memBudget) memBudget = newMB;
  927. }
  928. return memBudget;
  929. }
  930. /* ZSTD_getFrameProgression():
  931. * tells how much data has been consumed (input) and produced (output) for current frame.
  932. * able to count progression inside worker threads (non-blocking mode).
  933. */
  934. ZSTD_frameProgression ZSTD_getFrameProgression(const ZSTD_CCtx* cctx)
  935. {
  936. #ifdef ZSTD_MULTITHREAD
  937. if (cctx->appliedParams.nbWorkers > 0) {
  938. return ZSTDMT_getFrameProgression(cctx->mtctx);
  939. }
  940. #endif
  941. { ZSTD_frameProgression fp;
  942. size_t const buffered = (cctx->inBuff == NULL) ? 0 :
  943. cctx->inBuffPos - cctx->inToCompress;
  944. if (buffered) assert(cctx->inBuffPos >= cctx->inToCompress);
  945. assert(buffered <= ZSTD_BLOCKSIZE_MAX);
  946. fp.ingested = cctx->consumedSrcSize + buffered;
  947. fp.consumed = cctx->consumedSrcSize;
  948. fp.produced = cctx->producedCSize;
  949. fp.flushed = cctx->producedCSize; /* simplified; some data might still be left within streaming output buffer */
  950. fp.currentJobID = 0;
  951. fp.nbActiveWorkers = 0;
  952. return fp;
  953. } }
  954. /*! ZSTD_toFlushNow()
  955. * Only useful for multithreading scenarios currently (nbWorkers >= 1).
  956. */
  957. size_t ZSTD_toFlushNow(ZSTD_CCtx* cctx)
  958. {
  959. #ifdef ZSTD_MULTITHREAD
  960. if (cctx->appliedParams.nbWorkers > 0) {
  961. return ZSTDMT_toFlushNow(cctx->mtctx);
  962. }
  963. #endif
  964. (void)cctx;
  965. 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 */
  966. }
  967. static U32 ZSTD_equivalentCParams(ZSTD_compressionParameters cParams1,
  968. ZSTD_compressionParameters cParams2)
  969. {
  970. return (cParams1.hashLog == cParams2.hashLog)
  971. & (cParams1.chainLog == cParams2.chainLog)
  972. & (cParams1.strategy == cParams2.strategy) /* opt parser space */
  973. & ((cParams1.minMatch==3) == (cParams2.minMatch==3)); /* hashlog3 space */
  974. }
  975. static void ZSTD_assertEqualCParams(ZSTD_compressionParameters cParams1,
  976. ZSTD_compressionParameters cParams2)
  977. {
  978. (void)cParams1;
  979. (void)cParams2;
  980. assert(cParams1.windowLog == cParams2.windowLog);
  981. assert(cParams1.chainLog == cParams2.chainLog);
  982. assert(cParams1.hashLog == cParams2.hashLog);
  983. assert(cParams1.searchLog == cParams2.searchLog);
  984. assert(cParams1.minMatch == cParams2.minMatch);
  985. assert(cParams1.targetLength == cParams2.targetLength);
  986. assert(cParams1.strategy == cParams2.strategy);
  987. }
  988. /** The parameters are equivalent if ldm is not enabled in both sets or
  989. * all the parameters are equivalent. */
  990. static U32 ZSTD_equivalentLdmParams(ldmParams_t ldmParams1,
  991. ldmParams_t ldmParams2)
  992. {
  993. return (!ldmParams1.enableLdm && !ldmParams2.enableLdm) ||
  994. (ldmParams1.enableLdm == ldmParams2.enableLdm &&
  995. ldmParams1.hashLog == ldmParams2.hashLog &&
  996. ldmParams1.bucketSizeLog == ldmParams2.bucketSizeLog &&
  997. ldmParams1.minMatchLength == ldmParams2.minMatchLength &&
  998. ldmParams1.hashRateLog == ldmParams2.hashRateLog);
  999. }
  1000. typedef enum { ZSTDb_not_buffered, ZSTDb_buffered } ZSTD_buffered_policy_e;
  1001. /* ZSTD_sufficientBuff() :
  1002. * check internal buffers exist for streaming if buffPol == ZSTDb_buffered .
  1003. * Note : they are assumed to be correctly sized if ZSTD_equivalentCParams()==1 */
  1004. static U32 ZSTD_sufficientBuff(size_t bufferSize1, size_t maxNbSeq1,
  1005. size_t maxNbLit1,
  1006. ZSTD_buffered_policy_e buffPol2,
  1007. ZSTD_compressionParameters cParams2,
  1008. U64 pledgedSrcSize)
  1009. {
  1010. size_t const windowSize2 = MAX(1, (size_t)MIN(((U64)1 << cParams2.windowLog), pledgedSrcSize));
  1011. size_t const blockSize2 = MIN(ZSTD_BLOCKSIZE_MAX, windowSize2);
  1012. size_t const maxNbSeq2 = blockSize2 / ((cParams2.minMatch == 3) ? 3 : 4);
  1013. size_t const maxNbLit2 = blockSize2;
  1014. size_t const neededBufferSize2 = (buffPol2==ZSTDb_buffered) ? windowSize2 + blockSize2 : 0;
  1015. DEBUGLOG(4, "ZSTD_sufficientBuff: is neededBufferSize2=%u <= bufferSize1=%u",
  1016. (U32)neededBufferSize2, (U32)bufferSize1);
  1017. DEBUGLOG(4, "ZSTD_sufficientBuff: is maxNbSeq2=%u <= maxNbSeq1=%u",
  1018. (U32)maxNbSeq2, (U32)maxNbSeq1);
  1019. DEBUGLOG(4, "ZSTD_sufficientBuff: is maxNbLit2=%u <= maxNbLit1=%u",
  1020. (U32)maxNbLit2, (U32)maxNbLit1);
  1021. return (maxNbLit2 <= maxNbLit1)
  1022. & (maxNbSeq2 <= maxNbSeq1)
  1023. & (neededBufferSize2 <= bufferSize1);
  1024. }
  1025. /** Equivalence for resetCCtx purposes */
  1026. static U32 ZSTD_equivalentParams(ZSTD_CCtx_params params1,
  1027. ZSTD_CCtx_params params2,
  1028. size_t buffSize1,
  1029. size_t maxNbSeq1, size_t maxNbLit1,
  1030. ZSTD_buffered_policy_e buffPol2,
  1031. U64 pledgedSrcSize)
  1032. {
  1033. DEBUGLOG(4, "ZSTD_equivalentParams: pledgedSrcSize=%u", (U32)pledgedSrcSize);
  1034. if (!ZSTD_equivalentCParams(params1.cParams, params2.cParams)) {
  1035. DEBUGLOG(4, "ZSTD_equivalentCParams() == 0");
  1036. return 0;
  1037. }
  1038. if (!ZSTD_equivalentLdmParams(params1.ldmParams, params2.ldmParams)) {
  1039. DEBUGLOG(4, "ZSTD_equivalentLdmParams() == 0");
  1040. return 0;
  1041. }
  1042. if (!ZSTD_sufficientBuff(buffSize1, maxNbSeq1, maxNbLit1, buffPol2,
  1043. params2.cParams, pledgedSrcSize)) {
  1044. DEBUGLOG(4, "ZSTD_sufficientBuff() == 0");
  1045. return 0;
  1046. }
  1047. return 1;
  1048. }
  1049. static void ZSTD_reset_compressedBlockState(ZSTD_compressedBlockState_t* bs)
  1050. {
  1051. int i;
  1052. for (i = 0; i < ZSTD_REP_NUM; ++i)
  1053. bs->rep[i] = repStartValue[i];
  1054. bs->entropy.huf.repeatMode = HUF_repeat_none;
  1055. bs->entropy.fse.offcode_repeatMode = FSE_repeat_none;
  1056. bs->entropy.fse.matchlength_repeatMode = FSE_repeat_none;
  1057. bs->entropy.fse.litlength_repeatMode = FSE_repeat_none;
  1058. }
  1059. /*! ZSTD_invalidateMatchState()
  1060. * Invalidate all the matches in the match finder tables.
  1061. * Requires nextSrc and base to be set (can be NULL).
  1062. */
  1063. static void ZSTD_invalidateMatchState(ZSTD_matchState_t* ms)
  1064. {
  1065. ZSTD_window_clear(&ms->window);
  1066. ms->nextToUpdate = ms->window.dictLimit;
  1067. ms->nextToUpdate3 = ms->window.dictLimit;
  1068. ms->loadedDictEnd = 0;
  1069. ms->opt.litLengthSum = 0; /* force reset of btopt stats */
  1070. ms->dictMatchState = NULL;
  1071. }
  1072. /*! ZSTD_continueCCtx() :
  1073. * reuse CCtx without reset (note : requires no dictionary) */
  1074. static size_t ZSTD_continueCCtx(ZSTD_CCtx* cctx, ZSTD_CCtx_params params, U64 pledgedSrcSize)
  1075. {
  1076. size_t const windowSize = MAX(1, (size_t)MIN(((U64)1 << params.cParams.windowLog), pledgedSrcSize));
  1077. size_t const blockSize = MIN(ZSTD_BLOCKSIZE_MAX, windowSize);
  1078. DEBUGLOG(4, "ZSTD_continueCCtx: re-use context in place");
  1079. cctx->blockSize = blockSize; /* previous block size could be different even for same windowLog, due to pledgedSrcSize */
  1080. cctx->appliedParams = params;
  1081. cctx->blockState.matchState.cParams = params.cParams;
  1082. cctx->pledgedSrcSizePlusOne = pledgedSrcSize+1;
  1083. cctx->consumedSrcSize = 0;
  1084. cctx->producedCSize = 0;
  1085. if (pledgedSrcSize == ZSTD_CONTENTSIZE_UNKNOWN)
  1086. cctx->appliedParams.fParams.contentSizeFlag = 0;
  1087. DEBUGLOG(4, "pledged content size : %u ; flag : %u",
  1088. (U32)pledgedSrcSize, cctx->appliedParams.fParams.contentSizeFlag);
  1089. cctx->stage = ZSTDcs_init;
  1090. cctx->dictID = 0;
  1091. if (params.ldmParams.enableLdm)
  1092. ZSTD_window_clear(&cctx->ldmState.window);
  1093. ZSTD_referenceExternalSequences(cctx, NULL, 0);
  1094. ZSTD_invalidateMatchState(&cctx->blockState.matchState);
  1095. ZSTD_reset_compressedBlockState(cctx->blockState.prevCBlock);
  1096. XXH64_reset(&cctx->xxhState, 0);
  1097. return 0;
  1098. }
  1099. typedef enum { ZSTDcrp_continue, ZSTDcrp_noMemset } ZSTD_compResetPolicy_e;
  1100. static void*
  1101. ZSTD_reset_matchState(ZSTD_matchState_t* ms,
  1102. void* ptr,
  1103. const ZSTD_compressionParameters* cParams,
  1104. ZSTD_compResetPolicy_e const crp, U32 const forCCtx)
  1105. {
  1106. size_t const chainSize = (cParams->strategy == ZSTD_fast) ? 0 : ((size_t)1 << cParams->chainLog);
  1107. size_t const hSize = ((size_t)1) << cParams->hashLog;
  1108. U32 const hashLog3 = (forCCtx && cParams->minMatch==3) ? MIN(ZSTD_HASHLOG3_MAX, cParams->windowLog) : 0;
  1109. size_t const h3Size = ((size_t)1) << hashLog3;
  1110. size_t const tableSpace = (chainSize + hSize + h3Size) * sizeof(U32);
  1111. assert(((size_t)ptr & 3) == 0);
  1112. ms->hashLog3 = hashLog3;
  1113. memset(&ms->window, 0, sizeof(ms->window));
  1114. ms->window.dictLimit = 1; /* start from 1, so that 1st position is valid */
  1115. ms->window.lowLimit = 1; /* it ensures first and later CCtx usages compress the same */
  1116. ms->window.nextSrc = ms->window.base + 1; /* see issue #1241 */
  1117. ZSTD_invalidateMatchState(ms);
  1118. /* opt parser space */
  1119. if (forCCtx && (cParams->strategy >= ZSTD_btopt)) {
  1120. DEBUGLOG(4, "reserving optimal parser space");
  1121. ms->opt.litFreq = (unsigned*)ptr;
  1122. ms->opt.litLengthFreq = ms->opt.litFreq + (1<<Litbits);
  1123. ms->opt.matchLengthFreq = ms->opt.litLengthFreq + (MaxLL+1);
  1124. ms->opt.offCodeFreq = ms->opt.matchLengthFreq + (MaxML+1);
  1125. ptr = ms->opt.offCodeFreq + (MaxOff+1);
  1126. ms->opt.matchTable = (ZSTD_match_t*)ptr;
  1127. ptr = ms->opt.matchTable + ZSTD_OPT_NUM+1;
  1128. ms->opt.priceTable = (ZSTD_optimal_t*)ptr;
  1129. ptr = ms->opt.priceTable + ZSTD_OPT_NUM+1;
  1130. }
  1131. /* table Space */
  1132. DEBUGLOG(4, "reset table : %u", crp!=ZSTDcrp_noMemset);
  1133. assert(((size_t)ptr & 3) == 0); /* ensure ptr is properly aligned */
  1134. if (crp!=ZSTDcrp_noMemset) memset(ptr, 0, tableSpace); /* reset tables only */
  1135. ms->hashTable = (U32*)(ptr);
  1136. ms->chainTable = ms->hashTable + hSize;
  1137. ms->hashTable3 = ms->chainTable + chainSize;
  1138. ptr = ms->hashTable3 + h3Size;
  1139. ms->cParams = *cParams;
  1140. assert(((size_t)ptr & 3) == 0);
  1141. return ptr;
  1142. }
  1143. #define ZSTD_WORKSPACETOOLARGE_FACTOR 3 /* define "workspace is too large" as this number of times larger than needed */
  1144. #define ZSTD_WORKSPACETOOLARGE_MAXDURATION 128 /* when workspace is continuously too large
  1145. * during at least this number of times,
  1146. * context's memory usage is considered wasteful,
  1147. * because it's sized to handle a worst case scenario which rarely happens.
  1148. * In which case, resize it down to free some memory */
  1149. /*! ZSTD_resetCCtx_internal() :
  1150. note : `params` are assumed fully validated at this stage */
  1151. static size_t ZSTD_resetCCtx_internal(ZSTD_CCtx* zc,
  1152. ZSTD_CCtx_params params,
  1153. U64 pledgedSrcSize,
  1154. ZSTD_compResetPolicy_e const crp,
  1155. ZSTD_buffered_policy_e const zbuff)
  1156. {
  1157. DEBUGLOG(4, "ZSTD_resetCCtx_internal: pledgedSrcSize=%u, wlog=%u",
  1158. (U32)pledgedSrcSize, params.cParams.windowLog);
  1159. assert(!ZSTD_isError(ZSTD_checkCParams(params.cParams)));
  1160. if (crp == ZSTDcrp_continue) {
  1161. if (ZSTD_equivalentParams(zc->appliedParams, params,
  1162. zc->inBuffSize,
  1163. zc->seqStore.maxNbSeq, zc->seqStore.maxNbLit,
  1164. zbuff, pledgedSrcSize)) {
  1165. DEBUGLOG(4, "ZSTD_equivalentParams()==1 -> continue mode (wLog1=%u, blockSize1=%zu)",
  1166. zc->appliedParams.cParams.windowLog, zc->blockSize);
  1167. zc->workSpaceOversizedDuration += (zc->workSpaceOversizedDuration > 0); /* if it was too large, it still is */
  1168. if (zc->workSpaceOversizedDuration <= ZSTD_WORKSPACETOOLARGE_MAXDURATION)
  1169. return ZSTD_continueCCtx(zc, params, pledgedSrcSize);
  1170. } }
  1171. DEBUGLOG(4, "ZSTD_equivalentParams()==0 -> reset CCtx");
  1172. if (params.ldmParams.enableLdm) {
  1173. /* Adjust long distance matching parameters */
  1174. ZSTD_ldm_adjustParameters(&params.ldmParams, &params.cParams);
  1175. assert(params.ldmParams.hashLog >= params.ldmParams.bucketSizeLog);
  1176. assert(params.ldmParams.hashRateLog < 32);
  1177. zc->ldmState.hashPower = ZSTD_rollingHash_primePower(params.ldmParams.minMatchLength);
  1178. }
  1179. { size_t const windowSize = MAX(1, (size_t)MIN(((U64)1 << params.cParams.windowLog), pledgedSrcSize));
  1180. size_t const blockSize = MIN(ZSTD_BLOCKSIZE_MAX, windowSize);
  1181. U32 const divider = (params.cParams.minMatch==3) ? 3 : 4;
  1182. size_t const maxNbSeq = blockSize / divider;
  1183. size_t const tokenSpace = WILDCOPY_OVERLENGTH + blockSize + 11*maxNbSeq;
  1184. size_t const buffOutSize = (zbuff==ZSTDb_buffered) ? ZSTD_compressBound(blockSize)+1 : 0;
  1185. size_t const buffInSize = (zbuff==ZSTDb_buffered) ? windowSize + blockSize : 0;
  1186. size_t const matchStateSize = ZSTD_sizeof_matchState(&params.cParams, /* forCCtx */ 1);
  1187. size_t const maxNbLdmSeq = ZSTD_ldm_getMaxNbSeq(params.ldmParams, blockSize);
  1188. void* ptr; /* used to partition workSpace */
  1189. /* Check if workSpace is large enough, alloc a new one if needed */
  1190. { size_t const entropySpace = HUF_WORKSPACE_SIZE;
  1191. size_t const blockStateSpace = 2 * sizeof(ZSTD_compressedBlockState_t);
  1192. size_t const bufferSpace = buffInSize + buffOutSize;
  1193. size_t const ldmSpace = ZSTD_ldm_getTableSize(params.ldmParams);
  1194. size_t const ldmSeqSpace = maxNbLdmSeq * sizeof(rawSeq);
  1195. size_t const neededSpace = entropySpace + blockStateSpace + ldmSpace +
  1196. ldmSeqSpace + matchStateSize + tokenSpace +
  1197. bufferSpace;
  1198. int const workSpaceTooSmall = zc->workSpaceSize < neededSpace;
  1199. int const workSpaceTooLarge = zc->workSpaceSize > ZSTD_WORKSPACETOOLARGE_FACTOR * neededSpace;
  1200. int const workSpaceWasteful = workSpaceTooLarge && (zc->workSpaceOversizedDuration > ZSTD_WORKSPACETOOLARGE_MAXDURATION);
  1201. zc->workSpaceOversizedDuration = workSpaceTooLarge ? zc->workSpaceOversizedDuration+1 : 0;
  1202. DEBUGLOG(4, "Need %zuKB workspace, including %zuKB for match state, and %zuKB for buffers",
  1203. neededSpace>>10, matchStateSize>>10, bufferSpace>>10);
  1204. DEBUGLOG(4, "windowSize: %zu - blockSize: %zu", windowSize, blockSize);
  1205. if (workSpaceTooSmall || workSpaceWasteful) {
  1206. DEBUGLOG(4, "Need to resize workSpaceSize from %zuKB to %zuKB",
  1207. zc->workSpaceSize >> 10,
  1208. neededSpace >> 10);
  1209. /* static cctx : no resize, error out */
  1210. if (zc->staticSize) return ERROR(memory_allocation);
  1211. zc->workSpaceSize = 0;
  1212. ZSTD_free(zc->workSpace, zc->customMem);
  1213. zc->workSpace = ZSTD_malloc(neededSpace, zc->customMem);
  1214. if (zc->workSpace == NULL) return ERROR(memory_allocation);
  1215. zc->workSpaceSize = neededSpace;
  1216. zc->workSpaceOversizedDuration = 0;
  1217. /* Statically sized space.
  1218. * entropyWorkspace never moves,
  1219. * though prev/next block swap places */
  1220. assert(((size_t)zc->workSpace & 3) == 0); /* ensure correct alignment */
  1221. assert(zc->workSpaceSize >= 2 * sizeof(ZSTD_compressedBlockState_t));
  1222. zc->blockState.prevCBlock = (ZSTD_compressedBlockState_t*)zc->workSpace;
  1223. zc->blockState.nextCBlock = zc->blockState.prevCBlock + 1;
  1224. ptr = zc->blockState.nextCBlock + 1;
  1225. zc->entropyWorkspace = (U32*)ptr;
  1226. } }
  1227. /* init params */
  1228. zc->appliedParams = params;
  1229. zc->blockState.matchState.cParams = params.cParams;
  1230. zc->pledgedSrcSizePlusOne = pledgedSrcSize+1;
  1231. zc->consumedSrcSize = 0;
  1232. zc->producedCSize = 0;
  1233. if (pledgedSrcSize == ZSTD_CONTENTSIZE_UNKNOWN)
  1234. zc->appliedParams.fParams.contentSizeFlag = 0;
  1235. DEBUGLOG(4, "pledged content size : %u ; flag : %u",
  1236. (unsigned)pledgedSrcSize, zc->appliedParams.fParams.contentSizeFlag);
  1237. zc->blockSize = blockSize;
  1238. XXH64_reset(&zc->xxhState, 0);
  1239. zc->stage = ZSTDcs_init;
  1240. zc->dictID = 0;
  1241. ZSTD_reset_compressedBlockState(zc->blockState.prevCBlock);
  1242. ptr = zc->entropyWorkspace + HUF_WORKSPACE_SIZE_U32;
  1243. /* ldm hash table */
  1244. /* initialize bucketOffsets table later for pointer alignment */
  1245. if (params.ldmParams.enableLdm) {
  1246. size_t const ldmHSize = ((size_t)1) << params.ldmParams.hashLog;
  1247. memset(ptr, 0, ldmHSize * sizeof(ldmEntry_t));
  1248. assert(((size_t)ptr & 3) == 0); /* ensure ptr is properly aligned */
  1249. zc->ldmState.hashTable = (ldmEntry_t*)ptr;
  1250. ptr = zc->ldmState.hashTable + ldmHSize;
  1251. zc->ldmSequences = (rawSeq*)ptr;
  1252. ptr = zc->ldmSequences + maxNbLdmSeq;
  1253. zc->maxNbLdmSequences = maxNbLdmSeq;
  1254. memset(&zc->ldmState.window, 0, sizeof(zc->ldmState.window));
  1255. }
  1256. assert(((size_t)ptr & 3) == 0); /* ensure ptr is properly aligned */
  1257. ptr = ZSTD_reset_matchState(&zc->blockState.matchState, ptr, &params.cParams, crp, /* forCCtx */ 1);
  1258. /* sequences storage */
  1259. zc->seqStore.maxNbSeq = maxNbSeq;
  1260. zc->seqStore.sequencesStart = (seqDef*)ptr;
  1261. ptr = zc->seqStore.sequencesStart + maxNbSeq;
  1262. zc->seqStore.llCode = (BYTE*) ptr;
  1263. zc->seqStore.mlCode = zc->seqStore.llCode + maxNbSeq;
  1264. zc->seqStore.ofCode = zc->seqStore.mlCode + maxNbSeq;
  1265. zc->seqStore.litStart = zc->seqStore.ofCode + maxNbSeq;
  1266. /* ZSTD_wildcopy() is used to copy into the literals buffer,
  1267. * so we have to oversize the buffer by WILDCOPY_OVERLENGTH bytes.
  1268. */
  1269. zc->seqStore.maxNbLit = blockSize;
  1270. ptr = zc->seqStore.litStart + blockSize + WILDCOPY_OVERLENGTH;
  1271. /* ldm bucketOffsets table */
  1272. if (params.ldmParams.enableLdm) {
  1273. size_t const ldmBucketSize =
  1274. ((size_t)1) << (params.ldmParams.hashLog -
  1275. params.ldmParams.bucketSizeLog);
  1276. memset(ptr, 0, ldmBucketSize);
  1277. zc->ldmState.bucketOffsets = (BYTE*)ptr;
  1278. ptr = zc->ldmState.bucketOffsets + ldmBucketSize;
  1279. ZSTD_window_clear(&zc->ldmState.window);
  1280. }
  1281. ZSTD_referenceExternalSequences(zc, NULL, 0);
  1282. /* buffers */
  1283. zc->inBuffSize = buffInSize;
  1284. zc->inBuff = (char*)ptr;
  1285. zc->outBuffSize = buffOutSize;
  1286. zc->outBuff = zc->inBuff + buffInSize;
  1287. return 0;
  1288. }
  1289. }
  1290. /* ZSTD_invalidateRepCodes() :
  1291. * ensures next compression will not use repcodes from previous block.
  1292. * Note : only works with regular variant;
  1293. * do not use with extDict variant ! */
  1294. void ZSTD_invalidateRepCodes(ZSTD_CCtx* cctx) {
  1295. int i;
  1296. for (i=0; i<ZSTD_REP_NUM; i++) cctx->blockState.prevCBlock->rep[i] = 0;
  1297. assert(!ZSTD_window_hasExtDict(cctx->blockState.matchState.window));
  1298. }
  1299. /* These are the approximate sizes for each strategy past which copying the
  1300. * dictionary tables into the working context is faster than using them
  1301. * in-place.
  1302. */
  1303. static const size_t attachDictSizeCutoffs[ZSTD_STRATEGY_MAX+1] = {
  1304. 8 KB, /* unused */
  1305. 8 KB, /* ZSTD_fast */
  1306. 16 KB, /* ZSTD_dfast */
  1307. 32 KB, /* ZSTD_greedy */
  1308. 32 KB, /* ZSTD_lazy */
  1309. 32 KB, /* ZSTD_lazy2 */
  1310. 32 KB, /* ZSTD_btlazy2 */
  1311. 32 KB, /* ZSTD_btopt */
  1312. 8 KB, /* ZSTD_btultra */
  1313. 8 KB /* ZSTD_btultra2 */
  1314. };
  1315. static int ZSTD_shouldAttachDict(const ZSTD_CDict* cdict,
  1316. ZSTD_CCtx_params params,
  1317. U64 pledgedSrcSize)
  1318. {
  1319. size_t cutoff = attachDictSizeCutoffs[cdict->matchState.cParams.strategy];
  1320. return ( pledgedSrcSize <= cutoff
  1321. || pledgedSrcSize == ZSTD_CONTENTSIZE_UNKNOWN
  1322. || params.attachDictPref == ZSTD_dictForceAttach )
  1323. && params.attachDictPref != ZSTD_dictForceCopy
  1324. && !params.forceWindow; /* dictMatchState isn't correctly
  1325. * handled in _enforceMaxDist */
  1326. }
  1327. static size_t ZSTD_resetCCtx_byAttachingCDict(
  1328. ZSTD_CCtx* cctx,
  1329. const ZSTD_CDict* cdict,
  1330. ZSTD_CCtx_params params,
  1331. U64 pledgedSrcSize,
  1332. ZSTD_buffered_policy_e zbuff)
  1333. {
  1334. {
  1335. const ZSTD_compressionParameters *cdict_cParams = &cdict->matchState.cParams;
  1336. unsigned const windowLog = params.cParams.windowLog;
  1337. assert(windowLog != 0);
  1338. /* Resize working context table params for input only, since the dict
  1339. * has its own tables. */
  1340. params.cParams = ZSTD_adjustCParams_internal(*cdict_cParams, pledgedSrcSize, 0);
  1341. params.cParams.windowLog = windowLog;
  1342. ZSTD_resetCCtx_internal(cctx, params, pledgedSrcSize,
  1343. ZSTDcrp_continue, zbuff);
  1344. assert(cctx->appliedParams.cParams.strategy == cdict_cParams->strategy);
  1345. }
  1346. {
  1347. const U32 cdictEnd = (U32)( cdict->matchState.window.nextSrc
  1348. - cdict->matchState.window.base);
  1349. const U32 cdictLen = cdictEnd - cdict->matchState.window.dictLimit;
  1350. if (cdictLen == 0) {
  1351. /* don't even attach dictionaries with no contents */
  1352. DEBUGLOG(4, "skipping attaching empty dictionary");
  1353. } else {
  1354. DEBUGLOG(4, "attaching dictionary into context");
  1355. cctx->blockState.matchState.dictMatchState = &cdict->matchState;
  1356. /* prep working match state so dict matches never have negative indices
  1357. * when they are translated to the working context's index space. */
  1358. if (cctx->blockState.matchState.window.dictLimit < cdictEnd) {
  1359. cctx->blockState.matchState.window.nextSrc =
  1360. cctx->blockState.matchState.window.base + cdictEnd;
  1361. ZSTD_window_clear(&cctx->blockState.matchState.window);
  1362. }
  1363. cctx->blockState.matchState.loadedDictEnd = cctx->blockState.matchState.window.dictLimit;
  1364. }
  1365. }
  1366. cctx->dictID = cdict->dictID;
  1367. /* copy block state */
  1368. memcpy(cctx->blockState.prevCBlock, &cdict->cBlockState, sizeof(cdict->cBlockState));
  1369. return 0;
  1370. }
  1371. static size_t ZSTD_resetCCtx_byCopyingCDict(ZSTD_CCtx* cctx,
  1372. const ZSTD_CDict* cdict,
  1373. ZSTD_CCtx_params params,
  1374. U64 pledgedSrcSize,
  1375. ZSTD_buffered_policy_e zbuff)
  1376. {
  1377. const ZSTD_compressionParameters *cdict_cParams = &cdict->matchState.cParams;
  1378. DEBUGLOG(4, "copying dictionary into context");
  1379. { unsigned const windowLog = params.cParams.windowLog;
  1380. assert(windowLog != 0);
  1381. /* Copy only compression parameters related to tables. */
  1382. params.cParams = *cdict_cParams;
  1383. params.cParams.windowLog = windowLog;
  1384. ZSTD_resetCCtx_internal(cctx, params, pledgedSrcSize,
  1385. ZSTDcrp_noMemset, zbuff);
  1386. assert(cctx->appliedParams.cParams.strategy == cdict_cParams->strategy);
  1387. assert(cctx->appliedParams.cParams.hashLog == cdict_cParams->hashLog);
  1388. assert(cctx->appliedParams.cParams.chainLog == cdict_cParams->chainLog);
  1389. }
  1390. /* copy tables */
  1391. { size_t const chainSize = (cdict_cParams->strategy == ZSTD_fast) ? 0 : ((size_t)1 << cdict_cParams->chainLog);
  1392. size_t const hSize = (size_t)1 << cdict_cParams->hashLog;
  1393. size_t const tableSpace = (chainSize + hSize) * sizeof(U32);
  1394. assert((U32*)cctx->blockState.matchState.chainTable == (U32*)cctx->blockState.matchState.hashTable + hSize); /* chainTable must follow hashTable */
  1395. assert((U32*)cctx->blockState.matchState.hashTable3 == (U32*)cctx->blockState.matchState.chainTable + chainSize);
  1396. assert((U32*)cdict->matchState.chainTable == (U32*)cdict->matchState.hashTable + hSize); /* chainTable must follow hashTable */
  1397. assert((U32*)cdict->matchState.hashTable3 == (U32*)cdict->matchState.chainTable + chainSize);
  1398. memcpy(cctx->blockState.matchState.hashTable, cdict->matchState.hashTable, tableSpace); /* presumes all tables follow each other */
  1399. }
  1400. /* Zero the hashTable3, since the cdict never fills it */
  1401. { size_t const h3Size = (size_t)1 << cctx->blockState.matchState.hashLog3;
  1402. assert(cdict->matchState.hashLog3 == 0);
  1403. memset(cctx->blockState.matchState.hashTable3, 0, h3Size * sizeof(U32));
  1404. }
  1405. /* copy dictionary offsets */
  1406. { ZSTD_matchState_t const* srcMatchState = &cdict->matchState;
  1407. ZSTD_matchState_t* dstMatchState = &cctx->blockState.matchState;
  1408. dstMatchState->window = srcMatchState->window;
  1409. dstMatchState->nextToUpdate = srcMatchState->nextToUpdate;
  1410. dstMatchState->nextToUpdate3= srcMatchState->nextToUpdate3;
  1411. dstMatchState->loadedDictEnd= srcMatchState->loadedDictEnd;
  1412. }
  1413. cctx->dictID = cdict->dictID;
  1414. /* copy block state */
  1415. memcpy(cctx->blockState.prevCBlock, &cdict->cBlockState, sizeof(cdict->cBlockState));
  1416. return 0;
  1417. }
  1418. /* We have a choice between copying the dictionary context into the working
  1419. * context, or referencing the dictionary context from the working context
  1420. * in-place. We decide here which strategy to use. */
  1421. static size_t ZSTD_resetCCtx_usingCDict(ZSTD_CCtx* cctx,
  1422. const ZSTD_CDict* cdict,
  1423. ZSTD_CCtx_params params,
  1424. U64 pledgedSrcSize,
  1425. ZSTD_buffered_policy_e zbuff)
  1426. {
  1427. DEBUGLOG(4, "ZSTD_resetCCtx_usingCDict (pledgedSrcSize=%u)",
  1428. (unsigned)pledgedSrcSize);
  1429. if (ZSTD_shouldAttachDict(cdict, params, pledgedSrcSize)) {
  1430. return ZSTD_resetCCtx_byAttachingCDict(
  1431. cctx, cdict, params, pledgedSrcSize, zbuff);
  1432. } else {
  1433. return ZSTD_resetCCtx_byCopyingCDict(
  1434. cctx, cdict, params, pledgedSrcSize, zbuff);
  1435. }
  1436. }
  1437. /*! ZSTD_copyCCtx_internal() :
  1438. * Duplicate an existing context `srcCCtx` into another one `dstCCtx`.
  1439. * Only works during stage ZSTDcs_init (i.e. after creation, but before first call to ZSTD_compressContinue()).
  1440. * The "context", in this case, refers to the hash and chain tables,
  1441. * entropy tables, and dictionary references.
  1442. * `windowLog` value is enforced if != 0, otherwise value is copied from srcCCtx.
  1443. * @return : 0, or an error code */
  1444. static size_t ZSTD_copyCCtx_internal(ZSTD_CCtx* dstCCtx,
  1445. const ZSTD_CCtx* srcCCtx,
  1446. ZSTD_frameParameters fParams,
  1447. U64 pledgedSrcSize,
  1448. ZSTD_buffered_policy_e zbuff)
  1449. {
  1450. DEBUGLOG(5, "ZSTD_copyCCtx_internal");
  1451. if (srcCCtx->stage!=ZSTDcs_init) return ERROR(stage_wrong);
  1452. memcpy(&dstCCtx->customMem, &srcCCtx->customMem, sizeof(ZSTD_customMem));
  1453. { ZSTD_CCtx_params params = dstCCtx->requestedParams;
  1454. /* Copy only compression parameters related to tables. */
  1455. params.cParams = srcCCtx->appliedParams.cParams;
  1456. params.fParams = fParams;
  1457. ZSTD_resetCCtx_internal(dstCCtx, params, pledgedSrcSize,
  1458. ZSTDcrp_noMemset, zbuff);
  1459. assert(dstCCtx->appliedParams.cParams.windowLog == srcCCtx->appliedParams.cParams.windowLog);
  1460. assert(dstCCtx->appliedParams.cParams.strategy == srcCCtx->appliedParams.cParams.strategy);
  1461. assert(dstCCtx->appliedParams.cParams.hashLog == srcCCtx->appliedParams.cParams.hashLog);
  1462. assert(dstCCtx->appliedParams.cParams.chainLog == srcCCtx->appliedParams.cParams.chainLog);
  1463. assert(dstCCtx->blockState.matchState.hashLog3 == srcCCtx->blockState.matchState.hashLog3);
  1464. }
  1465. /* copy tables */
  1466. { size_t const chainSize = (srcCCtx->appliedParams.cParams.strategy == ZSTD_fast) ? 0 : ((size_t)1 << srcCCtx->appliedParams.cParams.chainLog);
  1467. size_t const hSize = (size_t)1 << srcCCtx->appliedParams.cParams.hashLog;
  1468. size_t const h3Size = (size_t)1 << srcCCtx->blockState.matchState.hashLog3;
  1469. size_t const tableSpace = (chainSize + hSize + h3Size) * sizeof(U32);
  1470. assert((U32*)dstCCtx->blockState.matchState.chainTable == (U32*)dstCCtx->blockState.matchState.hashTable + hSize); /* chainTable must follow hashTable */
  1471. assert((U32*)dstCCtx->blockState.matchState.hashTable3 == (U32*)dstCCtx->blockState.matchState.chainTable + chainSize);
  1472. memcpy(dstCCtx->blockState.matchState.hashTable, srcCCtx->blockState.matchState.hashTable, tableSpace); /* presumes all tables follow each other */
  1473. }
  1474. /* copy dictionary offsets */
  1475. {
  1476. const ZSTD_matchState_t* srcMatchState = &srcCCtx->blockState.matchState;
  1477. ZSTD_matchState_t* dstMatchState = &dstCCtx->blockState.matchState;
  1478. dstMatchState->window = srcMatchState->window;
  1479. dstMatchState->nextToUpdate = srcMatchState->nextToUpdate;
  1480. dstMatchState->nextToUpdate3= srcMatchState->nextToUpdate3;
  1481. dstMatchState->loadedDictEnd= srcMatchState->loadedDictEnd;
  1482. }
  1483. dstCCtx->dictID = srcCCtx->dictID;
  1484. /* copy block state */
  1485. memcpy(dstCCtx->blockState.prevCBlock, srcCCtx->blockState.prevCBlock, sizeof(*srcCCtx->blockState.prevCBlock));
  1486. return 0;
  1487. }
  1488. /*! ZSTD_copyCCtx() :
  1489. * Duplicate an existing context `srcCCtx` into another one `dstCCtx`.
  1490. * Only works during stage ZSTDcs_init (i.e. after creation, but before first call to ZSTD_compressContinue()).
  1491. * pledgedSrcSize==0 means "unknown".
  1492. * @return : 0, or an error code */
  1493. size_t ZSTD_copyCCtx(ZSTD_CCtx* dstCCtx, const ZSTD_CCtx* srcCCtx, unsigned long long pledgedSrcSize)
  1494. {
  1495. ZSTD_frameParameters fParams = { 1 /*content*/, 0 /*checksum*/, 0 /*noDictID*/ };
  1496. ZSTD_buffered_policy_e const zbuff = (ZSTD_buffered_policy_e)(srcCCtx->inBuffSize>0);
  1497. ZSTD_STATIC_ASSERT((U32)ZSTDb_buffered==1);
  1498. if (pledgedSrcSize==0) pledgedSrcSize = ZSTD_CONTENTSIZE_UNKNOWN;
  1499. fParams.contentSizeFlag = (pledgedSrcSize != ZSTD_CONTENTSIZE_UNKNOWN);
  1500. return ZSTD_copyCCtx_internal(dstCCtx, srcCCtx,
  1501. fParams, pledgedSrcSize,
  1502. zbuff);
  1503. }
  1504. #define ZSTD_ROWSIZE 16
  1505. /*! ZSTD_reduceTable() :
  1506. * reduce table indexes by `reducerValue`, or squash to zero.
  1507. * PreserveMark preserves "unsorted mark" for btlazy2 strategy.
  1508. * It must be set to a clear 0/1 value, to remove branch during inlining.
  1509. * Presume table size is a multiple of ZSTD_ROWSIZE
  1510. * to help auto-vectorization */
  1511. FORCE_INLINE_TEMPLATE void
  1512. ZSTD_reduceTable_internal (U32* const table, U32 const size, U32 const reducerValue, int const preserveMark)
  1513. {
  1514. int const nbRows = (int)size / ZSTD_ROWSIZE;
  1515. int cellNb = 0;
  1516. int rowNb;
  1517. assert((size & (ZSTD_ROWSIZE-1)) == 0); /* multiple of ZSTD_ROWSIZE */
  1518. assert(size < (1U<<31)); /* can be casted to int */
  1519. for (rowNb=0 ; rowNb < nbRows ; rowNb++) {
  1520. int column;
  1521. for (column=0; column<ZSTD_ROWSIZE; column++) {
  1522. if (preserveMark) {
  1523. U32 const adder = (table[cellNb] == ZSTD_DUBT_UNSORTED_MARK) ? reducerValue : 0;
  1524. table[cellNb] += adder;
  1525. }
  1526. if (table[cellNb] < reducerValue) table[cellNb] = 0;
  1527. else table[cellNb] -= reducerValue;
  1528. cellNb++;
  1529. } }
  1530. }
  1531. static void ZSTD_reduceTable(U32* const table, U32 const size, U32 const reducerValue)
  1532. {
  1533. ZSTD_reduceTable_internal(table, size, reducerValue, 0);
  1534. }
  1535. static void ZSTD_reduceTable_btlazy2(U32* const table, U32 const size, U32 const reducerValue)
  1536. {
  1537. ZSTD_reduceTable_internal(table, size, reducerValue, 1);
  1538. }
  1539. /*! ZSTD_reduceIndex() :
  1540. * rescale all indexes to avoid future overflow (indexes are U32) */
  1541. static void ZSTD_reduceIndex (ZSTD_CCtx* zc, const U32 reducerValue)
  1542. {
  1543. ZSTD_matchState_t* const ms = &zc->blockState.matchState;
  1544. { U32 const hSize = (U32)1 << zc->appliedParams.cParams.hashLog;
  1545. ZSTD_reduceTable(ms->hashTable, hSize, reducerValue);
  1546. }
  1547. if (zc->appliedParams.cParams.strategy != ZSTD_fast) {
  1548. U32 const chainSize = (U32)1 << zc->appliedParams.cParams.chainLog;
  1549. if (zc->appliedParams.cParams.strategy == ZSTD_btlazy2)
  1550. ZSTD_reduceTable_btlazy2(ms->chainTable, chainSize, reducerValue);
  1551. else
  1552. ZSTD_reduceTable(ms->chainTable, chainSize, reducerValue);
  1553. }
  1554. if (ms->hashLog3) {
  1555. U32 const h3Size = (U32)1 << ms->hashLog3;
  1556. ZSTD_reduceTable(ms->hashTable3, h3Size, reducerValue);
  1557. }
  1558. }
  1559. /*-*******************************************************
  1560. * Block entropic compression
  1561. *********************************************************/
  1562. /* See doc/zstd_compression_format.md for detailed format description */
  1563. static size_t ZSTD_noCompressBlock (void* dst, size_t dstCapacity, const void* src, size_t srcSize, U32 lastBlock)
  1564. {
  1565. U32 const cBlockHeader24 = lastBlock + (((U32)bt_raw)<<1) + (U32)(srcSize << 3);
  1566. if (srcSize + ZSTD_blockHeaderSize > dstCapacity) return ERROR(dstSize_tooSmall);
  1567. MEM_writeLE24(dst, cBlockHeader24);
  1568. memcpy((BYTE*)dst + ZSTD_blockHeaderSize, src, srcSize);
  1569. return ZSTD_blockHeaderSize + srcSize;
  1570. }
  1571. static size_t ZSTD_noCompressLiterals (void* dst, size_t dstCapacity, const void* src, size_t srcSize)
  1572. {
  1573. BYTE* const ostart = (BYTE* const)dst;
  1574. U32 const flSize = 1 + (srcSize>31) + (srcSize>4095);
  1575. if (srcSize + flSize > dstCapacity) return ERROR(dstSize_tooSmall);
  1576. switch(flSize)
  1577. {
  1578. case 1: /* 2 - 1 - 5 */
  1579. ostart[0] = (BYTE)((U32)set_basic + (srcSize<<3));
  1580. break;
  1581. case 2: /* 2 - 2 - 12 */
  1582. MEM_writeLE16(ostart, (U16)((U32)set_basic + (1<<2) + (srcSize<<4)));
  1583. break;
  1584. case 3: /* 2 - 2 - 20 */
  1585. MEM_writeLE32(ostart, (U32)((U32)set_basic + (3<<2) + (srcSize<<4)));
  1586. break;
  1587. default: /* not necessary : flSize is {1,2,3} */
  1588. assert(0);
  1589. }
  1590. memcpy(ostart + flSize, src, srcSize);
  1591. return srcSize + flSize;
  1592. }
  1593. static size_t ZSTD_compressRleLiteralsBlock (void* dst, size_t dstCapacity, const void* src, size_t srcSize)
  1594. {
  1595. BYTE* const ostart = (BYTE* const)dst;
  1596. U32 const flSize = 1 + (srcSize>31) + (srcSize>4095);
  1597. (void)dstCapacity; /* dstCapacity already guaranteed to be >=4, hence large enough */
  1598. switch(flSize)
  1599. {
  1600. case 1: /* 2 - 1 - 5 */
  1601. ostart[0] = (BYTE)((U32)set_rle + (srcSize<<3));
  1602. break;
  1603. case 2: /* 2 - 2 - 12 */
  1604. MEM_writeLE16(ostart, (U16)((U32)set_rle + (1<<2) + (srcSize<<4)));
  1605. break;
  1606. case 3: /* 2 - 2 - 20 */
  1607. MEM_writeLE32(ostart, (U32)((U32)set_rle + (3<<2) + (srcSize<<4)));
  1608. break;
  1609. default: /* not necessary : flSize is {1,2,3} */
  1610. assert(0);
  1611. }
  1612. ostart[flSize] = *(const BYTE*)src;
  1613. return flSize+1;
  1614. }
  1615. /* ZSTD_minGain() :
  1616. * minimum compression required
  1617. * to generate a compress block or a compressed literals section.
  1618. * note : use same formula for both situations */
  1619. static size_t ZSTD_minGain(size_t srcSize, ZSTD_strategy strat)
  1620. {
  1621. U32 const minlog = (strat>=ZSTD_btultra) ? (U32)(strat) - 1 : 6;
  1622. ZSTD_STATIC_ASSERT(ZSTD_btultra == 8);
  1623. assert(ZSTD_cParam_withinBounds(ZSTD_c_strategy, strat));
  1624. return (srcSize >> minlog) + 2;
  1625. }
  1626. static size_t ZSTD_compressLiterals (ZSTD_hufCTables_t const* prevHuf,
  1627. ZSTD_hufCTables_t* nextHuf,
  1628. ZSTD_strategy strategy, int disableLiteralCompression,
  1629. void* dst, size_t dstCapacity,
  1630. const void* src, size_t srcSize,
  1631. void* workspace, size_t wkspSize,
  1632. const int bmi2)
  1633. {
  1634. size_t const minGain = ZSTD_minGain(srcSize, strategy);
  1635. size_t const lhSize = 3 + (srcSize >= 1 KB) + (srcSize >= 16 KB);
  1636. BYTE* const ostart = (BYTE*)dst;
  1637. U32 singleStream = srcSize < 256;
  1638. symbolEncodingType_e hType = set_compressed;
  1639. size_t cLitSize;
  1640. DEBUGLOG(5,"ZSTD_compressLiterals (disableLiteralCompression=%i)",
  1641. disableLiteralCompression);
  1642. /* Prepare nextEntropy assuming reusing the existing table */
  1643. memcpy(nextHuf, prevHuf, sizeof(*prevHuf));
  1644. if (disableLiteralCompression)
  1645. return ZSTD_noCompressLiterals(dst, dstCapacity, src, srcSize);
  1646. /* small ? don't even attempt compression (speed opt) */
  1647. # define COMPRESS_LITERALS_SIZE_MIN 63
  1648. { size_t const minLitSize = (prevHuf->repeatMode == HUF_repeat_valid) ? 6 : COMPRESS_LITERALS_SIZE_MIN;
  1649. if (srcSize <= minLitSize) return ZSTD_noCompressLiterals(dst, dstCapacity, src, srcSize);
  1650. }
  1651. if (dstCapacity < lhSize+1) return ERROR(dstSize_tooSmall); /* not enough space for compression */
  1652. { HUF_repeat repeat = prevHuf->repeatMode;
  1653. int const preferRepeat = strategy < ZSTD_lazy ? srcSize <= 1024 : 0;
  1654. if (repeat == HUF_repeat_valid && lhSize == 3) singleStream = 1;
  1655. cLitSize = singleStream ? HUF_compress1X_repeat(ostart+lhSize, dstCapacity-lhSize, src, srcSize, 255, 11,
  1656. workspace, wkspSize, (HUF_CElt*)nextHuf->CTable, &repeat, preferRepeat, bmi2)
  1657. : HUF_compress4X_repeat(ostart+lhSize, dstCapacity-lhSize, src, srcSize, 255, 11,
  1658. workspace, wkspSize, (HUF_CElt*)nextHuf->CTable, &repeat, preferRepeat, bmi2);
  1659. if (repeat != HUF_repeat_none) {
  1660. /* reused the existing table */
  1661. hType = set_repeat;
  1662. }
  1663. }
  1664. if ((cLitSize==0) | (cLitSize >= srcSize - minGain) | ERR_isError(cLitSize)) {
  1665. memcpy(nextHuf, prevHuf, sizeof(*prevHuf));
  1666. return ZSTD_noCompressLiterals(dst, dstCapacity, src, srcSize);
  1667. }
  1668. if (cLitSize==1) {
  1669. memcpy(nextHuf, prevHuf, sizeof(*prevHuf));
  1670. return ZSTD_compressRleLiteralsBlock(dst, dstCapacity, src, srcSize);
  1671. }
  1672. if (hType == set_compressed) {
  1673. /* using a newly constructed table */
  1674. nextHuf->repeatMode = HUF_repeat_check;
  1675. }
  1676. /* Build header */
  1677. switch(lhSize)
  1678. {
  1679. case 3: /* 2 - 2 - 10 - 10 */
  1680. { U32 const lhc = hType + ((!singleStream) << 2) + ((U32)srcSize<<4) + ((U32)cLitSize<<14);
  1681. MEM_writeLE24(ostart, lhc);
  1682. break;
  1683. }
  1684. case 4: /* 2 - 2 - 14 - 14 */
  1685. { U32 const lhc = hType + (2 << 2) + ((U32)srcSize<<4) + ((U32)cLitSize<<18);
  1686. MEM_writeLE32(ostart, lhc);
  1687. break;
  1688. }
  1689. case 5: /* 2 - 2 - 18 - 18 */
  1690. { U32 const lhc = hType + (3 << 2) + ((U32)srcSize<<4) + ((U32)cLitSize<<22);
  1691. MEM_writeLE32(ostart, lhc);
  1692. ostart[4] = (BYTE)(cLitSize >> 10);
  1693. break;
  1694. }
  1695. default: /* not possible : lhSize is {3,4,5} */
  1696. assert(0);
  1697. }
  1698. return lhSize+cLitSize;
  1699. }
  1700. void ZSTD_seqToCodes(const seqStore_t* seqStorePtr)
  1701. {
  1702. const seqDef* const sequences = seqStorePtr->sequencesStart;
  1703. BYTE* const llCodeTable = seqStorePtr->llCode;
  1704. BYTE* const ofCodeTable = seqStorePtr->ofCode;
  1705. BYTE* const mlCodeTable = seqStorePtr->mlCode;
  1706. U32 const nbSeq = (U32)(seqStorePtr->sequences - seqStorePtr->sequencesStart);
  1707. U32 u;
  1708. assert(nbSeq <= seqStorePtr->maxNbSeq);
  1709. for (u=0; u<nbSeq; u++) {
  1710. U32 const llv = sequences[u].litLength;
  1711. U32 const mlv = sequences[u].matchLength;
  1712. llCodeTable[u] = (BYTE)ZSTD_LLcode(llv);
  1713. ofCodeTable[u] = (BYTE)ZSTD_highbit32(sequences[u].offset);
  1714. mlCodeTable[u] = (BYTE)ZSTD_MLcode(mlv);
  1715. }
  1716. if (seqStorePtr->longLengthID==1)
  1717. llCodeTable[seqStorePtr->longLengthPos] = MaxLL;
  1718. if (seqStorePtr->longLengthID==2)
  1719. mlCodeTable[seqStorePtr->longLengthPos] = MaxML;
  1720. }
  1721. /**
  1722. * -log2(x / 256) lookup table for x in [0, 256).
  1723. * If x == 0: Return 0
  1724. * Else: Return floor(-log2(x / 256) * 256)
  1725. */
  1726. static unsigned const kInverseProbabiltyLog256[256] = {
  1727. 0, 2048, 1792, 1642, 1536, 1453, 1386, 1329, 1280, 1236, 1197, 1162,
  1728. 1130, 1100, 1073, 1047, 1024, 1001, 980, 960, 941, 923, 906, 889,
  1729. 874, 859, 844, 830, 817, 804, 791, 779, 768, 756, 745, 734,
  1730. 724, 714, 704, 694, 685, 676, 667, 658, 650, 642, 633, 626,
  1731. 618, 610, 603, 595, 588, 581, 574, 567, 561, 554, 548, 542,
  1732. 535, 529, 523, 517, 512, 506, 500, 495, 489, 484, 478, 473,
  1733. 468, 463, 458, 453, 448, 443, 438, 434, 429, 424, 420, 415,
  1734. 411, 407, 402, 398, 394, 390, 386, 382, 377, 373, 370, 366,
  1735. 362, 358, 354, 350, 347, 343, 339, 336, 332, 329, 325, 322,
  1736. 318, 315, 311, 308, 305, 302, 298, 295, 292, 289, 286, 282,
  1737. 279, 276, 273, 270, 267, 264, 261, 258, 256, 253, 250, 247,
  1738. 244, 241, 239, 236, 233, 230, 228, 225, 222, 220, 217, 215,
  1739. 212, 209, 207, 204, 202, 199, 197, 194, 192, 190, 187, 185,
  1740. 182, 180, 178, 175, 173, 171, 168, 166, 164, 162, 159, 157,
  1741. 155, 153, 151, 149, 146, 144, 142, 140, 138, 136, 134, 132,
  1742. 130, 128, 126, 123, 121, 119, 117, 115, 114, 112, 110, 108,
  1743. 106, 104, 102, 100, 98, 96, 94, 93, 91, 89, 87, 85,
  1744. 83, 82, 80, 78, 76, 74, 73, 71, 69, 67, 66, 64,
  1745. 62, 61, 59, 57, 55, 54, 52, 50, 49, 47, 46, 44,
  1746. 42, 41, 39, 37, 36, 34, 33, 31, 30, 28, 26, 25,
  1747. 23, 22, 20, 19, 17, 16, 14, 13, 11, 10, 8, 7,
  1748. 5, 4, 2, 1,
  1749. };
  1750. /**
  1751. * Returns the cost in bits of encoding the distribution described by count
  1752. * using the entropy bound.
  1753. */
  1754. static size_t ZSTD_entropyCost(unsigned const* count, unsigned const max, size_t const total)
  1755. {
  1756. unsigned cost = 0;
  1757. unsigned s;
  1758. for (s = 0; s <= max; ++s) {
  1759. unsigned norm = (unsigned)((256 * count[s]) / total);
  1760. if (count[s] != 0 && norm == 0)
  1761. norm = 1;
  1762. assert(count[s] < total);
  1763. cost += count[s] * kInverseProbabiltyLog256[norm];
  1764. }
  1765. return cost >> 8;
  1766. }
  1767. /**
  1768. * Returns the cost in bits of encoding the distribution in count using the
  1769. * table described by norm. The max symbol support by norm is assumed >= max.
  1770. * norm must be valid for every symbol with non-zero probability in count.
  1771. */
  1772. static size_t ZSTD_crossEntropyCost(short const* norm, unsigned accuracyLog,
  1773. unsigned const* count, unsigned const max)
  1774. {
  1775. unsigned const shift = 8 - accuracyLog;
  1776. size_t cost = 0;
  1777. unsigned s;
  1778. assert(accuracyLog <= 8);
  1779. for (s = 0; s <= max; ++s) {
  1780. unsigned const normAcc = norm[s] != -1 ? norm[s] : 1;
  1781. unsigned const norm256 = normAcc << shift;
  1782. assert(norm256 > 0);
  1783. assert(norm256 < 256);
  1784. cost += count[s] * kInverseProbabiltyLog256[norm256];
  1785. }
  1786. return cost >> 8;
  1787. }
  1788. static unsigned ZSTD_getFSEMaxSymbolValue(FSE_CTable const* ctable) {
  1789. void const* ptr = ctable;
  1790. U16 const* u16ptr = (U16 const*)ptr;
  1791. U32 const maxSymbolValue = MEM_read16(u16ptr + 1);
  1792. return maxSymbolValue;
  1793. }
  1794. /**
  1795. * Returns the cost in bits of encoding the distribution in count using ctable.
  1796. * Returns an error if ctable cannot represent all the symbols in count.
  1797. */
  1798. static size_t ZSTD_fseBitCost(
  1799. FSE_CTable const* ctable,
  1800. unsigned const* count,
  1801. unsigned const max)
  1802. {
  1803. unsigned const kAccuracyLog = 8;
  1804. size_t cost = 0;
  1805. unsigned s;
  1806. FSE_CState_t cstate;
  1807. FSE_initCState(&cstate, ctable);
  1808. if (ZSTD_getFSEMaxSymbolValue(ctable) < max) {
  1809. DEBUGLOG(5, "Repeat FSE_CTable has maxSymbolValue %u < %u",
  1810. ZSTD_getFSEMaxSymbolValue(ctable), max);
  1811. return ERROR(GENERIC);
  1812. }
  1813. for (s = 0; s <= max; ++s) {
  1814. unsigned const tableLog = cstate.stateLog;
  1815. unsigned const badCost = (tableLog + 1) << kAccuracyLog;
  1816. unsigned const bitCost = FSE_bitCost(cstate.symbolTT, tableLog, s, kAccuracyLog);
  1817. if (count[s] == 0)
  1818. continue;
  1819. if (bitCost >= badCost) {
  1820. DEBUGLOG(5, "Repeat FSE_CTable has Prob[%u] == 0", s);
  1821. return ERROR(GENERIC);
  1822. }
  1823. cost += count[s] * bitCost;
  1824. }
  1825. return cost >> kAccuracyLog;
  1826. }
  1827. /**
  1828. * Returns the cost in bytes of encoding the normalized count header.
  1829. * Returns an error if any of the helper functions return an error.
  1830. */
  1831. static size_t ZSTD_NCountCost(unsigned const* count, unsigned const max,
  1832. size_t const nbSeq, unsigned const FSELog)
  1833. {
  1834. BYTE wksp[FSE_NCOUNTBOUND];
  1835. S16 norm[MaxSeq + 1];
  1836. const U32 tableLog = FSE_optimalTableLog(FSELog, nbSeq, max);
  1837. CHECK_F(FSE_normalizeCount(norm, tableLog, count, nbSeq, max));
  1838. return FSE_writeNCount(wksp, sizeof(wksp), norm, max, tableLog);
  1839. }
  1840. typedef enum {
  1841. ZSTD_defaultDisallowed = 0,
  1842. ZSTD_defaultAllowed = 1
  1843. } ZSTD_defaultPolicy_e;
  1844. MEM_STATIC symbolEncodingType_e
  1845. ZSTD_selectEncodingType(
  1846. FSE_repeat* repeatMode, unsigned const* count, unsigned const max,
  1847. size_t const mostFrequent, size_t nbSeq, unsigned const FSELog,
  1848. FSE_CTable const* prevCTable,
  1849. short const* defaultNorm, U32 defaultNormLog,
  1850. ZSTD_defaultPolicy_e const isDefaultAllowed,
  1851. ZSTD_strategy const strategy)
  1852. {
  1853. ZSTD_STATIC_ASSERT(ZSTD_defaultDisallowed == 0 && ZSTD_defaultAllowed != 0);
  1854. if (mostFrequent == nbSeq) {
  1855. *repeatMode = FSE_repeat_none;
  1856. if (isDefaultAllowed && nbSeq <= 2) {
  1857. /* Prefer set_basic over set_rle when there are 2 or less symbols,
  1858. * since RLE uses 1 byte, but set_basic uses 5-6 bits per symbol.
  1859. * If basic encoding isn't possible, always choose RLE.
  1860. */
  1861. DEBUGLOG(5, "Selected set_basic");
  1862. return set_basic;
  1863. }
  1864. DEBUGLOG(5, "Selected set_rle");
  1865. return set_rle;
  1866. }
  1867. if (strategy < ZSTD_lazy) {
  1868. if (isDefaultAllowed) {
  1869. size_t const staticFse_nbSeq_max = 1000;
  1870. size_t const mult = 10 - strategy;
  1871. size_t const baseLog = 3;
  1872. size_t const dynamicFse_nbSeq_min = (((size_t)1 << defaultNormLog) * mult) >> baseLog; /* 28-36 for offset, 56-72 for lengths */
  1873. assert(defaultNormLog >= 5 && defaultNormLog <= 6); /* xx_DEFAULTNORMLOG */
  1874. assert(mult <= 9 && mult >= 7);
  1875. if ( (*repeatMode == FSE_repeat_valid)
  1876. && (nbSeq < staticFse_nbSeq_max) ) {
  1877. DEBUGLOG(5, "Selected set_repeat");
  1878. return set_repeat;
  1879. }
  1880. if ( (nbSeq < dynamicFse_nbSeq_min)
  1881. || (mostFrequent < (nbSeq >> (defaultNormLog-1))) ) {
  1882. DEBUGLOG(5, "Selected set_basic");
  1883. /* The format allows default tables to be repeated, but it isn't useful.
  1884. * When using simple heuristics to select encoding type, we don't want
  1885. * to confuse these tables with dictionaries. When running more careful
  1886. * analysis, we don't need to waste time checking both repeating tables
  1887. * and default tables.
  1888. */
  1889. *repeatMode = FSE_repeat_none;
  1890. return set_basic;
  1891. }
  1892. }
  1893. } else {
  1894. size_t const basicCost = isDefaultAllowed ? ZSTD_crossEntropyCost(defaultNorm, defaultNormLog, count, max) : ERROR(GENERIC);
  1895. size_t const repeatCost = *repeatMode != FSE_repeat_none ? ZSTD_fseBitCost(prevCTable, count, max) : ERROR(GENERIC);
  1896. size_t const NCountCost = ZSTD_NCountCost(count, max, nbSeq, FSELog);
  1897. size_t const compressedCost = (NCountCost << 3) + ZSTD_entropyCost(count, max, nbSeq);
  1898. if (isDefaultAllowed) {
  1899. assert(!ZSTD_isError(basicCost));
  1900. assert(!(*repeatMode == FSE_repeat_valid && ZSTD_isError(repeatCost)));
  1901. }
  1902. assert(!ZSTD_isError(NCountCost));
  1903. assert(compressedCost < ERROR(maxCode));
  1904. DEBUGLOG(5, "Estimated bit costs: basic=%u\trepeat=%u\tcompressed=%u",
  1905. (unsigned)basicCost, (unsigned)repeatCost, (unsigned)compressedCost);
  1906. if (basicCost <= repeatCost && basicCost <= compressedCost) {
  1907. DEBUGLOG(5, "Selected set_basic");
  1908. assert(isDefaultAllowed);
  1909. *repeatMode = FSE_repeat_none;
  1910. return set_basic;
  1911. }
  1912. if (repeatCost <= compressedCost) {
  1913. DEBUGLOG(5, "Selected set_repeat");
  1914. assert(!ZSTD_isError(repeatCost));
  1915. return set_repeat;
  1916. }
  1917. assert(compressedCost < basicCost && compressedCost < repeatCost);
  1918. }
  1919. DEBUGLOG(5, "Selected set_compressed");
  1920. *repeatMode = FSE_repeat_check;
  1921. return set_compressed;
  1922. }
  1923. MEM_STATIC size_t
  1924. ZSTD_buildCTable(void* dst, size_t dstCapacity,
  1925. FSE_CTable* nextCTable, U32 FSELog, symbolEncodingType_e type,
  1926. unsigned* count, U32 max,
  1927. const BYTE* codeTable, size_t nbSeq,
  1928. const S16* defaultNorm, U32 defaultNormLog, U32 defaultMax,
  1929. const FSE_CTable* prevCTable, size_t prevCTableSize,
  1930. void* workspace, size_t workspaceSize)
  1931. {
  1932. BYTE* op = (BYTE*)dst;
  1933. const BYTE* const oend = op + dstCapacity;
  1934. DEBUGLOG(6, "ZSTD_buildCTable (dstCapacity=%u)", (unsigned)dstCapacity);
  1935. switch (type) {
  1936. case set_rle:
  1937. CHECK_F(FSE_buildCTable_rle(nextCTable, (BYTE)max));
  1938. if (dstCapacity==0) return ERROR(dstSize_tooSmall);
  1939. *op = codeTable[0];
  1940. return 1;
  1941. case set_repeat:
  1942. memcpy(nextCTable, prevCTable, prevCTableSize);
  1943. return 0;
  1944. case set_basic:
  1945. CHECK_F(FSE_buildCTable_wksp(nextCTable, defaultNorm, defaultMax, defaultNormLog, workspace, workspaceSize)); /* note : could be pre-calculated */
  1946. return 0;
  1947. case set_compressed: {
  1948. S16 norm[MaxSeq + 1];
  1949. size_t nbSeq_1 = nbSeq;
  1950. const U32 tableLog = FSE_optimalTableLog(FSELog, nbSeq, max);
  1951. if (count[codeTable[nbSeq-1]] > 1) {
  1952. count[codeTable[nbSeq-1]]--;
  1953. nbSeq_1--;
  1954. }
  1955. assert(nbSeq_1 > 1);
  1956. CHECK_F(FSE_normalizeCount(norm, tableLog, count, nbSeq_1, max));
  1957. { size_t const NCountSize = FSE_writeNCount(op, oend - op, norm, max, tableLog); /* overflow protected */
  1958. if (FSE_isError(NCountSize)) return NCountSize;
  1959. CHECK_F(FSE_buildCTable_wksp(nextCTable, norm, max, tableLog, workspace, workspaceSize));
  1960. return NCountSize;
  1961. }
  1962. }
  1963. default: return assert(0), ERROR(GENERIC);
  1964. }
  1965. }
  1966. FORCE_INLINE_TEMPLATE size_t
  1967. ZSTD_encodeSequences_body(
  1968. void* dst, size_t dstCapacity,
  1969. FSE_CTable const* CTable_MatchLength, BYTE const* mlCodeTable,
  1970. FSE_CTable const* CTable_OffsetBits, BYTE const* ofCodeTable,
  1971. FSE_CTable const* CTable_LitLength, BYTE const* llCodeTable,
  1972. seqDef const* sequences, size_t nbSeq, int longOffsets)
  1973. {
  1974. BIT_CStream_t blockStream;
  1975. FSE_CState_t stateMatchLength;
  1976. FSE_CState_t stateOffsetBits;
  1977. FSE_CState_t stateLitLength;
  1978. CHECK_E(BIT_initCStream(&blockStream, dst, dstCapacity), dstSize_tooSmall); /* not enough space remaining */
  1979. DEBUGLOG(6, "available space for bitstream : %i (dstCapacity=%u)",
  1980. (int)(blockStream.endPtr - blockStream.startPtr),
  1981. (unsigned)dstCapacity);
  1982. /* first symbols */
  1983. FSE_initCState2(&stateMatchLength, CTable_MatchLength, mlCodeTable[nbSeq-1]);
  1984. FSE_initCState2(&stateOffsetBits, CTable_OffsetBits, ofCodeTable[nbSeq-1]);
  1985. FSE_initCState2(&stateLitLength, CTable_LitLength, llCodeTable[nbSeq-1]);
  1986. BIT_addBits(&blockStream, sequences[nbSeq-1].litLength, LL_bits[llCodeTable[nbSeq-1]]);
  1987. if (MEM_32bits()) BIT_flushBits(&blockStream);
  1988. BIT_addBits(&blockStream, sequences[nbSeq-1].matchLength, ML_bits[mlCodeTable[nbSeq-1]]);
  1989. if (MEM_32bits()) BIT_flushBits(&blockStream);
  1990. if (longOffsets) {
  1991. U32 const ofBits = ofCodeTable[nbSeq-1];
  1992. int const extraBits = ofBits - MIN(ofBits, STREAM_ACCUMULATOR_MIN-1);
  1993. if (extraBits) {
  1994. BIT_addBits(&blockStream, sequences[nbSeq-1].offset, extraBits);
  1995. BIT_flushBits(&blockStream);
  1996. }
  1997. BIT_addBits(&blockStream, sequences[nbSeq-1].offset >> extraBits,
  1998. ofBits - extraBits);
  1999. } else {
  2000. BIT_addBits(&blockStream, sequences[nbSeq-1].offset, ofCodeTable[nbSeq-1]);
  2001. }
  2002. BIT_flushBits(&blockStream);
  2003. { size_t n;
  2004. for (n=nbSeq-2 ; n<nbSeq ; n--) { /* intentional underflow */
  2005. BYTE const llCode = llCodeTable[n];
  2006. BYTE const ofCode = ofCodeTable[n];
  2007. BYTE const mlCode = mlCodeTable[n];
  2008. U32 const llBits = LL_bits[llCode];
  2009. U32 const ofBits = ofCode;
  2010. U32 const mlBits = ML_bits[mlCode];
  2011. DEBUGLOG(6, "encoding: litlen:%2u - matchlen:%2u - offCode:%7u",
  2012. (unsigned)sequences[n].litLength,
  2013. (unsigned)sequences[n].matchLength + MINMATCH,
  2014. (unsigned)sequences[n].offset);
  2015. /* 32b*/ /* 64b*/
  2016. /* (7)*/ /* (7)*/
  2017. FSE_encodeSymbol(&blockStream, &stateOffsetBits, ofCode); /* 15 */ /* 15 */
  2018. FSE_encodeSymbol(&blockStream, &stateMatchLength, mlCode); /* 24 */ /* 24 */
  2019. if (MEM_32bits()) BIT_flushBits(&blockStream); /* (7)*/
  2020. FSE_encodeSymbol(&blockStream, &stateLitLength, llCode); /* 16 */ /* 33 */
  2021. if (MEM_32bits() || (ofBits+mlBits+llBits >= 64-7-(LLFSELog+MLFSELog+OffFSELog)))
  2022. BIT_flushBits(&blockStream); /* (7)*/
  2023. BIT_addBits(&blockStream, sequences[n].litLength, llBits);
  2024. if (MEM_32bits() && ((llBits+mlBits)>24)) BIT_flushBits(&blockStream);
  2025. BIT_addBits(&blockStream, sequences[n].matchLength, mlBits);
  2026. if (MEM_32bits() || (ofBits+mlBits+llBits > 56)) BIT_flushBits(&blockStream);
  2027. if (longOffsets) {
  2028. int const extraBits = ofBits - MIN(ofBits, STREAM_ACCUMULATOR_MIN-1);
  2029. if (extraBits) {
  2030. BIT_addBits(&blockStream, sequences[n].offset, extraBits);
  2031. BIT_flushBits(&blockStream); /* (7)*/
  2032. }
  2033. BIT_addBits(&blockStream, sequences[n].offset >> extraBits,
  2034. ofBits - extraBits); /* 31 */
  2035. } else {
  2036. BIT_addBits(&blockStream, sequences[n].offset, ofBits); /* 31 */
  2037. }
  2038. BIT_flushBits(&blockStream); /* (7)*/
  2039. DEBUGLOG(7, "remaining space : %i", (int)(blockStream.endPtr - blockStream.ptr));
  2040. } }
  2041. DEBUGLOG(6, "ZSTD_encodeSequences: flushing ML state with %u bits", stateMatchLength.stateLog);
  2042. FSE_flushCState(&blockStream, &stateMatchLength);
  2043. DEBUGLOG(6, "ZSTD_encodeSequences: flushing Off state with %u bits", stateOffsetBits.stateLog);
  2044. FSE_flushCState(&blockStream, &stateOffsetBits);
  2045. DEBUGLOG(6, "ZSTD_encodeSequences: flushing LL state with %u bits", stateLitLength.stateLog);
  2046. FSE_flushCState(&blockStream, &stateLitLength);
  2047. { size_t const streamSize = BIT_closeCStream(&blockStream);
  2048. if (streamSize==0) return ERROR(dstSize_tooSmall); /* not enough space */
  2049. return streamSize;
  2050. }
  2051. }
  2052. static size_t
  2053. ZSTD_encodeSequences_default(
  2054. void* dst, size_t dstCapacity,
  2055. FSE_CTable const* CTable_MatchLength, BYTE const* mlCodeTable,
  2056. FSE_CTable const* CTable_OffsetBits, BYTE const* ofCodeTable,
  2057. FSE_CTable const* CTable_LitLength, BYTE const* llCodeTable,
  2058. seqDef const* sequences, size_t nbSeq, int longOffsets)
  2059. {
  2060. return ZSTD_encodeSequences_body(dst, dstCapacity,
  2061. CTable_MatchLength, mlCodeTable,
  2062. CTable_OffsetBits, ofCodeTable,
  2063. CTable_LitLength, llCodeTable,
  2064. sequences, nbSeq, longOffsets);
  2065. }
  2066. #if DYNAMIC_BMI2
  2067. static TARGET_ATTRIBUTE("bmi2") size_t
  2068. ZSTD_encodeSequences_bmi2(
  2069. void* dst, size_t dstCapacity,
  2070. FSE_CTable const* CTable_MatchLength, BYTE const* mlCodeTable,
  2071. FSE_CTable const* CTable_OffsetBits, BYTE const* ofCodeTable,
  2072. FSE_CTable const* CTable_LitLength, BYTE const* llCodeTable,
  2073. seqDef const* sequences, size_t nbSeq, int longOffsets)
  2074. {
  2075. return ZSTD_encodeSequences_body(dst, dstCapacity,
  2076. CTable_MatchLength, mlCodeTable,
  2077. CTable_OffsetBits, ofCodeTable,
  2078. CTable_LitLength, llCodeTable,
  2079. sequences, nbSeq, longOffsets);
  2080. }
  2081. #endif
  2082. static size_t ZSTD_encodeSequences(
  2083. void* dst, size_t dstCapacity,
  2084. FSE_CTable const* CTable_MatchLength, BYTE const* mlCodeTable,
  2085. FSE_CTable const* CTable_OffsetBits, BYTE const* ofCodeTable,
  2086. FSE_CTable const* CTable_LitLength, BYTE const* llCodeTable,
  2087. seqDef const* sequences, size_t nbSeq, int longOffsets, int bmi2)
  2088. {
  2089. DEBUGLOG(5, "ZSTD_encodeSequences: dstCapacity = %u", (unsigned)dstCapacity);
  2090. #if DYNAMIC_BMI2
  2091. if (bmi2) {
  2092. return ZSTD_encodeSequences_bmi2(dst, dstCapacity,
  2093. CTable_MatchLength, mlCodeTable,
  2094. CTable_OffsetBits, ofCodeTable,
  2095. CTable_LitLength, llCodeTable,
  2096. sequences, nbSeq, longOffsets);
  2097. }
  2098. #endif
  2099. (void)bmi2;
  2100. return ZSTD_encodeSequences_default(dst, dstCapacity,
  2101. CTable_MatchLength, mlCodeTable,
  2102. CTable_OffsetBits, ofCodeTable,
  2103. CTable_LitLength, llCodeTable,
  2104. sequences, nbSeq, longOffsets);
  2105. }
  2106. /* ZSTD_compressSequences_internal():
  2107. * actually compresses both literals and sequences */
  2108. MEM_STATIC size_t
  2109. ZSTD_compressSequences_internal(seqStore_t* seqStorePtr,
  2110. const ZSTD_entropyCTables_t* prevEntropy,
  2111. ZSTD_entropyCTables_t* nextEntropy,
  2112. const ZSTD_CCtx_params* cctxParams,
  2113. void* dst, size_t dstCapacity,
  2114. void* workspace, size_t wkspSize,
  2115. const int bmi2)
  2116. {
  2117. const int longOffsets = cctxParams->cParams.windowLog > STREAM_ACCUMULATOR_MIN;
  2118. ZSTD_strategy const strategy = cctxParams->cParams.strategy;
  2119. unsigned count[MaxSeq+1];
  2120. FSE_CTable* CTable_LitLength = nextEntropy->fse.litlengthCTable;
  2121. FSE_CTable* CTable_OffsetBits = nextEntropy->fse.offcodeCTable;
  2122. FSE_CTable* CTable_MatchLength = nextEntropy->fse.matchlengthCTable;
  2123. U32 LLtype, Offtype, MLtype; /* compressed, raw or rle */
  2124. const seqDef* const sequences = seqStorePtr->sequencesStart;
  2125. const BYTE* const ofCodeTable = seqStorePtr->ofCode;
  2126. const BYTE* const llCodeTable = seqStorePtr->llCode;
  2127. const BYTE* const mlCodeTable = seqStorePtr->mlCode;
  2128. BYTE* const ostart = (BYTE*)dst;
  2129. BYTE* const oend = ostart + dstCapacity;
  2130. BYTE* op = ostart;
  2131. size_t const nbSeq = seqStorePtr->sequences - seqStorePtr->sequencesStart;
  2132. BYTE* seqHead;
  2133. BYTE* lastNCount = NULL;
  2134. ZSTD_STATIC_ASSERT(HUF_WORKSPACE_SIZE >= (1<<MAX(MLFSELog,LLFSELog)));
  2135. DEBUGLOG(5, "ZSTD_compressSequences_internal");
  2136. /* Compress literals */
  2137. { const BYTE* const literals = seqStorePtr->litStart;
  2138. size_t const litSize = seqStorePtr->lit - literals;
  2139. int const disableLiteralCompression = (cctxParams->cParams.strategy == ZSTD_fast) && (cctxParams->cParams.targetLength > 0);
  2140. size_t const cSize = ZSTD_compressLiterals(
  2141. &prevEntropy->huf, &nextEntropy->huf,
  2142. cctxParams->cParams.strategy, disableLiteralCompression,
  2143. op, dstCapacity,
  2144. literals, litSize,
  2145. workspace, wkspSize,
  2146. bmi2);
  2147. if (ZSTD_isError(cSize))
  2148. return cSize;
  2149. assert(cSize <= dstCapacity);
  2150. op += cSize;
  2151. }
  2152. /* Sequences Header */
  2153. if ((oend-op) < 3 /*max nbSeq Size*/ + 1 /*seqHead*/) return ERROR(dstSize_tooSmall);
  2154. if (nbSeq < 0x7F)
  2155. *op++ = (BYTE)nbSeq;
  2156. else if (nbSeq < LONGNBSEQ)
  2157. op[0] = (BYTE)((nbSeq>>8) + 0x80), op[1] = (BYTE)nbSeq, op+=2;
  2158. else
  2159. op[0]=0xFF, MEM_writeLE16(op+1, (U16)(nbSeq - LONGNBSEQ)), op+=3;
  2160. if (nbSeq==0) {
  2161. /* Copy the old tables over as if we repeated them */
  2162. memcpy(&nextEntropy->fse, &prevEntropy->fse, sizeof(prevEntropy->fse));
  2163. return op - ostart;
  2164. }
  2165. /* seqHead : flags for FSE encoding type */
  2166. seqHead = op++;
  2167. /* convert length/distances into codes */
  2168. ZSTD_seqToCodes(seqStorePtr);
  2169. /* build CTable for Literal Lengths */
  2170. { unsigned max = MaxLL;
  2171. size_t const mostFrequent = HIST_countFast_wksp(count, &max, llCodeTable, nbSeq, workspace, wkspSize); /* can't fail */
  2172. DEBUGLOG(5, "Building LL table");
  2173. nextEntropy->fse.litlength_repeatMode = prevEntropy->fse.litlength_repeatMode;
  2174. LLtype = ZSTD_selectEncodingType(&nextEntropy->fse.litlength_repeatMode,
  2175. count, max, mostFrequent, nbSeq,
  2176. LLFSELog, prevEntropy->fse.litlengthCTable,
  2177. LL_defaultNorm, LL_defaultNormLog,
  2178. ZSTD_defaultAllowed, strategy);
  2179. assert(set_basic < set_compressed && set_rle < set_compressed);
  2180. assert(!(LLtype < set_compressed && nextEntropy->fse.litlength_repeatMode != FSE_repeat_none)); /* We don't copy tables */
  2181. { size_t const countSize = ZSTD_buildCTable(op, oend - op, CTable_LitLength, LLFSELog, (symbolEncodingType_e)LLtype,
  2182. count, max, llCodeTable, nbSeq, LL_defaultNorm, LL_defaultNormLog, MaxLL,
  2183. prevEntropy->fse.litlengthCTable, sizeof(prevEntropy->fse.litlengthCTable),
  2184. workspace, wkspSize);
  2185. if (ZSTD_isError(countSize)) return countSize;
  2186. if (LLtype == set_compressed)
  2187. lastNCount = op;
  2188. op += countSize;
  2189. } }
  2190. /* build CTable for Offsets */
  2191. { unsigned max = MaxOff;
  2192. size_t const mostFrequent = HIST_countFast_wksp(count, &max, ofCodeTable, nbSeq, workspace, wkspSize); /* can't fail */
  2193. /* We can only use the basic table if max <= DefaultMaxOff, otherwise the offsets are too large */
  2194. ZSTD_defaultPolicy_e const defaultPolicy = (max <= DefaultMaxOff) ? ZSTD_defaultAllowed : ZSTD_defaultDisallowed;
  2195. DEBUGLOG(5, "Building OF table");
  2196. nextEntropy->fse.offcode_repeatMode = prevEntropy->fse.offcode_repeatMode;
  2197. Offtype = ZSTD_selectEncodingType(&nextEntropy->fse.offcode_repeatMode,
  2198. count, max, mostFrequent, nbSeq,
  2199. OffFSELog, prevEntropy->fse.offcodeCTable,
  2200. OF_defaultNorm, OF_defaultNormLog,
  2201. defaultPolicy, strategy);
  2202. assert(!(Offtype < set_compressed && nextEntropy->fse.offcode_repeatMode != FSE_repeat_none)); /* We don't copy tables */
  2203. { size_t const countSize = ZSTD_buildCTable(op, oend - op, CTable_OffsetBits, OffFSELog, (symbolEncodingType_e)Offtype,
  2204. count, max, ofCodeTable, nbSeq, OF_defaultNorm, OF_defaultNormLog, DefaultMaxOff,
  2205. prevEntropy->fse.offcodeCTable, sizeof(prevEntropy->fse.offcodeCTable),
  2206. workspace, wkspSize);
  2207. if (ZSTD_isError(countSize)) return countSize;
  2208. if (Offtype == set_compressed)
  2209. lastNCount = op;
  2210. op += countSize;
  2211. } }
  2212. /* build CTable for MatchLengths */
  2213. { unsigned max = MaxML;
  2214. size_t const mostFrequent = HIST_countFast_wksp(count, &max, mlCodeTable, nbSeq, workspace, wkspSize); /* can't fail */
  2215. DEBUGLOG(5, "Building ML table (remaining space : %i)", (int)(oend-op));
  2216. nextEntropy->fse.matchlength_repeatMode = prevEntropy->fse.matchlength_repeatMode;
  2217. MLtype = ZSTD_selectEncodingType(&nextEntropy->fse.matchlength_repeatMode,
  2218. count, max, mostFrequent, nbSeq,
  2219. MLFSELog, prevEntropy->fse.matchlengthCTable,
  2220. ML_defaultNorm, ML_defaultNormLog,
  2221. ZSTD_defaultAllowed, strategy);
  2222. assert(!(MLtype < set_compressed && nextEntropy->fse.matchlength_repeatMode != FSE_repeat_none)); /* We don't copy tables */
  2223. { size_t const countSize = ZSTD_buildCTable(op, oend - op, CTable_MatchLength, MLFSELog, (symbolEncodingType_e)MLtype,
  2224. count, max, mlCodeTable, nbSeq, ML_defaultNorm, ML_defaultNormLog, MaxML,
  2225. prevEntropy->fse.matchlengthCTable, sizeof(prevEntropy->fse.matchlengthCTable),
  2226. workspace, wkspSize);
  2227. if (ZSTD_isError(countSize)) return countSize;
  2228. if (MLtype == set_compressed)
  2229. lastNCount = op;
  2230. op += countSize;
  2231. } }
  2232. *seqHead = (BYTE)((LLtype<<6) + (Offtype<<4) + (MLtype<<2));
  2233. { size_t const bitstreamSize = ZSTD_encodeSequences(
  2234. op, oend - op,
  2235. CTable_MatchLength, mlCodeTable,
  2236. CTable_OffsetBits, ofCodeTable,
  2237. CTable_LitLength, llCodeTable,
  2238. sequences, nbSeq,
  2239. longOffsets, bmi2);
  2240. if (ZSTD_isError(bitstreamSize)) return bitstreamSize;
  2241. op += bitstreamSize;
  2242. /* zstd versions <= 1.3.4 mistakenly report corruption when
  2243. * FSE_readNCount() recieves a buffer < 4 bytes.
  2244. * Fixed by https://github.com/facebook/zstd/pull/1146.
  2245. * This can happen when the last set_compressed table present is 2
  2246. * bytes and the bitstream is only one byte.
  2247. * In this exceedingly rare case, we will simply emit an uncompressed
  2248. * block, since it isn't worth optimizing.
  2249. */
  2250. if (lastNCount && (op - lastNCount) < 4) {
  2251. /* NCountSize >= 2 && bitstreamSize > 0 ==> lastCountSize == 3 */
  2252. assert(op - lastNCount == 3);
  2253. DEBUGLOG(5, "Avoiding bug in zstd decoder in versions <= 1.3.4 by "
  2254. "emitting an uncompressed block.");
  2255. return 0;
  2256. }
  2257. }
  2258. DEBUGLOG(5, "compressed block size : %u", (unsigned)(op - ostart));
  2259. return op - ostart;
  2260. }
  2261. MEM_STATIC size_t
  2262. ZSTD_compressSequences(seqStore_t* seqStorePtr,
  2263. const ZSTD_entropyCTables_t* prevEntropy,
  2264. ZSTD_entropyCTables_t* nextEntropy,
  2265. const ZSTD_CCtx_params* cctxParams,
  2266. void* dst, size_t dstCapacity,
  2267. size_t srcSize,
  2268. void* workspace, size_t wkspSize,
  2269. int bmi2)
  2270. {
  2271. size_t const cSize = ZSTD_compressSequences_internal(
  2272. seqStorePtr, prevEntropy, nextEntropy, cctxParams,
  2273. dst, dstCapacity,
  2274. workspace, wkspSize, bmi2);
  2275. if (cSize == 0) return 0;
  2276. /* When srcSize <= dstCapacity, there is enough space to write a raw uncompressed block.
  2277. * Since we ran out of space, block must be not compressible, so fall back to raw uncompressed block.
  2278. */
  2279. if ((cSize == ERROR(dstSize_tooSmall)) & (srcSize <= dstCapacity))
  2280. return 0; /* block not compressed */
  2281. if (ZSTD_isError(cSize)) return cSize;
  2282. /* Check compressibility */
  2283. { size_t const maxCSize = srcSize - ZSTD_minGain(srcSize, cctxParams->cParams.strategy);
  2284. if (cSize >= maxCSize) return 0; /* block not compressed */
  2285. }
  2286. return cSize;
  2287. }
  2288. /* ZSTD_selectBlockCompressor() :
  2289. * Not static, but internal use only (used by long distance matcher)
  2290. * assumption : strat is a valid strategy */
  2291. ZSTD_blockCompressor ZSTD_selectBlockCompressor(ZSTD_strategy strat, ZSTD_dictMode_e dictMode)
  2292. {
  2293. static const ZSTD_blockCompressor blockCompressor[3][ZSTD_STRATEGY_MAX+1] = {
  2294. { ZSTD_compressBlock_fast /* default for 0 */,
  2295. ZSTD_compressBlock_fast,
  2296. ZSTD_compressBlock_doubleFast,
  2297. ZSTD_compressBlock_greedy,
  2298. ZSTD_compressBlock_lazy,
  2299. ZSTD_compressBlock_lazy2,
  2300. ZSTD_compressBlock_btlazy2,
  2301. ZSTD_compressBlock_btopt,
  2302. ZSTD_compressBlock_btultra,
  2303. ZSTD_compressBlock_btultra2 },
  2304. { ZSTD_compressBlock_fast_extDict /* default for 0 */,
  2305. ZSTD_compressBlock_fast_extDict,
  2306. ZSTD_compressBlock_doubleFast_extDict,
  2307. ZSTD_compressBlock_greedy_extDict,
  2308. ZSTD_compressBlock_lazy_extDict,
  2309. ZSTD_compressBlock_lazy2_extDict,
  2310. ZSTD_compressBlock_btlazy2_extDict,
  2311. ZSTD_compressBlock_btopt_extDict,
  2312. ZSTD_compressBlock_btultra_extDict,
  2313. ZSTD_compressBlock_btultra_extDict },
  2314. { ZSTD_compressBlock_fast_dictMatchState /* default for 0 */,
  2315. ZSTD_compressBlock_fast_dictMatchState,
  2316. ZSTD_compressBlock_doubleFast_dictMatchState,
  2317. ZSTD_compressBlock_greedy_dictMatchState,
  2318. ZSTD_compressBlock_lazy_dictMatchState,
  2319. ZSTD_compressBlock_lazy2_dictMatchState,
  2320. ZSTD_compressBlock_btlazy2_dictMatchState,
  2321. ZSTD_compressBlock_btopt_dictMatchState,
  2322. ZSTD_compressBlock_btultra_dictMatchState,
  2323. ZSTD_compressBlock_btultra_dictMatchState }
  2324. };
  2325. ZSTD_blockCompressor selectedCompressor;
  2326. ZSTD_STATIC_ASSERT((unsigned)ZSTD_fast == 1);
  2327. assert(ZSTD_cParam_withinBounds(ZSTD_c_strategy, strat));
  2328. selectedCompressor = blockCompressor[(int)dictMode][(int)strat];
  2329. assert(selectedCompressor != NULL);
  2330. return selectedCompressor;
  2331. }
  2332. static void ZSTD_storeLastLiterals(seqStore_t* seqStorePtr,
  2333. const BYTE* anchor, size_t lastLLSize)
  2334. {
  2335. memcpy(seqStorePtr->lit, anchor, lastLLSize);
  2336. seqStorePtr->lit += lastLLSize;
  2337. }
  2338. void ZSTD_resetSeqStore(seqStore_t* ssPtr)
  2339. {
  2340. ssPtr->lit = ssPtr->litStart;
  2341. ssPtr->sequences = ssPtr->sequencesStart;
  2342. ssPtr->longLengthID = 0;
  2343. }
  2344. static size_t ZSTD_compressBlock_internal(ZSTD_CCtx* zc,
  2345. void* dst, size_t dstCapacity,
  2346. const void* src, size_t srcSize)
  2347. {
  2348. ZSTD_matchState_t* const ms = &zc->blockState.matchState;
  2349. size_t cSize;
  2350. DEBUGLOG(5, "ZSTD_compressBlock_internal (dstCapacity=%u, dictLimit=%u, nextToUpdate=%u)",
  2351. (unsigned)dstCapacity, (unsigned)ms->window.dictLimit, (unsigned)ms->nextToUpdate);
  2352. assert(srcSize <= ZSTD_BLOCKSIZE_MAX);
  2353. /* Assert that we have correctly flushed the ctx params into the ms's copy */
  2354. ZSTD_assertEqualCParams(zc->appliedParams.cParams, ms->cParams);
  2355. if (srcSize < MIN_CBLOCK_SIZE+ZSTD_blockHeaderSize+1) {
  2356. ZSTD_ldm_skipSequences(&zc->externSeqStore, srcSize, zc->appliedParams.cParams.minMatch);
  2357. cSize = 0;
  2358. goto out; /* don't even attempt compression below a certain srcSize */
  2359. }
  2360. ZSTD_resetSeqStore(&(zc->seqStore));
  2361. ms->opt.symbolCosts = &zc->blockState.prevCBlock->entropy; /* required for optimal parser to read stats from dictionary */
  2362. /* a gap between an attached dict and the current window is not safe,
  2363. * they must remain adjacent,
  2364. * and when that stops being the case, the dict must be unset */
  2365. assert(ms->dictMatchState == NULL || ms->loadedDictEnd == ms->window.dictLimit);
  2366. /* limited update after a very long match */
  2367. { const BYTE* const base = ms->window.base;
  2368. const BYTE* const istart = (const BYTE*)src;
  2369. const U32 current = (U32)(istart-base);
  2370. if (sizeof(ptrdiff_t)==8) assert(istart - base < (ptrdiff_t)(U32)(-1)); /* ensure no overflow */
  2371. if (current > ms->nextToUpdate + 384)
  2372. ms->nextToUpdate = current - MIN(192, (U32)(current - ms->nextToUpdate - 384));
  2373. }
  2374. /* select and store sequences */
  2375. { ZSTD_dictMode_e const dictMode = ZSTD_matchState_dictMode(ms);
  2376. size_t lastLLSize;
  2377. { int i;
  2378. for (i = 0; i < ZSTD_REP_NUM; ++i)
  2379. zc->blockState.nextCBlock->rep[i] = zc->blockState.prevCBlock->rep[i];
  2380. }
  2381. if (zc->externSeqStore.pos < zc->externSeqStore.size) {
  2382. assert(!zc->appliedParams.ldmParams.enableLdm);
  2383. /* Updates ldmSeqStore.pos */
  2384. lastLLSize =
  2385. ZSTD_ldm_blockCompress(&zc->externSeqStore,
  2386. ms, &zc->seqStore,
  2387. zc->blockState.nextCBlock->rep,
  2388. src, srcSize);
  2389. assert(zc->externSeqStore.pos <= zc->externSeqStore.size);
  2390. } else if (zc->appliedParams.ldmParams.enableLdm) {
  2391. rawSeqStore_t ldmSeqStore = {NULL, 0, 0, 0};
  2392. ldmSeqStore.seq = zc->ldmSequences;
  2393. ldmSeqStore.capacity = zc->maxNbLdmSequences;
  2394. /* Updates ldmSeqStore.size */
  2395. CHECK_F(ZSTD_ldm_generateSequences(&zc->ldmState, &ldmSeqStore,
  2396. &zc->appliedParams.ldmParams,
  2397. src, srcSize));
  2398. /* Updates ldmSeqStore.pos */
  2399. lastLLSize =
  2400. ZSTD_ldm_blockCompress(&ldmSeqStore,
  2401. ms, &zc->seqStore,
  2402. zc->blockState.nextCBlock->rep,
  2403. src, srcSize);
  2404. assert(ldmSeqStore.pos == ldmSeqStore.size);
  2405. } else { /* not long range mode */
  2406. ZSTD_blockCompressor const blockCompressor = ZSTD_selectBlockCompressor(zc->appliedParams.cParams.strategy, dictMode);
  2407. lastLLSize = blockCompressor(ms, &zc->seqStore, zc->blockState.nextCBlock->rep, src, srcSize);
  2408. }
  2409. { const BYTE* const lastLiterals = (const BYTE*)src + srcSize - lastLLSize;
  2410. ZSTD_storeLastLiterals(&zc->seqStore, lastLiterals, lastLLSize);
  2411. } }
  2412. /* encode sequences and literals */
  2413. cSize = ZSTD_compressSequences(&zc->seqStore,
  2414. &zc->blockState.prevCBlock->entropy, &zc->blockState.nextCBlock->entropy,
  2415. &zc->appliedParams,
  2416. dst, dstCapacity,
  2417. srcSize,
  2418. zc->entropyWorkspace, HUF_WORKSPACE_SIZE /* statically allocated in resetCCtx */,
  2419. zc->bmi2);
  2420. out:
  2421. if (!ZSTD_isError(cSize) && cSize != 0) {
  2422. /* confirm repcodes and entropy tables when emitting a compressed block */
  2423. ZSTD_compressedBlockState_t* const tmp = zc->blockState.prevCBlock;
  2424. zc->blockState.prevCBlock = zc->blockState.nextCBlock;
  2425. zc->blockState.nextCBlock = tmp;
  2426. }
  2427. /* We check that dictionaries have offset codes available for the first
  2428. * block. After the first block, the offcode table might not have large
  2429. * enough codes to represent the offsets in the data.
  2430. */
  2431. if (zc->blockState.prevCBlock->entropy.fse.offcode_repeatMode == FSE_repeat_valid)
  2432. zc->blockState.prevCBlock->entropy.fse.offcode_repeatMode = FSE_repeat_check;
  2433. return cSize;
  2434. }
  2435. /*! ZSTD_compress_frameChunk() :
  2436. * Compress a chunk of data into one or multiple blocks.
  2437. * All blocks will be terminated, all input will be consumed.
  2438. * Function will issue an error if there is not enough `dstCapacity` to hold the compressed content.
  2439. * Frame is supposed already started (header already produced)
  2440. * @return : compressed size, or an error code
  2441. */
  2442. static size_t ZSTD_compress_frameChunk (ZSTD_CCtx* cctx,
  2443. void* dst, size_t dstCapacity,
  2444. const void* src, size_t srcSize,
  2445. U32 lastFrameChunk)
  2446. {
  2447. size_t blockSize = cctx->blockSize;
  2448. size_t remaining = srcSize;
  2449. const BYTE* ip = (const BYTE*)src;
  2450. BYTE* const ostart = (BYTE*)dst;
  2451. BYTE* op = ostart;
  2452. U32 const maxDist = (U32)1 << cctx->appliedParams.cParams.windowLog;
  2453. assert(cctx->appliedParams.cParams.windowLog <= 31);
  2454. DEBUGLOG(5, "ZSTD_compress_frameChunk (blockSize=%u)", (unsigned)blockSize);
  2455. if (cctx->appliedParams.fParams.checksumFlag && srcSize)
  2456. XXH64_update(&cctx->xxhState, src, srcSize);
  2457. while (remaining) {
  2458. ZSTD_matchState_t* const ms = &cctx->blockState.matchState;
  2459. U32 const lastBlock = lastFrameChunk & (blockSize >= remaining);
  2460. if (dstCapacity < ZSTD_blockHeaderSize + MIN_CBLOCK_SIZE)
  2461. return ERROR(dstSize_tooSmall); /* not enough space to store compressed block */
  2462. if (remaining < blockSize) blockSize = remaining;
  2463. if (ZSTD_window_needOverflowCorrection(ms->window, ip + blockSize)) {
  2464. U32 const cycleLog = ZSTD_cycleLog(cctx->appliedParams.cParams.chainLog, cctx->appliedParams.cParams.strategy);
  2465. U32 const correction = ZSTD_window_correctOverflow(&ms->window, cycleLog, maxDist, ip);
  2466. ZSTD_STATIC_ASSERT(ZSTD_CHAINLOG_MAX <= 30);
  2467. ZSTD_STATIC_ASSERT(ZSTD_WINDOWLOG_MAX_32 <= 30);
  2468. ZSTD_STATIC_ASSERT(ZSTD_WINDOWLOG_MAX <= 31);
  2469. ZSTD_reduceIndex(cctx, correction);
  2470. if (ms->nextToUpdate < correction) ms->nextToUpdate = 0;
  2471. else ms->nextToUpdate -= correction;
  2472. ms->loadedDictEnd = 0;
  2473. ms->dictMatchState = NULL;
  2474. }
  2475. ZSTD_window_enforceMaxDist(&ms->window, ip + blockSize, maxDist, &ms->loadedDictEnd, &ms->dictMatchState);
  2476. if (ms->nextToUpdate < ms->window.lowLimit) ms->nextToUpdate = ms->window.lowLimit;
  2477. { size_t cSize = ZSTD_compressBlock_internal(cctx,
  2478. op+ZSTD_blockHeaderSize, dstCapacity-ZSTD_blockHeaderSize,
  2479. ip, blockSize);
  2480. if (ZSTD_isError(cSize)) return cSize;
  2481. if (cSize == 0) { /* block is not compressible */
  2482. cSize = ZSTD_noCompressBlock(op, dstCapacity, ip, blockSize, lastBlock);
  2483. if (ZSTD_isError(cSize)) return cSize;
  2484. } else {
  2485. U32 const cBlockHeader24 = lastBlock + (((U32)bt_compressed)<<1) + (U32)(cSize << 3);
  2486. MEM_writeLE24(op, cBlockHeader24);
  2487. cSize += ZSTD_blockHeaderSize;
  2488. }
  2489. ip += blockSize;
  2490. assert(remaining >= blockSize);
  2491. remaining -= blockSize;
  2492. op += cSize;
  2493. assert(dstCapacity >= cSize);
  2494. dstCapacity -= cSize;
  2495. DEBUGLOG(5, "ZSTD_compress_frameChunk: adding a block of size %u",
  2496. (unsigned)cSize);
  2497. } }
  2498. if (lastFrameChunk && (op>ostart)) cctx->stage = ZSTDcs_ending;
  2499. return op-ostart;
  2500. }
  2501. static size_t ZSTD_writeFrameHeader(void* dst, size_t dstCapacity,
  2502. ZSTD_CCtx_params params, U64 pledgedSrcSize, U32 dictID)
  2503. { BYTE* const op = (BYTE*)dst;
  2504. U32 const dictIDSizeCodeLength = (dictID>0) + (dictID>=256) + (dictID>=65536); /* 0-3 */
  2505. U32 const dictIDSizeCode = params.fParams.noDictIDFlag ? 0 : dictIDSizeCodeLength; /* 0-3 */
  2506. U32 const checksumFlag = params.fParams.checksumFlag>0;
  2507. U32 const windowSize = (U32)1 << params.cParams.windowLog;
  2508. U32 const singleSegment = params.fParams.contentSizeFlag && (windowSize >= pledgedSrcSize);
  2509. BYTE const windowLogByte = (BYTE)((params.cParams.windowLog - ZSTD_WINDOWLOG_ABSOLUTEMIN) << 3);
  2510. U32 const fcsCode = params.fParams.contentSizeFlag ?
  2511. (pledgedSrcSize>=256) + (pledgedSrcSize>=65536+256) + (pledgedSrcSize>=0xFFFFFFFFU) : 0; /* 0-3 */
  2512. BYTE const frameHeaderDecriptionByte = (BYTE)(dictIDSizeCode + (checksumFlag<<2) + (singleSegment<<5) + (fcsCode<<6) );
  2513. size_t pos=0;
  2514. assert(!(params.fParams.contentSizeFlag && pledgedSrcSize == ZSTD_CONTENTSIZE_UNKNOWN));
  2515. if (dstCapacity < ZSTD_FRAMEHEADERSIZE_MAX) return ERROR(dstSize_tooSmall);
  2516. DEBUGLOG(4, "ZSTD_writeFrameHeader : dictIDFlag : %u ; dictID : %u ; dictIDSizeCode : %u",
  2517. !params.fParams.noDictIDFlag, (unsigned)dictID, (unsigned)dictIDSizeCode);
  2518. if (params.format == ZSTD_f_zstd1) {
  2519. MEM_writeLE32(dst, ZSTD_MAGICNUMBER);
  2520. pos = 4;
  2521. }
  2522. op[pos++] = frameHeaderDecriptionByte;
  2523. if (!singleSegment) op[pos++] = windowLogByte;
  2524. switch(dictIDSizeCode)
  2525. {
  2526. default: assert(0); /* impossible */
  2527. case 0 : break;
  2528. case 1 : op[pos] = (BYTE)(dictID); pos++; break;
  2529. case 2 : MEM_writeLE16(op+pos, (U16)dictID); pos+=2; break;
  2530. case 3 : MEM_writeLE32(op+pos, dictID); pos+=4; break;
  2531. }
  2532. switch(fcsCode)
  2533. {
  2534. default: assert(0); /* impossible */
  2535. case 0 : if (singleSegment) op[pos++] = (BYTE)(pledgedSrcSize); break;
  2536. case 1 : MEM_writeLE16(op+pos, (U16)(pledgedSrcSize-256)); pos+=2; break;
  2537. case 2 : MEM_writeLE32(op+pos, (U32)(pledgedSrcSize)); pos+=4; break;
  2538. case 3 : MEM_writeLE64(op+pos, (U64)(pledgedSrcSize)); pos+=8; break;
  2539. }
  2540. return pos;
  2541. }
  2542. /* ZSTD_writeLastEmptyBlock() :
  2543. * output an empty Block with end-of-frame mark to complete a frame
  2544. * @return : size of data written into `dst` (== ZSTD_blockHeaderSize (defined in zstd_internal.h))
  2545. * or an error code if `dstCapcity` is too small (<ZSTD_blockHeaderSize)
  2546. */
  2547. size_t ZSTD_writeLastEmptyBlock(void* dst, size_t dstCapacity)
  2548. {
  2549. if (dstCapacity < ZSTD_blockHeaderSize) return ERROR(dstSize_tooSmall);
  2550. { U32 const cBlockHeader24 = 1 /*lastBlock*/ + (((U32)bt_raw)<<1); /* 0 size */
  2551. MEM_writeLE24(dst, cBlockHeader24);
  2552. return ZSTD_blockHeaderSize;
  2553. }
  2554. }
  2555. size_t ZSTD_referenceExternalSequences(ZSTD_CCtx* cctx, rawSeq* seq, size_t nbSeq)
  2556. {
  2557. if (cctx->stage != ZSTDcs_init)
  2558. return ERROR(stage_wrong);
  2559. if (cctx->appliedParams.ldmParams.enableLdm)
  2560. return ERROR(parameter_unsupported);
  2561. cctx->externSeqStore.seq = seq;
  2562. cctx->externSeqStore.size = nbSeq;
  2563. cctx->externSeqStore.capacity = nbSeq;
  2564. cctx->externSeqStore.pos = 0;
  2565. return 0;
  2566. }
  2567. static size_t ZSTD_compressContinue_internal (ZSTD_CCtx* cctx,
  2568. void* dst, size_t dstCapacity,
  2569. const void* src, size_t srcSize,
  2570. U32 frame, U32 lastFrameChunk)
  2571. {
  2572. ZSTD_matchState_t* const ms = &cctx->blockState.matchState;
  2573. size_t fhSize = 0;
  2574. DEBUGLOG(5, "ZSTD_compressContinue_internal, stage: %u, srcSize: %u",
  2575. cctx->stage, (unsigned)srcSize);
  2576. if (cctx->stage==ZSTDcs_created) return ERROR(stage_wrong); /* missing init (ZSTD_compressBegin) */
  2577. if (frame && (cctx->stage==ZSTDcs_init)) {
  2578. fhSize = ZSTD_writeFrameHeader(dst, dstCapacity, cctx->appliedParams,
  2579. cctx->pledgedSrcSizePlusOne-1, cctx->dictID);
  2580. if (ZSTD_isError(fhSize)) return fhSize;
  2581. dstCapacity -= fhSize;
  2582. dst = (char*)dst + fhSize;
  2583. cctx->stage = ZSTDcs_ongoing;
  2584. }
  2585. if (!srcSize) return fhSize; /* do not generate an empty block if no input */
  2586. if (!ZSTD_window_update(&ms->window, src, srcSize)) {
  2587. ms->nextToUpdate = ms->window.dictLimit;
  2588. }
  2589. if (cctx->appliedParams.ldmParams.enableLdm) {
  2590. ZSTD_window_update(&cctx->ldmState.window, src, srcSize);
  2591. }
  2592. if (!frame) {
  2593. /* overflow check and correction for block mode */
  2594. if (ZSTD_window_needOverflowCorrection(ms->window, (const char*)src + srcSize)) {
  2595. U32 const cycleLog = ZSTD_cycleLog(cctx->appliedParams.cParams.chainLog, cctx->appliedParams.cParams.strategy);
  2596. U32 const correction = ZSTD_window_correctOverflow(&ms->window, cycleLog, 1 << cctx->appliedParams.cParams.windowLog, src);
  2597. ZSTD_STATIC_ASSERT(ZSTD_CHAINLOG_MAX <= 30);
  2598. ZSTD_STATIC_ASSERT(ZSTD_WINDOWLOG_MAX_32 <= 30);
  2599. ZSTD_STATIC_ASSERT(ZSTD_WINDOWLOG_MAX <= 31);
  2600. ZSTD_reduceIndex(cctx, correction);
  2601. if (ms->nextToUpdate < correction) ms->nextToUpdate = 0;
  2602. else ms->nextToUpdate -= correction;
  2603. ms->loadedDictEnd = 0;
  2604. ms->dictMatchState = NULL;
  2605. }
  2606. }
  2607. DEBUGLOG(5, "ZSTD_compressContinue_internal (blockSize=%u)", (unsigned)cctx->blockSize);
  2608. { size_t const cSize = frame ?
  2609. ZSTD_compress_frameChunk (cctx, dst, dstCapacity, src, srcSize, lastFrameChunk) :
  2610. ZSTD_compressBlock_internal (cctx, dst, dstCapacity, src, srcSize);
  2611. if (ZSTD_isError(cSize)) return cSize;
  2612. cctx->consumedSrcSize += srcSize;
  2613. cctx->producedCSize += (cSize + fhSize);
  2614. assert(!(cctx->appliedParams.fParams.contentSizeFlag && cctx->pledgedSrcSizePlusOne == 0));
  2615. if (cctx->pledgedSrcSizePlusOne != 0) { /* control src size */
  2616. ZSTD_STATIC_ASSERT(ZSTD_CONTENTSIZE_UNKNOWN == (unsigned long long)-1);
  2617. if (cctx->consumedSrcSize+1 > cctx->pledgedSrcSizePlusOne) {
  2618. DEBUGLOG(4, "error : pledgedSrcSize = %u, while realSrcSize >= %u",
  2619. (unsigned)cctx->pledgedSrcSizePlusOne-1, (unsigned)cctx->consumedSrcSize);
  2620. return ERROR(srcSize_wrong);
  2621. }
  2622. }
  2623. return cSize + fhSize;
  2624. }
  2625. }
  2626. size_t ZSTD_compressContinue (ZSTD_CCtx* cctx,
  2627. void* dst, size_t dstCapacity,
  2628. const void* src, size_t srcSize)
  2629. {
  2630. DEBUGLOG(5, "ZSTD_compressContinue (srcSize=%u)", (unsigned)srcSize);
  2631. return ZSTD_compressContinue_internal(cctx, dst, dstCapacity, src, srcSize, 1 /* frame mode */, 0 /* last chunk */);
  2632. }
  2633. size_t ZSTD_getBlockSize(const ZSTD_CCtx* cctx)
  2634. {
  2635. ZSTD_compressionParameters const cParams = cctx->appliedParams.cParams;
  2636. assert(!ZSTD_checkCParams(cParams));
  2637. return MIN (ZSTD_BLOCKSIZE_MAX, (U32)1 << cParams.windowLog);
  2638. }
  2639. size_t ZSTD_compressBlock(ZSTD_CCtx* cctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize)
  2640. {
  2641. size_t const blockSizeMax = ZSTD_getBlockSize(cctx);
  2642. if (srcSize > blockSizeMax) return ERROR(srcSize_wrong);
  2643. return ZSTD_compressContinue_internal(cctx, dst, dstCapacity, src, srcSize, 0 /* frame mode */, 0 /* last chunk */);
  2644. }
  2645. /*! ZSTD_loadDictionaryContent() :
  2646. * @return : 0, or an error code
  2647. */
  2648. static size_t ZSTD_loadDictionaryContent(ZSTD_matchState_t* ms,
  2649. ZSTD_CCtx_params const* params,
  2650. const void* src, size_t srcSize,
  2651. ZSTD_dictTableLoadMethod_e dtlm)
  2652. {
  2653. const BYTE* const ip = (const BYTE*) src;
  2654. const BYTE* const iend = ip + srcSize;
  2655. ZSTD_window_update(&ms->window, src, srcSize);
  2656. ms->loadedDictEnd = params->forceWindow ? 0 : (U32)(iend - ms->window.base);
  2657. /* Assert that we the ms params match the params we're being given */
  2658. ZSTD_assertEqualCParams(params->cParams, ms->cParams);
  2659. if (srcSize <= HASH_READ_SIZE) return 0;
  2660. switch(params->cParams.strategy)
  2661. {
  2662. case ZSTD_fast:
  2663. ZSTD_fillHashTable(ms, iend, dtlm);
  2664. break;
  2665. case ZSTD_dfast:
  2666. ZSTD_fillDoubleHashTable(ms, iend, dtlm);
  2667. break;
  2668. case ZSTD_greedy:
  2669. case ZSTD_lazy:
  2670. case ZSTD_lazy2:
  2671. if (srcSize >= HASH_READ_SIZE)
  2672. ZSTD_insertAndFindFirstIndex(ms, iend-HASH_READ_SIZE);
  2673. break;
  2674. case ZSTD_btlazy2: /* we want the dictionary table fully sorted */
  2675. case ZSTD_btopt:
  2676. case ZSTD_btultra:
  2677. case ZSTD_btultra2:
  2678. if (srcSize >= HASH_READ_SIZE)
  2679. ZSTD_updateTree(ms, iend-HASH_READ_SIZE, iend);
  2680. break;
  2681. default:
  2682. assert(0); /* not possible : not a valid strategy id */
  2683. }
  2684. ms->nextToUpdate = (U32)(iend - ms->window.base);
  2685. return 0;
  2686. }
  2687. /* Dictionaries that assign zero probability to symbols that show up causes problems
  2688. when FSE encoding. Refuse dictionaries that assign zero probability to symbols
  2689. that we may encounter during compression.
  2690. NOTE: This behavior is not standard and could be improved in the future. */
  2691. static size_t ZSTD_checkDictNCount(short* normalizedCounter, unsigned dictMaxSymbolValue, unsigned maxSymbolValue) {
  2692. U32 s;
  2693. if (dictMaxSymbolValue < maxSymbolValue) return ERROR(dictionary_corrupted);
  2694. for (s = 0; s <= maxSymbolValue; ++s) {
  2695. if (normalizedCounter[s] == 0) return ERROR(dictionary_corrupted);
  2696. }
  2697. return 0;
  2698. }
  2699. /* Dictionary format :
  2700. * See :
  2701. * https://github.com/facebook/zstd/blob/master/doc/zstd_compression_format.md#dictionary-format
  2702. */
  2703. /*! ZSTD_loadZstdDictionary() :
  2704. * @return : dictID, or an error code
  2705. * assumptions : magic number supposed already checked
  2706. * dictSize supposed > 8
  2707. */
  2708. static size_t ZSTD_loadZstdDictionary(ZSTD_compressedBlockState_t* bs,
  2709. ZSTD_matchState_t* ms,
  2710. ZSTD_CCtx_params const* params,
  2711. const void* dict, size_t dictSize,
  2712. ZSTD_dictTableLoadMethod_e dtlm,
  2713. void* workspace)
  2714. {
  2715. const BYTE* dictPtr = (const BYTE*)dict;
  2716. const BYTE* const dictEnd = dictPtr + dictSize;
  2717. short offcodeNCount[MaxOff+1];
  2718. unsigned offcodeMaxValue = MaxOff;
  2719. size_t dictID;
  2720. ZSTD_STATIC_ASSERT(HUF_WORKSPACE_SIZE >= (1<<MAX(MLFSELog,LLFSELog)));
  2721. assert(dictSize > 8);
  2722. assert(MEM_readLE32(dictPtr) == ZSTD_MAGIC_DICTIONARY);
  2723. dictPtr += 4; /* skip magic number */
  2724. dictID = params->fParams.noDictIDFlag ? 0 : MEM_readLE32(dictPtr);
  2725. dictPtr += 4;
  2726. { unsigned maxSymbolValue = 255;
  2727. size_t const hufHeaderSize = HUF_readCTable((HUF_CElt*)bs->entropy.huf.CTable, &maxSymbolValue, dictPtr, dictEnd-dictPtr);
  2728. if (HUF_isError(hufHeaderSize)) return ERROR(dictionary_corrupted);
  2729. if (maxSymbolValue < 255) return ERROR(dictionary_corrupted);
  2730. dictPtr += hufHeaderSize;
  2731. }
  2732. { unsigned offcodeLog;
  2733. size_t const offcodeHeaderSize = FSE_readNCount(offcodeNCount, &offcodeMaxValue, &offcodeLog, dictPtr, dictEnd-dictPtr);
  2734. if (FSE_isError(offcodeHeaderSize)) return ERROR(dictionary_corrupted);
  2735. if (offcodeLog > OffFSELog) return ERROR(dictionary_corrupted);
  2736. /* Defer checking offcodeMaxValue because we need to know the size of the dictionary content */
  2737. /* fill all offset symbols to avoid garbage at end of table */
  2738. CHECK_E( FSE_buildCTable_wksp(bs->entropy.fse.offcodeCTable,
  2739. offcodeNCount, MaxOff, offcodeLog,
  2740. workspace, HUF_WORKSPACE_SIZE),
  2741. dictionary_corrupted);
  2742. dictPtr += offcodeHeaderSize;
  2743. }
  2744. { short matchlengthNCount[MaxML+1];
  2745. unsigned matchlengthMaxValue = MaxML, matchlengthLog;
  2746. size_t const matchlengthHeaderSize = FSE_readNCount(matchlengthNCount, &matchlengthMaxValue, &matchlengthLog, dictPtr, dictEnd-dictPtr);
  2747. if (FSE_isError(matchlengthHeaderSize)) return ERROR(dictionary_corrupted);
  2748. if (matchlengthLog > MLFSELog) return ERROR(dictionary_corrupted);
  2749. /* Every match length code must have non-zero probability */
  2750. CHECK_F( ZSTD_checkDictNCount(matchlengthNCount, matchlengthMaxValue, MaxML));
  2751. CHECK_E( FSE_buildCTable_wksp(bs->entropy.fse.matchlengthCTable,
  2752. matchlengthNCount, matchlengthMaxValue, matchlengthLog,
  2753. workspace, HUF_WORKSPACE_SIZE),
  2754. dictionary_corrupted);
  2755. dictPtr += matchlengthHeaderSize;
  2756. }
  2757. { short litlengthNCount[MaxLL+1];
  2758. unsigned litlengthMaxValue = MaxLL, litlengthLog;
  2759. size_t const litlengthHeaderSize = FSE_readNCount(litlengthNCount, &litlengthMaxValue, &litlengthLog, dictPtr, dictEnd-dictPtr);
  2760. if (FSE_isError(litlengthHeaderSize)) return ERROR(dictionary_corrupted);
  2761. if (litlengthLog > LLFSELog) return ERROR(dictionary_corrupted);
  2762. /* Every literal length code must have non-zero probability */
  2763. CHECK_F( ZSTD_checkDictNCount(litlengthNCount, litlengthMaxValue, MaxLL));
  2764. CHECK_E( FSE_buildCTable_wksp(bs->entropy.fse.litlengthCTable,
  2765. litlengthNCount, litlengthMaxValue, litlengthLog,
  2766. workspace, HUF_WORKSPACE_SIZE),
  2767. dictionary_corrupted);
  2768. dictPtr += litlengthHeaderSize;
  2769. }
  2770. if (dictPtr+12 > dictEnd) return ERROR(dictionary_corrupted);
  2771. bs->rep[0] = MEM_readLE32(dictPtr+0);
  2772. bs->rep[1] = MEM_readLE32(dictPtr+4);
  2773. bs->rep[2] = MEM_readLE32(dictPtr+8);
  2774. dictPtr += 12;
  2775. { size_t const dictContentSize = (size_t)(dictEnd - dictPtr);
  2776. U32 offcodeMax = MaxOff;
  2777. if (dictContentSize <= ((U32)-1) - 128 KB) {
  2778. U32 const maxOffset = (U32)dictContentSize + 128 KB; /* The maximum offset that must be supported */
  2779. offcodeMax = ZSTD_highbit32(maxOffset); /* Calculate minimum offset code required to represent maxOffset */
  2780. }
  2781. /* All offset values <= dictContentSize + 128 KB must be representable */
  2782. CHECK_F (ZSTD_checkDictNCount(offcodeNCount, offcodeMaxValue, MIN(offcodeMax, MaxOff)));
  2783. /* All repCodes must be <= dictContentSize and != 0*/
  2784. { U32 u;
  2785. for (u=0; u<3; u++) {
  2786. if (bs->rep[u] == 0) return ERROR(dictionary_corrupted);
  2787. if (bs->rep[u] > dictContentSize) return ERROR(dictionary_corrupted);
  2788. } }
  2789. bs->entropy.huf.repeatMode = HUF_repeat_valid;
  2790. bs->entropy.fse.offcode_repeatMode = FSE_repeat_valid;
  2791. bs->entropy.fse.matchlength_repeatMode = FSE_repeat_valid;
  2792. bs->entropy.fse.litlength_repeatMode = FSE_repeat_valid;
  2793. CHECK_F(ZSTD_loadDictionaryContent(ms, params, dictPtr, dictContentSize, dtlm));
  2794. return dictID;
  2795. }
  2796. }
  2797. /** ZSTD_compress_insertDictionary() :
  2798. * @return : dictID, or an error code */
  2799. static size_t
  2800. ZSTD_compress_insertDictionary(ZSTD_compressedBlockState_t* bs,
  2801. ZSTD_matchState_t* ms,
  2802. const ZSTD_CCtx_params* params,
  2803. const void* dict, size_t dictSize,
  2804. ZSTD_dictContentType_e dictContentType,
  2805. ZSTD_dictTableLoadMethod_e dtlm,
  2806. void* workspace)
  2807. {
  2808. DEBUGLOG(4, "ZSTD_compress_insertDictionary (dictSize=%u)", (U32)dictSize);
  2809. if ((dict==NULL) || (dictSize<=8)) return 0;
  2810. ZSTD_reset_compressedBlockState(bs);
  2811. /* dict restricted modes */
  2812. if (dictContentType == ZSTD_dct_rawContent)
  2813. return ZSTD_loadDictionaryContent(ms, params, dict, dictSize, dtlm);
  2814. if (MEM_readLE32(dict) != ZSTD_MAGIC_DICTIONARY) {
  2815. if (dictContentType == ZSTD_dct_auto) {
  2816. DEBUGLOG(4, "raw content dictionary detected");
  2817. return ZSTD_loadDictionaryContent(ms, params, dict, dictSize, dtlm);
  2818. }
  2819. if (dictContentType == ZSTD_dct_fullDict)
  2820. return ERROR(dictionary_wrong);
  2821. assert(0); /* impossible */
  2822. }
  2823. /* dict as full zstd dictionary */
  2824. return ZSTD_loadZstdDictionary(bs, ms, params, dict, dictSize, dtlm, workspace);
  2825. }
  2826. /*! ZSTD_compressBegin_internal() :
  2827. * @return : 0, or an error code */
  2828. static size_t ZSTD_compressBegin_internal(ZSTD_CCtx* cctx,
  2829. const void* dict, size_t dictSize,
  2830. ZSTD_dictContentType_e dictContentType,
  2831. ZSTD_dictTableLoadMethod_e dtlm,
  2832. const ZSTD_CDict* cdict,
  2833. ZSTD_CCtx_params params, U64 pledgedSrcSize,
  2834. ZSTD_buffered_policy_e zbuff)
  2835. {
  2836. DEBUGLOG(4, "ZSTD_compressBegin_internal: wlog=%u", params.cParams.windowLog);
  2837. /* params are supposed to be fully validated at this point */
  2838. assert(!ZSTD_isError(ZSTD_checkCParams(params.cParams)));
  2839. assert(!((dict) && (cdict))); /* either dict or cdict, not both */
  2840. if (cdict && cdict->dictContentSize>0) {
  2841. return ZSTD_resetCCtx_usingCDict(cctx, cdict, params, pledgedSrcSize, zbuff);
  2842. }
  2843. CHECK_F( ZSTD_resetCCtx_internal(cctx, params, pledgedSrcSize,
  2844. ZSTDcrp_continue, zbuff) );
  2845. {
  2846. size_t const dictID = ZSTD_compress_insertDictionary(
  2847. cctx->blockState.prevCBlock, &cctx->blockState.matchState,
  2848. &params, dict, dictSize, dictContentType, dtlm, cctx->entropyWorkspace);
  2849. if (ZSTD_isError(dictID)) return dictID;
  2850. assert(dictID <= (size_t)(U32)-1);
  2851. cctx->dictID = (U32)dictID;
  2852. }
  2853. return 0;
  2854. }
  2855. size_t ZSTD_compressBegin_advanced_internal(ZSTD_CCtx* cctx,
  2856. const void* dict, size_t dictSize,
  2857. ZSTD_dictContentType_e dictContentType,
  2858. ZSTD_dictTableLoadMethod_e dtlm,
  2859. const ZSTD_CDict* cdict,
  2860. ZSTD_CCtx_params params,
  2861. unsigned long long pledgedSrcSize)
  2862. {
  2863. DEBUGLOG(4, "ZSTD_compressBegin_advanced_internal: wlog=%u", params.cParams.windowLog);
  2864. /* compression parameters verification and optimization */
  2865. CHECK_F( ZSTD_checkCParams(params.cParams) );
  2866. return ZSTD_compressBegin_internal(cctx,
  2867. dict, dictSize, dictContentType, dtlm,
  2868. cdict,
  2869. params, pledgedSrcSize,
  2870. ZSTDb_not_buffered);
  2871. }
  2872. /*! ZSTD_compressBegin_advanced() :
  2873. * @return : 0, or an error code */
  2874. size_t ZSTD_compressBegin_advanced(ZSTD_CCtx* cctx,
  2875. const void* dict, size_t dictSize,
  2876. ZSTD_parameters params, unsigned long long pledgedSrcSize)
  2877. {
  2878. ZSTD_CCtx_params const cctxParams =
  2879. ZSTD_assignParamsToCCtxParams(cctx->requestedParams, params);
  2880. return ZSTD_compressBegin_advanced_internal(cctx,
  2881. dict, dictSize, ZSTD_dct_auto, ZSTD_dtlm_fast,
  2882. NULL /*cdict*/,
  2883. cctxParams, pledgedSrcSize);
  2884. }
  2885. size_t ZSTD_compressBegin_usingDict(ZSTD_CCtx* cctx, const void* dict, size_t dictSize, int compressionLevel)
  2886. {
  2887. ZSTD_parameters const params = ZSTD_getParams(compressionLevel, ZSTD_CONTENTSIZE_UNKNOWN, dictSize);
  2888. ZSTD_CCtx_params const cctxParams =
  2889. ZSTD_assignParamsToCCtxParams(cctx->requestedParams, params);
  2890. DEBUGLOG(4, "ZSTD_compressBegin_usingDict (dictSize=%u)", (unsigned)dictSize);
  2891. return ZSTD_compressBegin_internal(cctx, dict, dictSize, ZSTD_dct_auto, ZSTD_dtlm_fast, NULL,
  2892. cctxParams, ZSTD_CONTENTSIZE_UNKNOWN, ZSTDb_not_buffered);
  2893. }
  2894. size_t ZSTD_compressBegin(ZSTD_CCtx* cctx, int compressionLevel)
  2895. {
  2896. return ZSTD_compressBegin_usingDict(cctx, NULL, 0, compressionLevel);
  2897. }
  2898. /*! ZSTD_writeEpilogue() :
  2899. * Ends a frame.
  2900. * @return : nb of bytes written into dst (or an error code) */
  2901. static size_t ZSTD_writeEpilogue(ZSTD_CCtx* cctx, void* dst, size_t dstCapacity)
  2902. {
  2903. BYTE* const ostart = (BYTE*)dst;
  2904. BYTE* op = ostart;
  2905. size_t fhSize = 0;
  2906. DEBUGLOG(4, "ZSTD_writeEpilogue");
  2907. if (cctx->stage == ZSTDcs_created) return ERROR(stage_wrong); /* init missing */
  2908. /* special case : empty frame */
  2909. if (cctx->stage == ZSTDcs_init) {
  2910. fhSize = ZSTD_writeFrameHeader(dst, dstCapacity, cctx->appliedParams, 0, 0);
  2911. if (ZSTD_isError(fhSize)) return fhSize;
  2912. dstCapacity -= fhSize;
  2913. op += fhSize;
  2914. cctx->stage = ZSTDcs_ongoing;
  2915. }
  2916. if (cctx->stage != ZSTDcs_ending) {
  2917. /* write one last empty block, make it the "last" block */
  2918. U32 const cBlockHeader24 = 1 /* last block */ + (((U32)bt_raw)<<1) + 0;
  2919. if (dstCapacity<4) return ERROR(dstSize_tooSmall);
  2920. MEM_writeLE32(op, cBlockHeader24);
  2921. op += ZSTD_blockHeaderSize;
  2922. dstCapacity -= ZSTD_blockHeaderSize;
  2923. }
  2924. if (cctx->appliedParams.fParams.checksumFlag) {
  2925. U32 const checksum = (U32) XXH64_digest(&cctx->xxhState);
  2926. if (dstCapacity<4) return ERROR(dstSize_tooSmall);
  2927. DEBUGLOG(4, "ZSTD_writeEpilogue: write checksum : %08X", (unsigned)checksum);
  2928. MEM_writeLE32(op, checksum);
  2929. op += 4;
  2930. }
  2931. cctx->stage = ZSTDcs_created; /* return to "created but no init" status */
  2932. return op-ostart;
  2933. }
  2934. size_t ZSTD_compressEnd (ZSTD_CCtx* cctx,
  2935. void* dst, size_t dstCapacity,
  2936. const void* src, size_t srcSize)
  2937. {
  2938. size_t endResult;
  2939. size_t const cSize = ZSTD_compressContinue_internal(cctx,
  2940. dst, dstCapacity, src, srcSize,
  2941. 1 /* frame mode */, 1 /* last chunk */);
  2942. if (ZSTD_isError(cSize)) return cSize;
  2943. endResult = ZSTD_writeEpilogue(cctx, (char*)dst + cSize, dstCapacity-cSize);
  2944. if (ZSTD_isError(endResult)) return endResult;
  2945. assert(!(cctx->appliedParams.fParams.contentSizeFlag && cctx->pledgedSrcSizePlusOne == 0));
  2946. if (cctx->pledgedSrcSizePlusOne != 0) { /* control src size */
  2947. ZSTD_STATIC_ASSERT(ZSTD_CONTENTSIZE_UNKNOWN == (unsigned long long)-1);
  2948. DEBUGLOG(4, "end of frame : controlling src size");
  2949. if (cctx->pledgedSrcSizePlusOne != cctx->consumedSrcSize+1) {
  2950. DEBUGLOG(4, "error : pledgedSrcSize = %u, while realSrcSize = %u",
  2951. (unsigned)cctx->pledgedSrcSizePlusOne-1, (unsigned)cctx->consumedSrcSize);
  2952. return ERROR(srcSize_wrong);
  2953. } }
  2954. return cSize + endResult;
  2955. }
  2956. static size_t ZSTD_compress_internal (ZSTD_CCtx* cctx,
  2957. void* dst, size_t dstCapacity,
  2958. const void* src, size_t srcSize,
  2959. const void* dict,size_t dictSize,
  2960. ZSTD_parameters params)
  2961. {
  2962. ZSTD_CCtx_params const cctxParams =
  2963. ZSTD_assignParamsToCCtxParams(cctx->requestedParams, params);
  2964. DEBUGLOG(4, "ZSTD_compress_internal");
  2965. return ZSTD_compress_advanced_internal(cctx,
  2966. dst, dstCapacity,
  2967. src, srcSize,
  2968. dict, dictSize,
  2969. cctxParams);
  2970. }
  2971. size_t ZSTD_compress_advanced (ZSTD_CCtx* cctx,
  2972. void* dst, size_t dstCapacity,
  2973. const void* src, size_t srcSize,
  2974. const void* dict,size_t dictSize,
  2975. ZSTD_parameters params)
  2976. {
  2977. DEBUGLOG(4, "ZSTD_compress_advanced");
  2978. CHECK_F(ZSTD_checkCParams(params.cParams));
  2979. return ZSTD_compress_internal(cctx,
  2980. dst, dstCapacity,
  2981. src, srcSize,
  2982. dict, dictSize,
  2983. params);
  2984. }
  2985. /* Internal */
  2986. size_t ZSTD_compress_advanced_internal(
  2987. ZSTD_CCtx* cctx,
  2988. void* dst, size_t dstCapacity,
  2989. const void* src, size_t srcSize,
  2990. const void* dict,size_t dictSize,
  2991. ZSTD_CCtx_params params)
  2992. {
  2993. DEBUGLOG(4, "ZSTD_compress_advanced_internal (srcSize:%u)", (unsigned)srcSize);
  2994. CHECK_F( ZSTD_compressBegin_internal(cctx,
  2995. dict, dictSize, ZSTD_dct_auto, ZSTD_dtlm_fast, NULL,
  2996. params, srcSize, ZSTDb_not_buffered) );
  2997. return ZSTD_compressEnd(cctx, dst, dstCapacity, src, srcSize);
  2998. }
  2999. size_t ZSTD_compress_usingDict(ZSTD_CCtx* cctx,
  3000. void* dst, size_t dstCapacity,
  3001. const void* src, size_t srcSize,
  3002. const void* dict, size_t dictSize,
  3003. int compressionLevel)
  3004. {
  3005. ZSTD_parameters const params = ZSTD_getParams(compressionLevel, srcSize + (!srcSize), dict ? dictSize : 0);
  3006. ZSTD_CCtx_params cctxParams = ZSTD_assignParamsToCCtxParams(cctx->requestedParams, params);
  3007. assert(params.fParams.contentSizeFlag == 1);
  3008. return ZSTD_compress_advanced_internal(cctx, dst, dstCapacity, src, srcSize, dict, dictSize, cctxParams);
  3009. }
  3010. size_t ZSTD_compressCCtx(ZSTD_CCtx* cctx,
  3011. void* dst, size_t dstCapacity,
  3012. const void* src, size_t srcSize,
  3013. int compressionLevel)
  3014. {
  3015. DEBUGLOG(4, "ZSTD_compressCCtx (srcSize=%u)", (unsigned)srcSize);
  3016. assert(cctx != NULL);
  3017. return ZSTD_compress_usingDict(cctx, dst, dstCapacity, src, srcSize, NULL, 0, compressionLevel);
  3018. }
  3019. size_t ZSTD_compress(void* dst, size_t dstCapacity,
  3020. const void* src, size_t srcSize,
  3021. int compressionLevel)
  3022. {
  3023. size_t result;
  3024. ZSTD_CCtx ctxBody;
  3025. ZSTD_initCCtx(&ctxBody, ZSTD_defaultCMem);
  3026. result = ZSTD_compressCCtx(&ctxBody, dst, dstCapacity, src, srcSize, compressionLevel);
  3027. ZSTD_freeCCtxContent(&ctxBody); /* can't free ctxBody itself, as it's on stack; free only heap content */
  3028. return result;
  3029. }
  3030. /* ===== Dictionary API ===== */
  3031. /*! ZSTD_estimateCDictSize_advanced() :
  3032. * Estimate amount of memory that will be needed to create a dictionary with following arguments */
  3033. size_t ZSTD_estimateCDictSize_advanced(
  3034. size_t dictSize, ZSTD_compressionParameters cParams,
  3035. ZSTD_dictLoadMethod_e dictLoadMethod)
  3036. {
  3037. DEBUGLOG(5, "sizeof(ZSTD_CDict) : %u", (unsigned)sizeof(ZSTD_CDict));
  3038. return sizeof(ZSTD_CDict) + HUF_WORKSPACE_SIZE + ZSTD_sizeof_matchState(&cParams, /* forCCtx */ 0)
  3039. + (dictLoadMethod == ZSTD_dlm_byRef ? 0 : dictSize);
  3040. }
  3041. size_t ZSTD_estimateCDictSize(size_t dictSize, int compressionLevel)
  3042. {
  3043. ZSTD_compressionParameters const cParams = ZSTD_getCParams(compressionLevel, 0, dictSize);
  3044. return ZSTD_estimateCDictSize_advanced(dictSize, cParams, ZSTD_dlm_byCopy);
  3045. }
  3046. size_t ZSTD_sizeof_CDict(const ZSTD_CDict* cdict)
  3047. {
  3048. if (cdict==NULL) return 0; /* support sizeof on NULL */
  3049. DEBUGLOG(5, "sizeof(*cdict) : %u", (unsigned)sizeof(*cdict));
  3050. return cdict->workspaceSize + (cdict->dictBuffer ? cdict->dictContentSize : 0) + sizeof(*cdict);
  3051. }
  3052. static size_t ZSTD_initCDict_internal(
  3053. ZSTD_CDict* cdict,
  3054. const void* dictBuffer, size_t dictSize,
  3055. ZSTD_dictLoadMethod_e dictLoadMethod,
  3056. ZSTD_dictContentType_e dictContentType,
  3057. ZSTD_compressionParameters cParams)
  3058. {
  3059. DEBUGLOG(3, "ZSTD_initCDict_internal (dictContentType:%u)", (unsigned)dictContentType);
  3060. assert(!ZSTD_checkCParams(cParams));
  3061. cdict->matchState.cParams = cParams;
  3062. if ((dictLoadMethod == ZSTD_dlm_byRef) || (!dictBuffer) || (!dictSize)) {
  3063. cdict->dictBuffer = NULL;
  3064. cdict->dictContent = dictBuffer;
  3065. } else {
  3066. void* const internalBuffer = ZSTD_malloc(dictSize, cdict->customMem);
  3067. cdict->dictBuffer = internalBuffer;
  3068. cdict->dictContent = internalBuffer;
  3069. if (!internalBuffer) return ERROR(memory_allocation);
  3070. memcpy(internalBuffer, dictBuffer, dictSize);
  3071. }
  3072. cdict->dictContentSize = dictSize;
  3073. /* Reset the state to no dictionary */
  3074. ZSTD_reset_compressedBlockState(&cdict->cBlockState);
  3075. { void* const end = ZSTD_reset_matchState(
  3076. &cdict->matchState,
  3077. (U32*)cdict->workspace + HUF_WORKSPACE_SIZE_U32,
  3078. &cParams, ZSTDcrp_continue, /* forCCtx */ 0);
  3079. assert(end == (char*)cdict->workspace + cdict->workspaceSize);
  3080. (void)end;
  3081. }
  3082. /* (Maybe) load the dictionary
  3083. * Skips loading the dictionary if it is <= 8 bytes.
  3084. */
  3085. { ZSTD_CCtx_params params;
  3086. memset(&params, 0, sizeof(params));
  3087. params.compressionLevel = ZSTD_CLEVEL_DEFAULT;
  3088. params.fParams.contentSizeFlag = 1;
  3089. params.cParams = cParams;
  3090. { size_t const dictID = ZSTD_compress_insertDictionary(
  3091. &cdict->cBlockState, &cdict->matchState, &params,
  3092. cdict->dictContent, cdict->dictContentSize,
  3093. dictContentType, ZSTD_dtlm_full, cdict->workspace);
  3094. if (ZSTD_isError(dictID)) return dictID;
  3095. assert(dictID <= (size_t)(U32)-1);
  3096. cdict->dictID = (U32)dictID;
  3097. }
  3098. }
  3099. return 0;
  3100. }
  3101. ZSTD_CDict* ZSTD_createCDict_advanced(const void* dictBuffer, size_t dictSize,
  3102. ZSTD_dictLoadMethod_e dictLoadMethod,
  3103. ZSTD_dictContentType_e dictContentType,
  3104. ZSTD_compressionParameters cParams, ZSTD_customMem customMem)
  3105. {
  3106. DEBUGLOG(3, "ZSTD_createCDict_advanced, mode %u", (unsigned)dictContentType);
  3107. if (!customMem.customAlloc ^ !customMem.customFree) return NULL;
  3108. { ZSTD_CDict* const cdict = (ZSTD_CDict*)ZSTD_malloc(sizeof(ZSTD_CDict), customMem);
  3109. size_t const workspaceSize = HUF_WORKSPACE_SIZE + ZSTD_sizeof_matchState(&cParams, /* forCCtx */ 0);
  3110. void* const workspace = ZSTD_malloc(workspaceSize, customMem);
  3111. if (!cdict || !workspace) {
  3112. ZSTD_free(cdict, customMem);
  3113. ZSTD_free(workspace, customMem);
  3114. return NULL;
  3115. }
  3116. cdict->customMem = customMem;
  3117. cdict->workspace = workspace;
  3118. cdict->workspaceSize = workspaceSize;
  3119. if (ZSTD_isError( ZSTD_initCDict_internal(cdict,
  3120. dictBuffer, dictSize,
  3121. dictLoadMethod, dictContentType,
  3122. cParams) )) {
  3123. ZSTD_freeCDict(cdict);
  3124. return NULL;
  3125. }
  3126. return cdict;
  3127. }
  3128. }
  3129. ZSTD_CDict* ZSTD_createCDict(const void* dict, size_t dictSize, int compressionLevel)
  3130. {
  3131. ZSTD_compressionParameters cParams = ZSTD_getCParams(compressionLevel, 0, dictSize);
  3132. return ZSTD_createCDict_advanced(dict, dictSize,
  3133. ZSTD_dlm_byCopy, ZSTD_dct_auto,
  3134. cParams, ZSTD_defaultCMem);
  3135. }
  3136. ZSTD_CDict* ZSTD_createCDict_byReference(const void* dict, size_t dictSize, int compressionLevel)
  3137. {
  3138. ZSTD_compressionParameters cParams = ZSTD_getCParams(compressionLevel, 0, dictSize);
  3139. return ZSTD_createCDict_advanced(dict, dictSize,
  3140. ZSTD_dlm_byRef, ZSTD_dct_auto,
  3141. cParams, ZSTD_defaultCMem);
  3142. }
  3143. size_t ZSTD_freeCDict(ZSTD_CDict* cdict)
  3144. {
  3145. if (cdict==NULL) return 0; /* support free on NULL */
  3146. { ZSTD_customMem const cMem = cdict->customMem;
  3147. ZSTD_free(cdict->workspace, cMem);
  3148. ZSTD_free(cdict->dictBuffer, cMem);
  3149. ZSTD_free(cdict, cMem);
  3150. return 0;
  3151. }
  3152. }
  3153. /*! ZSTD_initStaticCDict_advanced() :
  3154. * Generate a digested dictionary in provided memory area.
  3155. * workspace: The memory area to emplace the dictionary into.
  3156. * Provided pointer must 8-bytes aligned.
  3157. * It must outlive dictionary usage.
  3158. * workspaceSize: Use ZSTD_estimateCDictSize()
  3159. * to determine how large workspace must be.
  3160. * cParams : use ZSTD_getCParams() to transform a compression level
  3161. * into its relevants cParams.
  3162. * @return : pointer to ZSTD_CDict*, or NULL if error (size too small)
  3163. * Note : there is no corresponding "free" function.
  3164. * Since workspace was allocated externally, it must be freed externally.
  3165. */
  3166. const ZSTD_CDict* ZSTD_initStaticCDict(
  3167. void* workspace, size_t workspaceSize,
  3168. const void* dict, size_t dictSize,
  3169. ZSTD_dictLoadMethod_e dictLoadMethod,
  3170. ZSTD_dictContentType_e dictContentType,
  3171. ZSTD_compressionParameters cParams)
  3172. {
  3173. size_t const matchStateSize = ZSTD_sizeof_matchState(&cParams, /* forCCtx */ 0);
  3174. size_t const neededSize = sizeof(ZSTD_CDict) + (dictLoadMethod == ZSTD_dlm_byRef ? 0 : dictSize)
  3175. + HUF_WORKSPACE_SIZE + matchStateSize;
  3176. ZSTD_CDict* const cdict = (ZSTD_CDict*) workspace;
  3177. void* ptr;
  3178. if ((size_t)workspace & 7) return NULL; /* 8-aligned */
  3179. DEBUGLOG(4, "(workspaceSize < neededSize) : (%u < %u) => %u",
  3180. (unsigned)workspaceSize, (unsigned)neededSize, (unsigned)(workspaceSize < neededSize));
  3181. if (workspaceSize < neededSize) return NULL;
  3182. if (dictLoadMethod == ZSTD_dlm_byCopy) {
  3183. memcpy(cdict+1, dict, dictSize);
  3184. dict = cdict+1;
  3185. ptr = (char*)workspace + sizeof(ZSTD_CDict) + dictSize;
  3186. } else {
  3187. ptr = cdict+1;
  3188. }
  3189. cdict->workspace = ptr;
  3190. cdict->workspaceSize = HUF_WORKSPACE_SIZE + matchStateSize;
  3191. if (ZSTD_isError( ZSTD_initCDict_internal(cdict,
  3192. dict, dictSize,
  3193. ZSTD_dlm_byRef, dictContentType,
  3194. cParams) ))
  3195. return NULL;
  3196. return cdict;
  3197. }
  3198. ZSTD_compressionParameters ZSTD_getCParamsFromCDict(const ZSTD_CDict* cdict)
  3199. {
  3200. assert(cdict != NULL);
  3201. return cdict->matchState.cParams;
  3202. }
  3203. /* ZSTD_compressBegin_usingCDict_advanced() :
  3204. * cdict must be != NULL */
  3205. size_t ZSTD_compressBegin_usingCDict_advanced(
  3206. ZSTD_CCtx* const cctx, const ZSTD_CDict* const cdict,
  3207. ZSTD_frameParameters const fParams, unsigned long long const pledgedSrcSize)
  3208. {
  3209. DEBUGLOG(4, "ZSTD_compressBegin_usingCDict_advanced");
  3210. if (cdict==NULL) return ERROR(dictionary_wrong);
  3211. { ZSTD_CCtx_params params = cctx->requestedParams;
  3212. params.cParams = ZSTD_getCParamsFromCDict(cdict);
  3213. /* Increase window log to fit the entire dictionary and source if the
  3214. * source size is known. Limit the increase to 19, which is the
  3215. * window log for compression level 1 with the largest source size.
  3216. */
  3217. if (pledgedSrcSize != ZSTD_CONTENTSIZE_UNKNOWN) {
  3218. U32 const limitedSrcSize = (U32)MIN(pledgedSrcSize, 1U << 19);
  3219. U32 const limitedSrcLog = limitedSrcSize > 1 ? ZSTD_highbit32(limitedSrcSize - 1) + 1 : 1;
  3220. params.cParams.windowLog = MAX(params.cParams.windowLog, limitedSrcLog);
  3221. }
  3222. params.fParams = fParams;
  3223. return ZSTD_compressBegin_internal(cctx,
  3224. NULL, 0, ZSTD_dct_auto, ZSTD_dtlm_fast,
  3225. cdict,
  3226. params, pledgedSrcSize,
  3227. ZSTDb_not_buffered);
  3228. }
  3229. }
  3230. /* ZSTD_compressBegin_usingCDict() :
  3231. * pledgedSrcSize=0 means "unknown"
  3232. * if pledgedSrcSize>0, it will enable contentSizeFlag */
  3233. size_t ZSTD_compressBegin_usingCDict(ZSTD_CCtx* cctx, const ZSTD_CDict* cdict)
  3234. {
  3235. ZSTD_frameParameters const fParams = { 0 /*content*/, 0 /*checksum*/, 0 /*noDictID*/ };
  3236. DEBUGLOG(4, "ZSTD_compressBegin_usingCDict : dictIDFlag == %u", !fParams.noDictIDFlag);
  3237. return ZSTD_compressBegin_usingCDict_advanced(cctx, cdict, fParams, ZSTD_CONTENTSIZE_UNKNOWN);
  3238. }
  3239. size_t ZSTD_compress_usingCDict_advanced(ZSTD_CCtx* cctx,
  3240. void* dst, size_t dstCapacity,
  3241. const void* src, size_t srcSize,
  3242. const ZSTD_CDict* cdict, ZSTD_frameParameters fParams)
  3243. {
  3244. CHECK_F (ZSTD_compressBegin_usingCDict_advanced(cctx, cdict, fParams, srcSize)); /* will check if cdict != NULL */
  3245. return ZSTD_compressEnd(cctx, dst, dstCapacity, src, srcSize);
  3246. }
  3247. /*! ZSTD_compress_usingCDict() :
  3248. * Compression using a digested Dictionary.
  3249. * Faster startup than ZSTD_compress_usingDict(), recommended when same dictionary is used multiple times.
  3250. * Note that compression parameters are decided at CDict creation time
  3251. * while frame parameters are hardcoded */
  3252. size_t ZSTD_compress_usingCDict(ZSTD_CCtx* cctx,
  3253. void* dst, size_t dstCapacity,
  3254. const void* src, size_t srcSize,
  3255. const ZSTD_CDict* cdict)
  3256. {
  3257. ZSTD_frameParameters const fParams = { 1 /*content*/, 0 /*checksum*/, 0 /*noDictID*/ };
  3258. return ZSTD_compress_usingCDict_advanced(cctx, dst, dstCapacity, src, srcSize, cdict, fParams);
  3259. }
  3260. /* ******************************************************************
  3261. * Streaming
  3262. ********************************************************************/
  3263. ZSTD_CStream* ZSTD_createCStream(void)
  3264. {
  3265. DEBUGLOG(3, "ZSTD_createCStream");
  3266. return ZSTD_createCStream_advanced(ZSTD_defaultCMem);
  3267. }
  3268. ZSTD_CStream* ZSTD_initStaticCStream(void *workspace, size_t workspaceSize)
  3269. {
  3270. return ZSTD_initStaticCCtx(workspace, workspaceSize);
  3271. }
  3272. ZSTD_CStream* ZSTD_createCStream_advanced(ZSTD_customMem customMem)
  3273. { /* CStream and CCtx are now same object */
  3274. return ZSTD_createCCtx_advanced(customMem);
  3275. }
  3276. size_t ZSTD_freeCStream(ZSTD_CStream* zcs)
  3277. {
  3278. return ZSTD_freeCCtx(zcs); /* same object */
  3279. }
  3280. /*====== Initialization ======*/
  3281. size_t ZSTD_CStreamInSize(void) { return ZSTD_BLOCKSIZE_MAX; }
  3282. size_t ZSTD_CStreamOutSize(void)
  3283. {
  3284. return ZSTD_compressBound(ZSTD_BLOCKSIZE_MAX) + ZSTD_blockHeaderSize + 4 /* 32-bits hash */ ;
  3285. }
  3286. static size_t ZSTD_resetCStream_internal(ZSTD_CStream* cctx,
  3287. const void* const dict, size_t const dictSize, ZSTD_dictContentType_e const dictContentType,
  3288. const ZSTD_CDict* const cdict,
  3289. ZSTD_CCtx_params params, unsigned long long const pledgedSrcSize)
  3290. {
  3291. DEBUGLOG(4, "ZSTD_resetCStream_internal");
  3292. /* Finalize the compression parameters */
  3293. params.cParams = ZSTD_getCParamsFromCCtxParams(&params, pledgedSrcSize, dictSize);
  3294. /* params are supposed to be fully validated at this point */
  3295. assert(!ZSTD_isError(ZSTD_checkCParams(params.cParams)));
  3296. assert(!((dict) && (cdict))); /* either dict or cdict, not both */
  3297. CHECK_F( ZSTD_compressBegin_internal(cctx,
  3298. dict, dictSize, dictContentType, ZSTD_dtlm_fast,
  3299. cdict,
  3300. params, pledgedSrcSize,
  3301. ZSTDb_buffered) );
  3302. cctx->inToCompress = 0;
  3303. cctx->inBuffPos = 0;
  3304. cctx->inBuffTarget = cctx->blockSize
  3305. + (cctx->blockSize == pledgedSrcSize); /* for small input: avoid automatic flush on reaching end of block, since it would require to add a 3-bytes null block to end frame */
  3306. cctx->outBuffContentSize = cctx->outBuffFlushedSize = 0;
  3307. cctx->streamStage = zcss_load;
  3308. cctx->frameEnded = 0;
  3309. return 0; /* ready to go */
  3310. }
  3311. /* ZSTD_resetCStream():
  3312. * pledgedSrcSize == 0 means "unknown" */
  3313. size_t ZSTD_resetCStream(ZSTD_CStream* zcs, unsigned long long pledgedSrcSize)
  3314. {
  3315. ZSTD_CCtx_params params = zcs->requestedParams;
  3316. DEBUGLOG(4, "ZSTD_resetCStream: pledgedSrcSize = %u", (unsigned)pledgedSrcSize);
  3317. if (pledgedSrcSize==0) pledgedSrcSize = ZSTD_CONTENTSIZE_UNKNOWN;
  3318. params.fParams.contentSizeFlag = 1;
  3319. return ZSTD_resetCStream_internal(zcs, NULL, 0, ZSTD_dct_auto, zcs->cdict, params, pledgedSrcSize);
  3320. }
  3321. /*! ZSTD_initCStream_internal() :
  3322. * Note : for lib/compress only. Used by zstdmt_compress.c.
  3323. * Assumption 1 : params are valid
  3324. * Assumption 2 : either dict, or cdict, is defined, not both */
  3325. size_t ZSTD_initCStream_internal(ZSTD_CStream* zcs,
  3326. const void* dict, size_t dictSize, const ZSTD_CDict* cdict,
  3327. ZSTD_CCtx_params params, unsigned long long pledgedSrcSize)
  3328. {
  3329. DEBUGLOG(4, "ZSTD_initCStream_internal");
  3330. params.cParams = ZSTD_getCParamsFromCCtxParams(&params, pledgedSrcSize, dictSize);
  3331. assert(!ZSTD_isError(ZSTD_checkCParams(params.cParams)));
  3332. assert(!((dict) && (cdict))); /* either dict or cdict, not both */
  3333. if (dict && dictSize >= 8) {
  3334. DEBUGLOG(4, "loading dictionary of size %u", (unsigned)dictSize);
  3335. if (zcs->staticSize) { /* static CCtx : never uses malloc */
  3336. /* incompatible with internal cdict creation */
  3337. return ERROR(memory_allocation);
  3338. }
  3339. ZSTD_freeCDict(zcs->cdictLocal);
  3340. zcs->cdictLocal = ZSTD_createCDict_advanced(dict, dictSize,
  3341. ZSTD_dlm_byCopy, ZSTD_dct_auto,
  3342. params.cParams, zcs->customMem);
  3343. zcs->cdict = zcs->cdictLocal;
  3344. if (zcs->cdictLocal == NULL) return ERROR(memory_allocation);
  3345. } else {
  3346. if (cdict) {
  3347. params.cParams = ZSTD_getCParamsFromCDict(cdict); /* cParams are enforced from cdict; it includes windowLog */
  3348. }
  3349. ZSTD_freeCDict(zcs->cdictLocal);
  3350. zcs->cdictLocal = NULL;
  3351. zcs->cdict = cdict;
  3352. }
  3353. return ZSTD_resetCStream_internal(zcs, NULL, 0, ZSTD_dct_auto, zcs->cdict, params, pledgedSrcSize);
  3354. }
  3355. /* ZSTD_initCStream_usingCDict_advanced() :
  3356. * same as ZSTD_initCStream_usingCDict(), with control over frame parameters */
  3357. size_t ZSTD_initCStream_usingCDict_advanced(ZSTD_CStream* zcs,
  3358. const ZSTD_CDict* cdict,
  3359. ZSTD_frameParameters fParams,
  3360. unsigned long long pledgedSrcSize)
  3361. {
  3362. DEBUGLOG(4, "ZSTD_initCStream_usingCDict_advanced");
  3363. if (!cdict) return ERROR(dictionary_wrong); /* cannot handle NULL cdict (does not know what to do) */
  3364. { ZSTD_CCtx_params params = zcs->requestedParams;
  3365. params.cParams = ZSTD_getCParamsFromCDict(cdict);
  3366. params.fParams = fParams;
  3367. return ZSTD_initCStream_internal(zcs,
  3368. NULL, 0, cdict,
  3369. params, pledgedSrcSize);
  3370. }
  3371. }
  3372. /* note : cdict must outlive compression session */
  3373. size_t ZSTD_initCStream_usingCDict(ZSTD_CStream* zcs, const ZSTD_CDict* cdict)
  3374. {
  3375. ZSTD_frameParameters const fParams = { 0 /* contentSizeFlag */, 0 /* checksum */, 0 /* hideDictID */ };
  3376. DEBUGLOG(4, "ZSTD_initCStream_usingCDict");
  3377. return ZSTD_initCStream_usingCDict_advanced(zcs, cdict, fParams, ZSTD_CONTENTSIZE_UNKNOWN); /* note : will check that cdict != NULL */
  3378. }
  3379. /* ZSTD_initCStream_advanced() :
  3380. * pledgedSrcSize must be exact.
  3381. * if srcSize is not known at init time, use value ZSTD_CONTENTSIZE_UNKNOWN.
  3382. * dict is loaded with default parameters ZSTD_dm_auto and ZSTD_dlm_byCopy. */
  3383. size_t ZSTD_initCStream_advanced(ZSTD_CStream* zcs,
  3384. const void* dict, size_t dictSize,
  3385. ZSTD_parameters params, unsigned long long pledgedSrcSize)
  3386. {
  3387. DEBUGLOG(4, "ZSTD_initCStream_advanced: pledgedSrcSize=%u, flag=%u",
  3388. (unsigned)pledgedSrcSize, params.fParams.contentSizeFlag);
  3389. CHECK_F( ZSTD_checkCParams(params.cParams) );
  3390. if ((pledgedSrcSize==0) && (params.fParams.contentSizeFlag==0)) pledgedSrcSize = ZSTD_CONTENTSIZE_UNKNOWN; /* for compatibility with older programs relying on this behavior. Users should now specify ZSTD_CONTENTSIZE_UNKNOWN. This line will be removed in the future. */
  3391. zcs->requestedParams = ZSTD_assignParamsToCCtxParams(zcs->requestedParams, params);
  3392. return ZSTD_initCStream_internal(zcs, dict, dictSize, NULL /*cdict*/, zcs->requestedParams, pledgedSrcSize);
  3393. }
  3394. size_t ZSTD_initCStream_usingDict(ZSTD_CStream* zcs, const void* dict, size_t dictSize, int compressionLevel)
  3395. {
  3396. ZSTD_CCtxParams_init(&zcs->requestedParams, compressionLevel);
  3397. return ZSTD_initCStream_internal(zcs, dict, dictSize, NULL, zcs->requestedParams, ZSTD_CONTENTSIZE_UNKNOWN);
  3398. }
  3399. size_t ZSTD_initCStream_srcSize(ZSTD_CStream* zcs, int compressionLevel, unsigned long long pss)
  3400. {
  3401. U64 const pledgedSrcSize = (pss==0) ? ZSTD_CONTENTSIZE_UNKNOWN : pss; /* temporary : 0 interpreted as "unknown" during transition period. Users willing to specify "unknown" **must** use ZSTD_CONTENTSIZE_UNKNOWN. `0` will be interpreted as "empty" in the future */
  3402. ZSTD_CCtxParams_init(&zcs->requestedParams, compressionLevel);
  3403. return ZSTD_initCStream_internal(zcs, NULL, 0, NULL, zcs->requestedParams, pledgedSrcSize);
  3404. }
  3405. size_t ZSTD_initCStream(ZSTD_CStream* zcs, int compressionLevel)
  3406. {
  3407. DEBUGLOG(4, "ZSTD_initCStream");
  3408. return ZSTD_initCStream_srcSize(zcs, compressionLevel, ZSTD_CONTENTSIZE_UNKNOWN);
  3409. }
  3410. /*====== Compression ======*/
  3411. static size_t ZSTD_nextInputSizeHint(const ZSTD_CCtx* cctx)
  3412. {
  3413. size_t hintInSize = cctx->inBuffTarget - cctx->inBuffPos;
  3414. if (hintInSize==0) hintInSize = cctx->blockSize;
  3415. return hintInSize;
  3416. }
  3417. static size_t ZSTD_limitCopy(void* dst, size_t dstCapacity,
  3418. const void* src, size_t srcSize)
  3419. {
  3420. size_t const length = MIN(dstCapacity, srcSize);
  3421. if (length) memcpy(dst, src, length);
  3422. return length;
  3423. }
  3424. /** ZSTD_compressStream_generic():
  3425. * internal function for all *compressStream*() variants
  3426. * non-static, because can be called from zstdmt_compress.c
  3427. * @return : hint size for next input */
  3428. size_t ZSTD_compressStream_generic(ZSTD_CStream* zcs,
  3429. ZSTD_outBuffer* output,
  3430. ZSTD_inBuffer* input,
  3431. ZSTD_EndDirective const flushMode)
  3432. {
  3433. const char* const istart = (const char*)input->src;
  3434. const char* const iend = istart + input->size;
  3435. const char* ip = istart + input->pos;
  3436. char* const ostart = (char*)output->dst;
  3437. char* const oend = ostart + output->size;
  3438. char* op = ostart + output->pos;
  3439. U32 someMoreWork = 1;
  3440. /* check expectations */
  3441. DEBUGLOG(5, "ZSTD_compressStream_generic, flush=%u", (unsigned)flushMode);
  3442. assert(zcs->inBuff != NULL);
  3443. assert(zcs->inBuffSize > 0);
  3444. assert(zcs->outBuff != NULL);
  3445. assert(zcs->outBuffSize > 0);
  3446. assert(output->pos <= output->size);
  3447. assert(input->pos <= input->size);
  3448. while (someMoreWork) {
  3449. switch(zcs->streamStage)
  3450. {
  3451. case zcss_init:
  3452. /* call ZSTD_initCStream() first ! */
  3453. return ERROR(init_missing);
  3454. case zcss_load:
  3455. if ( (flushMode == ZSTD_e_end)
  3456. && ((size_t)(oend-op) >= ZSTD_compressBound(iend-ip)) /* enough dstCapacity */
  3457. && (zcs->inBuffPos == 0) ) {
  3458. /* shortcut to compression pass directly into output buffer */
  3459. size_t const cSize = ZSTD_compressEnd(zcs,
  3460. op, oend-op, ip, iend-ip);
  3461. DEBUGLOG(4, "ZSTD_compressEnd : cSize=%u", (unsigned)cSize);
  3462. if (ZSTD_isError(cSize)) return cSize;
  3463. ip = iend;
  3464. op += cSize;
  3465. zcs->frameEnded = 1;
  3466. ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only);
  3467. someMoreWork = 0; break;
  3468. }
  3469. /* complete loading into inBuffer */
  3470. { size_t const toLoad = zcs->inBuffTarget - zcs->inBuffPos;
  3471. size_t const loaded = ZSTD_limitCopy(
  3472. zcs->inBuff + zcs->inBuffPos, toLoad,
  3473. ip, iend-ip);
  3474. zcs->inBuffPos += loaded;
  3475. ip += loaded;
  3476. if ( (flushMode == ZSTD_e_continue)
  3477. && (zcs->inBuffPos < zcs->inBuffTarget) ) {
  3478. /* not enough input to fill full block : stop here */
  3479. someMoreWork = 0; break;
  3480. }
  3481. if ( (flushMode == ZSTD_e_flush)
  3482. && (zcs->inBuffPos == zcs->inToCompress) ) {
  3483. /* empty */
  3484. someMoreWork = 0; break;
  3485. }
  3486. }
  3487. /* compress current block (note : this stage cannot be stopped in the middle) */
  3488. DEBUGLOG(5, "stream compression stage (flushMode==%u)", flushMode);
  3489. { void* cDst;
  3490. size_t cSize;
  3491. size_t const iSize = zcs->inBuffPos - zcs->inToCompress;
  3492. size_t oSize = oend-op;
  3493. unsigned const lastBlock = (flushMode == ZSTD_e_end) && (ip==iend);
  3494. if (oSize >= ZSTD_compressBound(iSize))
  3495. cDst = op; /* compress into output buffer, to skip flush stage */
  3496. else
  3497. cDst = zcs->outBuff, oSize = zcs->outBuffSize;
  3498. cSize = lastBlock ?
  3499. ZSTD_compressEnd(zcs, cDst, oSize,
  3500. zcs->inBuff + zcs->inToCompress, iSize) :
  3501. ZSTD_compressContinue(zcs, cDst, oSize,
  3502. zcs->inBuff + zcs->inToCompress, iSize);
  3503. if (ZSTD_isError(cSize)) return cSize;
  3504. zcs->frameEnded = lastBlock;
  3505. /* prepare next block */
  3506. zcs->inBuffTarget = zcs->inBuffPos + zcs->blockSize;
  3507. if (zcs->inBuffTarget > zcs->inBuffSize)
  3508. zcs->inBuffPos = 0, zcs->inBuffTarget = zcs->blockSize;
  3509. DEBUGLOG(5, "inBuffTarget:%u / inBuffSize:%u",
  3510. (unsigned)zcs->inBuffTarget, (unsigned)zcs->inBuffSize);
  3511. if (!lastBlock)
  3512. assert(zcs->inBuffTarget <= zcs->inBuffSize);
  3513. zcs->inToCompress = zcs->inBuffPos;
  3514. if (cDst == op) { /* no need to flush */
  3515. op += cSize;
  3516. if (zcs->frameEnded) {
  3517. DEBUGLOG(5, "Frame completed directly in outBuffer");
  3518. someMoreWork = 0;
  3519. ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only);
  3520. }
  3521. break;
  3522. }
  3523. zcs->outBuffContentSize = cSize;
  3524. zcs->outBuffFlushedSize = 0;
  3525. zcs->streamStage = zcss_flush; /* pass-through to flush stage */
  3526. }
  3527. /* fall-through */
  3528. case zcss_flush:
  3529. DEBUGLOG(5, "flush stage");
  3530. { size_t const toFlush = zcs->outBuffContentSize - zcs->outBuffFlushedSize;
  3531. size_t const flushed = ZSTD_limitCopy(op, oend-op,
  3532. zcs->outBuff + zcs->outBuffFlushedSize, toFlush);
  3533. DEBUGLOG(5, "toFlush: %u into %u ==> flushed: %u",
  3534. (unsigned)toFlush, (unsigned)(oend-op), (unsigned)flushed);
  3535. op += flushed;
  3536. zcs->outBuffFlushedSize += flushed;
  3537. if (toFlush!=flushed) {
  3538. /* flush not fully completed, presumably because dst is too small */
  3539. assert(op==oend);
  3540. someMoreWork = 0;
  3541. break;
  3542. }
  3543. zcs->outBuffContentSize = zcs->outBuffFlushedSize = 0;
  3544. if (zcs->frameEnded) {
  3545. DEBUGLOG(5, "Frame completed on flush");
  3546. someMoreWork = 0;
  3547. ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only);
  3548. break;
  3549. }
  3550. zcs->streamStage = zcss_load;
  3551. break;
  3552. }
  3553. default: /* impossible */
  3554. assert(0);
  3555. }
  3556. }
  3557. input->pos = ip - istart;
  3558. output->pos = op - ostart;
  3559. if (zcs->frameEnded) return 0;
  3560. return ZSTD_nextInputSizeHint(zcs);
  3561. }
  3562. static size_t ZSTD_nextInputSizeHint_MTorST(const ZSTD_CCtx* cctx)
  3563. {
  3564. #ifdef ZSTD_MULTITHREAD
  3565. if (cctx->appliedParams.nbWorkers >= 1) {
  3566. assert(cctx->mtctx != NULL);
  3567. return ZSTDMT_nextInputSizeHint(cctx->mtctx);
  3568. }
  3569. #endif
  3570. return ZSTD_nextInputSizeHint(cctx);
  3571. }
  3572. size_t ZSTD_compressStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output, ZSTD_inBuffer* input)
  3573. {
  3574. CHECK_F( ZSTD_compressStream2(zcs, output, input, ZSTD_e_continue) );
  3575. return ZSTD_nextInputSizeHint_MTorST(zcs);
  3576. }
  3577. size_t ZSTD_compressStream2( ZSTD_CCtx* cctx,
  3578. ZSTD_outBuffer* output,
  3579. ZSTD_inBuffer* input,
  3580. ZSTD_EndDirective endOp)
  3581. {
  3582. DEBUGLOG(5, "ZSTD_compressStream2, endOp=%u ", (unsigned)endOp);
  3583. /* check conditions */
  3584. if (output->pos > output->size) return ERROR(GENERIC);
  3585. if (input->pos > input->size) return ERROR(GENERIC);
  3586. assert(cctx!=NULL);
  3587. /* transparent initialization stage */
  3588. if (cctx->streamStage == zcss_init) {
  3589. ZSTD_CCtx_params params = cctx->requestedParams;
  3590. ZSTD_prefixDict const prefixDict = cctx->prefixDict;
  3591. memset(&cctx->prefixDict, 0, sizeof(cctx->prefixDict)); /* single usage */
  3592. assert(prefixDict.dict==NULL || cctx->cdict==NULL); /* only one can be set */
  3593. DEBUGLOG(4, "ZSTD_compressStream2 : transparent init stage");
  3594. if (endOp == ZSTD_e_end) cctx->pledgedSrcSizePlusOne = input->size + 1; /* auto-fix pledgedSrcSize */
  3595. params.cParams = ZSTD_getCParamsFromCCtxParams(
  3596. &cctx->requestedParams, cctx->pledgedSrcSizePlusOne-1, 0 /*dictSize*/);
  3597. #ifdef ZSTD_MULTITHREAD
  3598. if ((cctx->pledgedSrcSizePlusOne-1) <= ZSTDMT_JOBSIZE_MIN) {
  3599. params.nbWorkers = 0; /* do not invoke multi-threading when src size is too small */
  3600. }
  3601. if (params.nbWorkers > 0) {
  3602. /* mt context creation */
  3603. if (cctx->mtctx == NULL) {
  3604. DEBUGLOG(4, "ZSTD_compressStream2: creating new mtctx for nbWorkers=%u",
  3605. params.nbWorkers);
  3606. cctx->mtctx = ZSTDMT_createCCtx_advanced(params.nbWorkers, cctx->customMem);
  3607. if (cctx->mtctx == NULL) return ERROR(memory_allocation);
  3608. }
  3609. /* mt compression */
  3610. DEBUGLOG(4, "call ZSTDMT_initCStream_internal as nbWorkers=%u", params.nbWorkers);
  3611. CHECK_F( ZSTDMT_initCStream_internal(
  3612. cctx->mtctx,
  3613. prefixDict.dict, prefixDict.dictSize, ZSTD_dct_rawContent,
  3614. cctx->cdict, params, cctx->pledgedSrcSizePlusOne-1) );
  3615. cctx->streamStage = zcss_load;
  3616. cctx->appliedParams.nbWorkers = params.nbWorkers;
  3617. } else
  3618. #endif
  3619. { CHECK_F( ZSTD_resetCStream_internal(cctx,
  3620. prefixDict.dict, prefixDict.dictSize, prefixDict.dictContentType,
  3621. cctx->cdict,
  3622. params, cctx->pledgedSrcSizePlusOne-1) );
  3623. assert(cctx->streamStage == zcss_load);
  3624. assert(cctx->appliedParams.nbWorkers == 0);
  3625. } }
  3626. /* end of transparent initialization stage */
  3627. /* compression stage */
  3628. #ifdef ZSTD_MULTITHREAD
  3629. if (cctx->appliedParams.nbWorkers > 0) {
  3630. if (cctx->cParamsChanged) {
  3631. ZSTDMT_updateCParams_whileCompressing(cctx->mtctx, &cctx->requestedParams);
  3632. cctx->cParamsChanged = 0;
  3633. }
  3634. { size_t const flushMin = ZSTDMT_compressStream_generic(cctx->mtctx, output, input, endOp);
  3635. if ( ZSTD_isError(flushMin)
  3636. || (endOp == ZSTD_e_end && flushMin == 0) ) { /* compression completed */
  3637. ZSTD_CCtx_reset(cctx, ZSTD_reset_session_only);
  3638. }
  3639. DEBUGLOG(5, "completed ZSTD_compressStream2 delegating to ZSTDMT_compressStream_generic");
  3640. return flushMin;
  3641. } }
  3642. #endif
  3643. CHECK_F( ZSTD_compressStream_generic(cctx, output, input, endOp) );
  3644. DEBUGLOG(5, "completed ZSTD_compressStream2");
  3645. return cctx->outBuffContentSize - cctx->outBuffFlushedSize; /* remaining to flush */
  3646. }
  3647. size_t ZSTD_compressStream2_simpleArgs (
  3648. ZSTD_CCtx* cctx,
  3649. void* dst, size_t dstCapacity, size_t* dstPos,
  3650. const void* src, size_t srcSize, size_t* srcPos,
  3651. ZSTD_EndDirective endOp)
  3652. {
  3653. ZSTD_outBuffer output = { dst, dstCapacity, *dstPos };
  3654. ZSTD_inBuffer input = { src, srcSize, *srcPos };
  3655. /* ZSTD_compressStream2() will check validity of dstPos and srcPos */
  3656. size_t const cErr = ZSTD_compressStream2(cctx, &output, &input, endOp);
  3657. *dstPos = output.pos;
  3658. *srcPos = input.pos;
  3659. return cErr;
  3660. }
  3661. size_t ZSTD_compress2(ZSTD_CCtx* cctx,
  3662. void* dst, size_t dstCapacity,
  3663. const void* src, size_t srcSize)
  3664. {
  3665. ZSTD_CCtx_reset(cctx, ZSTD_reset_session_only);
  3666. { size_t oPos = 0;
  3667. size_t iPos = 0;
  3668. size_t const result = ZSTD_compressStream2_simpleArgs(cctx,
  3669. dst, dstCapacity, &oPos,
  3670. src, srcSize, &iPos,
  3671. ZSTD_e_end);
  3672. if (ZSTD_isError(result)) return result;
  3673. if (result != 0) { /* compression not completed, due to lack of output space */
  3674. assert(oPos == dstCapacity);
  3675. return ERROR(dstSize_tooSmall);
  3676. }
  3677. assert(iPos == srcSize); /* all input is expected consumed */
  3678. return oPos;
  3679. }
  3680. }
  3681. /*====== Finalize ======*/
  3682. /*! ZSTD_flushStream() :
  3683. * @return : amount of data remaining to flush */
  3684. size_t ZSTD_flushStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output)
  3685. {
  3686. ZSTD_inBuffer input = { NULL, 0, 0 };
  3687. return ZSTD_compressStream2(zcs, output, &input, ZSTD_e_flush);
  3688. }
  3689. size_t ZSTD_endStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output)
  3690. {
  3691. ZSTD_inBuffer input = { NULL, 0, 0 };
  3692. size_t const remainingToFlush = ZSTD_compressStream2(zcs, output, &input, ZSTD_e_end);
  3693. CHECK_F( remainingToFlush );
  3694. if (zcs->appliedParams.nbWorkers > 0) return remainingToFlush; /* minimal estimation */
  3695. /* single thread mode : attempt to calculate remaining to flush more precisely */
  3696. { size_t const lastBlockSize = zcs->frameEnded ? 0 : ZSTD_BLOCKHEADERSIZE;
  3697. size_t const checksumSize = zcs->frameEnded ? 0 : zcs->appliedParams.fParams.checksumFlag * 4;
  3698. size_t const toFlush = remainingToFlush + lastBlockSize + checksumSize;
  3699. DEBUGLOG(4, "ZSTD_endStream : remaining to flush : %u", (unsigned)toFlush);
  3700. return toFlush;
  3701. }
  3702. }
  3703. /*-===== Pre-defined compression levels =====-*/
  3704. #define ZSTD_MAX_CLEVEL 22
  3705. int ZSTD_maxCLevel(void) { return ZSTD_MAX_CLEVEL; }
  3706. int ZSTD_minCLevel(void) { return (int)-ZSTD_TARGETLENGTH_MAX; }
  3707. static const ZSTD_compressionParameters ZSTD_defaultCParameters[4][ZSTD_MAX_CLEVEL+1] = {
  3708. { /* "default" - guarantees a monotonically increasing memory budget */
  3709. /* W, C, H, S, L, TL, strat */
  3710. { 19, 12, 13, 1, 6, 1, ZSTD_fast }, /* base for negative levels */
  3711. { 19, 13, 14, 1, 7, 0, ZSTD_fast }, /* level 1 */
  3712. { 20, 15, 16, 1, 6, 0, ZSTD_fast }, /* level 2 */
  3713. { 21, 16, 17, 1, 5, 1, ZSTD_dfast }, /* level 3 */
  3714. { 21, 18, 18, 1, 5, 1, ZSTD_dfast }, /* level 4 */
  3715. { 21, 18, 19, 2, 5, 2, ZSTD_greedy }, /* level 5 */
  3716. { 21, 19, 19, 3, 5, 4, ZSTD_greedy }, /* level 6 */
  3717. { 21, 19, 19, 3, 5, 8, ZSTD_lazy }, /* level 7 */
  3718. { 21, 19, 19, 3, 5, 16, ZSTD_lazy2 }, /* level 8 */
  3719. { 21, 19, 20, 4, 5, 16, ZSTD_lazy2 }, /* level 9 */
  3720. { 22, 20, 21, 4, 5, 16, ZSTD_lazy2 }, /* level 10 */
  3721. { 22, 21, 22, 4, 5, 16, ZSTD_lazy2 }, /* level 11 */
  3722. { 22, 21, 22, 5, 5, 16, ZSTD_lazy2 }, /* level 12 */
  3723. { 22, 21, 22, 5, 5, 32, ZSTD_btlazy2 }, /* level 13 */
  3724. { 22, 22, 23, 5, 5, 32, ZSTD_btlazy2 }, /* level 14 */
  3725. { 22, 23, 23, 6, 5, 32, ZSTD_btlazy2 }, /* level 15 */
  3726. { 22, 22, 22, 5, 5, 48, ZSTD_btopt }, /* level 16 */
  3727. { 23, 23, 22, 5, 4, 64, ZSTD_btopt }, /* level 17 */
  3728. { 23, 23, 22, 6, 3, 64, ZSTD_btultra }, /* level 18 */
  3729. { 23, 24, 22, 7, 3,256, ZSTD_btultra2}, /* level 19 */
  3730. { 25, 25, 23, 7, 3,256, ZSTD_btultra2}, /* level 20 */
  3731. { 26, 26, 24, 7, 3,512, ZSTD_btultra2}, /* level 21 */
  3732. { 27, 27, 25, 9, 3,999, ZSTD_btultra2}, /* level 22 */
  3733. },
  3734. { /* for srcSize <= 256 KB */
  3735. /* W, C, H, S, L, T, strat */
  3736. { 18, 12, 13, 1, 5, 1, ZSTD_fast }, /* base for negative levels */
  3737. { 18, 13, 14, 1, 6, 0, ZSTD_fast }, /* level 1 */
  3738. { 18, 14, 14, 1, 5, 1, ZSTD_dfast }, /* level 2 */
  3739. { 18, 16, 16, 1, 4, 1, ZSTD_dfast }, /* level 3 */
  3740. { 18, 16, 17, 2, 5, 2, ZSTD_greedy }, /* level 4.*/
  3741. { 18, 18, 18, 3, 5, 2, ZSTD_greedy }, /* level 5.*/
  3742. { 18, 18, 19, 3, 5, 4, ZSTD_lazy }, /* level 6.*/
  3743. { 18, 18, 19, 4, 4, 4, ZSTD_lazy }, /* level 7 */
  3744. { 18, 18, 19, 4, 4, 8, ZSTD_lazy2 }, /* level 8 */
  3745. { 18, 18, 19, 5, 4, 8, ZSTD_lazy2 }, /* level 9 */
  3746. { 18, 18, 19, 6, 4, 8, ZSTD_lazy2 }, /* level 10 */
  3747. { 18, 18, 19, 5, 4, 12, ZSTD_btlazy2 }, /* level 11.*/
  3748. { 18, 19, 19, 7, 4, 12, ZSTD_btlazy2 }, /* level 12.*/
  3749. { 18, 18, 19, 4, 4, 16, ZSTD_btopt }, /* level 13 */
  3750. { 18, 18, 19, 4, 3, 32, ZSTD_btopt }, /* level 14.*/
  3751. { 18, 18, 19, 6, 3,128, ZSTD_btopt }, /* level 15.*/
  3752. { 18, 19, 19, 6, 3,128, ZSTD_btultra }, /* level 16.*/
  3753. { 18, 19, 19, 8, 3,256, ZSTD_btultra }, /* level 17.*/
  3754. { 18, 19, 19, 6, 3,128, ZSTD_btultra2}, /* level 18.*/
  3755. { 18, 19, 19, 8, 3,256, ZSTD_btultra2}, /* level 19.*/
  3756. { 18, 19, 19, 10, 3,512, ZSTD_btultra2}, /* level 20.*/
  3757. { 18, 19, 19, 12, 3,512, ZSTD_btultra2}, /* level 21.*/
  3758. { 18, 19, 19, 13, 3,999, ZSTD_btultra2}, /* level 22.*/
  3759. },
  3760. { /* for srcSize <= 128 KB */
  3761. /* W, C, H, S, L, T, strat */
  3762. { 17, 12, 12, 1, 5, 1, ZSTD_fast }, /* base for negative levels */
  3763. { 17, 12, 13, 1, 6, 0, ZSTD_fast }, /* level 1 */
  3764. { 17, 13, 15, 1, 5, 0, ZSTD_fast }, /* level 2 */
  3765. { 17, 15, 16, 2, 5, 1, ZSTD_dfast }, /* level 3 */
  3766. { 17, 17, 17, 2, 4, 1, ZSTD_dfast }, /* level 4 */
  3767. { 17, 16, 17, 3, 4, 2, ZSTD_greedy }, /* level 5 */
  3768. { 17, 17, 17, 3, 4, 4, ZSTD_lazy }, /* level 6 */
  3769. { 17, 17, 17, 3, 4, 8, ZSTD_lazy2 }, /* level 7 */
  3770. { 17, 17, 17, 4, 4, 8, ZSTD_lazy2 }, /* level 8 */
  3771. { 17, 17, 17, 5, 4, 8, ZSTD_lazy2 }, /* level 9 */
  3772. { 17, 17, 17, 6, 4, 8, ZSTD_lazy2 }, /* level 10 */
  3773. { 17, 17, 17, 5, 4, 8, ZSTD_btlazy2 }, /* level 11 */
  3774. { 17, 18, 17, 7, 4, 12, ZSTD_btlazy2 }, /* level 12 */
  3775. { 17, 18, 17, 3, 4, 12, ZSTD_btopt }, /* level 13.*/
  3776. { 17, 18, 17, 4, 3, 32, ZSTD_btopt }, /* level 14.*/
  3777. { 17, 18, 17, 6, 3,256, ZSTD_btopt }, /* level 15.*/
  3778. { 17, 18, 17, 6, 3,128, ZSTD_btultra }, /* level 16.*/
  3779. { 17, 18, 17, 8, 3,256, ZSTD_btultra }, /* level 17.*/
  3780. { 17, 18, 17, 10, 3,512, ZSTD_btultra }, /* level 18.*/
  3781. { 17, 18, 17, 5, 3,256, ZSTD_btultra2}, /* level 19.*/
  3782. { 17, 18, 17, 7, 3,512, ZSTD_btultra2}, /* level 20.*/
  3783. { 17, 18, 17, 9, 3,512, ZSTD_btultra2}, /* level 21.*/
  3784. { 17, 18, 17, 11, 3,999, ZSTD_btultra2}, /* level 22.*/
  3785. },
  3786. { /* for srcSize <= 16 KB */
  3787. /* W, C, H, S, L, T, strat */
  3788. { 14, 12, 13, 1, 5, 1, ZSTD_fast }, /* base for negative levels */
  3789. { 14, 14, 15, 1, 5, 0, ZSTD_fast }, /* level 1 */
  3790. { 14, 14, 15, 1, 4, 0, ZSTD_fast }, /* level 2 */
  3791. { 14, 14, 15, 2, 4, 1, ZSTD_dfast }, /* level 3 */
  3792. { 14, 14, 14, 4, 4, 2, ZSTD_greedy }, /* level 4 */
  3793. { 14, 14, 14, 3, 4, 4, ZSTD_lazy }, /* level 5.*/
  3794. { 14, 14, 14, 4, 4, 8, ZSTD_lazy2 }, /* level 6 */
  3795. { 14, 14, 14, 6, 4, 8, ZSTD_lazy2 }, /* level 7 */
  3796. { 14, 14, 14, 8, 4, 8, ZSTD_lazy2 }, /* level 8.*/
  3797. { 14, 15, 14, 5, 4, 8, ZSTD_btlazy2 }, /* level 9.*/
  3798. { 14, 15, 14, 9, 4, 8, ZSTD_btlazy2 }, /* level 10.*/
  3799. { 14, 15, 14, 3, 4, 12, ZSTD_btopt }, /* level 11.*/
  3800. { 14, 15, 14, 4, 3, 24, ZSTD_btopt }, /* level 12.*/
  3801. { 14, 15, 14, 5, 3, 32, ZSTD_btultra }, /* level 13.*/
  3802. { 14, 15, 15, 6, 3, 64, ZSTD_btultra }, /* level 14.*/
  3803. { 14, 15, 15, 7, 3,256, ZSTD_btultra }, /* level 15.*/
  3804. { 14, 15, 15, 5, 3, 48, ZSTD_btultra2}, /* level 16.*/
  3805. { 14, 15, 15, 6, 3,128, ZSTD_btultra2}, /* level 17.*/
  3806. { 14, 15, 15, 7, 3,256, ZSTD_btultra2}, /* level 18.*/
  3807. { 14, 15, 15, 8, 3,256, ZSTD_btultra2}, /* level 19.*/
  3808. { 14, 15, 15, 8, 3,512, ZSTD_btultra2}, /* level 20.*/
  3809. { 14, 15, 15, 9, 3,512, ZSTD_btultra2}, /* level 21.*/
  3810. { 14, 15, 15, 10, 3,999, ZSTD_btultra2}, /* level 22.*/
  3811. },
  3812. };
  3813. /*! ZSTD_getCParams() :
  3814. * @return ZSTD_compressionParameters structure for a selected compression level, srcSize and dictSize.
  3815. * Size values are optional, provide 0 if not known or unused */
  3816. ZSTD_compressionParameters ZSTD_getCParams(int compressionLevel, unsigned long long srcSizeHint, size_t dictSize)
  3817. {
  3818. size_t const addedSize = srcSizeHint ? 0 : 500;
  3819. U64 const rSize = srcSizeHint+dictSize ? srcSizeHint+dictSize+addedSize : (U64)-1;
  3820. U32 const tableID = (rSize <= 256 KB) + (rSize <= 128 KB) + (rSize <= 16 KB); /* intentional underflow for srcSizeHint == 0 */
  3821. int row = compressionLevel;
  3822. DEBUGLOG(5, "ZSTD_getCParams (cLevel=%i)", compressionLevel);
  3823. if (compressionLevel == 0) row = ZSTD_CLEVEL_DEFAULT; /* 0 == default */
  3824. if (compressionLevel < 0) row = 0; /* entry 0 is baseline for fast mode */
  3825. if (compressionLevel > ZSTD_MAX_CLEVEL) row = ZSTD_MAX_CLEVEL;
  3826. { ZSTD_compressionParameters cp = ZSTD_defaultCParameters[tableID][row];
  3827. if (compressionLevel < 0) cp.targetLength = (unsigned)(-compressionLevel); /* acceleration factor */
  3828. return ZSTD_adjustCParams_internal(cp, srcSizeHint, dictSize);
  3829. }
  3830. }
  3831. /*! ZSTD_getParams() :
  3832. * same as ZSTD_getCParams(), but @return a `ZSTD_parameters` object (instead of `ZSTD_compressionParameters`).
  3833. * All fields of `ZSTD_frameParameters` are set to default (0) */
  3834. ZSTD_parameters ZSTD_getParams(int compressionLevel, unsigned long long srcSizeHint, size_t dictSize) {
  3835. ZSTD_parameters params;
  3836. ZSTD_compressionParameters const cParams = ZSTD_getCParams(compressionLevel, srcSizeHint, dictSize);
  3837. DEBUGLOG(5, "ZSTD_getParams (cLevel=%i)", compressionLevel);
  3838. memset(&params, 0, sizeof(params));
  3839. params.cParams = cParams;
  3840. params.fParams.contentSizeFlag = 1;
  3841. return params;
  3842. }