You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

zstd_compress.c 124KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963
  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. * Tuning parameters
  12. ***************************************/
  13. #ifndef ZSTD_CLEVEL_DEFAULT
  14. # define ZSTD_CLEVEL_DEFAULT 3
  15. #endif
  16. /*-*************************************
  17. * Dependencies
  18. ***************************************/
  19. #include <string.h> /* memset */
  20. #include "mem.h"
  21. #define FSE_STATIC_LINKING_ONLY /* FSE_encodeSymbol */
  22. #include "fse.h"
  23. #define HUF_STATIC_LINKING_ONLY
  24. #include "huf.h"
  25. #include "zstd_compress.h"
  26. #include "zstd_fast.h"
  27. #include "zstd_double_fast.h"
  28. #include "zstd_lazy.h"
  29. #include "zstd_opt.h"
  30. #include "zstd_ldm.h"
  31. /*-*************************************
  32. * Helper functions
  33. ***************************************/
  34. size_t ZSTD_compressBound(size_t srcSize) {
  35. size_t const lowLimit = 256 KB;
  36. size_t const margin = (srcSize < lowLimit) ? (lowLimit-srcSize) >> 12 : 0; /* from 64 to 0 */
  37. return srcSize + (srcSize >> 8) + margin;
  38. }
  39. /*-*************************************
  40. * Sequence storage
  41. ***************************************/
  42. static void ZSTD_resetSeqStore(seqStore_t* ssPtr)
  43. {
  44. ssPtr->lit = ssPtr->litStart;
  45. ssPtr->sequences = ssPtr->sequencesStart;
  46. ssPtr->longLengthID = 0;
  47. }
  48. /*-*************************************
  49. * Context memory management
  50. ***************************************/
  51. struct ZSTD_CDict_s {
  52. void* dictBuffer;
  53. const void* dictContent;
  54. size_t dictContentSize;
  55. ZSTD_CCtx* refContext;
  56. }; /* typedef'd to ZSTD_CDict within "zstd.h" */
  57. ZSTD_CCtx* ZSTD_createCCtx(void)
  58. {
  59. return ZSTD_createCCtx_advanced(ZSTD_defaultCMem);
  60. }
  61. ZSTD_CCtx* ZSTD_createCCtx_advanced(ZSTD_customMem customMem)
  62. {
  63. ZSTD_CCtx* cctx;
  64. if (!customMem.customAlloc ^ !customMem.customFree) return NULL;
  65. cctx = (ZSTD_CCtx*) ZSTD_calloc(sizeof(ZSTD_CCtx), customMem);
  66. if (!cctx) return NULL;
  67. cctx->customMem = customMem;
  68. cctx->requestedParams.compressionLevel = ZSTD_CLEVEL_DEFAULT;
  69. ZSTD_STATIC_ASSERT(zcss_init==0);
  70. ZSTD_STATIC_ASSERT(ZSTD_CONTENTSIZE_UNKNOWN==(0ULL - 1));
  71. return cctx;
  72. }
  73. ZSTD_CCtx* ZSTD_initStaticCCtx(void *workspace, size_t workspaceSize)
  74. {
  75. ZSTD_CCtx* const cctx = (ZSTD_CCtx*) workspace;
  76. if (workspaceSize <= sizeof(ZSTD_CCtx)) return NULL; /* minimum size */
  77. if ((size_t)workspace & 7) return NULL; /* must be 8-aligned */
  78. memset(workspace, 0, workspaceSize); /* may be a bit generous, could memset be smaller ? */
  79. cctx->staticSize = workspaceSize;
  80. cctx->workSpace = (void*)(cctx+1);
  81. cctx->workSpaceSize = workspaceSize - sizeof(ZSTD_CCtx);
  82. /* entropy space (never moves) */
  83. if (cctx->workSpaceSize < sizeof(ZSTD_entropyCTables_t)) return NULL;
  84. assert(((size_t)cctx->workSpace & (sizeof(void*)-1)) == 0); /* ensure correct alignment */
  85. cctx->entropy = (ZSTD_entropyCTables_t*)cctx->workSpace;
  86. return cctx;
  87. }
  88. size_t ZSTD_freeCCtx(ZSTD_CCtx* cctx)
  89. {
  90. if (cctx==NULL) return 0; /* support free on NULL */
  91. if (cctx->staticSize) return ERROR(memory_allocation); /* not compatible with static CCtx */
  92. ZSTD_free(cctx->workSpace, cctx->customMem);
  93. cctx->workSpace = NULL;
  94. ZSTD_freeCDict(cctx->cdictLocal);
  95. cctx->cdictLocal = NULL;
  96. #ifdef ZSTD_MULTITHREAD
  97. ZSTDMT_freeCCtx(cctx->mtctx);
  98. cctx->mtctx = NULL;
  99. #endif
  100. ZSTD_free(cctx, cctx->customMem);
  101. return 0; /* reserved as a potential error code in the future */
  102. }
  103. static size_t ZSTD_sizeof_mtctx(const ZSTD_CCtx* cctx)
  104. {
  105. #ifdef ZSTD_MULTITHREAD
  106. return ZSTDMT_sizeof_CCtx(cctx->mtctx);
  107. #else
  108. (void) cctx;
  109. return 0;
  110. #endif
  111. }
  112. size_t ZSTD_sizeof_CCtx(const ZSTD_CCtx* cctx)
  113. {
  114. if (cctx==NULL) return 0; /* support sizeof on NULL */
  115. DEBUGLOG(3, "sizeof(*cctx) : %u", (U32)sizeof(*cctx));
  116. DEBUGLOG(3, "workSpaceSize (including streaming buffers): %u", (U32)cctx->workSpaceSize);
  117. DEBUGLOG(3, "inner cdict : %u", (U32)ZSTD_sizeof_CDict(cctx->cdictLocal));
  118. DEBUGLOG(3, "inner MTCTX : %u", (U32)ZSTD_sizeof_mtctx(cctx));
  119. return sizeof(*cctx) + cctx->workSpaceSize
  120. + ZSTD_sizeof_CDict(cctx->cdictLocal)
  121. + ZSTD_sizeof_mtctx(cctx);
  122. }
  123. size_t ZSTD_sizeof_CStream(const ZSTD_CStream* zcs)
  124. {
  125. return ZSTD_sizeof_CCtx(zcs); /* same object */
  126. }
  127. /* private API call, for dictBuilder only */
  128. const seqStore_t* ZSTD_getSeqStore(const ZSTD_CCtx* ctx) { return &(ctx->seqStore); }
  129. #define ZSTD_CLEVEL_CUSTOM 999
  130. static ZSTD_compressionParameters ZSTD_getCParamsFromCCtxParams(
  131. ZSTD_CCtx_params params, U64 srcSizeHint, size_t dictSize)
  132. {
  133. return (params.compressionLevel == ZSTD_CLEVEL_CUSTOM ?
  134. params.cParams :
  135. ZSTD_getCParams(params.compressionLevel, srcSizeHint, dictSize));
  136. }
  137. static void ZSTD_cLevelToCCtxParams_srcSize(ZSTD_CCtx_params* params, U64 srcSize)
  138. {
  139. params->cParams = ZSTD_getCParamsFromCCtxParams(*params, srcSize, 0);
  140. params->compressionLevel = ZSTD_CLEVEL_CUSTOM;
  141. }
  142. static void ZSTD_cLevelToCParams(ZSTD_CCtx* cctx)
  143. {
  144. ZSTD_cLevelToCCtxParams_srcSize(
  145. &cctx->requestedParams, cctx->pledgedSrcSizePlusOne-1);
  146. }
  147. static void ZSTD_cLevelToCCtxParams(ZSTD_CCtx_params* params)
  148. {
  149. ZSTD_cLevelToCCtxParams_srcSize(params, 0);
  150. }
  151. static ZSTD_CCtx_params ZSTD_makeCCtxParamsFromCParams(
  152. ZSTD_compressionParameters cParams)
  153. {
  154. ZSTD_CCtx_params cctxParams;
  155. memset(&cctxParams, 0, sizeof(cctxParams));
  156. cctxParams.cParams = cParams;
  157. cctxParams.compressionLevel = ZSTD_CLEVEL_CUSTOM;
  158. return cctxParams;
  159. }
  160. static ZSTD_CCtx_params* ZSTD_createCCtxParams_advanced(
  161. ZSTD_customMem customMem)
  162. {
  163. ZSTD_CCtx_params* params;
  164. if (!customMem.customAlloc ^ !customMem.customFree) return NULL;
  165. params = (ZSTD_CCtx_params*)ZSTD_calloc(
  166. sizeof(ZSTD_CCtx_params), customMem);
  167. if (!params) { return NULL; }
  168. params->customMem = customMem;
  169. params->compressionLevel = ZSTD_CLEVEL_DEFAULT;
  170. return params;
  171. }
  172. ZSTD_CCtx_params* ZSTD_createCCtxParams(void)
  173. {
  174. return ZSTD_createCCtxParams_advanced(ZSTD_defaultCMem);
  175. }
  176. size_t ZSTD_freeCCtxParams(ZSTD_CCtx_params* params)
  177. {
  178. if (params == NULL) { return 0; }
  179. ZSTD_free(params, params->customMem);
  180. return 0;
  181. }
  182. size_t ZSTD_resetCCtxParams(ZSTD_CCtx_params* params)
  183. {
  184. return ZSTD_initCCtxParams(params, ZSTD_CLEVEL_DEFAULT);
  185. }
  186. size_t ZSTD_initCCtxParams(ZSTD_CCtx_params* cctxParams, int compressionLevel) {
  187. if (!cctxParams) { return ERROR(GENERIC); }
  188. memset(cctxParams, 0, sizeof(*cctxParams));
  189. cctxParams->compressionLevel = compressionLevel;
  190. return 0;
  191. }
  192. size_t ZSTD_initCCtxParams_advanced(ZSTD_CCtx_params* cctxParams, ZSTD_parameters params)
  193. {
  194. if (!cctxParams) { return ERROR(GENERIC); }
  195. CHECK_F( ZSTD_checkCParams(params.cParams) );
  196. memset(cctxParams, 0, sizeof(*cctxParams));
  197. cctxParams->cParams = params.cParams;
  198. cctxParams->fParams = params.fParams;
  199. cctxParams->compressionLevel = ZSTD_CLEVEL_CUSTOM;
  200. return 0;
  201. }
  202. static ZSTD_CCtx_params ZSTD_assignParamsToCCtxParams(
  203. ZSTD_CCtx_params cctxParams, ZSTD_parameters params)
  204. {
  205. ZSTD_CCtx_params ret = cctxParams;
  206. ret.cParams = params.cParams;
  207. ret.fParams = params.fParams;
  208. return ret;
  209. }
  210. #define CLAMPCHECK(val,min,max) { \
  211. if (((val)<(min)) | ((val)>(max))) { \
  212. return ERROR(parameter_outOfBound); \
  213. } }
  214. size_t ZSTD_CCtx_setParameter(ZSTD_CCtx* cctx, ZSTD_cParameter param, unsigned value)
  215. {
  216. if (cctx->streamStage != zcss_init) return ERROR(stage_wrong);
  217. switch(param)
  218. {
  219. case ZSTD_p_compressionLevel:
  220. if (value == 0) return 0; /* special value : 0 means "don't change anything" */
  221. if (cctx->cdict) return ERROR(stage_wrong);
  222. return ZSTD_CCtxParam_setParameter(&cctx->requestedParams, param, value);
  223. case ZSTD_p_windowLog:
  224. case ZSTD_p_hashLog:
  225. case ZSTD_p_chainLog:
  226. case ZSTD_p_searchLog:
  227. case ZSTD_p_minMatch:
  228. case ZSTD_p_targetLength:
  229. case ZSTD_p_compressionStrategy:
  230. if (value == 0) return 0; /* special value : 0 means "don't change anything" */
  231. if (cctx->cdict) return ERROR(stage_wrong);
  232. ZSTD_cLevelToCParams(cctx); /* Can optimize if srcSize is known */
  233. return ZSTD_CCtxParam_setParameter(&cctx->requestedParams, param, value);
  234. case ZSTD_p_contentSizeFlag:
  235. case ZSTD_p_checksumFlag:
  236. case ZSTD_p_dictIDFlag:
  237. return ZSTD_CCtxParam_setParameter(&cctx->requestedParams, param, value);
  238. case ZSTD_p_forceMaxWindow : /* Force back-references to remain < windowSize,
  239. * even when referencing into Dictionary content
  240. * default : 0 when using a CDict, 1 when using a Prefix */
  241. cctx->loadedDictEnd = 0;
  242. return ZSTD_CCtxParam_setParameter(&cctx->requestedParams, param, value);
  243. case ZSTD_p_nbThreads:
  244. if (value==0) return 0;
  245. DEBUGLOG(5, " setting nbThreads : %u", value);
  246. if (value > 1 && cctx->staticSize) {
  247. return ERROR(parameter_unsupported); /* MT not compatible with static alloc */
  248. }
  249. return ZSTD_CCtxParam_setParameter(&cctx->requestedParams, param, value);
  250. case ZSTD_p_jobSize:
  251. return ZSTD_CCtxParam_setParameter(&cctx->requestedParams, param, value);
  252. case ZSTD_p_overlapSizeLog:
  253. DEBUGLOG(5, " setting overlap with nbThreads == %u", cctx->requestedParams.nbThreads);
  254. return ZSTD_CCtxParam_setParameter(&cctx->requestedParams, param, value);
  255. case ZSTD_p_enableLongDistanceMatching:
  256. if (cctx->cdict) return ERROR(stage_wrong);
  257. if (value != 0) {
  258. ZSTD_cLevelToCParams(cctx);
  259. }
  260. return ZSTD_CCtxParam_setParameter(&cctx->requestedParams, param, value);
  261. case ZSTD_p_ldmHashLog:
  262. case ZSTD_p_ldmMinMatch:
  263. if (value == 0) return 0; /* special value : 0 means "don't change anything" */
  264. if (cctx->cdict) return ERROR(stage_wrong);
  265. return ZSTD_CCtxParam_setParameter(&cctx->requestedParams, param, value);
  266. case ZSTD_p_ldmBucketSizeLog:
  267. case ZSTD_p_ldmHashEveryLog:
  268. if (cctx->cdict) return ERROR(stage_wrong);
  269. return ZSTD_CCtxParam_setParameter(&cctx->requestedParams, param, value);
  270. default: return ERROR(parameter_unsupported);
  271. }
  272. }
  273. size_t ZSTD_CCtxParam_setParameter(
  274. ZSTD_CCtx_params* params, ZSTD_cParameter param, unsigned value)
  275. {
  276. switch(param)
  277. {
  278. case ZSTD_p_compressionLevel :
  279. if ((int)value > ZSTD_maxCLevel()) value = ZSTD_maxCLevel();
  280. if (value == 0) return 0;
  281. params->compressionLevel = value;
  282. return 0;
  283. case ZSTD_p_windowLog :
  284. if (value == 0) return 0;
  285. CLAMPCHECK(value, ZSTD_WINDOWLOG_MIN, ZSTD_WINDOWLOG_MAX);
  286. ZSTD_cLevelToCCtxParams(params);
  287. params->cParams.windowLog = value;
  288. return 0;
  289. case ZSTD_p_hashLog :
  290. if (value == 0) return 0;
  291. CLAMPCHECK(value, ZSTD_HASHLOG_MIN, ZSTD_HASHLOG_MAX);
  292. ZSTD_cLevelToCCtxParams(params);
  293. params->cParams.hashLog = value;
  294. return 0;
  295. case ZSTD_p_chainLog :
  296. if (value == 0) return 0;
  297. CLAMPCHECK(value, ZSTD_CHAINLOG_MIN, ZSTD_CHAINLOG_MAX);
  298. ZSTD_cLevelToCCtxParams(params);
  299. params->cParams.chainLog = value;
  300. return 0;
  301. case ZSTD_p_searchLog :
  302. if (value == 0) return 0;
  303. CLAMPCHECK(value, ZSTD_SEARCHLOG_MIN, ZSTD_SEARCHLOG_MAX);
  304. ZSTD_cLevelToCCtxParams(params);
  305. params->cParams.searchLog = value;
  306. return 0;
  307. case ZSTD_p_minMatch :
  308. if (value == 0) return 0;
  309. CLAMPCHECK(value, ZSTD_SEARCHLENGTH_MIN, ZSTD_SEARCHLENGTH_MAX);
  310. ZSTD_cLevelToCCtxParams(params);
  311. params->cParams.searchLength = value;
  312. return 0;
  313. case ZSTD_p_targetLength :
  314. if (value == 0) return 0;
  315. CLAMPCHECK(value, ZSTD_TARGETLENGTH_MIN, ZSTD_TARGETLENGTH_MAX);
  316. ZSTD_cLevelToCCtxParams(params);
  317. params->cParams.targetLength = value;
  318. return 0;
  319. case ZSTD_p_compressionStrategy :
  320. if (value == 0) return 0;
  321. CLAMPCHECK(value, (unsigned)ZSTD_fast, (unsigned)ZSTD_btultra);
  322. ZSTD_cLevelToCCtxParams(params);
  323. params->cParams.strategy = (ZSTD_strategy)value;
  324. return 0;
  325. case ZSTD_p_contentSizeFlag :
  326. /* Content size written in frame header _when known_ (default:1) */
  327. DEBUGLOG(5, "set content size flag = %u", (value>0));
  328. params->fParams.contentSizeFlag = value > 0;
  329. return 0;
  330. case ZSTD_p_checksumFlag :
  331. /* A 32-bits content checksum will be calculated and written at end of frame (default:0) */
  332. params->fParams.checksumFlag = value > 0;
  333. return 0;
  334. case ZSTD_p_dictIDFlag : /* When applicable, dictionary's dictID is provided in frame header (default:1) */
  335. DEBUGLOG(5, "set dictIDFlag = %u", (value>0));
  336. params->fParams.noDictIDFlag = (value == 0);
  337. return 0;
  338. case ZSTD_p_forceMaxWindow :
  339. params->forceWindow = value > 0;
  340. return 0;
  341. case ZSTD_p_nbThreads :
  342. if (value == 0) return 0;
  343. #ifndef ZSTD_MULTITHREAD
  344. if (value > 1) return ERROR(parameter_unsupported);
  345. return 0;
  346. #else
  347. return ZSTDMT_initializeCCtxParameters(params, value);
  348. #endif
  349. case ZSTD_p_jobSize :
  350. #ifndef ZSTD_MULTITHREAD
  351. return ERROR(parameter_unsupported);
  352. #else
  353. if (params->nbThreads <= 1) return ERROR(parameter_unsupported);
  354. return ZSTDMT_CCtxParam_setMTCtxParameter(params, ZSTDMT_p_sectionSize, value);
  355. #endif
  356. case ZSTD_p_overlapSizeLog :
  357. #ifndef ZSTD_MULTITHREAD
  358. return ERROR(parameter_unsupported);
  359. #else
  360. if (params->nbThreads <= 1) return ERROR(parameter_unsupported);
  361. return ZSTDMT_CCtxParam_setMTCtxParameter(params, ZSTDMT_p_overlapSectionLog, value);
  362. #endif
  363. case ZSTD_p_enableLongDistanceMatching :
  364. if (value != 0) {
  365. ZSTD_cLevelToCCtxParams(params);
  366. params->cParams.windowLog = ZSTD_LDM_WINDOW_LOG;
  367. }
  368. return ZSTD_ldm_initializeParameters(&params->ldmParams, value);
  369. case ZSTD_p_ldmHashLog :
  370. if (value == 0) return 0;
  371. CLAMPCHECK(value, ZSTD_HASHLOG_MIN, ZSTD_HASHLOG_MAX);
  372. params->ldmParams.hashLog = value;
  373. return 0;
  374. case ZSTD_p_ldmMinMatch :
  375. if (value == 0) return 0;
  376. CLAMPCHECK(value, ZSTD_LDM_MINMATCH_MIN, ZSTD_LDM_MINMATCH_MAX);
  377. params->ldmParams.minMatchLength = value;
  378. return 0;
  379. case ZSTD_p_ldmBucketSizeLog :
  380. if (value > ZSTD_LDM_BUCKETSIZELOG_MAX) {
  381. return ERROR(parameter_outOfBound);
  382. }
  383. params->ldmParams.bucketSizeLog = value;
  384. return 0;
  385. case ZSTD_p_ldmHashEveryLog :
  386. if (value > ZSTD_WINDOWLOG_MAX - ZSTD_HASHLOG_MIN) {
  387. return ERROR(parameter_outOfBound);
  388. }
  389. params->ldmParams.hashEveryLog = value;
  390. return 0;
  391. default: return ERROR(parameter_unsupported);
  392. }
  393. }
  394. /**
  395. * This function should be updated whenever ZSTD_CCtx_params is updated.
  396. * Parameters are copied manually before the dictionary is loaded.
  397. * The multithreading parameters jobSize and overlapSizeLog are set only if
  398. * nbThreads > 1.
  399. *
  400. * Pledged srcSize is treated as unknown.
  401. */
  402. size_t ZSTD_CCtx_setParametersUsingCCtxParams(
  403. ZSTD_CCtx* cctx, const ZSTD_CCtx_params* params)
  404. {
  405. if (cctx->streamStage != zcss_init) return ERROR(stage_wrong);
  406. if (cctx->cdict) return ERROR(stage_wrong);
  407. /* Assume the compression and frame parameters are validated */
  408. cctx->requestedParams.cParams = params->cParams;
  409. cctx->requestedParams.fParams = params->fParams;
  410. cctx->requestedParams.compressionLevel = params->compressionLevel;
  411. /* Set force window explicitly since it sets cctx->loadedDictEnd */
  412. CHECK_F( ZSTD_CCtx_setParameter(
  413. cctx, ZSTD_p_forceMaxWindow, params->forceWindow) );
  414. /* Set multithreading parameters explicitly */
  415. CHECK_F( ZSTD_CCtx_setParameter(cctx, ZSTD_p_nbThreads, params->nbThreads) );
  416. if (params->nbThreads > 1) {
  417. CHECK_F( ZSTD_CCtx_setParameter(cctx, ZSTD_p_jobSize, params->jobSize) );
  418. CHECK_F( ZSTD_CCtx_setParameter(
  419. cctx, ZSTD_p_overlapSizeLog, params->overlapSizeLog) );
  420. }
  421. /* Copy long distance matching parameters */
  422. cctx->requestedParams.ldmParams = params->ldmParams;
  423. /* customMem is used only for create/free params and can be ignored */
  424. return 0;
  425. }
  426. ZSTDLIB_API size_t ZSTD_CCtx_setPledgedSrcSize(ZSTD_CCtx* cctx, unsigned long long pledgedSrcSize)
  427. {
  428. DEBUGLOG(5, " setting pledgedSrcSize to %u", (U32)pledgedSrcSize);
  429. if (cctx->streamStage != zcss_init) return ERROR(stage_wrong);
  430. cctx->pledgedSrcSizePlusOne = pledgedSrcSize+1;
  431. return 0;
  432. }
  433. size_t ZSTD_CCtx_loadDictionary_advanced(
  434. ZSTD_CCtx* cctx, const void* dict, size_t dictSize,
  435. ZSTD_dictLoadMethod_e dictLoadMethod, ZSTD_dictMode_e dictMode)
  436. {
  437. if (cctx->streamStage != zcss_init) return ERROR(stage_wrong);
  438. if (cctx->staticSize) return ERROR(memory_allocation); /* no malloc for static CCtx */
  439. DEBUGLOG(5, "load dictionary of size %u", (U32)dictSize);
  440. ZSTD_freeCDict(cctx->cdictLocal); /* in case one already exists */
  441. if (dict==NULL || dictSize==0) { /* no dictionary mode */
  442. cctx->cdictLocal = NULL;
  443. cctx->cdict = NULL;
  444. } else {
  445. ZSTD_compressionParameters const cParams =
  446. ZSTD_getCParamsFromCCtxParams(cctx->requestedParams, 0, dictSize);
  447. cctx->cdictLocal = ZSTD_createCDict_advanced(
  448. dict, dictSize,
  449. dictLoadMethod, dictMode,
  450. cParams, cctx->customMem);
  451. cctx->cdict = cctx->cdictLocal;
  452. if (cctx->cdictLocal == NULL)
  453. return ERROR(memory_allocation);
  454. }
  455. return 0;
  456. }
  457. ZSTDLIB_API size_t ZSTD_CCtx_loadDictionary_byReference(
  458. ZSTD_CCtx* cctx, const void* dict, size_t dictSize)
  459. {
  460. return ZSTD_CCtx_loadDictionary_advanced(
  461. cctx, dict, dictSize, ZSTD_dlm_byRef, ZSTD_dm_auto);
  462. }
  463. ZSTDLIB_API size_t ZSTD_CCtx_loadDictionary(ZSTD_CCtx* cctx, const void* dict, size_t dictSize)
  464. {
  465. return ZSTD_CCtx_loadDictionary_advanced(
  466. cctx, dict, dictSize, ZSTD_dlm_byCopy, ZSTD_dm_auto);
  467. }
  468. size_t ZSTD_CCtx_refCDict(ZSTD_CCtx* cctx, const ZSTD_CDict* cdict)
  469. {
  470. if (cctx->streamStage != zcss_init) return ERROR(stage_wrong);
  471. cctx->cdict = cdict;
  472. memset(&cctx->prefixDict, 0, sizeof(cctx->prefixDict)); /* exclusive */
  473. return 0;
  474. }
  475. size_t ZSTD_CCtx_refPrefix(ZSTD_CCtx* cctx, const void* prefix, size_t prefixSize)
  476. {
  477. return ZSTD_CCtx_refPrefix_advanced(cctx, prefix, prefixSize, ZSTD_dm_rawContent);
  478. }
  479. size_t ZSTD_CCtx_refPrefix_advanced(
  480. ZSTD_CCtx* cctx, const void* prefix, size_t prefixSize, ZSTD_dictMode_e dictMode)
  481. {
  482. if (cctx->streamStage != zcss_init) return ERROR(stage_wrong);
  483. cctx->cdict = NULL; /* prefix discards any prior cdict */
  484. cctx->prefixDict.dict = prefix;
  485. cctx->prefixDict.dictSize = prefixSize;
  486. cctx->prefixDict.dictMode = dictMode;
  487. return 0;
  488. }
  489. static void ZSTD_startNewCompression(ZSTD_CCtx* cctx)
  490. {
  491. cctx->streamStage = zcss_init;
  492. cctx->pledgedSrcSizePlusOne = 0;
  493. }
  494. /*! ZSTD_CCtx_reset() :
  495. * Also dumps dictionary */
  496. void ZSTD_CCtx_reset(ZSTD_CCtx* cctx)
  497. {
  498. ZSTD_startNewCompression(cctx);
  499. cctx->cdict = NULL;
  500. }
  501. /** ZSTD_checkCParams() :
  502. control CParam values remain within authorized range.
  503. @return : 0, or an error code if one value is beyond authorized range */
  504. size_t ZSTD_checkCParams(ZSTD_compressionParameters cParams)
  505. {
  506. CLAMPCHECK(cParams.windowLog, ZSTD_WINDOWLOG_MIN, ZSTD_WINDOWLOG_MAX);
  507. CLAMPCHECK(cParams.chainLog, ZSTD_CHAINLOG_MIN, ZSTD_CHAINLOG_MAX);
  508. CLAMPCHECK(cParams.hashLog, ZSTD_HASHLOG_MIN, ZSTD_HASHLOG_MAX);
  509. CLAMPCHECK(cParams.searchLog, ZSTD_SEARCHLOG_MIN, ZSTD_SEARCHLOG_MAX);
  510. CLAMPCHECK(cParams.searchLength, ZSTD_SEARCHLENGTH_MIN, ZSTD_SEARCHLENGTH_MAX);
  511. CLAMPCHECK(cParams.targetLength, ZSTD_TARGETLENGTH_MIN, ZSTD_TARGETLENGTH_MAX);
  512. if ((U32)(cParams.strategy) > (U32)ZSTD_btultra)
  513. return ERROR(parameter_unsupported);
  514. return 0;
  515. }
  516. /** ZSTD_clampCParams() :
  517. * make CParam values within valid range.
  518. * @return : valid CParams */
  519. static ZSTD_compressionParameters ZSTD_clampCParams(ZSTD_compressionParameters cParams)
  520. {
  521. # define CLAMP(val,min,max) { \
  522. if (val<min) val=min; \
  523. else if (val>max) val=max; \
  524. }
  525. CLAMP(cParams.windowLog, ZSTD_WINDOWLOG_MIN, ZSTD_WINDOWLOG_MAX);
  526. CLAMP(cParams.chainLog, ZSTD_CHAINLOG_MIN, ZSTD_CHAINLOG_MAX);
  527. CLAMP(cParams.hashLog, ZSTD_HASHLOG_MIN, ZSTD_HASHLOG_MAX);
  528. CLAMP(cParams.searchLog, ZSTD_SEARCHLOG_MIN, ZSTD_SEARCHLOG_MAX);
  529. CLAMP(cParams.searchLength, ZSTD_SEARCHLENGTH_MIN, ZSTD_SEARCHLENGTH_MAX);
  530. CLAMP(cParams.targetLength, ZSTD_TARGETLENGTH_MIN, ZSTD_TARGETLENGTH_MAX);
  531. if ((U32)(cParams.strategy) > (U32)ZSTD_btultra) cParams.strategy = ZSTD_btultra;
  532. return cParams;
  533. }
  534. /** ZSTD_cycleLog() :
  535. * condition for correct operation : hashLog > 1 */
  536. static U32 ZSTD_cycleLog(U32 hashLog, ZSTD_strategy strat)
  537. {
  538. U32 const btScale = ((U32)strat >= (U32)ZSTD_btlazy2);
  539. return hashLog - btScale;
  540. }
  541. /** ZSTD_adjustCParams_internal() :
  542. optimize `cPar` for a given input (`srcSize` and `dictSize`).
  543. mostly downsizing to reduce memory consumption and initialization.
  544. Both `srcSize` and `dictSize` are optional (use 0 if unknown),
  545. but if both are 0, no optimization can be done.
  546. Note : cPar is considered validated at this stage. Use ZSTD_checkParams() to ensure that. */
  547. ZSTD_compressionParameters ZSTD_adjustCParams_internal(ZSTD_compressionParameters cPar, unsigned long long srcSize, size_t dictSize)
  548. {
  549. assert(ZSTD_checkCParams(cPar)==0);
  550. if (srcSize+dictSize == 0) return cPar; /* no size information available : no adjustment */
  551. /* resize params, to use less memory when necessary */
  552. { U32 const minSrcSize = (srcSize==0) ? 500 : 0;
  553. U64 const rSize = srcSize + dictSize + minSrcSize;
  554. if (rSize < ((U64)1<<ZSTD_WINDOWLOG_MAX)) {
  555. U32 const srcLog =
  556. MAX(ZSTD_HASHLOG_MIN, (rSize==1) ? 1 : ZSTD_highbit32((U32)(rSize)-1) + 1);
  557. if (cPar.windowLog > srcLog) cPar.windowLog = srcLog;
  558. } }
  559. if (cPar.hashLog > cPar.windowLog) cPar.hashLog = cPar.windowLog;
  560. { U32 const cycleLog = ZSTD_cycleLog(cPar.chainLog, cPar.strategy);
  561. if (cycleLog > cPar.windowLog) cPar.chainLog -= (cycleLog - cPar.windowLog);
  562. }
  563. if (cPar.windowLog < ZSTD_WINDOWLOG_ABSOLUTEMIN) cPar.windowLog = ZSTD_WINDOWLOG_ABSOLUTEMIN; /* required for frame header */
  564. return cPar;
  565. }
  566. ZSTD_compressionParameters ZSTD_adjustCParams(ZSTD_compressionParameters cPar, unsigned long long srcSize, size_t dictSize)
  567. {
  568. cPar = ZSTD_clampCParams(cPar);
  569. return ZSTD_adjustCParams_internal(cPar, srcSize, dictSize);
  570. }
  571. size_t ZSTD_estimateCCtxSize_advanced_usingCCtxParams(const ZSTD_CCtx_params* params)
  572. {
  573. /* Estimate CCtx size is supported for single-threaded compression only. */
  574. if (params->nbThreads > 1) { return ERROR(GENERIC); }
  575. { ZSTD_compressionParameters const cParams =
  576. ZSTD_getCParamsFromCCtxParams(*params, 0, 0);
  577. size_t const blockSize = MIN(ZSTD_BLOCKSIZE_MAX, (size_t)1 << cParams.windowLog);
  578. U32 const divider = (cParams.searchLength==3) ? 3 : 4;
  579. size_t const maxNbSeq = blockSize / divider;
  580. size_t const tokenSpace = blockSize + 11*maxNbSeq;
  581. size_t const chainSize =
  582. (cParams.strategy == ZSTD_fast) ? 0 : (1 << cParams.chainLog);
  583. size_t const hSize = ((size_t)1) << cParams.hashLog;
  584. U32 const hashLog3 = (cParams.searchLength>3) ?
  585. 0 : MIN(ZSTD_HASHLOG3_MAX, cParams.windowLog);
  586. size_t const h3Size = ((size_t)1) << hashLog3;
  587. size_t const entropySpace = sizeof(ZSTD_entropyCTables_t);
  588. size_t const tableSpace = (chainSize + hSize + h3Size) * sizeof(U32);
  589. size_t const optBudget =
  590. ((MaxML+1) + (MaxLL+1) + (MaxOff+1) + (1<<Litbits))*sizeof(U32)
  591. + (ZSTD_OPT_NUM+1)*(sizeof(ZSTD_match_t) + sizeof(ZSTD_optimal_t));
  592. size_t const optSpace = ((cParams.strategy == ZSTD_btopt) || (cParams.strategy == ZSTD_btultra)) ? optBudget : 0;
  593. size_t const ldmSpace = params->ldmParams.enableLdm ?
  594. ZSTD_ldm_getTableSize(params->ldmParams.hashLog,
  595. params->ldmParams.bucketSizeLog) : 0;
  596. size_t const neededSpace = entropySpace + tableSpace + tokenSpace +
  597. optSpace + ldmSpace;
  598. DEBUGLOG(5, "sizeof(ZSTD_CCtx) : %u", (U32)sizeof(ZSTD_CCtx));
  599. DEBUGLOG(5, "estimate workSpace : %u", (U32)neededSpace);
  600. return sizeof(ZSTD_CCtx) + neededSpace;
  601. }
  602. }
  603. size_t ZSTD_estimateCCtxSize_advanced_usingCParams(ZSTD_compressionParameters cParams)
  604. {
  605. ZSTD_CCtx_params const params = ZSTD_makeCCtxParamsFromCParams(cParams);
  606. return ZSTD_estimateCCtxSize_advanced_usingCCtxParams(&params);
  607. }
  608. size_t ZSTD_estimateCCtxSize(int compressionLevel)
  609. {
  610. ZSTD_compressionParameters const cParams = ZSTD_getCParams(compressionLevel, 0, 0);
  611. return ZSTD_estimateCCtxSize_advanced_usingCParams(cParams);
  612. }
  613. size_t ZSTD_estimateCStreamSize_advanced_usingCCtxParams(const ZSTD_CCtx_params* params)
  614. {
  615. if (params->nbThreads > 1) { return ERROR(GENERIC); }
  616. { size_t const CCtxSize = ZSTD_estimateCCtxSize_advanced_usingCCtxParams(params);
  617. size_t const blockSize = MIN(ZSTD_BLOCKSIZE_MAX, (size_t)1 << params->cParams.windowLog);
  618. size_t const inBuffSize = ((size_t)1 << params->cParams.windowLog) + blockSize;
  619. size_t const outBuffSize = ZSTD_compressBound(blockSize) + 1;
  620. size_t const streamingSize = inBuffSize + outBuffSize;
  621. return CCtxSize + streamingSize;
  622. }
  623. }
  624. size_t ZSTD_estimateCStreamSize_advanced_usingCParams(ZSTD_compressionParameters cParams)
  625. {
  626. ZSTD_CCtx_params const params = ZSTD_makeCCtxParamsFromCParams(cParams);
  627. return ZSTD_estimateCStreamSize_advanced_usingCCtxParams(&params);
  628. }
  629. size_t ZSTD_estimateCStreamSize(int compressionLevel) {
  630. ZSTD_compressionParameters const cParams = ZSTD_getCParams(compressionLevel, 0, 0);
  631. return ZSTD_estimateCStreamSize_advanced_usingCParams(cParams);
  632. }
  633. static U32 ZSTD_equivalentCParams(ZSTD_compressionParameters cParams1,
  634. ZSTD_compressionParameters cParams2)
  635. {
  636. U32 bslog1 = MIN(cParams1.windowLog, ZSTD_BLOCKSIZELOG_MAX);
  637. U32 bslog2 = MIN(cParams2.windowLog, ZSTD_BLOCKSIZELOG_MAX);
  638. return (bslog1 == bslog2) /* same block size */
  639. & (cParams1.hashLog == cParams2.hashLog)
  640. & (cParams1.chainLog == cParams2.chainLog)
  641. & (cParams1.strategy == cParams2.strategy) /* opt parser space */
  642. & ((cParams1.searchLength==3) == (cParams2.searchLength==3)); /* hashlog3 space */
  643. }
  644. /** The parameters are equivalent if ldm is not enabled in both sets or
  645. * all the parameters are equivalent. */
  646. static U32 ZSTD_equivalentLdmParams(ldmParams_t ldmParams1,
  647. ldmParams_t ldmParams2)
  648. {
  649. return (!ldmParams1.enableLdm && !ldmParams2.enableLdm) ||
  650. (ldmParams1.enableLdm == ldmParams2.enableLdm &&
  651. ldmParams1.hashLog == ldmParams2.hashLog &&
  652. ldmParams1.bucketSizeLog == ldmParams2.bucketSizeLog &&
  653. ldmParams1.minMatchLength == ldmParams2.minMatchLength &&
  654. ldmParams1.hashEveryLog == ldmParams2.hashEveryLog);
  655. }
  656. /** Equivalence for resetCCtx purposes */
  657. static U32 ZSTD_equivalentParams(ZSTD_CCtx_params params1,
  658. ZSTD_CCtx_params params2)
  659. {
  660. return ZSTD_equivalentCParams(params1.cParams, params2.cParams) &&
  661. ZSTD_equivalentLdmParams(params1.ldmParams, params2.ldmParams);
  662. }
  663. /*! ZSTD_continueCCtx() :
  664. * reuse CCtx without reset (note : requires no dictionary) */
  665. static size_t ZSTD_continueCCtx(ZSTD_CCtx* cctx, ZSTD_CCtx_params params, U64 pledgedSrcSize)
  666. {
  667. U32 const end = (U32)(cctx->nextSrc - cctx->base);
  668. DEBUGLOG(5, "continue mode");
  669. cctx->appliedParams = params;
  670. cctx->pledgedSrcSizePlusOne = pledgedSrcSize+1;
  671. cctx->consumedSrcSize = 0;
  672. if (pledgedSrcSize == ZSTD_CONTENTSIZE_UNKNOWN)
  673. cctx->appliedParams.fParams.contentSizeFlag = 0;
  674. DEBUGLOG(5, "pledged content size : %u ; flag : %u",
  675. (U32)pledgedSrcSize, cctx->appliedParams.fParams.contentSizeFlag);
  676. cctx->lowLimit = end;
  677. cctx->dictLimit = end;
  678. cctx->nextToUpdate = end+1;
  679. cctx->stage = ZSTDcs_init;
  680. cctx->dictID = 0;
  681. cctx->loadedDictEnd = 0;
  682. { int i; for (i=0; i<ZSTD_REP_NUM; i++) cctx->seqStore.rep[i] = repStartValue[i]; }
  683. cctx->optState.litLengthSum = 0; /* force reset of btopt stats */
  684. XXH64_reset(&cctx->xxhState, 0);
  685. return 0;
  686. }
  687. typedef enum { ZSTDcrp_continue, ZSTDcrp_noMemset } ZSTD_compResetPolicy_e;
  688. typedef enum { ZSTDb_not_buffered, ZSTDb_buffered } ZSTD_buffered_policy_e;
  689. /*! ZSTD_resetCCtx_internal() :
  690. note : `params` are assumed fully validated at this stage */
  691. static size_t ZSTD_resetCCtx_internal(ZSTD_CCtx* zc,
  692. ZSTD_CCtx_params params, U64 pledgedSrcSize,
  693. ZSTD_compResetPolicy_e const crp,
  694. ZSTD_buffered_policy_e const zbuff)
  695. {
  696. assert(!ZSTD_isError(ZSTD_checkCParams(params.cParams)));
  697. if (crp == ZSTDcrp_continue) {
  698. if (ZSTD_equivalentParams(params, zc->appliedParams)) {
  699. DEBUGLOG(5, "ZSTD_equivalentParams()==1");
  700. assert(!(params.ldmParams.enableLdm &&
  701. params.ldmParams.hashEveryLog == ZSTD_LDM_HASHEVERYLOG_NOTSET));
  702. zc->entropy->hufCTable_repeatMode = HUF_repeat_none;
  703. zc->entropy->offcode_repeatMode = FSE_repeat_none;
  704. zc->entropy->matchlength_repeatMode = FSE_repeat_none;
  705. zc->entropy->litlength_repeatMode = FSE_repeat_none;
  706. return ZSTD_continueCCtx(zc, params, pledgedSrcSize);
  707. } }
  708. if (params.ldmParams.enableLdm) {
  709. /* Adjust long distance matching parameters */
  710. ZSTD_ldm_adjustParameters(&params.ldmParams, params.cParams.windowLog);
  711. assert(params.ldmParams.hashLog >= params.ldmParams.bucketSizeLog);
  712. assert(params.ldmParams.hashEveryLog < 32);
  713. zc->ldmState.hashPower =
  714. ZSTD_ldm_getHashPower(params.ldmParams.minMatchLength);
  715. }
  716. { size_t const blockSize = MIN(ZSTD_BLOCKSIZE_MAX, (size_t)1 << params.cParams.windowLog);
  717. U32 const divider = (params.cParams.searchLength==3) ? 3 : 4;
  718. size_t const maxNbSeq = blockSize / divider;
  719. size_t const tokenSpace = blockSize + 11*maxNbSeq;
  720. size_t const chainSize = (params.cParams.strategy == ZSTD_fast) ?
  721. 0 : (1 << params.cParams.chainLog);
  722. size_t const hSize = ((size_t)1) << params.cParams.hashLog;
  723. U32 const hashLog3 = (params.cParams.searchLength>3) ?
  724. 0 : MIN(ZSTD_HASHLOG3_MAX, params.cParams.windowLog);
  725. size_t const h3Size = ((size_t)1) << hashLog3;
  726. size_t const tableSpace = (chainSize + hSize + h3Size) * sizeof(U32);
  727. size_t const buffOutSize = (zbuff==ZSTDb_buffered) ? ZSTD_compressBound(blockSize)+1 : 0;
  728. size_t const buffInSize = (zbuff==ZSTDb_buffered) ? ((size_t)1 << params.cParams.windowLog) + blockSize : 0;
  729. void* ptr;
  730. /* Check if workSpace is large enough, alloc a new one if needed */
  731. { size_t const entropySpace = sizeof(ZSTD_entropyCTables_t);
  732. size_t const optPotentialSpace = ((MaxML+1) + (MaxLL+1) + (MaxOff+1) + (1<<Litbits)) * sizeof(U32)
  733. + (ZSTD_OPT_NUM+1) * (sizeof(ZSTD_match_t)+sizeof(ZSTD_optimal_t));
  734. size_t const optSpace = ( (params.cParams.strategy == ZSTD_btopt)
  735. || (params.cParams.strategy == ZSTD_btultra)) ?
  736. optPotentialSpace : 0;
  737. size_t const bufferSpace = buffInSize + buffOutSize;
  738. size_t const ldmSpace = params.ldmParams.enableLdm
  739. ? ZSTD_ldm_getTableSize(params.ldmParams.hashLog, params.ldmParams.bucketSizeLog)
  740. : 0;
  741. size_t const neededSpace = entropySpace + optSpace + ldmSpace +
  742. tableSpace + tokenSpace + bufferSpace;
  743. if (zc->workSpaceSize < neededSpace) { /* too small : resize */
  744. DEBUGLOG(5, "Need to update workSpaceSize from %uK to %uK \n",
  745. (unsigned)zc->workSpaceSize>>10,
  746. (unsigned)neededSpace>>10);
  747. /* static cctx : no resize, error out */
  748. if (zc->staticSize) return ERROR(memory_allocation);
  749. zc->workSpaceSize = 0;
  750. ZSTD_free(zc->workSpace, zc->customMem);
  751. zc->workSpace = ZSTD_malloc(neededSpace, zc->customMem);
  752. if (zc->workSpace == NULL) return ERROR(memory_allocation);
  753. zc->workSpaceSize = neededSpace;
  754. ptr = zc->workSpace;
  755. /* entropy space */
  756. assert(((size_t)zc->workSpace & 3) == 0); /* ensure correct alignment */
  757. assert(zc->workSpaceSize >= sizeof(ZSTD_entropyCTables_t));
  758. zc->entropy = (ZSTD_entropyCTables_t*)zc->workSpace;
  759. } }
  760. /* init params */
  761. zc->appliedParams = params;
  762. zc->pledgedSrcSizePlusOne = pledgedSrcSize+1;
  763. zc->consumedSrcSize = 0;
  764. if (pledgedSrcSize == ZSTD_CONTENTSIZE_UNKNOWN)
  765. zc->appliedParams.fParams.contentSizeFlag = 0;
  766. DEBUGLOG(5, "pledged content size : %u ; flag : %u",
  767. (U32)pledgedSrcSize, zc->appliedParams.fParams.contentSizeFlag);
  768. zc->blockSize = blockSize;
  769. XXH64_reset(&zc->xxhState, 0);
  770. zc->stage = ZSTDcs_init;
  771. zc->dictID = 0;
  772. zc->loadedDictEnd = 0;
  773. zc->entropy->hufCTable_repeatMode = HUF_repeat_none;
  774. zc->entropy->offcode_repeatMode = FSE_repeat_none;
  775. zc->entropy->matchlength_repeatMode = FSE_repeat_none;
  776. zc->entropy->litlength_repeatMode = FSE_repeat_none;
  777. zc->nextToUpdate = 1;
  778. zc->nextSrc = NULL;
  779. zc->base = NULL;
  780. zc->dictBase = NULL;
  781. zc->dictLimit = 0;
  782. zc->lowLimit = 0;
  783. { int i; for (i=0; i<ZSTD_REP_NUM; i++) zc->seqStore.rep[i] = repStartValue[i]; }
  784. zc->hashLog3 = hashLog3;
  785. zc->optState.litLengthSum = 0;
  786. ptr = zc->entropy + 1;
  787. /* opt parser space */
  788. if ((params.cParams.strategy == ZSTD_btopt) || (params.cParams.strategy == ZSTD_btultra)) {
  789. DEBUGLOG(5, "reserving optimal parser space");
  790. assert(((size_t)ptr & 3) == 0); /* ensure ptr is properly aligned */
  791. zc->optState.litFreq = (U32*)ptr;
  792. zc->optState.litLengthFreq = zc->optState.litFreq + (1<<Litbits);
  793. zc->optState.matchLengthFreq = zc->optState.litLengthFreq + (MaxLL+1);
  794. zc->optState.offCodeFreq = zc->optState.matchLengthFreq + (MaxML+1);
  795. ptr = zc->optState.offCodeFreq + (MaxOff+1);
  796. zc->optState.matchTable = (ZSTD_match_t*)ptr;
  797. ptr = zc->optState.matchTable + ZSTD_OPT_NUM+1;
  798. zc->optState.priceTable = (ZSTD_optimal_t*)ptr;
  799. ptr = zc->optState.priceTable + ZSTD_OPT_NUM+1;
  800. }
  801. /* ldm hash table */
  802. /* initialize bucketOffsets table later for pointer alignment */
  803. if (params.ldmParams.enableLdm) {
  804. size_t const ldmHSize = ((size_t)1) << params.ldmParams.hashLog;
  805. memset(ptr, 0, ldmHSize * sizeof(ldmEntry_t));
  806. assert(((size_t)ptr & 3) == 0); /* ensure ptr is properly aligned */
  807. zc->ldmState.hashTable = (ldmEntry_t*)ptr;
  808. ptr = zc->ldmState.hashTable + ldmHSize;
  809. }
  810. /* table Space */
  811. if (crp!=ZSTDcrp_noMemset) memset(ptr, 0, tableSpace); /* reset tables only */
  812. assert(((size_t)ptr & 3) == 0); /* ensure ptr is properly aligned */
  813. zc->hashTable = (U32*)(ptr);
  814. zc->chainTable = zc->hashTable + hSize;
  815. zc->hashTable3 = zc->chainTable + chainSize;
  816. ptr = zc->hashTable3 + h3Size;
  817. /* sequences storage */
  818. zc->seqStore.sequencesStart = (seqDef*)ptr;
  819. ptr = zc->seqStore.sequencesStart + maxNbSeq;
  820. zc->seqStore.llCode = (BYTE*) ptr;
  821. zc->seqStore.mlCode = zc->seqStore.llCode + maxNbSeq;
  822. zc->seqStore.ofCode = zc->seqStore.mlCode + maxNbSeq;
  823. zc->seqStore.litStart = zc->seqStore.ofCode + maxNbSeq;
  824. ptr = zc->seqStore.litStart + blockSize;
  825. /* ldm bucketOffsets table */
  826. if (params.ldmParams.enableLdm) {
  827. size_t const ldmBucketSize =
  828. ((size_t)1) << (params.ldmParams.hashLog -
  829. params.ldmParams.bucketSizeLog);
  830. memset(ptr, 0, ldmBucketSize);
  831. zc->ldmState.bucketOffsets = (BYTE*)ptr;
  832. ptr = zc->ldmState.bucketOffsets + ldmBucketSize;
  833. }
  834. /* buffers */
  835. zc->inBuffSize = buffInSize;
  836. zc->inBuff = (char*)ptr;
  837. zc->outBuffSize = buffOutSize;
  838. zc->outBuff = zc->inBuff + buffInSize;
  839. return 0;
  840. }
  841. }
  842. /* ZSTD_invalidateRepCodes() :
  843. * ensures next compression will not use repcodes from previous block.
  844. * Note : only works with regular variant;
  845. * do not use with extDict variant ! */
  846. void ZSTD_invalidateRepCodes(ZSTD_CCtx* cctx) {
  847. int i;
  848. for (i=0; i<ZSTD_REP_NUM; i++) cctx->seqStore.rep[i] = 0;
  849. }
  850. /*! ZSTD_copyCCtx_internal() :
  851. * Duplicate an existing context `srcCCtx` into another one `dstCCtx`.
  852. * The "context", in this case, refers to the hash and chain tables, entropy
  853. * tables, and dictionary offsets.
  854. * Only works during stage ZSTDcs_init (i.e. after creation, but before first call to ZSTD_compressContinue()).
  855. * pledgedSrcSize=0 means "empty" if fParams.contentSizeFlag=1
  856. * @return : 0, or an error code */
  857. static size_t ZSTD_copyCCtx_internal(ZSTD_CCtx* dstCCtx,
  858. const ZSTD_CCtx* srcCCtx,
  859. ZSTD_frameParameters fParams,
  860. unsigned long long pledgedSrcSize,
  861. ZSTD_buffered_policy_e zbuff)
  862. {
  863. DEBUGLOG(5, "ZSTD_copyCCtx_internal");
  864. if (srcCCtx->stage!=ZSTDcs_init) return ERROR(stage_wrong);
  865. memcpy(&dstCCtx->customMem, &srcCCtx->customMem, sizeof(ZSTD_customMem));
  866. { ZSTD_CCtx_params params = dstCCtx->requestedParams;
  867. /* Copy only compression parameters related to tables. */
  868. params.cParams = srcCCtx->appliedParams.cParams;
  869. params.fParams = fParams;
  870. ZSTD_resetCCtx_internal(dstCCtx, params, pledgedSrcSize,
  871. ZSTDcrp_noMemset, zbuff);
  872. }
  873. /* copy tables */
  874. { size_t const chainSize = (srcCCtx->appliedParams.cParams.strategy == ZSTD_fast) ? 0 : (1 << srcCCtx->appliedParams.cParams.chainLog);
  875. size_t const hSize = (size_t)1 << srcCCtx->appliedParams.cParams.hashLog;
  876. size_t const h3Size = (size_t)1 << srcCCtx->hashLog3;
  877. size_t const tableSpace = (chainSize + hSize + h3Size) * sizeof(U32);
  878. assert((U32*)dstCCtx->chainTable == (U32*)dstCCtx->hashTable + hSize); /* chainTable must follow hashTable */
  879. assert((U32*)dstCCtx->hashTable3 == (U32*)dstCCtx->chainTable + chainSize);
  880. memcpy(dstCCtx->hashTable, srcCCtx->hashTable, tableSpace); /* presumes all tables follow each other */
  881. }
  882. /* copy dictionary offsets */
  883. dstCCtx->nextToUpdate = srcCCtx->nextToUpdate;
  884. dstCCtx->nextToUpdate3= srcCCtx->nextToUpdate3;
  885. dstCCtx->nextSrc = srcCCtx->nextSrc;
  886. dstCCtx->base = srcCCtx->base;
  887. dstCCtx->dictBase = srcCCtx->dictBase;
  888. dstCCtx->dictLimit = srcCCtx->dictLimit;
  889. dstCCtx->lowLimit = srcCCtx->lowLimit;
  890. dstCCtx->loadedDictEnd= srcCCtx->loadedDictEnd;
  891. dstCCtx->dictID = srcCCtx->dictID;
  892. /* copy entropy tables */
  893. memcpy(dstCCtx->entropy, srcCCtx->entropy, sizeof(ZSTD_entropyCTables_t));
  894. return 0;
  895. }
  896. /*! ZSTD_copyCCtx() :
  897. * Duplicate an existing context `srcCCtx` into another one `dstCCtx`.
  898. * Only works during stage ZSTDcs_init (i.e. after creation, but before first call to ZSTD_compressContinue()).
  899. * pledgedSrcSize==0 means "unknown".
  900. * @return : 0, or an error code */
  901. size_t ZSTD_copyCCtx(ZSTD_CCtx* dstCCtx, const ZSTD_CCtx* srcCCtx, unsigned long long pledgedSrcSize)
  902. {
  903. ZSTD_frameParameters fParams = { 1 /*content*/, 0 /*checksum*/, 0 /*noDictID*/ };
  904. ZSTD_buffered_policy_e const zbuff = (ZSTD_buffered_policy_e)(srcCCtx->inBuffSize>0);
  905. ZSTD_STATIC_ASSERT((U32)ZSTDb_buffered==1);
  906. fParams.contentSizeFlag = pledgedSrcSize>0;
  907. return ZSTD_copyCCtx_internal(dstCCtx, srcCCtx, fParams, pledgedSrcSize, zbuff);
  908. }
  909. /*! ZSTD_reduceTable() :
  910. * reduce table indexes by `reducerValue` */
  911. static void ZSTD_reduceTable (U32* const table, U32 const size, U32 const reducerValue)
  912. {
  913. U32 u;
  914. for (u=0 ; u < size ; u++) {
  915. if (table[u] < reducerValue) table[u] = 0;
  916. else table[u] -= reducerValue;
  917. }
  918. }
  919. /*! ZSTD_ldm_reduceTable() :
  920. * reduce table indexes by `reducerValue` */
  921. static void ZSTD_ldm_reduceTable(ldmEntry_t* const table, U32 const size,
  922. U32 const reducerValue)
  923. {
  924. U32 u;
  925. for (u = 0; u < size; u++) {
  926. if (table[u].offset < reducerValue) table[u].offset = 0;
  927. else table[u].offset -= reducerValue;
  928. }
  929. }
  930. /*! ZSTD_reduceIndex() :
  931. * rescale all indexes to avoid future overflow (indexes are U32) */
  932. static void ZSTD_reduceIndex (ZSTD_CCtx* zc, const U32 reducerValue)
  933. {
  934. { U32 const hSize = (U32)1 << zc->appliedParams.cParams.hashLog;
  935. ZSTD_reduceTable(zc->hashTable, hSize, reducerValue); }
  936. { U32 const chainSize = (zc->appliedParams.cParams.strategy == ZSTD_fast) ? 0 : ((U32)1 << zc->appliedParams.cParams.chainLog);
  937. ZSTD_reduceTable(zc->chainTable, chainSize, reducerValue); }
  938. { U32 const h3Size = (zc->hashLog3) ? (U32)1 << zc->hashLog3 : 0;
  939. ZSTD_reduceTable(zc->hashTable3, h3Size, reducerValue); }
  940. { if (zc->appliedParams.ldmParams.enableLdm) {
  941. U32 const ldmHSize = (U32)1 << zc->appliedParams.ldmParams.hashLog;
  942. ZSTD_ldm_reduceTable(zc->ldmState.hashTable, ldmHSize, reducerValue);
  943. }
  944. }
  945. }
  946. /*-*******************************************************
  947. * Block entropic compression
  948. *********************************************************/
  949. /* See doc/zstd_compression_format.md for detailed format description */
  950. size_t ZSTD_noCompressBlock (void* dst, size_t dstCapacity, const void* src, size_t srcSize)
  951. {
  952. if (srcSize + ZSTD_blockHeaderSize > dstCapacity) return ERROR(dstSize_tooSmall);
  953. memcpy((BYTE*)dst + ZSTD_blockHeaderSize, src, srcSize);
  954. MEM_writeLE24(dst, (U32)(srcSize << 2) + (U32)bt_raw);
  955. return ZSTD_blockHeaderSize+srcSize;
  956. }
  957. static size_t ZSTD_noCompressLiterals (void* dst, size_t dstCapacity, const void* src, size_t srcSize)
  958. {
  959. BYTE* const ostart = (BYTE* const)dst;
  960. U32 const flSize = 1 + (srcSize>31) + (srcSize>4095);
  961. if (srcSize + flSize > dstCapacity) return ERROR(dstSize_tooSmall);
  962. switch(flSize)
  963. {
  964. case 1: /* 2 - 1 - 5 */
  965. ostart[0] = (BYTE)((U32)set_basic + (srcSize<<3));
  966. break;
  967. case 2: /* 2 - 2 - 12 */
  968. MEM_writeLE16(ostart, (U16)((U32)set_basic + (1<<2) + (srcSize<<4)));
  969. break;
  970. case 3: /* 2 - 2 - 20 */
  971. MEM_writeLE32(ostart, (U32)((U32)set_basic + (3<<2) + (srcSize<<4)));
  972. break;
  973. default: /* not necessary : flSize is {1,2,3} */
  974. assert(0);
  975. }
  976. memcpy(ostart + flSize, src, srcSize);
  977. return srcSize + flSize;
  978. }
  979. static size_t ZSTD_compressRleLiteralsBlock (void* dst, size_t dstCapacity, const void* src, size_t srcSize)
  980. {
  981. BYTE* const ostart = (BYTE* const)dst;
  982. U32 const flSize = 1 + (srcSize>31) + (srcSize>4095);
  983. (void)dstCapacity; /* dstCapacity already guaranteed to be >=4, hence large enough */
  984. switch(flSize)
  985. {
  986. case 1: /* 2 - 1 - 5 */
  987. ostart[0] = (BYTE)((U32)set_rle + (srcSize<<3));
  988. break;
  989. case 2: /* 2 - 2 - 12 */
  990. MEM_writeLE16(ostart, (U16)((U32)set_rle + (1<<2) + (srcSize<<4)));
  991. break;
  992. case 3: /* 2 - 2 - 20 */
  993. MEM_writeLE32(ostart, (U32)((U32)set_rle + (3<<2) + (srcSize<<4)));
  994. break;
  995. default: /* not necessary : flSize is {1,2,3} */
  996. assert(0);
  997. }
  998. ostart[flSize] = *(const BYTE*)src;
  999. return flSize+1;
  1000. }
  1001. static size_t ZSTD_minGain(size_t srcSize) { return (srcSize >> 6) + 2; }
  1002. static size_t ZSTD_compressLiterals (ZSTD_entropyCTables_t * entropy,
  1003. ZSTD_strategy strategy,
  1004. void* dst, size_t dstCapacity,
  1005. const void* src, size_t srcSize)
  1006. {
  1007. size_t const minGain = ZSTD_minGain(srcSize);
  1008. size_t const lhSize = 3 + (srcSize >= 1 KB) + (srcSize >= 16 KB);
  1009. BYTE* const ostart = (BYTE*)dst;
  1010. U32 singleStream = srcSize < 256;
  1011. symbolEncodingType_e hType = set_compressed;
  1012. size_t cLitSize;
  1013. /* small ? don't even attempt compression (speed opt) */
  1014. # define LITERAL_NOENTROPY 63
  1015. { size_t const minLitSize = entropy->hufCTable_repeatMode == HUF_repeat_valid ? 6 : LITERAL_NOENTROPY;
  1016. if (srcSize <= minLitSize) return ZSTD_noCompressLiterals(dst, dstCapacity, src, srcSize);
  1017. }
  1018. if (dstCapacity < lhSize+1) return ERROR(dstSize_tooSmall); /* not enough space for compression */
  1019. { HUF_repeat repeat = entropy->hufCTable_repeatMode;
  1020. int const preferRepeat = strategy < ZSTD_lazy ? srcSize <= 1024 : 0;
  1021. if (repeat == HUF_repeat_valid && lhSize == 3) singleStream = 1;
  1022. cLitSize = singleStream ? HUF_compress1X_repeat(ostart+lhSize, dstCapacity-lhSize, src, srcSize, 255, 11,
  1023. entropy->workspace, sizeof(entropy->workspace), (HUF_CElt*)entropy->hufCTable, &repeat, preferRepeat)
  1024. : HUF_compress4X_repeat(ostart+lhSize, dstCapacity-lhSize, src, srcSize, 255, 11,
  1025. entropy->workspace, sizeof(entropy->workspace), (HUF_CElt*)entropy->hufCTable, &repeat, preferRepeat);
  1026. if (repeat != HUF_repeat_none) { hType = set_repeat; } /* reused the existing table */
  1027. else { entropy->hufCTable_repeatMode = HUF_repeat_check; } /* now have a table to reuse */
  1028. }
  1029. if ((cLitSize==0) | (cLitSize >= srcSize - minGain) | ERR_isError(cLitSize)) {
  1030. entropy->hufCTable_repeatMode = HUF_repeat_none;
  1031. return ZSTD_noCompressLiterals(dst, dstCapacity, src, srcSize);
  1032. }
  1033. if (cLitSize==1) {
  1034. entropy->hufCTable_repeatMode = HUF_repeat_none;
  1035. return ZSTD_compressRleLiteralsBlock(dst, dstCapacity, src, srcSize);
  1036. }
  1037. /* Build header */
  1038. switch(lhSize)
  1039. {
  1040. case 3: /* 2 - 2 - 10 - 10 */
  1041. { U32 const lhc = hType + ((!singleStream) << 2) + ((U32)srcSize<<4) + ((U32)cLitSize<<14);
  1042. MEM_writeLE24(ostart, lhc);
  1043. break;
  1044. }
  1045. case 4: /* 2 - 2 - 14 - 14 */
  1046. { U32 const lhc = hType + (2 << 2) + ((U32)srcSize<<4) + ((U32)cLitSize<<18);
  1047. MEM_writeLE32(ostart, lhc);
  1048. break;
  1049. }
  1050. case 5: /* 2 - 2 - 18 - 18 */
  1051. { U32 const lhc = hType + (3 << 2) + ((U32)srcSize<<4) + ((U32)cLitSize<<22);
  1052. MEM_writeLE32(ostart, lhc);
  1053. ostart[4] = (BYTE)(cLitSize >> 10);
  1054. break;
  1055. }
  1056. default: /* not possible : lhSize is {3,4,5} */
  1057. assert(0);
  1058. }
  1059. return lhSize+cLitSize;
  1060. }
  1061. void ZSTD_seqToCodes(const seqStore_t* seqStorePtr)
  1062. {
  1063. BYTE const LL_deltaCode = 19;
  1064. BYTE const ML_deltaCode = 36;
  1065. const seqDef* const sequences = seqStorePtr->sequencesStart;
  1066. BYTE* const llCodeTable = seqStorePtr->llCode;
  1067. BYTE* const ofCodeTable = seqStorePtr->ofCode;
  1068. BYTE* const mlCodeTable = seqStorePtr->mlCode;
  1069. U32 const nbSeq = (U32)(seqStorePtr->sequences - seqStorePtr->sequencesStart);
  1070. U32 u;
  1071. for (u=0; u<nbSeq; u++) {
  1072. U32 const llv = sequences[u].litLength;
  1073. U32 const mlv = sequences[u].matchLength;
  1074. llCodeTable[u] = (llv> 63) ? (BYTE)ZSTD_highbit32(llv) + LL_deltaCode : LL_Code[llv];
  1075. ofCodeTable[u] = (BYTE)ZSTD_highbit32(sequences[u].offset);
  1076. mlCodeTable[u] = (mlv>127) ? (BYTE)ZSTD_highbit32(mlv) + ML_deltaCode : ML_Code[mlv];
  1077. }
  1078. if (seqStorePtr->longLengthID==1)
  1079. llCodeTable[seqStorePtr->longLengthPos] = MaxLL;
  1080. if (seqStorePtr->longLengthID==2)
  1081. mlCodeTable[seqStorePtr->longLengthPos] = MaxML;
  1082. }
  1083. MEM_STATIC symbolEncodingType_e ZSTD_selectEncodingType(FSE_repeat* repeatMode,
  1084. size_t const mostFrequent, size_t nbSeq, U32 defaultNormLog)
  1085. {
  1086. #define MIN_SEQ_FOR_DYNAMIC_FSE 64
  1087. #define MAX_SEQ_FOR_STATIC_FSE 1000
  1088. if ((mostFrequent == nbSeq) && (nbSeq > 2)) {
  1089. *repeatMode = FSE_repeat_check;
  1090. return set_rle;
  1091. }
  1092. if ((*repeatMode == FSE_repeat_valid) && (nbSeq < MAX_SEQ_FOR_STATIC_FSE)) {
  1093. return set_repeat;
  1094. }
  1095. if ((nbSeq < MIN_SEQ_FOR_DYNAMIC_FSE) || (mostFrequent < (nbSeq >> (defaultNormLog-1)))) {
  1096. *repeatMode = FSE_repeat_valid;
  1097. return set_basic;
  1098. }
  1099. *repeatMode = FSE_repeat_check;
  1100. return set_compressed;
  1101. }
  1102. MEM_STATIC size_t ZSTD_buildCTable(void* dst, size_t dstCapacity,
  1103. FSE_CTable* CTable, U32 FSELog, symbolEncodingType_e type,
  1104. U32* count, U32 max,
  1105. BYTE const* codeTable, size_t nbSeq,
  1106. S16 const* defaultNorm, U32 defaultNormLog, U32 defaultMax,
  1107. void* workspace, size_t workspaceSize)
  1108. {
  1109. BYTE* op = (BYTE*)dst;
  1110. BYTE const* const oend = op + dstCapacity;
  1111. switch (type) {
  1112. case set_rle:
  1113. *op = codeTable[0];
  1114. CHECK_F(FSE_buildCTable_rle(CTable, (BYTE)max));
  1115. return 1;
  1116. case set_repeat:
  1117. return 0;
  1118. case set_basic:
  1119. CHECK_F(FSE_buildCTable_wksp(CTable, defaultNorm, defaultMax, defaultNormLog, workspace, workspaceSize));
  1120. return 0;
  1121. case set_compressed: {
  1122. S16 norm[MaxSeq + 1];
  1123. size_t nbSeq_1 = nbSeq;
  1124. const U32 tableLog = FSE_optimalTableLog(FSELog, nbSeq, max);
  1125. if (count[codeTable[nbSeq-1]] > 1) {
  1126. count[codeTable[nbSeq-1]]--;
  1127. nbSeq_1--;
  1128. }
  1129. CHECK_F(FSE_normalizeCount(norm, tableLog, count, nbSeq_1, max));
  1130. { size_t const NCountSize = FSE_writeNCount(op, oend - op, norm, max, tableLog); /* overflow protected */
  1131. if (FSE_isError(NCountSize)) return NCountSize;
  1132. CHECK_F(FSE_buildCTable_wksp(CTable, norm, max, tableLog, workspace, workspaceSize));
  1133. return NCountSize;
  1134. }
  1135. }
  1136. default: return assert(0), ERROR(GENERIC);
  1137. }
  1138. }
  1139. MEM_STATIC size_t ZSTD_encodeSequences(void* dst, size_t dstCapacity,
  1140. FSE_CTable const* CTable_MatchLength, BYTE const* mlCodeTable,
  1141. FSE_CTable const* CTable_OffsetBits, BYTE const* ofCodeTable,
  1142. FSE_CTable const* CTable_LitLength, BYTE const* llCodeTable,
  1143. seqDef const* sequences, size_t nbSeq, int longOffsets)
  1144. {
  1145. BIT_CStream_t blockStream;
  1146. FSE_CState_t stateMatchLength;
  1147. FSE_CState_t stateOffsetBits;
  1148. FSE_CState_t stateLitLength;
  1149. CHECK_E(BIT_initCStream(&blockStream, dst, dstCapacity), dstSize_tooSmall); /* not enough space remaining */
  1150. /* first symbols */
  1151. FSE_initCState2(&stateMatchLength, CTable_MatchLength, mlCodeTable[nbSeq-1]);
  1152. FSE_initCState2(&stateOffsetBits, CTable_OffsetBits, ofCodeTable[nbSeq-1]);
  1153. FSE_initCState2(&stateLitLength, CTable_LitLength, llCodeTable[nbSeq-1]);
  1154. BIT_addBits(&blockStream, sequences[nbSeq-1].litLength, LL_bits[llCodeTable[nbSeq-1]]);
  1155. if (MEM_32bits()) BIT_flushBits(&blockStream);
  1156. BIT_addBits(&blockStream, sequences[nbSeq-1].matchLength, ML_bits[mlCodeTable[nbSeq-1]]);
  1157. if (MEM_32bits()) BIT_flushBits(&blockStream);
  1158. if (longOffsets) {
  1159. U32 const ofBits = ofCodeTable[nbSeq-1];
  1160. int const extraBits = ofBits - MIN(ofBits, STREAM_ACCUMULATOR_MIN-1);
  1161. if (extraBits) {
  1162. BIT_addBits(&blockStream, sequences[nbSeq-1].offset, extraBits);
  1163. BIT_flushBits(&blockStream);
  1164. }
  1165. BIT_addBits(&blockStream, sequences[nbSeq-1].offset >> extraBits,
  1166. ofBits - extraBits);
  1167. } else {
  1168. BIT_addBits(&blockStream, sequences[nbSeq-1].offset, ofCodeTable[nbSeq-1]);
  1169. }
  1170. BIT_flushBits(&blockStream);
  1171. { size_t n;
  1172. for (n=nbSeq-2 ; n<nbSeq ; n--) { /* intentional underflow */
  1173. BYTE const llCode = llCodeTable[n];
  1174. BYTE const ofCode = ofCodeTable[n];
  1175. BYTE const mlCode = mlCodeTable[n];
  1176. U32 const llBits = LL_bits[llCode];
  1177. U32 const ofBits = ofCode; /* 32b*/ /* 64b*/
  1178. U32 const mlBits = ML_bits[mlCode];
  1179. /* (7)*/ /* (7)*/
  1180. FSE_encodeSymbol(&blockStream, &stateOffsetBits, ofCode); /* 15 */ /* 15 */
  1181. FSE_encodeSymbol(&blockStream, &stateMatchLength, mlCode); /* 24 */ /* 24 */
  1182. if (MEM_32bits()) BIT_flushBits(&blockStream); /* (7)*/
  1183. FSE_encodeSymbol(&blockStream, &stateLitLength, llCode); /* 16 */ /* 33 */
  1184. if (MEM_32bits() || (ofBits+mlBits+llBits >= 64-7-(LLFSELog+MLFSELog+OffFSELog)))
  1185. BIT_flushBits(&blockStream); /* (7)*/
  1186. BIT_addBits(&blockStream, sequences[n].litLength, llBits);
  1187. if (MEM_32bits() && ((llBits+mlBits)>24)) BIT_flushBits(&blockStream);
  1188. BIT_addBits(&blockStream, sequences[n].matchLength, mlBits);
  1189. if (MEM_32bits() || (ofBits+mlBits+llBits > 56)) BIT_flushBits(&blockStream);
  1190. if (longOffsets) {
  1191. int const extraBits = ofBits - MIN(ofBits, STREAM_ACCUMULATOR_MIN-1);
  1192. if (extraBits) {
  1193. BIT_addBits(&blockStream, sequences[n].offset, extraBits);
  1194. BIT_flushBits(&blockStream); /* (7)*/
  1195. }
  1196. BIT_addBits(&blockStream, sequences[n].offset >> extraBits,
  1197. ofBits - extraBits); /* 31 */
  1198. } else {
  1199. BIT_addBits(&blockStream, sequences[n].offset, ofBits); /* 31 */
  1200. }
  1201. BIT_flushBits(&blockStream); /* (7)*/
  1202. } }
  1203. FSE_flushCState(&blockStream, &stateMatchLength);
  1204. FSE_flushCState(&blockStream, &stateOffsetBits);
  1205. FSE_flushCState(&blockStream, &stateLitLength);
  1206. { size_t const streamSize = BIT_closeCStream(&blockStream);
  1207. if (streamSize==0) return ERROR(dstSize_tooSmall); /* not enough space */
  1208. return streamSize;
  1209. }
  1210. }
  1211. MEM_STATIC size_t ZSTD_compressSequences_internal(seqStore_t* seqStorePtr,
  1212. ZSTD_entropyCTables_t* entropy,
  1213. ZSTD_compressionParameters const* cParams,
  1214. void* dst, size_t dstCapacity)
  1215. {
  1216. const int longOffsets = cParams->windowLog > STREAM_ACCUMULATOR_MIN;
  1217. U32 count[MaxSeq+1];
  1218. FSE_CTable* CTable_LitLength = entropy->litlengthCTable;
  1219. FSE_CTable* CTable_OffsetBits = entropy->offcodeCTable;
  1220. FSE_CTable* CTable_MatchLength = entropy->matchlengthCTable;
  1221. U32 LLtype, Offtype, MLtype; /* compressed, raw or rle */
  1222. const seqDef* const sequences = seqStorePtr->sequencesStart;
  1223. const BYTE* const ofCodeTable = seqStorePtr->ofCode;
  1224. const BYTE* const llCodeTable = seqStorePtr->llCode;
  1225. const BYTE* const mlCodeTable = seqStorePtr->mlCode;
  1226. BYTE* const ostart = (BYTE*)dst;
  1227. BYTE* const oend = ostart + dstCapacity;
  1228. BYTE* op = ostart;
  1229. size_t const nbSeq = seqStorePtr->sequences - seqStorePtr->sequencesStart;
  1230. BYTE* seqHead;
  1231. ZSTD_STATIC_ASSERT(sizeof(entropy->workspace) >= (1<<MAX(MLFSELog,LLFSELog)));
  1232. /* Compress literals */
  1233. { const BYTE* const literals = seqStorePtr->litStart;
  1234. size_t const litSize = seqStorePtr->lit - literals;
  1235. size_t const cSize = ZSTD_compressLiterals(
  1236. entropy, cParams->strategy, op, dstCapacity, literals, litSize);
  1237. if (ZSTD_isError(cSize))
  1238. return cSize;
  1239. op += cSize;
  1240. }
  1241. /* Sequences Header */
  1242. if ((oend-op) < 3 /*max nbSeq Size*/ + 1 /*seqHead */) return ERROR(dstSize_tooSmall);
  1243. if (nbSeq < 0x7F) *op++ = (BYTE)nbSeq;
  1244. else if (nbSeq < LONGNBSEQ) op[0] = (BYTE)((nbSeq>>8) + 0x80), op[1] = (BYTE)nbSeq, op+=2;
  1245. else op[0]=0xFF, MEM_writeLE16(op+1, (U16)(nbSeq - LONGNBSEQ)), op+=3;
  1246. if (nbSeq==0) return op - ostart;
  1247. /* seqHead : flags for FSE encoding type */
  1248. seqHead = op++;
  1249. /* convert length/distances into codes */
  1250. ZSTD_seqToCodes(seqStorePtr);
  1251. /* CTable for Literal Lengths */
  1252. { U32 max = MaxLL;
  1253. size_t const mostFrequent = FSE_countFast_wksp(count, &max, llCodeTable, nbSeq, entropy->workspace);
  1254. LLtype = ZSTD_selectEncodingType(&entropy->litlength_repeatMode, mostFrequent, nbSeq, LL_defaultNormLog);
  1255. { size_t const countSize = ZSTD_buildCTable(op, oend - op, CTable_LitLength, LLFSELog, (symbolEncodingType_e)LLtype,
  1256. count, max, llCodeTable, nbSeq, LL_defaultNorm, LL_defaultNormLog, MaxLL,
  1257. entropy->workspace, sizeof(entropy->workspace));
  1258. if (ZSTD_isError(countSize)) return countSize;
  1259. op += countSize;
  1260. } }
  1261. /* CTable for Offsets */
  1262. { U32 max = MaxOff;
  1263. size_t const mostFrequent = FSE_countFast_wksp(count, &max, ofCodeTable, nbSeq, entropy->workspace);
  1264. Offtype = ZSTD_selectEncodingType(&entropy->offcode_repeatMode, mostFrequent, nbSeq, OF_defaultNormLog);
  1265. { size_t const countSize = ZSTD_buildCTable(op, oend - op, CTable_OffsetBits, OffFSELog, (symbolEncodingType_e)Offtype,
  1266. count, max, ofCodeTable, nbSeq, OF_defaultNorm, OF_defaultNormLog, MaxOff,
  1267. entropy->workspace, sizeof(entropy->workspace));
  1268. if (ZSTD_isError(countSize)) return countSize;
  1269. op += countSize;
  1270. } }
  1271. /* CTable for MatchLengths */
  1272. { U32 max = MaxML;
  1273. size_t const mostFrequent = FSE_countFast_wksp(count, &max, mlCodeTable, nbSeq, entropy->workspace);
  1274. MLtype = ZSTD_selectEncodingType(&entropy->matchlength_repeatMode, mostFrequent, nbSeq, ML_defaultNormLog);
  1275. { size_t const countSize = ZSTD_buildCTable(op, oend - op, CTable_MatchLength, MLFSELog, (symbolEncodingType_e)MLtype,
  1276. count, max, mlCodeTable, nbSeq, ML_defaultNorm, ML_defaultNormLog, MaxML,
  1277. entropy->workspace, sizeof(entropy->workspace));
  1278. if (ZSTD_isError(countSize)) return countSize;
  1279. op += countSize;
  1280. } }
  1281. *seqHead = (BYTE)((LLtype<<6) + (Offtype<<4) + (MLtype<<2));
  1282. { size_t const streamSize = ZSTD_encodeSequences(op, oend - op,
  1283. CTable_MatchLength, mlCodeTable,
  1284. CTable_OffsetBits, ofCodeTable,
  1285. CTable_LitLength, llCodeTable,
  1286. sequences, nbSeq, longOffsets);
  1287. if (ZSTD_isError(streamSize)) return streamSize;
  1288. op += streamSize;
  1289. }
  1290. return op - ostart;
  1291. }
  1292. MEM_STATIC size_t ZSTD_compressSequences(seqStore_t* seqStorePtr,
  1293. ZSTD_entropyCTables_t* entropy,
  1294. ZSTD_compressionParameters const* cParams,
  1295. void* dst, size_t dstCapacity,
  1296. size_t srcSize)
  1297. {
  1298. size_t const cSize = ZSTD_compressSequences_internal(seqStorePtr, entropy, cParams,
  1299. dst, dstCapacity);
  1300. size_t const minGain = ZSTD_minGain(srcSize);
  1301. size_t const maxCSize = srcSize - minGain;
  1302. /* If the srcSize <= dstCapacity, then there is enough space to write a
  1303. * raw uncompressed block. Since we ran out of space, the block must not
  1304. * be compressible, so fall back to a raw uncompressed block.
  1305. */
  1306. int const uncompressibleError = cSize == ERROR(dstSize_tooSmall) && srcSize <= dstCapacity;
  1307. if (ZSTD_isError(cSize) && !uncompressibleError)
  1308. return cSize;
  1309. /* Check compressibility */
  1310. if (cSize >= maxCSize || uncompressibleError) {
  1311. entropy->hufCTable_repeatMode = HUF_repeat_none;
  1312. entropy->offcode_repeatMode = FSE_repeat_none;
  1313. entropy->matchlength_repeatMode = FSE_repeat_none;
  1314. entropy->litlength_repeatMode = FSE_repeat_none;
  1315. return 0;
  1316. }
  1317. assert(!ZSTD_isError(cSize));
  1318. /* confirm repcodes */
  1319. { int i; for (i=0; i<ZSTD_REP_NUM; i++) seqStorePtr->rep[i] = seqStorePtr->repToConfirm[i]; }
  1320. return cSize;
  1321. }
  1322. /* ZSTD_selectBlockCompressor() :
  1323. * Not static, but internal use only (used by long distance matcher)
  1324. * assumption : strat is a valid strategy */
  1325. typedef size_t (*ZSTD_blockCompressor) (ZSTD_CCtx* ctx, const void* src, size_t srcSize);
  1326. ZSTD_blockCompressor ZSTD_selectBlockCompressor(ZSTD_strategy strat, int extDict)
  1327. {
  1328. static const ZSTD_blockCompressor blockCompressor[2][(unsigned)ZSTD_btultra+1] = {
  1329. { ZSTD_compressBlock_fast /* default for 0 */,
  1330. ZSTD_compressBlock_fast, ZSTD_compressBlock_doubleFast, ZSTD_compressBlock_greedy,
  1331. ZSTD_compressBlock_lazy, ZSTD_compressBlock_lazy2, ZSTD_compressBlock_btlazy2,
  1332. ZSTD_compressBlock_btopt, ZSTD_compressBlock_btultra },
  1333. { ZSTD_compressBlock_fast_extDict /* default for 0 */,
  1334. ZSTD_compressBlock_fast_extDict, ZSTD_compressBlock_doubleFast_extDict, ZSTD_compressBlock_greedy_extDict,
  1335. ZSTD_compressBlock_lazy_extDict,ZSTD_compressBlock_lazy2_extDict, ZSTD_compressBlock_btlazy2_extDict,
  1336. ZSTD_compressBlock_btopt_extDict, ZSTD_compressBlock_btultra_extDict }
  1337. };
  1338. ZSTD_STATIC_ASSERT((unsigned)ZSTD_fast == 1);
  1339. assert((U32)strat >= (U32)ZSTD_fast);
  1340. assert((U32)strat <= (U32)ZSTD_btultra);
  1341. return blockCompressor[extDict!=0][(U32)strat];
  1342. }
  1343. static void ZSTD_storeLastLiterals(seqStore_t* seqStorePtr,
  1344. const BYTE* anchor, size_t lastLLSize)
  1345. {
  1346. memcpy(seqStorePtr->lit, anchor, lastLLSize);
  1347. seqStorePtr->lit += lastLLSize;
  1348. }
  1349. static size_t ZSTD_compressBlock_internal(ZSTD_CCtx* zc, void* dst, size_t dstCapacity, const void* src, size_t srcSize)
  1350. {
  1351. const BYTE* const base = zc->base;
  1352. const BYTE* const istart = (const BYTE*)src;
  1353. const U32 current = (U32)(istart-base);
  1354. size_t lastLLSize;
  1355. const BYTE* anchor;
  1356. U32 const extDict = zc->lowLimit < zc->dictLimit;
  1357. const ZSTD_blockCompressor blockCompressor =
  1358. zc->appliedParams.ldmParams.enableLdm
  1359. ? (extDict ? ZSTD_compressBlock_ldm_extDict : ZSTD_compressBlock_ldm)
  1360. : ZSTD_selectBlockCompressor(zc->appliedParams.cParams.strategy, extDict);
  1361. if (srcSize < MIN_CBLOCK_SIZE+ZSTD_blockHeaderSize+1) return 0; /* don't even attempt compression below a certain srcSize */
  1362. ZSTD_resetSeqStore(&(zc->seqStore));
  1363. if (current > zc->nextToUpdate + 384)
  1364. zc->nextToUpdate = current - MIN(192, (U32)(current - zc->nextToUpdate - 384)); /* limited update after finding a very long match */
  1365. lastLLSize = blockCompressor(zc, src, srcSize);
  1366. /* Last literals */
  1367. anchor = (const BYTE*)src + srcSize - lastLLSize;
  1368. ZSTD_storeLastLiterals(&zc->seqStore, anchor, lastLLSize);
  1369. return ZSTD_compressSequences(&zc->seqStore, zc->entropy, &zc->appliedParams.cParams, dst, dstCapacity, srcSize);
  1370. }
  1371. /*! ZSTD_compress_frameChunk() :
  1372. * Compress a chunk of data into one or multiple blocks.
  1373. * All blocks will be terminated, all input will be consumed.
  1374. * Function will issue an error if there is not enough `dstCapacity` to hold the compressed content.
  1375. * Frame is supposed already started (header already produced)
  1376. * @return : compressed size, or an error code
  1377. */
  1378. static size_t ZSTD_compress_frameChunk (ZSTD_CCtx* cctx,
  1379. void* dst, size_t dstCapacity,
  1380. const void* src, size_t srcSize,
  1381. U32 lastFrameChunk)
  1382. {
  1383. size_t blockSize = cctx->blockSize;
  1384. size_t remaining = srcSize;
  1385. const BYTE* ip = (const BYTE*)src;
  1386. BYTE* const ostart = (BYTE*)dst;
  1387. BYTE* op = ostart;
  1388. U32 const maxDist = 1 << cctx->appliedParams.cParams.windowLog;
  1389. if (cctx->appliedParams.fParams.checksumFlag && srcSize)
  1390. XXH64_update(&cctx->xxhState, src, srcSize);
  1391. while (remaining) {
  1392. U32 const lastBlock = lastFrameChunk & (blockSize >= remaining);
  1393. size_t cSize;
  1394. if (dstCapacity < ZSTD_blockHeaderSize + MIN_CBLOCK_SIZE)
  1395. return ERROR(dstSize_tooSmall); /* not enough space to store compressed block */
  1396. if (remaining < blockSize) blockSize = remaining;
  1397. /* preemptive overflow correction */
  1398. if (cctx->lowLimit > (3U<<29)) {
  1399. U32 const cycleMask = (1 << ZSTD_cycleLog(cctx->appliedParams.cParams.hashLog, cctx->appliedParams.cParams.strategy)) - 1;
  1400. U32 const current = (U32)(ip - cctx->base);
  1401. U32 const newCurrent = (current & cycleMask) + (1 << cctx->appliedParams.cParams.windowLog);
  1402. U32 const correction = current - newCurrent;
  1403. ZSTD_STATIC_ASSERT(ZSTD_WINDOWLOG_MAX_64 <= 30);
  1404. ZSTD_reduceIndex(cctx, correction);
  1405. cctx->base += correction;
  1406. cctx->dictBase += correction;
  1407. cctx->lowLimit -= correction;
  1408. cctx->dictLimit -= correction;
  1409. if (cctx->nextToUpdate < correction) cctx->nextToUpdate = 0;
  1410. else cctx->nextToUpdate -= correction;
  1411. }
  1412. if ((U32)(ip+blockSize - cctx->base) > cctx->loadedDictEnd + maxDist) {
  1413. /* enforce maxDist */
  1414. U32 const newLowLimit = (U32)(ip+blockSize - cctx->base) - maxDist;
  1415. if (cctx->lowLimit < newLowLimit) cctx->lowLimit = newLowLimit;
  1416. if (cctx->dictLimit < cctx->lowLimit) cctx->dictLimit = cctx->lowLimit;
  1417. }
  1418. cSize = ZSTD_compressBlock_internal(cctx, op+ZSTD_blockHeaderSize, dstCapacity-ZSTD_blockHeaderSize, ip, blockSize);
  1419. if (ZSTD_isError(cSize)) return cSize;
  1420. if (cSize == 0) { /* block is not compressible */
  1421. U32 const cBlockHeader24 = lastBlock + (((U32)bt_raw)<<1) + (U32)(blockSize << 3);
  1422. if (blockSize + ZSTD_blockHeaderSize > dstCapacity) return ERROR(dstSize_tooSmall);
  1423. MEM_writeLE32(op, cBlockHeader24); /* no pb, 4th byte will be overwritten */
  1424. memcpy(op + ZSTD_blockHeaderSize, ip, blockSize);
  1425. cSize = ZSTD_blockHeaderSize+blockSize;
  1426. } else {
  1427. U32 const cBlockHeader24 = lastBlock + (((U32)bt_compressed)<<1) + (U32)(cSize << 3);
  1428. MEM_writeLE24(op, cBlockHeader24);
  1429. cSize += ZSTD_blockHeaderSize;
  1430. }
  1431. remaining -= blockSize;
  1432. dstCapacity -= cSize;
  1433. ip += blockSize;
  1434. op += cSize;
  1435. }
  1436. if (lastFrameChunk && (op>ostart)) cctx->stage = ZSTDcs_ending;
  1437. return op-ostart;
  1438. }
  1439. static size_t ZSTD_writeFrameHeader(void* dst, size_t dstCapacity,
  1440. ZSTD_CCtx_params params, U64 pledgedSrcSize, U32 dictID)
  1441. { BYTE* const op = (BYTE*)dst;
  1442. U32 const dictIDSizeCodeLength = (dictID>0) + (dictID>=256) + (dictID>=65536); /* 0-3 */
  1443. U32 const dictIDSizeCode = params.fParams.noDictIDFlag ? 0 : dictIDSizeCodeLength; /* 0-3 */
  1444. U32 const checksumFlag = params.fParams.checksumFlag>0;
  1445. U32 const windowSize = 1U << params.cParams.windowLog;
  1446. U32 const singleSegment = params.fParams.contentSizeFlag && (windowSize >= pledgedSrcSize);
  1447. BYTE const windowLogByte = (BYTE)((params.cParams.windowLog - ZSTD_WINDOWLOG_ABSOLUTEMIN) << 3);
  1448. U32 const fcsCode = params.fParams.contentSizeFlag ?
  1449. (pledgedSrcSize>=256) + (pledgedSrcSize>=65536+256) + (pledgedSrcSize>=0xFFFFFFFFU) : 0; /* 0-3 */
  1450. BYTE const frameHeaderDecriptionByte = (BYTE)(dictIDSizeCode + (checksumFlag<<2) + (singleSegment<<5) + (fcsCode<<6) );
  1451. size_t pos;
  1452. if (dstCapacity < ZSTD_frameHeaderSize_max) return ERROR(dstSize_tooSmall);
  1453. DEBUGLOG(5, "ZSTD_writeFrameHeader : dictIDFlag : %u ; dictID : %u ; dictIDSizeCode : %u",
  1454. !params.fParams.noDictIDFlag, dictID, dictIDSizeCode);
  1455. MEM_writeLE32(dst, ZSTD_MAGICNUMBER);
  1456. op[4] = frameHeaderDecriptionByte; pos=5;
  1457. if (!singleSegment) op[pos++] = windowLogByte;
  1458. switch(dictIDSizeCode)
  1459. {
  1460. default: assert(0); /* impossible */
  1461. case 0 : break;
  1462. case 1 : op[pos] = (BYTE)(dictID); pos++; break;
  1463. case 2 : MEM_writeLE16(op+pos, (U16)dictID); pos+=2; break;
  1464. case 3 : MEM_writeLE32(op+pos, dictID); pos+=4; break;
  1465. }
  1466. switch(fcsCode)
  1467. {
  1468. default: assert(0); /* impossible */
  1469. case 0 : if (singleSegment) op[pos++] = (BYTE)(pledgedSrcSize); break;
  1470. case 1 : MEM_writeLE16(op+pos, (U16)(pledgedSrcSize-256)); pos+=2; break;
  1471. case 2 : MEM_writeLE32(op+pos, (U32)(pledgedSrcSize)); pos+=4; break;
  1472. case 3 : MEM_writeLE64(op+pos, (U64)(pledgedSrcSize)); pos+=8; break;
  1473. }
  1474. return pos;
  1475. }
  1476. static size_t ZSTD_compressContinue_internal (ZSTD_CCtx* cctx,
  1477. void* dst, size_t dstCapacity,
  1478. const void* src, size_t srcSize,
  1479. U32 frame, U32 lastFrameChunk)
  1480. {
  1481. const BYTE* const ip = (const BYTE*) src;
  1482. size_t fhSize = 0;
  1483. DEBUGLOG(5, "ZSTD_compressContinue_internal");
  1484. DEBUGLOG(5, "stage: %u", cctx->stage);
  1485. if (cctx->stage==ZSTDcs_created) return ERROR(stage_wrong); /* missing init (ZSTD_compressBegin) */
  1486. if (frame && (cctx->stage==ZSTDcs_init)) {
  1487. fhSize = ZSTD_writeFrameHeader(dst, dstCapacity, cctx->appliedParams,
  1488. cctx->pledgedSrcSizePlusOne-1, cctx->dictID);
  1489. if (ZSTD_isError(fhSize)) return fhSize;
  1490. dstCapacity -= fhSize;
  1491. dst = (char*)dst + fhSize;
  1492. cctx->stage = ZSTDcs_ongoing;
  1493. }
  1494. /* Check if blocks follow each other */
  1495. if (src != cctx->nextSrc) {
  1496. /* not contiguous */
  1497. ptrdiff_t const delta = cctx->nextSrc - ip;
  1498. cctx->lowLimit = cctx->dictLimit;
  1499. cctx->dictLimit = (U32)(cctx->nextSrc - cctx->base);
  1500. cctx->dictBase = cctx->base;
  1501. cctx->base -= delta;
  1502. cctx->nextToUpdate = cctx->dictLimit;
  1503. if (cctx->dictLimit - cctx->lowLimit < HASH_READ_SIZE) cctx->lowLimit = cctx->dictLimit; /* too small extDict */
  1504. }
  1505. /* if input and dictionary overlap : reduce dictionary (area presumed modified by input) */
  1506. if ((ip+srcSize > cctx->dictBase + cctx->lowLimit) & (ip < cctx->dictBase + cctx->dictLimit)) {
  1507. ptrdiff_t const highInputIdx = (ip + srcSize) - cctx->dictBase;
  1508. U32 const lowLimitMax = (highInputIdx > (ptrdiff_t)cctx->dictLimit) ? cctx->dictLimit : (U32)highInputIdx;
  1509. cctx->lowLimit = lowLimitMax;
  1510. }
  1511. cctx->nextSrc = ip + srcSize;
  1512. if (srcSize) {
  1513. size_t const cSize = frame ?
  1514. ZSTD_compress_frameChunk (cctx, dst, dstCapacity, src, srcSize, lastFrameChunk) :
  1515. ZSTD_compressBlock_internal (cctx, dst, dstCapacity, src, srcSize);
  1516. if (ZSTD_isError(cSize)) return cSize;
  1517. cctx->consumedSrcSize += srcSize;
  1518. return cSize + fhSize;
  1519. } else
  1520. return fhSize;
  1521. }
  1522. size_t ZSTD_compressContinue (ZSTD_CCtx* cctx,
  1523. void* dst, size_t dstCapacity,
  1524. const void* src, size_t srcSize)
  1525. {
  1526. return ZSTD_compressContinue_internal(cctx, dst, dstCapacity, src, srcSize, 1 /* frame mode */, 0 /* last chunk */);
  1527. }
  1528. size_t ZSTD_getBlockSize(const ZSTD_CCtx* cctx)
  1529. {
  1530. ZSTD_compressionParameters const cParams =
  1531. ZSTD_getCParamsFromCCtxParams(cctx->appliedParams, 0, 0);
  1532. return MIN (ZSTD_BLOCKSIZE_MAX, 1 << cParams.windowLog);
  1533. }
  1534. size_t ZSTD_compressBlock(ZSTD_CCtx* cctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize)
  1535. {
  1536. size_t const blockSizeMax = ZSTD_getBlockSize(cctx);
  1537. if (srcSize > blockSizeMax) return ERROR(srcSize_wrong);
  1538. return ZSTD_compressContinue_internal(cctx, dst, dstCapacity, src, srcSize, 0 /* frame mode */, 0 /* last chunk */);
  1539. }
  1540. /*! ZSTD_loadDictionaryContent() :
  1541. * @return : 0, or an error code
  1542. */
  1543. static size_t ZSTD_loadDictionaryContent(ZSTD_CCtx* zc, const void* src, size_t srcSize)
  1544. {
  1545. const BYTE* const ip = (const BYTE*) src;
  1546. const BYTE* const iend = ip + srcSize;
  1547. /* input becomes current prefix */
  1548. zc->lowLimit = zc->dictLimit;
  1549. zc->dictLimit = (U32)(zc->nextSrc - zc->base);
  1550. zc->dictBase = zc->base;
  1551. zc->base += ip - zc->nextSrc;
  1552. zc->nextToUpdate = zc->dictLimit;
  1553. zc->loadedDictEnd = zc->appliedParams.forceWindow ? 0 : (U32)(iend - zc->base);
  1554. zc->nextSrc = iend;
  1555. if (srcSize <= HASH_READ_SIZE) return 0;
  1556. switch(zc->appliedParams.cParams.strategy)
  1557. {
  1558. case ZSTD_fast:
  1559. ZSTD_fillHashTable (zc, iend, zc->appliedParams.cParams.searchLength);
  1560. break;
  1561. case ZSTD_dfast:
  1562. ZSTD_fillDoubleHashTable (zc, iend, zc->appliedParams.cParams.searchLength);
  1563. break;
  1564. case ZSTD_greedy:
  1565. case ZSTD_lazy:
  1566. case ZSTD_lazy2:
  1567. if (srcSize >= HASH_READ_SIZE)
  1568. ZSTD_insertAndFindFirstIndex(zc, iend-HASH_READ_SIZE, zc->appliedParams.cParams.searchLength);
  1569. break;
  1570. case ZSTD_btlazy2:
  1571. case ZSTD_btopt:
  1572. case ZSTD_btultra:
  1573. if (srcSize >= HASH_READ_SIZE)
  1574. ZSTD_updateTree(zc, iend-HASH_READ_SIZE, iend, 1 << zc->appliedParams.cParams.searchLog, zc->appliedParams.cParams.searchLength);
  1575. break;
  1576. default:
  1577. assert(0); /* not possible : not a valid strategy id */
  1578. }
  1579. zc->nextToUpdate = (U32)(iend - zc->base);
  1580. return 0;
  1581. }
  1582. /* Dictionaries that assign zero probability to symbols that show up causes problems
  1583. when FSE encoding. Refuse dictionaries that assign zero probability to symbols
  1584. that we may encounter during compression.
  1585. NOTE: This behavior is not standard and could be improved in the future. */
  1586. static size_t ZSTD_checkDictNCount(short* normalizedCounter, unsigned dictMaxSymbolValue, unsigned maxSymbolValue) {
  1587. U32 s;
  1588. if (dictMaxSymbolValue < maxSymbolValue) return ERROR(dictionary_corrupted);
  1589. for (s = 0; s <= maxSymbolValue; ++s) {
  1590. if (normalizedCounter[s] == 0) return ERROR(dictionary_corrupted);
  1591. }
  1592. return 0;
  1593. }
  1594. /* Dictionary format :
  1595. * See :
  1596. * https://github.com/facebook/zstd/blob/master/doc/zstd_compression_format.md#dictionary-format
  1597. */
  1598. /*! ZSTD_loadZstdDictionary() :
  1599. * @return : 0, or an error code
  1600. * assumptions : magic number supposed already checked
  1601. * dictSize supposed > 8
  1602. */
  1603. static size_t ZSTD_loadZstdDictionary(ZSTD_CCtx* cctx, const void* dict, size_t dictSize)
  1604. {
  1605. const BYTE* dictPtr = (const BYTE*)dict;
  1606. const BYTE* const dictEnd = dictPtr + dictSize;
  1607. short offcodeNCount[MaxOff+1];
  1608. unsigned offcodeMaxValue = MaxOff;
  1609. ZSTD_STATIC_ASSERT(sizeof(cctx->entropy->workspace) >= (1<<MAX(MLFSELog,LLFSELog)));
  1610. dictPtr += 4; /* skip magic number */
  1611. cctx->dictID = cctx->appliedParams.fParams.noDictIDFlag ? 0 : MEM_readLE32(dictPtr);
  1612. dictPtr += 4;
  1613. { size_t const hufHeaderSize = HUF_readCTable((HUF_CElt*)cctx->entropy->hufCTable, 255, dictPtr, dictEnd-dictPtr);
  1614. if (HUF_isError(hufHeaderSize)) return ERROR(dictionary_corrupted);
  1615. dictPtr += hufHeaderSize;
  1616. }
  1617. { unsigned offcodeLog;
  1618. size_t const offcodeHeaderSize = FSE_readNCount(offcodeNCount, &offcodeMaxValue, &offcodeLog, dictPtr, dictEnd-dictPtr);
  1619. if (FSE_isError(offcodeHeaderSize)) return ERROR(dictionary_corrupted);
  1620. if (offcodeLog > OffFSELog) return ERROR(dictionary_corrupted);
  1621. /* Defer checking offcodeMaxValue because we need to know the size of the dictionary content */
  1622. CHECK_E( FSE_buildCTable_wksp(cctx->entropy->offcodeCTable, offcodeNCount, offcodeMaxValue, offcodeLog, cctx->entropy->workspace, sizeof(cctx->entropy->workspace)),
  1623. dictionary_corrupted);
  1624. dictPtr += offcodeHeaderSize;
  1625. }
  1626. { short matchlengthNCount[MaxML+1];
  1627. unsigned matchlengthMaxValue = MaxML, matchlengthLog;
  1628. size_t const matchlengthHeaderSize = FSE_readNCount(matchlengthNCount, &matchlengthMaxValue, &matchlengthLog, dictPtr, dictEnd-dictPtr);
  1629. if (FSE_isError(matchlengthHeaderSize)) return ERROR(dictionary_corrupted);
  1630. if (matchlengthLog > MLFSELog) return ERROR(dictionary_corrupted);
  1631. /* Every match length code must have non-zero probability */
  1632. CHECK_F( ZSTD_checkDictNCount(matchlengthNCount, matchlengthMaxValue, MaxML));
  1633. CHECK_E( FSE_buildCTable_wksp(cctx->entropy->matchlengthCTable, matchlengthNCount, matchlengthMaxValue, matchlengthLog, cctx->entropy->workspace, sizeof(cctx->entropy->workspace)),
  1634. dictionary_corrupted);
  1635. dictPtr += matchlengthHeaderSize;
  1636. }
  1637. { short litlengthNCount[MaxLL+1];
  1638. unsigned litlengthMaxValue = MaxLL, litlengthLog;
  1639. size_t const litlengthHeaderSize = FSE_readNCount(litlengthNCount, &litlengthMaxValue, &litlengthLog, dictPtr, dictEnd-dictPtr);
  1640. if (FSE_isError(litlengthHeaderSize)) return ERROR(dictionary_corrupted);
  1641. if (litlengthLog > LLFSELog) return ERROR(dictionary_corrupted);
  1642. /* Every literal length code must have non-zero probability */
  1643. CHECK_F( ZSTD_checkDictNCount(litlengthNCount, litlengthMaxValue, MaxLL));
  1644. CHECK_E( FSE_buildCTable_wksp(cctx->entropy->litlengthCTable, litlengthNCount, litlengthMaxValue, litlengthLog, cctx->entropy->workspace, sizeof(cctx->entropy->workspace)),
  1645. dictionary_corrupted);
  1646. dictPtr += litlengthHeaderSize;
  1647. }
  1648. if (dictPtr+12 > dictEnd) return ERROR(dictionary_corrupted);
  1649. cctx->seqStore.rep[0] = MEM_readLE32(dictPtr+0);
  1650. cctx->seqStore.rep[1] = MEM_readLE32(dictPtr+4);
  1651. cctx->seqStore.rep[2] = MEM_readLE32(dictPtr+8);
  1652. dictPtr += 12;
  1653. { size_t const dictContentSize = (size_t)(dictEnd - dictPtr);
  1654. U32 offcodeMax = MaxOff;
  1655. if (dictContentSize <= ((U32)-1) - 128 KB) {
  1656. U32 const maxOffset = (U32)dictContentSize + 128 KB; /* The maximum offset that must be supported */
  1657. offcodeMax = ZSTD_highbit32(maxOffset); /* Calculate minimum offset code required to represent maxOffset */
  1658. }
  1659. /* All offset values <= dictContentSize + 128 KB must be representable */
  1660. CHECK_F (ZSTD_checkDictNCount(offcodeNCount, offcodeMaxValue, MIN(offcodeMax, MaxOff)));
  1661. /* All repCodes must be <= dictContentSize and != 0*/
  1662. { U32 u;
  1663. for (u=0; u<3; u++) {
  1664. if (cctx->seqStore.rep[u] == 0) return ERROR(dictionary_corrupted);
  1665. if (cctx->seqStore.rep[u] > dictContentSize) return ERROR(dictionary_corrupted);
  1666. } }
  1667. cctx->entropy->hufCTable_repeatMode = HUF_repeat_valid;
  1668. cctx->entropy->offcode_repeatMode = FSE_repeat_valid;
  1669. cctx->entropy->matchlength_repeatMode = FSE_repeat_valid;
  1670. cctx->entropy->litlength_repeatMode = FSE_repeat_valid;
  1671. return ZSTD_loadDictionaryContent(cctx, dictPtr, dictContentSize);
  1672. }
  1673. }
  1674. /** ZSTD_compress_insertDictionary() :
  1675. * @return : 0, or an error code */
  1676. static size_t ZSTD_compress_insertDictionary(ZSTD_CCtx* cctx,
  1677. const void* dict, size_t dictSize,
  1678. ZSTD_dictMode_e dictMode)
  1679. {
  1680. DEBUGLOG(5, "ZSTD_compress_insertDictionary");
  1681. if ((dict==NULL) || (dictSize<=8)) return 0;
  1682. /* dict restricted modes */
  1683. if (dictMode==ZSTD_dm_rawContent)
  1684. return ZSTD_loadDictionaryContent(cctx, dict, dictSize);
  1685. if (MEM_readLE32(dict) != ZSTD_MAGIC_DICTIONARY) {
  1686. if (dictMode == ZSTD_dm_auto) {
  1687. DEBUGLOG(5, "raw content dictionary detected");
  1688. return ZSTD_loadDictionaryContent(cctx, dict, dictSize);
  1689. }
  1690. if (dictMode == ZSTD_dm_fullDict)
  1691. return ERROR(dictionary_wrong);
  1692. assert(0); /* impossible */
  1693. }
  1694. /* dict as full zstd dictionary */
  1695. return ZSTD_loadZstdDictionary(cctx, dict, dictSize);
  1696. }
  1697. /*! ZSTD_compressBegin_internal() :
  1698. * @return : 0, or an error code */
  1699. static size_t ZSTD_compressBegin_internal(ZSTD_CCtx* cctx,
  1700. const void* dict, size_t dictSize,
  1701. ZSTD_dictMode_e dictMode,
  1702. const ZSTD_CDict* cdict,
  1703. ZSTD_CCtx_params params, U64 pledgedSrcSize,
  1704. ZSTD_buffered_policy_e zbuff)
  1705. {
  1706. DEBUGLOG(4, "ZSTD_compressBegin_internal");
  1707. DEBUGLOG(4, "dict ? %s", dict ? "dict" : (cdict ? "cdict" : "none"));
  1708. DEBUGLOG(4, "dictMode : %u", (U32)dictMode);
  1709. /* params are supposed to be fully validated at this point */
  1710. assert(!ZSTD_isError(ZSTD_checkCParams(params.cParams)));
  1711. assert(!((dict) && (cdict))); /* either dict or cdict, not both */
  1712. if (cdict && cdict->dictContentSize>0) {
  1713. return ZSTD_copyCCtx_internal(cctx, cdict->refContext,
  1714. params.fParams, pledgedSrcSize,
  1715. zbuff);
  1716. }
  1717. CHECK_F( ZSTD_resetCCtx_internal(cctx, params, pledgedSrcSize,
  1718. ZSTDcrp_continue, zbuff) );
  1719. return ZSTD_compress_insertDictionary(cctx, dict, dictSize, dictMode);
  1720. }
  1721. size_t ZSTD_compressBegin_advanced_internal(
  1722. ZSTD_CCtx* cctx,
  1723. const void* dict, size_t dictSize,
  1724. ZSTD_dictMode_e dictMode,
  1725. ZSTD_CCtx_params params,
  1726. unsigned long long pledgedSrcSize)
  1727. {
  1728. /* compression parameters verification and optimization */
  1729. CHECK_F( ZSTD_checkCParams(params.cParams) );
  1730. return ZSTD_compressBegin_internal(cctx, dict, dictSize, dictMode, NULL,
  1731. params, pledgedSrcSize,
  1732. ZSTDb_not_buffered);
  1733. }
  1734. /*! ZSTD_compressBegin_advanced() :
  1735. * @return : 0, or an error code */
  1736. size_t ZSTD_compressBegin_advanced(ZSTD_CCtx* cctx,
  1737. const void* dict, size_t dictSize,
  1738. ZSTD_parameters params, unsigned long long pledgedSrcSize)
  1739. {
  1740. ZSTD_CCtx_params const cctxParams =
  1741. ZSTD_assignParamsToCCtxParams(cctx->requestedParams, params);
  1742. return ZSTD_compressBegin_advanced_internal(cctx, dict, dictSize, ZSTD_dm_auto,
  1743. cctxParams,
  1744. pledgedSrcSize);
  1745. }
  1746. size_t ZSTD_compressBegin_usingDict(ZSTD_CCtx* cctx, const void* dict, size_t dictSize, int compressionLevel)
  1747. {
  1748. ZSTD_parameters const params = ZSTD_getParams(compressionLevel, 0, dictSize);
  1749. ZSTD_CCtx_params const cctxParams =
  1750. ZSTD_assignParamsToCCtxParams(cctx->requestedParams, params);
  1751. return ZSTD_compressBegin_internal(cctx, dict, dictSize, ZSTD_dm_auto, NULL,
  1752. cctxParams, 0, ZSTDb_not_buffered);
  1753. }
  1754. size_t ZSTD_compressBegin(ZSTD_CCtx* cctx, int compressionLevel)
  1755. {
  1756. return ZSTD_compressBegin_usingDict(cctx, NULL, 0, compressionLevel);
  1757. }
  1758. /*! ZSTD_writeEpilogue() :
  1759. * Ends a frame.
  1760. * @return : nb of bytes written into dst (or an error code) */
  1761. static size_t ZSTD_writeEpilogue(ZSTD_CCtx* cctx, void* dst, size_t dstCapacity)
  1762. {
  1763. BYTE* const ostart = (BYTE*)dst;
  1764. BYTE* op = ostart;
  1765. size_t fhSize = 0;
  1766. DEBUGLOG(5, "ZSTD_writeEpilogue");
  1767. if (cctx->stage == ZSTDcs_created) return ERROR(stage_wrong); /* init missing */
  1768. /* special case : empty frame */
  1769. if (cctx->stage == ZSTDcs_init) {
  1770. fhSize = ZSTD_writeFrameHeader(dst, dstCapacity, cctx->appliedParams, 0, 0);
  1771. if (ZSTD_isError(fhSize)) return fhSize;
  1772. dstCapacity -= fhSize;
  1773. op += fhSize;
  1774. cctx->stage = ZSTDcs_ongoing;
  1775. }
  1776. if (cctx->stage != ZSTDcs_ending) {
  1777. /* write one last empty block, make it the "last" block */
  1778. U32 const cBlockHeader24 = 1 /* last block */ + (((U32)bt_raw)<<1) + 0;
  1779. if (dstCapacity<4) return ERROR(dstSize_tooSmall);
  1780. MEM_writeLE32(op, cBlockHeader24);
  1781. op += ZSTD_blockHeaderSize;
  1782. dstCapacity -= ZSTD_blockHeaderSize;
  1783. }
  1784. if (cctx->appliedParams.fParams.checksumFlag) {
  1785. U32 const checksum = (U32) XXH64_digest(&cctx->xxhState);
  1786. if (dstCapacity<4) return ERROR(dstSize_tooSmall);
  1787. MEM_writeLE32(op, checksum);
  1788. op += 4;
  1789. }
  1790. cctx->stage = ZSTDcs_created; /* return to "created but no init" status */
  1791. return op-ostart;
  1792. }
  1793. size_t ZSTD_compressEnd (ZSTD_CCtx* cctx,
  1794. void* dst, size_t dstCapacity,
  1795. const void* src, size_t srcSize)
  1796. {
  1797. size_t endResult;
  1798. size_t const cSize = ZSTD_compressContinue_internal(cctx,
  1799. dst, dstCapacity, src, srcSize,
  1800. 1 /* frame mode */, 1 /* last chunk */);
  1801. if (ZSTD_isError(cSize)) return cSize;
  1802. endResult = ZSTD_writeEpilogue(cctx, (char*)dst + cSize, dstCapacity-cSize);
  1803. if (ZSTD_isError(endResult)) return endResult;
  1804. if (cctx->appliedParams.fParams.contentSizeFlag) { /* control src size */
  1805. DEBUGLOG(5, "end of frame : controlling src size");
  1806. if (cctx->pledgedSrcSizePlusOne != cctx->consumedSrcSize+1) {
  1807. DEBUGLOG(5, "error : pledgedSrcSize = %u, while realSrcSize = %u",
  1808. (U32)cctx->pledgedSrcSizePlusOne-1, (U32)cctx->consumedSrcSize);
  1809. return ERROR(srcSize_wrong);
  1810. } }
  1811. return cSize + endResult;
  1812. }
  1813. static size_t ZSTD_compress_internal (ZSTD_CCtx* cctx,
  1814. void* dst, size_t dstCapacity,
  1815. const void* src, size_t srcSize,
  1816. const void* dict,size_t dictSize,
  1817. ZSTD_parameters params)
  1818. {
  1819. ZSTD_CCtx_params const cctxParams =
  1820. ZSTD_assignParamsToCCtxParams(cctx->requestedParams, params);
  1821. return ZSTD_compress_advanced_internal(cctx,
  1822. dst, dstCapacity,
  1823. src, srcSize,
  1824. dict, dictSize,
  1825. cctxParams);
  1826. }
  1827. size_t ZSTD_compress_advanced (ZSTD_CCtx* ctx,
  1828. void* dst, size_t dstCapacity,
  1829. const void* src, size_t srcSize,
  1830. const void* dict,size_t dictSize,
  1831. ZSTD_parameters params)
  1832. {
  1833. CHECK_F(ZSTD_checkCParams(params.cParams));
  1834. return ZSTD_compress_internal(ctx, dst, dstCapacity, src, srcSize, dict, dictSize, params);
  1835. }
  1836. /* Internal */
  1837. size_t ZSTD_compress_advanced_internal(
  1838. ZSTD_CCtx* cctx,
  1839. void* dst, size_t dstCapacity,
  1840. const void* src, size_t srcSize,
  1841. const void* dict,size_t dictSize,
  1842. ZSTD_CCtx_params params)
  1843. {
  1844. CHECK_F( ZSTD_compressBegin_internal(cctx, dict, dictSize, ZSTD_dm_auto, NULL,
  1845. params, srcSize, ZSTDb_not_buffered) );
  1846. return ZSTD_compressEnd(cctx, dst, dstCapacity, src, srcSize);
  1847. }
  1848. size_t ZSTD_compress_usingDict(ZSTD_CCtx* ctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize,
  1849. const void* dict, size_t dictSize, int compressionLevel)
  1850. {
  1851. ZSTD_parameters params = ZSTD_getParams(compressionLevel, srcSize, dict ? dictSize : 0);
  1852. params.fParams.contentSizeFlag = 1;
  1853. return ZSTD_compress_internal(ctx, dst, dstCapacity, src, srcSize, dict, dictSize, params);
  1854. }
  1855. size_t ZSTD_compressCCtx (ZSTD_CCtx* ctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize, int compressionLevel)
  1856. {
  1857. return ZSTD_compress_usingDict(ctx, dst, dstCapacity, src, srcSize, NULL, 0, compressionLevel);
  1858. }
  1859. size_t ZSTD_compress(void* dst, size_t dstCapacity, const void* src, size_t srcSize, int compressionLevel)
  1860. {
  1861. size_t result;
  1862. ZSTD_CCtx ctxBody;
  1863. memset(&ctxBody, 0, sizeof(ctxBody));
  1864. ctxBody.customMem = ZSTD_defaultCMem;
  1865. result = ZSTD_compressCCtx(&ctxBody, dst, dstCapacity, src, srcSize, compressionLevel);
  1866. ZSTD_free(ctxBody.workSpace, ZSTD_defaultCMem); /* can't free ctxBody itself, as it's on stack; free only heap content */
  1867. return result;
  1868. }
  1869. /* ===== Dictionary API ===== */
  1870. /*! ZSTD_estimateCDictSize_advanced() :
  1871. * Estimate amount of memory that will be needed to create a dictionary with following arguments */
  1872. size_t ZSTD_estimateCDictSize_advanced(
  1873. size_t dictSize, ZSTD_compressionParameters cParams,
  1874. ZSTD_dictLoadMethod_e dictLoadMethod)
  1875. {
  1876. DEBUGLOG(5, "sizeof(ZSTD_CDict) : %u", (U32)sizeof(ZSTD_CDict));
  1877. DEBUGLOG(5, "CCtx estimate : %u",
  1878. (U32)ZSTD_estimateCCtxSize_advanced_usingCParams(cParams));
  1879. return sizeof(ZSTD_CDict) + ZSTD_estimateCCtxSize_advanced_usingCParams(cParams)
  1880. + (dictLoadMethod == ZSTD_dlm_byRef ? 0 : dictSize);
  1881. }
  1882. size_t ZSTD_estimateCDictSize(size_t dictSize, int compressionLevel)
  1883. {
  1884. ZSTD_compressionParameters const cParams = ZSTD_getCParams(compressionLevel, 0, dictSize);
  1885. return ZSTD_estimateCDictSize_advanced(dictSize, cParams, ZSTD_dlm_byCopy);
  1886. }
  1887. size_t ZSTD_sizeof_CDict(const ZSTD_CDict* cdict)
  1888. {
  1889. if (cdict==NULL) return 0; /* support sizeof on NULL */
  1890. DEBUGLOG(5, "sizeof(*cdict) : %u", (U32)sizeof(*cdict));
  1891. DEBUGLOG(5, "ZSTD_sizeof_CCtx : %u", (U32)ZSTD_sizeof_CCtx(cdict->refContext));
  1892. return ZSTD_sizeof_CCtx(cdict->refContext) + (cdict->dictBuffer ? cdict->dictContentSize : 0) + sizeof(*cdict);
  1893. }
  1894. static size_t ZSTD_initCDict_internal(
  1895. ZSTD_CDict* cdict,
  1896. const void* dictBuffer, size_t dictSize,
  1897. ZSTD_dictLoadMethod_e dictLoadMethod,
  1898. ZSTD_dictMode_e dictMode,
  1899. ZSTD_compressionParameters cParams)
  1900. {
  1901. DEBUGLOG(5, "ZSTD_initCDict_internal, mode %u", (U32)dictMode);
  1902. if ((dictLoadMethod == ZSTD_dlm_byRef) || (!dictBuffer) || (!dictSize)) {
  1903. cdict->dictBuffer = NULL;
  1904. cdict->dictContent = dictBuffer;
  1905. } else {
  1906. void* const internalBuffer = ZSTD_malloc(dictSize, cdict->refContext->customMem);
  1907. cdict->dictBuffer = internalBuffer;
  1908. cdict->dictContent = internalBuffer;
  1909. if (!internalBuffer) return ERROR(memory_allocation);
  1910. memcpy(internalBuffer, dictBuffer, dictSize);
  1911. }
  1912. cdict->dictContentSize = dictSize;
  1913. { ZSTD_CCtx_params cctxParams = cdict->refContext->requestedParams;
  1914. cctxParams.cParams = cParams;
  1915. CHECK_F( ZSTD_compressBegin_internal(cdict->refContext,
  1916. cdict->dictContent, dictSize, dictMode,
  1917. NULL,
  1918. cctxParams, ZSTD_CONTENTSIZE_UNKNOWN,
  1919. ZSTDb_not_buffered) );
  1920. }
  1921. return 0;
  1922. }
  1923. ZSTD_CDict* ZSTD_createCDict_advanced(const void* dictBuffer, size_t dictSize,
  1924. ZSTD_dictLoadMethod_e dictLoadMethod,
  1925. ZSTD_dictMode_e dictMode,
  1926. ZSTD_compressionParameters cParams, ZSTD_customMem customMem)
  1927. {
  1928. DEBUGLOG(5, "ZSTD_createCDict_advanced, mode %u", (U32)dictMode);
  1929. if (!customMem.customAlloc ^ !customMem.customFree) return NULL;
  1930. { ZSTD_CDict* const cdict = (ZSTD_CDict*)ZSTD_malloc(sizeof(ZSTD_CDict), customMem);
  1931. ZSTD_CCtx* const cctx = ZSTD_createCCtx_advanced(customMem);
  1932. if (!cdict || !cctx) {
  1933. ZSTD_free(cdict, customMem);
  1934. ZSTD_freeCCtx(cctx);
  1935. return NULL;
  1936. }
  1937. cdict->refContext = cctx;
  1938. if (ZSTD_isError( ZSTD_initCDict_internal(cdict,
  1939. dictBuffer, dictSize,
  1940. dictLoadMethod, dictMode,
  1941. cParams) )) {
  1942. ZSTD_freeCDict(cdict);
  1943. return NULL;
  1944. }
  1945. return cdict;
  1946. }
  1947. }
  1948. ZSTD_CDict* ZSTD_createCDict(const void* dict, size_t dictSize, int compressionLevel)
  1949. {
  1950. ZSTD_compressionParameters cParams = ZSTD_getCParams(compressionLevel, 0, dictSize);
  1951. return ZSTD_createCDict_advanced(dict, dictSize,
  1952. ZSTD_dlm_byCopy, ZSTD_dm_auto,
  1953. cParams, ZSTD_defaultCMem);
  1954. }
  1955. ZSTD_CDict* ZSTD_createCDict_byReference(const void* dict, size_t dictSize, int compressionLevel)
  1956. {
  1957. ZSTD_compressionParameters cParams = ZSTD_getCParams(compressionLevel, 0, dictSize);
  1958. return ZSTD_createCDict_advanced(dict, dictSize,
  1959. ZSTD_dlm_byRef, ZSTD_dm_auto,
  1960. cParams, ZSTD_defaultCMem);
  1961. }
  1962. size_t ZSTD_freeCDict(ZSTD_CDict* cdict)
  1963. {
  1964. if (cdict==NULL) return 0; /* support free on NULL */
  1965. { ZSTD_customMem const cMem = cdict->refContext->customMem;
  1966. ZSTD_freeCCtx(cdict->refContext);
  1967. ZSTD_free(cdict->dictBuffer, cMem);
  1968. ZSTD_free(cdict, cMem);
  1969. return 0;
  1970. }
  1971. }
  1972. /*! ZSTD_initStaticCDict_advanced() :
  1973. * Generate a digested dictionary in provided memory area.
  1974. * workspace: The memory area to emplace the dictionary into.
  1975. * Provided pointer must 8-bytes aligned.
  1976. * It must outlive dictionary usage.
  1977. * workspaceSize: Use ZSTD_estimateCDictSize()
  1978. * to determine how large workspace must be.
  1979. * cParams : use ZSTD_getCParams() to transform a compression level
  1980. * into its relevants cParams.
  1981. * @return : pointer to ZSTD_CDict*, or NULL if error (size too small)
  1982. * Note : there is no corresponding "free" function.
  1983. * Since workspace was allocated externally, it must be freed externally.
  1984. */
  1985. ZSTD_CDict* ZSTD_initStaticCDict(void* workspace, size_t workspaceSize,
  1986. const void* dict, size_t dictSize,
  1987. ZSTD_dictLoadMethod_e dictLoadMethod,
  1988. ZSTD_dictMode_e dictMode,
  1989. ZSTD_compressionParameters cParams)
  1990. {
  1991. size_t const cctxSize = ZSTD_estimateCCtxSize_advanced_usingCParams(cParams);
  1992. size_t const neededSize = sizeof(ZSTD_CDict) + (dictLoadMethod == ZSTD_dlm_byRef ? 0 : dictSize)
  1993. + cctxSize;
  1994. ZSTD_CDict* const cdict = (ZSTD_CDict*) workspace;
  1995. void* ptr;
  1996. DEBUGLOG(5, "(size_t)workspace & 7 : %u", (U32)(size_t)workspace & 7);
  1997. if ((size_t)workspace & 7) return NULL; /* 8-aligned */
  1998. DEBUGLOG(5, "(workspaceSize < neededSize) : (%u < %u) => %u",
  1999. (U32)workspaceSize, (U32)neededSize, (U32)(workspaceSize < neededSize));
  2000. if (workspaceSize < neededSize) return NULL;
  2001. if (dictLoadMethod == ZSTD_dlm_byCopy) {
  2002. memcpy(cdict+1, dict, dictSize);
  2003. dict = cdict+1;
  2004. ptr = (char*)workspace + sizeof(ZSTD_CDict) + dictSize;
  2005. } else {
  2006. ptr = cdict+1;
  2007. }
  2008. cdict->refContext = ZSTD_initStaticCCtx(ptr, cctxSize);
  2009. if (ZSTD_isError( ZSTD_initCDict_internal(cdict,
  2010. dict, dictSize,
  2011. ZSTD_dlm_byRef, dictMode,
  2012. cParams) ))
  2013. return NULL;
  2014. return cdict;
  2015. }
  2016. ZSTD_compressionParameters ZSTD_getCParamsFromCDict(const ZSTD_CDict* cdict) {
  2017. return cdict->refContext->appliedParams.cParams;
  2018. }
  2019. /* ZSTD_compressBegin_usingCDict_advanced() :
  2020. * cdict must be != NULL */
  2021. size_t ZSTD_compressBegin_usingCDict_advanced(
  2022. ZSTD_CCtx* const cctx, const ZSTD_CDict* const cdict,
  2023. ZSTD_frameParameters const fParams, unsigned long long const pledgedSrcSize)
  2024. {
  2025. if (cdict==NULL) return ERROR(dictionary_wrong);
  2026. { ZSTD_CCtx_params params = cctx->requestedParams;
  2027. params.cParams = ZSTD_getCParamsFromCDict(cdict);
  2028. params.fParams = fParams;
  2029. DEBUGLOG(5, "ZSTD_compressBegin_usingCDict_advanced");
  2030. return ZSTD_compressBegin_internal(cctx,
  2031. NULL, 0, ZSTD_dm_auto,
  2032. cdict,
  2033. params, pledgedSrcSize,
  2034. ZSTDb_not_buffered);
  2035. }
  2036. }
  2037. /* ZSTD_compressBegin_usingCDict() :
  2038. * pledgedSrcSize=0 means "unknown"
  2039. * if pledgedSrcSize>0, it will enable contentSizeFlag */
  2040. size_t ZSTD_compressBegin_usingCDict(ZSTD_CCtx* cctx, const ZSTD_CDict* cdict)
  2041. {
  2042. ZSTD_frameParameters const fParams = { 0 /*content*/, 0 /*checksum*/, 0 /*noDictID*/ };
  2043. DEBUGLOG(5, "ZSTD_compressBegin_usingCDict : dictIDFlag == %u", !fParams.noDictIDFlag);
  2044. return ZSTD_compressBegin_usingCDict_advanced(cctx, cdict, fParams, 0);
  2045. }
  2046. size_t ZSTD_compress_usingCDict_advanced(ZSTD_CCtx* cctx,
  2047. void* dst, size_t dstCapacity,
  2048. const void* src, size_t srcSize,
  2049. const ZSTD_CDict* cdict, ZSTD_frameParameters fParams)
  2050. {
  2051. CHECK_F (ZSTD_compressBegin_usingCDict_advanced(cctx, cdict, fParams, srcSize)); /* will check if cdict != NULL */
  2052. return ZSTD_compressEnd(cctx, dst, dstCapacity, src, srcSize);
  2053. }
  2054. /*! ZSTD_compress_usingCDict() :
  2055. * Compression using a digested Dictionary.
  2056. * Faster startup than ZSTD_compress_usingDict(), recommended when same dictionary is used multiple times.
  2057. * Note that compression parameters are decided at CDict creation time
  2058. * while frame parameters are hardcoded */
  2059. size_t ZSTD_compress_usingCDict(ZSTD_CCtx* cctx,
  2060. void* dst, size_t dstCapacity,
  2061. const void* src, size_t srcSize,
  2062. const ZSTD_CDict* cdict)
  2063. {
  2064. ZSTD_frameParameters const fParams = { 1 /*content*/, 0 /*checksum*/, 0 /*noDictID*/ };
  2065. return ZSTD_compress_usingCDict_advanced(cctx, dst, dstCapacity, src, srcSize, cdict, fParams);
  2066. }
  2067. /* ******************************************************************
  2068. * Streaming
  2069. ********************************************************************/
  2070. ZSTD_CStream* ZSTD_createCStream(void)
  2071. {
  2072. return ZSTD_createCStream_advanced(ZSTD_defaultCMem);
  2073. }
  2074. ZSTD_CStream* ZSTD_initStaticCStream(void *workspace, size_t workspaceSize)
  2075. {
  2076. return ZSTD_initStaticCCtx(workspace, workspaceSize);
  2077. }
  2078. ZSTD_CStream* ZSTD_createCStream_advanced(ZSTD_customMem customMem)
  2079. { /* CStream and CCtx are now same object */
  2080. return ZSTD_createCCtx_advanced(customMem);
  2081. }
  2082. size_t ZSTD_freeCStream(ZSTD_CStream* zcs)
  2083. {
  2084. return ZSTD_freeCCtx(zcs); /* same object */
  2085. }
  2086. /*====== Initialization ======*/
  2087. size_t ZSTD_CStreamInSize(void) { return ZSTD_BLOCKSIZE_MAX; }
  2088. size_t ZSTD_CStreamOutSize(void)
  2089. {
  2090. return ZSTD_compressBound(ZSTD_BLOCKSIZE_MAX) + ZSTD_blockHeaderSize + 4 /* 32-bits hash */ ;
  2091. }
  2092. static size_t ZSTD_resetCStream_internal(ZSTD_CStream* zcs,
  2093. const void* dict, size_t dictSize, ZSTD_dictMode_e dictMode,
  2094. const ZSTD_CDict* cdict,
  2095. const ZSTD_CCtx_params params, unsigned long long pledgedSrcSize)
  2096. {
  2097. DEBUGLOG(4, "ZSTD_resetCStream_internal");
  2098. /* params are supposed to be fully validated at this point */
  2099. assert(!ZSTD_isError(ZSTD_checkCParams(params.cParams)));
  2100. assert(!((dict) && (cdict))); /* either dict or cdict, not both */
  2101. CHECK_F( ZSTD_compressBegin_internal(zcs,
  2102. dict, dictSize, dictMode,
  2103. cdict,
  2104. params, pledgedSrcSize,
  2105. ZSTDb_buffered) );
  2106. zcs->inToCompress = 0;
  2107. zcs->inBuffPos = 0;
  2108. zcs->inBuffTarget = zcs->blockSize;
  2109. zcs->outBuffContentSize = zcs->outBuffFlushedSize = 0;
  2110. zcs->streamStage = zcss_load;
  2111. zcs->frameEnded = 0;
  2112. return 0; /* ready to go */
  2113. }
  2114. size_t ZSTD_resetCStream(ZSTD_CStream* zcs, unsigned long long pledgedSrcSize)
  2115. {
  2116. ZSTD_CCtx_params params = zcs->requestedParams;
  2117. params.fParams.contentSizeFlag = (pledgedSrcSize > 0);
  2118. params.cParams = ZSTD_getCParamsFromCCtxParams(params, pledgedSrcSize, 0);
  2119. DEBUGLOG(5, "ZSTD_resetCStream");
  2120. return ZSTD_resetCStream_internal(zcs, NULL, 0, ZSTD_dm_auto, zcs->cdict, params, pledgedSrcSize);
  2121. }
  2122. /*! ZSTD_initCStream_internal() :
  2123. * Note : not static, but hidden (not exposed). Used by zstdmt_compress.c
  2124. * Assumption 1 : params are valid
  2125. * Assumption 2 : either dict, or cdict, is defined, not both */
  2126. size_t ZSTD_initCStream_internal(ZSTD_CStream* zcs,
  2127. const void* dict, size_t dictSize, const ZSTD_CDict* cdict,
  2128. ZSTD_CCtx_params params, unsigned long long pledgedSrcSize)
  2129. {
  2130. assert(!ZSTD_isError(ZSTD_checkCParams(params.cParams)));
  2131. assert(!((dict) && (cdict))); /* either dict or cdict, not both */
  2132. if (dict && dictSize >= 8) {
  2133. DEBUGLOG(5, "loading dictionary of size %u", (U32)dictSize);
  2134. if (zcs->staticSize) { /* static CCtx : never uses malloc */
  2135. /* incompatible with internal cdict creation */
  2136. return ERROR(memory_allocation);
  2137. }
  2138. ZSTD_freeCDict(zcs->cdictLocal);
  2139. zcs->cdictLocal = ZSTD_createCDict_advanced(dict, dictSize,
  2140. ZSTD_dlm_byCopy, ZSTD_dm_auto,
  2141. params.cParams, zcs->customMem);
  2142. zcs->cdict = zcs->cdictLocal;
  2143. if (zcs->cdictLocal == NULL) return ERROR(memory_allocation);
  2144. } else {
  2145. if (cdict) {
  2146. params.cParams = ZSTD_getCParamsFromCDict(cdict); /* cParams are enforced from cdict */
  2147. }
  2148. ZSTD_freeCDict(zcs->cdictLocal);
  2149. zcs->cdictLocal = NULL;
  2150. zcs->cdict = cdict;
  2151. }
  2152. params.compressionLevel = ZSTD_CLEVEL_CUSTOM;
  2153. zcs->requestedParams = params;
  2154. return ZSTD_resetCStream_internal(zcs, NULL, 0, ZSTD_dm_auto, zcs->cdict, params, pledgedSrcSize);
  2155. }
  2156. /* ZSTD_initCStream_usingCDict_advanced() :
  2157. * same as ZSTD_initCStream_usingCDict(), with control over frame parameters */
  2158. size_t ZSTD_initCStream_usingCDict_advanced(ZSTD_CStream* zcs,
  2159. const ZSTD_CDict* cdict,
  2160. ZSTD_frameParameters fParams,
  2161. unsigned long long pledgedSrcSize)
  2162. { /* cannot handle NULL cdict (does not know what to do) */
  2163. if (!cdict) return ERROR(dictionary_wrong);
  2164. { ZSTD_CCtx_params params = zcs->requestedParams;
  2165. params.cParams = ZSTD_getCParamsFromCDict(cdict);
  2166. params.fParams = fParams;
  2167. return ZSTD_initCStream_internal(zcs,
  2168. NULL, 0, cdict,
  2169. params, pledgedSrcSize);
  2170. }
  2171. }
  2172. /* note : cdict must outlive compression session */
  2173. size_t ZSTD_initCStream_usingCDict(ZSTD_CStream* zcs, const ZSTD_CDict* cdict)
  2174. {
  2175. ZSTD_frameParameters const fParams = { 0 /* contentSize */, 0 /* checksum */, 0 /* hideDictID */ };
  2176. return ZSTD_initCStream_usingCDict_advanced(zcs, cdict, fParams, 0); /* note : will check that cdict != NULL */
  2177. }
  2178. size_t ZSTD_initCStream_advanced(ZSTD_CStream* zcs,
  2179. const void* dict, size_t dictSize,
  2180. ZSTD_parameters params, unsigned long long pledgedSrcSize)
  2181. {
  2182. ZSTD_CCtx_params const cctxParams =
  2183. ZSTD_assignParamsToCCtxParams(zcs->requestedParams, params);
  2184. CHECK_F( ZSTD_checkCParams(params.cParams) );
  2185. return ZSTD_initCStream_internal(zcs, dict, dictSize, NULL, cctxParams, pledgedSrcSize);
  2186. }
  2187. size_t ZSTD_initCStream_usingDict(ZSTD_CStream* zcs, const void* dict, size_t dictSize, int compressionLevel)
  2188. {
  2189. ZSTD_parameters const params = ZSTD_getParams(compressionLevel, 0, dictSize);
  2190. ZSTD_CCtx_params const cctxParams =
  2191. ZSTD_assignParamsToCCtxParams(zcs->requestedParams, params);
  2192. return ZSTD_initCStream_internal(zcs, dict, dictSize, NULL, cctxParams, 0);
  2193. }
  2194. size_t ZSTD_initCStream_srcSize(ZSTD_CStream* zcs, int compressionLevel, unsigned long long pledgedSrcSize)
  2195. {
  2196. ZSTD_CCtx_params cctxParams;
  2197. ZSTD_parameters const params = ZSTD_getParams(compressionLevel, pledgedSrcSize, 0);
  2198. cctxParams = ZSTD_assignParamsToCCtxParams(zcs->requestedParams, params);
  2199. cctxParams.fParams.contentSizeFlag = (pledgedSrcSize>0);
  2200. return ZSTD_initCStream_internal(zcs, NULL, 0, NULL, cctxParams, pledgedSrcSize);
  2201. }
  2202. size_t ZSTD_initCStream(ZSTD_CStream* zcs, int compressionLevel)
  2203. {
  2204. return ZSTD_initCStream_srcSize(zcs, compressionLevel, 0);
  2205. }
  2206. /*====== Compression ======*/
  2207. MEM_STATIC size_t ZSTD_limitCopy(void* dst, size_t dstCapacity,
  2208. const void* src, size_t srcSize)
  2209. {
  2210. size_t const length = MIN(dstCapacity, srcSize);
  2211. if (length) memcpy(dst, src, length);
  2212. return length;
  2213. }
  2214. /** ZSTD_compressStream_generic():
  2215. * internal function for all *compressStream*() variants and *compress_generic()
  2216. * @return : hint size for next input */
  2217. size_t ZSTD_compressStream_generic(ZSTD_CStream* zcs,
  2218. ZSTD_outBuffer* output,
  2219. ZSTD_inBuffer* input,
  2220. ZSTD_EndDirective const flushMode)
  2221. {
  2222. const char* const istart = (const char*)input->src;
  2223. const char* const iend = istart + input->size;
  2224. const char* ip = istart + input->pos;
  2225. char* const ostart = (char*)output->dst;
  2226. char* const oend = ostart + output->size;
  2227. char* op = ostart + output->pos;
  2228. U32 someMoreWork = 1;
  2229. /* check expectations */
  2230. DEBUGLOG(5, "ZSTD_compressStream_generic, flush=%u", (U32)flushMode);
  2231. assert(zcs->inBuff != NULL);
  2232. assert(zcs->inBuffSize>0);
  2233. assert(zcs->outBuff!= NULL);
  2234. assert(zcs->outBuffSize>0);
  2235. assert(output->pos <= output->size);
  2236. assert(input->pos <= input->size);
  2237. while (someMoreWork) {
  2238. switch(zcs->streamStage)
  2239. {
  2240. case zcss_init:
  2241. /* call ZSTD_initCStream() first ! */
  2242. return ERROR(init_missing);
  2243. case zcss_load:
  2244. if ( (flushMode == ZSTD_e_end)
  2245. && ((size_t)(oend-op) >= ZSTD_compressBound(iend-ip)) /* enough dstCapacity */
  2246. && (zcs->inBuffPos == 0) ) {
  2247. /* shortcut to compression pass directly into output buffer */
  2248. size_t const cSize = ZSTD_compressEnd(zcs,
  2249. op, oend-op, ip, iend-ip);
  2250. DEBUGLOG(4, "ZSTD_compressEnd : %u", (U32)cSize);
  2251. if (ZSTD_isError(cSize)) return cSize;
  2252. ip = iend;
  2253. op += cSize;
  2254. zcs->frameEnded = 1;
  2255. ZSTD_startNewCompression(zcs);
  2256. someMoreWork = 0; break;
  2257. }
  2258. /* complete loading into inBuffer */
  2259. { size_t const toLoad = zcs->inBuffTarget - zcs->inBuffPos;
  2260. size_t const loaded = ZSTD_limitCopy(
  2261. zcs->inBuff + zcs->inBuffPos, toLoad,
  2262. ip, iend-ip);
  2263. zcs->inBuffPos += loaded;
  2264. ip += loaded;
  2265. if ( (flushMode == ZSTD_e_continue)
  2266. && (zcs->inBuffPos < zcs->inBuffTarget) ) {
  2267. /* not enough input to fill full block : stop here */
  2268. someMoreWork = 0; break;
  2269. }
  2270. if ( (flushMode == ZSTD_e_flush)
  2271. && (zcs->inBuffPos == zcs->inToCompress) ) {
  2272. /* empty */
  2273. someMoreWork = 0; break;
  2274. }
  2275. }
  2276. /* compress current block (note : this stage cannot be stopped in the middle) */
  2277. DEBUGLOG(5, "stream compression stage (flushMode==%u)", flushMode);
  2278. { void* cDst;
  2279. size_t cSize;
  2280. size_t const iSize = zcs->inBuffPos - zcs->inToCompress;
  2281. size_t oSize = oend-op;
  2282. unsigned const lastBlock = (flushMode == ZSTD_e_end) && (ip==iend);
  2283. if (oSize >= ZSTD_compressBound(iSize))
  2284. cDst = op; /* compress into output buffer, to skip flush stage */
  2285. else
  2286. cDst = zcs->outBuff, oSize = zcs->outBuffSize;
  2287. cSize = lastBlock ?
  2288. ZSTD_compressEnd(zcs, cDst, oSize,
  2289. zcs->inBuff + zcs->inToCompress, iSize) :
  2290. ZSTD_compressContinue(zcs, cDst, oSize,
  2291. zcs->inBuff + zcs->inToCompress, iSize);
  2292. if (ZSTD_isError(cSize)) return cSize;
  2293. zcs->frameEnded = lastBlock;
  2294. /* prepare next block */
  2295. zcs->inBuffTarget = zcs->inBuffPos + zcs->blockSize;
  2296. if (zcs->inBuffTarget > zcs->inBuffSize)
  2297. zcs->inBuffPos = 0, zcs->inBuffTarget = zcs->blockSize;
  2298. DEBUGLOG(5, "inBuffTarget:%u / inBuffSize:%u",
  2299. (U32)zcs->inBuffTarget, (U32)zcs->inBuffSize);
  2300. if (!lastBlock)
  2301. assert(zcs->inBuffTarget <= zcs->inBuffSize);
  2302. zcs->inToCompress = zcs->inBuffPos;
  2303. if (cDst == op) { /* no need to flush */
  2304. op += cSize;
  2305. if (zcs->frameEnded) {
  2306. DEBUGLOG(5, "Frame completed directly in outBuffer");
  2307. someMoreWork = 0;
  2308. ZSTD_startNewCompression(zcs);
  2309. }
  2310. break;
  2311. }
  2312. zcs->outBuffContentSize = cSize;
  2313. zcs->outBuffFlushedSize = 0;
  2314. zcs->streamStage = zcss_flush; /* pass-through to flush stage */
  2315. }
  2316. /* fall-through */
  2317. case zcss_flush:
  2318. DEBUGLOG(5, "flush stage");
  2319. { size_t const toFlush = zcs->outBuffContentSize - zcs->outBuffFlushedSize;
  2320. size_t const flushed = ZSTD_limitCopy(op, oend-op,
  2321. zcs->outBuff + zcs->outBuffFlushedSize, toFlush);
  2322. DEBUGLOG(5, "toFlush: %u into %u ==> flushed: %u",
  2323. (U32)toFlush, (U32)(oend-op), (U32)flushed);
  2324. op += flushed;
  2325. zcs->outBuffFlushedSize += flushed;
  2326. if (toFlush!=flushed) {
  2327. /* flush not fully completed, presumably because dst is too small */
  2328. assert(op==oend);
  2329. someMoreWork = 0;
  2330. break;
  2331. }
  2332. zcs->outBuffContentSize = zcs->outBuffFlushedSize = 0;
  2333. if (zcs->frameEnded) {
  2334. DEBUGLOG(5, "Frame completed on flush");
  2335. someMoreWork = 0;
  2336. ZSTD_startNewCompression(zcs);
  2337. break;
  2338. }
  2339. zcs->streamStage = zcss_load;
  2340. break;
  2341. }
  2342. default: /* impossible */
  2343. assert(0);
  2344. }
  2345. }
  2346. input->pos = ip - istart;
  2347. output->pos = op - ostart;
  2348. if (zcs->frameEnded) return 0;
  2349. { size_t hintInSize = zcs->inBuffTarget - zcs->inBuffPos;
  2350. if (hintInSize==0) hintInSize = zcs->blockSize;
  2351. return hintInSize;
  2352. }
  2353. }
  2354. size_t ZSTD_compressStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output, ZSTD_inBuffer* input)
  2355. {
  2356. /* check conditions */
  2357. if (output->pos > output->size) return ERROR(GENERIC);
  2358. if (input->pos > input->size) return ERROR(GENERIC);
  2359. return ZSTD_compressStream_generic(zcs, output, input, ZSTD_e_continue);
  2360. }
  2361. size_t ZSTD_compress_generic (ZSTD_CCtx* cctx,
  2362. ZSTD_outBuffer* output,
  2363. ZSTD_inBuffer* input,
  2364. ZSTD_EndDirective endOp)
  2365. {
  2366. /* check conditions */
  2367. if (output->pos > output->size) return ERROR(GENERIC);
  2368. if (input->pos > input->size) return ERROR(GENERIC);
  2369. assert(cctx!=NULL);
  2370. /* transparent initialization stage */
  2371. if (cctx->streamStage == zcss_init) {
  2372. ZSTD_prefixDict const prefixDict = cctx->prefixDict;
  2373. ZSTD_CCtx_params params = cctx->requestedParams;
  2374. params.cParams = ZSTD_getCParamsFromCCtxParams(
  2375. cctx->requestedParams, cctx->pledgedSrcSizePlusOne-1, 0 /*dictSize*/);
  2376. memset(&cctx->prefixDict, 0, sizeof(cctx->prefixDict)); /* single usage */
  2377. assert(prefixDict.dict==NULL || cctx->cdict==NULL); /* only one can be set */
  2378. #ifdef ZSTD_MULTITHREAD
  2379. if (params.nbThreads > 1) {
  2380. if (cctx->mtctx == NULL || cctx->appliedParams.nbThreads != params.nbThreads) {
  2381. ZSTDMT_freeCCtx(cctx->mtctx);
  2382. cctx->mtctx = ZSTDMT_createCCtx_advanced(params.nbThreads, cctx->customMem);
  2383. if (cctx->mtctx == NULL) return ERROR(memory_allocation);
  2384. }
  2385. DEBUGLOG(4, "call ZSTDMT_initCStream_internal as nbThreads=%u", params.nbThreads);
  2386. CHECK_F( ZSTDMT_initCStream_internal(
  2387. cctx->mtctx,
  2388. prefixDict.dict, prefixDict.dictSize, ZSTD_dm_rawContent,
  2389. cctx->cdict, params, cctx->pledgedSrcSizePlusOne-1) );
  2390. cctx->streamStage = zcss_load;
  2391. cctx->appliedParams.nbThreads = params.nbThreads;
  2392. } else
  2393. #endif
  2394. {
  2395. CHECK_F( ZSTD_resetCStream_internal(
  2396. cctx, prefixDict.dict, prefixDict.dictSize,
  2397. prefixDict.dictMode, cctx->cdict, params,
  2398. cctx->pledgedSrcSizePlusOne-1) );
  2399. } }
  2400. /* compression stage */
  2401. #ifdef ZSTD_MULTITHREAD
  2402. if (cctx->appliedParams.nbThreads > 1) {
  2403. size_t const flushMin = ZSTDMT_compressStream_generic(cctx->mtctx, output, input, endOp);
  2404. DEBUGLOG(5, "ZSTDMT_compressStream_generic : %u", (U32)flushMin);
  2405. if ( ZSTD_isError(flushMin)
  2406. || (endOp == ZSTD_e_end && flushMin == 0) ) { /* compression completed */
  2407. ZSTD_startNewCompression(cctx);
  2408. }
  2409. return flushMin;
  2410. }
  2411. #endif
  2412. CHECK_F( ZSTD_compressStream_generic(cctx, output, input, endOp) );
  2413. DEBUGLOG(5, "completed ZSTD_compress_generic");
  2414. return cctx->outBuffContentSize - cctx->outBuffFlushedSize; /* remaining to flush */
  2415. }
  2416. size_t ZSTD_compress_generic_simpleArgs (
  2417. ZSTD_CCtx* cctx,
  2418. void* dst, size_t dstCapacity, size_t* dstPos,
  2419. const void* src, size_t srcSize, size_t* srcPos,
  2420. ZSTD_EndDirective endOp)
  2421. {
  2422. ZSTD_outBuffer output = { dst, dstCapacity, *dstPos };
  2423. ZSTD_inBuffer input = { src, srcSize, *srcPos };
  2424. /* ZSTD_compress_generic() will check validity of dstPos and srcPos */
  2425. size_t const cErr = ZSTD_compress_generic(cctx, &output, &input, endOp);
  2426. *dstPos = output.pos;
  2427. *srcPos = input.pos;
  2428. return cErr;
  2429. }
  2430. /*====== Finalize ======*/
  2431. /*! ZSTD_flushStream() :
  2432. * @return : amount of data remaining to flush */
  2433. size_t ZSTD_flushStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output)
  2434. {
  2435. ZSTD_inBuffer input = { NULL, 0, 0 };
  2436. if (output->pos > output->size) return ERROR(GENERIC);
  2437. CHECK_F( ZSTD_compressStream_generic(zcs, output, &input, ZSTD_e_flush) );
  2438. return zcs->outBuffContentSize - zcs->outBuffFlushedSize; /* remaining to flush */
  2439. }
  2440. size_t ZSTD_endStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output)
  2441. {
  2442. ZSTD_inBuffer input = { NULL, 0, 0 };
  2443. if (output->pos > output->size) return ERROR(GENERIC);
  2444. CHECK_F( ZSTD_compressStream_generic(zcs, output, &input, ZSTD_e_end) );
  2445. { size_t const lastBlockSize = zcs->frameEnded ? 0 : ZSTD_BLOCKHEADERSIZE;
  2446. size_t const checksumSize = zcs->frameEnded ? 0 : zcs->appliedParams.fParams.checksumFlag * 4;
  2447. size_t const toFlush = zcs->outBuffContentSize - zcs->outBuffFlushedSize + lastBlockSize + checksumSize;
  2448. DEBUGLOG(5, "ZSTD_endStream : remaining to flush : %u",
  2449. (unsigned)toFlush);
  2450. return toFlush;
  2451. }
  2452. }
  2453. /*-===== Pre-defined compression levels =====-*/
  2454. #define ZSTD_MAX_CLEVEL 22
  2455. int ZSTD_maxCLevel(void) { return ZSTD_MAX_CLEVEL; }
  2456. static const ZSTD_compressionParameters ZSTD_defaultCParameters[4][ZSTD_MAX_CLEVEL+1] = {
  2457. { /* "default" - guarantees a monotonically increasing memory budget */
  2458. /* W, C, H, S, L, TL, strat */
  2459. { 18, 12, 12, 1, 7, 16, ZSTD_fast }, /* level 0 - never used */
  2460. { 19, 13, 14, 1, 7, 16, ZSTD_fast }, /* level 1 */
  2461. { 19, 15, 16, 1, 6, 16, ZSTD_fast }, /* level 2 */
  2462. { 20, 16, 17, 1, 5, 16, ZSTD_dfast }, /* level 3 */
  2463. { 20, 17, 18, 1, 5, 16, ZSTD_dfast }, /* level 4 */
  2464. { 20, 17, 18, 2, 5, 16, ZSTD_greedy }, /* level 5 */
  2465. { 21, 17, 19, 2, 5, 16, ZSTD_lazy }, /* level 6 */
  2466. { 21, 18, 19, 3, 5, 16, ZSTD_lazy }, /* level 7 */
  2467. { 21, 18, 20, 3, 5, 16, ZSTD_lazy2 }, /* level 8 */
  2468. { 21, 19, 20, 3, 5, 16, ZSTD_lazy2 }, /* level 9 */
  2469. { 21, 19, 21, 4, 5, 16, ZSTD_lazy2 }, /* level 10 */
  2470. { 22, 20, 22, 4, 5, 16, ZSTD_lazy2 }, /* level 11 */
  2471. { 22, 20, 22, 5, 5, 16, ZSTD_lazy2 }, /* level 12 */
  2472. { 22, 21, 22, 5, 5, 16, ZSTD_lazy2 }, /* level 13 */
  2473. { 22, 21, 22, 6, 5, 16, ZSTD_lazy2 }, /* level 14 */
  2474. { 22, 21, 22, 5, 5, 16, ZSTD_btlazy2 }, /* level 15 */
  2475. { 23, 22, 22, 5, 5, 16, ZSTD_btlazy2 }, /* level 16 */
  2476. { 23, 22, 22, 4, 5, 24, ZSTD_btopt }, /* level 17 */
  2477. { 23, 22, 22, 5, 4, 32, ZSTD_btopt }, /* level 18 */
  2478. { 23, 23, 22, 6, 3, 48, ZSTD_btopt }, /* level 19 */
  2479. { 25, 25, 23, 7, 3, 64, ZSTD_btultra }, /* level 20 */
  2480. { 26, 26, 24, 7, 3,256, ZSTD_btultra }, /* level 21 */
  2481. { 27, 27, 25, 9, 3,512, ZSTD_btultra }, /* level 22 */
  2482. },
  2483. { /* for srcSize <= 256 KB */
  2484. /* W, C, H, S, L, T, strat */
  2485. { 0, 0, 0, 0, 0, 0, ZSTD_fast }, /* level 0 - not used */
  2486. { 18, 13, 14, 1, 6, 8, ZSTD_fast }, /* level 1 */
  2487. { 18, 14, 13, 1, 5, 8, ZSTD_dfast }, /* level 2 */
  2488. { 18, 16, 15, 1, 5, 8, ZSTD_dfast }, /* level 3 */
  2489. { 18, 15, 17, 1, 5, 8, ZSTD_greedy }, /* level 4.*/
  2490. { 18, 16, 17, 4, 5, 8, ZSTD_greedy }, /* level 5.*/
  2491. { 18, 16, 17, 3, 5, 8, ZSTD_lazy }, /* level 6.*/
  2492. { 18, 17, 17, 4, 4, 8, ZSTD_lazy }, /* level 7 */
  2493. { 18, 17, 17, 4, 4, 8, ZSTD_lazy2 }, /* level 8 */
  2494. { 18, 17, 17, 5, 4, 8, ZSTD_lazy2 }, /* level 9 */
  2495. { 18, 17, 17, 6, 4, 8, ZSTD_lazy2 }, /* level 10 */
  2496. { 18, 18, 17, 6, 4, 8, ZSTD_lazy2 }, /* level 11.*/
  2497. { 18, 18, 17, 7, 4, 8, ZSTD_lazy2 }, /* level 12.*/
  2498. { 18, 19, 17, 6, 4, 8, ZSTD_btlazy2 }, /* level 13 */
  2499. { 18, 18, 18, 4, 4, 16, ZSTD_btopt }, /* level 14.*/
  2500. { 18, 18, 18, 4, 3, 16, ZSTD_btopt }, /* level 15.*/
  2501. { 18, 19, 18, 6, 3, 32, ZSTD_btopt }, /* level 16.*/
  2502. { 18, 19, 18, 8, 3, 64, ZSTD_btopt }, /* level 17.*/
  2503. { 18, 19, 18, 9, 3,128, ZSTD_btopt }, /* level 18.*/
  2504. { 18, 19, 18, 10, 3,256, ZSTD_btopt }, /* level 19.*/
  2505. { 18, 19, 18, 11, 3,512, ZSTD_btultra }, /* level 20.*/
  2506. { 18, 19, 18, 12, 3,512, ZSTD_btultra }, /* level 21.*/
  2507. { 18, 19, 18, 13, 3,512, ZSTD_btultra }, /* level 22.*/
  2508. },
  2509. { /* for srcSize <= 128 KB */
  2510. /* W, C, H, S, L, T, strat */
  2511. { 17, 12, 12, 1, 7, 8, ZSTD_fast }, /* level 0 - not used */
  2512. { 17, 12, 13, 1, 6, 8, ZSTD_fast }, /* level 1 */
  2513. { 17, 13, 16, 1, 5, 8, ZSTD_fast }, /* level 2 */
  2514. { 17, 16, 16, 2, 5, 8, ZSTD_dfast }, /* level 3 */
  2515. { 17, 13, 15, 3, 4, 8, ZSTD_greedy }, /* level 4 */
  2516. { 17, 15, 17, 4, 4, 8, ZSTD_greedy }, /* level 5 */
  2517. { 17, 16, 17, 3, 4, 8, ZSTD_lazy }, /* level 6 */
  2518. { 17, 15, 17, 4, 4, 8, ZSTD_lazy2 }, /* level 7 */
  2519. { 17, 17, 17, 4, 4, 8, ZSTD_lazy2 }, /* level 8 */
  2520. { 17, 17, 17, 5, 4, 8, ZSTD_lazy2 }, /* level 9 */
  2521. { 17, 17, 17, 6, 4, 8, ZSTD_lazy2 }, /* level 10 */
  2522. { 17, 17, 17, 7, 4, 8, ZSTD_lazy2 }, /* level 11 */
  2523. { 17, 17, 17, 8, 4, 8, ZSTD_lazy2 }, /* level 12 */
  2524. { 17, 18, 17, 6, 4, 8, ZSTD_btlazy2 }, /* level 13.*/
  2525. { 17, 17, 17, 7, 3, 8, ZSTD_btopt }, /* level 14.*/
  2526. { 17, 17, 17, 7, 3, 16, ZSTD_btopt }, /* level 15.*/
  2527. { 17, 18, 17, 7, 3, 32, ZSTD_btopt }, /* level 16.*/
  2528. { 17, 18, 17, 7, 3, 64, ZSTD_btopt }, /* level 17.*/
  2529. { 17, 18, 17, 7, 3,256, ZSTD_btopt }, /* level 18.*/
  2530. { 17, 18, 17, 8, 3,256, ZSTD_btopt }, /* level 19.*/
  2531. { 17, 18, 17, 9, 3,256, ZSTD_btultra }, /* level 20.*/
  2532. { 17, 18, 17, 10, 3,256, ZSTD_btultra }, /* level 21.*/
  2533. { 17, 18, 17, 11, 3,512, ZSTD_btultra }, /* level 22.*/
  2534. },
  2535. { /* for srcSize <= 16 KB */
  2536. /* W, C, H, S, L, T, strat */
  2537. { 14, 12, 12, 1, 7, 6, ZSTD_fast }, /* level 0 - not used */
  2538. { 14, 14, 14, 1, 6, 6, ZSTD_fast }, /* level 1 */
  2539. { 14, 14, 14, 1, 4, 6, ZSTD_fast }, /* level 2 */
  2540. { 14, 14, 14, 1, 4, 6, ZSTD_dfast }, /* level 3.*/
  2541. { 14, 14, 14, 4, 4, 6, ZSTD_greedy }, /* level 4.*/
  2542. { 14, 14, 14, 3, 4, 6, ZSTD_lazy }, /* level 5.*/
  2543. { 14, 14, 14, 4, 4, 6, ZSTD_lazy2 }, /* level 6 */
  2544. { 14, 14, 14, 5, 4, 6, ZSTD_lazy2 }, /* level 7 */
  2545. { 14, 14, 14, 6, 4, 6, ZSTD_lazy2 }, /* level 8.*/
  2546. { 14, 15, 14, 6, 4, 6, ZSTD_btlazy2 }, /* level 9.*/
  2547. { 14, 15, 14, 3, 3, 6, ZSTD_btopt }, /* level 10.*/
  2548. { 14, 15, 14, 6, 3, 8, ZSTD_btopt }, /* level 11.*/
  2549. { 14, 15, 14, 6, 3, 16, ZSTD_btopt }, /* level 12.*/
  2550. { 14, 15, 14, 6, 3, 24, ZSTD_btopt }, /* level 13.*/
  2551. { 14, 15, 15, 6, 3, 48, ZSTD_btopt }, /* level 14.*/
  2552. { 14, 15, 15, 6, 3, 64, ZSTD_btopt }, /* level 15.*/
  2553. { 14, 15, 15, 6, 3, 96, ZSTD_btopt }, /* level 16.*/
  2554. { 14, 15, 15, 6, 3,128, ZSTD_btopt }, /* level 17.*/
  2555. { 14, 15, 15, 6, 3,256, ZSTD_btopt }, /* level 18.*/
  2556. { 14, 15, 15, 7, 3,256, ZSTD_btopt }, /* level 19.*/
  2557. { 14, 15, 15, 8, 3,256, ZSTD_btultra }, /* level 20.*/
  2558. { 14, 15, 15, 9, 3,256, ZSTD_btultra }, /* level 21.*/
  2559. { 14, 15, 15, 10, 3,256, ZSTD_btultra }, /* level 22.*/
  2560. },
  2561. };
  2562. #if defined(ZSTD_DEBUG) && (ZSTD_DEBUG>=1)
  2563. /* This function just controls
  2564. * the monotonic memory budget increase of ZSTD_defaultCParameters[0].
  2565. * Run once, on first ZSTD_getCParams() usage, if ZSTD_DEBUG is enabled
  2566. */
  2567. MEM_STATIC void ZSTD_check_compressionLevel_monotonicIncrease_memoryBudget(void)
  2568. {
  2569. int level;
  2570. for (level=1; level<ZSTD_maxCLevel(); level++) {
  2571. ZSTD_compressionParameters const c1 = ZSTD_defaultCParameters[0][level];
  2572. ZSTD_compressionParameters const c2 = ZSTD_defaultCParameters[0][level+1];
  2573. assert(c1.windowLog <= c2.windowLog);
  2574. # define ZSTD_TABLECOST(h,c) ((1<<(h)) + (1<<(c)))
  2575. assert(ZSTD_TABLECOST(c1.hashLog, c1.chainLog) <= ZSTD_TABLECOST(c2.hashLog, c2.chainLog));
  2576. }
  2577. }
  2578. #endif
  2579. /*! ZSTD_getCParams() :
  2580. * @return ZSTD_compressionParameters structure for a selected compression level, `srcSize` and `dictSize`.
  2581. * Size values are optional, provide 0 if not known or unused */
  2582. ZSTD_compressionParameters ZSTD_getCParams(int compressionLevel, unsigned long long srcSizeHint, size_t dictSize)
  2583. {
  2584. size_t const addedSize = srcSizeHint ? 0 : 500;
  2585. U64 const rSize = srcSizeHint+dictSize ? srcSizeHint+dictSize+addedSize : (U64)-1;
  2586. U32 const tableID = (rSize <= 256 KB) + (rSize <= 128 KB) + (rSize <= 16 KB); /* intentional underflow for srcSizeHint == 0 */
  2587. #if defined(ZSTD_DEBUG) && (ZSTD_DEBUG>=1)
  2588. static int g_monotonicTest = 1;
  2589. if (g_monotonicTest) {
  2590. ZSTD_check_compressionLevel_monotonicIncrease_memoryBudget();
  2591. g_monotonicTest=0;
  2592. }
  2593. #endif
  2594. if (compressionLevel <= 0) compressionLevel = ZSTD_CLEVEL_DEFAULT; /* 0 == default; no negative compressionLevel yet */
  2595. if (compressionLevel > ZSTD_MAX_CLEVEL) compressionLevel = ZSTD_MAX_CLEVEL;
  2596. { ZSTD_compressionParameters const cp = ZSTD_defaultCParameters[tableID][compressionLevel];
  2597. return ZSTD_adjustCParams_internal(cp, srcSizeHint, dictSize); }
  2598. }
  2599. /*! ZSTD_getParams() :
  2600. * same as ZSTD_getCParams(), but @return a `ZSTD_parameters` object (instead of `ZSTD_compressionParameters`).
  2601. * All fields of `ZSTD_frameParameters` are set to default (0) */
  2602. ZSTD_parameters ZSTD_getParams(int compressionLevel, unsigned long long srcSizeHint, size_t dictSize) {
  2603. ZSTD_parameters params;
  2604. ZSTD_compressionParameters const cParams = ZSTD_getCParams(compressionLevel, srcSizeHint, dictSize);
  2605. memset(&params, 0, sizeof(params));
  2606. params.cParams = cParams;
  2607. return params;
  2608. }