Path: blob/master/Utilities/cmzstd/lib/compress/zstd_compress.c
5033 views
/*1* Copyright (c) Meta Platforms, Inc. and affiliates.2* All rights reserved.3*4* This source code is licensed under both the BSD-style license (found in the5* LICENSE file in the root directory of this source tree) and the GPLv2 (found6* in the COPYING file in the root directory of this source tree).7* You may select, at your option, one of the above-listed licenses.8*/910/*-*************************************11* Dependencies12***************************************/13#include "../common/allocations.h" /* ZSTD_customMalloc, ZSTD_customCalloc, ZSTD_customFree */14#include "../common/zstd_deps.h" /* INT_MAX, ZSTD_memset, ZSTD_memcpy */15#include "../common/mem.h"16#include "../common/error_private.h"17#include "hist.h" /* HIST_countFast_wksp */18#define FSE_STATIC_LINKING_ONLY /* FSE_encodeSymbol */19#include "../common/fse.h"20#include "../common/huf.h"21#include "zstd_compress_internal.h"22#include "zstd_compress_sequences.h"23#include "zstd_compress_literals.h"24#include "zstd_fast.h"25#include "zstd_double_fast.h"26#include "zstd_lazy.h"27#include "zstd_opt.h"28#include "zstd_ldm.h"29#include "zstd_compress_superblock.h"30#include "../common/bits.h" /* ZSTD_highbit32, ZSTD_rotateRight_U64 */3132/* ***************************************************************33* Tuning parameters34*****************************************************************/35/*!36* COMPRESS_HEAPMODE :37* Select how default decompression function ZSTD_compress() allocates its context,38* on stack (0, default), or into heap (1).39* Note that functions with explicit context such as ZSTD_compressCCtx() are unaffected.40*/41#ifndef ZSTD_COMPRESS_HEAPMODE42# define ZSTD_COMPRESS_HEAPMODE 043#endif4445/*!46* ZSTD_HASHLOG3_MAX :47* Maximum size of the hash table dedicated to find 3-bytes matches,48* in log format, aka 17 => 1 << 17 == 128Ki positions.49* This structure is only used in zstd_opt.50* Since allocation is centralized for all strategies, it has to be known here.51* The actual (selected) size of the hash table is then stored in ZSTD_MatchState_t.hashLog3,52* so that zstd_opt.c doesn't need to know about this constant.53*/54#ifndef ZSTD_HASHLOG3_MAX55# define ZSTD_HASHLOG3_MAX 1756#endif5758/*-*************************************59* Helper functions60***************************************/61/* ZSTD_compressBound()62* Note that the result from this function is only valid for63* the one-pass compression functions.64* When employing the streaming mode,65* if flushes are frequently altering the size of blocks,66* the overhead from block headers can make the compressed data larger67* than the return value of ZSTD_compressBound().68*/69size_t ZSTD_compressBound(size_t srcSize) {70size_t const r = ZSTD_COMPRESSBOUND(srcSize);71if (r==0) return ERROR(srcSize_wrong);72return r;73}747576/*-*************************************77* Context memory management78***************************************/79struct ZSTD_CDict_s {80const void* dictContent;81size_t dictContentSize;82ZSTD_dictContentType_e dictContentType; /* The dictContentType the CDict was created with */83U32* entropyWorkspace; /* entropy workspace of HUF_WORKSPACE_SIZE bytes */84ZSTD_cwksp workspace;85ZSTD_MatchState_t matchState;86ZSTD_compressedBlockState_t cBlockState;87ZSTD_customMem customMem;88U32 dictID;89int compressionLevel; /* 0 indicates that advanced API was used to select CDict params */90ZSTD_ParamSwitch_e useRowMatchFinder; /* Indicates whether the CDict was created with params that would use91* row-based matchfinder. Unless the cdict is reloaded, we will use92* the same greedy/lazy matchfinder at compression time.93*/94}; /* typedef'd to ZSTD_CDict within "zstd.h" */9596ZSTD_CCtx* ZSTD_createCCtx(void)97{98return ZSTD_createCCtx_advanced(ZSTD_defaultCMem);99}100101static void ZSTD_initCCtx(ZSTD_CCtx* cctx, ZSTD_customMem memManager)102{103assert(cctx != NULL);104ZSTD_memset(cctx, 0, sizeof(*cctx));105cctx->customMem = memManager;106cctx->bmi2 = ZSTD_cpuSupportsBmi2();107{ size_t const err = ZSTD_CCtx_reset(cctx, ZSTD_reset_parameters);108assert(!ZSTD_isError(err));109(void)err;110}111}112113ZSTD_CCtx* ZSTD_createCCtx_advanced(ZSTD_customMem customMem)114{115ZSTD_STATIC_ASSERT(zcss_init==0);116ZSTD_STATIC_ASSERT(ZSTD_CONTENTSIZE_UNKNOWN==(0ULL - 1));117if ((!customMem.customAlloc) ^ (!customMem.customFree)) return NULL;118{ ZSTD_CCtx* const cctx = (ZSTD_CCtx*)ZSTD_customMalloc(sizeof(ZSTD_CCtx), customMem);119if (!cctx) return NULL;120ZSTD_initCCtx(cctx, customMem);121return cctx;122}123}124125ZSTD_CCtx* ZSTD_initStaticCCtx(void* workspace, size_t workspaceSize)126{127ZSTD_cwksp ws;128ZSTD_CCtx* cctx;129if (workspaceSize <= sizeof(ZSTD_CCtx)) return NULL; /* minimum size */130if ((size_t)workspace & 7) return NULL; /* must be 8-aligned */131ZSTD_cwksp_init(&ws, workspace, workspaceSize, ZSTD_cwksp_static_alloc);132133cctx = (ZSTD_CCtx*)ZSTD_cwksp_reserve_object(&ws, sizeof(ZSTD_CCtx));134if (cctx == NULL) return NULL;135136ZSTD_memset(cctx, 0, sizeof(ZSTD_CCtx));137ZSTD_cwksp_move(&cctx->workspace, &ws);138cctx->staticSize = workspaceSize;139140/* statically sized space. tmpWorkspace never moves (but prev/next block swap places) */141if (!ZSTD_cwksp_check_available(&cctx->workspace, TMP_WORKSPACE_SIZE + 2 * sizeof(ZSTD_compressedBlockState_t))) return NULL;142cctx->blockState.prevCBlock = (ZSTD_compressedBlockState_t*)ZSTD_cwksp_reserve_object(&cctx->workspace, sizeof(ZSTD_compressedBlockState_t));143cctx->blockState.nextCBlock = (ZSTD_compressedBlockState_t*)ZSTD_cwksp_reserve_object(&cctx->workspace, sizeof(ZSTD_compressedBlockState_t));144cctx->tmpWorkspace = ZSTD_cwksp_reserve_object(&cctx->workspace, TMP_WORKSPACE_SIZE);145cctx->tmpWkspSize = TMP_WORKSPACE_SIZE;146cctx->bmi2 = ZSTD_cpuid_bmi2(ZSTD_cpuid());147return cctx;148}149150/**151* Clears and frees all of the dictionaries in the CCtx.152*/153static void ZSTD_clearAllDicts(ZSTD_CCtx* cctx)154{155ZSTD_customFree(cctx->localDict.dictBuffer, cctx->customMem);156ZSTD_freeCDict(cctx->localDict.cdict);157ZSTD_memset(&cctx->localDict, 0, sizeof(cctx->localDict));158ZSTD_memset(&cctx->prefixDict, 0, sizeof(cctx->prefixDict));159cctx->cdict = NULL;160}161162static size_t ZSTD_sizeof_localDict(ZSTD_localDict dict)163{164size_t const bufferSize = dict.dictBuffer != NULL ? dict.dictSize : 0;165size_t const cdictSize = ZSTD_sizeof_CDict(dict.cdict);166return bufferSize + cdictSize;167}168169static void ZSTD_freeCCtxContent(ZSTD_CCtx* cctx)170{171assert(cctx != NULL);172assert(cctx->staticSize == 0);173ZSTD_clearAllDicts(cctx);174#ifdef ZSTD_MULTITHREAD175ZSTDMT_freeCCtx(cctx->mtctx); cctx->mtctx = NULL;176#endif177ZSTD_cwksp_free(&cctx->workspace, cctx->customMem);178}179180size_t ZSTD_freeCCtx(ZSTD_CCtx* cctx)181{182DEBUGLOG(3, "ZSTD_freeCCtx (address: %p)", (void*)cctx);183if (cctx==NULL) return 0; /* support free on NULL */184RETURN_ERROR_IF(cctx->staticSize, memory_allocation,185"not compatible with static CCtx");186{ int cctxInWorkspace = ZSTD_cwksp_owns_buffer(&cctx->workspace, cctx);187ZSTD_freeCCtxContent(cctx);188if (!cctxInWorkspace) ZSTD_customFree(cctx, cctx->customMem);189}190return 0;191}192193194static size_t ZSTD_sizeof_mtctx(const ZSTD_CCtx* cctx)195{196#ifdef ZSTD_MULTITHREAD197return ZSTDMT_sizeof_CCtx(cctx->mtctx);198#else199(void)cctx;200return 0;201#endif202}203204205size_t ZSTD_sizeof_CCtx(const ZSTD_CCtx* cctx)206{207if (cctx==NULL) return 0; /* support sizeof on NULL */208/* cctx may be in the workspace */209return (cctx->workspace.workspace == cctx ? 0 : sizeof(*cctx))210+ ZSTD_cwksp_sizeof(&cctx->workspace)211+ ZSTD_sizeof_localDict(cctx->localDict)212+ ZSTD_sizeof_mtctx(cctx);213}214215size_t ZSTD_sizeof_CStream(const ZSTD_CStream* zcs)216{217return ZSTD_sizeof_CCtx(zcs); /* same object */218}219220/* private API call, for dictBuilder only */221const SeqStore_t* ZSTD_getSeqStore(const ZSTD_CCtx* ctx) { return &(ctx->seqStore); }222223/* Returns true if the strategy supports using a row based matchfinder */224static int ZSTD_rowMatchFinderSupported(const ZSTD_strategy strategy) {225return (strategy >= ZSTD_greedy && strategy <= ZSTD_lazy2);226}227228/* Returns true if the strategy and useRowMatchFinder mode indicate that we will use the row based matchfinder229* for this compression.230*/231static int ZSTD_rowMatchFinderUsed(const ZSTD_strategy strategy, const ZSTD_ParamSwitch_e mode) {232assert(mode != ZSTD_ps_auto);233return ZSTD_rowMatchFinderSupported(strategy) && (mode == ZSTD_ps_enable);234}235236/* Returns row matchfinder usage given an initial mode and cParams */237static ZSTD_ParamSwitch_e ZSTD_resolveRowMatchFinderMode(ZSTD_ParamSwitch_e mode,238const ZSTD_compressionParameters* const cParams) {239if (mode != ZSTD_ps_auto) return mode; /* if requested enabled, but no SIMD, we still will use row matchfinder */240mode = ZSTD_ps_disable;241if (!ZSTD_rowMatchFinderSupported(cParams->strategy)) return mode;242if (cParams->windowLog > 14) mode = ZSTD_ps_enable;243return mode;244}245246/* Returns block splitter usage (generally speaking, when using slower/stronger compression modes) */247static ZSTD_ParamSwitch_e ZSTD_resolveBlockSplitterMode(ZSTD_ParamSwitch_e mode,248const ZSTD_compressionParameters* const cParams) {249if (mode != ZSTD_ps_auto) return mode;250return (cParams->strategy >= ZSTD_btopt && cParams->windowLog >= 17) ? ZSTD_ps_enable : ZSTD_ps_disable;251}252253/* Returns 1 if the arguments indicate that we should allocate a chainTable, 0 otherwise */254static int ZSTD_allocateChainTable(const ZSTD_strategy strategy,255const ZSTD_ParamSwitch_e useRowMatchFinder,256const U32 forDDSDict) {257assert(useRowMatchFinder != ZSTD_ps_auto);258/* We always should allocate a chaintable if we are allocating a matchstate for a DDS dictionary matchstate.259* We do not allocate a chaintable if we are using ZSTD_fast, or are using the row-based matchfinder.260*/261return forDDSDict || ((strategy != ZSTD_fast) && !ZSTD_rowMatchFinderUsed(strategy, useRowMatchFinder));262}263264/* Returns ZSTD_ps_enable if compression parameters are such that we should265* enable long distance matching (wlog >= 27, strategy >= btopt).266* Returns ZSTD_ps_disable otherwise.267*/268static ZSTD_ParamSwitch_e ZSTD_resolveEnableLdm(ZSTD_ParamSwitch_e mode,269const ZSTD_compressionParameters* const cParams) {270if (mode != ZSTD_ps_auto) return mode;271return (cParams->strategy >= ZSTD_btopt && cParams->windowLog >= 27) ? ZSTD_ps_enable : ZSTD_ps_disable;272}273274static int ZSTD_resolveExternalSequenceValidation(int mode) {275return mode;276}277278/* Resolves maxBlockSize to the default if no value is present. */279static size_t ZSTD_resolveMaxBlockSize(size_t maxBlockSize) {280if (maxBlockSize == 0) {281return ZSTD_BLOCKSIZE_MAX;282} else {283return maxBlockSize;284}285}286287static ZSTD_ParamSwitch_e ZSTD_resolveExternalRepcodeSearch(ZSTD_ParamSwitch_e value, int cLevel) {288if (value != ZSTD_ps_auto) return value;289if (cLevel < 10) {290return ZSTD_ps_disable;291} else {292return ZSTD_ps_enable;293}294}295296/* Returns 1 if compression parameters are such that CDict hashtable and chaintable indices are tagged.297* If so, the tags need to be removed in ZSTD_resetCCtx_byCopyingCDict. */298static int ZSTD_CDictIndicesAreTagged(const ZSTD_compressionParameters* const cParams) {299return cParams->strategy == ZSTD_fast || cParams->strategy == ZSTD_dfast;300}301302static ZSTD_CCtx_params ZSTD_makeCCtxParamsFromCParams(303ZSTD_compressionParameters cParams)304{305ZSTD_CCtx_params cctxParams;306/* should not matter, as all cParams are presumed properly defined */307ZSTD_CCtxParams_init(&cctxParams, ZSTD_CLEVEL_DEFAULT);308cctxParams.cParams = cParams;309310/* Adjust advanced params according to cParams */311cctxParams.ldmParams.enableLdm = ZSTD_resolveEnableLdm(cctxParams.ldmParams.enableLdm, &cParams);312if (cctxParams.ldmParams.enableLdm == ZSTD_ps_enable) {313ZSTD_ldm_adjustParameters(&cctxParams.ldmParams, &cParams);314assert(cctxParams.ldmParams.hashLog >= cctxParams.ldmParams.bucketSizeLog);315assert(cctxParams.ldmParams.hashRateLog < 32);316}317cctxParams.postBlockSplitter = ZSTD_resolveBlockSplitterMode(cctxParams.postBlockSplitter, &cParams);318cctxParams.useRowMatchFinder = ZSTD_resolveRowMatchFinderMode(cctxParams.useRowMatchFinder, &cParams);319cctxParams.validateSequences = ZSTD_resolveExternalSequenceValidation(cctxParams.validateSequences);320cctxParams.maxBlockSize = ZSTD_resolveMaxBlockSize(cctxParams.maxBlockSize);321cctxParams.searchForExternalRepcodes = ZSTD_resolveExternalRepcodeSearch(cctxParams.searchForExternalRepcodes,322cctxParams.compressionLevel);323assert(!ZSTD_checkCParams(cParams));324return cctxParams;325}326327static ZSTD_CCtx_params* ZSTD_createCCtxParams_advanced(328ZSTD_customMem customMem)329{330ZSTD_CCtx_params* params;331if ((!customMem.customAlloc) ^ (!customMem.customFree)) return NULL;332params = (ZSTD_CCtx_params*)ZSTD_customCalloc(333sizeof(ZSTD_CCtx_params), customMem);334if (!params) { return NULL; }335ZSTD_CCtxParams_init(params, ZSTD_CLEVEL_DEFAULT);336params->customMem = customMem;337return params;338}339340ZSTD_CCtx_params* ZSTD_createCCtxParams(void)341{342return ZSTD_createCCtxParams_advanced(ZSTD_defaultCMem);343}344345size_t ZSTD_freeCCtxParams(ZSTD_CCtx_params* params)346{347if (params == NULL) { return 0; }348ZSTD_customFree(params, params->customMem);349return 0;350}351352size_t ZSTD_CCtxParams_reset(ZSTD_CCtx_params* params)353{354return ZSTD_CCtxParams_init(params, ZSTD_CLEVEL_DEFAULT);355}356357size_t ZSTD_CCtxParams_init(ZSTD_CCtx_params* cctxParams, int compressionLevel) {358RETURN_ERROR_IF(!cctxParams, GENERIC, "NULL pointer!");359ZSTD_memset(cctxParams, 0, sizeof(*cctxParams));360cctxParams->compressionLevel = compressionLevel;361cctxParams->fParams.contentSizeFlag = 1;362return 0;363}364365#define ZSTD_NO_CLEVEL 0366367/**368* Initializes `cctxParams` from `params` and `compressionLevel`.369* @param compressionLevel If params are derived from a compression level then that compression level, otherwise ZSTD_NO_CLEVEL.370*/371static void372ZSTD_CCtxParams_init_internal(ZSTD_CCtx_params* cctxParams,373const ZSTD_parameters* params,374int compressionLevel)375{376assert(!ZSTD_checkCParams(params->cParams));377ZSTD_memset(cctxParams, 0, sizeof(*cctxParams));378cctxParams->cParams = params->cParams;379cctxParams->fParams = params->fParams;380/* Should not matter, as all cParams are presumed properly defined.381* But, set it for tracing anyway.382*/383cctxParams->compressionLevel = compressionLevel;384cctxParams->useRowMatchFinder = ZSTD_resolveRowMatchFinderMode(cctxParams->useRowMatchFinder, ¶ms->cParams);385cctxParams->postBlockSplitter = ZSTD_resolveBlockSplitterMode(cctxParams->postBlockSplitter, ¶ms->cParams);386cctxParams->ldmParams.enableLdm = ZSTD_resolveEnableLdm(cctxParams->ldmParams.enableLdm, ¶ms->cParams);387cctxParams->validateSequences = ZSTD_resolveExternalSequenceValidation(cctxParams->validateSequences);388cctxParams->maxBlockSize = ZSTD_resolveMaxBlockSize(cctxParams->maxBlockSize);389cctxParams->searchForExternalRepcodes = ZSTD_resolveExternalRepcodeSearch(cctxParams->searchForExternalRepcodes, compressionLevel);390DEBUGLOG(4, "ZSTD_CCtxParams_init_internal: useRowMatchFinder=%d, useBlockSplitter=%d ldm=%d",391cctxParams->useRowMatchFinder, cctxParams->postBlockSplitter, cctxParams->ldmParams.enableLdm);392}393394size_t ZSTD_CCtxParams_init_advanced(ZSTD_CCtx_params* cctxParams, ZSTD_parameters params)395{396RETURN_ERROR_IF(!cctxParams, GENERIC, "NULL pointer!");397FORWARD_IF_ERROR( ZSTD_checkCParams(params.cParams) , "");398ZSTD_CCtxParams_init_internal(cctxParams, ¶ms, ZSTD_NO_CLEVEL);399return 0;400}401402/**403* Sets cctxParams' cParams and fParams from params, but otherwise leaves them alone.404* @param params Validated zstd parameters.405*/406static void ZSTD_CCtxParams_setZstdParams(407ZSTD_CCtx_params* cctxParams, const ZSTD_parameters* params)408{409assert(!ZSTD_checkCParams(params->cParams));410cctxParams->cParams = params->cParams;411cctxParams->fParams = params->fParams;412/* Should not matter, as all cParams are presumed properly defined.413* But, set it for tracing anyway.414*/415cctxParams->compressionLevel = ZSTD_NO_CLEVEL;416}417418ZSTD_bounds ZSTD_cParam_getBounds(ZSTD_cParameter param)419{420ZSTD_bounds bounds = { 0, 0, 0 };421422switch(param)423{424case ZSTD_c_compressionLevel:425bounds.lowerBound = ZSTD_minCLevel();426bounds.upperBound = ZSTD_maxCLevel();427return bounds;428429case ZSTD_c_windowLog:430bounds.lowerBound = ZSTD_WINDOWLOG_MIN;431bounds.upperBound = ZSTD_WINDOWLOG_MAX;432return bounds;433434case ZSTD_c_hashLog:435bounds.lowerBound = ZSTD_HASHLOG_MIN;436bounds.upperBound = ZSTD_HASHLOG_MAX;437return bounds;438439case ZSTD_c_chainLog:440bounds.lowerBound = ZSTD_CHAINLOG_MIN;441bounds.upperBound = ZSTD_CHAINLOG_MAX;442return bounds;443444case ZSTD_c_searchLog:445bounds.lowerBound = ZSTD_SEARCHLOG_MIN;446bounds.upperBound = ZSTD_SEARCHLOG_MAX;447return bounds;448449case ZSTD_c_minMatch:450bounds.lowerBound = ZSTD_MINMATCH_MIN;451bounds.upperBound = ZSTD_MINMATCH_MAX;452return bounds;453454case ZSTD_c_targetLength:455bounds.lowerBound = ZSTD_TARGETLENGTH_MIN;456bounds.upperBound = ZSTD_TARGETLENGTH_MAX;457return bounds;458459case ZSTD_c_strategy:460bounds.lowerBound = ZSTD_STRATEGY_MIN;461bounds.upperBound = ZSTD_STRATEGY_MAX;462return bounds;463464case ZSTD_c_contentSizeFlag:465bounds.lowerBound = 0;466bounds.upperBound = 1;467return bounds;468469case ZSTD_c_checksumFlag:470bounds.lowerBound = 0;471bounds.upperBound = 1;472return bounds;473474case ZSTD_c_dictIDFlag:475bounds.lowerBound = 0;476bounds.upperBound = 1;477return bounds;478479case ZSTD_c_nbWorkers:480bounds.lowerBound = 0;481#ifdef ZSTD_MULTITHREAD482bounds.upperBound = ZSTDMT_NBWORKERS_MAX;483#else484bounds.upperBound = 0;485#endif486return bounds;487488case ZSTD_c_jobSize:489bounds.lowerBound = 0;490#ifdef ZSTD_MULTITHREAD491bounds.upperBound = ZSTDMT_JOBSIZE_MAX;492#else493bounds.upperBound = 0;494#endif495return bounds;496497case ZSTD_c_overlapLog:498#ifdef ZSTD_MULTITHREAD499bounds.lowerBound = ZSTD_OVERLAPLOG_MIN;500bounds.upperBound = ZSTD_OVERLAPLOG_MAX;501#else502bounds.lowerBound = 0;503bounds.upperBound = 0;504#endif505return bounds;506507case ZSTD_c_enableDedicatedDictSearch:508bounds.lowerBound = 0;509bounds.upperBound = 1;510return bounds;511512case ZSTD_c_enableLongDistanceMatching:513bounds.lowerBound = (int)ZSTD_ps_auto;514bounds.upperBound = (int)ZSTD_ps_disable;515return bounds;516517case ZSTD_c_ldmHashLog:518bounds.lowerBound = ZSTD_LDM_HASHLOG_MIN;519bounds.upperBound = ZSTD_LDM_HASHLOG_MAX;520return bounds;521522case ZSTD_c_ldmMinMatch:523bounds.lowerBound = ZSTD_LDM_MINMATCH_MIN;524bounds.upperBound = ZSTD_LDM_MINMATCH_MAX;525return bounds;526527case ZSTD_c_ldmBucketSizeLog:528bounds.lowerBound = ZSTD_LDM_BUCKETSIZELOG_MIN;529bounds.upperBound = ZSTD_LDM_BUCKETSIZELOG_MAX;530return bounds;531532case ZSTD_c_ldmHashRateLog:533bounds.lowerBound = ZSTD_LDM_HASHRATELOG_MIN;534bounds.upperBound = ZSTD_LDM_HASHRATELOG_MAX;535return bounds;536537/* experimental parameters */538case ZSTD_c_rsyncable:539bounds.lowerBound = 0;540bounds.upperBound = 1;541return bounds;542543case ZSTD_c_forceMaxWindow :544bounds.lowerBound = 0;545bounds.upperBound = 1;546return bounds;547548case ZSTD_c_format:549ZSTD_STATIC_ASSERT(ZSTD_f_zstd1 < ZSTD_f_zstd1_magicless);550bounds.lowerBound = ZSTD_f_zstd1;551bounds.upperBound = ZSTD_f_zstd1_magicless; /* note : how to ensure at compile time that this is the highest value enum ? */552return bounds;553554case ZSTD_c_forceAttachDict:555ZSTD_STATIC_ASSERT(ZSTD_dictDefaultAttach < ZSTD_dictForceLoad);556bounds.lowerBound = ZSTD_dictDefaultAttach;557bounds.upperBound = ZSTD_dictForceLoad; /* note : how to ensure at compile time that this is the highest value enum ? */558return bounds;559560case ZSTD_c_literalCompressionMode:561ZSTD_STATIC_ASSERT(ZSTD_ps_auto < ZSTD_ps_enable && ZSTD_ps_enable < ZSTD_ps_disable);562bounds.lowerBound = (int)ZSTD_ps_auto;563bounds.upperBound = (int)ZSTD_ps_disable;564return bounds;565566case ZSTD_c_targetCBlockSize:567bounds.lowerBound = ZSTD_TARGETCBLOCKSIZE_MIN;568bounds.upperBound = ZSTD_TARGETCBLOCKSIZE_MAX;569return bounds;570571case ZSTD_c_srcSizeHint:572bounds.lowerBound = ZSTD_SRCSIZEHINT_MIN;573bounds.upperBound = ZSTD_SRCSIZEHINT_MAX;574return bounds;575576case ZSTD_c_stableInBuffer:577case ZSTD_c_stableOutBuffer:578bounds.lowerBound = (int)ZSTD_bm_buffered;579bounds.upperBound = (int)ZSTD_bm_stable;580return bounds;581582case ZSTD_c_blockDelimiters:583bounds.lowerBound = (int)ZSTD_sf_noBlockDelimiters;584bounds.upperBound = (int)ZSTD_sf_explicitBlockDelimiters;585return bounds;586587case ZSTD_c_validateSequences:588bounds.lowerBound = 0;589bounds.upperBound = 1;590return bounds;591592case ZSTD_c_splitAfterSequences:593bounds.lowerBound = (int)ZSTD_ps_auto;594bounds.upperBound = (int)ZSTD_ps_disable;595return bounds;596597case ZSTD_c_blockSplitterLevel:598bounds.lowerBound = 0;599bounds.upperBound = ZSTD_BLOCKSPLITTER_LEVEL_MAX;600return bounds;601602case ZSTD_c_useRowMatchFinder:603bounds.lowerBound = (int)ZSTD_ps_auto;604bounds.upperBound = (int)ZSTD_ps_disable;605return bounds;606607case ZSTD_c_deterministicRefPrefix:608bounds.lowerBound = 0;609bounds.upperBound = 1;610return bounds;611612case ZSTD_c_prefetchCDictTables:613bounds.lowerBound = (int)ZSTD_ps_auto;614bounds.upperBound = (int)ZSTD_ps_disable;615return bounds;616617case ZSTD_c_enableSeqProducerFallback:618bounds.lowerBound = 0;619bounds.upperBound = 1;620return bounds;621622case ZSTD_c_maxBlockSize:623bounds.lowerBound = ZSTD_BLOCKSIZE_MAX_MIN;624bounds.upperBound = ZSTD_BLOCKSIZE_MAX;625return bounds;626627case ZSTD_c_repcodeResolution:628bounds.lowerBound = (int)ZSTD_ps_auto;629bounds.upperBound = (int)ZSTD_ps_disable;630return bounds;631632default:633bounds.error = ERROR(parameter_unsupported);634return bounds;635}636}637638/* ZSTD_cParam_clampBounds:639* Clamps the value into the bounded range.640*/641static size_t ZSTD_cParam_clampBounds(ZSTD_cParameter cParam, int* value)642{643ZSTD_bounds const bounds = ZSTD_cParam_getBounds(cParam);644if (ZSTD_isError(bounds.error)) return bounds.error;645if (*value < bounds.lowerBound) *value = bounds.lowerBound;646if (*value > bounds.upperBound) *value = bounds.upperBound;647return 0;648}649650#define BOUNDCHECK(cParam, val) \651do { \652RETURN_ERROR_IF(!ZSTD_cParam_withinBounds(cParam,val), \653parameter_outOfBound, "Param out of bounds"); \654} while (0)655656657static int ZSTD_isUpdateAuthorized(ZSTD_cParameter param)658{659switch(param)660{661case ZSTD_c_compressionLevel:662case ZSTD_c_hashLog:663case ZSTD_c_chainLog:664case ZSTD_c_searchLog:665case ZSTD_c_minMatch:666case ZSTD_c_targetLength:667case ZSTD_c_strategy:668case ZSTD_c_blockSplitterLevel:669return 1;670671case ZSTD_c_format:672case ZSTD_c_windowLog:673case ZSTD_c_contentSizeFlag:674case ZSTD_c_checksumFlag:675case ZSTD_c_dictIDFlag:676case ZSTD_c_forceMaxWindow :677case ZSTD_c_nbWorkers:678case ZSTD_c_jobSize:679case ZSTD_c_overlapLog:680case ZSTD_c_rsyncable:681case ZSTD_c_enableDedicatedDictSearch:682case ZSTD_c_enableLongDistanceMatching:683case ZSTD_c_ldmHashLog:684case ZSTD_c_ldmMinMatch:685case ZSTD_c_ldmBucketSizeLog:686case ZSTD_c_ldmHashRateLog:687case ZSTD_c_forceAttachDict:688case ZSTD_c_literalCompressionMode:689case ZSTD_c_targetCBlockSize:690case ZSTD_c_srcSizeHint:691case ZSTD_c_stableInBuffer:692case ZSTD_c_stableOutBuffer:693case ZSTD_c_blockDelimiters:694case ZSTD_c_validateSequences:695case ZSTD_c_splitAfterSequences:696case ZSTD_c_useRowMatchFinder:697case ZSTD_c_deterministicRefPrefix:698case ZSTD_c_prefetchCDictTables:699case ZSTD_c_enableSeqProducerFallback:700case ZSTD_c_maxBlockSize:701case ZSTD_c_repcodeResolution:702default:703return 0;704}705}706707size_t ZSTD_CCtx_setParameter(ZSTD_CCtx* cctx, ZSTD_cParameter param, int value)708{709DEBUGLOG(4, "ZSTD_CCtx_setParameter (%i, %i)", (int)param, value);710if (cctx->streamStage != zcss_init) {711if (ZSTD_isUpdateAuthorized(param)) {712cctx->cParamsChanged = 1;713} else {714RETURN_ERROR(stage_wrong, "can only set params in cctx init stage");715} }716717switch(param)718{719case ZSTD_c_nbWorkers:720RETURN_ERROR_IF((value!=0) && cctx->staticSize, parameter_unsupported,721"MT not compatible with static alloc");722break;723724case ZSTD_c_compressionLevel:725case ZSTD_c_windowLog:726case ZSTD_c_hashLog:727case ZSTD_c_chainLog:728case ZSTD_c_searchLog:729case ZSTD_c_minMatch:730case ZSTD_c_targetLength:731case ZSTD_c_strategy:732case ZSTD_c_ldmHashRateLog:733case ZSTD_c_format:734case ZSTD_c_contentSizeFlag:735case ZSTD_c_checksumFlag:736case ZSTD_c_dictIDFlag:737case ZSTD_c_forceMaxWindow:738case ZSTD_c_forceAttachDict:739case ZSTD_c_literalCompressionMode:740case ZSTD_c_jobSize:741case ZSTD_c_overlapLog:742case ZSTD_c_rsyncable:743case ZSTD_c_enableDedicatedDictSearch:744case ZSTD_c_enableLongDistanceMatching:745case ZSTD_c_ldmHashLog:746case ZSTD_c_ldmMinMatch:747case ZSTD_c_ldmBucketSizeLog:748case ZSTD_c_targetCBlockSize:749case ZSTD_c_srcSizeHint:750case ZSTD_c_stableInBuffer:751case ZSTD_c_stableOutBuffer:752case ZSTD_c_blockDelimiters:753case ZSTD_c_validateSequences:754case ZSTD_c_splitAfterSequences:755case ZSTD_c_blockSplitterLevel:756case ZSTD_c_useRowMatchFinder:757case ZSTD_c_deterministicRefPrefix:758case ZSTD_c_prefetchCDictTables:759case ZSTD_c_enableSeqProducerFallback:760case ZSTD_c_maxBlockSize:761case ZSTD_c_repcodeResolution:762break;763764default: RETURN_ERROR(parameter_unsupported, "unknown parameter");765}766return ZSTD_CCtxParams_setParameter(&cctx->requestedParams, param, value);767}768769size_t ZSTD_CCtxParams_setParameter(ZSTD_CCtx_params* CCtxParams,770ZSTD_cParameter param, int value)771{772DEBUGLOG(4, "ZSTD_CCtxParams_setParameter (%i, %i)", (int)param, value);773switch(param)774{775case ZSTD_c_format :776BOUNDCHECK(ZSTD_c_format, value);777CCtxParams->format = (ZSTD_format_e)value;778return (size_t)CCtxParams->format;779780case ZSTD_c_compressionLevel : {781FORWARD_IF_ERROR(ZSTD_cParam_clampBounds(param, &value), "");782if (value == 0)783CCtxParams->compressionLevel = ZSTD_CLEVEL_DEFAULT; /* 0 == default */784else785CCtxParams->compressionLevel = value;786if (CCtxParams->compressionLevel >= 0) return (size_t)CCtxParams->compressionLevel;787return 0; /* return type (size_t) cannot represent negative values */788}789790case ZSTD_c_windowLog :791if (value!=0) /* 0 => use default */792BOUNDCHECK(ZSTD_c_windowLog, value);793CCtxParams->cParams.windowLog = (U32)value;794return CCtxParams->cParams.windowLog;795796case ZSTD_c_hashLog :797if (value!=0) /* 0 => use default */798BOUNDCHECK(ZSTD_c_hashLog, value);799CCtxParams->cParams.hashLog = (U32)value;800return CCtxParams->cParams.hashLog;801802case ZSTD_c_chainLog :803if (value!=0) /* 0 => use default */804BOUNDCHECK(ZSTD_c_chainLog, value);805CCtxParams->cParams.chainLog = (U32)value;806return CCtxParams->cParams.chainLog;807808case ZSTD_c_searchLog :809if (value!=0) /* 0 => use default */810BOUNDCHECK(ZSTD_c_searchLog, value);811CCtxParams->cParams.searchLog = (U32)value;812return (size_t)value;813814case ZSTD_c_minMatch :815if (value!=0) /* 0 => use default */816BOUNDCHECK(ZSTD_c_minMatch, value);817CCtxParams->cParams.minMatch = (U32)value;818return CCtxParams->cParams.minMatch;819820case ZSTD_c_targetLength :821BOUNDCHECK(ZSTD_c_targetLength, value);822CCtxParams->cParams.targetLength = (U32)value;823return CCtxParams->cParams.targetLength;824825case ZSTD_c_strategy :826if (value!=0) /* 0 => use default */827BOUNDCHECK(ZSTD_c_strategy, value);828CCtxParams->cParams.strategy = (ZSTD_strategy)value;829return (size_t)CCtxParams->cParams.strategy;830831case ZSTD_c_contentSizeFlag :832/* Content size written in frame header _when known_ (default:1) */833DEBUGLOG(4, "set content size flag = %u", (value!=0));834CCtxParams->fParams.contentSizeFlag = value != 0;835return (size_t)CCtxParams->fParams.contentSizeFlag;836837case ZSTD_c_checksumFlag :838/* A 32-bits content checksum will be calculated and written at end of frame (default:0) */839CCtxParams->fParams.checksumFlag = value != 0;840return (size_t)CCtxParams->fParams.checksumFlag;841842case ZSTD_c_dictIDFlag : /* When applicable, dictionary's dictID is provided in frame header (default:1) */843DEBUGLOG(4, "set dictIDFlag = %u", (value!=0));844CCtxParams->fParams.noDictIDFlag = !value;845return !CCtxParams->fParams.noDictIDFlag;846847case ZSTD_c_forceMaxWindow :848CCtxParams->forceWindow = (value != 0);849return (size_t)CCtxParams->forceWindow;850851case ZSTD_c_forceAttachDict : {852const ZSTD_dictAttachPref_e pref = (ZSTD_dictAttachPref_e)value;853BOUNDCHECK(ZSTD_c_forceAttachDict, (int)pref);854CCtxParams->attachDictPref = pref;855return CCtxParams->attachDictPref;856}857858case ZSTD_c_literalCompressionMode : {859const ZSTD_ParamSwitch_e lcm = (ZSTD_ParamSwitch_e)value;860BOUNDCHECK(ZSTD_c_literalCompressionMode, (int)lcm);861CCtxParams->literalCompressionMode = lcm;862return CCtxParams->literalCompressionMode;863}864865case ZSTD_c_nbWorkers :866#ifndef ZSTD_MULTITHREAD867RETURN_ERROR_IF(value!=0, parameter_unsupported, "not compiled with multithreading");868return 0;869#else870FORWARD_IF_ERROR(ZSTD_cParam_clampBounds(param, &value), "");871CCtxParams->nbWorkers = value;872return (size_t)(CCtxParams->nbWorkers);873#endif874875case ZSTD_c_jobSize :876#ifndef ZSTD_MULTITHREAD877RETURN_ERROR_IF(value!=0, parameter_unsupported, "not compiled with multithreading");878return 0;879#else880/* Adjust to the minimum non-default value. */881if (value != 0 && value < ZSTDMT_JOBSIZE_MIN)882value = ZSTDMT_JOBSIZE_MIN;883FORWARD_IF_ERROR(ZSTD_cParam_clampBounds(param, &value), "");884assert(value >= 0);885CCtxParams->jobSize = (size_t)value;886return CCtxParams->jobSize;887#endif888889case ZSTD_c_overlapLog :890#ifndef ZSTD_MULTITHREAD891RETURN_ERROR_IF(value!=0, parameter_unsupported, "not compiled with multithreading");892return 0;893#else894FORWARD_IF_ERROR(ZSTD_cParam_clampBounds(ZSTD_c_overlapLog, &value), "");895CCtxParams->overlapLog = value;896return (size_t)CCtxParams->overlapLog;897#endif898899case ZSTD_c_rsyncable :900#ifndef ZSTD_MULTITHREAD901RETURN_ERROR_IF(value!=0, parameter_unsupported, "not compiled with multithreading");902return 0;903#else904FORWARD_IF_ERROR(ZSTD_cParam_clampBounds(ZSTD_c_overlapLog, &value), "");905CCtxParams->rsyncable = value;906return (size_t)CCtxParams->rsyncable;907#endif908909case ZSTD_c_enableDedicatedDictSearch :910CCtxParams->enableDedicatedDictSearch = (value!=0);911return (size_t)CCtxParams->enableDedicatedDictSearch;912913case ZSTD_c_enableLongDistanceMatching :914BOUNDCHECK(ZSTD_c_enableLongDistanceMatching, value);915CCtxParams->ldmParams.enableLdm = (ZSTD_ParamSwitch_e)value;916return CCtxParams->ldmParams.enableLdm;917918case ZSTD_c_ldmHashLog :919if (value!=0) /* 0 ==> auto */920BOUNDCHECK(ZSTD_c_ldmHashLog, value);921CCtxParams->ldmParams.hashLog = (U32)value;922return CCtxParams->ldmParams.hashLog;923924case ZSTD_c_ldmMinMatch :925if (value!=0) /* 0 ==> default */926BOUNDCHECK(ZSTD_c_ldmMinMatch, value);927CCtxParams->ldmParams.minMatchLength = (U32)value;928return CCtxParams->ldmParams.minMatchLength;929930case ZSTD_c_ldmBucketSizeLog :931if (value!=0) /* 0 ==> default */932BOUNDCHECK(ZSTD_c_ldmBucketSizeLog, value);933CCtxParams->ldmParams.bucketSizeLog = (U32)value;934return CCtxParams->ldmParams.bucketSizeLog;935936case ZSTD_c_ldmHashRateLog :937if (value!=0) /* 0 ==> default */938BOUNDCHECK(ZSTD_c_ldmHashRateLog, value);939CCtxParams->ldmParams.hashRateLog = (U32)value;940return CCtxParams->ldmParams.hashRateLog;941942case ZSTD_c_targetCBlockSize :943if (value!=0) { /* 0 ==> default */944value = MAX(value, ZSTD_TARGETCBLOCKSIZE_MIN);945BOUNDCHECK(ZSTD_c_targetCBlockSize, value);946}947CCtxParams->targetCBlockSize = (U32)value;948return CCtxParams->targetCBlockSize;949950case ZSTD_c_srcSizeHint :951if (value!=0) /* 0 ==> default */952BOUNDCHECK(ZSTD_c_srcSizeHint, value);953CCtxParams->srcSizeHint = value;954return (size_t)CCtxParams->srcSizeHint;955956case ZSTD_c_stableInBuffer:957BOUNDCHECK(ZSTD_c_stableInBuffer, value);958CCtxParams->inBufferMode = (ZSTD_bufferMode_e)value;959return CCtxParams->inBufferMode;960961case ZSTD_c_stableOutBuffer:962BOUNDCHECK(ZSTD_c_stableOutBuffer, value);963CCtxParams->outBufferMode = (ZSTD_bufferMode_e)value;964return CCtxParams->outBufferMode;965966case ZSTD_c_blockDelimiters:967BOUNDCHECK(ZSTD_c_blockDelimiters, value);968CCtxParams->blockDelimiters = (ZSTD_SequenceFormat_e)value;969return CCtxParams->blockDelimiters;970971case ZSTD_c_validateSequences:972BOUNDCHECK(ZSTD_c_validateSequences, value);973CCtxParams->validateSequences = value;974return (size_t)CCtxParams->validateSequences;975976case ZSTD_c_splitAfterSequences:977BOUNDCHECK(ZSTD_c_splitAfterSequences, value);978CCtxParams->postBlockSplitter = (ZSTD_ParamSwitch_e)value;979return CCtxParams->postBlockSplitter;980981case ZSTD_c_blockSplitterLevel:982BOUNDCHECK(ZSTD_c_blockSplitterLevel, value);983CCtxParams->preBlockSplitter_level = value;984return (size_t)CCtxParams->preBlockSplitter_level;985986case ZSTD_c_useRowMatchFinder:987BOUNDCHECK(ZSTD_c_useRowMatchFinder, value);988CCtxParams->useRowMatchFinder = (ZSTD_ParamSwitch_e)value;989return CCtxParams->useRowMatchFinder;990991case ZSTD_c_deterministicRefPrefix:992BOUNDCHECK(ZSTD_c_deterministicRefPrefix, value);993CCtxParams->deterministicRefPrefix = !!value;994return (size_t)CCtxParams->deterministicRefPrefix;995996case ZSTD_c_prefetchCDictTables:997BOUNDCHECK(ZSTD_c_prefetchCDictTables, value);998CCtxParams->prefetchCDictTables = (ZSTD_ParamSwitch_e)value;999return CCtxParams->prefetchCDictTables;10001001case ZSTD_c_enableSeqProducerFallback:1002BOUNDCHECK(ZSTD_c_enableSeqProducerFallback, value);1003CCtxParams->enableMatchFinderFallback = value;1004return (size_t)CCtxParams->enableMatchFinderFallback;10051006case ZSTD_c_maxBlockSize:1007if (value!=0) /* 0 ==> default */1008BOUNDCHECK(ZSTD_c_maxBlockSize, value);1009assert(value>=0);1010CCtxParams->maxBlockSize = (size_t)value;1011return CCtxParams->maxBlockSize;10121013case ZSTD_c_repcodeResolution:1014BOUNDCHECK(ZSTD_c_repcodeResolution, value);1015CCtxParams->searchForExternalRepcodes = (ZSTD_ParamSwitch_e)value;1016return CCtxParams->searchForExternalRepcodes;10171018default: RETURN_ERROR(parameter_unsupported, "unknown parameter");1019}1020}10211022size_t ZSTD_CCtx_getParameter(ZSTD_CCtx const* cctx, ZSTD_cParameter param, int* value)1023{1024return ZSTD_CCtxParams_getParameter(&cctx->requestedParams, param, value);1025}10261027size_t ZSTD_CCtxParams_getParameter(1028ZSTD_CCtx_params const* CCtxParams, ZSTD_cParameter param, int* value)1029{1030switch(param)1031{1032case ZSTD_c_format :1033*value = (int)CCtxParams->format;1034break;1035case ZSTD_c_compressionLevel :1036*value = CCtxParams->compressionLevel;1037break;1038case ZSTD_c_windowLog :1039*value = (int)CCtxParams->cParams.windowLog;1040break;1041case ZSTD_c_hashLog :1042*value = (int)CCtxParams->cParams.hashLog;1043break;1044case ZSTD_c_chainLog :1045*value = (int)CCtxParams->cParams.chainLog;1046break;1047case ZSTD_c_searchLog :1048*value = (int)CCtxParams->cParams.searchLog;1049break;1050case ZSTD_c_minMatch :1051*value = (int)CCtxParams->cParams.minMatch;1052break;1053case ZSTD_c_targetLength :1054*value = (int)CCtxParams->cParams.targetLength;1055break;1056case ZSTD_c_strategy :1057*value = (int)CCtxParams->cParams.strategy;1058break;1059case ZSTD_c_contentSizeFlag :1060*value = CCtxParams->fParams.contentSizeFlag;1061break;1062case ZSTD_c_checksumFlag :1063*value = CCtxParams->fParams.checksumFlag;1064break;1065case ZSTD_c_dictIDFlag :1066*value = !CCtxParams->fParams.noDictIDFlag;1067break;1068case ZSTD_c_forceMaxWindow :1069*value = CCtxParams->forceWindow;1070break;1071case ZSTD_c_forceAttachDict :1072*value = (int)CCtxParams->attachDictPref;1073break;1074case ZSTD_c_literalCompressionMode :1075*value = (int)CCtxParams->literalCompressionMode;1076break;1077case ZSTD_c_nbWorkers :1078#ifndef ZSTD_MULTITHREAD1079assert(CCtxParams->nbWorkers == 0);1080#endif1081*value = CCtxParams->nbWorkers;1082break;1083case ZSTD_c_jobSize :1084#ifndef ZSTD_MULTITHREAD1085RETURN_ERROR(parameter_unsupported, "not compiled with multithreading");1086#else1087assert(CCtxParams->jobSize <= INT_MAX);1088*value = (int)CCtxParams->jobSize;1089break;1090#endif1091case ZSTD_c_overlapLog :1092#ifndef ZSTD_MULTITHREAD1093RETURN_ERROR(parameter_unsupported, "not compiled with multithreading");1094#else1095*value = CCtxParams->overlapLog;1096break;1097#endif1098case ZSTD_c_rsyncable :1099#ifndef ZSTD_MULTITHREAD1100RETURN_ERROR(parameter_unsupported, "not compiled with multithreading");1101#else1102*value = CCtxParams->rsyncable;1103break;1104#endif1105case ZSTD_c_enableDedicatedDictSearch :1106*value = CCtxParams->enableDedicatedDictSearch;1107break;1108case ZSTD_c_enableLongDistanceMatching :1109*value = (int)CCtxParams->ldmParams.enableLdm;1110break;1111case ZSTD_c_ldmHashLog :1112*value = (int)CCtxParams->ldmParams.hashLog;1113break;1114case ZSTD_c_ldmMinMatch :1115*value = (int)CCtxParams->ldmParams.minMatchLength;1116break;1117case ZSTD_c_ldmBucketSizeLog :1118*value = (int)CCtxParams->ldmParams.bucketSizeLog;1119break;1120case ZSTD_c_ldmHashRateLog :1121*value = (int)CCtxParams->ldmParams.hashRateLog;1122break;1123case ZSTD_c_targetCBlockSize :1124*value = (int)CCtxParams->targetCBlockSize;1125break;1126case ZSTD_c_srcSizeHint :1127*value = (int)CCtxParams->srcSizeHint;1128break;1129case ZSTD_c_stableInBuffer :1130*value = (int)CCtxParams->inBufferMode;1131break;1132case ZSTD_c_stableOutBuffer :1133*value = (int)CCtxParams->outBufferMode;1134break;1135case ZSTD_c_blockDelimiters :1136*value = (int)CCtxParams->blockDelimiters;1137break;1138case ZSTD_c_validateSequences :1139*value = (int)CCtxParams->validateSequences;1140break;1141case ZSTD_c_splitAfterSequences :1142*value = (int)CCtxParams->postBlockSplitter;1143break;1144case ZSTD_c_blockSplitterLevel :1145*value = CCtxParams->preBlockSplitter_level;1146break;1147case ZSTD_c_useRowMatchFinder :1148*value = (int)CCtxParams->useRowMatchFinder;1149break;1150case ZSTD_c_deterministicRefPrefix:1151*value = (int)CCtxParams->deterministicRefPrefix;1152break;1153case ZSTD_c_prefetchCDictTables:1154*value = (int)CCtxParams->prefetchCDictTables;1155break;1156case ZSTD_c_enableSeqProducerFallback:1157*value = CCtxParams->enableMatchFinderFallback;1158break;1159case ZSTD_c_maxBlockSize:1160*value = (int)CCtxParams->maxBlockSize;1161break;1162case ZSTD_c_repcodeResolution:1163*value = (int)CCtxParams->searchForExternalRepcodes;1164break;1165default: RETURN_ERROR(parameter_unsupported, "unknown parameter");1166}1167return 0;1168}11691170/** ZSTD_CCtx_setParametersUsingCCtxParams() :1171* just applies `params` into `cctx`1172* no action is performed, parameters are merely stored.1173* If ZSTDMT is enabled, parameters are pushed to cctx->mtctx.1174* This is possible even if a compression is ongoing.1175* In which case, new parameters will be applied on the fly, starting with next compression job.1176*/1177size_t ZSTD_CCtx_setParametersUsingCCtxParams(1178ZSTD_CCtx* cctx, const ZSTD_CCtx_params* params)1179{1180DEBUGLOG(4, "ZSTD_CCtx_setParametersUsingCCtxParams");1181RETURN_ERROR_IF(cctx->streamStage != zcss_init, stage_wrong,1182"The context is in the wrong stage!");1183RETURN_ERROR_IF(cctx->cdict, stage_wrong,1184"Can't override parameters with cdict attached (some must "1185"be inherited from the cdict).");11861187cctx->requestedParams = *params;1188return 0;1189}11901191size_t ZSTD_CCtx_setCParams(ZSTD_CCtx* cctx, ZSTD_compressionParameters cparams)1192{1193ZSTD_STATIC_ASSERT(sizeof(cparams) == 7 * 4 /* all params are listed below */);1194DEBUGLOG(4, "ZSTD_CCtx_setCParams");1195/* only update if all parameters are valid */1196FORWARD_IF_ERROR(ZSTD_checkCParams(cparams), "");1197FORWARD_IF_ERROR(ZSTD_CCtx_setParameter(cctx, ZSTD_c_windowLog, (int)cparams.windowLog), "");1198FORWARD_IF_ERROR(ZSTD_CCtx_setParameter(cctx, ZSTD_c_chainLog, (int)cparams.chainLog), "");1199FORWARD_IF_ERROR(ZSTD_CCtx_setParameter(cctx, ZSTD_c_hashLog, (int)cparams.hashLog), "");1200FORWARD_IF_ERROR(ZSTD_CCtx_setParameter(cctx, ZSTD_c_searchLog, (int)cparams.searchLog), "");1201FORWARD_IF_ERROR(ZSTD_CCtx_setParameter(cctx, ZSTD_c_minMatch, (int)cparams.minMatch), "");1202FORWARD_IF_ERROR(ZSTD_CCtx_setParameter(cctx, ZSTD_c_targetLength, (int)cparams.targetLength), "");1203FORWARD_IF_ERROR(ZSTD_CCtx_setParameter(cctx, ZSTD_c_strategy, (int)cparams.strategy), "");1204return 0;1205}12061207size_t ZSTD_CCtx_setFParams(ZSTD_CCtx* cctx, ZSTD_frameParameters fparams)1208{1209ZSTD_STATIC_ASSERT(sizeof(fparams) == 3 * 4 /* all params are listed below */);1210DEBUGLOG(4, "ZSTD_CCtx_setFParams");1211FORWARD_IF_ERROR(ZSTD_CCtx_setParameter(cctx, ZSTD_c_contentSizeFlag, fparams.contentSizeFlag != 0), "");1212FORWARD_IF_ERROR(ZSTD_CCtx_setParameter(cctx, ZSTD_c_checksumFlag, fparams.checksumFlag != 0), "");1213FORWARD_IF_ERROR(ZSTD_CCtx_setParameter(cctx, ZSTD_c_dictIDFlag, fparams.noDictIDFlag == 0), "");1214return 0;1215}12161217size_t ZSTD_CCtx_setParams(ZSTD_CCtx* cctx, ZSTD_parameters params)1218{1219DEBUGLOG(4, "ZSTD_CCtx_setParams");1220/* First check cParams, because we want to update all or none. */1221FORWARD_IF_ERROR(ZSTD_checkCParams(params.cParams), "");1222/* Next set fParams, because this could fail if the cctx isn't in init stage. */1223FORWARD_IF_ERROR(ZSTD_CCtx_setFParams(cctx, params.fParams), "");1224/* Finally set cParams, which should succeed. */1225FORWARD_IF_ERROR(ZSTD_CCtx_setCParams(cctx, params.cParams), "");1226return 0;1227}12281229size_t ZSTD_CCtx_setPledgedSrcSize(ZSTD_CCtx* cctx, unsigned long long pledgedSrcSize)1230{1231DEBUGLOG(4, "ZSTD_CCtx_setPledgedSrcSize to %llu bytes", pledgedSrcSize);1232RETURN_ERROR_IF(cctx->streamStage != zcss_init, stage_wrong,1233"Can't set pledgedSrcSize when not in init stage.");1234cctx->pledgedSrcSizePlusOne = pledgedSrcSize+1;1235return 0;1236}12371238static ZSTD_compressionParameters ZSTD_dedicatedDictSearch_getCParams(1239int const compressionLevel,1240size_t const dictSize);1241static int ZSTD_dedicatedDictSearch_isSupported(1242const ZSTD_compressionParameters* cParams);1243static void ZSTD_dedicatedDictSearch_revertCParams(1244ZSTD_compressionParameters* cParams);12451246/**1247* Initializes the local dictionary using requested parameters.1248* NOTE: Initialization does not employ the pledged src size,1249* because the dictionary may be used for multiple compressions.1250*/1251static size_t ZSTD_initLocalDict(ZSTD_CCtx* cctx)1252{1253ZSTD_localDict* const dl = &cctx->localDict;1254if (dl->dict == NULL) {1255/* No local dictionary. */1256assert(dl->dictBuffer == NULL);1257assert(dl->cdict == NULL);1258assert(dl->dictSize == 0);1259return 0;1260}1261if (dl->cdict != NULL) {1262/* Local dictionary already initialized. */1263assert(cctx->cdict == dl->cdict);1264return 0;1265}1266assert(dl->dictSize > 0);1267assert(cctx->cdict == NULL);1268assert(cctx->prefixDict.dict == NULL);12691270dl->cdict = ZSTD_createCDict_advanced2(1271dl->dict,1272dl->dictSize,1273ZSTD_dlm_byRef,1274dl->dictContentType,1275&cctx->requestedParams,1276cctx->customMem);1277RETURN_ERROR_IF(!dl->cdict, memory_allocation, "ZSTD_createCDict_advanced failed");1278cctx->cdict = dl->cdict;1279return 0;1280}12811282size_t ZSTD_CCtx_loadDictionary_advanced(1283ZSTD_CCtx* cctx,1284const void* dict, size_t dictSize,1285ZSTD_dictLoadMethod_e dictLoadMethod,1286ZSTD_dictContentType_e dictContentType)1287{1288DEBUGLOG(4, "ZSTD_CCtx_loadDictionary_advanced (size: %u)", (U32)dictSize);1289RETURN_ERROR_IF(cctx->streamStage != zcss_init, stage_wrong,1290"Can't load a dictionary when cctx is not in init stage.");1291ZSTD_clearAllDicts(cctx); /* erase any previously set dictionary */1292if (dict == NULL || dictSize == 0) /* no dictionary */1293return 0;1294if (dictLoadMethod == ZSTD_dlm_byRef) {1295cctx->localDict.dict = dict;1296} else {1297/* copy dictionary content inside CCtx to own its lifetime */1298void* dictBuffer;1299RETURN_ERROR_IF(cctx->staticSize, memory_allocation,1300"static CCtx can't allocate for an internal copy of dictionary");1301dictBuffer = ZSTD_customMalloc(dictSize, cctx->customMem);1302RETURN_ERROR_IF(dictBuffer==NULL, memory_allocation,1303"allocation failed for dictionary content");1304ZSTD_memcpy(dictBuffer, dict, dictSize);1305cctx->localDict.dictBuffer = dictBuffer; /* owned ptr to free */1306cctx->localDict.dict = dictBuffer; /* read-only reference */1307}1308cctx->localDict.dictSize = dictSize;1309cctx->localDict.dictContentType = dictContentType;1310return 0;1311}13121313size_t ZSTD_CCtx_loadDictionary_byReference(1314ZSTD_CCtx* cctx, const void* dict, size_t dictSize)1315{1316return ZSTD_CCtx_loadDictionary_advanced(1317cctx, dict, dictSize, ZSTD_dlm_byRef, ZSTD_dct_auto);1318}13191320size_t ZSTD_CCtx_loadDictionary(ZSTD_CCtx* cctx, const void* dict, size_t dictSize)1321{1322return ZSTD_CCtx_loadDictionary_advanced(1323cctx, dict, dictSize, ZSTD_dlm_byCopy, ZSTD_dct_auto);1324}132513261327size_t ZSTD_CCtx_refCDict(ZSTD_CCtx* cctx, const ZSTD_CDict* cdict)1328{1329RETURN_ERROR_IF(cctx->streamStage != zcss_init, stage_wrong,1330"Can't ref a dict when ctx not in init stage.");1331/* Free the existing local cdict (if any) to save memory. */1332ZSTD_clearAllDicts(cctx);1333cctx->cdict = cdict;1334return 0;1335}13361337size_t ZSTD_CCtx_refThreadPool(ZSTD_CCtx* cctx, ZSTD_threadPool* pool)1338{1339RETURN_ERROR_IF(cctx->streamStage != zcss_init, stage_wrong,1340"Can't ref a pool when ctx not in init stage.");1341cctx->pool = pool;1342return 0;1343}13441345size_t ZSTD_CCtx_refPrefix(ZSTD_CCtx* cctx, const void* prefix, size_t prefixSize)1346{1347return ZSTD_CCtx_refPrefix_advanced(cctx, prefix, prefixSize, ZSTD_dct_rawContent);1348}13491350size_t ZSTD_CCtx_refPrefix_advanced(1351ZSTD_CCtx* cctx, const void* prefix, size_t prefixSize, ZSTD_dictContentType_e dictContentType)1352{1353RETURN_ERROR_IF(cctx->streamStage != zcss_init, stage_wrong,1354"Can't ref a prefix when ctx not in init stage.");1355ZSTD_clearAllDicts(cctx);1356if (prefix != NULL && prefixSize > 0) {1357cctx->prefixDict.dict = prefix;1358cctx->prefixDict.dictSize = prefixSize;1359cctx->prefixDict.dictContentType = dictContentType;1360}1361return 0;1362}13631364/*! ZSTD_CCtx_reset() :1365* Also dumps dictionary */1366size_t ZSTD_CCtx_reset(ZSTD_CCtx* cctx, ZSTD_ResetDirective reset)1367{1368if ( (reset == ZSTD_reset_session_only)1369|| (reset == ZSTD_reset_session_and_parameters) ) {1370cctx->streamStage = zcss_init;1371cctx->pledgedSrcSizePlusOne = 0;1372}1373if ( (reset == ZSTD_reset_parameters)1374|| (reset == ZSTD_reset_session_and_parameters) ) {1375RETURN_ERROR_IF(cctx->streamStage != zcss_init, stage_wrong,1376"Reset parameters is only possible during init stage.");1377ZSTD_clearAllDicts(cctx);1378return ZSTD_CCtxParams_reset(&cctx->requestedParams);1379}1380return 0;1381}138213831384/** ZSTD_checkCParams() :1385control CParam values remain within authorized range.1386@return : 0, or an error code if one value is beyond authorized range */1387size_t ZSTD_checkCParams(ZSTD_compressionParameters cParams)1388{1389BOUNDCHECK(ZSTD_c_windowLog, (int)cParams.windowLog);1390BOUNDCHECK(ZSTD_c_chainLog, (int)cParams.chainLog);1391BOUNDCHECK(ZSTD_c_hashLog, (int)cParams.hashLog);1392BOUNDCHECK(ZSTD_c_searchLog, (int)cParams.searchLog);1393BOUNDCHECK(ZSTD_c_minMatch, (int)cParams.minMatch);1394BOUNDCHECK(ZSTD_c_targetLength,(int)cParams.targetLength);1395BOUNDCHECK(ZSTD_c_strategy, (int)cParams.strategy);1396return 0;1397}13981399/** ZSTD_clampCParams() :1400* make CParam values within valid range.1401* @return : valid CParams */1402static ZSTD_compressionParameters1403ZSTD_clampCParams(ZSTD_compressionParameters cParams)1404{1405# define CLAMP_TYPE(cParam, val, type) \1406do { \1407ZSTD_bounds const bounds = ZSTD_cParam_getBounds(cParam); \1408if ((int)val<bounds.lowerBound) val=(type)bounds.lowerBound; \1409else if ((int)val>bounds.upperBound) val=(type)bounds.upperBound; \1410} while (0)1411# define CLAMP(cParam, val) CLAMP_TYPE(cParam, val, unsigned)1412CLAMP(ZSTD_c_windowLog, cParams.windowLog);1413CLAMP(ZSTD_c_chainLog, cParams.chainLog);1414CLAMP(ZSTD_c_hashLog, cParams.hashLog);1415CLAMP(ZSTD_c_searchLog, cParams.searchLog);1416CLAMP(ZSTD_c_minMatch, cParams.minMatch);1417CLAMP(ZSTD_c_targetLength,cParams.targetLength);1418CLAMP_TYPE(ZSTD_c_strategy,cParams.strategy, ZSTD_strategy);1419return cParams;1420}14211422/** ZSTD_cycleLog() :1423* condition for correct operation : hashLog > 1 */1424U32 ZSTD_cycleLog(U32 hashLog, ZSTD_strategy strat)1425{1426U32 const btScale = ((U32)strat >= (U32)ZSTD_btlazy2);1427return hashLog - btScale;1428}14291430/** ZSTD_dictAndWindowLog() :1431* Returns an adjusted window log that is large enough to fit the source and the dictionary.1432* The zstd format says that the entire dictionary is valid if one byte of the dictionary1433* is within the window. So the hashLog and chainLog should be large enough to reference both1434* the dictionary and the window. So we must use this adjusted dictAndWindowLog when downsizing1435* the hashLog and windowLog.1436* NOTE: srcSize must not be ZSTD_CONTENTSIZE_UNKNOWN.1437*/1438static U32 ZSTD_dictAndWindowLog(U32 windowLog, U64 srcSize, U64 dictSize)1439{1440const U64 maxWindowSize = 1ULL << ZSTD_WINDOWLOG_MAX;1441/* No dictionary ==> No change */1442if (dictSize == 0) {1443return windowLog;1444}1445assert(windowLog <= ZSTD_WINDOWLOG_MAX);1446assert(srcSize != ZSTD_CONTENTSIZE_UNKNOWN); /* Handled in ZSTD_adjustCParams_internal() */1447{1448U64 const windowSize = 1ULL << windowLog;1449U64 const dictAndWindowSize = dictSize + windowSize;1450/* If the window size is already large enough to fit both the source and the dictionary1451* then just use the window size. Otherwise adjust so that it fits the dictionary and1452* the window.1453*/1454if (windowSize >= dictSize + srcSize) {1455return windowLog; /* Window size large enough already */1456} else if (dictAndWindowSize >= maxWindowSize) {1457return ZSTD_WINDOWLOG_MAX; /* Larger than max window log */1458} else {1459return ZSTD_highbit32((U32)dictAndWindowSize - 1) + 1;1460}1461}1462}14631464/** ZSTD_adjustCParams_internal() :1465* optimize `cPar` for a specified input (`srcSize` and `dictSize`).1466* mostly downsize to reduce memory consumption and initialization latency.1467* `srcSize` can be ZSTD_CONTENTSIZE_UNKNOWN when not known.1468* `mode` is the mode for parameter adjustment. See docs for `ZSTD_CParamMode_e`.1469* note : `srcSize==0` means 0!1470* condition : cPar is presumed validated (can be checked using ZSTD_checkCParams()). */1471static ZSTD_compressionParameters1472ZSTD_adjustCParams_internal(ZSTD_compressionParameters cPar,1473unsigned long long srcSize,1474size_t dictSize,1475ZSTD_CParamMode_e mode,1476ZSTD_ParamSwitch_e useRowMatchFinder)1477{1478const U64 minSrcSize = 513; /* (1<<9) + 1 */1479const U64 maxWindowResize = 1ULL << (ZSTD_WINDOWLOG_MAX-1);1480assert(ZSTD_checkCParams(cPar)==0);14811482/* Cascade the selected strategy down to the next-highest one built into1483* this binary. */1484#ifdef ZSTD_EXCLUDE_BTULTRA_BLOCK_COMPRESSOR1485if (cPar.strategy == ZSTD_btultra2) {1486cPar.strategy = ZSTD_btultra;1487}1488if (cPar.strategy == ZSTD_btultra) {1489cPar.strategy = ZSTD_btopt;1490}1491#endif1492#ifdef ZSTD_EXCLUDE_BTOPT_BLOCK_COMPRESSOR1493if (cPar.strategy == ZSTD_btopt) {1494cPar.strategy = ZSTD_btlazy2;1495}1496#endif1497#ifdef ZSTD_EXCLUDE_BTLAZY2_BLOCK_COMPRESSOR1498if (cPar.strategy == ZSTD_btlazy2) {1499cPar.strategy = ZSTD_lazy2;1500}1501#endif1502#ifdef ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR1503if (cPar.strategy == ZSTD_lazy2) {1504cPar.strategy = ZSTD_lazy;1505}1506#endif1507#ifdef ZSTD_EXCLUDE_LAZY_BLOCK_COMPRESSOR1508if (cPar.strategy == ZSTD_lazy) {1509cPar.strategy = ZSTD_greedy;1510}1511#endif1512#ifdef ZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR1513if (cPar.strategy == ZSTD_greedy) {1514cPar.strategy = ZSTD_dfast;1515}1516#endif1517#ifdef ZSTD_EXCLUDE_DFAST_BLOCK_COMPRESSOR1518if (cPar.strategy == ZSTD_dfast) {1519cPar.strategy = ZSTD_fast;1520cPar.targetLength = 0;1521}1522#endif15231524switch (mode) {1525case ZSTD_cpm_unknown:1526case ZSTD_cpm_noAttachDict:1527/* If we don't know the source size, don't make any1528* assumptions about it. We will already have selected1529* smaller parameters if a dictionary is in use.1530*/1531break;1532case ZSTD_cpm_createCDict:1533/* Assume a small source size when creating a dictionary1534* with an unknown source size.1535*/1536if (dictSize && srcSize == ZSTD_CONTENTSIZE_UNKNOWN)1537srcSize = minSrcSize;1538break;1539case ZSTD_cpm_attachDict:1540/* Dictionary has its own dedicated parameters which have1541* already been selected. We are selecting parameters1542* for only the source.1543*/1544dictSize = 0;1545break;1546default:1547assert(0);1548break;1549}15501551/* resize windowLog if input is small enough, to use less memory */1552if ( (srcSize <= maxWindowResize)1553&& (dictSize <= maxWindowResize) ) {1554U32 const tSize = (U32)(srcSize + dictSize);1555static U32 const hashSizeMin = 1 << ZSTD_HASHLOG_MIN;1556U32 const srcLog = (tSize < hashSizeMin) ? ZSTD_HASHLOG_MIN :1557ZSTD_highbit32(tSize-1) + 1;1558if (cPar.windowLog > srcLog) cPar.windowLog = srcLog;1559}1560if (srcSize != ZSTD_CONTENTSIZE_UNKNOWN) {1561U32 const dictAndWindowLog = ZSTD_dictAndWindowLog(cPar.windowLog, (U64)srcSize, (U64)dictSize);1562U32 const cycleLog = ZSTD_cycleLog(cPar.chainLog, cPar.strategy);1563if (cPar.hashLog > dictAndWindowLog+1) cPar.hashLog = dictAndWindowLog+1;1564if (cycleLog > dictAndWindowLog)1565cPar.chainLog -= (cycleLog - dictAndWindowLog);1566}15671568if (cPar.windowLog < ZSTD_WINDOWLOG_ABSOLUTEMIN)1569cPar.windowLog = ZSTD_WINDOWLOG_ABSOLUTEMIN; /* minimum wlog required for valid frame header */15701571/* We can't use more than 32 bits of hash in total, so that means that we require:1572* (hashLog + 8) <= 32 && (chainLog + 8) <= 321573*/1574if (mode == ZSTD_cpm_createCDict && ZSTD_CDictIndicesAreTagged(&cPar)) {1575U32 const maxShortCacheHashLog = 32 - ZSTD_SHORT_CACHE_TAG_BITS;1576if (cPar.hashLog > maxShortCacheHashLog) {1577cPar.hashLog = maxShortCacheHashLog;1578}1579if (cPar.chainLog > maxShortCacheHashLog) {1580cPar.chainLog = maxShortCacheHashLog;1581}1582}158315841585/* At this point, we aren't 100% sure if we are using the row match finder.1586* Unless it is explicitly disabled, conservatively assume that it is enabled.1587* In this case it will only be disabled for small sources, so shrinking the1588* hash log a little bit shouldn't result in any ratio loss.1589*/1590if (useRowMatchFinder == ZSTD_ps_auto)1591useRowMatchFinder = ZSTD_ps_enable;15921593/* We can't hash more than 32-bits in total. So that means that we require:1594* (hashLog - rowLog + 8) <= 321595*/1596if (ZSTD_rowMatchFinderUsed(cPar.strategy, useRowMatchFinder)) {1597/* Switch to 32-entry rows if searchLog is 5 (or more) */1598U32 const rowLog = BOUNDED(4, cPar.searchLog, 6);1599U32 const maxRowHashLog = 32 - ZSTD_ROW_HASH_TAG_BITS;1600U32 const maxHashLog = maxRowHashLog + rowLog;1601assert(cPar.hashLog >= rowLog);1602if (cPar.hashLog > maxHashLog) {1603cPar.hashLog = maxHashLog;1604}1605}16061607return cPar;1608}16091610ZSTD_compressionParameters1611ZSTD_adjustCParams(ZSTD_compressionParameters cPar,1612unsigned long long srcSize,1613size_t dictSize)1614{1615cPar = ZSTD_clampCParams(cPar); /* resulting cPar is necessarily valid (all parameters within range) */1616if (srcSize == 0) srcSize = ZSTD_CONTENTSIZE_UNKNOWN;1617return ZSTD_adjustCParams_internal(cPar, srcSize, dictSize, ZSTD_cpm_unknown, ZSTD_ps_auto);1618}16191620static ZSTD_compressionParameters ZSTD_getCParams_internal(int compressionLevel, unsigned long long srcSizeHint, size_t dictSize, ZSTD_CParamMode_e mode);1621static ZSTD_parameters ZSTD_getParams_internal(int compressionLevel, unsigned long long srcSizeHint, size_t dictSize, ZSTD_CParamMode_e mode);16221623static void ZSTD_overrideCParams(1624ZSTD_compressionParameters* cParams,1625const ZSTD_compressionParameters* overrides)1626{1627if (overrides->windowLog) cParams->windowLog = overrides->windowLog;1628if (overrides->hashLog) cParams->hashLog = overrides->hashLog;1629if (overrides->chainLog) cParams->chainLog = overrides->chainLog;1630if (overrides->searchLog) cParams->searchLog = overrides->searchLog;1631if (overrides->minMatch) cParams->minMatch = overrides->minMatch;1632if (overrides->targetLength) cParams->targetLength = overrides->targetLength;1633if (overrides->strategy) cParams->strategy = overrides->strategy;1634}16351636ZSTD_compressionParameters ZSTD_getCParamsFromCCtxParams(1637const ZSTD_CCtx_params* CCtxParams, U64 srcSizeHint, size_t dictSize, ZSTD_CParamMode_e mode)1638{1639ZSTD_compressionParameters cParams;1640if (srcSizeHint == ZSTD_CONTENTSIZE_UNKNOWN && CCtxParams->srcSizeHint > 0) {1641assert(CCtxParams->srcSizeHint>=0);1642srcSizeHint = (U64)CCtxParams->srcSizeHint;1643}1644cParams = ZSTD_getCParams_internal(CCtxParams->compressionLevel, srcSizeHint, dictSize, mode);1645if (CCtxParams->ldmParams.enableLdm == ZSTD_ps_enable) cParams.windowLog = ZSTD_LDM_DEFAULT_WINDOW_LOG;1646ZSTD_overrideCParams(&cParams, &CCtxParams->cParams);1647assert(!ZSTD_checkCParams(cParams));1648/* srcSizeHint == 0 means 0 */1649return ZSTD_adjustCParams_internal(cParams, srcSizeHint, dictSize, mode, CCtxParams->useRowMatchFinder);1650}16511652static size_t1653ZSTD_sizeof_matchState(const ZSTD_compressionParameters* const cParams,1654const ZSTD_ParamSwitch_e useRowMatchFinder,1655const int enableDedicatedDictSearch,1656const U32 forCCtx)1657{1658/* chain table size should be 0 for fast or row-hash strategies */1659size_t const chainSize = ZSTD_allocateChainTable(cParams->strategy, useRowMatchFinder, enableDedicatedDictSearch && !forCCtx)1660? ((size_t)1 << cParams->chainLog)1661: 0;1662size_t const hSize = ((size_t)1) << cParams->hashLog;1663U32 const hashLog3 = (forCCtx && cParams->minMatch==3) ? MIN(ZSTD_HASHLOG3_MAX, cParams->windowLog) : 0;1664size_t const h3Size = hashLog3 ? ((size_t)1) << hashLog3 : 0;1665/* We don't use ZSTD_cwksp_alloc_size() here because the tables aren't1666* surrounded by redzones in ASAN. */1667size_t const tableSpace = chainSize * sizeof(U32)1668+ hSize * sizeof(U32)1669+ h3Size * sizeof(U32);1670size_t const optPotentialSpace =1671ZSTD_cwksp_aligned64_alloc_size((MaxML+1) * sizeof(U32))1672+ ZSTD_cwksp_aligned64_alloc_size((MaxLL+1) * sizeof(U32))1673+ ZSTD_cwksp_aligned64_alloc_size((MaxOff+1) * sizeof(U32))1674+ ZSTD_cwksp_aligned64_alloc_size((1<<Litbits) * sizeof(U32))1675+ ZSTD_cwksp_aligned64_alloc_size(ZSTD_OPT_SIZE * sizeof(ZSTD_match_t))1676+ ZSTD_cwksp_aligned64_alloc_size(ZSTD_OPT_SIZE * sizeof(ZSTD_optimal_t));1677size_t const lazyAdditionalSpace = ZSTD_rowMatchFinderUsed(cParams->strategy, useRowMatchFinder)1678? ZSTD_cwksp_aligned64_alloc_size(hSize)1679: 0;1680size_t const optSpace = (forCCtx && (cParams->strategy >= ZSTD_btopt))1681? optPotentialSpace1682: 0;1683size_t const slackSpace = ZSTD_cwksp_slack_space_required();16841685/* tables are guaranteed to be sized in multiples of 64 bytes (or 16 uint32_t) */1686ZSTD_STATIC_ASSERT(ZSTD_HASHLOG_MIN >= 4 && ZSTD_WINDOWLOG_MIN >= 4 && ZSTD_CHAINLOG_MIN >= 4);1687assert(useRowMatchFinder != ZSTD_ps_auto);16881689DEBUGLOG(4, "chainSize: %u - hSize: %u - h3Size: %u",1690(U32)chainSize, (U32)hSize, (U32)h3Size);1691return tableSpace + optSpace + slackSpace + lazyAdditionalSpace;1692}16931694/* Helper function for calculating memory requirements.1695* Gives a tighter bound than ZSTD_sequenceBound() by taking minMatch into account. */1696static size_t ZSTD_maxNbSeq(size_t blockSize, unsigned minMatch, int useSequenceProducer) {1697U32 const divider = (minMatch==3 || useSequenceProducer) ? 3 : 4;1698return blockSize / divider;1699}17001701static size_t ZSTD_estimateCCtxSize_usingCCtxParams_internal(1702const ZSTD_compressionParameters* cParams,1703const ldmParams_t* ldmParams,1704const int isStatic,1705const ZSTD_ParamSwitch_e useRowMatchFinder,1706const size_t buffInSize,1707const size_t buffOutSize,1708const U64 pledgedSrcSize,1709int useSequenceProducer,1710size_t maxBlockSize)1711{1712size_t const windowSize = (size_t) BOUNDED(1ULL, 1ULL << cParams->windowLog, pledgedSrcSize);1713size_t const blockSize = MIN(ZSTD_resolveMaxBlockSize(maxBlockSize), windowSize);1714size_t const maxNbSeq = ZSTD_maxNbSeq(blockSize, cParams->minMatch, useSequenceProducer);1715size_t const tokenSpace = ZSTD_cwksp_alloc_size(WILDCOPY_OVERLENGTH + blockSize)1716+ ZSTD_cwksp_aligned64_alloc_size(maxNbSeq * sizeof(SeqDef))1717+ 3 * ZSTD_cwksp_alloc_size(maxNbSeq * sizeof(BYTE));1718size_t const tmpWorkSpace = ZSTD_cwksp_alloc_size(TMP_WORKSPACE_SIZE);1719size_t const blockStateSpace = 2 * ZSTD_cwksp_alloc_size(sizeof(ZSTD_compressedBlockState_t));1720size_t const matchStateSize = ZSTD_sizeof_matchState(cParams, useRowMatchFinder, /* enableDedicatedDictSearch */ 0, /* forCCtx */ 1);17211722size_t const ldmSpace = ZSTD_ldm_getTableSize(*ldmParams);1723size_t const maxNbLdmSeq = ZSTD_ldm_getMaxNbSeq(*ldmParams, blockSize);1724size_t const ldmSeqSpace = ldmParams->enableLdm == ZSTD_ps_enable ?1725ZSTD_cwksp_aligned64_alloc_size(maxNbLdmSeq * sizeof(rawSeq)) : 0;172617271728size_t const bufferSpace = ZSTD_cwksp_alloc_size(buffInSize)1729+ ZSTD_cwksp_alloc_size(buffOutSize);17301731size_t const cctxSpace = isStatic ? ZSTD_cwksp_alloc_size(sizeof(ZSTD_CCtx)) : 0;17321733size_t const maxNbExternalSeq = ZSTD_sequenceBound(blockSize);1734size_t const externalSeqSpace = useSequenceProducer1735? ZSTD_cwksp_aligned64_alloc_size(maxNbExternalSeq * sizeof(ZSTD_Sequence))1736: 0;17371738size_t const neededSpace =1739cctxSpace +1740tmpWorkSpace +1741blockStateSpace +1742ldmSpace +1743ldmSeqSpace +1744matchStateSize +1745tokenSpace +1746bufferSpace +1747externalSeqSpace;17481749DEBUGLOG(5, "estimate workspace : %u", (U32)neededSpace);1750return neededSpace;1751}17521753size_t ZSTD_estimateCCtxSize_usingCCtxParams(const ZSTD_CCtx_params* params)1754{1755ZSTD_compressionParameters const cParams =1756ZSTD_getCParamsFromCCtxParams(params, ZSTD_CONTENTSIZE_UNKNOWN, 0, ZSTD_cpm_noAttachDict);1757ZSTD_ParamSwitch_e const useRowMatchFinder = ZSTD_resolveRowMatchFinderMode(params->useRowMatchFinder,1758&cParams);17591760RETURN_ERROR_IF(params->nbWorkers > 0, GENERIC, "Estimate CCtx size is supported for single-threaded compression only.");1761/* estimateCCtxSize is for one-shot compression. So no buffers should1762* be needed. However, we still allocate two 0-sized buffers, which can1763* take space under ASAN. */1764return ZSTD_estimateCCtxSize_usingCCtxParams_internal(1765&cParams, ¶ms->ldmParams, 1, useRowMatchFinder, 0, 0, ZSTD_CONTENTSIZE_UNKNOWN, ZSTD_hasExtSeqProd(params), params->maxBlockSize);1766}17671768size_t ZSTD_estimateCCtxSize_usingCParams(ZSTD_compressionParameters cParams)1769{1770ZSTD_CCtx_params initialParams = ZSTD_makeCCtxParamsFromCParams(cParams);1771if (ZSTD_rowMatchFinderSupported(cParams.strategy)) {1772/* Pick bigger of not using and using row-based matchfinder for greedy and lazy strategies */1773size_t noRowCCtxSize;1774size_t rowCCtxSize;1775initialParams.useRowMatchFinder = ZSTD_ps_disable;1776noRowCCtxSize = ZSTD_estimateCCtxSize_usingCCtxParams(&initialParams);1777initialParams.useRowMatchFinder = ZSTD_ps_enable;1778rowCCtxSize = ZSTD_estimateCCtxSize_usingCCtxParams(&initialParams);1779return MAX(noRowCCtxSize, rowCCtxSize);1780} else {1781return ZSTD_estimateCCtxSize_usingCCtxParams(&initialParams);1782}1783}17841785static size_t ZSTD_estimateCCtxSize_internal(int compressionLevel)1786{1787int tier = 0;1788size_t largestSize = 0;1789static const unsigned long long srcSizeTiers[4] = {16 KB, 128 KB, 256 KB, ZSTD_CONTENTSIZE_UNKNOWN};1790for (; tier < 4; ++tier) {1791/* Choose the set of cParams for a given level across all srcSizes that give the largest cctxSize */1792ZSTD_compressionParameters const cParams = ZSTD_getCParams_internal(compressionLevel, srcSizeTiers[tier], 0, ZSTD_cpm_noAttachDict);1793largestSize = MAX(ZSTD_estimateCCtxSize_usingCParams(cParams), largestSize);1794}1795return largestSize;1796}17971798size_t ZSTD_estimateCCtxSize(int compressionLevel)1799{1800int level;1801size_t memBudget = 0;1802for (level=MIN(compressionLevel, 1); level<=compressionLevel; level++) {1803/* Ensure monotonically increasing memory usage as compression level increases */1804size_t const newMB = ZSTD_estimateCCtxSize_internal(level);1805if (newMB > memBudget) memBudget = newMB;1806}1807return memBudget;1808}18091810size_t ZSTD_estimateCStreamSize_usingCCtxParams(const ZSTD_CCtx_params* params)1811{1812RETURN_ERROR_IF(params->nbWorkers > 0, GENERIC, "Estimate CCtx size is supported for single-threaded compression only.");1813{ ZSTD_compressionParameters const cParams =1814ZSTD_getCParamsFromCCtxParams(params, ZSTD_CONTENTSIZE_UNKNOWN, 0, ZSTD_cpm_noAttachDict);1815size_t const blockSize = MIN(ZSTD_resolveMaxBlockSize(params->maxBlockSize), (size_t)1 << cParams.windowLog);1816size_t const inBuffSize = (params->inBufferMode == ZSTD_bm_buffered)1817? ((size_t)1 << cParams.windowLog) + blockSize1818: 0;1819size_t const outBuffSize = (params->outBufferMode == ZSTD_bm_buffered)1820? ZSTD_compressBound(blockSize) + 11821: 0;1822ZSTD_ParamSwitch_e const useRowMatchFinder = ZSTD_resolveRowMatchFinderMode(params->useRowMatchFinder, ¶ms->cParams);18231824return ZSTD_estimateCCtxSize_usingCCtxParams_internal(1825&cParams, ¶ms->ldmParams, 1, useRowMatchFinder, inBuffSize, outBuffSize,1826ZSTD_CONTENTSIZE_UNKNOWN, ZSTD_hasExtSeqProd(params), params->maxBlockSize);1827}1828}18291830size_t ZSTD_estimateCStreamSize_usingCParams(ZSTD_compressionParameters cParams)1831{1832ZSTD_CCtx_params initialParams = ZSTD_makeCCtxParamsFromCParams(cParams);1833if (ZSTD_rowMatchFinderSupported(cParams.strategy)) {1834/* Pick bigger of not using and using row-based matchfinder for greedy and lazy strategies */1835size_t noRowCCtxSize;1836size_t rowCCtxSize;1837initialParams.useRowMatchFinder = ZSTD_ps_disable;1838noRowCCtxSize = ZSTD_estimateCStreamSize_usingCCtxParams(&initialParams);1839initialParams.useRowMatchFinder = ZSTD_ps_enable;1840rowCCtxSize = ZSTD_estimateCStreamSize_usingCCtxParams(&initialParams);1841return MAX(noRowCCtxSize, rowCCtxSize);1842} else {1843return ZSTD_estimateCStreamSize_usingCCtxParams(&initialParams);1844}1845}18461847static size_t ZSTD_estimateCStreamSize_internal(int compressionLevel)1848{1849ZSTD_compressionParameters const cParams = ZSTD_getCParams_internal(compressionLevel, ZSTD_CONTENTSIZE_UNKNOWN, 0, ZSTD_cpm_noAttachDict);1850return ZSTD_estimateCStreamSize_usingCParams(cParams);1851}18521853size_t ZSTD_estimateCStreamSize(int compressionLevel)1854{1855int level;1856size_t memBudget = 0;1857for (level=MIN(compressionLevel, 1); level<=compressionLevel; level++) {1858size_t const newMB = ZSTD_estimateCStreamSize_internal(level);1859if (newMB > memBudget) memBudget = newMB;1860}1861return memBudget;1862}18631864/* ZSTD_getFrameProgression():1865* tells how much data has been consumed (input) and produced (output) for current frame.1866* able to count progression inside worker threads (non-blocking mode).1867*/1868ZSTD_frameProgression ZSTD_getFrameProgression(const ZSTD_CCtx* cctx)1869{1870#ifdef ZSTD_MULTITHREAD1871if (cctx->appliedParams.nbWorkers > 0) {1872return ZSTDMT_getFrameProgression(cctx->mtctx);1873}1874#endif1875{ ZSTD_frameProgression fp;1876size_t const buffered = (cctx->inBuff == NULL) ? 0 :1877cctx->inBuffPos - cctx->inToCompress;1878if (buffered) assert(cctx->inBuffPos >= cctx->inToCompress);1879assert(buffered <= ZSTD_BLOCKSIZE_MAX);1880fp.ingested = cctx->consumedSrcSize + buffered;1881fp.consumed = cctx->consumedSrcSize;1882fp.produced = cctx->producedCSize;1883fp.flushed = cctx->producedCSize; /* simplified; some data might still be left within streaming output buffer */1884fp.currentJobID = 0;1885fp.nbActiveWorkers = 0;1886return fp;1887} }18881889/*! ZSTD_toFlushNow()1890* Only useful for multithreading scenarios currently (nbWorkers >= 1).1891*/1892size_t ZSTD_toFlushNow(ZSTD_CCtx* cctx)1893{1894#ifdef ZSTD_MULTITHREAD1895if (cctx->appliedParams.nbWorkers > 0) {1896return ZSTDMT_toFlushNow(cctx->mtctx);1897}1898#endif1899(void)cctx;1900return 0; /* over-simplification; could also check if context is currently running in streaming mode, and in which case, report how many bytes are left to be flushed within output buffer */1901}19021903static void ZSTD_assertEqualCParams(ZSTD_compressionParameters cParams1,1904ZSTD_compressionParameters cParams2)1905{1906(void)cParams1;1907(void)cParams2;1908assert(cParams1.windowLog == cParams2.windowLog);1909assert(cParams1.chainLog == cParams2.chainLog);1910assert(cParams1.hashLog == cParams2.hashLog);1911assert(cParams1.searchLog == cParams2.searchLog);1912assert(cParams1.minMatch == cParams2.minMatch);1913assert(cParams1.targetLength == cParams2.targetLength);1914assert(cParams1.strategy == cParams2.strategy);1915}19161917void ZSTD_reset_compressedBlockState(ZSTD_compressedBlockState_t* bs)1918{1919int i;1920for (i = 0; i < ZSTD_REP_NUM; ++i)1921bs->rep[i] = repStartValue[i];1922bs->entropy.huf.repeatMode = HUF_repeat_none;1923bs->entropy.fse.offcode_repeatMode = FSE_repeat_none;1924bs->entropy.fse.matchlength_repeatMode = FSE_repeat_none;1925bs->entropy.fse.litlength_repeatMode = FSE_repeat_none;1926}19271928/*! ZSTD_invalidateMatchState()1929* Invalidate all the matches in the match finder tables.1930* Requires nextSrc and base to be set (can be NULL).1931*/1932static void ZSTD_invalidateMatchState(ZSTD_MatchState_t* ms)1933{1934ZSTD_window_clear(&ms->window);19351936ms->nextToUpdate = ms->window.dictLimit;1937ms->loadedDictEnd = 0;1938ms->opt.litLengthSum = 0; /* force reset of btopt stats */1939ms->dictMatchState = NULL;1940}19411942/**1943* Controls, for this matchState reset, whether the tables need to be cleared /1944* prepared for the coming compression (ZSTDcrp_makeClean), or whether the1945* tables can be left unclean (ZSTDcrp_leaveDirty), because we know that a1946* subsequent operation will overwrite the table space anyways (e.g., copying1947* the matchState contents in from a CDict).1948*/1949typedef enum {1950ZSTDcrp_makeClean,1951ZSTDcrp_leaveDirty1952} ZSTD_compResetPolicy_e;19531954/**1955* Controls, for this matchState reset, whether indexing can continue where it1956* left off (ZSTDirp_continue), or whether it needs to be restarted from zero1957* (ZSTDirp_reset).1958*/1959typedef enum {1960ZSTDirp_continue,1961ZSTDirp_reset1962} ZSTD_indexResetPolicy_e;19631964typedef enum {1965ZSTD_resetTarget_CDict,1966ZSTD_resetTarget_CCtx1967} ZSTD_resetTarget_e;19681969/* Mixes bits in a 64 bits in a value, based on XXH3_rrmxmx */1970static U64 ZSTD_bitmix(U64 val, U64 len) {1971val ^= ZSTD_rotateRight_U64(val, 49) ^ ZSTD_rotateRight_U64(val, 24);1972val *= 0x9FB21C651E98DF25ULL;1973val ^= (val >> 35) + len ;1974val *= 0x9FB21C651E98DF25ULL;1975return val ^ (val >> 28);1976}19771978/* Mixes in the hashSalt and hashSaltEntropy to create a new hashSalt */1979static void ZSTD_advanceHashSalt(ZSTD_MatchState_t* ms) {1980ms->hashSalt = ZSTD_bitmix(ms->hashSalt, 8) ^ ZSTD_bitmix((U64) ms->hashSaltEntropy, 4);1981}19821983static size_t1984ZSTD_reset_matchState(ZSTD_MatchState_t* ms,1985ZSTD_cwksp* ws,1986const ZSTD_compressionParameters* cParams,1987const ZSTD_ParamSwitch_e useRowMatchFinder,1988const ZSTD_compResetPolicy_e crp,1989const ZSTD_indexResetPolicy_e forceResetIndex,1990const ZSTD_resetTarget_e forWho)1991{1992/* disable chain table allocation for fast or row-based strategies */1993size_t const chainSize = ZSTD_allocateChainTable(cParams->strategy, useRowMatchFinder,1994ms->dedicatedDictSearch && (forWho == ZSTD_resetTarget_CDict))1995? ((size_t)1 << cParams->chainLog)1996: 0;1997size_t const hSize = ((size_t)1) << cParams->hashLog;1998U32 const hashLog3 = ((forWho == ZSTD_resetTarget_CCtx) && cParams->minMatch==3) ? MIN(ZSTD_HASHLOG3_MAX, cParams->windowLog) : 0;1999size_t const h3Size = hashLog3 ? ((size_t)1) << hashLog3 : 0;20002001DEBUGLOG(4, "reset indices : %u", forceResetIndex == ZSTDirp_reset);2002assert(useRowMatchFinder != ZSTD_ps_auto);2003if (forceResetIndex == ZSTDirp_reset) {2004ZSTD_window_init(&ms->window);2005ZSTD_cwksp_mark_tables_dirty(ws);2006}20072008ms->hashLog3 = hashLog3;2009ms->lazySkipping = 0;20102011ZSTD_invalidateMatchState(ms);20122013assert(!ZSTD_cwksp_reserve_failed(ws)); /* check that allocation hasn't already failed */20142015ZSTD_cwksp_clear_tables(ws);20162017DEBUGLOG(5, "reserving table space");2018/* table Space */2019ms->hashTable = (U32*)ZSTD_cwksp_reserve_table(ws, hSize * sizeof(U32));2020ms->chainTable = (U32*)ZSTD_cwksp_reserve_table(ws, chainSize * sizeof(U32));2021ms->hashTable3 = (U32*)ZSTD_cwksp_reserve_table(ws, h3Size * sizeof(U32));2022RETURN_ERROR_IF(ZSTD_cwksp_reserve_failed(ws), memory_allocation,2023"failed a workspace allocation in ZSTD_reset_matchState");20242025DEBUGLOG(4, "reset table : %u", crp!=ZSTDcrp_leaveDirty);2026if (crp!=ZSTDcrp_leaveDirty) {2027/* reset tables only */2028ZSTD_cwksp_clean_tables(ws);2029}20302031if (ZSTD_rowMatchFinderUsed(cParams->strategy, useRowMatchFinder)) {2032/* Row match finder needs an additional table of hashes ("tags") */2033size_t const tagTableSize = hSize;2034/* We want to generate a new salt in case we reset a Cctx, but we always want to use2035* 0 when we reset a Cdict */2036if(forWho == ZSTD_resetTarget_CCtx) {2037ms->tagTable = (BYTE*) ZSTD_cwksp_reserve_aligned_init_once(ws, tagTableSize);2038ZSTD_advanceHashSalt(ms);2039} else {2040/* When we are not salting we want to always memset the memory */2041ms->tagTable = (BYTE*) ZSTD_cwksp_reserve_aligned64(ws, tagTableSize);2042ZSTD_memset(ms->tagTable, 0, tagTableSize);2043ms->hashSalt = 0;2044}2045{ /* Switch to 32-entry rows if searchLog is 5 (or more) */2046U32 const rowLog = BOUNDED(4, cParams->searchLog, 6);2047assert(cParams->hashLog >= rowLog);2048ms->rowHashLog = cParams->hashLog - rowLog;2049}2050}20512052/* opt parser space */2053if ((forWho == ZSTD_resetTarget_CCtx) && (cParams->strategy >= ZSTD_btopt)) {2054DEBUGLOG(4, "reserving optimal parser space");2055ms->opt.litFreq = (unsigned*)ZSTD_cwksp_reserve_aligned64(ws, (1<<Litbits) * sizeof(unsigned));2056ms->opt.litLengthFreq = (unsigned*)ZSTD_cwksp_reserve_aligned64(ws, (MaxLL+1) * sizeof(unsigned));2057ms->opt.matchLengthFreq = (unsigned*)ZSTD_cwksp_reserve_aligned64(ws, (MaxML+1) * sizeof(unsigned));2058ms->opt.offCodeFreq = (unsigned*)ZSTD_cwksp_reserve_aligned64(ws, (MaxOff+1) * sizeof(unsigned));2059ms->opt.matchTable = (ZSTD_match_t*)ZSTD_cwksp_reserve_aligned64(ws, ZSTD_OPT_SIZE * sizeof(ZSTD_match_t));2060ms->opt.priceTable = (ZSTD_optimal_t*)ZSTD_cwksp_reserve_aligned64(ws, ZSTD_OPT_SIZE * sizeof(ZSTD_optimal_t));2061}20622063ms->cParams = *cParams;20642065RETURN_ERROR_IF(ZSTD_cwksp_reserve_failed(ws), memory_allocation,2066"failed a workspace allocation in ZSTD_reset_matchState");2067return 0;2068}20692070/* ZSTD_indexTooCloseToMax() :2071* minor optimization : prefer memset() rather than reduceIndex()2072* which is measurably slow in some circumstances (reported for Visual Studio).2073* Works when re-using a context for a lot of smallish inputs :2074* if all inputs are smaller than ZSTD_INDEXOVERFLOW_MARGIN,2075* memset() will be triggered before reduceIndex().2076*/2077#define ZSTD_INDEXOVERFLOW_MARGIN (16 MB)2078static int ZSTD_indexTooCloseToMax(ZSTD_window_t w)2079{2080return (size_t)(w.nextSrc - w.base) > (ZSTD_CURRENT_MAX - ZSTD_INDEXOVERFLOW_MARGIN);2081}20822083/** ZSTD_dictTooBig():2084* When dictionaries are larger than ZSTD_CHUNKSIZE_MAX they can't be loaded in2085* one go generically. So we ensure that in that case we reset the tables to zero,2086* so that we can load as much of the dictionary as possible.2087*/2088static int ZSTD_dictTooBig(size_t const loadedDictSize)2089{2090return loadedDictSize > ZSTD_CHUNKSIZE_MAX;2091}20922093/*! ZSTD_resetCCtx_internal() :2094* @param loadedDictSize The size of the dictionary to be loaded2095* into the context, if any. If no dictionary is used, or the2096* dictionary is being attached / copied, then pass 0.2097* note : `params` are assumed fully validated at this stage.2098*/2099static size_t ZSTD_resetCCtx_internal(ZSTD_CCtx* zc,2100ZSTD_CCtx_params const* params,2101U64 const pledgedSrcSize,2102size_t const loadedDictSize,2103ZSTD_compResetPolicy_e const crp,2104ZSTD_buffered_policy_e const zbuff)2105{2106ZSTD_cwksp* const ws = &zc->workspace;2107DEBUGLOG(4, "ZSTD_resetCCtx_internal: pledgedSrcSize=%u, wlog=%u, useRowMatchFinder=%d useBlockSplitter=%d",2108(U32)pledgedSrcSize, params->cParams.windowLog, (int)params->useRowMatchFinder, (int)params->postBlockSplitter);2109assert(!ZSTD_isError(ZSTD_checkCParams(params->cParams)));21102111zc->isFirstBlock = 1;21122113/* Set applied params early so we can modify them for LDM,2114* and point params at the applied params.2115*/2116zc->appliedParams = *params;2117params = &zc->appliedParams;21182119assert(params->useRowMatchFinder != ZSTD_ps_auto);2120assert(params->postBlockSplitter != ZSTD_ps_auto);2121assert(params->ldmParams.enableLdm != ZSTD_ps_auto);2122assert(params->maxBlockSize != 0);2123if (params->ldmParams.enableLdm == ZSTD_ps_enable) {2124/* Adjust long distance matching parameters */2125ZSTD_ldm_adjustParameters(&zc->appliedParams.ldmParams, ¶ms->cParams);2126assert(params->ldmParams.hashLog >= params->ldmParams.bucketSizeLog);2127assert(params->ldmParams.hashRateLog < 32);2128}21292130{ size_t const windowSize = MAX(1, (size_t)MIN(((U64)1 << params->cParams.windowLog), pledgedSrcSize));2131size_t const blockSize = MIN(params->maxBlockSize, windowSize);2132size_t const maxNbSeq = ZSTD_maxNbSeq(blockSize, params->cParams.minMatch, ZSTD_hasExtSeqProd(params));2133size_t const buffOutSize = (zbuff == ZSTDb_buffered && params->outBufferMode == ZSTD_bm_buffered)2134? ZSTD_compressBound(blockSize) + 12135: 0;2136size_t const buffInSize = (zbuff == ZSTDb_buffered && params->inBufferMode == ZSTD_bm_buffered)2137? windowSize + blockSize2138: 0;2139size_t const maxNbLdmSeq = ZSTD_ldm_getMaxNbSeq(params->ldmParams, blockSize);21402141int const indexTooClose = ZSTD_indexTooCloseToMax(zc->blockState.matchState.window);2142int const dictTooBig = ZSTD_dictTooBig(loadedDictSize);2143ZSTD_indexResetPolicy_e needsIndexReset =2144(indexTooClose || dictTooBig || !zc->initialized) ? ZSTDirp_reset : ZSTDirp_continue;21452146size_t const neededSpace =2147ZSTD_estimateCCtxSize_usingCCtxParams_internal(2148¶ms->cParams, ¶ms->ldmParams, zc->staticSize != 0, params->useRowMatchFinder,2149buffInSize, buffOutSize, pledgedSrcSize, ZSTD_hasExtSeqProd(params), params->maxBlockSize);21502151FORWARD_IF_ERROR(neededSpace, "cctx size estimate failed!");21522153if (!zc->staticSize) ZSTD_cwksp_bump_oversized_duration(ws, 0);21542155{ /* Check if workspace is large enough, alloc a new one if needed */2156int const workspaceTooSmall = ZSTD_cwksp_sizeof(ws) < neededSpace;2157int const workspaceWasteful = ZSTD_cwksp_check_wasteful(ws, neededSpace);2158int resizeWorkspace = workspaceTooSmall || workspaceWasteful;2159DEBUGLOG(4, "Need %zu B workspace", neededSpace);2160DEBUGLOG(4, "windowSize: %zu - blockSize: %zu", windowSize, blockSize);21612162if (resizeWorkspace) {2163DEBUGLOG(4, "Resize workspaceSize from %zuKB to %zuKB",2164ZSTD_cwksp_sizeof(ws) >> 10,2165neededSpace >> 10);21662167RETURN_ERROR_IF(zc->staticSize, memory_allocation, "static cctx : no resize");21682169needsIndexReset = ZSTDirp_reset;21702171ZSTD_cwksp_free(ws, zc->customMem);2172FORWARD_IF_ERROR(ZSTD_cwksp_create(ws, neededSpace, zc->customMem), "");21732174DEBUGLOG(5, "reserving object space");2175/* Statically sized space.2176* tmpWorkspace never moves,2177* though prev/next block swap places */2178assert(ZSTD_cwksp_check_available(ws, 2 * sizeof(ZSTD_compressedBlockState_t)));2179zc->blockState.prevCBlock = (ZSTD_compressedBlockState_t*) ZSTD_cwksp_reserve_object(ws, sizeof(ZSTD_compressedBlockState_t));2180RETURN_ERROR_IF(zc->blockState.prevCBlock == NULL, memory_allocation, "couldn't allocate prevCBlock");2181zc->blockState.nextCBlock = (ZSTD_compressedBlockState_t*) ZSTD_cwksp_reserve_object(ws, sizeof(ZSTD_compressedBlockState_t));2182RETURN_ERROR_IF(zc->blockState.nextCBlock == NULL, memory_allocation, "couldn't allocate nextCBlock");2183zc->tmpWorkspace = ZSTD_cwksp_reserve_object(ws, TMP_WORKSPACE_SIZE);2184RETURN_ERROR_IF(zc->tmpWorkspace == NULL, memory_allocation, "couldn't allocate tmpWorkspace");2185zc->tmpWkspSize = TMP_WORKSPACE_SIZE;2186} }21872188ZSTD_cwksp_clear(ws);21892190/* init params */2191zc->blockState.matchState.cParams = params->cParams;2192zc->blockState.matchState.prefetchCDictTables = params->prefetchCDictTables == ZSTD_ps_enable;2193zc->pledgedSrcSizePlusOne = pledgedSrcSize+1;2194zc->consumedSrcSize = 0;2195zc->producedCSize = 0;2196if (pledgedSrcSize == ZSTD_CONTENTSIZE_UNKNOWN)2197zc->appliedParams.fParams.contentSizeFlag = 0;2198DEBUGLOG(4, "pledged content size : %u ; flag : %u",2199(unsigned)pledgedSrcSize, zc->appliedParams.fParams.contentSizeFlag);2200zc->blockSizeMax = blockSize;22012202XXH64_reset(&zc->xxhState, 0);2203zc->stage = ZSTDcs_init;2204zc->dictID = 0;2205zc->dictContentSize = 0;22062207ZSTD_reset_compressedBlockState(zc->blockState.prevCBlock);22082209FORWARD_IF_ERROR(ZSTD_reset_matchState(2210&zc->blockState.matchState,2211ws,2212¶ms->cParams,2213params->useRowMatchFinder,2214crp,2215needsIndexReset,2216ZSTD_resetTarget_CCtx), "");22172218zc->seqStore.sequencesStart = (SeqDef*)ZSTD_cwksp_reserve_aligned64(ws, maxNbSeq * sizeof(SeqDef));22192220/* ldm hash table */2221if (params->ldmParams.enableLdm == ZSTD_ps_enable) {2222/* TODO: avoid memset? */2223size_t const ldmHSize = ((size_t)1) << params->ldmParams.hashLog;2224zc->ldmState.hashTable = (ldmEntry_t*)ZSTD_cwksp_reserve_aligned64(ws, ldmHSize * sizeof(ldmEntry_t));2225ZSTD_memset(zc->ldmState.hashTable, 0, ldmHSize * sizeof(ldmEntry_t));2226zc->ldmSequences = (rawSeq*)ZSTD_cwksp_reserve_aligned64(ws, maxNbLdmSeq * sizeof(rawSeq));2227zc->maxNbLdmSequences = maxNbLdmSeq;22282229ZSTD_window_init(&zc->ldmState.window);2230zc->ldmState.loadedDictEnd = 0;2231}22322233/* reserve space for block-level external sequences */2234if (ZSTD_hasExtSeqProd(params)) {2235size_t const maxNbExternalSeq = ZSTD_sequenceBound(blockSize);2236zc->extSeqBufCapacity = maxNbExternalSeq;2237zc->extSeqBuf =2238(ZSTD_Sequence*)ZSTD_cwksp_reserve_aligned64(ws, maxNbExternalSeq * sizeof(ZSTD_Sequence));2239}22402241/* buffers */22422243/* ZSTD_wildcopy() is used to copy into the literals buffer,2244* so we have to oversize the buffer by WILDCOPY_OVERLENGTH bytes.2245*/2246zc->seqStore.litStart = ZSTD_cwksp_reserve_buffer(ws, blockSize + WILDCOPY_OVERLENGTH);2247zc->seqStore.maxNbLit = blockSize;22482249zc->bufferedPolicy = zbuff;2250zc->inBuffSize = buffInSize;2251zc->inBuff = (char*)ZSTD_cwksp_reserve_buffer(ws, buffInSize);2252zc->outBuffSize = buffOutSize;2253zc->outBuff = (char*)ZSTD_cwksp_reserve_buffer(ws, buffOutSize);22542255/* ldm bucketOffsets table */2256if (params->ldmParams.enableLdm == ZSTD_ps_enable) {2257/* TODO: avoid memset? */2258size_t const numBuckets =2259((size_t)1) << (params->ldmParams.hashLog -2260params->ldmParams.bucketSizeLog);2261zc->ldmState.bucketOffsets = ZSTD_cwksp_reserve_buffer(ws, numBuckets);2262ZSTD_memset(zc->ldmState.bucketOffsets, 0, numBuckets);2263}22642265/* sequences storage */2266ZSTD_referenceExternalSequences(zc, NULL, 0);2267zc->seqStore.maxNbSeq = maxNbSeq;2268zc->seqStore.llCode = ZSTD_cwksp_reserve_buffer(ws, maxNbSeq * sizeof(BYTE));2269zc->seqStore.mlCode = ZSTD_cwksp_reserve_buffer(ws, maxNbSeq * sizeof(BYTE));2270zc->seqStore.ofCode = ZSTD_cwksp_reserve_buffer(ws, maxNbSeq * sizeof(BYTE));22712272DEBUGLOG(3, "wksp: finished allocating, %zd bytes remain available", ZSTD_cwksp_available_space(ws));2273assert(ZSTD_cwksp_estimated_space_within_bounds(ws, neededSpace));22742275zc->initialized = 1;22762277return 0;2278}2279}22802281/* ZSTD_invalidateRepCodes() :2282* ensures next compression will not use repcodes from previous block.2283* Note : only works with regular variant;2284* do not use with extDict variant ! */2285void ZSTD_invalidateRepCodes(ZSTD_CCtx* cctx) {2286int i;2287for (i=0; i<ZSTD_REP_NUM; i++) cctx->blockState.prevCBlock->rep[i] = 0;2288assert(!ZSTD_window_hasExtDict(cctx->blockState.matchState.window));2289}22902291/* These are the approximate sizes for each strategy past which copying the2292* dictionary tables into the working context is faster than using them2293* in-place.2294*/2295static const size_t attachDictSizeCutoffs[ZSTD_STRATEGY_MAX+1] = {22968 KB, /* unused */22978 KB, /* ZSTD_fast */229816 KB, /* ZSTD_dfast */229932 KB, /* ZSTD_greedy */230032 KB, /* ZSTD_lazy */230132 KB, /* ZSTD_lazy2 */230232 KB, /* ZSTD_btlazy2 */230332 KB, /* ZSTD_btopt */23048 KB, /* ZSTD_btultra */23058 KB /* ZSTD_btultra2 */2306};23072308static int ZSTD_shouldAttachDict(const ZSTD_CDict* cdict,2309const ZSTD_CCtx_params* params,2310U64 pledgedSrcSize)2311{2312size_t cutoff = attachDictSizeCutoffs[cdict->matchState.cParams.strategy];2313int const dedicatedDictSearch = cdict->matchState.dedicatedDictSearch;2314return dedicatedDictSearch2315|| ( ( pledgedSrcSize <= cutoff2316|| pledgedSrcSize == ZSTD_CONTENTSIZE_UNKNOWN2317|| params->attachDictPref == ZSTD_dictForceAttach )2318&& params->attachDictPref != ZSTD_dictForceCopy2319&& !params->forceWindow ); /* dictMatchState isn't correctly2320* handled in _enforceMaxDist */2321}23222323static size_t2324ZSTD_resetCCtx_byAttachingCDict(ZSTD_CCtx* cctx,2325const ZSTD_CDict* cdict,2326ZSTD_CCtx_params params,2327U64 pledgedSrcSize,2328ZSTD_buffered_policy_e zbuff)2329{2330DEBUGLOG(4, "ZSTD_resetCCtx_byAttachingCDict() pledgedSrcSize=%llu",2331(unsigned long long)pledgedSrcSize);2332{2333ZSTD_compressionParameters adjusted_cdict_cParams = cdict->matchState.cParams;2334unsigned const windowLog = params.cParams.windowLog;2335assert(windowLog != 0);2336/* Resize working context table params for input only, since the dict2337* has its own tables. */2338/* pledgedSrcSize == 0 means 0! */23392340if (cdict->matchState.dedicatedDictSearch) {2341ZSTD_dedicatedDictSearch_revertCParams(&adjusted_cdict_cParams);2342}23432344params.cParams = ZSTD_adjustCParams_internal(adjusted_cdict_cParams, pledgedSrcSize,2345cdict->dictContentSize, ZSTD_cpm_attachDict,2346params.useRowMatchFinder);2347params.cParams.windowLog = windowLog;2348params.useRowMatchFinder = cdict->useRowMatchFinder; /* cdict overrides */2349FORWARD_IF_ERROR(ZSTD_resetCCtx_internal(cctx, ¶ms, pledgedSrcSize,2350/* loadedDictSize */ 0,2351ZSTDcrp_makeClean, zbuff), "");2352assert(cctx->appliedParams.cParams.strategy == adjusted_cdict_cParams.strategy);2353}23542355{ const U32 cdictEnd = (U32)( cdict->matchState.window.nextSrc2356- cdict->matchState.window.base);2357const U32 cdictLen = cdictEnd - cdict->matchState.window.dictLimit;2358if (cdictLen == 0) {2359/* don't even attach dictionaries with no contents */2360DEBUGLOG(4, "skipping attaching empty dictionary");2361} else {2362DEBUGLOG(4, "attaching dictionary into context");2363cctx->blockState.matchState.dictMatchState = &cdict->matchState;23642365/* prep working match state so dict matches never have negative indices2366* when they are translated to the working context's index space. */2367if (cctx->blockState.matchState.window.dictLimit < cdictEnd) {2368cctx->blockState.matchState.window.nextSrc =2369cctx->blockState.matchState.window.base + cdictEnd;2370ZSTD_window_clear(&cctx->blockState.matchState.window);2371}2372/* loadedDictEnd is expressed within the referential of the active context */2373cctx->blockState.matchState.loadedDictEnd = cctx->blockState.matchState.window.dictLimit;2374} }23752376cctx->dictID = cdict->dictID;2377cctx->dictContentSize = cdict->dictContentSize;23782379/* copy block state */2380ZSTD_memcpy(cctx->blockState.prevCBlock, &cdict->cBlockState, sizeof(cdict->cBlockState));23812382return 0;2383}23842385static void ZSTD_copyCDictTableIntoCCtx(U32* dst, U32 const* src, size_t tableSize,2386ZSTD_compressionParameters const* cParams) {2387if (ZSTD_CDictIndicesAreTagged(cParams)){2388/* Remove tags from the CDict table if they are present.2389* See docs on "short cache" in zstd_compress_internal.h for context. */2390size_t i;2391for (i = 0; i < tableSize; i++) {2392U32 const taggedIndex = src[i];2393U32 const index = taggedIndex >> ZSTD_SHORT_CACHE_TAG_BITS;2394dst[i] = index;2395}2396} else {2397ZSTD_memcpy(dst, src, tableSize * sizeof(U32));2398}2399}24002401static size_t ZSTD_resetCCtx_byCopyingCDict(ZSTD_CCtx* cctx,2402const ZSTD_CDict* cdict,2403ZSTD_CCtx_params params,2404U64 pledgedSrcSize,2405ZSTD_buffered_policy_e zbuff)2406{2407const ZSTD_compressionParameters *cdict_cParams = &cdict->matchState.cParams;24082409assert(!cdict->matchState.dedicatedDictSearch);2410DEBUGLOG(4, "ZSTD_resetCCtx_byCopyingCDict() pledgedSrcSize=%llu",2411(unsigned long long)pledgedSrcSize);24122413{ unsigned const windowLog = params.cParams.windowLog;2414assert(windowLog != 0);2415/* Copy only compression parameters related to tables. */2416params.cParams = *cdict_cParams;2417params.cParams.windowLog = windowLog;2418params.useRowMatchFinder = cdict->useRowMatchFinder;2419FORWARD_IF_ERROR(ZSTD_resetCCtx_internal(cctx, ¶ms, pledgedSrcSize,2420/* loadedDictSize */ 0,2421ZSTDcrp_leaveDirty, zbuff), "");2422assert(cctx->appliedParams.cParams.strategy == cdict_cParams->strategy);2423assert(cctx->appliedParams.cParams.hashLog == cdict_cParams->hashLog);2424assert(cctx->appliedParams.cParams.chainLog == cdict_cParams->chainLog);2425}24262427ZSTD_cwksp_mark_tables_dirty(&cctx->workspace);2428assert(params.useRowMatchFinder != ZSTD_ps_auto);24292430/* copy tables */2431{ size_t const chainSize = ZSTD_allocateChainTable(cdict_cParams->strategy, cdict->useRowMatchFinder, 0 /* DDS guaranteed disabled */)2432? ((size_t)1 << cdict_cParams->chainLog)2433: 0;2434size_t const hSize = (size_t)1 << cdict_cParams->hashLog;24352436ZSTD_copyCDictTableIntoCCtx(cctx->blockState.matchState.hashTable,2437cdict->matchState.hashTable,2438hSize, cdict_cParams);24392440/* Do not copy cdict's chainTable if cctx has parameters such that it would not use chainTable */2441if (ZSTD_allocateChainTable(cctx->appliedParams.cParams.strategy, cctx->appliedParams.useRowMatchFinder, 0 /* forDDSDict */)) {2442ZSTD_copyCDictTableIntoCCtx(cctx->blockState.matchState.chainTable,2443cdict->matchState.chainTable,2444chainSize, cdict_cParams);2445}2446/* copy tag table */2447if (ZSTD_rowMatchFinderUsed(cdict_cParams->strategy, cdict->useRowMatchFinder)) {2448size_t const tagTableSize = hSize;2449ZSTD_memcpy(cctx->blockState.matchState.tagTable,2450cdict->matchState.tagTable,2451tagTableSize);2452cctx->blockState.matchState.hashSalt = cdict->matchState.hashSalt;2453}2454}24552456/* Zero the hashTable3, since the cdict never fills it */2457assert(cctx->blockState.matchState.hashLog3 <= 31);2458{ U32 const h3log = cctx->blockState.matchState.hashLog3;2459size_t const h3Size = h3log ? ((size_t)1 << h3log) : 0;2460assert(cdict->matchState.hashLog3 == 0);2461ZSTD_memset(cctx->blockState.matchState.hashTable3, 0, h3Size * sizeof(U32));2462}24632464ZSTD_cwksp_mark_tables_clean(&cctx->workspace);24652466/* copy dictionary offsets */2467{ ZSTD_MatchState_t const* srcMatchState = &cdict->matchState;2468ZSTD_MatchState_t* dstMatchState = &cctx->blockState.matchState;2469dstMatchState->window = srcMatchState->window;2470dstMatchState->nextToUpdate = srcMatchState->nextToUpdate;2471dstMatchState->loadedDictEnd= srcMatchState->loadedDictEnd;2472}24732474cctx->dictID = cdict->dictID;2475cctx->dictContentSize = cdict->dictContentSize;24762477/* copy block state */2478ZSTD_memcpy(cctx->blockState.prevCBlock, &cdict->cBlockState, sizeof(cdict->cBlockState));24792480return 0;2481}24822483/* We have a choice between copying the dictionary context into the working2484* context, or referencing the dictionary context from the working context2485* in-place. We decide here which strategy to use. */2486static size_t ZSTD_resetCCtx_usingCDict(ZSTD_CCtx* cctx,2487const ZSTD_CDict* cdict,2488const ZSTD_CCtx_params* params,2489U64 pledgedSrcSize,2490ZSTD_buffered_policy_e zbuff)2491{24922493DEBUGLOG(4, "ZSTD_resetCCtx_usingCDict (pledgedSrcSize=%u)",2494(unsigned)pledgedSrcSize);24952496if (ZSTD_shouldAttachDict(cdict, params, pledgedSrcSize)) {2497return ZSTD_resetCCtx_byAttachingCDict(2498cctx, cdict, *params, pledgedSrcSize, zbuff);2499} else {2500return ZSTD_resetCCtx_byCopyingCDict(2501cctx, cdict, *params, pledgedSrcSize, zbuff);2502}2503}25042505/*! ZSTD_copyCCtx_internal() :2506* Duplicate an existing context `srcCCtx` into another one `dstCCtx`.2507* Only works during stage ZSTDcs_init (i.e. after creation, but before first call to ZSTD_compressContinue()).2508* The "context", in this case, refers to the hash and chain tables,2509* entropy tables, and dictionary references.2510* `windowLog` value is enforced if != 0, otherwise value is copied from srcCCtx.2511* @return : 0, or an error code */2512static size_t ZSTD_copyCCtx_internal(ZSTD_CCtx* dstCCtx,2513const ZSTD_CCtx* srcCCtx,2514ZSTD_frameParameters fParams,2515U64 pledgedSrcSize,2516ZSTD_buffered_policy_e zbuff)2517{2518RETURN_ERROR_IF(srcCCtx->stage!=ZSTDcs_init, stage_wrong,2519"Can't copy a ctx that's not in init stage.");2520DEBUGLOG(5, "ZSTD_copyCCtx_internal");2521ZSTD_memcpy(&dstCCtx->customMem, &srcCCtx->customMem, sizeof(ZSTD_customMem));2522{ ZSTD_CCtx_params params = dstCCtx->requestedParams;2523/* Copy only compression parameters related to tables. */2524params.cParams = srcCCtx->appliedParams.cParams;2525assert(srcCCtx->appliedParams.useRowMatchFinder != ZSTD_ps_auto);2526assert(srcCCtx->appliedParams.postBlockSplitter != ZSTD_ps_auto);2527assert(srcCCtx->appliedParams.ldmParams.enableLdm != ZSTD_ps_auto);2528params.useRowMatchFinder = srcCCtx->appliedParams.useRowMatchFinder;2529params.postBlockSplitter = srcCCtx->appliedParams.postBlockSplitter;2530params.ldmParams = srcCCtx->appliedParams.ldmParams;2531params.fParams = fParams;2532params.maxBlockSize = srcCCtx->appliedParams.maxBlockSize;2533ZSTD_resetCCtx_internal(dstCCtx, ¶ms, pledgedSrcSize,2534/* loadedDictSize */ 0,2535ZSTDcrp_leaveDirty, zbuff);2536assert(dstCCtx->appliedParams.cParams.windowLog == srcCCtx->appliedParams.cParams.windowLog);2537assert(dstCCtx->appliedParams.cParams.strategy == srcCCtx->appliedParams.cParams.strategy);2538assert(dstCCtx->appliedParams.cParams.hashLog == srcCCtx->appliedParams.cParams.hashLog);2539assert(dstCCtx->appliedParams.cParams.chainLog == srcCCtx->appliedParams.cParams.chainLog);2540assert(dstCCtx->blockState.matchState.hashLog3 == srcCCtx->blockState.matchState.hashLog3);2541}25422543ZSTD_cwksp_mark_tables_dirty(&dstCCtx->workspace);25442545/* copy tables */2546{ size_t const chainSize = ZSTD_allocateChainTable(srcCCtx->appliedParams.cParams.strategy,2547srcCCtx->appliedParams.useRowMatchFinder,25480 /* forDDSDict */)2549? ((size_t)1 << srcCCtx->appliedParams.cParams.chainLog)2550: 0;2551size_t const hSize = (size_t)1 << srcCCtx->appliedParams.cParams.hashLog;2552U32 const h3log = srcCCtx->blockState.matchState.hashLog3;2553size_t const h3Size = h3log ? ((size_t)1 << h3log) : 0;25542555ZSTD_memcpy(dstCCtx->blockState.matchState.hashTable,2556srcCCtx->blockState.matchState.hashTable,2557hSize * sizeof(U32));2558ZSTD_memcpy(dstCCtx->blockState.matchState.chainTable,2559srcCCtx->blockState.matchState.chainTable,2560chainSize * sizeof(U32));2561ZSTD_memcpy(dstCCtx->blockState.matchState.hashTable3,2562srcCCtx->blockState.matchState.hashTable3,2563h3Size * sizeof(U32));2564}25652566ZSTD_cwksp_mark_tables_clean(&dstCCtx->workspace);25672568/* copy dictionary offsets */2569{2570const ZSTD_MatchState_t* srcMatchState = &srcCCtx->blockState.matchState;2571ZSTD_MatchState_t* dstMatchState = &dstCCtx->blockState.matchState;2572dstMatchState->window = srcMatchState->window;2573dstMatchState->nextToUpdate = srcMatchState->nextToUpdate;2574dstMatchState->loadedDictEnd= srcMatchState->loadedDictEnd;2575}2576dstCCtx->dictID = srcCCtx->dictID;2577dstCCtx->dictContentSize = srcCCtx->dictContentSize;25782579/* copy block state */2580ZSTD_memcpy(dstCCtx->blockState.prevCBlock, srcCCtx->blockState.prevCBlock, sizeof(*srcCCtx->blockState.prevCBlock));25812582return 0;2583}25842585/*! ZSTD_copyCCtx() :2586* Duplicate an existing context `srcCCtx` into another one `dstCCtx`.2587* Only works during stage ZSTDcs_init (i.e. after creation, but before first call to ZSTD_compressContinue()).2588* pledgedSrcSize==0 means "unknown".2589* @return : 0, or an error code */2590size_t ZSTD_copyCCtx(ZSTD_CCtx* dstCCtx, const ZSTD_CCtx* srcCCtx, unsigned long long pledgedSrcSize)2591{2592ZSTD_frameParameters fParams = { 1 /*content*/, 0 /*checksum*/, 0 /*noDictID*/ };2593ZSTD_buffered_policy_e const zbuff = srcCCtx->bufferedPolicy;2594ZSTD_STATIC_ASSERT((U32)ZSTDb_buffered==1);2595if (pledgedSrcSize==0) pledgedSrcSize = ZSTD_CONTENTSIZE_UNKNOWN;2596fParams.contentSizeFlag = (pledgedSrcSize != ZSTD_CONTENTSIZE_UNKNOWN);25972598return ZSTD_copyCCtx_internal(dstCCtx, srcCCtx,2599fParams, pledgedSrcSize,2600zbuff);2601}260226032604#define ZSTD_ROWSIZE 162605/*! ZSTD_reduceTable() :2606* reduce table indexes by `reducerValue`, or squash to zero.2607* PreserveMark preserves "unsorted mark" for btlazy2 strategy.2608* It must be set to a clear 0/1 value, to remove branch during inlining.2609* Presume table size is a multiple of ZSTD_ROWSIZE2610* to help auto-vectorization */2611FORCE_INLINE_TEMPLATE void2612ZSTD_reduceTable_internal (U32* const table, U32 const size, U32 const reducerValue, int const preserveMark)2613{2614int const nbRows = (int)size / ZSTD_ROWSIZE;2615int cellNb = 0;2616int rowNb;2617/* Protect special index values < ZSTD_WINDOW_START_INDEX. */2618U32 const reducerThreshold = reducerValue + ZSTD_WINDOW_START_INDEX;2619assert((size & (ZSTD_ROWSIZE-1)) == 0); /* multiple of ZSTD_ROWSIZE */2620assert(size < (1U<<31)); /* can be cast to int */26212622#if ZSTD_MEMORY_SANITIZER && !defined (ZSTD_MSAN_DONT_POISON_WORKSPACE)2623/* To validate that the table reuse logic is sound, and that we don't2624* access table space that we haven't cleaned, we re-"poison" the table2625* space every time we mark it dirty.2626*2627* This function however is intended to operate on those dirty tables and2628* re-clean them. So when this function is used correctly, we can unpoison2629* the memory it operated on. This introduces a blind spot though, since2630* if we now try to operate on __actually__ poisoned memory, we will not2631* detect that. */2632__msan_unpoison(table, size * sizeof(U32));2633#endif26342635for (rowNb=0 ; rowNb < nbRows ; rowNb++) {2636int column;2637for (column=0; column<ZSTD_ROWSIZE; column++) {2638U32 newVal;2639if (preserveMark && table[cellNb] == ZSTD_DUBT_UNSORTED_MARK) {2640/* This write is pointless, but is required(?) for the compiler2641* to auto-vectorize the loop. */2642newVal = ZSTD_DUBT_UNSORTED_MARK;2643} else if (table[cellNb] < reducerThreshold) {2644newVal = 0;2645} else {2646newVal = table[cellNb] - reducerValue;2647}2648table[cellNb] = newVal;2649cellNb++;2650} }2651}26522653static void ZSTD_reduceTable(U32* const table, U32 const size, U32 const reducerValue)2654{2655ZSTD_reduceTable_internal(table, size, reducerValue, 0);2656}26572658static void ZSTD_reduceTable_btlazy2(U32* const table, U32 const size, U32 const reducerValue)2659{2660ZSTD_reduceTable_internal(table, size, reducerValue, 1);2661}26622663/*! ZSTD_reduceIndex() :2664* rescale all indexes to avoid future overflow (indexes are U32) */2665static void ZSTD_reduceIndex (ZSTD_MatchState_t* ms, ZSTD_CCtx_params const* params, const U32 reducerValue)2666{2667{ U32 const hSize = (U32)1 << params->cParams.hashLog;2668ZSTD_reduceTable(ms->hashTable, hSize, reducerValue);2669}26702671if (ZSTD_allocateChainTable(params->cParams.strategy, params->useRowMatchFinder, (U32)ms->dedicatedDictSearch)) {2672U32 const chainSize = (U32)1 << params->cParams.chainLog;2673if (params->cParams.strategy == ZSTD_btlazy2)2674ZSTD_reduceTable_btlazy2(ms->chainTable, chainSize, reducerValue);2675else2676ZSTD_reduceTable(ms->chainTable, chainSize, reducerValue);2677}26782679if (ms->hashLog3) {2680U32 const h3Size = (U32)1 << ms->hashLog3;2681ZSTD_reduceTable(ms->hashTable3, h3Size, reducerValue);2682}2683}268426852686/*-*******************************************************2687* Block entropic compression2688*********************************************************/26892690/* See doc/zstd_compression_format.md for detailed format description */26912692int ZSTD_seqToCodes(const SeqStore_t* seqStorePtr)2693{2694const SeqDef* const sequences = seqStorePtr->sequencesStart;2695BYTE* const llCodeTable = seqStorePtr->llCode;2696BYTE* const ofCodeTable = seqStorePtr->ofCode;2697BYTE* const mlCodeTable = seqStorePtr->mlCode;2698U32 const nbSeq = (U32)(seqStorePtr->sequences - seqStorePtr->sequencesStart);2699U32 u;2700int longOffsets = 0;2701assert(nbSeq <= seqStorePtr->maxNbSeq);2702for (u=0; u<nbSeq; u++) {2703U32 const llv = sequences[u].litLength;2704U32 const ofCode = ZSTD_highbit32(sequences[u].offBase);2705U32 const mlv = sequences[u].mlBase;2706llCodeTable[u] = (BYTE)ZSTD_LLcode(llv);2707ofCodeTable[u] = (BYTE)ofCode;2708mlCodeTable[u] = (BYTE)ZSTD_MLcode(mlv);2709assert(!(MEM_64bits() && ofCode >= STREAM_ACCUMULATOR_MIN));2710if (MEM_32bits() && ofCode >= STREAM_ACCUMULATOR_MIN)2711longOffsets = 1;2712}2713if (seqStorePtr->longLengthType==ZSTD_llt_literalLength)2714llCodeTable[seqStorePtr->longLengthPos] = MaxLL;2715if (seqStorePtr->longLengthType==ZSTD_llt_matchLength)2716mlCodeTable[seqStorePtr->longLengthPos] = MaxML;2717return longOffsets;2718}27192720/* ZSTD_useTargetCBlockSize():2721* Returns if target compressed block size param is being used.2722* If used, compression will do best effort to make a compressed block size to be around targetCBlockSize.2723* Returns 1 if true, 0 otherwise. */2724static int ZSTD_useTargetCBlockSize(const ZSTD_CCtx_params* cctxParams)2725{2726DEBUGLOG(5, "ZSTD_useTargetCBlockSize (targetCBlockSize=%zu)", cctxParams->targetCBlockSize);2727return (cctxParams->targetCBlockSize != 0);2728}27292730/* ZSTD_blockSplitterEnabled():2731* Returns if block splitting param is being used2732* If used, compression will do best effort to split a block in order to improve compression ratio.2733* At the time this function is called, the parameter must be finalized.2734* Returns 1 if true, 0 otherwise. */2735static int ZSTD_blockSplitterEnabled(ZSTD_CCtx_params* cctxParams)2736{2737DEBUGLOG(5, "ZSTD_blockSplitterEnabled (postBlockSplitter=%d)", cctxParams->postBlockSplitter);2738assert(cctxParams->postBlockSplitter != ZSTD_ps_auto);2739return (cctxParams->postBlockSplitter == ZSTD_ps_enable);2740}27412742/* Type returned by ZSTD_buildSequencesStatistics containing finalized symbol encoding types2743* and size of the sequences statistics2744*/2745typedef struct {2746U32 LLtype;2747U32 Offtype;2748U32 MLtype;2749size_t size;2750size_t lastCountSize; /* Accounts for bug in 1.3.4. More detail in ZSTD_entropyCompressSeqStore_internal() */2751int longOffsets;2752} ZSTD_symbolEncodingTypeStats_t;27532754/* ZSTD_buildSequencesStatistics():2755* Returns a ZSTD_symbolEncodingTypeStats_t, or a zstd error code in the `size` field.2756* Modifies `nextEntropy` to have the appropriate values as a side effect.2757* nbSeq must be greater than 0.2758*2759* entropyWkspSize must be of size at least ENTROPY_WORKSPACE_SIZE - (MaxSeq + 1)*sizeof(U32)2760*/2761static ZSTD_symbolEncodingTypeStats_t2762ZSTD_buildSequencesStatistics(2763const SeqStore_t* seqStorePtr, size_t nbSeq,2764const ZSTD_fseCTables_t* prevEntropy, ZSTD_fseCTables_t* nextEntropy,2765BYTE* dst, const BYTE* const dstEnd,2766ZSTD_strategy strategy, unsigned* countWorkspace,2767void* entropyWorkspace, size_t entropyWkspSize)2768{2769BYTE* const ostart = dst;2770const BYTE* const oend = dstEnd;2771BYTE* op = ostart;2772FSE_CTable* CTable_LitLength = nextEntropy->litlengthCTable;2773FSE_CTable* CTable_OffsetBits = nextEntropy->offcodeCTable;2774FSE_CTable* CTable_MatchLength = nextEntropy->matchlengthCTable;2775const BYTE* const ofCodeTable = seqStorePtr->ofCode;2776const BYTE* const llCodeTable = seqStorePtr->llCode;2777const BYTE* const mlCodeTable = seqStorePtr->mlCode;2778ZSTD_symbolEncodingTypeStats_t stats;27792780stats.lastCountSize = 0;2781/* convert length/distances into codes */2782stats.longOffsets = ZSTD_seqToCodes(seqStorePtr);2783assert(op <= oend);2784assert(nbSeq != 0); /* ZSTD_selectEncodingType() divides by nbSeq */2785/* build CTable for Literal Lengths */2786{ unsigned max = MaxLL;2787size_t const mostFrequent = HIST_countFast_wksp(countWorkspace, &max, llCodeTable, nbSeq, entropyWorkspace, entropyWkspSize); /* can't fail */2788DEBUGLOG(5, "Building LL table");2789nextEntropy->litlength_repeatMode = prevEntropy->litlength_repeatMode;2790stats.LLtype = ZSTD_selectEncodingType(&nextEntropy->litlength_repeatMode,2791countWorkspace, max, mostFrequent, nbSeq,2792LLFSELog, prevEntropy->litlengthCTable,2793LL_defaultNorm, LL_defaultNormLog,2794ZSTD_defaultAllowed, strategy);2795assert(set_basic < set_compressed && set_rle < set_compressed);2796assert(!(stats.LLtype < set_compressed && nextEntropy->litlength_repeatMode != FSE_repeat_none)); /* We don't copy tables */2797{ size_t const countSize = ZSTD_buildCTable(2798op, (size_t)(oend - op),2799CTable_LitLength, LLFSELog, (SymbolEncodingType_e)stats.LLtype,2800countWorkspace, max, llCodeTable, nbSeq,2801LL_defaultNorm, LL_defaultNormLog, MaxLL,2802prevEntropy->litlengthCTable,2803sizeof(prevEntropy->litlengthCTable),2804entropyWorkspace, entropyWkspSize);2805if (ZSTD_isError(countSize)) {2806DEBUGLOG(3, "ZSTD_buildCTable for LitLens failed");2807stats.size = countSize;2808return stats;2809}2810if (stats.LLtype == set_compressed)2811stats.lastCountSize = countSize;2812op += countSize;2813assert(op <= oend);2814} }2815/* build CTable for Offsets */2816{ unsigned max = MaxOff;2817size_t const mostFrequent = HIST_countFast_wksp(2818countWorkspace, &max, ofCodeTable, nbSeq, entropyWorkspace, entropyWkspSize); /* can't fail */2819/* We can only use the basic table if max <= DefaultMaxOff, otherwise the offsets are too large */2820ZSTD_DefaultPolicy_e const defaultPolicy = (max <= DefaultMaxOff) ? ZSTD_defaultAllowed : ZSTD_defaultDisallowed;2821DEBUGLOG(5, "Building OF table");2822nextEntropy->offcode_repeatMode = prevEntropy->offcode_repeatMode;2823stats.Offtype = ZSTD_selectEncodingType(&nextEntropy->offcode_repeatMode,2824countWorkspace, max, mostFrequent, nbSeq,2825OffFSELog, prevEntropy->offcodeCTable,2826OF_defaultNorm, OF_defaultNormLog,2827defaultPolicy, strategy);2828assert(!(stats.Offtype < set_compressed && nextEntropy->offcode_repeatMode != FSE_repeat_none)); /* We don't copy tables */2829{ size_t const countSize = ZSTD_buildCTable(2830op, (size_t)(oend - op),2831CTable_OffsetBits, OffFSELog, (SymbolEncodingType_e)stats.Offtype,2832countWorkspace, max, ofCodeTable, nbSeq,2833OF_defaultNorm, OF_defaultNormLog, DefaultMaxOff,2834prevEntropy->offcodeCTable,2835sizeof(prevEntropy->offcodeCTable),2836entropyWorkspace, entropyWkspSize);2837if (ZSTD_isError(countSize)) {2838DEBUGLOG(3, "ZSTD_buildCTable for Offsets failed");2839stats.size = countSize;2840return stats;2841}2842if (stats.Offtype == set_compressed)2843stats.lastCountSize = countSize;2844op += countSize;2845assert(op <= oend);2846} }2847/* build CTable for MatchLengths */2848{ unsigned max = MaxML;2849size_t const mostFrequent = HIST_countFast_wksp(2850countWorkspace, &max, mlCodeTable, nbSeq, entropyWorkspace, entropyWkspSize); /* can't fail */2851DEBUGLOG(5, "Building ML table (remaining space : %i)", (int)(oend-op));2852nextEntropy->matchlength_repeatMode = prevEntropy->matchlength_repeatMode;2853stats.MLtype = ZSTD_selectEncodingType(&nextEntropy->matchlength_repeatMode,2854countWorkspace, max, mostFrequent, nbSeq,2855MLFSELog, prevEntropy->matchlengthCTable,2856ML_defaultNorm, ML_defaultNormLog,2857ZSTD_defaultAllowed, strategy);2858assert(!(stats.MLtype < set_compressed && nextEntropy->matchlength_repeatMode != FSE_repeat_none)); /* We don't copy tables */2859{ size_t const countSize = ZSTD_buildCTable(2860op, (size_t)(oend - op),2861CTable_MatchLength, MLFSELog, (SymbolEncodingType_e)stats.MLtype,2862countWorkspace, max, mlCodeTable, nbSeq,2863ML_defaultNorm, ML_defaultNormLog, MaxML,2864prevEntropy->matchlengthCTable,2865sizeof(prevEntropy->matchlengthCTable),2866entropyWorkspace, entropyWkspSize);2867if (ZSTD_isError(countSize)) {2868DEBUGLOG(3, "ZSTD_buildCTable for MatchLengths failed");2869stats.size = countSize;2870return stats;2871}2872if (stats.MLtype == set_compressed)2873stats.lastCountSize = countSize;2874op += countSize;2875assert(op <= oend);2876} }2877stats.size = (size_t)(op-ostart);2878return stats;2879}28802881/* ZSTD_entropyCompressSeqStore_internal():2882* compresses both literals and sequences2883* Returns compressed size of block, or a zstd error.2884*/2885#define SUSPECT_UNCOMPRESSIBLE_LITERAL_RATIO 202886MEM_STATIC size_t2887ZSTD_entropyCompressSeqStore_internal(2888void* dst, size_t dstCapacity,2889const void* literals, size_t litSize,2890const SeqStore_t* seqStorePtr,2891const ZSTD_entropyCTables_t* prevEntropy,2892ZSTD_entropyCTables_t* nextEntropy,2893const ZSTD_CCtx_params* cctxParams,2894void* entropyWorkspace, size_t entropyWkspSize,2895const int bmi2)2896{2897ZSTD_strategy const strategy = cctxParams->cParams.strategy;2898unsigned* count = (unsigned*)entropyWorkspace;2899FSE_CTable* CTable_LitLength = nextEntropy->fse.litlengthCTable;2900FSE_CTable* CTable_OffsetBits = nextEntropy->fse.offcodeCTable;2901FSE_CTable* CTable_MatchLength = nextEntropy->fse.matchlengthCTable;2902const SeqDef* const sequences = seqStorePtr->sequencesStart;2903const size_t nbSeq = (size_t)(seqStorePtr->sequences - seqStorePtr->sequencesStart);2904const BYTE* const ofCodeTable = seqStorePtr->ofCode;2905const BYTE* const llCodeTable = seqStorePtr->llCode;2906const BYTE* const mlCodeTable = seqStorePtr->mlCode;2907BYTE* const ostart = (BYTE*)dst;2908BYTE* const oend = ostart + dstCapacity;2909BYTE* op = ostart;2910size_t lastCountSize;2911int longOffsets = 0;29122913entropyWorkspace = count + (MaxSeq + 1);2914entropyWkspSize -= (MaxSeq + 1) * sizeof(*count);29152916DEBUGLOG(5, "ZSTD_entropyCompressSeqStore_internal (nbSeq=%zu, dstCapacity=%zu)", nbSeq, dstCapacity);2917ZSTD_STATIC_ASSERT(HUF_WORKSPACE_SIZE >= (1<<MAX(MLFSELog,LLFSELog)));2918assert(entropyWkspSize >= HUF_WORKSPACE_SIZE);29192920/* Compress literals */2921{ size_t const numSequences = (size_t)(seqStorePtr->sequences - seqStorePtr->sequencesStart);2922/* Base suspicion of uncompressibility on ratio of literals to sequences */2923int const suspectUncompressible = (numSequences == 0) || (litSize / numSequences >= SUSPECT_UNCOMPRESSIBLE_LITERAL_RATIO);29242925size_t const cSize = ZSTD_compressLiterals(2926op, dstCapacity,2927literals, litSize,2928entropyWorkspace, entropyWkspSize,2929&prevEntropy->huf, &nextEntropy->huf,2930cctxParams->cParams.strategy,2931ZSTD_literalsCompressionIsDisabled(cctxParams),2932suspectUncompressible, bmi2);2933FORWARD_IF_ERROR(cSize, "ZSTD_compressLiterals failed");2934assert(cSize <= dstCapacity);2935op += cSize;2936}29372938/* Sequences Header */2939RETURN_ERROR_IF((oend-op) < 3 /*max nbSeq Size*/ + 1 /*seqHead*/,2940dstSize_tooSmall, "Can't fit seq hdr in output buf!");2941if (nbSeq < 128) {2942*op++ = (BYTE)nbSeq;2943} else if (nbSeq < LONGNBSEQ) {2944op[0] = (BYTE)((nbSeq>>8) + 0x80);2945op[1] = (BYTE)nbSeq;2946op+=2;2947} else {2948op[0]=0xFF;2949MEM_writeLE16(op+1, (U16)(nbSeq - LONGNBSEQ));2950op+=3;2951}2952assert(op <= oend);2953if (nbSeq==0) {2954/* Copy the old tables over as if we repeated them */2955ZSTD_memcpy(&nextEntropy->fse, &prevEntropy->fse, sizeof(prevEntropy->fse));2956return (size_t)(op - ostart);2957}2958{ BYTE* const seqHead = op++;2959/* build stats for sequences */2960const ZSTD_symbolEncodingTypeStats_t stats =2961ZSTD_buildSequencesStatistics(seqStorePtr, nbSeq,2962&prevEntropy->fse, &nextEntropy->fse,2963op, oend,2964strategy, count,2965entropyWorkspace, entropyWkspSize);2966FORWARD_IF_ERROR(stats.size, "ZSTD_buildSequencesStatistics failed!");2967*seqHead = (BYTE)((stats.LLtype<<6) + (stats.Offtype<<4) + (stats.MLtype<<2));2968lastCountSize = stats.lastCountSize;2969op += stats.size;2970longOffsets = stats.longOffsets;2971}29722973{ size_t const bitstreamSize = ZSTD_encodeSequences(2974op, (size_t)(oend - op),2975CTable_MatchLength, mlCodeTable,2976CTable_OffsetBits, ofCodeTable,2977CTable_LitLength, llCodeTable,2978sequences, nbSeq,2979longOffsets, bmi2);2980FORWARD_IF_ERROR(bitstreamSize, "ZSTD_encodeSequences failed");2981op += bitstreamSize;2982assert(op <= oend);2983/* zstd versions <= 1.3.4 mistakenly report corruption when2984* FSE_readNCount() receives a buffer < 4 bytes.2985* Fixed by https://github.com/facebook/zstd/pull/1146.2986* This can happen when the last set_compressed table present is 22987* bytes and the bitstream is only one byte.2988* In this exceedingly rare case, we will simply emit an uncompressed2989* block, since it isn't worth optimizing.2990*/2991if (lastCountSize && (lastCountSize + bitstreamSize) < 4) {2992/* lastCountSize >= 2 && bitstreamSize > 0 ==> lastCountSize == 3 */2993assert(lastCountSize + bitstreamSize == 3);2994DEBUGLOG(5, "Avoiding bug in zstd decoder in versions <= 1.3.4 by "2995"emitting an uncompressed block.");2996return 0;2997}2998}29993000DEBUGLOG(5, "compressed block size : %u", (unsigned)(op - ostart));3001return (size_t)(op - ostart);3002}30033004static size_t3005ZSTD_entropyCompressSeqStore_wExtLitBuffer(3006void* dst, size_t dstCapacity,3007const void* literals, size_t litSize,3008size_t blockSize,3009const SeqStore_t* seqStorePtr,3010const ZSTD_entropyCTables_t* prevEntropy,3011ZSTD_entropyCTables_t* nextEntropy,3012const ZSTD_CCtx_params* cctxParams,3013void* entropyWorkspace, size_t entropyWkspSize,3014int bmi2)3015{3016size_t const cSize = ZSTD_entropyCompressSeqStore_internal(3017dst, dstCapacity,3018literals, litSize,3019seqStorePtr, prevEntropy, nextEntropy, cctxParams,3020entropyWorkspace, entropyWkspSize, bmi2);3021if (cSize == 0) return 0;3022/* When srcSize <= dstCapacity, there is enough space to write a raw uncompressed block.3023* Since we ran out of space, block must be not compressible, so fall back to raw uncompressed block.3024*/3025if ((cSize == ERROR(dstSize_tooSmall)) & (blockSize <= dstCapacity)) {3026DEBUGLOG(4, "not enough dstCapacity (%zu) for ZSTD_entropyCompressSeqStore_internal()=> do not compress block", dstCapacity);3027return 0; /* block not compressed */3028}3029FORWARD_IF_ERROR(cSize, "ZSTD_entropyCompressSeqStore_internal failed");30303031/* Check compressibility */3032{ size_t const maxCSize = blockSize - ZSTD_minGain(blockSize, cctxParams->cParams.strategy);3033if (cSize >= maxCSize) return 0; /* block not compressed */3034}3035DEBUGLOG(5, "ZSTD_entropyCompressSeqStore() cSize: %zu", cSize);3036/* libzstd decoder before > v1.5.4 is not compatible with compressed blocks of size ZSTD_BLOCKSIZE_MAX exactly.3037* This restriction is indirectly already fulfilled by respecting ZSTD_minGain() condition above.3038*/3039assert(cSize < ZSTD_BLOCKSIZE_MAX);3040return cSize;3041}30423043static size_t3044ZSTD_entropyCompressSeqStore(3045const SeqStore_t* seqStorePtr,3046const ZSTD_entropyCTables_t* prevEntropy,3047ZSTD_entropyCTables_t* nextEntropy,3048const ZSTD_CCtx_params* cctxParams,3049void* dst, size_t dstCapacity,3050size_t srcSize,3051void* entropyWorkspace, size_t entropyWkspSize,3052int bmi2)3053{3054return ZSTD_entropyCompressSeqStore_wExtLitBuffer(3055dst, dstCapacity,3056seqStorePtr->litStart, (size_t)(seqStorePtr->lit - seqStorePtr->litStart),3057srcSize,3058seqStorePtr,3059prevEntropy, nextEntropy,3060cctxParams,3061entropyWorkspace, entropyWkspSize,3062bmi2);3063}30643065/* ZSTD_selectBlockCompressor() :3066* Not static, but internal use only (used by long distance matcher)3067* assumption : strat is a valid strategy */3068ZSTD_BlockCompressor_f ZSTD_selectBlockCompressor(ZSTD_strategy strat, ZSTD_ParamSwitch_e useRowMatchFinder, ZSTD_dictMode_e dictMode)3069{3070static const ZSTD_BlockCompressor_f blockCompressor[4][ZSTD_STRATEGY_MAX+1] = {3071{ ZSTD_compressBlock_fast /* default for 0 */,3072ZSTD_compressBlock_fast,3073ZSTD_COMPRESSBLOCK_DOUBLEFAST,3074ZSTD_COMPRESSBLOCK_GREEDY,3075ZSTD_COMPRESSBLOCK_LAZY,3076ZSTD_COMPRESSBLOCK_LAZY2,3077ZSTD_COMPRESSBLOCK_BTLAZY2,3078ZSTD_COMPRESSBLOCK_BTOPT,3079ZSTD_COMPRESSBLOCK_BTULTRA,3080ZSTD_COMPRESSBLOCK_BTULTRA23081},3082{ ZSTD_compressBlock_fast_extDict /* default for 0 */,3083ZSTD_compressBlock_fast_extDict,3084ZSTD_COMPRESSBLOCK_DOUBLEFAST_EXTDICT,3085ZSTD_COMPRESSBLOCK_GREEDY_EXTDICT,3086ZSTD_COMPRESSBLOCK_LAZY_EXTDICT,3087ZSTD_COMPRESSBLOCK_LAZY2_EXTDICT,3088ZSTD_COMPRESSBLOCK_BTLAZY2_EXTDICT,3089ZSTD_COMPRESSBLOCK_BTOPT_EXTDICT,3090ZSTD_COMPRESSBLOCK_BTULTRA_EXTDICT,3091ZSTD_COMPRESSBLOCK_BTULTRA_EXTDICT3092},3093{ ZSTD_compressBlock_fast_dictMatchState /* default for 0 */,3094ZSTD_compressBlock_fast_dictMatchState,3095ZSTD_COMPRESSBLOCK_DOUBLEFAST_DICTMATCHSTATE,3096ZSTD_COMPRESSBLOCK_GREEDY_DICTMATCHSTATE,3097ZSTD_COMPRESSBLOCK_LAZY_DICTMATCHSTATE,3098ZSTD_COMPRESSBLOCK_LAZY2_DICTMATCHSTATE,3099ZSTD_COMPRESSBLOCK_BTLAZY2_DICTMATCHSTATE,3100ZSTD_COMPRESSBLOCK_BTOPT_DICTMATCHSTATE,3101ZSTD_COMPRESSBLOCK_BTULTRA_DICTMATCHSTATE,3102ZSTD_COMPRESSBLOCK_BTULTRA_DICTMATCHSTATE3103},3104{ NULL /* default for 0 */,3105NULL,3106NULL,3107ZSTD_COMPRESSBLOCK_GREEDY_DEDICATEDDICTSEARCH,3108ZSTD_COMPRESSBLOCK_LAZY_DEDICATEDDICTSEARCH,3109ZSTD_COMPRESSBLOCK_LAZY2_DEDICATEDDICTSEARCH,3110NULL,3111NULL,3112NULL,3113NULL }3114};3115ZSTD_BlockCompressor_f selectedCompressor;3116ZSTD_STATIC_ASSERT((unsigned)ZSTD_fast == 1);31173118assert(ZSTD_cParam_withinBounds(ZSTD_c_strategy, (int)strat));3119DEBUGLOG(5, "Selected block compressor: dictMode=%d strat=%d rowMatchfinder=%d", (int)dictMode, (int)strat, (int)useRowMatchFinder);3120if (ZSTD_rowMatchFinderUsed(strat, useRowMatchFinder)) {3121static const ZSTD_BlockCompressor_f rowBasedBlockCompressors[4][3] = {3122{3123ZSTD_COMPRESSBLOCK_GREEDY_ROW,3124ZSTD_COMPRESSBLOCK_LAZY_ROW,3125ZSTD_COMPRESSBLOCK_LAZY2_ROW3126},3127{3128ZSTD_COMPRESSBLOCK_GREEDY_EXTDICT_ROW,3129ZSTD_COMPRESSBLOCK_LAZY_EXTDICT_ROW,3130ZSTD_COMPRESSBLOCK_LAZY2_EXTDICT_ROW3131},3132{3133ZSTD_COMPRESSBLOCK_GREEDY_DICTMATCHSTATE_ROW,3134ZSTD_COMPRESSBLOCK_LAZY_DICTMATCHSTATE_ROW,3135ZSTD_COMPRESSBLOCK_LAZY2_DICTMATCHSTATE_ROW3136},3137{3138ZSTD_COMPRESSBLOCK_GREEDY_DEDICATEDDICTSEARCH_ROW,3139ZSTD_COMPRESSBLOCK_LAZY_DEDICATEDDICTSEARCH_ROW,3140ZSTD_COMPRESSBLOCK_LAZY2_DEDICATEDDICTSEARCH_ROW3141}3142};3143DEBUGLOG(5, "Selecting a row-based matchfinder");3144assert(useRowMatchFinder != ZSTD_ps_auto);3145selectedCompressor = rowBasedBlockCompressors[(int)dictMode][(int)strat - (int)ZSTD_greedy];3146} else {3147selectedCompressor = blockCompressor[(int)dictMode][(int)strat];3148}3149assert(selectedCompressor != NULL);3150return selectedCompressor;3151}31523153static void ZSTD_storeLastLiterals(SeqStore_t* seqStorePtr,3154const BYTE* anchor, size_t lastLLSize)3155{3156ZSTD_memcpy(seqStorePtr->lit, anchor, lastLLSize);3157seqStorePtr->lit += lastLLSize;3158}31593160void ZSTD_resetSeqStore(SeqStore_t* ssPtr)3161{3162ssPtr->lit = ssPtr->litStart;3163ssPtr->sequences = ssPtr->sequencesStart;3164ssPtr->longLengthType = ZSTD_llt_none;3165}31663167/* ZSTD_postProcessSequenceProducerResult() :3168* Validates and post-processes sequences obtained through the external matchfinder API:3169* - Checks whether nbExternalSeqs represents an error condition.3170* - Appends a block delimiter to outSeqs if one is not already present.3171* See zstd.h for context regarding block delimiters.3172* Returns the number of sequences after post-processing, or an error code. */3173static size_t ZSTD_postProcessSequenceProducerResult(3174ZSTD_Sequence* outSeqs, size_t nbExternalSeqs, size_t outSeqsCapacity, size_t srcSize3175) {3176RETURN_ERROR_IF(3177nbExternalSeqs > outSeqsCapacity,3178sequenceProducer_failed,3179"External sequence producer returned error code %lu",3180(unsigned long)nbExternalSeqs3181);31823183RETURN_ERROR_IF(3184nbExternalSeqs == 0 && srcSize > 0,3185sequenceProducer_failed,3186"Got zero sequences from external sequence producer for a non-empty src buffer!"3187);31883189if (srcSize == 0) {3190ZSTD_memset(&outSeqs[0], 0, sizeof(ZSTD_Sequence));3191return 1;3192}31933194{3195ZSTD_Sequence const lastSeq = outSeqs[nbExternalSeqs - 1];31963197/* We can return early if lastSeq is already a block delimiter. */3198if (lastSeq.offset == 0 && lastSeq.matchLength == 0) {3199return nbExternalSeqs;3200}32013202/* This error condition is only possible if the external matchfinder3203* produced an invalid parse, by definition of ZSTD_sequenceBound(). */3204RETURN_ERROR_IF(3205nbExternalSeqs == outSeqsCapacity,3206sequenceProducer_failed,3207"nbExternalSeqs == outSeqsCapacity but lastSeq is not a block delimiter!"3208);32093210/* lastSeq is not a block delimiter, so we need to append one. */3211ZSTD_memset(&outSeqs[nbExternalSeqs], 0, sizeof(ZSTD_Sequence));3212return nbExternalSeqs + 1;3213}3214}32153216/* ZSTD_fastSequenceLengthSum() :3217* Returns sum(litLen) + sum(matchLen) + lastLits for *seqBuf*.3218* Similar to another function in zstd_compress.c (determine_blockSize),3219* except it doesn't check for a block delimiter to end summation.3220* Removing the early exit allows the compiler to auto-vectorize (https://godbolt.org/z/cY1cajz9P).3221* This function can be deleted and replaced by determine_blockSize after we resolve issue #3456. */3222static size_t ZSTD_fastSequenceLengthSum(ZSTD_Sequence const* seqBuf, size_t seqBufSize) {3223size_t matchLenSum, litLenSum, i;3224matchLenSum = 0;3225litLenSum = 0;3226for (i = 0; i < seqBufSize; i++) {3227litLenSum += seqBuf[i].litLength;3228matchLenSum += seqBuf[i].matchLength;3229}3230return litLenSum + matchLenSum;3231}32323233/**3234* Function to validate sequences produced by a block compressor.3235*/3236static void ZSTD_validateSeqStore(const SeqStore_t* seqStore, const ZSTD_compressionParameters* cParams)3237{3238#if DEBUGLEVEL >= 13239const SeqDef* seq = seqStore->sequencesStart;3240const SeqDef* const seqEnd = seqStore->sequences;3241size_t const matchLenLowerBound = cParams->minMatch == 3 ? 3 : 4;3242for (; seq < seqEnd; ++seq) {3243const ZSTD_SequenceLength seqLength = ZSTD_getSequenceLength(seqStore, seq);3244assert(seqLength.matchLength >= matchLenLowerBound);3245(void)seqLength;3246(void)matchLenLowerBound;3247}3248#else3249(void)seqStore;3250(void)cParams;3251#endif3252}32533254static size_t3255ZSTD_transferSequences_wBlockDelim(ZSTD_CCtx* cctx,3256ZSTD_SequencePosition* seqPos,3257const ZSTD_Sequence* const inSeqs, size_t inSeqsSize,3258const void* src, size_t blockSize,3259ZSTD_ParamSwitch_e externalRepSearch);32603261typedef enum { ZSTDbss_compress, ZSTDbss_noCompress } ZSTD_BuildSeqStore_e;32623263static size_t ZSTD_buildSeqStore(ZSTD_CCtx* zc, const void* src, size_t srcSize)3264{3265ZSTD_MatchState_t* const ms = &zc->blockState.matchState;3266DEBUGLOG(5, "ZSTD_buildSeqStore (srcSize=%zu)", srcSize);3267assert(srcSize <= ZSTD_BLOCKSIZE_MAX);3268/* Assert that we have correctly flushed the ctx params into the ms's copy */3269ZSTD_assertEqualCParams(zc->appliedParams.cParams, ms->cParams);3270/* TODO: See 3090. We reduced MIN_CBLOCK_SIZE from 3 to 2 so to compensate we are adding3271* additional 1. We need to revisit and change this logic to be more consistent */3272if (srcSize < MIN_CBLOCK_SIZE+ZSTD_blockHeaderSize+1+1) {3273if (zc->appliedParams.cParams.strategy >= ZSTD_btopt) {3274ZSTD_ldm_skipRawSeqStoreBytes(&zc->externSeqStore, srcSize);3275} else {3276ZSTD_ldm_skipSequences(&zc->externSeqStore, srcSize, zc->appliedParams.cParams.minMatch);3277}3278return ZSTDbss_noCompress; /* don't even attempt compression below a certain srcSize */3279}3280ZSTD_resetSeqStore(&(zc->seqStore));3281/* required for optimal parser to read stats from dictionary */3282ms->opt.symbolCosts = &zc->blockState.prevCBlock->entropy;3283/* tell the optimal parser how we expect to compress literals */3284ms->opt.literalCompressionMode = zc->appliedParams.literalCompressionMode;3285/* a gap between an attached dict and the current window is not safe,3286* they must remain adjacent,3287* and when that stops being the case, the dict must be unset */3288assert(ms->dictMatchState == NULL || ms->loadedDictEnd == ms->window.dictLimit);32893290/* limited update after a very long match */3291{ const BYTE* const base = ms->window.base;3292const BYTE* const istart = (const BYTE*)src;3293const U32 curr = (U32)(istart-base);3294if (sizeof(ptrdiff_t)==8) assert(istart - base < (ptrdiff_t)(U32)(-1)); /* ensure no overflow */3295if (curr > ms->nextToUpdate + 384)3296ms->nextToUpdate = curr - MIN(192, (U32)(curr - ms->nextToUpdate - 384));3297}32983299/* select and store sequences */3300{ ZSTD_dictMode_e const dictMode = ZSTD_matchState_dictMode(ms);3301size_t lastLLSize;3302{ int i;3303for (i = 0; i < ZSTD_REP_NUM; ++i)3304zc->blockState.nextCBlock->rep[i] = zc->blockState.prevCBlock->rep[i];3305}3306if (zc->externSeqStore.pos < zc->externSeqStore.size) {3307assert(zc->appliedParams.ldmParams.enableLdm == ZSTD_ps_disable);33083309/* External matchfinder + LDM is technically possible, just not implemented yet.3310* We need to revisit soon and implement it. */3311RETURN_ERROR_IF(3312ZSTD_hasExtSeqProd(&zc->appliedParams),3313parameter_combination_unsupported,3314"Long-distance matching with external sequence producer enabled is not currently supported."3315);33163317/* Updates ldmSeqStore.pos */3318lastLLSize =3319ZSTD_ldm_blockCompress(&zc->externSeqStore,3320ms, &zc->seqStore,3321zc->blockState.nextCBlock->rep,3322zc->appliedParams.useRowMatchFinder,3323src, srcSize);3324assert(zc->externSeqStore.pos <= zc->externSeqStore.size);3325} else if (zc->appliedParams.ldmParams.enableLdm == ZSTD_ps_enable) {3326RawSeqStore_t ldmSeqStore = kNullRawSeqStore;33273328/* External matchfinder + LDM is technically possible, just not implemented yet.3329* We need to revisit soon and implement it. */3330RETURN_ERROR_IF(3331ZSTD_hasExtSeqProd(&zc->appliedParams),3332parameter_combination_unsupported,3333"Long-distance matching with external sequence producer enabled is not currently supported."3334);33353336ldmSeqStore.seq = zc->ldmSequences;3337ldmSeqStore.capacity = zc->maxNbLdmSequences;3338/* Updates ldmSeqStore.size */3339FORWARD_IF_ERROR(ZSTD_ldm_generateSequences(&zc->ldmState, &ldmSeqStore,3340&zc->appliedParams.ldmParams,3341src, srcSize), "");3342/* Updates ldmSeqStore.pos */3343lastLLSize =3344ZSTD_ldm_blockCompress(&ldmSeqStore,3345ms, &zc->seqStore,3346zc->blockState.nextCBlock->rep,3347zc->appliedParams.useRowMatchFinder,3348src, srcSize);3349assert(ldmSeqStore.pos == ldmSeqStore.size);3350} else if (ZSTD_hasExtSeqProd(&zc->appliedParams)) {3351assert(3352zc->extSeqBufCapacity >= ZSTD_sequenceBound(srcSize)3353);3354assert(zc->appliedParams.extSeqProdFunc != NULL);33553356{ U32 const windowSize = (U32)1 << zc->appliedParams.cParams.windowLog;33573358size_t const nbExternalSeqs = (zc->appliedParams.extSeqProdFunc)(3359zc->appliedParams.extSeqProdState,3360zc->extSeqBuf,3361zc->extSeqBufCapacity,3362src, srcSize,3363NULL, 0, /* dict and dictSize, currently not supported */3364zc->appliedParams.compressionLevel,3365windowSize3366);33673368size_t const nbPostProcessedSeqs = ZSTD_postProcessSequenceProducerResult(3369zc->extSeqBuf,3370nbExternalSeqs,3371zc->extSeqBufCapacity,3372srcSize3373);33743375/* Return early if there is no error, since we don't need to worry about last literals */3376if (!ZSTD_isError(nbPostProcessedSeqs)) {3377ZSTD_SequencePosition seqPos = {0,0,0};3378size_t const seqLenSum = ZSTD_fastSequenceLengthSum(zc->extSeqBuf, nbPostProcessedSeqs);3379RETURN_ERROR_IF(seqLenSum > srcSize, externalSequences_invalid, "External sequences imply too large a block!");3380FORWARD_IF_ERROR(3381ZSTD_transferSequences_wBlockDelim(3382zc, &seqPos,3383zc->extSeqBuf, nbPostProcessedSeqs,3384src, srcSize,3385zc->appliedParams.searchForExternalRepcodes3386),3387"Failed to copy external sequences to seqStore!"3388);3389ms->ldmSeqStore = NULL;3390DEBUGLOG(5, "Copied %lu sequences from external sequence producer to internal seqStore.", (unsigned long)nbExternalSeqs);3391return ZSTDbss_compress;3392}33933394/* Propagate the error if fallback is disabled */3395if (!zc->appliedParams.enableMatchFinderFallback) {3396return nbPostProcessedSeqs;3397}33983399/* Fallback to software matchfinder */3400{ ZSTD_BlockCompressor_f const blockCompressor =3401ZSTD_selectBlockCompressor(3402zc->appliedParams.cParams.strategy,3403zc->appliedParams.useRowMatchFinder,3404dictMode);3405ms->ldmSeqStore = NULL;3406DEBUGLOG(34075,3408"External sequence producer returned error code %lu. Falling back to internal parser.",3409(unsigned long)nbExternalSeqs3410);3411lastLLSize = blockCompressor(ms, &zc->seqStore, zc->blockState.nextCBlock->rep, src, srcSize);3412} }3413} else { /* not long range mode and no external matchfinder */3414ZSTD_BlockCompressor_f const blockCompressor = ZSTD_selectBlockCompressor(3415zc->appliedParams.cParams.strategy,3416zc->appliedParams.useRowMatchFinder,3417dictMode);3418ms->ldmSeqStore = NULL;3419lastLLSize = blockCompressor(ms, &zc->seqStore, zc->blockState.nextCBlock->rep, src, srcSize);3420}3421{ const BYTE* const lastLiterals = (const BYTE*)src + srcSize - lastLLSize;3422ZSTD_storeLastLiterals(&zc->seqStore, lastLiterals, lastLLSize);3423} }3424ZSTD_validateSeqStore(&zc->seqStore, &zc->appliedParams.cParams);3425return ZSTDbss_compress;3426}34273428static size_t ZSTD_copyBlockSequences(SeqCollector* seqCollector, const SeqStore_t* seqStore, const U32 prevRepcodes[ZSTD_REP_NUM])3429{3430const SeqDef* inSeqs = seqStore->sequencesStart;3431const size_t nbInSequences = (size_t)(seqStore->sequences - inSeqs);3432const size_t nbInLiterals = (size_t)(seqStore->lit - seqStore->litStart);34333434ZSTD_Sequence* outSeqs = seqCollector->seqIndex == 0 ? seqCollector->seqStart : seqCollector->seqStart + seqCollector->seqIndex;3435const size_t nbOutSequences = nbInSequences + 1;3436size_t nbOutLiterals = 0;3437Repcodes_t repcodes;3438size_t i;34393440/* Bounds check that we have enough space for every input sequence3441* and the block delimiter3442*/3443assert(seqCollector->seqIndex <= seqCollector->maxSequences);3444RETURN_ERROR_IF(3445nbOutSequences > (size_t)(seqCollector->maxSequences - seqCollector->seqIndex),3446dstSize_tooSmall,3447"Not enough space to copy sequences");34483449ZSTD_memcpy(&repcodes, prevRepcodes, sizeof(repcodes));3450for (i = 0; i < nbInSequences; ++i) {3451U32 rawOffset;3452outSeqs[i].litLength = inSeqs[i].litLength;3453outSeqs[i].matchLength = inSeqs[i].mlBase + MINMATCH;3454outSeqs[i].rep = 0;34553456/* Handle the possible single length >= 64K3457* There can only be one because we add MINMATCH to every match length,3458* and blocks are at most 128K.3459*/3460if (i == seqStore->longLengthPos) {3461if (seqStore->longLengthType == ZSTD_llt_literalLength) {3462outSeqs[i].litLength += 0x10000;3463} else if (seqStore->longLengthType == ZSTD_llt_matchLength) {3464outSeqs[i].matchLength += 0x10000;3465}3466}34673468/* Determine the raw offset given the offBase, which may be a repcode. */3469if (OFFBASE_IS_REPCODE(inSeqs[i].offBase)) {3470const U32 repcode = OFFBASE_TO_REPCODE(inSeqs[i].offBase);3471assert(repcode > 0);3472outSeqs[i].rep = repcode;3473if (outSeqs[i].litLength != 0) {3474rawOffset = repcodes.rep[repcode - 1];3475} else {3476if (repcode == 3) {3477assert(repcodes.rep[0] > 1);3478rawOffset = repcodes.rep[0] - 1;3479} else {3480rawOffset = repcodes.rep[repcode];3481}3482}3483} else {3484rawOffset = OFFBASE_TO_OFFSET(inSeqs[i].offBase);3485}3486outSeqs[i].offset = rawOffset;34873488/* Update repcode history for the sequence */3489ZSTD_updateRep(repcodes.rep,3490inSeqs[i].offBase,3491inSeqs[i].litLength == 0);34923493nbOutLiterals += outSeqs[i].litLength;3494}3495/* Insert last literals (if any exist) in the block as a sequence with ml == off == 0.3496* If there are no last literals, then we'll emit (of: 0, ml: 0, ll: 0), which is a marker3497* for the block boundary, according to the API.3498*/3499assert(nbInLiterals >= nbOutLiterals);3500{3501const size_t lastLLSize = nbInLiterals - nbOutLiterals;3502outSeqs[nbInSequences].litLength = (U32)lastLLSize;3503outSeqs[nbInSequences].matchLength = 0;3504outSeqs[nbInSequences].offset = 0;3505assert(nbOutSequences == nbInSequences + 1);3506}3507seqCollector->seqIndex += nbOutSequences;3508assert(seqCollector->seqIndex <= seqCollector->maxSequences);35093510return 0;3511}35123513size_t ZSTD_sequenceBound(size_t srcSize) {3514const size_t maxNbSeq = (srcSize / ZSTD_MINMATCH_MIN) + 1;3515const size_t maxNbDelims = (srcSize / ZSTD_BLOCKSIZE_MAX_MIN) + 1;3516return maxNbSeq + maxNbDelims;3517}35183519size_t ZSTD_generateSequences(ZSTD_CCtx* zc, ZSTD_Sequence* outSeqs,3520size_t outSeqsSize, const void* src, size_t srcSize)3521{3522const size_t dstCapacity = ZSTD_compressBound(srcSize);3523void* dst; /* Make C90 happy. */3524SeqCollector seqCollector;3525{3526int targetCBlockSize;3527FORWARD_IF_ERROR(ZSTD_CCtx_getParameter(zc, ZSTD_c_targetCBlockSize, &targetCBlockSize), "");3528RETURN_ERROR_IF(targetCBlockSize != 0, parameter_unsupported, "targetCBlockSize != 0");3529}3530{3531int nbWorkers;3532FORWARD_IF_ERROR(ZSTD_CCtx_getParameter(zc, ZSTD_c_nbWorkers, &nbWorkers), "");3533RETURN_ERROR_IF(nbWorkers != 0, parameter_unsupported, "nbWorkers != 0");3534}35353536dst = ZSTD_customMalloc(dstCapacity, ZSTD_defaultCMem);3537RETURN_ERROR_IF(dst == NULL, memory_allocation, "NULL pointer!");35383539seqCollector.collectSequences = 1;3540seqCollector.seqStart = outSeqs;3541seqCollector.seqIndex = 0;3542seqCollector.maxSequences = outSeqsSize;3543zc->seqCollector = seqCollector;35443545{3546const size_t ret = ZSTD_compress2(zc, dst, dstCapacity, src, srcSize);3547ZSTD_customFree(dst, ZSTD_defaultCMem);3548FORWARD_IF_ERROR(ret, "ZSTD_compress2 failed");3549}3550assert(zc->seqCollector.seqIndex <= ZSTD_sequenceBound(srcSize));3551return zc->seqCollector.seqIndex;3552}35533554size_t ZSTD_mergeBlockDelimiters(ZSTD_Sequence* sequences, size_t seqsSize) {3555size_t in = 0;3556size_t out = 0;3557for (; in < seqsSize; ++in) {3558if (sequences[in].offset == 0 && sequences[in].matchLength == 0) {3559if (in != seqsSize - 1) {3560sequences[in+1].litLength += sequences[in].litLength;3561}3562} else {3563sequences[out] = sequences[in];3564++out;3565}3566}3567return out;3568}35693570/* Unrolled loop to read four size_ts of input at a time. Returns 1 if is RLE, 0 if not. */3571static int ZSTD_isRLE(const BYTE* src, size_t length) {3572const BYTE* ip = src;3573const BYTE value = ip[0];3574const size_t valueST = (size_t)((U64)value * 0x0101010101010101ULL);3575const size_t unrollSize = sizeof(size_t) * 4;3576const size_t unrollMask = unrollSize - 1;3577const size_t prefixLength = length & unrollMask;3578size_t i;3579if (length == 1) return 1;3580/* Check if prefix is RLE first before using unrolled loop */3581if (prefixLength && ZSTD_count(ip+1, ip, ip+prefixLength) != prefixLength-1) {3582return 0;3583}3584for (i = prefixLength; i != length; i += unrollSize) {3585size_t u;3586for (u = 0; u < unrollSize; u += sizeof(size_t)) {3587if (MEM_readST(ip + i + u) != valueST) {3588return 0;3589} } }3590return 1;3591}35923593/* Returns true if the given block may be RLE.3594* This is just a heuristic based on the compressibility.3595* It may return both false positives and false negatives.3596*/3597static int ZSTD_maybeRLE(SeqStore_t const* seqStore)3598{3599size_t const nbSeqs = (size_t)(seqStore->sequences - seqStore->sequencesStart);3600size_t const nbLits = (size_t)(seqStore->lit - seqStore->litStart);36013602return nbSeqs < 4 && nbLits < 10;3603}36043605static void3606ZSTD_blockState_confirmRepcodesAndEntropyTables(ZSTD_blockState_t* const bs)3607{3608ZSTD_compressedBlockState_t* const tmp = bs->prevCBlock;3609bs->prevCBlock = bs->nextCBlock;3610bs->nextCBlock = tmp;3611}36123613/* Writes the block header */3614static void3615writeBlockHeader(void* op, size_t cSize, size_t blockSize, U32 lastBlock)3616{3617U32 const cBlockHeader = cSize == 1 ?3618lastBlock + (((U32)bt_rle)<<1) + (U32)(blockSize << 3) :3619lastBlock + (((U32)bt_compressed)<<1) + (U32)(cSize << 3);3620MEM_writeLE24(op, cBlockHeader);3621DEBUGLOG(5, "writeBlockHeader: cSize: %zu blockSize: %zu lastBlock: %u", cSize, blockSize, lastBlock);3622}36233624/** ZSTD_buildBlockEntropyStats_literals() :3625* Builds entropy for the literals.3626* Stores literals block type (raw, rle, compressed, repeat) and3627* huffman description table to hufMetadata.3628* Requires ENTROPY_WORKSPACE_SIZE workspace3629* @return : size of huffman description table, or an error code3630*/3631static size_t3632ZSTD_buildBlockEntropyStats_literals(void* const src, size_t srcSize,3633const ZSTD_hufCTables_t* prevHuf,3634ZSTD_hufCTables_t* nextHuf,3635ZSTD_hufCTablesMetadata_t* hufMetadata,3636const int literalsCompressionIsDisabled,3637void* workspace, size_t wkspSize,3638int hufFlags)3639{3640BYTE* const wkspStart = (BYTE*)workspace;3641BYTE* const wkspEnd = wkspStart + wkspSize;3642BYTE* const countWkspStart = wkspStart;3643unsigned* const countWksp = (unsigned*)workspace;3644const size_t countWkspSize = (HUF_SYMBOLVALUE_MAX + 1) * sizeof(unsigned);3645BYTE* const nodeWksp = countWkspStart + countWkspSize;3646const size_t nodeWkspSize = (size_t)(wkspEnd - nodeWksp);3647unsigned maxSymbolValue = HUF_SYMBOLVALUE_MAX;3648unsigned huffLog = LitHufLog;3649HUF_repeat repeat = prevHuf->repeatMode;3650DEBUGLOG(5, "ZSTD_buildBlockEntropyStats_literals (srcSize=%zu)", srcSize);36513652/* Prepare nextEntropy assuming reusing the existing table */3653ZSTD_memcpy(nextHuf, prevHuf, sizeof(*prevHuf));36543655if (literalsCompressionIsDisabled) {3656DEBUGLOG(5, "set_basic - disabled");3657hufMetadata->hType = set_basic;3658return 0;3659}36603661/* small ? don't even attempt compression (speed opt) */3662#ifndef COMPRESS_LITERALS_SIZE_MIN3663# define COMPRESS_LITERALS_SIZE_MIN 63 /* heuristic */3664#endif3665{ size_t const minLitSize = (prevHuf->repeatMode == HUF_repeat_valid) ? 6 : COMPRESS_LITERALS_SIZE_MIN;3666if (srcSize <= minLitSize) {3667DEBUGLOG(5, "set_basic - too small");3668hufMetadata->hType = set_basic;3669return 0;3670} }36713672/* Scan input and build symbol stats */3673{ size_t const largest =3674HIST_count_wksp (countWksp, &maxSymbolValue,3675(const BYTE*)src, srcSize,3676workspace, wkspSize);3677FORWARD_IF_ERROR(largest, "HIST_count_wksp failed");3678if (largest == srcSize) {3679/* only one literal symbol */3680DEBUGLOG(5, "set_rle");3681hufMetadata->hType = set_rle;3682return 0;3683}3684if (largest <= (srcSize >> 7)+4) {3685/* heuristic: likely not compressible */3686DEBUGLOG(5, "set_basic - no gain");3687hufMetadata->hType = set_basic;3688return 0;3689} }36903691/* Validate the previous Huffman table */3692if (repeat == HUF_repeat_check3693&& !HUF_validateCTable((HUF_CElt const*)prevHuf->CTable, countWksp, maxSymbolValue)) {3694repeat = HUF_repeat_none;3695}36963697/* Build Huffman Tree */3698ZSTD_memset(nextHuf->CTable, 0, sizeof(nextHuf->CTable));3699huffLog = HUF_optimalTableLog(huffLog, srcSize, maxSymbolValue, nodeWksp, nodeWkspSize, nextHuf->CTable, countWksp, hufFlags);3700assert(huffLog <= LitHufLog);3701{ size_t const maxBits = HUF_buildCTable_wksp((HUF_CElt*)nextHuf->CTable, countWksp,3702maxSymbolValue, huffLog,3703nodeWksp, nodeWkspSize);3704FORWARD_IF_ERROR(maxBits, "HUF_buildCTable_wksp");3705huffLog = (U32)maxBits;3706}3707{ /* Build and write the CTable */3708size_t const newCSize = HUF_estimateCompressedSize(3709(HUF_CElt*)nextHuf->CTable, countWksp, maxSymbolValue);3710size_t const hSize = HUF_writeCTable_wksp(3711hufMetadata->hufDesBuffer, sizeof(hufMetadata->hufDesBuffer),3712(HUF_CElt*)nextHuf->CTable, maxSymbolValue, huffLog,3713nodeWksp, nodeWkspSize);3714/* Check against repeating the previous CTable */3715if (repeat != HUF_repeat_none) {3716size_t const oldCSize = HUF_estimateCompressedSize(3717(HUF_CElt const*)prevHuf->CTable, countWksp, maxSymbolValue);3718if (oldCSize < srcSize && (oldCSize <= hSize + newCSize || hSize + 12 >= srcSize)) {3719DEBUGLOG(5, "set_repeat - smaller");3720ZSTD_memcpy(nextHuf, prevHuf, sizeof(*prevHuf));3721hufMetadata->hType = set_repeat;3722return 0;3723} }3724if (newCSize + hSize >= srcSize) {3725DEBUGLOG(5, "set_basic - no gains");3726ZSTD_memcpy(nextHuf, prevHuf, sizeof(*prevHuf));3727hufMetadata->hType = set_basic;3728return 0;3729}3730DEBUGLOG(5, "set_compressed (hSize=%u)", (U32)hSize);3731hufMetadata->hType = set_compressed;3732nextHuf->repeatMode = HUF_repeat_check;3733return hSize;3734}3735}373637373738/* ZSTD_buildDummySequencesStatistics():3739* Returns a ZSTD_symbolEncodingTypeStats_t with all encoding types as set_basic,3740* and updates nextEntropy to the appropriate repeatMode.3741*/3742static ZSTD_symbolEncodingTypeStats_t3743ZSTD_buildDummySequencesStatistics(ZSTD_fseCTables_t* nextEntropy)3744{3745ZSTD_symbolEncodingTypeStats_t stats = {set_basic, set_basic, set_basic, 0, 0, 0};3746nextEntropy->litlength_repeatMode = FSE_repeat_none;3747nextEntropy->offcode_repeatMode = FSE_repeat_none;3748nextEntropy->matchlength_repeatMode = FSE_repeat_none;3749return stats;3750}37513752/** ZSTD_buildBlockEntropyStats_sequences() :3753* Builds entropy for the sequences.3754* Stores symbol compression modes and fse table to fseMetadata.3755* Requires ENTROPY_WORKSPACE_SIZE wksp.3756* @return : size of fse tables or error code */3757static size_t3758ZSTD_buildBlockEntropyStats_sequences(3759const SeqStore_t* seqStorePtr,3760const ZSTD_fseCTables_t* prevEntropy,3761ZSTD_fseCTables_t* nextEntropy,3762const ZSTD_CCtx_params* cctxParams,3763ZSTD_fseCTablesMetadata_t* fseMetadata,3764void* workspace, size_t wkspSize)3765{3766ZSTD_strategy const strategy = cctxParams->cParams.strategy;3767size_t const nbSeq = (size_t)(seqStorePtr->sequences - seqStorePtr->sequencesStart);3768BYTE* const ostart = fseMetadata->fseTablesBuffer;3769BYTE* const oend = ostart + sizeof(fseMetadata->fseTablesBuffer);3770BYTE* op = ostart;3771unsigned* countWorkspace = (unsigned*)workspace;3772unsigned* entropyWorkspace = countWorkspace + (MaxSeq + 1);3773size_t entropyWorkspaceSize = wkspSize - (MaxSeq + 1) * sizeof(*countWorkspace);3774ZSTD_symbolEncodingTypeStats_t stats;37753776DEBUGLOG(5, "ZSTD_buildBlockEntropyStats_sequences (nbSeq=%zu)", nbSeq);3777stats = nbSeq != 0 ? ZSTD_buildSequencesStatistics(seqStorePtr, nbSeq,3778prevEntropy, nextEntropy, op, oend,3779strategy, countWorkspace,3780entropyWorkspace, entropyWorkspaceSize)3781: ZSTD_buildDummySequencesStatistics(nextEntropy);3782FORWARD_IF_ERROR(stats.size, "ZSTD_buildSequencesStatistics failed!");3783fseMetadata->llType = (SymbolEncodingType_e) stats.LLtype;3784fseMetadata->ofType = (SymbolEncodingType_e) stats.Offtype;3785fseMetadata->mlType = (SymbolEncodingType_e) stats.MLtype;3786fseMetadata->lastCountSize = stats.lastCountSize;3787return stats.size;3788}378937903791/** ZSTD_buildBlockEntropyStats() :3792* Builds entropy for the block.3793* Requires workspace size ENTROPY_WORKSPACE_SIZE3794* @return : 0 on success, or an error code3795* Note : also employed in superblock3796*/3797size_t ZSTD_buildBlockEntropyStats(3798const SeqStore_t* seqStorePtr,3799const ZSTD_entropyCTables_t* prevEntropy,3800ZSTD_entropyCTables_t* nextEntropy,3801const ZSTD_CCtx_params* cctxParams,3802ZSTD_entropyCTablesMetadata_t* entropyMetadata,3803void* workspace, size_t wkspSize)3804{3805size_t const litSize = (size_t)(seqStorePtr->lit - seqStorePtr->litStart);3806int const huf_useOptDepth = (cctxParams->cParams.strategy >= HUF_OPTIMAL_DEPTH_THRESHOLD);3807int const hufFlags = huf_useOptDepth ? HUF_flags_optimalDepth : 0;38083809entropyMetadata->hufMetadata.hufDesSize =3810ZSTD_buildBlockEntropyStats_literals(seqStorePtr->litStart, litSize,3811&prevEntropy->huf, &nextEntropy->huf,3812&entropyMetadata->hufMetadata,3813ZSTD_literalsCompressionIsDisabled(cctxParams),3814workspace, wkspSize, hufFlags);38153816FORWARD_IF_ERROR(entropyMetadata->hufMetadata.hufDesSize, "ZSTD_buildBlockEntropyStats_literals failed");3817entropyMetadata->fseMetadata.fseTablesSize =3818ZSTD_buildBlockEntropyStats_sequences(seqStorePtr,3819&prevEntropy->fse, &nextEntropy->fse,3820cctxParams,3821&entropyMetadata->fseMetadata,3822workspace, wkspSize);3823FORWARD_IF_ERROR(entropyMetadata->fseMetadata.fseTablesSize, "ZSTD_buildBlockEntropyStats_sequences failed");3824return 0;3825}38263827/* Returns the size estimate for the literals section (header + content) of a block */3828static size_t3829ZSTD_estimateBlockSize_literal(const BYTE* literals, size_t litSize,3830const ZSTD_hufCTables_t* huf,3831const ZSTD_hufCTablesMetadata_t* hufMetadata,3832void* workspace, size_t wkspSize,3833int writeEntropy)3834{3835unsigned* const countWksp = (unsigned*)workspace;3836unsigned maxSymbolValue = HUF_SYMBOLVALUE_MAX;3837size_t literalSectionHeaderSize = 3 + (litSize >= 1 KB) + (litSize >= 16 KB);3838U32 singleStream = litSize < 256;38393840if (hufMetadata->hType == set_basic) return litSize;3841else if (hufMetadata->hType == set_rle) return 1;3842else if (hufMetadata->hType == set_compressed || hufMetadata->hType == set_repeat) {3843size_t const largest = HIST_count_wksp (countWksp, &maxSymbolValue, (const BYTE*)literals, litSize, workspace, wkspSize);3844if (ZSTD_isError(largest)) return litSize;3845{ size_t cLitSizeEstimate = HUF_estimateCompressedSize((const HUF_CElt*)huf->CTable, countWksp, maxSymbolValue);3846if (writeEntropy) cLitSizeEstimate += hufMetadata->hufDesSize;3847if (!singleStream) cLitSizeEstimate += 6; /* multi-stream huffman uses 6-byte jump table */3848return cLitSizeEstimate + literalSectionHeaderSize;3849} }3850assert(0); /* impossible */3851return 0;3852}38533854/* Returns the size estimate for the FSE-compressed symbols (of, ml, ll) of a block */3855static size_t3856ZSTD_estimateBlockSize_symbolType(SymbolEncodingType_e type,3857const BYTE* codeTable, size_t nbSeq, unsigned maxCode,3858const FSE_CTable* fseCTable,3859const U8* additionalBits,3860short const* defaultNorm, U32 defaultNormLog, U32 defaultMax,3861void* workspace, size_t wkspSize)3862{3863unsigned* const countWksp = (unsigned*)workspace;3864const BYTE* ctp = codeTable;3865const BYTE* const ctStart = ctp;3866const BYTE* const ctEnd = ctStart + nbSeq;3867size_t cSymbolTypeSizeEstimateInBits = 0;3868unsigned max = maxCode;38693870HIST_countFast_wksp(countWksp, &max, codeTable, nbSeq, workspace, wkspSize); /* can't fail */3871if (type == set_basic) {3872/* We selected this encoding type, so it must be valid. */3873assert(max <= defaultMax);3874(void)defaultMax;3875cSymbolTypeSizeEstimateInBits = ZSTD_crossEntropyCost(defaultNorm, defaultNormLog, countWksp, max);3876} else if (type == set_rle) {3877cSymbolTypeSizeEstimateInBits = 0;3878} else if (type == set_compressed || type == set_repeat) {3879cSymbolTypeSizeEstimateInBits = ZSTD_fseBitCost(fseCTable, countWksp, max);3880}3881if (ZSTD_isError(cSymbolTypeSizeEstimateInBits)) {3882return nbSeq * 10;3883}3884while (ctp < ctEnd) {3885if (additionalBits) cSymbolTypeSizeEstimateInBits += additionalBits[*ctp];3886else cSymbolTypeSizeEstimateInBits += *ctp; /* for offset, offset code is also the number of additional bits */3887ctp++;3888}3889return cSymbolTypeSizeEstimateInBits >> 3;3890}38913892/* Returns the size estimate for the sequences section (header + content) of a block */3893static size_t3894ZSTD_estimateBlockSize_sequences(const BYTE* ofCodeTable,3895const BYTE* llCodeTable,3896const BYTE* mlCodeTable,3897size_t nbSeq,3898const ZSTD_fseCTables_t* fseTables,3899const ZSTD_fseCTablesMetadata_t* fseMetadata,3900void* workspace, size_t wkspSize,3901int writeEntropy)3902{3903size_t sequencesSectionHeaderSize = 1 /* seqHead */ + 1 /* min seqSize size */ + (nbSeq >= 128) + (nbSeq >= LONGNBSEQ);3904size_t cSeqSizeEstimate = 0;3905cSeqSizeEstimate += ZSTD_estimateBlockSize_symbolType(fseMetadata->ofType, ofCodeTable, nbSeq, MaxOff,3906fseTables->offcodeCTable, NULL,3907OF_defaultNorm, OF_defaultNormLog, DefaultMaxOff,3908workspace, wkspSize);3909cSeqSizeEstimate += ZSTD_estimateBlockSize_symbolType(fseMetadata->llType, llCodeTable, nbSeq, MaxLL,3910fseTables->litlengthCTable, LL_bits,3911LL_defaultNorm, LL_defaultNormLog, MaxLL,3912workspace, wkspSize);3913cSeqSizeEstimate += ZSTD_estimateBlockSize_symbolType(fseMetadata->mlType, mlCodeTable, nbSeq, MaxML,3914fseTables->matchlengthCTable, ML_bits,3915ML_defaultNorm, ML_defaultNormLog, MaxML,3916workspace, wkspSize);3917if (writeEntropy) cSeqSizeEstimate += fseMetadata->fseTablesSize;3918return cSeqSizeEstimate + sequencesSectionHeaderSize;3919}39203921/* Returns the size estimate for a given stream of literals, of, ll, ml */3922static size_t3923ZSTD_estimateBlockSize(const BYTE* literals, size_t litSize,3924const BYTE* ofCodeTable,3925const BYTE* llCodeTable,3926const BYTE* mlCodeTable,3927size_t nbSeq,3928const ZSTD_entropyCTables_t* entropy,3929const ZSTD_entropyCTablesMetadata_t* entropyMetadata,3930void* workspace, size_t wkspSize,3931int writeLitEntropy, int writeSeqEntropy)3932{3933size_t const literalsSize = ZSTD_estimateBlockSize_literal(literals, litSize,3934&entropy->huf, &entropyMetadata->hufMetadata,3935workspace, wkspSize, writeLitEntropy);3936size_t const seqSize = ZSTD_estimateBlockSize_sequences(ofCodeTable, llCodeTable, mlCodeTable,3937nbSeq, &entropy->fse, &entropyMetadata->fseMetadata,3938workspace, wkspSize, writeSeqEntropy);3939return seqSize + literalsSize + ZSTD_blockHeaderSize;3940}39413942/* Builds entropy statistics and uses them for blocksize estimation.3943*3944* @return: estimated compressed size of the seqStore, or a zstd error.3945*/3946static size_t3947ZSTD_buildEntropyStatisticsAndEstimateSubBlockSize(SeqStore_t* seqStore, ZSTD_CCtx* zc)3948{3949ZSTD_entropyCTablesMetadata_t* const entropyMetadata = &zc->blockSplitCtx.entropyMetadata;3950DEBUGLOG(6, "ZSTD_buildEntropyStatisticsAndEstimateSubBlockSize()");3951FORWARD_IF_ERROR(ZSTD_buildBlockEntropyStats(seqStore,3952&zc->blockState.prevCBlock->entropy,3953&zc->blockState.nextCBlock->entropy,3954&zc->appliedParams,3955entropyMetadata,3956zc->tmpWorkspace, zc->tmpWkspSize), "");3957return ZSTD_estimateBlockSize(3958seqStore->litStart, (size_t)(seqStore->lit - seqStore->litStart),3959seqStore->ofCode, seqStore->llCode, seqStore->mlCode,3960(size_t)(seqStore->sequences - seqStore->sequencesStart),3961&zc->blockState.nextCBlock->entropy,3962entropyMetadata,3963zc->tmpWorkspace, zc->tmpWkspSize,3964(int)(entropyMetadata->hufMetadata.hType == set_compressed), 1);3965}39663967/* Returns literals bytes represented in a seqStore */3968static size_t ZSTD_countSeqStoreLiteralsBytes(const SeqStore_t* const seqStore)3969{3970size_t literalsBytes = 0;3971size_t const nbSeqs = (size_t)(seqStore->sequences - seqStore->sequencesStart);3972size_t i;3973for (i = 0; i < nbSeqs; ++i) {3974SeqDef const seq = seqStore->sequencesStart[i];3975literalsBytes += seq.litLength;3976if (i == seqStore->longLengthPos && seqStore->longLengthType == ZSTD_llt_literalLength) {3977literalsBytes += 0x10000;3978} }3979return literalsBytes;3980}39813982/* Returns match bytes represented in a seqStore */3983static size_t ZSTD_countSeqStoreMatchBytes(const SeqStore_t* const seqStore)3984{3985size_t matchBytes = 0;3986size_t const nbSeqs = (size_t)(seqStore->sequences - seqStore->sequencesStart);3987size_t i;3988for (i = 0; i < nbSeqs; ++i) {3989SeqDef seq = seqStore->sequencesStart[i];3990matchBytes += seq.mlBase + MINMATCH;3991if (i == seqStore->longLengthPos && seqStore->longLengthType == ZSTD_llt_matchLength) {3992matchBytes += 0x10000;3993} }3994return matchBytes;3995}39963997/* Derives the seqStore that is a chunk of the originalSeqStore from [startIdx, endIdx).3998* Stores the result in resultSeqStore.3999*/4000static void ZSTD_deriveSeqStoreChunk(SeqStore_t* resultSeqStore,4001const SeqStore_t* originalSeqStore,4002size_t startIdx, size_t endIdx)4003{4004*resultSeqStore = *originalSeqStore;4005if (startIdx > 0) {4006resultSeqStore->sequences = originalSeqStore->sequencesStart + startIdx;4007resultSeqStore->litStart += ZSTD_countSeqStoreLiteralsBytes(resultSeqStore);4008}40094010/* Move longLengthPos into the correct position if necessary */4011if (originalSeqStore->longLengthType != ZSTD_llt_none) {4012if (originalSeqStore->longLengthPos < startIdx || originalSeqStore->longLengthPos > endIdx) {4013resultSeqStore->longLengthType = ZSTD_llt_none;4014} else {4015resultSeqStore->longLengthPos -= (U32)startIdx;4016}4017}4018resultSeqStore->sequencesStart = originalSeqStore->sequencesStart + startIdx;4019resultSeqStore->sequences = originalSeqStore->sequencesStart + endIdx;4020if (endIdx == (size_t)(originalSeqStore->sequences - originalSeqStore->sequencesStart)) {4021/* This accounts for possible last literals if the derived chunk reaches the end of the block */4022assert(resultSeqStore->lit == originalSeqStore->lit);4023} else {4024size_t const literalsBytes = ZSTD_countSeqStoreLiteralsBytes(resultSeqStore);4025resultSeqStore->lit = resultSeqStore->litStart + literalsBytes;4026}4027resultSeqStore->llCode += startIdx;4028resultSeqStore->mlCode += startIdx;4029resultSeqStore->ofCode += startIdx;4030}40314032/**4033* Returns the raw offset represented by the combination of offBase, ll0, and repcode history.4034* offBase must represent a repcode in the numeric representation of ZSTD_storeSeq().4035*/4036static U324037ZSTD_resolveRepcodeToRawOffset(const U32 rep[ZSTD_REP_NUM], const U32 offBase, const U32 ll0)4038{4039U32 const adjustedRepCode = OFFBASE_TO_REPCODE(offBase) - 1 + ll0; /* [ 0 - 3 ] */4040assert(OFFBASE_IS_REPCODE(offBase));4041if (adjustedRepCode == ZSTD_REP_NUM) {4042assert(ll0);4043/* litlength == 0 and offCode == 2 implies selection of first repcode - 14044* This is only valid if it results in a valid offset value, aka > 0.4045* Note : it may happen that `rep[0]==1` in exceptional circumstances.4046* In which case this function will return 0, which is an invalid offset.4047* It's not an issue though, since this value will be4048* compared and discarded within ZSTD_seqStore_resolveOffCodes().4049*/4050return rep[0] - 1;4051}4052return rep[adjustedRepCode];4053}40544055/**4056* ZSTD_seqStore_resolveOffCodes() reconciles any possible divergences in offset history that may arise4057* due to emission of RLE/raw blocks that disturb the offset history,4058* and replaces any repcodes within the seqStore that may be invalid.4059*4060* dRepcodes are updated as would be on the decompression side.4061* cRepcodes are updated exactly in accordance with the seqStore.4062*4063* Note : this function assumes seq->offBase respects the following numbering scheme :4064* 0 : invalid4065* 1-3 : repcode 1-34066* 4+ : real_offset+34067*/4068static void4069ZSTD_seqStore_resolveOffCodes(Repcodes_t* const dRepcodes, Repcodes_t* const cRepcodes,4070const SeqStore_t* const seqStore, U32 const nbSeq)4071{4072U32 idx = 0;4073U32 const longLitLenIdx = seqStore->longLengthType == ZSTD_llt_literalLength ? seqStore->longLengthPos : nbSeq;4074for (; idx < nbSeq; ++idx) {4075SeqDef* const seq = seqStore->sequencesStart + idx;4076U32 const ll0 = (seq->litLength == 0) && (idx != longLitLenIdx);4077U32 const offBase = seq->offBase;4078assert(offBase > 0);4079if (OFFBASE_IS_REPCODE(offBase)) {4080U32 const dRawOffset = ZSTD_resolveRepcodeToRawOffset(dRepcodes->rep, offBase, ll0);4081U32 const cRawOffset = ZSTD_resolveRepcodeToRawOffset(cRepcodes->rep, offBase, ll0);4082/* Adjust simulated decompression repcode history if we come across a mismatch. Replace4083* the repcode with the offset it actually references, determined by the compression4084* repcode history.4085*/4086if (dRawOffset != cRawOffset) {4087seq->offBase = OFFSET_TO_OFFBASE(cRawOffset);4088}4089}4090/* Compression repcode history is always updated with values directly from the unmodified seqStore.4091* Decompression repcode history may use modified seq->offset value taken from compression repcode history.4092*/4093ZSTD_updateRep(dRepcodes->rep, seq->offBase, ll0);4094ZSTD_updateRep(cRepcodes->rep, offBase, ll0);4095}4096}40974098/* ZSTD_compressSeqStore_singleBlock():4099* Compresses a seqStore into a block with a block header, into the buffer dst.4100*4101* Returns the total size of that block (including header) or a ZSTD error code.4102*/4103static size_t4104ZSTD_compressSeqStore_singleBlock(ZSTD_CCtx* zc,4105const SeqStore_t* const seqStore,4106Repcodes_t* const dRep, Repcodes_t* const cRep,4107void* dst, size_t dstCapacity,4108const void* src, size_t srcSize,4109U32 lastBlock, U32 isPartition)4110{4111const U32 rleMaxLength = 25;4112BYTE* op = (BYTE*)dst;4113const BYTE* ip = (const BYTE*)src;4114size_t cSize;4115size_t cSeqsSize;41164117/* In case of an RLE or raw block, the simulated decompression repcode history must be reset */4118Repcodes_t const dRepOriginal = *dRep;4119DEBUGLOG(5, "ZSTD_compressSeqStore_singleBlock");4120if (isPartition)4121ZSTD_seqStore_resolveOffCodes(dRep, cRep, seqStore, (U32)(seqStore->sequences - seqStore->sequencesStart));41224123RETURN_ERROR_IF(dstCapacity < ZSTD_blockHeaderSize, dstSize_tooSmall, "Block header doesn't fit");4124cSeqsSize = ZSTD_entropyCompressSeqStore(seqStore,4125&zc->blockState.prevCBlock->entropy, &zc->blockState.nextCBlock->entropy,4126&zc->appliedParams,4127op + ZSTD_blockHeaderSize, dstCapacity - ZSTD_blockHeaderSize,4128srcSize,4129zc->tmpWorkspace, zc->tmpWkspSize /* statically allocated in resetCCtx */,4130zc->bmi2);4131FORWARD_IF_ERROR(cSeqsSize, "ZSTD_entropyCompressSeqStore failed!");41324133if (!zc->isFirstBlock &&4134cSeqsSize < rleMaxLength &&4135ZSTD_isRLE((BYTE const*)src, srcSize)) {4136/* We don't want to emit our first block as a RLE even if it qualifies because4137* doing so will cause the decoder (cli only) to throw a "should consume all input error."4138* This is only an issue for zstd <= v1.4.34139*/4140cSeqsSize = 1;4141}41424143/* Sequence collection not supported when block splitting */4144if (zc->seqCollector.collectSequences) {4145FORWARD_IF_ERROR(ZSTD_copyBlockSequences(&zc->seqCollector, seqStore, dRepOriginal.rep), "copyBlockSequences failed");4146ZSTD_blockState_confirmRepcodesAndEntropyTables(&zc->blockState);4147return 0;4148}41494150if (cSeqsSize == 0) {4151cSize = ZSTD_noCompressBlock(op, dstCapacity, ip, srcSize, lastBlock);4152FORWARD_IF_ERROR(cSize, "Nocompress block failed");4153DEBUGLOG(5, "Writing out nocompress block, size: %zu", cSize);4154*dRep = dRepOriginal; /* reset simulated decompression repcode history */4155} else if (cSeqsSize == 1) {4156cSize = ZSTD_rleCompressBlock(op, dstCapacity, *ip, srcSize, lastBlock);4157FORWARD_IF_ERROR(cSize, "RLE compress block failed");4158DEBUGLOG(5, "Writing out RLE block, size: %zu", cSize);4159*dRep = dRepOriginal; /* reset simulated decompression repcode history */4160} else {4161ZSTD_blockState_confirmRepcodesAndEntropyTables(&zc->blockState);4162writeBlockHeader(op, cSeqsSize, srcSize, lastBlock);4163cSize = ZSTD_blockHeaderSize + cSeqsSize;4164DEBUGLOG(5, "Writing out compressed block, size: %zu", cSize);4165}41664167if (zc->blockState.prevCBlock->entropy.fse.offcode_repeatMode == FSE_repeat_valid)4168zc->blockState.prevCBlock->entropy.fse.offcode_repeatMode = FSE_repeat_check;41694170return cSize;4171}41724173/* Struct to keep track of where we are in our recursive calls. */4174typedef struct {4175U32* splitLocations; /* Array of split indices */4176size_t idx; /* The current index within splitLocations being worked on */4177} seqStoreSplits;41784179#define MIN_SEQUENCES_BLOCK_SPLITTING 30041804181/* Helper function to perform the recursive search for block splits.4182* Estimates the cost of seqStore prior to split, and estimates the cost of splitting the sequences in half.4183* If advantageous to split, then we recurse down the two sub-blocks.4184* If not, or if an error occurred in estimation, then we do not recurse.4185*4186* Note: The recursion depth is capped by a heuristic minimum number of sequences,4187* defined by MIN_SEQUENCES_BLOCK_SPLITTING.4188* In theory, this means the absolute largest recursion depth is 10 == log2(maxNbSeqInBlock/MIN_SEQUENCES_BLOCK_SPLITTING).4189* In practice, recursion depth usually doesn't go beyond 4.4190*4191* Furthermore, the number of splits is capped by ZSTD_MAX_NB_BLOCK_SPLITS.4192* At ZSTD_MAX_NB_BLOCK_SPLITS == 196 with the current existing blockSize4193* maximum of 128 KB, this value is actually impossible to reach.4194*/4195static void4196ZSTD_deriveBlockSplitsHelper(seqStoreSplits* splits, size_t startIdx, size_t endIdx,4197ZSTD_CCtx* zc, const SeqStore_t* origSeqStore)4198{4199SeqStore_t* const fullSeqStoreChunk = &zc->blockSplitCtx.fullSeqStoreChunk;4200SeqStore_t* const firstHalfSeqStore = &zc->blockSplitCtx.firstHalfSeqStore;4201SeqStore_t* const secondHalfSeqStore = &zc->blockSplitCtx.secondHalfSeqStore;4202size_t estimatedOriginalSize;4203size_t estimatedFirstHalfSize;4204size_t estimatedSecondHalfSize;4205size_t midIdx = (startIdx + endIdx)/2;42064207DEBUGLOG(5, "ZSTD_deriveBlockSplitsHelper: startIdx=%zu endIdx=%zu", startIdx, endIdx);4208assert(endIdx >= startIdx);4209if (endIdx - startIdx < MIN_SEQUENCES_BLOCK_SPLITTING || splits->idx >= ZSTD_MAX_NB_BLOCK_SPLITS) {4210DEBUGLOG(6, "ZSTD_deriveBlockSplitsHelper: Too few sequences (%zu)", endIdx - startIdx);4211return;4212}4213ZSTD_deriveSeqStoreChunk(fullSeqStoreChunk, origSeqStore, startIdx, endIdx);4214ZSTD_deriveSeqStoreChunk(firstHalfSeqStore, origSeqStore, startIdx, midIdx);4215ZSTD_deriveSeqStoreChunk(secondHalfSeqStore, origSeqStore, midIdx, endIdx);4216estimatedOriginalSize = ZSTD_buildEntropyStatisticsAndEstimateSubBlockSize(fullSeqStoreChunk, zc);4217estimatedFirstHalfSize = ZSTD_buildEntropyStatisticsAndEstimateSubBlockSize(firstHalfSeqStore, zc);4218estimatedSecondHalfSize = ZSTD_buildEntropyStatisticsAndEstimateSubBlockSize(secondHalfSeqStore, zc);4219DEBUGLOG(5, "Estimated original block size: %zu -- First half split: %zu -- Second half split: %zu",4220estimatedOriginalSize, estimatedFirstHalfSize, estimatedSecondHalfSize);4221if (ZSTD_isError(estimatedOriginalSize) || ZSTD_isError(estimatedFirstHalfSize) || ZSTD_isError(estimatedSecondHalfSize)) {4222return;4223}4224if (estimatedFirstHalfSize + estimatedSecondHalfSize < estimatedOriginalSize) {4225DEBUGLOG(5, "split decided at seqNb:%zu", midIdx);4226ZSTD_deriveBlockSplitsHelper(splits, startIdx, midIdx, zc, origSeqStore);4227splits->splitLocations[splits->idx] = (U32)midIdx;4228splits->idx++;4229ZSTD_deriveBlockSplitsHelper(splits, midIdx, endIdx, zc, origSeqStore);4230}4231}42324233/* Base recursive function.4234* Populates a table with intra-block partition indices that can improve compression ratio.4235*4236* @return: number of splits made (which equals the size of the partition table - 1).4237*/4238static size_t ZSTD_deriveBlockSplits(ZSTD_CCtx* zc, U32 partitions[], U32 nbSeq)4239{4240seqStoreSplits splits;4241splits.splitLocations = partitions;4242splits.idx = 0;4243if (nbSeq <= 4) {4244DEBUGLOG(5, "ZSTD_deriveBlockSplits: Too few sequences to split (%u <= 4)", nbSeq);4245/* Refuse to try and split anything with less than 4 sequences */4246return 0;4247}4248ZSTD_deriveBlockSplitsHelper(&splits, 0, nbSeq, zc, &zc->seqStore);4249splits.splitLocations[splits.idx] = nbSeq;4250DEBUGLOG(5, "ZSTD_deriveBlockSplits: final nb partitions: %zu", splits.idx+1);4251return splits.idx;4252}42534254/* ZSTD_compressBlock_splitBlock():4255* Attempts to split a given block into multiple blocks to improve compression ratio.4256*4257* Returns combined size of all blocks (which includes headers), or a ZSTD error code.4258*/4259static size_t4260ZSTD_compressBlock_splitBlock_internal(ZSTD_CCtx* zc,4261void* dst, size_t dstCapacity,4262const void* src, size_t blockSize,4263U32 lastBlock, U32 nbSeq)4264{4265size_t cSize = 0;4266const BYTE* ip = (const BYTE*)src;4267BYTE* op = (BYTE*)dst;4268size_t i = 0;4269size_t srcBytesTotal = 0;4270U32* const partitions = zc->blockSplitCtx.partitions; /* size == ZSTD_MAX_NB_BLOCK_SPLITS */4271SeqStore_t* const nextSeqStore = &zc->blockSplitCtx.nextSeqStore;4272SeqStore_t* const currSeqStore = &zc->blockSplitCtx.currSeqStore;4273size_t const numSplits = ZSTD_deriveBlockSplits(zc, partitions, nbSeq);42744275/* If a block is split and some partitions are emitted as RLE/uncompressed, then repcode history4276* may become invalid. In order to reconcile potentially invalid repcodes, we keep track of two4277* separate repcode histories that simulate repcode history on compression and decompression side,4278* and use the histories to determine whether we must replace a particular repcode with its raw offset.4279*4280* 1) cRep gets updated for each partition, regardless of whether the block was emitted as uncompressed4281* or RLE. This allows us to retrieve the offset value that an invalid repcode references within4282* a nocompress/RLE block.4283* 2) dRep gets updated only for compressed partitions, and when a repcode gets replaced, will use4284* the replacement offset value rather than the original repcode to update the repcode history.4285* dRep also will be the final repcode history sent to the next block.4286*4287* See ZSTD_seqStore_resolveOffCodes() for more details.4288*/4289Repcodes_t dRep;4290Repcodes_t cRep;4291ZSTD_memcpy(dRep.rep, zc->blockState.prevCBlock->rep, sizeof(Repcodes_t));4292ZSTD_memcpy(cRep.rep, zc->blockState.prevCBlock->rep, sizeof(Repcodes_t));4293ZSTD_memset(nextSeqStore, 0, sizeof(SeqStore_t));42944295DEBUGLOG(5, "ZSTD_compressBlock_splitBlock_internal (dstCapacity=%u, dictLimit=%u, nextToUpdate=%u)",4296(unsigned)dstCapacity, (unsigned)zc->blockState.matchState.window.dictLimit,4297(unsigned)zc->blockState.matchState.nextToUpdate);42984299if (numSplits == 0) {4300size_t cSizeSingleBlock =4301ZSTD_compressSeqStore_singleBlock(zc, &zc->seqStore,4302&dRep, &cRep,4303op, dstCapacity,4304ip, blockSize,4305lastBlock, 0 /* isPartition */);4306FORWARD_IF_ERROR(cSizeSingleBlock, "Compressing single block from splitBlock_internal() failed!");4307DEBUGLOG(5, "ZSTD_compressBlock_splitBlock_internal: No splits");4308assert(zc->blockSizeMax <= ZSTD_BLOCKSIZE_MAX);4309assert(cSizeSingleBlock <= zc->blockSizeMax + ZSTD_blockHeaderSize);4310return cSizeSingleBlock;4311}43124313ZSTD_deriveSeqStoreChunk(currSeqStore, &zc->seqStore, 0, partitions[0]);4314for (i = 0; i <= numSplits; ++i) {4315size_t cSizeChunk;4316U32 const lastPartition = (i == numSplits);4317U32 lastBlockEntireSrc = 0;43184319size_t srcBytes = ZSTD_countSeqStoreLiteralsBytes(currSeqStore) + ZSTD_countSeqStoreMatchBytes(currSeqStore);4320srcBytesTotal += srcBytes;4321if (lastPartition) {4322/* This is the final partition, need to account for possible last literals */4323srcBytes += blockSize - srcBytesTotal;4324lastBlockEntireSrc = lastBlock;4325} else {4326ZSTD_deriveSeqStoreChunk(nextSeqStore, &zc->seqStore, partitions[i], partitions[i+1]);4327}43284329cSizeChunk = ZSTD_compressSeqStore_singleBlock(zc, currSeqStore,4330&dRep, &cRep,4331op, dstCapacity,4332ip, srcBytes,4333lastBlockEntireSrc, 1 /* isPartition */);4334DEBUGLOG(5, "Estimated size: %zu vs %zu : actual size",4335ZSTD_buildEntropyStatisticsAndEstimateSubBlockSize(currSeqStore, zc), cSizeChunk);4336FORWARD_IF_ERROR(cSizeChunk, "Compressing chunk failed!");43374338ip += srcBytes;4339op += cSizeChunk;4340dstCapacity -= cSizeChunk;4341cSize += cSizeChunk;4342*currSeqStore = *nextSeqStore;4343assert(cSizeChunk <= zc->blockSizeMax + ZSTD_blockHeaderSize);4344}4345/* cRep and dRep may have diverged during the compression.4346* If so, we use the dRep repcodes for the next block.4347*/4348ZSTD_memcpy(zc->blockState.prevCBlock->rep, dRep.rep, sizeof(Repcodes_t));4349return cSize;4350}43514352static size_t4353ZSTD_compressBlock_splitBlock(ZSTD_CCtx* zc,4354void* dst, size_t dstCapacity,4355const void* src, size_t srcSize, U32 lastBlock)4356{4357U32 nbSeq;4358size_t cSize;4359DEBUGLOG(5, "ZSTD_compressBlock_splitBlock");4360assert(zc->appliedParams.postBlockSplitter == ZSTD_ps_enable);43614362{ const size_t bss = ZSTD_buildSeqStore(zc, src, srcSize);4363FORWARD_IF_ERROR(bss, "ZSTD_buildSeqStore failed");4364if (bss == ZSTDbss_noCompress) {4365if (zc->blockState.prevCBlock->entropy.fse.offcode_repeatMode == FSE_repeat_valid)4366zc->blockState.prevCBlock->entropy.fse.offcode_repeatMode = FSE_repeat_check;4367RETURN_ERROR_IF(zc->seqCollector.collectSequences, sequenceProducer_failed, "Uncompressible block");4368cSize = ZSTD_noCompressBlock(dst, dstCapacity, src, srcSize, lastBlock);4369FORWARD_IF_ERROR(cSize, "ZSTD_noCompressBlock failed");4370DEBUGLOG(5, "ZSTD_compressBlock_splitBlock: Nocompress block");4371return cSize;4372}4373nbSeq = (U32)(zc->seqStore.sequences - zc->seqStore.sequencesStart);4374}43754376cSize = ZSTD_compressBlock_splitBlock_internal(zc, dst, dstCapacity, src, srcSize, lastBlock, nbSeq);4377FORWARD_IF_ERROR(cSize, "Splitting blocks failed!");4378return cSize;4379}43804381static size_t4382ZSTD_compressBlock_internal(ZSTD_CCtx* zc,4383void* dst, size_t dstCapacity,4384const void* src, size_t srcSize, U32 frame)4385{4386/* This is an estimated upper bound for the length of an rle block.4387* This isn't the actual upper bound.4388* Finding the real threshold needs further investigation.4389*/4390const U32 rleMaxLength = 25;4391size_t cSize;4392const BYTE* ip = (const BYTE*)src;4393BYTE* op = (BYTE*)dst;4394DEBUGLOG(5, "ZSTD_compressBlock_internal (dstCapacity=%u, dictLimit=%u, nextToUpdate=%u)",4395(unsigned)dstCapacity, (unsigned)zc->blockState.matchState.window.dictLimit,4396(unsigned)zc->blockState.matchState.nextToUpdate);43974398{ const size_t bss = ZSTD_buildSeqStore(zc, src, srcSize);4399FORWARD_IF_ERROR(bss, "ZSTD_buildSeqStore failed");4400if (bss == ZSTDbss_noCompress) {4401RETURN_ERROR_IF(zc->seqCollector.collectSequences, sequenceProducer_failed, "Uncompressible block");4402cSize = 0;4403goto out;4404}4405}44064407if (zc->seqCollector.collectSequences) {4408FORWARD_IF_ERROR(ZSTD_copyBlockSequences(&zc->seqCollector, ZSTD_getSeqStore(zc), zc->blockState.prevCBlock->rep), "copyBlockSequences failed");4409ZSTD_blockState_confirmRepcodesAndEntropyTables(&zc->blockState);4410return 0;4411}44124413/* encode sequences and literals */4414cSize = ZSTD_entropyCompressSeqStore(&zc->seqStore,4415&zc->blockState.prevCBlock->entropy, &zc->blockState.nextCBlock->entropy,4416&zc->appliedParams,4417dst, dstCapacity,4418srcSize,4419zc->tmpWorkspace, zc->tmpWkspSize /* statically allocated in resetCCtx */,4420zc->bmi2);44214422if (frame &&4423/* We don't want to emit our first block as a RLE even if it qualifies because4424* doing so will cause the decoder (cli only) to throw a "should consume all input error."4425* This is only an issue for zstd <= v1.4.34426*/4427!zc->isFirstBlock &&4428cSize < rleMaxLength &&4429ZSTD_isRLE(ip, srcSize))4430{4431cSize = 1;4432op[0] = ip[0];4433}44344435out:4436if (!ZSTD_isError(cSize) && cSize > 1) {4437ZSTD_blockState_confirmRepcodesAndEntropyTables(&zc->blockState);4438}4439/* We check that dictionaries have offset codes available for the first4440* block. After the first block, the offcode table might not have large4441* enough codes to represent the offsets in the data.4442*/4443if (zc->blockState.prevCBlock->entropy.fse.offcode_repeatMode == FSE_repeat_valid)4444zc->blockState.prevCBlock->entropy.fse.offcode_repeatMode = FSE_repeat_check;44454446return cSize;4447}44484449static size_t ZSTD_compressBlock_targetCBlockSize_body(ZSTD_CCtx* zc,4450void* dst, size_t dstCapacity,4451const void* src, size_t srcSize,4452const size_t bss, U32 lastBlock)4453{4454DEBUGLOG(6, "Attempting ZSTD_compressSuperBlock()");4455if (bss == ZSTDbss_compress) {4456if (/* We don't want to emit our first block as a RLE even if it qualifies because4457* doing so will cause the decoder (cli only) to throw a "should consume all input error."4458* This is only an issue for zstd <= v1.4.34459*/4460!zc->isFirstBlock &&4461ZSTD_maybeRLE(&zc->seqStore) &&4462ZSTD_isRLE((BYTE const*)src, srcSize))4463{4464return ZSTD_rleCompressBlock(dst, dstCapacity, *(BYTE const*)src, srcSize, lastBlock);4465}4466/* Attempt superblock compression.4467*4468* Note that compressed size of ZSTD_compressSuperBlock() is not bound by the4469* standard ZSTD_compressBound(). This is a problem, because even if we have4470* space now, taking an extra byte now could cause us to run out of space later4471* and violate ZSTD_compressBound().4472*4473* Define blockBound(blockSize) = blockSize + ZSTD_blockHeaderSize.4474*4475* In order to respect ZSTD_compressBound() we must attempt to emit a raw4476* uncompressed block in these cases:4477* * cSize == 0: Return code for an uncompressed block.4478* * cSize == dstSize_tooSmall: We may have expanded beyond blockBound(srcSize).4479* ZSTD_noCompressBlock() will return dstSize_tooSmall if we are really out of4480* output space.4481* * cSize >= blockBound(srcSize): We have expanded the block too much so4482* emit an uncompressed block.4483*/4484{ size_t const cSize =4485ZSTD_compressSuperBlock(zc, dst, dstCapacity, src, srcSize, lastBlock);4486if (cSize != ERROR(dstSize_tooSmall)) {4487size_t const maxCSize =4488srcSize - ZSTD_minGain(srcSize, zc->appliedParams.cParams.strategy);4489FORWARD_IF_ERROR(cSize, "ZSTD_compressSuperBlock failed");4490if (cSize != 0 && cSize < maxCSize + ZSTD_blockHeaderSize) {4491ZSTD_blockState_confirmRepcodesAndEntropyTables(&zc->blockState);4492return cSize;4493}4494}4495}4496} /* if (bss == ZSTDbss_compress)*/44974498DEBUGLOG(6, "Resorting to ZSTD_noCompressBlock()");4499/* Superblock compression failed, attempt to emit a single no compress block.4500* The decoder will be able to stream this block since it is uncompressed.4501*/4502return ZSTD_noCompressBlock(dst, dstCapacity, src, srcSize, lastBlock);4503}45044505static size_t ZSTD_compressBlock_targetCBlockSize(ZSTD_CCtx* zc,4506void* dst, size_t dstCapacity,4507const void* src, size_t srcSize,4508U32 lastBlock)4509{4510size_t cSize = 0;4511const size_t bss = ZSTD_buildSeqStore(zc, src, srcSize);4512DEBUGLOG(5, "ZSTD_compressBlock_targetCBlockSize (dstCapacity=%u, dictLimit=%u, nextToUpdate=%u, srcSize=%zu)",4513(unsigned)dstCapacity, (unsigned)zc->blockState.matchState.window.dictLimit, (unsigned)zc->blockState.matchState.nextToUpdate, srcSize);4514FORWARD_IF_ERROR(bss, "ZSTD_buildSeqStore failed");45154516cSize = ZSTD_compressBlock_targetCBlockSize_body(zc, dst, dstCapacity, src, srcSize, bss, lastBlock);4517FORWARD_IF_ERROR(cSize, "ZSTD_compressBlock_targetCBlockSize_body failed");45184519if (zc->blockState.prevCBlock->entropy.fse.offcode_repeatMode == FSE_repeat_valid)4520zc->blockState.prevCBlock->entropy.fse.offcode_repeatMode = FSE_repeat_check;45214522return cSize;4523}45244525static void ZSTD_overflowCorrectIfNeeded(ZSTD_MatchState_t* ms,4526ZSTD_cwksp* ws,4527ZSTD_CCtx_params const* params,4528void const* ip,4529void const* iend)4530{4531U32 const cycleLog = ZSTD_cycleLog(params->cParams.chainLog, params->cParams.strategy);4532U32 const maxDist = (U32)1 << params->cParams.windowLog;4533if (ZSTD_window_needOverflowCorrection(ms->window, cycleLog, maxDist, ms->loadedDictEnd, ip, iend)) {4534U32 const correction = ZSTD_window_correctOverflow(&ms->window, cycleLog, maxDist, ip);4535ZSTD_STATIC_ASSERT(ZSTD_CHAINLOG_MAX <= 30);4536ZSTD_STATIC_ASSERT(ZSTD_WINDOWLOG_MAX_32 <= 30);4537ZSTD_STATIC_ASSERT(ZSTD_WINDOWLOG_MAX <= 31);4538ZSTD_cwksp_mark_tables_dirty(ws);4539ZSTD_reduceIndex(ms, params, correction);4540ZSTD_cwksp_mark_tables_clean(ws);4541if (ms->nextToUpdate < correction) ms->nextToUpdate = 0;4542else ms->nextToUpdate -= correction;4543/* invalidate dictionaries on overflow correction */4544ms->loadedDictEnd = 0;4545ms->dictMatchState = NULL;4546}4547}45484549#include "zstd_preSplit.h"45504551static size_t ZSTD_optimalBlockSize(ZSTD_CCtx* cctx, const void* src, size_t srcSize, size_t blockSizeMax, int splitLevel, ZSTD_strategy strat, S64 savings)4552{4553/* split level based on compression strategy, from `fast` to `btultra2` */4554static const int splitLevels[] = { 0, 0, 1, 2, 2, 3, 3, 4, 4, 4 };4555/* note: conservatively only split full blocks (128 KB) currently.4556* While it's possible to go lower, let's keep it simple for a first implementation.4557* Besides, benefits of splitting are reduced when blocks are already small.4558*/4559if (srcSize < 128 KB || blockSizeMax < 128 KB)4560return MIN(srcSize, blockSizeMax);4561/* do not split incompressible data though:4562* require verified savings to allow pre-splitting.4563* Note: as a consequence, the first full block is not split.4564*/4565if (savings < 3) {4566DEBUGLOG(6, "don't attempt splitting: savings (%i) too low", (int)savings);4567return 128 KB;4568}4569/* apply @splitLevel, or use default value (which depends on @strat).4570* note that splitting heuristic is still conditioned by @savings >= 3,4571* so the first block will not reach this code path */4572if (splitLevel == 1) return 128 KB;4573if (splitLevel == 0) {4574assert(ZSTD_fast <= strat && strat <= ZSTD_btultra2);4575splitLevel = splitLevels[strat];4576} else {4577assert(2 <= splitLevel && splitLevel <= 6);4578splitLevel -= 2;4579}4580return ZSTD_splitBlock(src, blockSizeMax, splitLevel, cctx->tmpWorkspace, cctx->tmpWkspSize);4581}45824583/*! ZSTD_compress_frameChunk() :4584* Compress a chunk of data into one or multiple blocks.4585* All blocks will be terminated, all input will be consumed.4586* Function will issue an error if there is not enough `dstCapacity` to hold the compressed content.4587* Frame is supposed already started (header already produced)4588* @return : compressed size, or an error code4589*/4590static size_t ZSTD_compress_frameChunk(ZSTD_CCtx* cctx,4591void* dst, size_t dstCapacity,4592const void* src, size_t srcSize,4593U32 lastFrameChunk)4594{4595size_t blockSizeMax = cctx->blockSizeMax;4596size_t remaining = srcSize;4597const BYTE* ip = (const BYTE*)src;4598BYTE* const ostart = (BYTE*)dst;4599BYTE* op = ostart;4600U32 const maxDist = (U32)1 << cctx->appliedParams.cParams.windowLog;4601S64 savings = (S64)cctx->consumedSrcSize - (S64)cctx->producedCSize;46024603assert(cctx->appliedParams.cParams.windowLog <= ZSTD_WINDOWLOG_MAX);46044605DEBUGLOG(5, "ZSTD_compress_frameChunk (srcSize=%u, blockSizeMax=%u)", (unsigned)srcSize, (unsigned)blockSizeMax);4606if (cctx->appliedParams.fParams.checksumFlag && srcSize)4607XXH64_update(&cctx->xxhState, src, srcSize);46084609while (remaining) {4610ZSTD_MatchState_t* const ms = &cctx->blockState.matchState;4611size_t const blockSize = ZSTD_optimalBlockSize(cctx,4612ip, remaining,4613blockSizeMax,4614cctx->appliedParams.preBlockSplitter_level,4615cctx->appliedParams.cParams.strategy,4616savings);4617U32 const lastBlock = lastFrameChunk & (blockSize == remaining);4618assert(blockSize <= remaining);46194620/* TODO: See 3090. We reduced MIN_CBLOCK_SIZE from 3 to 2 so to compensate we are adding4621* additional 1. We need to revisit and change this logic to be more consistent */4622RETURN_ERROR_IF(dstCapacity < ZSTD_blockHeaderSize + MIN_CBLOCK_SIZE + 1,4623dstSize_tooSmall,4624"not enough space to store compressed block");46254626ZSTD_overflowCorrectIfNeeded(4627ms, &cctx->workspace, &cctx->appliedParams, ip, ip + blockSize);4628ZSTD_checkDictValidity(&ms->window, ip + blockSize, maxDist, &ms->loadedDictEnd, &ms->dictMatchState);4629ZSTD_window_enforceMaxDist(&ms->window, ip, maxDist, &ms->loadedDictEnd, &ms->dictMatchState);46304631/* Ensure hash/chain table insertion resumes no sooner than lowlimit */4632if (ms->nextToUpdate < ms->window.lowLimit) ms->nextToUpdate = ms->window.lowLimit;46334634{ size_t cSize;4635if (ZSTD_useTargetCBlockSize(&cctx->appliedParams)) {4636cSize = ZSTD_compressBlock_targetCBlockSize(cctx, op, dstCapacity, ip, blockSize, lastBlock);4637FORWARD_IF_ERROR(cSize, "ZSTD_compressBlock_targetCBlockSize failed");4638assert(cSize > 0);4639assert(cSize <= blockSize + ZSTD_blockHeaderSize);4640} else if (ZSTD_blockSplitterEnabled(&cctx->appliedParams)) {4641cSize = ZSTD_compressBlock_splitBlock(cctx, op, dstCapacity, ip, blockSize, lastBlock);4642FORWARD_IF_ERROR(cSize, "ZSTD_compressBlock_splitBlock failed");4643assert(cSize > 0 || cctx->seqCollector.collectSequences == 1);4644} else {4645cSize = ZSTD_compressBlock_internal(cctx,4646op+ZSTD_blockHeaderSize, dstCapacity-ZSTD_blockHeaderSize,4647ip, blockSize, 1 /* frame */);4648FORWARD_IF_ERROR(cSize, "ZSTD_compressBlock_internal failed");46494650if (cSize == 0) { /* block is not compressible */4651cSize = ZSTD_noCompressBlock(op, dstCapacity, ip, blockSize, lastBlock);4652FORWARD_IF_ERROR(cSize, "ZSTD_noCompressBlock failed");4653} else {4654U32 const cBlockHeader = cSize == 1 ?4655lastBlock + (((U32)bt_rle)<<1) + (U32)(blockSize << 3) :4656lastBlock + (((U32)bt_compressed)<<1) + (U32)(cSize << 3);4657MEM_writeLE24(op, cBlockHeader);4658cSize += ZSTD_blockHeaderSize;4659}4660} /* if (ZSTD_useTargetCBlockSize(&cctx->appliedParams))*/46614662/* @savings is employed to ensure that splitting doesn't worsen expansion of incompressible data.4663* Without splitting, the maximum expansion is 3 bytes per full block.4664* An adversarial input could attempt to fudge the split detector,4665* and make it split incompressible data, resulting in more block headers.4666* Note that, since ZSTD_COMPRESSBOUND() assumes a worst case scenario of 1KB per block,4667* and the splitter never creates blocks that small (current lower limit is 8 KB),4668* there is already no risk to expand beyond ZSTD_COMPRESSBOUND() limit.4669* But if the goal is to not expand by more than 3-bytes per 128 KB full block,4670* then yes, it becomes possible to make the block splitter oversplit incompressible data.4671* Using @savings, we enforce an even more conservative condition,4672* requiring the presence of enough savings (at least 3 bytes) to authorize splitting,4673* otherwise only full blocks are used.4674* But being conservative is fine,4675* since splitting barely compressible blocks is not fruitful anyway */4676savings += (S64)blockSize - (S64)cSize;46774678ip += blockSize;4679assert(remaining >= blockSize);4680remaining -= blockSize;4681op += cSize;4682assert(dstCapacity >= cSize);4683dstCapacity -= cSize;4684cctx->isFirstBlock = 0;4685DEBUGLOG(5, "ZSTD_compress_frameChunk: adding a block of size %u",4686(unsigned)cSize);4687} }46884689if (lastFrameChunk && (op>ostart)) cctx->stage = ZSTDcs_ending;4690return (size_t)(op-ostart);4691}469246934694static size_t ZSTD_writeFrameHeader(void* dst, size_t dstCapacity,4695const ZSTD_CCtx_params* params,4696U64 pledgedSrcSize, U32 dictID)4697{4698BYTE* const op = (BYTE*)dst;4699U32 const dictIDSizeCodeLength = (dictID>0) + (dictID>=256) + (dictID>=65536); /* 0-3 */4700U32 const dictIDSizeCode = params->fParams.noDictIDFlag ? 0 : dictIDSizeCodeLength; /* 0-3 */4701U32 const checksumFlag = params->fParams.checksumFlag>0;4702U32 const windowSize = (U32)1 << params->cParams.windowLog;4703U32 const singleSegment = params->fParams.contentSizeFlag && (windowSize >= pledgedSrcSize);4704BYTE const windowLogByte = (BYTE)((params->cParams.windowLog - ZSTD_WINDOWLOG_ABSOLUTEMIN) << 3);4705U32 const fcsCode = params->fParams.contentSizeFlag ?4706(pledgedSrcSize>=256) + (pledgedSrcSize>=65536+256) + (pledgedSrcSize>=0xFFFFFFFFU) : 0; /* 0-3 */4707BYTE const frameHeaderDescriptionByte = (BYTE)(dictIDSizeCode + (checksumFlag<<2) + (singleSegment<<5) + (fcsCode<<6) );4708size_t pos=0;47094710assert(!(params->fParams.contentSizeFlag && pledgedSrcSize == ZSTD_CONTENTSIZE_UNKNOWN));4711RETURN_ERROR_IF(dstCapacity < ZSTD_FRAMEHEADERSIZE_MAX, dstSize_tooSmall,4712"dst buf is too small to fit worst-case frame header size.");4713DEBUGLOG(4, "ZSTD_writeFrameHeader : dictIDFlag : %u ; dictID : %u ; dictIDSizeCode : %u",4714!params->fParams.noDictIDFlag, (unsigned)dictID, (unsigned)dictIDSizeCode);4715if (params->format == ZSTD_f_zstd1) {4716MEM_writeLE32(dst, ZSTD_MAGICNUMBER);4717pos = 4;4718}4719op[pos++] = frameHeaderDescriptionByte;4720if (!singleSegment) op[pos++] = windowLogByte;4721switch(dictIDSizeCode)4722{4723default:4724assert(0); /* impossible */4725ZSTD_FALLTHROUGH;4726case 0 : break;4727case 1 : op[pos] = (BYTE)(dictID); pos++; break;4728case 2 : MEM_writeLE16(op+pos, (U16)dictID); pos+=2; break;4729case 3 : MEM_writeLE32(op+pos, dictID); pos+=4; break;4730}4731switch(fcsCode)4732{4733default:4734assert(0); /* impossible */4735ZSTD_FALLTHROUGH;4736case 0 : if (singleSegment) op[pos++] = (BYTE)(pledgedSrcSize); break;4737case 1 : MEM_writeLE16(op+pos, (U16)(pledgedSrcSize-256)); pos+=2; break;4738case 2 : MEM_writeLE32(op+pos, (U32)(pledgedSrcSize)); pos+=4; break;4739case 3 : MEM_writeLE64(op+pos, (U64)(pledgedSrcSize)); pos+=8; break;4740}4741return pos;4742}47434744/* ZSTD_writeSkippableFrame_advanced() :4745* Writes out a skippable frame with the specified magic number variant (16 are supported),4746* from ZSTD_MAGIC_SKIPPABLE_START to ZSTD_MAGIC_SKIPPABLE_START+15, and the desired source data.4747*4748* Returns the total number of bytes written, or a ZSTD error code.4749*/4750size_t ZSTD_writeSkippableFrame(void* dst, size_t dstCapacity,4751const void* src, size_t srcSize, unsigned magicVariant) {4752BYTE* op = (BYTE*)dst;4753RETURN_ERROR_IF(dstCapacity < srcSize + ZSTD_SKIPPABLEHEADERSIZE /* Skippable frame overhead */,4754dstSize_tooSmall, "Not enough room for skippable frame");4755RETURN_ERROR_IF(srcSize > (unsigned)0xFFFFFFFF, srcSize_wrong, "Src size too large for skippable frame");4756RETURN_ERROR_IF(magicVariant > 15, parameter_outOfBound, "Skippable frame magic number variant not supported");47574758MEM_writeLE32(op, (U32)(ZSTD_MAGIC_SKIPPABLE_START + magicVariant));4759MEM_writeLE32(op+4, (U32)srcSize);4760ZSTD_memcpy(op+8, src, srcSize);4761return srcSize + ZSTD_SKIPPABLEHEADERSIZE;4762}47634764/* ZSTD_writeLastEmptyBlock() :4765* output an empty Block with end-of-frame mark to complete a frame4766* @return : size of data written into `dst` (== ZSTD_blockHeaderSize (defined in zstd_internal.h))4767* or an error code if `dstCapacity` is too small (<ZSTD_blockHeaderSize)4768*/4769size_t ZSTD_writeLastEmptyBlock(void* dst, size_t dstCapacity)4770{4771RETURN_ERROR_IF(dstCapacity < ZSTD_blockHeaderSize, dstSize_tooSmall,4772"dst buf is too small to write frame trailer empty block.");4773{ U32 const cBlockHeader24 = 1 /*lastBlock*/ + (((U32)bt_raw)<<1); /* 0 size */4774MEM_writeLE24(dst, cBlockHeader24);4775return ZSTD_blockHeaderSize;4776}4777}47784779void ZSTD_referenceExternalSequences(ZSTD_CCtx* cctx, rawSeq* seq, size_t nbSeq)4780{4781assert(cctx->stage == ZSTDcs_init);4782assert(nbSeq == 0 || cctx->appliedParams.ldmParams.enableLdm != ZSTD_ps_enable);4783cctx->externSeqStore.seq = seq;4784cctx->externSeqStore.size = nbSeq;4785cctx->externSeqStore.capacity = nbSeq;4786cctx->externSeqStore.pos = 0;4787cctx->externSeqStore.posInSequence = 0;4788}478947904791static size_t ZSTD_compressContinue_internal (ZSTD_CCtx* cctx,4792void* dst, size_t dstCapacity,4793const void* src, size_t srcSize,4794U32 frame, U32 lastFrameChunk)4795{4796ZSTD_MatchState_t* const ms = &cctx->blockState.matchState;4797size_t fhSize = 0;47984799DEBUGLOG(5, "ZSTD_compressContinue_internal, stage: %u, srcSize: %u",4800cctx->stage, (unsigned)srcSize);4801RETURN_ERROR_IF(cctx->stage==ZSTDcs_created, stage_wrong,4802"missing init (ZSTD_compressBegin)");48034804if (frame && (cctx->stage==ZSTDcs_init)) {4805fhSize = ZSTD_writeFrameHeader(dst, dstCapacity, &cctx->appliedParams,4806cctx->pledgedSrcSizePlusOne-1, cctx->dictID);4807FORWARD_IF_ERROR(fhSize, "ZSTD_writeFrameHeader failed");4808assert(fhSize <= dstCapacity);4809dstCapacity -= fhSize;4810dst = (char*)dst + fhSize;4811cctx->stage = ZSTDcs_ongoing;4812}48134814if (!srcSize) return fhSize; /* do not generate an empty block if no input */48154816if (!ZSTD_window_update(&ms->window, src, srcSize, ms->forceNonContiguous)) {4817ms->forceNonContiguous = 0;4818ms->nextToUpdate = ms->window.dictLimit;4819}4820if (cctx->appliedParams.ldmParams.enableLdm == ZSTD_ps_enable) {4821ZSTD_window_update(&cctx->ldmState.window, src, srcSize, /* forceNonContiguous */ 0);4822}48234824if (!frame) {4825/* overflow check and correction for block mode */4826ZSTD_overflowCorrectIfNeeded(4827ms, &cctx->workspace, &cctx->appliedParams,4828src, (BYTE const*)src + srcSize);4829}48304831DEBUGLOG(5, "ZSTD_compressContinue_internal (blockSize=%u)", (unsigned)cctx->blockSizeMax);4832{ size_t const cSize = frame ?4833ZSTD_compress_frameChunk (cctx, dst, dstCapacity, src, srcSize, lastFrameChunk) :4834ZSTD_compressBlock_internal (cctx, dst, dstCapacity, src, srcSize, 0 /* frame */);4835FORWARD_IF_ERROR(cSize, "%s", frame ? "ZSTD_compress_frameChunk failed" : "ZSTD_compressBlock_internal failed");4836cctx->consumedSrcSize += srcSize;4837cctx->producedCSize += (cSize + fhSize);4838assert(!(cctx->appliedParams.fParams.contentSizeFlag && cctx->pledgedSrcSizePlusOne == 0));4839if (cctx->pledgedSrcSizePlusOne != 0) { /* control src size */4840ZSTD_STATIC_ASSERT(ZSTD_CONTENTSIZE_UNKNOWN == (unsigned long long)-1);4841RETURN_ERROR_IF(4842cctx->consumedSrcSize+1 > cctx->pledgedSrcSizePlusOne,4843srcSize_wrong,4844"error : pledgedSrcSize = %u, while realSrcSize >= %u",4845(unsigned)cctx->pledgedSrcSizePlusOne-1,4846(unsigned)cctx->consumedSrcSize);4847}4848return cSize + fhSize;4849}4850}48514852size_t ZSTD_compressContinue_public(ZSTD_CCtx* cctx,4853void* dst, size_t dstCapacity,4854const void* src, size_t srcSize)4855{4856DEBUGLOG(5, "ZSTD_compressContinue (srcSize=%u)", (unsigned)srcSize);4857return ZSTD_compressContinue_internal(cctx, dst, dstCapacity, src, srcSize, 1 /* frame mode */, 0 /* last chunk */);4858}48594860/* NOTE: Must just wrap ZSTD_compressContinue_public() */4861size_t ZSTD_compressContinue(ZSTD_CCtx* cctx,4862void* dst, size_t dstCapacity,4863const void* src, size_t srcSize)4864{4865return ZSTD_compressContinue_public(cctx, dst, dstCapacity, src, srcSize);4866}48674868static size_t ZSTD_getBlockSize_deprecated(const ZSTD_CCtx* cctx)4869{4870ZSTD_compressionParameters const cParams = cctx->appliedParams.cParams;4871assert(!ZSTD_checkCParams(cParams));4872return MIN(cctx->appliedParams.maxBlockSize, (size_t)1 << cParams.windowLog);4873}48744875/* NOTE: Must just wrap ZSTD_getBlockSize_deprecated() */4876size_t ZSTD_getBlockSize(const ZSTD_CCtx* cctx)4877{4878return ZSTD_getBlockSize_deprecated(cctx);4879}48804881/* NOTE: Must just wrap ZSTD_compressBlock_deprecated() */4882size_t ZSTD_compressBlock_deprecated(ZSTD_CCtx* cctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize)4883{4884DEBUGLOG(5, "ZSTD_compressBlock: srcSize = %u", (unsigned)srcSize);4885{ size_t const blockSizeMax = ZSTD_getBlockSize_deprecated(cctx);4886RETURN_ERROR_IF(srcSize > blockSizeMax, srcSize_wrong, "input is larger than a block"); }48874888return ZSTD_compressContinue_internal(cctx, dst, dstCapacity, src, srcSize, 0 /* frame mode */, 0 /* last chunk */);4889}48904891/* NOTE: Must just wrap ZSTD_compressBlock_deprecated() */4892size_t ZSTD_compressBlock(ZSTD_CCtx* cctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize)4893{4894return ZSTD_compressBlock_deprecated(cctx, dst, dstCapacity, src, srcSize);4895}48964897/*! ZSTD_loadDictionaryContent() :4898* @return : 0, or an error code4899*/4900static size_t4901ZSTD_loadDictionaryContent(ZSTD_MatchState_t* ms,4902ldmState_t* ls,4903ZSTD_cwksp* ws,4904ZSTD_CCtx_params const* params,4905const void* src, size_t srcSize,4906ZSTD_dictTableLoadMethod_e dtlm,4907ZSTD_tableFillPurpose_e tfp)4908{4909const BYTE* ip = (const BYTE*) src;4910const BYTE* const iend = ip + srcSize;4911int const loadLdmDict = params->ldmParams.enableLdm == ZSTD_ps_enable && ls != NULL;49124913/* Assert that the ms params match the params we're being given */4914ZSTD_assertEqualCParams(params->cParams, ms->cParams);49154916{ /* Ensure large dictionaries can't cause index overflow */49174918/* Allow the dictionary to set indices up to exactly ZSTD_CURRENT_MAX.4919* Dictionaries right at the edge will immediately trigger overflow4920* correction, but I don't want to insert extra constraints here.4921*/4922U32 maxDictSize = ZSTD_CURRENT_MAX - ZSTD_WINDOW_START_INDEX;49234924int const CDictTaggedIndices = ZSTD_CDictIndicesAreTagged(¶ms->cParams);4925if (CDictTaggedIndices && tfp == ZSTD_tfp_forCDict) {4926/* Some dictionary matchfinders in zstd use "short cache",4927* which treats the lower ZSTD_SHORT_CACHE_TAG_BITS of each4928* CDict hashtable entry as a tag rather than as part of an index.4929* When short cache is used, we need to truncate the dictionary4930* so that its indices don't overlap with the tag. */4931U32 const shortCacheMaxDictSize = (1u << (32 - ZSTD_SHORT_CACHE_TAG_BITS)) - ZSTD_WINDOW_START_INDEX;4932maxDictSize = MIN(maxDictSize, shortCacheMaxDictSize);4933assert(!loadLdmDict);4934}49354936/* If the dictionary is too large, only load the suffix of the dictionary. */4937if (srcSize > maxDictSize) {4938ip = iend - maxDictSize;4939src = ip;4940srcSize = maxDictSize;4941}4942}49434944if (srcSize > ZSTD_CHUNKSIZE_MAX) {4945/* We must have cleared our windows when our source is this large. */4946assert(ZSTD_window_isEmpty(ms->window));4947if (loadLdmDict) assert(ZSTD_window_isEmpty(ls->window));4948}4949ZSTD_window_update(&ms->window, src, srcSize, /* forceNonContiguous */ 0);49504951DEBUGLOG(4, "ZSTD_loadDictionaryContent: useRowMatchFinder=%d", (int)params->useRowMatchFinder);49524953if (loadLdmDict) { /* Load the entire dict into LDM matchfinders. */4954DEBUGLOG(4, "ZSTD_loadDictionaryContent: Trigger loadLdmDict");4955ZSTD_window_update(&ls->window, src, srcSize, /* forceNonContiguous */ 0);4956ls->loadedDictEnd = params->forceWindow ? 0 : (U32)(iend - ls->window.base);4957ZSTD_ldm_fillHashTable(ls, ip, iend, ¶ms->ldmParams);4958DEBUGLOG(4, "ZSTD_loadDictionaryContent: ZSTD_ldm_fillHashTable completes");4959}49604961/* If the dict is larger than we can reasonably index in our tables, only load the suffix. */4962{ U32 maxDictSize = 1U << MIN(MAX(params->cParams.hashLog + 3, params->cParams.chainLog + 1), 31);4963if (srcSize > maxDictSize) {4964ip = iend - maxDictSize;4965/* src = ip; deadcode.DeadStores */4966srcSize = maxDictSize;4967}4968}49694970ms->nextToUpdate = (U32)(ip - ms->window.base);4971ms->loadedDictEnd = params->forceWindow ? 0 : (U32)(iend - ms->window.base);4972ms->forceNonContiguous = params->deterministicRefPrefix;49734974if (srcSize <= HASH_READ_SIZE) return 0;49754976ZSTD_overflowCorrectIfNeeded(ms, ws, params, ip, iend);49774978switch(params->cParams.strategy)4979{4980case ZSTD_fast:4981ZSTD_fillHashTable(ms, iend, dtlm, tfp);4982break;4983case ZSTD_dfast:4984#ifndef ZSTD_EXCLUDE_DFAST_BLOCK_COMPRESSOR4985ZSTD_fillDoubleHashTable(ms, iend, dtlm, tfp);4986#else4987assert(0); /* shouldn't be called: cparams should've been adjusted. */4988#endif4989break;49904991case ZSTD_greedy:4992case ZSTD_lazy:4993case ZSTD_lazy2:4994#if !defined(ZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR) \4995|| !defined(ZSTD_EXCLUDE_LAZY_BLOCK_COMPRESSOR) \4996|| !defined(ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR)4997assert(srcSize >= HASH_READ_SIZE);4998if (ms->dedicatedDictSearch) {4999assert(ms->chainTable != NULL);5000ZSTD_dedicatedDictSearch_lazy_loadDictionary(ms, iend-HASH_READ_SIZE);5001} else {5002assert(params->useRowMatchFinder != ZSTD_ps_auto);5003if (params->useRowMatchFinder == ZSTD_ps_enable) {5004size_t const tagTableSize = ((size_t)1 << params->cParams.hashLog);5005ZSTD_memset(ms->tagTable, 0, tagTableSize);5006ZSTD_row_update(ms, iend-HASH_READ_SIZE);5007DEBUGLOG(4, "Using row-based hash table for lazy dict");5008} else {5009ZSTD_insertAndFindFirstIndex(ms, iend-HASH_READ_SIZE);5010DEBUGLOG(4, "Using chain-based hash table for lazy dict");5011}5012}5013#else5014assert(0); /* shouldn't be called: cparams should've been adjusted. */5015#endif5016break;50175018case ZSTD_btlazy2: /* we want the dictionary table fully sorted */5019case ZSTD_btopt:5020case ZSTD_btultra:5021case ZSTD_btultra2:5022#if !defined(ZSTD_EXCLUDE_BTLAZY2_BLOCK_COMPRESSOR) \5023|| !defined(ZSTD_EXCLUDE_BTOPT_BLOCK_COMPRESSOR) \5024|| !defined(ZSTD_EXCLUDE_BTULTRA_BLOCK_COMPRESSOR)5025assert(srcSize >= HASH_READ_SIZE);5026DEBUGLOG(4, "Fill %u bytes into the Binary Tree", (unsigned)srcSize);5027ZSTD_updateTree(ms, iend-HASH_READ_SIZE, iend);5028#else5029assert(0); /* shouldn't be called: cparams should've been adjusted. */5030#endif5031break;50325033default:5034assert(0); /* not possible : not a valid strategy id */5035}50365037ms->nextToUpdate = (U32)(iend - ms->window.base);5038return 0;5039}504050415042/* Dictionaries that assign zero probability to symbols that show up causes problems5043* when FSE encoding. Mark dictionaries with zero probability symbols as FSE_repeat_check5044* and only dictionaries with 100% valid symbols can be assumed valid.5045*/5046static FSE_repeat ZSTD_dictNCountRepeat(short* normalizedCounter, unsigned dictMaxSymbolValue, unsigned maxSymbolValue)5047{5048U32 s;5049if (dictMaxSymbolValue < maxSymbolValue) {5050return FSE_repeat_check;5051}5052for (s = 0; s <= maxSymbolValue; ++s) {5053if (normalizedCounter[s] == 0) {5054return FSE_repeat_check;5055}5056}5057return FSE_repeat_valid;5058}50595060size_t ZSTD_loadCEntropy(ZSTD_compressedBlockState_t* bs, void* workspace,5061const void* const dict, size_t dictSize)5062{5063short offcodeNCount[MaxOff+1];5064unsigned offcodeMaxValue = MaxOff;5065const BYTE* dictPtr = (const BYTE*)dict; /* skip magic num and dict ID */5066const BYTE* const dictEnd = dictPtr + dictSize;5067dictPtr += 8;5068bs->entropy.huf.repeatMode = HUF_repeat_check;50695070{ unsigned maxSymbolValue = 255;5071unsigned hasZeroWeights = 1;5072size_t const hufHeaderSize = HUF_readCTable((HUF_CElt*)bs->entropy.huf.CTable, &maxSymbolValue, dictPtr,5073(size_t)(dictEnd-dictPtr), &hasZeroWeights);50745075/* We only set the loaded table as valid if it contains all non-zero5076* weights. Otherwise, we set it to check */5077if (!hasZeroWeights && maxSymbolValue == 255)5078bs->entropy.huf.repeatMode = HUF_repeat_valid;50795080RETURN_ERROR_IF(HUF_isError(hufHeaderSize), dictionary_corrupted, "");5081dictPtr += hufHeaderSize;5082}50835084{ unsigned offcodeLog;5085size_t const offcodeHeaderSize = FSE_readNCount(offcodeNCount, &offcodeMaxValue, &offcodeLog, dictPtr, (size_t)(dictEnd-dictPtr));5086RETURN_ERROR_IF(FSE_isError(offcodeHeaderSize), dictionary_corrupted, "");5087RETURN_ERROR_IF(offcodeLog > OffFSELog, dictionary_corrupted, "");5088/* fill all offset symbols to avoid garbage at end of table */5089RETURN_ERROR_IF(FSE_isError(FSE_buildCTable_wksp(5090bs->entropy.fse.offcodeCTable,5091offcodeNCount, MaxOff, offcodeLog,5092workspace, HUF_WORKSPACE_SIZE)),5093dictionary_corrupted, "");5094/* Defer checking offcodeMaxValue because we need to know the size of the dictionary content */5095dictPtr += offcodeHeaderSize;5096}50975098{ short matchlengthNCount[MaxML+1];5099unsigned matchlengthMaxValue = MaxML, matchlengthLog;5100size_t const matchlengthHeaderSize = FSE_readNCount(matchlengthNCount, &matchlengthMaxValue, &matchlengthLog, dictPtr, (size_t)(dictEnd-dictPtr));5101RETURN_ERROR_IF(FSE_isError(matchlengthHeaderSize), dictionary_corrupted, "");5102RETURN_ERROR_IF(matchlengthLog > MLFSELog, dictionary_corrupted, "");5103RETURN_ERROR_IF(FSE_isError(FSE_buildCTable_wksp(5104bs->entropy.fse.matchlengthCTable,5105matchlengthNCount, matchlengthMaxValue, matchlengthLog,5106workspace, HUF_WORKSPACE_SIZE)),5107dictionary_corrupted, "");5108bs->entropy.fse.matchlength_repeatMode = ZSTD_dictNCountRepeat(matchlengthNCount, matchlengthMaxValue, MaxML);5109dictPtr += matchlengthHeaderSize;5110}51115112{ short litlengthNCount[MaxLL+1];5113unsigned litlengthMaxValue = MaxLL, litlengthLog;5114size_t const litlengthHeaderSize = FSE_readNCount(litlengthNCount, &litlengthMaxValue, &litlengthLog, dictPtr, (size_t)(dictEnd-dictPtr));5115RETURN_ERROR_IF(FSE_isError(litlengthHeaderSize), dictionary_corrupted, "");5116RETURN_ERROR_IF(litlengthLog > LLFSELog, dictionary_corrupted, "");5117RETURN_ERROR_IF(FSE_isError(FSE_buildCTable_wksp(5118bs->entropy.fse.litlengthCTable,5119litlengthNCount, litlengthMaxValue, litlengthLog,5120workspace, HUF_WORKSPACE_SIZE)),5121dictionary_corrupted, "");5122bs->entropy.fse.litlength_repeatMode = ZSTD_dictNCountRepeat(litlengthNCount, litlengthMaxValue, MaxLL);5123dictPtr += litlengthHeaderSize;5124}51255126RETURN_ERROR_IF(dictPtr+12 > dictEnd, dictionary_corrupted, "");5127bs->rep[0] = MEM_readLE32(dictPtr+0);5128bs->rep[1] = MEM_readLE32(dictPtr+4);5129bs->rep[2] = MEM_readLE32(dictPtr+8);5130dictPtr += 12;51315132{ size_t const dictContentSize = (size_t)(dictEnd - dictPtr);5133U32 offcodeMax = MaxOff;5134if (dictContentSize <= ((U32)-1) - 128 KB) {5135U32 const maxOffset = (U32)dictContentSize + 128 KB; /* The maximum offset that must be supported */5136offcodeMax = ZSTD_highbit32(maxOffset); /* Calculate minimum offset code required to represent maxOffset */5137}5138/* All offset values <= dictContentSize + 128 KB must be representable for a valid table */5139bs->entropy.fse.offcode_repeatMode = ZSTD_dictNCountRepeat(offcodeNCount, offcodeMaxValue, MIN(offcodeMax, MaxOff));51405141/* All repCodes must be <= dictContentSize and != 0 */5142{ U32 u;5143for (u=0; u<3; u++) {5144RETURN_ERROR_IF(bs->rep[u] == 0, dictionary_corrupted, "");5145RETURN_ERROR_IF(bs->rep[u] > dictContentSize, dictionary_corrupted, "");5146} } }51475148return (size_t)(dictPtr - (const BYTE*)dict);5149}51505151/* Dictionary format :5152* See :5153* https://github.com/facebook/zstd/blob/release/doc/zstd_compression_format.md#dictionary-format5154*/5155/*! ZSTD_loadZstdDictionary() :5156* @return : dictID, or an error code5157* assumptions : magic number supposed already checked5158* dictSize supposed >= 85159*/5160static size_t ZSTD_loadZstdDictionary(ZSTD_compressedBlockState_t* bs,5161ZSTD_MatchState_t* ms,5162ZSTD_cwksp* ws,5163ZSTD_CCtx_params const* params,5164const void* dict, size_t dictSize,5165ZSTD_dictTableLoadMethod_e dtlm,5166ZSTD_tableFillPurpose_e tfp,5167void* workspace)5168{5169const BYTE* dictPtr = (const BYTE*)dict;5170const BYTE* const dictEnd = dictPtr + dictSize;5171size_t dictID;5172size_t eSize;5173ZSTD_STATIC_ASSERT(HUF_WORKSPACE_SIZE >= (1<<MAX(MLFSELog,LLFSELog)));5174assert(dictSize >= 8);5175assert(MEM_readLE32(dictPtr) == ZSTD_MAGIC_DICTIONARY);51765177dictID = params->fParams.noDictIDFlag ? 0 : MEM_readLE32(dictPtr + 4 /* skip magic number */ );5178eSize = ZSTD_loadCEntropy(bs, workspace, dict, dictSize);5179FORWARD_IF_ERROR(eSize, "ZSTD_loadCEntropy failed");5180dictPtr += eSize;51815182{5183size_t const dictContentSize = (size_t)(dictEnd - dictPtr);5184FORWARD_IF_ERROR(ZSTD_loadDictionaryContent(5185ms, NULL, ws, params, dictPtr, dictContentSize, dtlm, tfp), "");5186}5187return dictID;5188}51895190/** ZSTD_compress_insertDictionary() :5191* @return : dictID, or an error code */5192static size_t5193ZSTD_compress_insertDictionary(ZSTD_compressedBlockState_t* bs,5194ZSTD_MatchState_t* ms,5195ldmState_t* ls,5196ZSTD_cwksp* ws,5197const ZSTD_CCtx_params* params,5198const void* dict, size_t dictSize,5199ZSTD_dictContentType_e dictContentType,5200ZSTD_dictTableLoadMethod_e dtlm,5201ZSTD_tableFillPurpose_e tfp,5202void* workspace)5203{5204DEBUGLOG(4, "ZSTD_compress_insertDictionary (dictSize=%u)", (U32)dictSize);5205if ((dict==NULL) || (dictSize<8)) {5206RETURN_ERROR_IF(dictContentType == ZSTD_dct_fullDict, dictionary_wrong, "");5207return 0;5208}52095210ZSTD_reset_compressedBlockState(bs);52115212/* dict restricted modes */5213if (dictContentType == ZSTD_dct_rawContent)5214return ZSTD_loadDictionaryContent(ms, ls, ws, params, dict, dictSize, dtlm, tfp);52155216if (MEM_readLE32(dict) != ZSTD_MAGIC_DICTIONARY) {5217if (dictContentType == ZSTD_dct_auto) {5218DEBUGLOG(4, "raw content dictionary detected");5219return ZSTD_loadDictionaryContent(5220ms, ls, ws, params, dict, dictSize, dtlm, tfp);5221}5222RETURN_ERROR_IF(dictContentType == ZSTD_dct_fullDict, dictionary_wrong, "");5223assert(0); /* impossible */5224}52255226/* dict as full zstd dictionary */5227return ZSTD_loadZstdDictionary(5228bs, ms, ws, params, dict, dictSize, dtlm, tfp, workspace);5229}52305231#define ZSTD_USE_CDICT_PARAMS_SRCSIZE_CUTOFF (128 KB)5232#define ZSTD_USE_CDICT_PARAMS_DICTSIZE_MULTIPLIER (6ULL)52335234/*! ZSTD_compressBegin_internal() :5235* Assumption : either @dict OR @cdict (or none) is non-NULL, never both5236* @return : 0, or an error code */5237static size_t ZSTD_compressBegin_internal(ZSTD_CCtx* cctx,5238const void* dict, size_t dictSize,5239ZSTD_dictContentType_e dictContentType,5240ZSTD_dictTableLoadMethod_e dtlm,5241const ZSTD_CDict* cdict,5242const ZSTD_CCtx_params* params, U64 pledgedSrcSize,5243ZSTD_buffered_policy_e zbuff)5244{5245size_t const dictContentSize = cdict ? cdict->dictContentSize : dictSize;5246#if ZSTD_TRACE5247cctx->traceCtx = (ZSTD_trace_compress_begin != NULL) ? ZSTD_trace_compress_begin(cctx) : 0;5248#endif5249DEBUGLOG(4, "ZSTD_compressBegin_internal: wlog=%u", params->cParams.windowLog);5250/* params are supposed to be fully validated at this point */5251assert(!ZSTD_isError(ZSTD_checkCParams(params->cParams)));5252assert(!((dict) && (cdict))); /* either dict or cdict, not both */5253if ( (cdict)5254&& (cdict->dictContentSize > 0)5255&& ( pledgedSrcSize < ZSTD_USE_CDICT_PARAMS_SRCSIZE_CUTOFF5256|| pledgedSrcSize < cdict->dictContentSize * ZSTD_USE_CDICT_PARAMS_DICTSIZE_MULTIPLIER5257|| pledgedSrcSize == ZSTD_CONTENTSIZE_UNKNOWN5258|| cdict->compressionLevel == 0)5259&& (params->attachDictPref != ZSTD_dictForceLoad) ) {5260return ZSTD_resetCCtx_usingCDict(cctx, cdict, params, pledgedSrcSize, zbuff);5261}52625263FORWARD_IF_ERROR( ZSTD_resetCCtx_internal(cctx, params, pledgedSrcSize,5264dictContentSize,5265ZSTDcrp_makeClean, zbuff) , "");5266{ size_t const dictID = cdict ?5267ZSTD_compress_insertDictionary(5268cctx->blockState.prevCBlock, &cctx->blockState.matchState,5269&cctx->ldmState, &cctx->workspace, &cctx->appliedParams, cdict->dictContent,5270cdict->dictContentSize, cdict->dictContentType, dtlm,5271ZSTD_tfp_forCCtx, cctx->tmpWorkspace)5272: ZSTD_compress_insertDictionary(5273cctx->blockState.prevCBlock, &cctx->blockState.matchState,5274&cctx->ldmState, &cctx->workspace, &cctx->appliedParams, dict, dictSize,5275dictContentType, dtlm, ZSTD_tfp_forCCtx, cctx->tmpWorkspace);5276FORWARD_IF_ERROR(dictID, "ZSTD_compress_insertDictionary failed");5277assert(dictID <= UINT_MAX);5278cctx->dictID = (U32)dictID;5279cctx->dictContentSize = dictContentSize;5280}5281return 0;5282}52835284size_t ZSTD_compressBegin_advanced_internal(ZSTD_CCtx* cctx,5285const void* dict, size_t dictSize,5286ZSTD_dictContentType_e dictContentType,5287ZSTD_dictTableLoadMethod_e dtlm,5288const ZSTD_CDict* cdict,5289const ZSTD_CCtx_params* params,5290unsigned long long pledgedSrcSize)5291{5292DEBUGLOG(4, "ZSTD_compressBegin_advanced_internal: wlog=%u", params->cParams.windowLog);5293/* compression parameters verification and optimization */5294FORWARD_IF_ERROR( ZSTD_checkCParams(params->cParams) , "");5295return ZSTD_compressBegin_internal(cctx,5296dict, dictSize, dictContentType, dtlm,5297cdict,5298params, pledgedSrcSize,5299ZSTDb_not_buffered);5300}53015302/*! ZSTD_compressBegin_advanced() :5303* @return : 0, or an error code */5304size_t ZSTD_compressBegin_advanced(ZSTD_CCtx* cctx,5305const void* dict, size_t dictSize,5306ZSTD_parameters params, unsigned long long pledgedSrcSize)5307{5308ZSTD_CCtx_params cctxParams;5309ZSTD_CCtxParams_init_internal(&cctxParams, ¶ms, ZSTD_NO_CLEVEL);5310return ZSTD_compressBegin_advanced_internal(cctx,5311dict, dictSize, ZSTD_dct_auto, ZSTD_dtlm_fast,5312NULL /*cdict*/,5313&cctxParams, pledgedSrcSize);5314}53155316static size_t5317ZSTD_compressBegin_usingDict_deprecated(ZSTD_CCtx* cctx, const void* dict, size_t dictSize, int compressionLevel)5318{5319ZSTD_CCtx_params cctxParams;5320{ ZSTD_parameters const params = ZSTD_getParams_internal(compressionLevel, ZSTD_CONTENTSIZE_UNKNOWN, dictSize, ZSTD_cpm_noAttachDict);5321ZSTD_CCtxParams_init_internal(&cctxParams, ¶ms, (compressionLevel == 0) ? ZSTD_CLEVEL_DEFAULT : compressionLevel);5322}5323DEBUGLOG(4, "ZSTD_compressBegin_usingDict (dictSize=%u)", (unsigned)dictSize);5324return ZSTD_compressBegin_internal(cctx, dict, dictSize, ZSTD_dct_auto, ZSTD_dtlm_fast, NULL,5325&cctxParams, ZSTD_CONTENTSIZE_UNKNOWN, ZSTDb_not_buffered);5326}53275328size_t5329ZSTD_compressBegin_usingDict(ZSTD_CCtx* cctx, const void* dict, size_t dictSize, int compressionLevel)5330{5331return ZSTD_compressBegin_usingDict_deprecated(cctx, dict, dictSize, compressionLevel);5332}53335334size_t ZSTD_compressBegin(ZSTD_CCtx* cctx, int compressionLevel)5335{5336return ZSTD_compressBegin_usingDict_deprecated(cctx, NULL, 0, compressionLevel);5337}533853395340/*! ZSTD_writeEpilogue() :5341* Ends a frame.5342* @return : nb of bytes written into dst (or an error code) */5343static size_t ZSTD_writeEpilogue(ZSTD_CCtx* cctx, void* dst, size_t dstCapacity)5344{5345BYTE* const ostart = (BYTE*)dst;5346BYTE* op = ostart;53475348DEBUGLOG(4, "ZSTD_writeEpilogue");5349RETURN_ERROR_IF(cctx->stage == ZSTDcs_created, stage_wrong, "init missing");53505351/* special case : empty frame */5352if (cctx->stage == ZSTDcs_init) {5353size_t fhSize = ZSTD_writeFrameHeader(dst, dstCapacity, &cctx->appliedParams, 0, 0);5354FORWARD_IF_ERROR(fhSize, "ZSTD_writeFrameHeader failed");5355dstCapacity -= fhSize;5356op += fhSize;5357cctx->stage = ZSTDcs_ongoing;5358}53595360if (cctx->stage != ZSTDcs_ending) {5361/* write one last empty block, make it the "last" block */5362U32 const cBlockHeader24 = 1 /* last block */ + (((U32)bt_raw)<<1) + 0;5363ZSTD_STATIC_ASSERT(ZSTD_BLOCKHEADERSIZE == 3);5364RETURN_ERROR_IF(dstCapacity<3, dstSize_tooSmall, "no room for epilogue");5365MEM_writeLE24(op, cBlockHeader24);5366op += ZSTD_blockHeaderSize;5367dstCapacity -= ZSTD_blockHeaderSize;5368}53695370if (cctx->appliedParams.fParams.checksumFlag) {5371U32 const checksum = (U32) XXH64_digest(&cctx->xxhState);5372RETURN_ERROR_IF(dstCapacity<4, dstSize_tooSmall, "no room for checksum");5373DEBUGLOG(4, "ZSTD_writeEpilogue: write checksum : %08X", (unsigned)checksum);5374MEM_writeLE32(op, checksum);5375op += 4;5376}53775378cctx->stage = ZSTDcs_created; /* return to "created but no init" status */5379return (size_t)(op-ostart);5380}53815382void ZSTD_CCtx_trace(ZSTD_CCtx* cctx, size_t extraCSize)5383{5384#if ZSTD_TRACE5385if (cctx->traceCtx && ZSTD_trace_compress_end != NULL) {5386int const streaming = cctx->inBuffSize > 0 || cctx->outBuffSize > 0 || cctx->appliedParams.nbWorkers > 0;5387ZSTD_Trace trace;5388ZSTD_memset(&trace, 0, sizeof(trace));5389trace.version = ZSTD_VERSION_NUMBER;5390trace.streaming = streaming;5391trace.dictionaryID = cctx->dictID;5392trace.dictionarySize = cctx->dictContentSize;5393trace.uncompressedSize = cctx->consumedSrcSize;5394trace.compressedSize = cctx->producedCSize + extraCSize;5395trace.params = &cctx->appliedParams;5396trace.cctx = cctx;5397ZSTD_trace_compress_end(cctx->traceCtx, &trace);5398}5399cctx->traceCtx = 0;5400#else5401(void)cctx;5402(void)extraCSize;5403#endif5404}54055406size_t ZSTD_compressEnd_public(ZSTD_CCtx* cctx,5407void* dst, size_t dstCapacity,5408const void* src, size_t srcSize)5409{5410size_t endResult;5411size_t const cSize = ZSTD_compressContinue_internal(cctx,5412dst, dstCapacity, src, srcSize,54131 /* frame mode */, 1 /* last chunk */);5414FORWARD_IF_ERROR(cSize, "ZSTD_compressContinue_internal failed");5415endResult = ZSTD_writeEpilogue(cctx, (char*)dst + cSize, dstCapacity-cSize);5416FORWARD_IF_ERROR(endResult, "ZSTD_writeEpilogue failed");5417assert(!(cctx->appliedParams.fParams.contentSizeFlag && cctx->pledgedSrcSizePlusOne == 0));5418if (cctx->pledgedSrcSizePlusOne != 0) { /* control src size */5419ZSTD_STATIC_ASSERT(ZSTD_CONTENTSIZE_UNKNOWN == (unsigned long long)-1);5420DEBUGLOG(4, "end of frame : controlling src size");5421RETURN_ERROR_IF(5422cctx->pledgedSrcSizePlusOne != cctx->consumedSrcSize+1,5423srcSize_wrong,5424"error : pledgedSrcSize = %u, while realSrcSize = %u",5425(unsigned)cctx->pledgedSrcSizePlusOne-1,5426(unsigned)cctx->consumedSrcSize);5427}5428ZSTD_CCtx_trace(cctx, endResult);5429return cSize + endResult;5430}54315432/* NOTE: Must just wrap ZSTD_compressEnd_public() */5433size_t ZSTD_compressEnd(ZSTD_CCtx* cctx,5434void* dst, size_t dstCapacity,5435const void* src, size_t srcSize)5436{5437return ZSTD_compressEnd_public(cctx, dst, dstCapacity, src, srcSize);5438}54395440size_t ZSTD_compress_advanced (ZSTD_CCtx* cctx,5441void* dst, size_t dstCapacity,5442const void* src, size_t srcSize,5443const void* dict,size_t dictSize,5444ZSTD_parameters params)5445{5446DEBUGLOG(4, "ZSTD_compress_advanced");5447FORWARD_IF_ERROR(ZSTD_checkCParams(params.cParams), "");5448ZSTD_CCtxParams_init_internal(&cctx->simpleApiParams, ¶ms, ZSTD_NO_CLEVEL);5449return ZSTD_compress_advanced_internal(cctx,5450dst, dstCapacity,5451src, srcSize,5452dict, dictSize,5453&cctx->simpleApiParams);5454}54555456/* Internal */5457size_t ZSTD_compress_advanced_internal(5458ZSTD_CCtx* cctx,5459void* dst, size_t dstCapacity,5460const void* src, size_t srcSize,5461const void* dict,size_t dictSize,5462const ZSTD_CCtx_params* params)5463{5464DEBUGLOG(4, "ZSTD_compress_advanced_internal (srcSize:%u)", (unsigned)srcSize);5465FORWARD_IF_ERROR( ZSTD_compressBegin_internal(cctx,5466dict, dictSize, ZSTD_dct_auto, ZSTD_dtlm_fast, NULL,5467params, srcSize, ZSTDb_not_buffered) , "");5468return ZSTD_compressEnd_public(cctx, dst, dstCapacity, src, srcSize);5469}54705471size_t ZSTD_compress_usingDict(ZSTD_CCtx* cctx,5472void* dst, size_t dstCapacity,5473const void* src, size_t srcSize,5474const void* dict, size_t dictSize,5475int compressionLevel)5476{5477{5478ZSTD_parameters const params = ZSTD_getParams_internal(compressionLevel, srcSize, dict ? dictSize : 0, ZSTD_cpm_noAttachDict);5479assert(params.fParams.contentSizeFlag == 1);5480ZSTD_CCtxParams_init_internal(&cctx->simpleApiParams, ¶ms, (compressionLevel == 0) ? ZSTD_CLEVEL_DEFAULT: compressionLevel);5481}5482DEBUGLOG(4, "ZSTD_compress_usingDict (srcSize=%u)", (unsigned)srcSize);5483return ZSTD_compress_advanced_internal(cctx, dst, dstCapacity, src, srcSize, dict, dictSize, &cctx->simpleApiParams);5484}54855486size_t ZSTD_compressCCtx(ZSTD_CCtx* cctx,5487void* dst, size_t dstCapacity,5488const void* src, size_t srcSize,5489int compressionLevel)5490{5491DEBUGLOG(4, "ZSTD_compressCCtx (srcSize=%u)", (unsigned)srcSize);5492assert(cctx != NULL);5493return ZSTD_compress_usingDict(cctx, dst, dstCapacity, src, srcSize, NULL, 0, compressionLevel);5494}54955496size_t ZSTD_compress(void* dst, size_t dstCapacity,5497const void* src, size_t srcSize,5498int compressionLevel)5499{5500size_t result;5501#if ZSTD_COMPRESS_HEAPMODE5502ZSTD_CCtx* cctx = ZSTD_createCCtx();5503RETURN_ERROR_IF(!cctx, memory_allocation, "ZSTD_createCCtx failed");5504result = ZSTD_compressCCtx(cctx, dst, dstCapacity, src, srcSize, compressionLevel);5505ZSTD_freeCCtx(cctx);5506#else5507ZSTD_CCtx ctxBody;5508ZSTD_initCCtx(&ctxBody, ZSTD_defaultCMem);5509result = ZSTD_compressCCtx(&ctxBody, dst, dstCapacity, src, srcSize, compressionLevel);5510ZSTD_freeCCtxContent(&ctxBody); /* can't free ctxBody itself, as it's on stack; free only heap content */5511#endif5512return result;5513}551455155516/* ===== Dictionary API ===== */55175518/*! ZSTD_estimateCDictSize_advanced() :5519* Estimate amount of memory that will be needed to create a dictionary with following arguments */5520size_t ZSTD_estimateCDictSize_advanced(5521size_t dictSize, ZSTD_compressionParameters cParams,5522ZSTD_dictLoadMethod_e dictLoadMethod)5523{5524DEBUGLOG(5, "sizeof(ZSTD_CDict) : %u", (unsigned)sizeof(ZSTD_CDict));5525return ZSTD_cwksp_alloc_size(sizeof(ZSTD_CDict))5526+ ZSTD_cwksp_alloc_size(HUF_WORKSPACE_SIZE)5527/* enableDedicatedDictSearch == 1 ensures that CDict estimation will not be too small5528* in case we are using DDS with row-hash. */5529+ ZSTD_sizeof_matchState(&cParams, ZSTD_resolveRowMatchFinderMode(ZSTD_ps_auto, &cParams),5530/* enableDedicatedDictSearch */ 1, /* forCCtx */ 0)5531+ (dictLoadMethod == ZSTD_dlm_byRef ? 05532: ZSTD_cwksp_alloc_size(ZSTD_cwksp_align(dictSize, sizeof(void *))));5533}55345535size_t ZSTD_estimateCDictSize(size_t dictSize, int compressionLevel)5536{5537ZSTD_compressionParameters const cParams = ZSTD_getCParams_internal(compressionLevel, ZSTD_CONTENTSIZE_UNKNOWN, dictSize, ZSTD_cpm_createCDict);5538return ZSTD_estimateCDictSize_advanced(dictSize, cParams, ZSTD_dlm_byCopy);5539}55405541size_t ZSTD_sizeof_CDict(const ZSTD_CDict* cdict)5542{5543if (cdict==NULL) return 0; /* support sizeof on NULL */5544DEBUGLOG(5, "sizeof(*cdict) : %u", (unsigned)sizeof(*cdict));5545/* cdict may be in the workspace */5546return (cdict->workspace.workspace == cdict ? 0 : sizeof(*cdict))5547+ ZSTD_cwksp_sizeof(&cdict->workspace);5548}55495550static size_t ZSTD_initCDict_internal(5551ZSTD_CDict* cdict,5552const void* dictBuffer, size_t dictSize,5553ZSTD_dictLoadMethod_e dictLoadMethod,5554ZSTD_dictContentType_e dictContentType,5555ZSTD_CCtx_params params)5556{5557DEBUGLOG(3, "ZSTD_initCDict_internal (dictContentType:%u)", (unsigned)dictContentType);5558assert(!ZSTD_checkCParams(params.cParams));5559cdict->matchState.cParams = params.cParams;5560cdict->matchState.dedicatedDictSearch = params.enableDedicatedDictSearch;5561if ((dictLoadMethod == ZSTD_dlm_byRef) || (!dictBuffer) || (!dictSize)) {5562cdict->dictContent = dictBuffer;5563} else {5564void *internalBuffer = ZSTD_cwksp_reserve_object(&cdict->workspace, ZSTD_cwksp_align(dictSize, sizeof(void*)));5565RETURN_ERROR_IF(!internalBuffer, memory_allocation, "NULL pointer!");5566cdict->dictContent = internalBuffer;5567ZSTD_memcpy(internalBuffer, dictBuffer, dictSize);5568}5569cdict->dictContentSize = dictSize;5570cdict->dictContentType = dictContentType;55715572cdict->entropyWorkspace = (U32*)ZSTD_cwksp_reserve_object(&cdict->workspace, HUF_WORKSPACE_SIZE);557355745575/* Reset the state to no dictionary */5576ZSTD_reset_compressedBlockState(&cdict->cBlockState);5577FORWARD_IF_ERROR(ZSTD_reset_matchState(5578&cdict->matchState,5579&cdict->workspace,5580¶ms.cParams,5581params.useRowMatchFinder,5582ZSTDcrp_makeClean,5583ZSTDirp_reset,5584ZSTD_resetTarget_CDict), "");5585/* (Maybe) load the dictionary5586* Skips loading the dictionary if it is < 8 bytes.5587*/5588{ params.compressionLevel = ZSTD_CLEVEL_DEFAULT;5589params.fParams.contentSizeFlag = 1;5590{ size_t const dictID = ZSTD_compress_insertDictionary(5591&cdict->cBlockState, &cdict->matchState, NULL, &cdict->workspace,5592¶ms, cdict->dictContent, cdict->dictContentSize,5593dictContentType, ZSTD_dtlm_full, ZSTD_tfp_forCDict, cdict->entropyWorkspace);5594FORWARD_IF_ERROR(dictID, "ZSTD_compress_insertDictionary failed");5595assert(dictID <= (size_t)(U32)-1);5596cdict->dictID = (U32)dictID;5597}5598}55995600return 0;5601}56025603static ZSTD_CDict*5604ZSTD_createCDict_advanced_internal(size_t dictSize,5605ZSTD_dictLoadMethod_e dictLoadMethod,5606ZSTD_compressionParameters cParams,5607ZSTD_ParamSwitch_e useRowMatchFinder,5608int enableDedicatedDictSearch,5609ZSTD_customMem customMem)5610{5611if ((!customMem.customAlloc) ^ (!customMem.customFree)) return NULL;5612DEBUGLOG(3, "ZSTD_createCDict_advanced_internal (dictSize=%u)", (unsigned)dictSize);56135614{ size_t const workspaceSize =5615ZSTD_cwksp_alloc_size(sizeof(ZSTD_CDict)) +5616ZSTD_cwksp_alloc_size(HUF_WORKSPACE_SIZE) +5617ZSTD_sizeof_matchState(&cParams, useRowMatchFinder, enableDedicatedDictSearch, /* forCCtx */ 0) +5618(dictLoadMethod == ZSTD_dlm_byRef ? 05619: ZSTD_cwksp_alloc_size(ZSTD_cwksp_align(dictSize, sizeof(void*))));5620void* const workspace = ZSTD_customMalloc(workspaceSize, customMem);5621ZSTD_cwksp ws;5622ZSTD_CDict* cdict;56235624if (!workspace) {5625ZSTD_customFree(workspace, customMem);5626return NULL;5627}56285629ZSTD_cwksp_init(&ws, workspace, workspaceSize, ZSTD_cwksp_dynamic_alloc);56305631cdict = (ZSTD_CDict*)ZSTD_cwksp_reserve_object(&ws, sizeof(ZSTD_CDict));5632assert(cdict != NULL);5633ZSTD_cwksp_move(&cdict->workspace, &ws);5634cdict->customMem = customMem;5635cdict->compressionLevel = ZSTD_NO_CLEVEL; /* signals advanced API usage */5636cdict->useRowMatchFinder = useRowMatchFinder;5637return cdict;5638}5639}56405641ZSTD_CDict* ZSTD_createCDict_advanced(const void* dictBuffer, size_t dictSize,5642ZSTD_dictLoadMethod_e dictLoadMethod,5643ZSTD_dictContentType_e dictContentType,5644ZSTD_compressionParameters cParams,5645ZSTD_customMem customMem)5646{5647ZSTD_CCtx_params cctxParams;5648ZSTD_memset(&cctxParams, 0, sizeof(cctxParams));5649DEBUGLOG(3, "ZSTD_createCDict_advanced, dictSize=%u, mode=%u", (unsigned)dictSize, (unsigned)dictContentType);5650ZSTD_CCtxParams_init(&cctxParams, 0);5651cctxParams.cParams = cParams;5652cctxParams.customMem = customMem;5653return ZSTD_createCDict_advanced2(5654dictBuffer, dictSize,5655dictLoadMethod, dictContentType,5656&cctxParams, customMem);5657}56585659ZSTD_CDict* ZSTD_createCDict_advanced2(5660const void* dict, size_t dictSize,5661ZSTD_dictLoadMethod_e dictLoadMethod,5662ZSTD_dictContentType_e dictContentType,5663const ZSTD_CCtx_params* originalCctxParams,5664ZSTD_customMem customMem)5665{5666ZSTD_CCtx_params cctxParams = *originalCctxParams;5667ZSTD_compressionParameters cParams;5668ZSTD_CDict* cdict;56695670DEBUGLOG(3, "ZSTD_createCDict_advanced2, dictSize=%u, mode=%u", (unsigned)dictSize, (unsigned)dictContentType);5671if (!customMem.customAlloc ^ !customMem.customFree) return NULL;56725673if (cctxParams.enableDedicatedDictSearch) {5674cParams = ZSTD_dedicatedDictSearch_getCParams(5675cctxParams.compressionLevel, dictSize);5676ZSTD_overrideCParams(&cParams, &cctxParams.cParams);5677} else {5678cParams = ZSTD_getCParamsFromCCtxParams(5679&cctxParams, ZSTD_CONTENTSIZE_UNKNOWN, dictSize, ZSTD_cpm_createCDict);5680}56815682if (!ZSTD_dedicatedDictSearch_isSupported(&cParams)) {5683/* Fall back to non-DDSS params */5684cctxParams.enableDedicatedDictSearch = 0;5685cParams = ZSTD_getCParamsFromCCtxParams(5686&cctxParams, ZSTD_CONTENTSIZE_UNKNOWN, dictSize, ZSTD_cpm_createCDict);5687}56885689DEBUGLOG(3, "ZSTD_createCDict_advanced2: DedicatedDictSearch=%u", cctxParams.enableDedicatedDictSearch);5690cctxParams.cParams = cParams;5691cctxParams.useRowMatchFinder = ZSTD_resolveRowMatchFinderMode(cctxParams.useRowMatchFinder, &cParams);56925693cdict = ZSTD_createCDict_advanced_internal(dictSize,5694dictLoadMethod, cctxParams.cParams,5695cctxParams.useRowMatchFinder, cctxParams.enableDedicatedDictSearch,5696customMem);56975698if (!cdict || ZSTD_isError( ZSTD_initCDict_internal(cdict,5699dict, dictSize,5700dictLoadMethod, dictContentType,5701cctxParams) )) {5702ZSTD_freeCDict(cdict);5703return NULL;5704}57055706return cdict;5707}57085709ZSTD_CDict* ZSTD_createCDict(const void* dict, size_t dictSize, int compressionLevel)5710{5711ZSTD_compressionParameters cParams = ZSTD_getCParams_internal(compressionLevel, ZSTD_CONTENTSIZE_UNKNOWN, dictSize, ZSTD_cpm_createCDict);5712ZSTD_CDict* const cdict = ZSTD_createCDict_advanced(dict, dictSize,5713ZSTD_dlm_byCopy, ZSTD_dct_auto,5714cParams, ZSTD_defaultCMem);5715if (cdict)5716cdict->compressionLevel = (compressionLevel == 0) ? ZSTD_CLEVEL_DEFAULT : compressionLevel;5717return cdict;5718}57195720ZSTD_CDict* ZSTD_createCDict_byReference(const void* dict, size_t dictSize, int compressionLevel)5721{5722ZSTD_compressionParameters cParams = ZSTD_getCParams_internal(compressionLevel, ZSTD_CONTENTSIZE_UNKNOWN, dictSize, ZSTD_cpm_createCDict);5723ZSTD_CDict* const cdict = ZSTD_createCDict_advanced(dict, dictSize,5724ZSTD_dlm_byRef, ZSTD_dct_auto,5725cParams, ZSTD_defaultCMem);5726if (cdict)5727cdict->compressionLevel = (compressionLevel == 0) ? ZSTD_CLEVEL_DEFAULT : compressionLevel;5728return cdict;5729}57305731size_t ZSTD_freeCDict(ZSTD_CDict* cdict)5732{5733if (cdict==NULL) return 0; /* support free on NULL */5734{ ZSTD_customMem const cMem = cdict->customMem;5735int cdictInWorkspace = ZSTD_cwksp_owns_buffer(&cdict->workspace, cdict);5736ZSTD_cwksp_free(&cdict->workspace, cMem);5737if (!cdictInWorkspace) {5738ZSTD_customFree(cdict, cMem);5739}5740return 0;5741}5742}57435744/*! ZSTD_initStaticCDict_advanced() :5745* Generate a digested dictionary in provided memory area.5746* workspace: The memory area to emplace the dictionary into.5747* Provided pointer must 8-bytes aligned.5748* It must outlive dictionary usage.5749* workspaceSize: Use ZSTD_estimateCDictSize()5750* to determine how large workspace must be.5751* cParams : use ZSTD_getCParams() to transform a compression level5752* into its relevant cParams.5753* @return : pointer to ZSTD_CDict*, or NULL if error (size too small)5754* Note : there is no corresponding "free" function.5755* Since workspace was allocated externally, it must be freed externally.5756*/5757const ZSTD_CDict* ZSTD_initStaticCDict(5758void* workspace, size_t workspaceSize,5759const void* dict, size_t dictSize,5760ZSTD_dictLoadMethod_e dictLoadMethod,5761ZSTD_dictContentType_e dictContentType,5762ZSTD_compressionParameters cParams)5763{5764ZSTD_ParamSwitch_e const useRowMatchFinder = ZSTD_resolveRowMatchFinderMode(ZSTD_ps_auto, &cParams);5765/* enableDedicatedDictSearch == 1 ensures matchstate is not too small in case this CDict will be used for DDS + row hash */5766size_t const matchStateSize = ZSTD_sizeof_matchState(&cParams, useRowMatchFinder, /* enableDedicatedDictSearch */ 1, /* forCCtx */ 0);5767size_t const neededSize = ZSTD_cwksp_alloc_size(sizeof(ZSTD_CDict))5768+ (dictLoadMethod == ZSTD_dlm_byRef ? 05769: ZSTD_cwksp_alloc_size(ZSTD_cwksp_align(dictSize, sizeof(void*))))5770+ ZSTD_cwksp_alloc_size(HUF_WORKSPACE_SIZE)5771+ matchStateSize;5772ZSTD_CDict* cdict;5773ZSTD_CCtx_params params;57745775DEBUGLOG(4, "ZSTD_initStaticCDict (dictSize==%u)", (unsigned)dictSize);5776if ((size_t)workspace & 7) return NULL; /* 8-aligned */57775778{5779ZSTD_cwksp ws;5780ZSTD_cwksp_init(&ws, workspace, workspaceSize, ZSTD_cwksp_static_alloc);5781cdict = (ZSTD_CDict*)ZSTD_cwksp_reserve_object(&ws, sizeof(ZSTD_CDict));5782if (cdict == NULL) return NULL;5783ZSTD_cwksp_move(&cdict->workspace, &ws);5784}57855786if (workspaceSize < neededSize) return NULL;57875788ZSTD_CCtxParams_init(¶ms, 0);5789params.cParams = cParams;5790params.useRowMatchFinder = useRowMatchFinder;5791cdict->useRowMatchFinder = useRowMatchFinder;5792cdict->compressionLevel = ZSTD_NO_CLEVEL;57935794if (ZSTD_isError( ZSTD_initCDict_internal(cdict,5795dict, dictSize,5796dictLoadMethod, dictContentType,5797params) ))5798return NULL;57995800return cdict;5801}58025803ZSTD_compressionParameters ZSTD_getCParamsFromCDict(const ZSTD_CDict* cdict)5804{5805assert(cdict != NULL);5806return cdict->matchState.cParams;5807}58085809/*! ZSTD_getDictID_fromCDict() :5810* Provides the dictID of the dictionary loaded into `cdict`.5811* If @return == 0, the dictionary is not conformant to Zstandard specification, or empty.5812* Non-conformant dictionaries can still be loaded, but as content-only dictionaries. */5813unsigned ZSTD_getDictID_fromCDict(const ZSTD_CDict* cdict)5814{5815if (cdict==NULL) return 0;5816return cdict->dictID;5817}58185819/* ZSTD_compressBegin_usingCDict_internal() :5820* Implementation of various ZSTD_compressBegin_usingCDict* functions.5821*/5822static size_t ZSTD_compressBegin_usingCDict_internal(5823ZSTD_CCtx* const cctx, const ZSTD_CDict* const cdict,5824ZSTD_frameParameters const fParams, unsigned long long const pledgedSrcSize)5825{5826ZSTD_CCtx_params cctxParams;5827DEBUGLOG(4, "ZSTD_compressBegin_usingCDict_internal");5828RETURN_ERROR_IF(cdict==NULL, dictionary_wrong, "NULL pointer!");5829/* Initialize the cctxParams from the cdict */5830{5831ZSTD_parameters params;5832params.fParams = fParams;5833params.cParams = ( pledgedSrcSize < ZSTD_USE_CDICT_PARAMS_SRCSIZE_CUTOFF5834|| pledgedSrcSize < cdict->dictContentSize * ZSTD_USE_CDICT_PARAMS_DICTSIZE_MULTIPLIER5835|| pledgedSrcSize == ZSTD_CONTENTSIZE_UNKNOWN5836|| cdict->compressionLevel == 0 ) ?5837ZSTD_getCParamsFromCDict(cdict)5838: ZSTD_getCParams(cdict->compressionLevel,5839pledgedSrcSize,5840cdict->dictContentSize);5841ZSTD_CCtxParams_init_internal(&cctxParams, ¶ms, cdict->compressionLevel);5842}5843/* Increase window log to fit the entire dictionary and source if the5844* source size is known. Limit the increase to 19, which is the5845* window log for compression level 1 with the largest source size.5846*/5847if (pledgedSrcSize != ZSTD_CONTENTSIZE_UNKNOWN) {5848U32 const limitedSrcSize = (U32)MIN(pledgedSrcSize, 1U << 19);5849U32 const limitedSrcLog = limitedSrcSize > 1 ? ZSTD_highbit32(limitedSrcSize - 1) + 1 : 1;5850cctxParams.cParams.windowLog = MAX(cctxParams.cParams.windowLog, limitedSrcLog);5851}5852return ZSTD_compressBegin_internal(cctx,5853NULL, 0, ZSTD_dct_auto, ZSTD_dtlm_fast,5854cdict,5855&cctxParams, pledgedSrcSize,5856ZSTDb_not_buffered);5857}585858595860/* ZSTD_compressBegin_usingCDict_advanced() :5861* This function is DEPRECATED.5862* cdict must be != NULL */5863size_t ZSTD_compressBegin_usingCDict_advanced(5864ZSTD_CCtx* const cctx, const ZSTD_CDict* const cdict,5865ZSTD_frameParameters const fParams, unsigned long long const pledgedSrcSize)5866{5867return ZSTD_compressBegin_usingCDict_internal(cctx, cdict, fParams, pledgedSrcSize);5868}58695870/* ZSTD_compressBegin_usingCDict() :5871* cdict must be != NULL */5872size_t ZSTD_compressBegin_usingCDict_deprecated(ZSTD_CCtx* cctx, const ZSTD_CDict* cdict)5873{5874ZSTD_frameParameters const fParams = { 0 /*content*/, 0 /*checksum*/, 0 /*noDictID*/ };5875return ZSTD_compressBegin_usingCDict_internal(cctx, cdict, fParams, ZSTD_CONTENTSIZE_UNKNOWN);5876}58775878size_t ZSTD_compressBegin_usingCDict(ZSTD_CCtx* cctx, const ZSTD_CDict* cdict)5879{5880return ZSTD_compressBegin_usingCDict_deprecated(cctx, cdict);5881}58825883/*! ZSTD_compress_usingCDict_internal():5884* Implementation of various ZSTD_compress_usingCDict* functions.5885*/5886static size_t ZSTD_compress_usingCDict_internal(ZSTD_CCtx* cctx,5887void* dst, size_t dstCapacity,5888const void* src, size_t srcSize,5889const ZSTD_CDict* cdict, ZSTD_frameParameters fParams)5890{5891FORWARD_IF_ERROR(ZSTD_compressBegin_usingCDict_internal(cctx, cdict, fParams, srcSize), ""); /* will check if cdict != NULL */5892return ZSTD_compressEnd_public(cctx, dst, dstCapacity, src, srcSize);5893}58945895/*! ZSTD_compress_usingCDict_advanced():5896* This function is DEPRECATED.5897*/5898size_t ZSTD_compress_usingCDict_advanced(ZSTD_CCtx* cctx,5899void* dst, size_t dstCapacity,5900const void* src, size_t srcSize,5901const ZSTD_CDict* cdict, ZSTD_frameParameters fParams)5902{5903return ZSTD_compress_usingCDict_internal(cctx, dst, dstCapacity, src, srcSize, cdict, fParams);5904}59055906/*! ZSTD_compress_usingCDict() :5907* Compression using a digested Dictionary.5908* Faster startup than ZSTD_compress_usingDict(), recommended when same dictionary is used multiple times.5909* Note that compression parameters are decided at CDict creation time5910* while frame parameters are hardcoded */5911size_t ZSTD_compress_usingCDict(ZSTD_CCtx* cctx,5912void* dst, size_t dstCapacity,5913const void* src, size_t srcSize,5914const ZSTD_CDict* cdict)5915{5916ZSTD_frameParameters const fParams = { 1 /*content*/, 0 /*checksum*/, 0 /*noDictID*/ };5917return ZSTD_compress_usingCDict_internal(cctx, dst, dstCapacity, src, srcSize, cdict, fParams);5918}5919592059215922/* ******************************************************************5923* Streaming5924********************************************************************/59255926ZSTD_CStream* ZSTD_createCStream(void)5927{5928DEBUGLOG(3, "ZSTD_createCStream");5929return ZSTD_createCStream_advanced(ZSTD_defaultCMem);5930}59315932ZSTD_CStream* ZSTD_initStaticCStream(void *workspace, size_t workspaceSize)5933{5934return ZSTD_initStaticCCtx(workspace, workspaceSize);5935}59365937ZSTD_CStream* ZSTD_createCStream_advanced(ZSTD_customMem customMem)5938{ /* CStream and CCtx are now same object */5939return ZSTD_createCCtx_advanced(customMem);5940}59415942size_t ZSTD_freeCStream(ZSTD_CStream* zcs)5943{5944return ZSTD_freeCCtx(zcs); /* same object */5945}5946594759485949/*====== Initialization ======*/59505951size_t ZSTD_CStreamInSize(void) { return ZSTD_BLOCKSIZE_MAX; }59525953size_t ZSTD_CStreamOutSize(void)5954{5955return ZSTD_compressBound(ZSTD_BLOCKSIZE_MAX) + ZSTD_blockHeaderSize + 4 /* 32-bits hash */ ;5956}59575958static ZSTD_CParamMode_e ZSTD_getCParamMode(ZSTD_CDict const* cdict, ZSTD_CCtx_params const* params, U64 pledgedSrcSize)5959{5960if (cdict != NULL && ZSTD_shouldAttachDict(cdict, params, pledgedSrcSize))5961return ZSTD_cpm_attachDict;5962else5963return ZSTD_cpm_noAttachDict;5964}59655966/* ZSTD_resetCStream():5967* pledgedSrcSize == 0 means "unknown" */5968size_t ZSTD_resetCStream(ZSTD_CStream* zcs, unsigned long long pss)5969{5970/* temporary : 0 interpreted as "unknown" during transition period.5971* Users willing to specify "unknown" **must** use ZSTD_CONTENTSIZE_UNKNOWN.5972* 0 will be interpreted as "empty" in the future.5973*/5974U64 const pledgedSrcSize = (pss==0) ? ZSTD_CONTENTSIZE_UNKNOWN : pss;5975DEBUGLOG(4, "ZSTD_resetCStream: pledgedSrcSize = %u", (unsigned)pledgedSrcSize);5976FORWARD_IF_ERROR( ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only) , "");5977FORWARD_IF_ERROR( ZSTD_CCtx_setPledgedSrcSize(zcs, pledgedSrcSize) , "");5978return 0;5979}59805981/*! ZSTD_initCStream_internal() :5982* Note : for lib/compress only. Used by zstdmt_compress.c.5983* Assumption 1 : params are valid5984* Assumption 2 : either dict, or cdict, is defined, not both */5985size_t ZSTD_initCStream_internal(ZSTD_CStream* zcs,5986const void* dict, size_t dictSize, const ZSTD_CDict* cdict,5987const ZSTD_CCtx_params* params,5988unsigned long long pledgedSrcSize)5989{5990DEBUGLOG(4, "ZSTD_initCStream_internal");5991FORWARD_IF_ERROR( ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only) , "");5992FORWARD_IF_ERROR( ZSTD_CCtx_setPledgedSrcSize(zcs, pledgedSrcSize) , "");5993assert(!ZSTD_isError(ZSTD_checkCParams(params->cParams)));5994zcs->requestedParams = *params;5995assert(!((dict) && (cdict))); /* either dict or cdict, not both */5996if (dict) {5997FORWARD_IF_ERROR( ZSTD_CCtx_loadDictionary(zcs, dict, dictSize) , "");5998} else {5999/* Dictionary is cleared if !cdict */6000FORWARD_IF_ERROR( ZSTD_CCtx_refCDict(zcs, cdict) , "");6001}6002return 0;6003}60046005/* ZSTD_initCStream_usingCDict_advanced() :6006* same as ZSTD_initCStream_usingCDict(), with control over frame parameters */6007size_t ZSTD_initCStream_usingCDict_advanced(ZSTD_CStream* zcs,6008const ZSTD_CDict* cdict,6009ZSTD_frameParameters fParams,6010unsigned long long pledgedSrcSize)6011{6012DEBUGLOG(4, "ZSTD_initCStream_usingCDict_advanced");6013FORWARD_IF_ERROR( ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only) , "");6014FORWARD_IF_ERROR( ZSTD_CCtx_setPledgedSrcSize(zcs, pledgedSrcSize) , "");6015zcs->requestedParams.fParams = fParams;6016FORWARD_IF_ERROR( ZSTD_CCtx_refCDict(zcs, cdict) , "");6017return 0;6018}60196020/* note : cdict must outlive compression session */6021size_t ZSTD_initCStream_usingCDict(ZSTD_CStream* zcs, const ZSTD_CDict* cdict)6022{6023DEBUGLOG(4, "ZSTD_initCStream_usingCDict");6024FORWARD_IF_ERROR( ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only) , "");6025FORWARD_IF_ERROR( ZSTD_CCtx_refCDict(zcs, cdict) , "");6026return 0;6027}602860296030/* ZSTD_initCStream_advanced() :6031* pledgedSrcSize must be exact.6032* if srcSize is not known at init time, use value ZSTD_CONTENTSIZE_UNKNOWN.6033* dict is loaded with default parameters ZSTD_dct_auto and ZSTD_dlm_byCopy. */6034size_t ZSTD_initCStream_advanced(ZSTD_CStream* zcs,6035const void* dict, size_t dictSize,6036ZSTD_parameters params, unsigned long long pss)6037{6038/* for compatibility with older programs relying on this behavior.6039* Users should now specify ZSTD_CONTENTSIZE_UNKNOWN.6040* This line will be removed in the future.6041*/6042U64 const pledgedSrcSize = (pss==0 && params.fParams.contentSizeFlag==0) ? ZSTD_CONTENTSIZE_UNKNOWN : pss;6043DEBUGLOG(4, "ZSTD_initCStream_advanced");6044FORWARD_IF_ERROR( ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only) , "");6045FORWARD_IF_ERROR( ZSTD_CCtx_setPledgedSrcSize(zcs, pledgedSrcSize) , "");6046FORWARD_IF_ERROR( ZSTD_checkCParams(params.cParams) , "");6047ZSTD_CCtxParams_setZstdParams(&zcs->requestedParams, ¶ms);6048FORWARD_IF_ERROR( ZSTD_CCtx_loadDictionary(zcs, dict, dictSize) , "");6049return 0;6050}60516052size_t ZSTD_initCStream_usingDict(ZSTD_CStream* zcs, const void* dict, size_t dictSize, int compressionLevel)6053{6054DEBUGLOG(4, "ZSTD_initCStream_usingDict");6055FORWARD_IF_ERROR( ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only) , "");6056FORWARD_IF_ERROR( ZSTD_CCtx_setParameter(zcs, ZSTD_c_compressionLevel, compressionLevel) , "");6057FORWARD_IF_ERROR( ZSTD_CCtx_loadDictionary(zcs, dict, dictSize) , "");6058return 0;6059}60606061size_t ZSTD_initCStream_srcSize(ZSTD_CStream* zcs, int compressionLevel, unsigned long long pss)6062{6063/* temporary : 0 interpreted as "unknown" during transition period.6064* Users willing to specify "unknown" **must** use ZSTD_CONTENTSIZE_UNKNOWN.6065* 0 will be interpreted as "empty" in the future.6066*/6067U64 const pledgedSrcSize = (pss==0) ? ZSTD_CONTENTSIZE_UNKNOWN : pss;6068DEBUGLOG(4, "ZSTD_initCStream_srcSize");6069FORWARD_IF_ERROR( ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only) , "");6070FORWARD_IF_ERROR( ZSTD_CCtx_refCDict(zcs, NULL) , "");6071FORWARD_IF_ERROR( ZSTD_CCtx_setParameter(zcs, ZSTD_c_compressionLevel, compressionLevel) , "");6072FORWARD_IF_ERROR( ZSTD_CCtx_setPledgedSrcSize(zcs, pledgedSrcSize) , "");6073return 0;6074}60756076size_t ZSTD_initCStream(ZSTD_CStream* zcs, int compressionLevel)6077{6078DEBUGLOG(4, "ZSTD_initCStream");6079FORWARD_IF_ERROR( ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only) , "");6080FORWARD_IF_ERROR( ZSTD_CCtx_refCDict(zcs, NULL) , "");6081FORWARD_IF_ERROR( ZSTD_CCtx_setParameter(zcs, ZSTD_c_compressionLevel, compressionLevel) , "");6082return 0;6083}60846085/*====== Compression ======*/60866087static size_t ZSTD_nextInputSizeHint(const ZSTD_CCtx* cctx)6088{6089if (cctx->appliedParams.inBufferMode == ZSTD_bm_stable) {6090return cctx->blockSizeMax - cctx->stableIn_notConsumed;6091}6092assert(cctx->appliedParams.inBufferMode == ZSTD_bm_buffered);6093{ size_t hintInSize = cctx->inBuffTarget - cctx->inBuffPos;6094if (hintInSize==0) hintInSize = cctx->blockSizeMax;6095return hintInSize;6096}6097}60986099/** ZSTD_compressStream_generic():6100* internal function for all *compressStream*() variants6101* @return : hint size for next input to complete ongoing block */6102static size_t ZSTD_compressStream_generic(ZSTD_CStream* zcs,6103ZSTD_outBuffer* output,6104ZSTD_inBuffer* input,6105ZSTD_EndDirective const flushMode)6106{6107const char* const istart = (assert(input != NULL), (const char*)input->src);6108const char* const iend = (istart != NULL) ? istart + input->size : istart;6109const char* ip = (istart != NULL) ? istart + input->pos : istart;6110char* const ostart = (assert(output != NULL), (char*)output->dst);6111char* const oend = (ostart != NULL) ? ostart + output->size : ostart;6112char* op = (ostart != NULL) ? ostart + output->pos : ostart;6113U32 someMoreWork = 1;61146115/* check expectations */6116DEBUGLOG(5, "ZSTD_compressStream_generic, flush=%i, srcSize = %zu", (int)flushMode, input->size - input->pos);6117assert(zcs != NULL);6118if (zcs->appliedParams.inBufferMode == ZSTD_bm_stable) {6119assert(input->pos >= zcs->stableIn_notConsumed);6120input->pos -= zcs->stableIn_notConsumed;6121if (ip) ip -= zcs->stableIn_notConsumed;6122zcs->stableIn_notConsumed = 0;6123}6124if (zcs->appliedParams.inBufferMode == ZSTD_bm_buffered) {6125assert(zcs->inBuff != NULL);6126assert(zcs->inBuffSize > 0);6127}6128if (zcs->appliedParams.outBufferMode == ZSTD_bm_buffered) {6129assert(zcs->outBuff != NULL);6130assert(zcs->outBuffSize > 0);6131}6132if (input->src == NULL) assert(input->size == 0);6133assert(input->pos <= input->size);6134if (output->dst == NULL) assert(output->size == 0);6135assert(output->pos <= output->size);6136assert((U32)flushMode <= (U32)ZSTD_e_end);61376138while (someMoreWork) {6139switch(zcs->streamStage)6140{6141case zcss_init:6142RETURN_ERROR(init_missing, "call ZSTD_initCStream() first!");61436144case zcss_load:6145if ( (flushMode == ZSTD_e_end)6146&& ( (size_t)(oend-op) >= ZSTD_compressBound((size_t)(iend-ip)) /* Enough output space */6147|| zcs->appliedParams.outBufferMode == ZSTD_bm_stable) /* OR we are allowed to return dstSizeTooSmall */6148&& (zcs->inBuffPos == 0) ) {6149/* shortcut to compression pass directly into output buffer */6150size_t const cSize = ZSTD_compressEnd_public(zcs,6151op, (size_t)(oend-op),6152ip, (size_t)(iend-ip));6153DEBUGLOG(4, "ZSTD_compressEnd : cSize=%u", (unsigned)cSize);6154FORWARD_IF_ERROR(cSize, "ZSTD_compressEnd failed");6155ip = iend;6156op += cSize;6157zcs->frameEnded = 1;6158ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only);6159someMoreWork = 0; break;6160}6161/* complete loading into inBuffer in buffered mode */6162if (zcs->appliedParams.inBufferMode == ZSTD_bm_buffered) {6163size_t const toLoad = zcs->inBuffTarget - zcs->inBuffPos;6164size_t const loaded = ZSTD_limitCopy(6165zcs->inBuff + zcs->inBuffPos, toLoad,6166ip, (size_t)(iend-ip));6167zcs->inBuffPos += loaded;6168if (ip) ip += loaded;6169if ( (flushMode == ZSTD_e_continue)6170&& (zcs->inBuffPos < zcs->inBuffTarget) ) {6171/* not enough input to fill full block : stop here */6172someMoreWork = 0; break;6173}6174if ( (flushMode == ZSTD_e_flush)6175&& (zcs->inBuffPos == zcs->inToCompress) ) {6176/* empty */6177someMoreWork = 0; break;6178}6179} else {6180assert(zcs->appliedParams.inBufferMode == ZSTD_bm_stable);6181if ( (flushMode == ZSTD_e_continue)6182&& ( (size_t)(iend - ip) < zcs->blockSizeMax) ) {6183/* can't compress a full block : stop here */6184zcs->stableIn_notConsumed = (size_t)(iend - ip);6185ip = iend; /* pretend to have consumed input */6186someMoreWork = 0; break;6187}6188if ( (flushMode == ZSTD_e_flush)6189&& (ip == iend) ) {6190/* empty */6191someMoreWork = 0; break;6192}6193}6194/* compress current block (note : this stage cannot be stopped in the middle) */6195DEBUGLOG(5, "stream compression stage (flushMode==%u)", flushMode);6196{ int const inputBuffered = (zcs->appliedParams.inBufferMode == ZSTD_bm_buffered);6197void* cDst;6198size_t cSize;6199size_t oSize = (size_t)(oend-op);6200size_t const iSize = inputBuffered ? zcs->inBuffPos - zcs->inToCompress6201: MIN((size_t)(iend - ip), zcs->blockSizeMax);6202if (oSize >= ZSTD_compressBound(iSize) || zcs->appliedParams.outBufferMode == ZSTD_bm_stable)6203cDst = op; /* compress into output buffer, to skip flush stage */6204else6205cDst = zcs->outBuff, oSize = zcs->outBuffSize;6206if (inputBuffered) {6207unsigned const lastBlock = (flushMode == ZSTD_e_end) && (ip==iend);6208cSize = lastBlock ?6209ZSTD_compressEnd_public(zcs, cDst, oSize,6210zcs->inBuff + zcs->inToCompress, iSize) :6211ZSTD_compressContinue_public(zcs, cDst, oSize,6212zcs->inBuff + zcs->inToCompress, iSize);6213FORWARD_IF_ERROR(cSize, "%s", lastBlock ? "ZSTD_compressEnd failed" : "ZSTD_compressContinue failed");6214zcs->frameEnded = lastBlock;6215/* prepare next block */6216zcs->inBuffTarget = zcs->inBuffPos + zcs->blockSizeMax;6217if (zcs->inBuffTarget > zcs->inBuffSize)6218zcs->inBuffPos = 0, zcs->inBuffTarget = zcs->blockSizeMax;6219DEBUGLOG(5, "inBuffTarget:%u / inBuffSize:%u",6220(unsigned)zcs->inBuffTarget, (unsigned)zcs->inBuffSize);6221if (!lastBlock)6222assert(zcs->inBuffTarget <= zcs->inBuffSize);6223zcs->inToCompress = zcs->inBuffPos;6224} else { /* !inputBuffered, hence ZSTD_bm_stable */6225unsigned const lastBlock = (flushMode == ZSTD_e_end) && (ip + iSize == iend);6226cSize = lastBlock ?6227ZSTD_compressEnd_public(zcs, cDst, oSize, ip, iSize) :6228ZSTD_compressContinue_public(zcs, cDst, oSize, ip, iSize);6229/* Consume the input prior to error checking to mirror buffered mode. */6230if (ip) ip += iSize;6231FORWARD_IF_ERROR(cSize, "%s", lastBlock ? "ZSTD_compressEnd failed" : "ZSTD_compressContinue failed");6232zcs->frameEnded = lastBlock;6233if (lastBlock) assert(ip == iend);6234}6235if (cDst == op) { /* no need to flush */6236op += cSize;6237if (zcs->frameEnded) {6238DEBUGLOG(5, "Frame completed directly in outBuffer");6239someMoreWork = 0;6240ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only);6241}6242break;6243}6244zcs->outBuffContentSize = cSize;6245zcs->outBuffFlushedSize = 0;6246zcs->streamStage = zcss_flush; /* pass-through to flush stage */6247}6248ZSTD_FALLTHROUGH;6249case zcss_flush:6250DEBUGLOG(5, "flush stage");6251assert(zcs->appliedParams.outBufferMode == ZSTD_bm_buffered);6252{ size_t const toFlush = zcs->outBuffContentSize - zcs->outBuffFlushedSize;6253size_t const flushed = ZSTD_limitCopy(op, (size_t)(oend-op),6254zcs->outBuff + zcs->outBuffFlushedSize, toFlush);6255DEBUGLOG(5, "toFlush: %u into %u ==> flushed: %u",6256(unsigned)toFlush, (unsigned)(oend-op), (unsigned)flushed);6257if (flushed)6258op += flushed;6259zcs->outBuffFlushedSize += flushed;6260if (toFlush!=flushed) {6261/* flush not fully completed, presumably because dst is too small */6262assert(op==oend);6263someMoreWork = 0;6264break;6265}6266zcs->outBuffContentSize = zcs->outBuffFlushedSize = 0;6267if (zcs->frameEnded) {6268DEBUGLOG(5, "Frame completed on flush");6269someMoreWork = 0;6270ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only);6271break;6272}6273zcs->streamStage = zcss_load;6274break;6275}62766277default: /* impossible */6278assert(0);6279}6280}62816282input->pos = (size_t)(ip - istart);6283output->pos = (size_t)(op - ostart);6284if (zcs->frameEnded) return 0;6285return ZSTD_nextInputSizeHint(zcs);6286}62876288static size_t ZSTD_nextInputSizeHint_MTorST(const ZSTD_CCtx* cctx)6289{6290#ifdef ZSTD_MULTITHREAD6291if (cctx->appliedParams.nbWorkers >= 1) {6292assert(cctx->mtctx != NULL);6293return ZSTDMT_nextInputSizeHint(cctx->mtctx);6294}6295#endif6296return ZSTD_nextInputSizeHint(cctx);62976298}62996300size_t ZSTD_compressStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output, ZSTD_inBuffer* input)6301{6302FORWARD_IF_ERROR( ZSTD_compressStream2(zcs, output, input, ZSTD_e_continue) , "");6303return ZSTD_nextInputSizeHint_MTorST(zcs);6304}63056306/* After a compression call set the expected input/output buffer.6307* This is validated at the start of the next compression call.6308*/6309static void6310ZSTD_setBufferExpectations(ZSTD_CCtx* cctx, const ZSTD_outBuffer* output, const ZSTD_inBuffer* input)6311{6312DEBUGLOG(5, "ZSTD_setBufferExpectations (for advanced stable in/out modes)");6313if (cctx->appliedParams.inBufferMode == ZSTD_bm_stable) {6314cctx->expectedInBuffer = *input;6315}6316if (cctx->appliedParams.outBufferMode == ZSTD_bm_stable) {6317cctx->expectedOutBufferSize = output->size - output->pos;6318}6319}63206321/* Validate that the input/output buffers match the expectations set by6322* ZSTD_setBufferExpectations.6323*/6324static size_t ZSTD_checkBufferStability(ZSTD_CCtx const* cctx,6325ZSTD_outBuffer const* output,6326ZSTD_inBuffer const* input,6327ZSTD_EndDirective endOp)6328{6329if (cctx->appliedParams.inBufferMode == ZSTD_bm_stable) {6330ZSTD_inBuffer const expect = cctx->expectedInBuffer;6331if (expect.src != input->src || expect.pos != input->pos)6332RETURN_ERROR(stabilityCondition_notRespected, "ZSTD_c_stableInBuffer enabled but input differs!");6333}6334(void)endOp;6335if (cctx->appliedParams.outBufferMode == ZSTD_bm_stable) {6336size_t const outBufferSize = output->size - output->pos;6337if (cctx->expectedOutBufferSize != outBufferSize)6338RETURN_ERROR(stabilityCondition_notRespected, "ZSTD_c_stableOutBuffer enabled but output size differs!");6339}6340return 0;6341}63426343/*6344* If @endOp == ZSTD_e_end, @inSize becomes pledgedSrcSize.6345* Otherwise, it's ignored.6346* @return: 0 on success, or a ZSTD_error code otherwise.6347*/6348static size_t ZSTD_CCtx_init_compressStream2(ZSTD_CCtx* cctx,6349ZSTD_EndDirective endOp,6350size_t inSize)6351{6352ZSTD_CCtx_params params = cctx->requestedParams;6353ZSTD_prefixDict const prefixDict = cctx->prefixDict;6354FORWARD_IF_ERROR( ZSTD_initLocalDict(cctx) , ""); /* Init the local dict if present. */6355ZSTD_memset(&cctx->prefixDict, 0, sizeof(cctx->prefixDict)); /* single usage */6356assert(prefixDict.dict==NULL || cctx->cdict==NULL); /* only one can be set */6357if (cctx->cdict && !cctx->localDict.cdict) {6358/* Let the cdict's compression level take priority over the requested params.6359* But do not take the cdict's compression level if the "cdict" is actually a localDict6360* generated from ZSTD_initLocalDict().6361*/6362params.compressionLevel = cctx->cdict->compressionLevel;6363}6364DEBUGLOG(4, "ZSTD_CCtx_init_compressStream2 : transparent init stage");6365if (endOp == ZSTD_e_end) cctx->pledgedSrcSizePlusOne = inSize + 1; /* auto-determine pledgedSrcSize */63666367{ size_t const dictSize = prefixDict.dict6368? prefixDict.dictSize6369: (cctx->cdict ? cctx->cdict->dictContentSize : 0);6370ZSTD_CParamMode_e const mode = ZSTD_getCParamMode(cctx->cdict, ¶ms, cctx->pledgedSrcSizePlusOne - 1);6371params.cParams = ZSTD_getCParamsFromCCtxParams(6372¶ms, cctx->pledgedSrcSizePlusOne-1,6373dictSize, mode);6374}63756376params.postBlockSplitter = ZSTD_resolveBlockSplitterMode(params.postBlockSplitter, ¶ms.cParams);6377params.ldmParams.enableLdm = ZSTD_resolveEnableLdm(params.ldmParams.enableLdm, ¶ms.cParams);6378params.useRowMatchFinder = ZSTD_resolveRowMatchFinderMode(params.useRowMatchFinder, ¶ms.cParams);6379params.validateSequences = ZSTD_resolveExternalSequenceValidation(params.validateSequences);6380params.maxBlockSize = ZSTD_resolveMaxBlockSize(params.maxBlockSize);6381params.searchForExternalRepcodes = ZSTD_resolveExternalRepcodeSearch(params.searchForExternalRepcodes, params.compressionLevel);63826383#ifdef ZSTD_MULTITHREAD6384/* If external matchfinder is enabled, make sure to fail before checking job size (for consistency) */6385RETURN_ERROR_IF(6386ZSTD_hasExtSeqProd(¶ms) && params.nbWorkers >= 1,6387parameter_combination_unsupported,6388"External sequence producer isn't supported with nbWorkers >= 1"6389);63906391if ((cctx->pledgedSrcSizePlusOne-1) <= ZSTDMT_JOBSIZE_MIN) {6392params.nbWorkers = 0; /* do not invoke multi-threading when src size is too small */6393}6394if (params.nbWorkers > 0) {6395# if ZSTD_TRACE6396cctx->traceCtx = (ZSTD_trace_compress_begin != NULL) ? ZSTD_trace_compress_begin(cctx) : 0;6397# endif6398/* mt context creation */6399if (cctx->mtctx == NULL) {6400DEBUGLOG(4, "ZSTD_compressStream2: creating new mtctx for nbWorkers=%u",6401params.nbWorkers);6402cctx->mtctx = ZSTDMT_createCCtx_advanced((U32)params.nbWorkers, cctx->customMem, cctx->pool);6403RETURN_ERROR_IF(cctx->mtctx == NULL, memory_allocation, "NULL pointer!");6404}6405/* mt compression */6406DEBUGLOG(4, "call ZSTDMT_initCStream_internal as nbWorkers=%u", params.nbWorkers);6407FORWARD_IF_ERROR( ZSTDMT_initCStream_internal(6408cctx->mtctx,6409prefixDict.dict, prefixDict.dictSize, prefixDict.dictContentType,6410cctx->cdict, params, cctx->pledgedSrcSizePlusOne-1) , "");6411cctx->dictID = cctx->cdict ? cctx->cdict->dictID : 0;6412cctx->dictContentSize = cctx->cdict ? cctx->cdict->dictContentSize : prefixDict.dictSize;6413cctx->consumedSrcSize = 0;6414cctx->producedCSize = 0;6415cctx->streamStage = zcss_load;6416cctx->appliedParams = params;6417} else6418#endif /* ZSTD_MULTITHREAD */6419{ U64 const pledgedSrcSize = cctx->pledgedSrcSizePlusOne - 1;6420assert(!ZSTD_isError(ZSTD_checkCParams(params.cParams)));6421FORWARD_IF_ERROR( ZSTD_compressBegin_internal(cctx,6422prefixDict.dict, prefixDict.dictSize, prefixDict.dictContentType, ZSTD_dtlm_fast,6423cctx->cdict,6424¶ms, pledgedSrcSize,6425ZSTDb_buffered) , "");6426assert(cctx->appliedParams.nbWorkers == 0);6427cctx->inToCompress = 0;6428cctx->inBuffPos = 0;6429if (cctx->appliedParams.inBufferMode == ZSTD_bm_buffered) {6430/* for small input: avoid automatic flush on reaching end of block, since6431* it would require to add a 3-bytes null block to end frame6432*/6433cctx->inBuffTarget = cctx->blockSizeMax + (cctx->blockSizeMax == pledgedSrcSize);6434} else {6435cctx->inBuffTarget = 0;6436}6437cctx->outBuffContentSize = cctx->outBuffFlushedSize = 0;6438cctx->streamStage = zcss_load;6439cctx->frameEnded = 0;6440}6441return 0;6442}64436444/* @return provides a minimum amount of data remaining to be flushed from internal buffers6445*/6446size_t ZSTD_compressStream2( ZSTD_CCtx* cctx,6447ZSTD_outBuffer* output,6448ZSTD_inBuffer* input,6449ZSTD_EndDirective endOp)6450{6451DEBUGLOG(5, "ZSTD_compressStream2, endOp=%u ", (unsigned)endOp);6452/* check conditions */6453RETURN_ERROR_IF(output->pos > output->size, dstSize_tooSmall, "invalid output buffer");6454RETURN_ERROR_IF(input->pos > input->size, srcSize_wrong, "invalid input buffer");6455RETURN_ERROR_IF((U32)endOp > (U32)ZSTD_e_end, parameter_outOfBound, "invalid endDirective");6456assert(cctx != NULL);64576458/* transparent initialization stage */6459if (cctx->streamStage == zcss_init) {6460size_t const inputSize = input->size - input->pos; /* no obligation to start from pos==0 */6461size_t const totalInputSize = inputSize + cctx->stableIn_notConsumed;6462if ( (cctx->requestedParams.inBufferMode == ZSTD_bm_stable) /* input is presumed stable, across invocations */6463&& (endOp == ZSTD_e_continue) /* no flush requested, more input to come */6464&& (totalInputSize < ZSTD_BLOCKSIZE_MAX) ) { /* not even reached one block yet */6465if (cctx->stableIn_notConsumed) { /* not the first time */6466/* check stable source guarantees */6467RETURN_ERROR_IF(input->src != cctx->expectedInBuffer.src, stabilityCondition_notRespected, "stableInBuffer condition not respected: wrong src pointer");6468RETURN_ERROR_IF(input->pos != cctx->expectedInBuffer.size, stabilityCondition_notRespected, "stableInBuffer condition not respected: externally modified pos");6469}6470/* pretend input was consumed, to give a sense forward progress */6471input->pos = input->size;6472/* save stable inBuffer, for later control, and flush/end */6473cctx->expectedInBuffer = *input;6474/* but actually input wasn't consumed, so keep track of position from where compression shall resume */6475cctx->stableIn_notConsumed += inputSize;6476/* don't initialize yet, wait for the first block of flush() order, for better parameters adaptation */6477return ZSTD_FRAMEHEADERSIZE_MIN(cctx->requestedParams.format); /* at least some header to produce */6478}6479FORWARD_IF_ERROR(ZSTD_CCtx_init_compressStream2(cctx, endOp, totalInputSize), "compressStream2 initialization failed");6480ZSTD_setBufferExpectations(cctx, output, input); /* Set initial buffer expectations now that we've initialized */6481}6482/* end of transparent initialization stage */64836484FORWARD_IF_ERROR(ZSTD_checkBufferStability(cctx, output, input, endOp), "invalid buffers");6485/* compression stage */6486#ifdef ZSTD_MULTITHREAD6487if (cctx->appliedParams.nbWorkers > 0) {6488size_t flushMin;6489if (cctx->cParamsChanged) {6490ZSTDMT_updateCParams_whileCompressing(cctx->mtctx, &cctx->requestedParams);6491cctx->cParamsChanged = 0;6492}6493if (cctx->stableIn_notConsumed) {6494assert(cctx->appliedParams.inBufferMode == ZSTD_bm_stable);6495/* some early data was skipped - make it available for consumption */6496assert(input->pos >= cctx->stableIn_notConsumed);6497input->pos -= cctx->stableIn_notConsumed;6498cctx->stableIn_notConsumed = 0;6499}6500for (;;) {6501size_t const ipos = input->pos;6502size_t const opos = output->pos;6503flushMin = ZSTDMT_compressStream_generic(cctx->mtctx, output, input, endOp);6504cctx->consumedSrcSize += (U64)(input->pos - ipos);6505cctx->producedCSize += (U64)(output->pos - opos);6506if ( ZSTD_isError(flushMin)6507|| (endOp == ZSTD_e_end && flushMin == 0) ) { /* compression completed */6508if (flushMin == 0)6509ZSTD_CCtx_trace(cctx, 0);6510ZSTD_CCtx_reset(cctx, ZSTD_reset_session_only);6511}6512FORWARD_IF_ERROR(flushMin, "ZSTDMT_compressStream_generic failed");65136514if (endOp == ZSTD_e_continue) {6515/* We only require some progress with ZSTD_e_continue, not maximal progress.6516* We're done if we've consumed or produced any bytes, or either buffer is6517* full.6518*/6519if (input->pos != ipos || output->pos != opos || input->pos == input->size || output->pos == output->size)6520break;6521} else {6522assert(endOp == ZSTD_e_flush || endOp == ZSTD_e_end);6523/* We require maximal progress. We're done when the flush is complete or the6524* output buffer is full.6525*/6526if (flushMin == 0 || output->pos == output->size)6527break;6528}6529}6530DEBUGLOG(5, "completed ZSTD_compressStream2 delegating to ZSTDMT_compressStream_generic");6531/* Either we don't require maximum forward progress, we've finished the6532* flush, or we are out of output space.6533*/6534assert(endOp == ZSTD_e_continue || flushMin == 0 || output->pos == output->size);6535ZSTD_setBufferExpectations(cctx, output, input);6536return flushMin;6537}6538#endif /* ZSTD_MULTITHREAD */6539FORWARD_IF_ERROR( ZSTD_compressStream_generic(cctx, output, input, endOp) , "");6540DEBUGLOG(5, "completed ZSTD_compressStream2");6541ZSTD_setBufferExpectations(cctx, output, input);6542return cctx->outBuffContentSize - cctx->outBuffFlushedSize; /* remaining to flush */6543}65446545size_t ZSTD_compressStream2_simpleArgs (6546ZSTD_CCtx* cctx,6547void* dst, size_t dstCapacity, size_t* dstPos,6548const void* src, size_t srcSize, size_t* srcPos,6549ZSTD_EndDirective endOp)6550{6551ZSTD_outBuffer output;6552ZSTD_inBuffer input;6553output.dst = dst;6554output.size = dstCapacity;6555output.pos = *dstPos;6556input.src = src;6557input.size = srcSize;6558input.pos = *srcPos;6559/* ZSTD_compressStream2() will check validity of dstPos and srcPos */6560{ size_t const cErr = ZSTD_compressStream2(cctx, &output, &input, endOp);6561*dstPos = output.pos;6562*srcPos = input.pos;6563return cErr;6564}6565}65666567size_t ZSTD_compress2(ZSTD_CCtx* cctx,6568void* dst, size_t dstCapacity,6569const void* src, size_t srcSize)6570{6571ZSTD_bufferMode_e const originalInBufferMode = cctx->requestedParams.inBufferMode;6572ZSTD_bufferMode_e const originalOutBufferMode = cctx->requestedParams.outBufferMode;6573DEBUGLOG(4, "ZSTD_compress2 (srcSize=%u)", (unsigned)srcSize);6574ZSTD_CCtx_reset(cctx, ZSTD_reset_session_only);6575/* Enable stable input/output buffers. */6576cctx->requestedParams.inBufferMode = ZSTD_bm_stable;6577cctx->requestedParams.outBufferMode = ZSTD_bm_stable;6578{ size_t oPos = 0;6579size_t iPos = 0;6580size_t const result = ZSTD_compressStream2_simpleArgs(cctx,6581dst, dstCapacity, &oPos,6582src, srcSize, &iPos,6583ZSTD_e_end);6584/* Reset to the original values. */6585cctx->requestedParams.inBufferMode = originalInBufferMode;6586cctx->requestedParams.outBufferMode = originalOutBufferMode;65876588FORWARD_IF_ERROR(result, "ZSTD_compressStream2_simpleArgs failed");6589if (result != 0) { /* compression not completed, due to lack of output space */6590assert(oPos == dstCapacity);6591RETURN_ERROR(dstSize_tooSmall, "");6592}6593assert(iPos == srcSize); /* all input is expected consumed */6594return oPos;6595}6596}65976598/* ZSTD_validateSequence() :6599* @offBase : must use the format required by ZSTD_storeSeq()6600* @returns a ZSTD error code if sequence is not valid6601*/6602static size_t6603ZSTD_validateSequence(U32 offBase, U32 matchLength, U32 minMatch,6604size_t posInSrc, U32 windowLog, size_t dictSize, int useSequenceProducer)6605{6606U32 const windowSize = 1u << windowLog;6607/* posInSrc represents the amount of data the decoder would decode up to this point.6608* As long as the amount of data decoded is less than or equal to window size, offsets may be6609* larger than the total length of output decoded in order to reference the dict, even larger than6610* window size. After output surpasses windowSize, we're limited to windowSize offsets again.6611*/6612size_t const offsetBound = posInSrc > windowSize ? (size_t)windowSize : posInSrc + (size_t)dictSize;6613size_t const matchLenLowerBound = (minMatch == 3 || useSequenceProducer) ? 3 : 4;6614RETURN_ERROR_IF(offBase > OFFSET_TO_OFFBASE(offsetBound), externalSequences_invalid, "Offset too large!");6615/* Validate maxNbSeq is large enough for the given matchLength and minMatch */6616RETURN_ERROR_IF(matchLength < matchLenLowerBound, externalSequences_invalid, "Matchlength too small for the minMatch");6617return 0;6618}66196620/* Returns an offset code, given a sequence's raw offset, the ongoing repcode array, and whether litLength == 0 */6621static U32 ZSTD_finalizeOffBase(U32 rawOffset, const U32 rep[ZSTD_REP_NUM], U32 ll0)6622{6623U32 offBase = OFFSET_TO_OFFBASE(rawOffset);66246625if (!ll0 && rawOffset == rep[0]) {6626offBase = REPCODE1_TO_OFFBASE;6627} else if (rawOffset == rep[1]) {6628offBase = REPCODE_TO_OFFBASE(2 - ll0);6629} else if (rawOffset == rep[2]) {6630offBase = REPCODE_TO_OFFBASE(3 - ll0);6631} else if (ll0 && rawOffset == rep[0] - 1) {6632offBase = REPCODE3_TO_OFFBASE;6633}6634return offBase;6635}66366637/* This function scans through an array of ZSTD_Sequence,6638* storing the sequences it reads, until it reaches a block delimiter.6639* Note that the block delimiter includes the last literals of the block.6640* @blockSize must be == sum(sequence_lengths).6641* @returns @blockSize on success, and a ZSTD_error otherwise.6642*/6643static size_t6644ZSTD_transferSequences_wBlockDelim(ZSTD_CCtx* cctx,6645ZSTD_SequencePosition* seqPos,6646const ZSTD_Sequence* const inSeqs, size_t inSeqsSize,6647const void* src, size_t blockSize,6648ZSTD_ParamSwitch_e externalRepSearch)6649{6650U32 idx = seqPos->idx;6651U32 const startIdx = idx;6652BYTE const* ip = (BYTE const*)(src);6653const BYTE* const iend = ip + blockSize;6654Repcodes_t updatedRepcodes;6655U32 dictSize;66566657DEBUGLOG(5, "ZSTD_transferSequences_wBlockDelim (blockSize = %zu)", blockSize);66586659if (cctx->cdict) {6660dictSize = (U32)cctx->cdict->dictContentSize;6661} else if (cctx->prefixDict.dict) {6662dictSize = (U32)cctx->prefixDict.dictSize;6663} else {6664dictSize = 0;6665}6666ZSTD_memcpy(updatedRepcodes.rep, cctx->blockState.prevCBlock->rep, sizeof(Repcodes_t));6667for (; idx < inSeqsSize && (inSeqs[idx].matchLength != 0 || inSeqs[idx].offset != 0); ++idx) {6668U32 const litLength = inSeqs[idx].litLength;6669U32 const matchLength = inSeqs[idx].matchLength;6670U32 offBase;66716672if (externalRepSearch == ZSTD_ps_disable) {6673offBase = OFFSET_TO_OFFBASE(inSeqs[idx].offset);6674} else {6675U32 const ll0 = (litLength == 0);6676offBase = ZSTD_finalizeOffBase(inSeqs[idx].offset, updatedRepcodes.rep, ll0);6677ZSTD_updateRep(updatedRepcodes.rep, offBase, ll0);6678}66796680DEBUGLOG(6, "Storing sequence: (of: %u, ml: %u, ll: %u)", offBase, matchLength, litLength);6681if (cctx->appliedParams.validateSequences) {6682seqPos->posInSrc += litLength + matchLength;6683FORWARD_IF_ERROR(ZSTD_validateSequence(offBase, matchLength, cctx->appliedParams.cParams.minMatch,6684seqPos->posInSrc,6685cctx->appliedParams.cParams.windowLog, dictSize,6686ZSTD_hasExtSeqProd(&cctx->appliedParams)),6687"Sequence validation failed");6688}6689RETURN_ERROR_IF(idx - seqPos->idx >= cctx->seqStore.maxNbSeq, externalSequences_invalid,6690"Not enough memory allocated. Try adjusting ZSTD_c_minMatch.");6691ZSTD_storeSeq(&cctx->seqStore, litLength, ip, iend, offBase, matchLength);6692ip += matchLength + litLength;6693}6694RETURN_ERROR_IF(idx == inSeqsSize, externalSequences_invalid, "Block delimiter not found.");66956696/* If we skipped repcode search while parsing, we need to update repcodes now */6697assert(externalRepSearch != ZSTD_ps_auto);6698assert(idx >= startIdx);6699if (externalRepSearch == ZSTD_ps_disable && idx != startIdx) {6700U32* const rep = updatedRepcodes.rep;6701U32 lastSeqIdx = idx - 1; /* index of last non-block-delimiter sequence */67026703if (lastSeqIdx >= startIdx + 2) {6704rep[2] = inSeqs[lastSeqIdx - 2].offset;6705rep[1] = inSeqs[lastSeqIdx - 1].offset;6706rep[0] = inSeqs[lastSeqIdx].offset;6707} else if (lastSeqIdx == startIdx + 1) {6708rep[2] = rep[0];6709rep[1] = inSeqs[lastSeqIdx - 1].offset;6710rep[0] = inSeqs[lastSeqIdx].offset;6711} else {6712assert(lastSeqIdx == startIdx);6713rep[2] = rep[1];6714rep[1] = rep[0];6715rep[0] = inSeqs[lastSeqIdx].offset;6716}6717}67186719ZSTD_memcpy(cctx->blockState.nextCBlock->rep, updatedRepcodes.rep, sizeof(Repcodes_t));67206721if (inSeqs[idx].litLength) {6722DEBUGLOG(6, "Storing last literals of size: %u", inSeqs[idx].litLength);6723ZSTD_storeLastLiterals(&cctx->seqStore, ip, inSeqs[idx].litLength);6724ip += inSeqs[idx].litLength;6725seqPos->posInSrc += inSeqs[idx].litLength;6726}6727RETURN_ERROR_IF(ip != iend, externalSequences_invalid, "Blocksize doesn't agree with block delimiter!");6728seqPos->idx = idx+1;6729return blockSize;6730}67316732/*6733* This function attempts to scan through @blockSize bytes in @src6734* represented by the sequences in @inSeqs,6735* storing any (partial) sequences.6736*6737* Occasionally, we may want to reduce the actual number of bytes consumed from @src6738* to avoid splitting a match, notably if it would produce a match smaller than MINMATCH.6739*6740* @returns the number of bytes consumed from @src, necessarily <= @blockSize.6741* Otherwise, it may return a ZSTD error if something went wrong.6742*/6743static size_t6744ZSTD_transferSequences_noDelim(ZSTD_CCtx* cctx,6745ZSTD_SequencePosition* seqPos,6746const ZSTD_Sequence* const inSeqs, size_t inSeqsSize,6747const void* src, size_t blockSize,6748ZSTD_ParamSwitch_e externalRepSearch)6749{6750U32 idx = seqPos->idx;6751U32 startPosInSequence = seqPos->posInSequence;6752U32 endPosInSequence = seqPos->posInSequence + (U32)blockSize;6753size_t dictSize;6754const BYTE* const istart = (const BYTE*)(src);6755const BYTE* ip = istart;6756const BYTE* iend = istart + blockSize; /* May be adjusted if we decide to process fewer than blockSize bytes */6757Repcodes_t updatedRepcodes;6758U32 bytesAdjustment = 0;6759U32 finalMatchSplit = 0;67606761/* TODO(embg) support fast parsing mode in noBlockDelim mode */6762(void)externalRepSearch;67636764if (cctx->cdict) {6765dictSize = cctx->cdict->dictContentSize;6766} else if (cctx->prefixDict.dict) {6767dictSize = cctx->prefixDict.dictSize;6768} else {6769dictSize = 0;6770}6771DEBUGLOG(5, "ZSTD_transferSequences_noDelim: idx: %u PIS: %u blockSize: %zu", idx, startPosInSequence, blockSize);6772DEBUGLOG(5, "Start seq: idx: %u (of: %u ml: %u ll: %u)", idx, inSeqs[idx].offset, inSeqs[idx].matchLength, inSeqs[idx].litLength);6773ZSTD_memcpy(updatedRepcodes.rep, cctx->blockState.prevCBlock->rep, sizeof(Repcodes_t));6774while (endPosInSequence && idx < inSeqsSize && !finalMatchSplit) {6775const ZSTD_Sequence currSeq = inSeqs[idx];6776U32 litLength = currSeq.litLength;6777U32 matchLength = currSeq.matchLength;6778U32 const rawOffset = currSeq.offset;6779U32 offBase;67806781/* Modify the sequence depending on where endPosInSequence lies */6782if (endPosInSequence >= currSeq.litLength + currSeq.matchLength) {6783if (startPosInSequence >= litLength) {6784startPosInSequence -= litLength;6785litLength = 0;6786matchLength -= startPosInSequence;6787} else {6788litLength -= startPosInSequence;6789}6790/* Move to the next sequence */6791endPosInSequence -= currSeq.litLength + currSeq.matchLength;6792startPosInSequence = 0;6793} else {6794/* This is the final (partial) sequence we're adding from inSeqs, and endPosInSequence6795does not reach the end of the match. So, we have to split the sequence */6796DEBUGLOG(6, "Require a split: diff: %u, idx: %u PIS: %u",6797currSeq.litLength + currSeq.matchLength - endPosInSequence, idx, endPosInSequence);6798if (endPosInSequence > litLength) {6799U32 firstHalfMatchLength;6800litLength = startPosInSequence >= litLength ? 0 : litLength - startPosInSequence;6801firstHalfMatchLength = endPosInSequence - startPosInSequence - litLength;6802if (matchLength > blockSize && firstHalfMatchLength >= cctx->appliedParams.cParams.minMatch) {6803/* Only ever split the match if it is larger than the block size */6804U32 secondHalfMatchLength = currSeq.matchLength + currSeq.litLength - endPosInSequence;6805if (secondHalfMatchLength < cctx->appliedParams.cParams.minMatch) {6806/* Move the endPosInSequence backward so that it creates match of minMatch length */6807endPosInSequence -= cctx->appliedParams.cParams.minMatch - secondHalfMatchLength;6808bytesAdjustment = cctx->appliedParams.cParams.minMatch - secondHalfMatchLength;6809firstHalfMatchLength -= bytesAdjustment;6810}6811matchLength = firstHalfMatchLength;6812/* Flag that we split the last match - after storing the sequence, exit the loop,6813but keep the value of endPosInSequence */6814finalMatchSplit = 1;6815} else {6816/* Move the position in sequence backwards so that we don't split match, and break to store6817* the last literals. We use the original currSeq.litLength as a marker for where endPosInSequence6818* should go. We prefer to do this whenever it is not necessary to split the match, or if doing so6819* would cause the first half of the match to be too small6820*/6821bytesAdjustment = endPosInSequence - currSeq.litLength;6822endPosInSequence = currSeq.litLength;6823break;6824}6825} else {6826/* This sequence ends inside the literals, break to store the last literals */6827break;6828}6829}6830/* Check if this offset can be represented with a repcode */6831{ U32 const ll0 = (litLength == 0);6832offBase = ZSTD_finalizeOffBase(rawOffset, updatedRepcodes.rep, ll0);6833ZSTD_updateRep(updatedRepcodes.rep, offBase, ll0);6834}68356836if (cctx->appliedParams.validateSequences) {6837seqPos->posInSrc += litLength + matchLength;6838FORWARD_IF_ERROR(ZSTD_validateSequence(offBase, matchLength, cctx->appliedParams.cParams.minMatch, seqPos->posInSrc,6839cctx->appliedParams.cParams.windowLog, dictSize, ZSTD_hasExtSeqProd(&cctx->appliedParams)),6840"Sequence validation failed");6841}6842DEBUGLOG(6, "Storing sequence: (of: %u, ml: %u, ll: %u)", offBase, matchLength, litLength);6843RETURN_ERROR_IF(idx - seqPos->idx >= cctx->seqStore.maxNbSeq, externalSequences_invalid,6844"Not enough memory allocated. Try adjusting ZSTD_c_minMatch.");6845ZSTD_storeSeq(&cctx->seqStore, litLength, ip, iend, offBase, matchLength);6846ip += matchLength + litLength;6847if (!finalMatchSplit)6848idx++; /* Next Sequence */6849}6850DEBUGLOG(5, "Ending seq: idx: %u (of: %u ml: %u ll: %u)", idx, inSeqs[idx].offset, inSeqs[idx].matchLength, inSeqs[idx].litLength);6851assert(idx == inSeqsSize || endPosInSequence <= inSeqs[idx].litLength + inSeqs[idx].matchLength);6852seqPos->idx = idx;6853seqPos->posInSequence = endPosInSequence;6854ZSTD_memcpy(cctx->blockState.nextCBlock->rep, updatedRepcodes.rep, sizeof(Repcodes_t));68556856iend -= bytesAdjustment;6857if (ip != iend) {6858/* Store any last literals */6859U32 const lastLLSize = (U32)(iend - ip);6860assert(ip <= iend);6861DEBUGLOG(6, "Storing last literals of size: %u", lastLLSize);6862ZSTD_storeLastLiterals(&cctx->seqStore, ip, lastLLSize);6863seqPos->posInSrc += lastLLSize;6864}68656866return (size_t)(iend-istart);6867}68686869/* @seqPos represents a position within @inSeqs,6870* it is read and updated by this function,6871* once the goal to produce a block of size @blockSize is reached.6872* @return: nb of bytes consumed from @src, necessarily <= @blockSize.6873*/6874typedef size_t (*ZSTD_SequenceCopier_f)(ZSTD_CCtx* cctx,6875ZSTD_SequencePosition* seqPos,6876const ZSTD_Sequence* const inSeqs, size_t inSeqsSize,6877const void* src, size_t blockSize,6878ZSTD_ParamSwitch_e externalRepSearch);68796880static ZSTD_SequenceCopier_f ZSTD_selectSequenceCopier(ZSTD_SequenceFormat_e mode)6881{6882assert(ZSTD_cParam_withinBounds(ZSTD_c_blockDelimiters, (int)mode));6883if (mode == ZSTD_sf_explicitBlockDelimiters) {6884return ZSTD_transferSequences_wBlockDelim;6885}6886assert(mode == ZSTD_sf_noBlockDelimiters);6887return ZSTD_transferSequences_noDelim;6888}68896890/* Discover the size of next block by searching for the delimiter.6891* Note that a block delimiter **must** exist in this mode,6892* otherwise it's an input error.6893* The block size retrieved will be later compared to ensure it remains within bounds */6894static size_t6895blockSize_explicitDelimiter(const ZSTD_Sequence* inSeqs, size_t inSeqsSize, ZSTD_SequencePosition seqPos)6896{6897int end = 0;6898size_t blockSize = 0;6899size_t spos = seqPos.idx;6900DEBUGLOG(6, "blockSize_explicitDelimiter : seq %zu / %zu", spos, inSeqsSize);6901assert(spos <= inSeqsSize);6902while (spos < inSeqsSize) {6903end = (inSeqs[spos].offset == 0);6904blockSize += inSeqs[spos].litLength + inSeqs[spos].matchLength;6905if (end) {6906if (inSeqs[spos].matchLength != 0)6907RETURN_ERROR(externalSequences_invalid, "delimiter format error : both matchlength and offset must be == 0");6908break;6909}6910spos++;6911}6912if (!end)6913RETURN_ERROR(externalSequences_invalid, "Reached end of sequences without finding a block delimiter");6914return blockSize;6915}69166917static size_t determine_blockSize(ZSTD_SequenceFormat_e mode,6918size_t blockSize, size_t remaining,6919const ZSTD_Sequence* inSeqs, size_t inSeqsSize,6920ZSTD_SequencePosition seqPos)6921{6922DEBUGLOG(6, "determine_blockSize : remainingSize = %zu", remaining);6923if (mode == ZSTD_sf_noBlockDelimiters) {6924/* Note: more a "target" block size */6925return MIN(remaining, blockSize);6926}6927assert(mode == ZSTD_sf_explicitBlockDelimiters);6928{ size_t const explicitBlockSize = blockSize_explicitDelimiter(inSeqs, inSeqsSize, seqPos);6929FORWARD_IF_ERROR(explicitBlockSize, "Error while determining block size with explicit delimiters");6930if (explicitBlockSize > blockSize)6931RETURN_ERROR(externalSequences_invalid, "sequences incorrectly define a too large block");6932if (explicitBlockSize > remaining)6933RETURN_ERROR(externalSequences_invalid, "sequences define a frame longer than source");6934return explicitBlockSize;6935}6936}69376938/* Compress all provided sequences, block-by-block.6939*6940* Returns the cumulative size of all compressed blocks (including their headers),6941* otherwise a ZSTD error.6942*/6943static size_t6944ZSTD_compressSequences_internal(ZSTD_CCtx* cctx,6945void* dst, size_t dstCapacity,6946const ZSTD_Sequence* inSeqs, size_t inSeqsSize,6947const void* src, size_t srcSize)6948{6949size_t cSize = 0;6950size_t remaining = srcSize;6951ZSTD_SequencePosition seqPos = {0, 0, 0};69526953const BYTE* ip = (BYTE const*)src;6954BYTE* op = (BYTE*)dst;6955ZSTD_SequenceCopier_f const sequenceCopier = ZSTD_selectSequenceCopier(cctx->appliedParams.blockDelimiters);69566957DEBUGLOG(4, "ZSTD_compressSequences_internal srcSize: %zu, inSeqsSize: %zu", srcSize, inSeqsSize);6958/* Special case: empty frame */6959if (remaining == 0) {6960U32 const cBlockHeader24 = 1 /* last block */ + (((U32)bt_raw)<<1);6961RETURN_ERROR_IF(dstCapacity<4, dstSize_tooSmall, "No room for empty frame block header");6962MEM_writeLE32(op, cBlockHeader24);6963op += ZSTD_blockHeaderSize;6964dstCapacity -= ZSTD_blockHeaderSize;6965cSize += ZSTD_blockHeaderSize;6966}69676968while (remaining) {6969size_t compressedSeqsSize;6970size_t cBlockSize;6971size_t blockSize = determine_blockSize(cctx->appliedParams.blockDelimiters,6972cctx->blockSizeMax, remaining,6973inSeqs, inSeqsSize, seqPos);6974U32 const lastBlock = (blockSize == remaining);6975FORWARD_IF_ERROR(blockSize, "Error while trying to determine block size");6976assert(blockSize <= remaining);6977ZSTD_resetSeqStore(&cctx->seqStore);69786979blockSize = sequenceCopier(cctx,6980&seqPos, inSeqs, inSeqsSize,6981ip, blockSize,6982cctx->appliedParams.searchForExternalRepcodes);6983FORWARD_IF_ERROR(blockSize, "Bad sequence copy");69846985/* If blocks are too small, emit as a nocompress block */6986/* TODO: See 3090. We reduced MIN_CBLOCK_SIZE from 3 to 2 so to compensate we are adding6987* additional 1. We need to revisit and change this logic to be more consistent */6988if (blockSize < MIN_CBLOCK_SIZE+ZSTD_blockHeaderSize+1+1) {6989cBlockSize = ZSTD_noCompressBlock(op, dstCapacity, ip, blockSize, lastBlock);6990FORWARD_IF_ERROR(cBlockSize, "Nocompress block failed");6991DEBUGLOG(5, "Block too small (%zu): data remains uncompressed: cSize=%zu", blockSize, cBlockSize);6992cSize += cBlockSize;6993ip += blockSize;6994op += cBlockSize;6995remaining -= blockSize;6996dstCapacity -= cBlockSize;6997continue;6998}69997000RETURN_ERROR_IF(dstCapacity < ZSTD_blockHeaderSize, dstSize_tooSmall, "not enough dstCapacity to write a new compressed block");7001compressedSeqsSize = ZSTD_entropyCompressSeqStore(&cctx->seqStore,7002&cctx->blockState.prevCBlock->entropy, &cctx->blockState.nextCBlock->entropy,7003&cctx->appliedParams,7004op + ZSTD_blockHeaderSize /* Leave space for block header */, dstCapacity - ZSTD_blockHeaderSize,7005blockSize,7006cctx->tmpWorkspace, cctx->tmpWkspSize /* statically allocated in resetCCtx */,7007cctx->bmi2);7008FORWARD_IF_ERROR(compressedSeqsSize, "Compressing sequences of block failed");7009DEBUGLOG(5, "Compressed sequences size: %zu", compressedSeqsSize);70107011if (!cctx->isFirstBlock &&7012ZSTD_maybeRLE(&cctx->seqStore) &&7013ZSTD_isRLE(ip, blockSize)) {7014/* Note: don't emit the first block as RLE even if it qualifies because7015* doing so will cause the decoder (cli <= v1.4.3 only) to throw an (invalid) error7016* "should consume all input error."7017*/7018compressedSeqsSize = 1;7019}70207021if (compressedSeqsSize == 0) {7022/* ZSTD_noCompressBlock writes the block header as well */7023cBlockSize = ZSTD_noCompressBlock(op, dstCapacity, ip, blockSize, lastBlock);7024FORWARD_IF_ERROR(cBlockSize, "ZSTD_noCompressBlock failed");7025DEBUGLOG(5, "Writing out nocompress block, size: %zu", cBlockSize);7026} else if (compressedSeqsSize == 1) {7027cBlockSize = ZSTD_rleCompressBlock(op, dstCapacity, *ip, blockSize, lastBlock);7028FORWARD_IF_ERROR(cBlockSize, "ZSTD_rleCompressBlock failed");7029DEBUGLOG(5, "Writing out RLE block, size: %zu", cBlockSize);7030} else {7031U32 cBlockHeader;7032/* Error checking and repcodes update */7033ZSTD_blockState_confirmRepcodesAndEntropyTables(&cctx->blockState);7034if (cctx->blockState.prevCBlock->entropy.fse.offcode_repeatMode == FSE_repeat_valid)7035cctx->blockState.prevCBlock->entropy.fse.offcode_repeatMode = FSE_repeat_check;70367037/* Write block header into beginning of block*/7038cBlockHeader = lastBlock + (((U32)bt_compressed)<<1) + (U32)(compressedSeqsSize << 3);7039MEM_writeLE24(op, cBlockHeader);7040cBlockSize = ZSTD_blockHeaderSize + compressedSeqsSize;7041DEBUGLOG(5, "Writing out compressed block, size: %zu", cBlockSize);7042}70437044cSize += cBlockSize;70457046if (lastBlock) {7047break;7048} else {7049ip += blockSize;7050op += cBlockSize;7051remaining -= blockSize;7052dstCapacity -= cBlockSize;7053cctx->isFirstBlock = 0;7054}7055DEBUGLOG(5, "cSize running total: %zu (remaining dstCapacity=%zu)", cSize, dstCapacity);7056}70577058DEBUGLOG(4, "cSize final total: %zu", cSize);7059return cSize;7060}70617062size_t ZSTD_compressSequences(ZSTD_CCtx* cctx,7063void* dst, size_t dstCapacity,7064const ZSTD_Sequence* inSeqs, size_t inSeqsSize,7065const void* src, size_t srcSize)7066{7067BYTE* op = (BYTE*)dst;7068size_t cSize = 0;70697070/* Transparent initialization stage, same as compressStream2() */7071DEBUGLOG(4, "ZSTD_compressSequences (nbSeqs=%zu,dstCapacity=%zu)", inSeqsSize, dstCapacity);7072assert(cctx != NULL);7073FORWARD_IF_ERROR(ZSTD_CCtx_init_compressStream2(cctx, ZSTD_e_end, srcSize), "CCtx initialization failed");70747075/* Begin writing output, starting with frame header */7076{ size_t const frameHeaderSize = ZSTD_writeFrameHeader(op, dstCapacity,7077&cctx->appliedParams, srcSize, cctx->dictID);7078op += frameHeaderSize;7079assert(frameHeaderSize <= dstCapacity);7080dstCapacity -= frameHeaderSize;7081cSize += frameHeaderSize;7082}7083if (cctx->appliedParams.fParams.checksumFlag && srcSize) {7084XXH64_update(&cctx->xxhState, src, srcSize);7085}70867087/* Now generate compressed blocks */7088{ size_t const cBlocksSize = ZSTD_compressSequences_internal(cctx,7089op, dstCapacity,7090inSeqs, inSeqsSize,7091src, srcSize);7092FORWARD_IF_ERROR(cBlocksSize, "Compressing blocks failed!");7093cSize += cBlocksSize;7094assert(cBlocksSize <= dstCapacity);7095dstCapacity -= cBlocksSize;7096}70977098/* Complete with frame checksum, if needed */7099if (cctx->appliedParams.fParams.checksumFlag) {7100U32 const checksum = (U32) XXH64_digest(&cctx->xxhState);7101RETURN_ERROR_IF(dstCapacity<4, dstSize_tooSmall, "no room for checksum");7102DEBUGLOG(4, "Write checksum : %08X", (unsigned)checksum);7103MEM_writeLE32((char*)dst + cSize, checksum);7104cSize += 4;7105}71067107DEBUGLOG(4, "Final compressed size: %zu", cSize);7108return cSize;7109}711071117112#if defined(__AVX2__)71137114#include <immintrin.h> /* AVX2 intrinsics */71157116/*7117* Convert 2 sequences per iteration, using AVX2 intrinsics:7118* - offset -> offBase = offset + 27119* - litLength -> (U16) litLength7120* - matchLength -> (U16)(matchLength - 3)7121* - rep is ignored7122* Store only 8 bytes per SeqDef (offBase[4], litLength[2], mlBase[2]).7123*7124* At the end, instead of extracting two __m128i,7125* we use _mm256_permute4x64_epi64(..., 0xE8) to move lane2 into lane1,7126* then store the lower 16 bytes in one go.7127*7128* @returns 0 on succes, with no long length detected7129* @returns > 0 if there is one long length (> 65535),7130* indicating the position, and type.7131*/7132static size_t convertSequences_noRepcodes(7133SeqDef* dstSeqs,7134const ZSTD_Sequence* inSeqs,7135size_t nbSequences)7136{7137/*7138* addition:7139* For each 128-bit half: (offset+2, litLength+0, matchLength-3, rep+0)7140*/7141const __m256i addition = _mm256_setr_epi32(7142ZSTD_REP_NUM, 0, -MINMATCH, 0, /* for sequence i */7143ZSTD_REP_NUM, 0, -MINMATCH, 0 /* for sequence i+1 */7144);71457146/* limit: check if there is a long length */7147const __m256i limit = _mm256_set1_epi32(65535);71487149/*7150* shuffle mask for byte-level rearrangement in each 128-bit half:7151*7152* Input layout (after addition) per 128-bit half:7153* [ offset+2 (4 bytes) | litLength (4 bytes) | matchLength (4 bytes) | rep (4 bytes) ]7154* We only need:7155* offBase (4 bytes) = offset+27156* litLength (2 bytes) = low 2 bytes of litLength7157* mlBase (2 bytes) = low 2 bytes of (matchLength)7158* => Bytes [0..3, 4..5, 8..9], zero the rest.7159*/7160const __m256i mask = _mm256_setr_epi8(7161/* For the lower 128 bits => sequence i */71620, 1, 2, 3, /* offset+2 */71634, 5, /* litLength (16 bits) */71648, 9, /* matchLength (16 bits) */7165(BYTE)0x80, (BYTE)0x80, (BYTE)0x80, (BYTE)0x80,7166(BYTE)0x80, (BYTE)0x80, (BYTE)0x80, (BYTE)0x80,71677168/* For the upper 128 bits => sequence i+1 */716916,17,18,19, /* offset+2 */717020,21, /* litLength */717124,25, /* matchLength */7172(BYTE)0x80, (BYTE)0x80, (BYTE)0x80, (BYTE)0x80,7173(BYTE)0x80, (BYTE)0x80, (BYTE)0x80, (BYTE)0x807174);71757176/*7177* Next, we'll use _mm256_permute4x64_epi64(vshf, 0xE8).7178* Explanation of 0xE8 = 11101000b => [lane0, lane2, lane2, lane3].7179* So the lower 128 bits become [lane0, lane2] => combining seq0 and seq1.7180*/7181#define PERM_LANE_0X_E8 0xE8 /* [0,2,2,3] in lane indices */71827183size_t longLen = 0, i = 0;71847185/* AVX permutation depends on the specific definition of target structures */7186ZSTD_STATIC_ASSERT(sizeof(ZSTD_Sequence) == 16);7187ZSTD_STATIC_ASSERT(offsetof(ZSTD_Sequence, offset) == 0);7188ZSTD_STATIC_ASSERT(offsetof(ZSTD_Sequence, litLength) == 4);7189ZSTD_STATIC_ASSERT(offsetof(ZSTD_Sequence, matchLength) == 8);7190ZSTD_STATIC_ASSERT(sizeof(SeqDef) == 8);7191ZSTD_STATIC_ASSERT(offsetof(SeqDef, offBase) == 0);7192ZSTD_STATIC_ASSERT(offsetof(SeqDef, litLength) == 4);7193ZSTD_STATIC_ASSERT(offsetof(SeqDef, mlBase) == 6);71947195/* Process 2 sequences per loop iteration */7196for (; i + 1 < nbSequences; i += 2) {7197/* Load 2 ZSTD_Sequence (32 bytes) */7198__m256i vin = _mm256_loadu_si256((const __m256i*)(const void*)&inSeqs[i]);71997200/* Add {2, 0, -3, 0} in each 128-bit half */7201__m256i vadd = _mm256_add_epi32(vin, addition);72027203/* Check for long length */7204__m256i ll_cmp = _mm256_cmpgt_epi32(vadd, limit); /* 0xFFFFFFFF for element > 65535 */7205int ll_res = _mm256_movemask_epi8(ll_cmp);72067207/* Shuffle bytes so each half gives us the 8 bytes we need */7208__m256i vshf = _mm256_shuffle_epi8(vadd, mask);7209/*7210* Now:7211* Lane0 = seq0's 8 bytes7212* Lane1 = 07213* Lane2 = seq1's 8 bytes7214* Lane3 = 07215*/72167217/* Permute 64-bit lanes => move Lane2 down into Lane1. */7218__m256i vperm = _mm256_permute4x64_epi64(vshf, PERM_LANE_0X_E8);7219/*7220* Now the lower 16 bytes (Lane0+Lane1) = [seq0, seq1].7221* The upper 16 bytes are [Lane2, Lane3] = [seq1, 0], but we won't use them.7222*/72237224/* Store only the lower 16 bytes => 2 SeqDef (8 bytes each) */7225_mm_storeu_si128((__m128i *)(void*)&dstSeqs[i], _mm256_castsi256_si128(vperm));7226/*7227* This writes out 16 bytes total:7228* - offset 0..7 => seq0 (offBase, litLength, mlBase)7229* - offset 8..15 => seq1 (offBase, litLength, mlBase)7230*/72317232/* check (unlikely) long lengths > 655357233* indices for lengths correspond to bits [4..7], [8..11], [20..23], [24..27]7234* => combined mask = 0x0FF00FF07235*/7236if (UNLIKELY((ll_res & 0x0FF00FF0) != 0)) {7237/* long length detected: let's figure out which one*/7238if (inSeqs[i].matchLength > 65535+MINMATCH) {7239assert(longLen == 0);7240longLen = i + 1;7241}7242if (inSeqs[i].litLength > 65535) {7243assert(longLen == 0);7244longLen = i + nbSequences + 1;7245}7246if (inSeqs[i+1].matchLength > 65535+MINMATCH) {7247assert(longLen == 0);7248longLen = i + 1 + 1;7249}7250if (inSeqs[i+1].litLength > 65535) {7251assert(longLen == 0);7252longLen = i + 1 + nbSequences + 1;7253}7254}7255}72567257/* Handle leftover if @nbSequences is odd */7258if (i < nbSequences) {7259/* process last sequence */7260assert(i == nbSequences - 1);7261dstSeqs[i].offBase = OFFSET_TO_OFFBASE(inSeqs[i].offset);7262dstSeqs[i].litLength = (U16)inSeqs[i].litLength;7263dstSeqs[i].mlBase = (U16)(inSeqs[i].matchLength - MINMATCH);7264/* check (unlikely) long lengths > 65535 */7265if (UNLIKELY(inSeqs[i].matchLength > 65535+MINMATCH)) {7266assert(longLen == 0);7267longLen = i + 1;7268}7269if (UNLIKELY(inSeqs[i].litLength > 65535)) {7270assert(longLen == 0);7271longLen = i + nbSequences + 1;7272}7273}72747275return longLen;7276}72777278/* the vector implementation could also be ported to SSSE3,7279* but since this implementation is targeting modern systems (>= Sapphire Rapid),7280* it's not useful to develop and maintain code for older pre-AVX2 platforms */72817282#else /* no AVX2 */72837284static size_t convertSequences_noRepcodes(7285SeqDef* dstSeqs,7286const ZSTD_Sequence* inSeqs,7287size_t nbSequences)7288{7289size_t longLen = 0;7290size_t n;7291for (n=0; n<nbSequences; n++) {7292dstSeqs[n].offBase = OFFSET_TO_OFFBASE(inSeqs[n].offset);7293dstSeqs[n].litLength = (U16)inSeqs[n].litLength;7294dstSeqs[n].mlBase = (U16)(inSeqs[n].matchLength - MINMATCH);7295/* check for long length > 65535 */7296if (UNLIKELY(inSeqs[n].matchLength > 65535+MINMATCH)) {7297assert(longLen == 0);7298longLen = n + 1;7299}7300if (UNLIKELY(inSeqs[n].litLength > 65535)) {7301assert(longLen == 0);7302longLen = n + nbSequences + 1;7303}7304}7305return longLen;7306}73077308#endif73097310/*7311* Precondition: Sequences must end on an explicit Block Delimiter7312* @return: 0 on success, or an error code.7313* Note: Sequence validation functionality has been disabled (removed).7314* This is helpful to generate a lean main pipeline, improving performance.7315* It may be re-inserted later.7316*/7317size_t ZSTD_convertBlockSequences(ZSTD_CCtx* cctx,7318const ZSTD_Sequence* const inSeqs, size_t nbSequences,7319int repcodeResolution)7320{7321Repcodes_t updatedRepcodes;7322size_t seqNb = 0;73237324DEBUGLOG(5, "ZSTD_convertBlockSequences (nbSequences = %zu)", nbSequences);73257326RETURN_ERROR_IF(nbSequences >= cctx->seqStore.maxNbSeq, externalSequences_invalid,7327"Not enough memory allocated. Try adjusting ZSTD_c_minMatch.");73287329ZSTD_memcpy(updatedRepcodes.rep, cctx->blockState.prevCBlock->rep, sizeof(Repcodes_t));73307331/* check end condition */7332assert(nbSequences >= 1);7333assert(inSeqs[nbSequences-1].matchLength == 0);7334assert(inSeqs[nbSequences-1].offset == 0);73357336/* Convert Sequences from public format to internal format */7337if (!repcodeResolution) {7338size_t const longl = convertSequences_noRepcodes(cctx->seqStore.sequencesStart, inSeqs, nbSequences-1);7339cctx->seqStore.sequences = cctx->seqStore.sequencesStart + nbSequences-1;7340if (longl) {7341DEBUGLOG(5, "long length");7342assert(cctx->seqStore.longLengthType == ZSTD_llt_none);7343if (longl <= nbSequences-1) {7344DEBUGLOG(5, "long match length detected at pos %zu", longl-1);7345cctx->seqStore.longLengthType = ZSTD_llt_matchLength;7346cctx->seqStore.longLengthPos = (U32)(longl-1);7347} else {7348DEBUGLOG(5, "long literals length detected at pos %zu", longl-nbSequences);7349assert(longl <= 2* (nbSequences-1));7350cctx->seqStore.longLengthType = ZSTD_llt_literalLength;7351cctx->seqStore.longLengthPos = (U32)(longl-(nbSequences-1)-1);7352}7353}7354} else {7355for (seqNb = 0; seqNb < nbSequences - 1 ; seqNb++) {7356U32 const litLength = inSeqs[seqNb].litLength;7357U32 const matchLength = inSeqs[seqNb].matchLength;7358U32 const ll0 = (litLength == 0);7359U32 const offBase = ZSTD_finalizeOffBase(inSeqs[seqNb].offset, updatedRepcodes.rep, ll0);73607361DEBUGLOG(6, "Storing sequence: (of: %u, ml: %u, ll: %u)", offBase, matchLength, litLength);7362ZSTD_storeSeqOnly(&cctx->seqStore, litLength, offBase, matchLength);7363ZSTD_updateRep(updatedRepcodes.rep, offBase, ll0);7364}7365}73667367/* If we skipped repcode search while parsing, we need to update repcodes now */7368if (!repcodeResolution && nbSequences > 1) {7369U32* const rep = updatedRepcodes.rep;73707371if (nbSequences >= 4) {7372U32 lastSeqIdx = (U32)nbSequences - 2; /* index of last full sequence */7373rep[2] = inSeqs[lastSeqIdx - 2].offset;7374rep[1] = inSeqs[lastSeqIdx - 1].offset;7375rep[0] = inSeqs[lastSeqIdx].offset;7376} else if (nbSequences == 3) {7377rep[2] = rep[0];7378rep[1] = inSeqs[0].offset;7379rep[0] = inSeqs[1].offset;7380} else {7381assert(nbSequences == 2);7382rep[2] = rep[1];7383rep[1] = rep[0];7384rep[0] = inSeqs[0].offset;7385}7386}73877388ZSTD_memcpy(cctx->blockState.nextCBlock->rep, updatedRepcodes.rep, sizeof(Repcodes_t));73897390return 0;7391}73927393#if defined(ZSTD_ARCH_X86_AVX2)73947395BlockSummary ZSTD_get1BlockSummary(const ZSTD_Sequence* seqs, size_t nbSeqs)7396{7397size_t i;7398__m256i const zeroVec = _mm256_setzero_si256();7399__m256i sumVec = zeroVec; /* accumulates match+lit in 32-bit lanes */7400ZSTD_ALIGNED(32) U32 tmp[8]; /* temporary buffer for reduction */7401size_t mSum = 0, lSum = 0;7402ZSTD_STATIC_ASSERT(sizeof(ZSTD_Sequence) == 16);74037404/* Process 2 structs (32 bytes) at a time */7405for (i = 0; i + 2 <= nbSeqs; i += 2) {7406/* Load two consecutive ZSTD_Sequence (8×4 = 32 bytes) */7407__m256i data = _mm256_loadu_si256((const __m256i*)(const void*)&seqs[i]);7408/* check end of block signal */7409__m256i cmp = _mm256_cmpeq_epi32(data, zeroVec);7410int cmp_res = _mm256_movemask_epi8(cmp);7411/* indices for match lengths correspond to bits [8..11], [24..27]7412* => combined mask = 0x0F000F00 */7413ZSTD_STATIC_ASSERT(offsetof(ZSTD_Sequence, matchLength) == 8);7414if (cmp_res & 0x0F000F00) break;7415/* Accumulate in sumVec */7416sumVec = _mm256_add_epi32(sumVec, data);7417}74187419/* Horizontal reduction */7420_mm256_store_si256((__m256i*)tmp, sumVec);7421lSum = tmp[1] + tmp[5];7422mSum = tmp[2] + tmp[6];74237424/* Handle the leftover */7425for (; i < nbSeqs; i++) {7426lSum += seqs[i].litLength;7427mSum += seqs[i].matchLength;7428if (seqs[i].matchLength == 0) break; /* end of block */7429}74307431if (i==nbSeqs) {7432/* reaching end of sequences: end of block signal was not present */7433BlockSummary bs;7434bs.nbSequences = ERROR(externalSequences_invalid);7435return bs;7436}7437{ BlockSummary bs;7438bs.nbSequences = i+1;7439bs.blockSize = lSum + mSum;7440bs.litSize = lSum;7441return bs;7442}7443}74447445#else74467447BlockSummary ZSTD_get1BlockSummary(const ZSTD_Sequence* seqs, size_t nbSeqs)7448{7449size_t totalMatchSize = 0;7450size_t litSize = 0;7451size_t n;7452assert(seqs);7453for (n=0; n<nbSeqs; n++) {7454totalMatchSize += seqs[n].matchLength;7455litSize += seqs[n].litLength;7456if (seqs[n].matchLength == 0) {7457assert(seqs[n].offset == 0);7458break;7459}7460}7461if (n==nbSeqs) {7462BlockSummary bs;7463bs.nbSequences = ERROR(externalSequences_invalid);7464return bs;7465}7466{ BlockSummary bs;7467bs.nbSequences = n+1;7468bs.blockSize = litSize + totalMatchSize;7469bs.litSize = litSize;7470return bs;7471}7472}7473#endif747474757476static size_t7477ZSTD_compressSequencesAndLiterals_internal(ZSTD_CCtx* cctx,7478void* dst, size_t dstCapacity,7479const ZSTD_Sequence* inSeqs, size_t nbSequences,7480const void* literals, size_t litSize, size_t srcSize)7481{7482size_t remaining = srcSize;7483size_t cSize = 0;7484BYTE* op = (BYTE*)dst;7485int const repcodeResolution = (cctx->appliedParams.searchForExternalRepcodes == ZSTD_ps_enable);7486assert(cctx->appliedParams.searchForExternalRepcodes != ZSTD_ps_auto);74877488DEBUGLOG(4, "ZSTD_compressSequencesAndLiterals_internal: nbSeqs=%zu, litSize=%zu", nbSequences, litSize);7489RETURN_ERROR_IF(nbSequences == 0, externalSequences_invalid, "Requires at least 1 end-of-block");74907491/* Special case: empty frame */7492if ((nbSequences == 1) && (inSeqs[0].litLength == 0)) {7493U32 const cBlockHeader24 = 1 /* last block */ + (((U32)bt_raw)<<1);7494RETURN_ERROR_IF(dstCapacity<3, dstSize_tooSmall, "No room for empty frame block header");7495MEM_writeLE24(op, cBlockHeader24);7496op += ZSTD_blockHeaderSize;7497dstCapacity -= ZSTD_blockHeaderSize;7498cSize += ZSTD_blockHeaderSize;7499}75007501while (nbSequences) {7502size_t compressedSeqsSize, cBlockSize, conversionStatus;7503BlockSummary const block = ZSTD_get1BlockSummary(inSeqs, nbSequences);7504U32 const lastBlock = (block.nbSequences == nbSequences);7505FORWARD_IF_ERROR(block.nbSequences, "Error while trying to determine nb of sequences for a block");7506assert(block.nbSequences <= nbSequences);7507RETURN_ERROR_IF(block.litSize > litSize, externalSequences_invalid, "discrepancy: Sequences require more literals than present in buffer");7508ZSTD_resetSeqStore(&cctx->seqStore);75097510conversionStatus = ZSTD_convertBlockSequences(cctx,7511inSeqs, block.nbSequences,7512repcodeResolution);7513FORWARD_IF_ERROR(conversionStatus, "Bad sequence conversion");7514inSeqs += block.nbSequences;7515nbSequences -= block.nbSequences;7516remaining -= block.blockSize;75177518/* Note: when blockSize is very small, other variant send it uncompressed.7519* Here, we still send the sequences, because we don't have the original source to send it uncompressed.7520* One could imagine in theory reproducing the source from the sequences,7521* but that's complex and costly memory intensive, and goes against the objectives of this variant. */75227523RETURN_ERROR_IF(dstCapacity < ZSTD_blockHeaderSize, dstSize_tooSmall, "not enough dstCapacity to write a new compressed block");75247525compressedSeqsSize = ZSTD_entropyCompressSeqStore_internal(7526op + ZSTD_blockHeaderSize /* Leave space for block header */, dstCapacity - ZSTD_blockHeaderSize,7527literals, block.litSize,7528&cctx->seqStore,7529&cctx->blockState.prevCBlock->entropy, &cctx->blockState.nextCBlock->entropy,7530&cctx->appliedParams,7531cctx->tmpWorkspace, cctx->tmpWkspSize /* statically allocated in resetCCtx */,7532cctx->bmi2);7533FORWARD_IF_ERROR(compressedSeqsSize, "Compressing sequences of block failed");7534/* note: the spec forbids for any compressed block to be larger than maximum block size */7535if (compressedSeqsSize > cctx->blockSizeMax) compressedSeqsSize = 0;7536DEBUGLOG(5, "Compressed sequences size: %zu", compressedSeqsSize);7537litSize -= block.litSize;7538literals = (const char*)literals + block.litSize;75397540/* Note: difficult to check source for RLE block when only Literals are provided,7541* but it could be considered from analyzing the sequence directly */75427543if (compressedSeqsSize == 0) {7544/* Sending uncompressed blocks is out of reach, because the source is not provided.7545* In theory, one could use the sequences to regenerate the source, like a decompressor,7546* but it's complex, and memory hungry, killing the purpose of this variant.7547* Current outcome: generate an error code.7548*/7549RETURN_ERROR(cannotProduce_uncompressedBlock, "ZSTD_compressSequencesAndLiterals cannot generate an uncompressed block");7550} else {7551U32 cBlockHeader;7552assert(compressedSeqsSize > 1); /* no RLE */7553/* Error checking and repcodes update */7554ZSTD_blockState_confirmRepcodesAndEntropyTables(&cctx->blockState);7555if (cctx->blockState.prevCBlock->entropy.fse.offcode_repeatMode == FSE_repeat_valid)7556cctx->blockState.prevCBlock->entropy.fse.offcode_repeatMode = FSE_repeat_check;75577558/* Write block header into beginning of block*/7559cBlockHeader = lastBlock + (((U32)bt_compressed)<<1) + (U32)(compressedSeqsSize << 3);7560MEM_writeLE24(op, cBlockHeader);7561cBlockSize = ZSTD_blockHeaderSize + compressedSeqsSize;7562DEBUGLOG(5, "Writing out compressed block, size: %zu", cBlockSize);7563}75647565cSize += cBlockSize;7566op += cBlockSize;7567dstCapacity -= cBlockSize;7568cctx->isFirstBlock = 0;7569DEBUGLOG(5, "cSize running total: %zu (remaining dstCapacity=%zu)", cSize, dstCapacity);75707571if (lastBlock) {7572assert(nbSequences == 0);7573break;7574}7575}75767577RETURN_ERROR_IF(litSize != 0, externalSequences_invalid, "literals must be entirely and exactly consumed");7578RETURN_ERROR_IF(remaining != 0, externalSequences_invalid, "Sequences must represent a total of exactly srcSize=%zu", srcSize);7579DEBUGLOG(4, "cSize final total: %zu", cSize);7580return cSize;7581}75827583size_t7584ZSTD_compressSequencesAndLiterals(ZSTD_CCtx* cctx,7585void* dst, size_t dstCapacity,7586const ZSTD_Sequence* inSeqs, size_t inSeqsSize,7587const void* literals, size_t litSize, size_t litCapacity,7588size_t decompressedSize)7589{7590BYTE* op = (BYTE*)dst;7591size_t cSize = 0;75927593/* Transparent initialization stage, same as compressStream2() */7594DEBUGLOG(4, "ZSTD_compressSequencesAndLiterals (dstCapacity=%zu)", dstCapacity);7595assert(cctx != NULL);7596if (litCapacity < litSize) {7597RETURN_ERROR(workSpace_tooSmall, "literals buffer is not large enough: must be at least 8 bytes larger than litSize (risk of read out-of-bound)");7598}7599FORWARD_IF_ERROR(ZSTD_CCtx_init_compressStream2(cctx, ZSTD_e_end, decompressedSize), "CCtx initialization failed");76007601if (cctx->appliedParams.blockDelimiters == ZSTD_sf_noBlockDelimiters) {7602RETURN_ERROR(frameParameter_unsupported, "This mode is only compatible with explicit delimiters");7603}7604if (cctx->appliedParams.validateSequences) {7605RETURN_ERROR(parameter_unsupported, "This mode is not compatible with Sequence validation");7606}7607if (cctx->appliedParams.fParams.checksumFlag) {7608RETURN_ERROR(frameParameter_unsupported, "this mode is not compatible with frame checksum");7609}76107611/* Begin writing output, starting with frame header */7612{ size_t const frameHeaderSize = ZSTD_writeFrameHeader(op, dstCapacity,7613&cctx->appliedParams, decompressedSize, cctx->dictID);7614op += frameHeaderSize;7615assert(frameHeaderSize <= dstCapacity);7616dstCapacity -= frameHeaderSize;7617cSize += frameHeaderSize;7618}76197620/* Now generate compressed blocks */7621{ size_t const cBlocksSize = ZSTD_compressSequencesAndLiterals_internal(cctx,7622op, dstCapacity,7623inSeqs, inSeqsSize,7624literals, litSize, decompressedSize);7625FORWARD_IF_ERROR(cBlocksSize, "Compressing blocks failed!");7626cSize += cBlocksSize;7627assert(cBlocksSize <= dstCapacity);7628dstCapacity -= cBlocksSize;7629}76307631DEBUGLOG(4, "Final compressed size: %zu", cSize);7632return cSize;7633}76347635/*====== Finalize ======*/76367637static ZSTD_inBuffer inBuffer_forEndFlush(const ZSTD_CStream* zcs)7638{7639const ZSTD_inBuffer nullInput = { NULL, 0, 0 };7640const int stableInput = (zcs->appliedParams.inBufferMode == ZSTD_bm_stable);7641return stableInput ? zcs->expectedInBuffer : nullInput;7642}76437644/*! ZSTD_flushStream() :7645* @return : amount of data remaining to flush */7646size_t ZSTD_flushStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output)7647{7648ZSTD_inBuffer input = inBuffer_forEndFlush(zcs);7649input.size = input.pos; /* do not ingest more input during flush */7650return ZSTD_compressStream2(zcs, output, &input, ZSTD_e_flush);7651}76527653size_t ZSTD_endStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output)7654{7655ZSTD_inBuffer input = inBuffer_forEndFlush(zcs);7656size_t const remainingToFlush = ZSTD_compressStream2(zcs, output, &input, ZSTD_e_end);7657FORWARD_IF_ERROR(remainingToFlush , "ZSTD_compressStream2(,,ZSTD_e_end) failed");7658if (zcs->appliedParams.nbWorkers > 0) return remainingToFlush; /* minimal estimation */7659/* single thread mode : attempt to calculate remaining to flush more precisely */7660{ size_t const lastBlockSize = zcs->frameEnded ? 0 : ZSTD_BLOCKHEADERSIZE;7661size_t const checksumSize = (size_t)(zcs->frameEnded ? 0 : zcs->appliedParams.fParams.checksumFlag * 4);7662size_t const toFlush = remainingToFlush + lastBlockSize + checksumSize;7663DEBUGLOG(4, "ZSTD_endStream : remaining to flush : %u", (unsigned)toFlush);7664return toFlush;7665}7666}766776687669/*-===== Pre-defined compression levels =====-*/7670#include "clevels.h"76717672int ZSTD_maxCLevel(void) { return ZSTD_MAX_CLEVEL; }7673int ZSTD_minCLevel(void) { return (int)-ZSTD_TARGETLENGTH_MAX; }7674int ZSTD_defaultCLevel(void) { return ZSTD_CLEVEL_DEFAULT; }76757676static ZSTD_compressionParameters ZSTD_dedicatedDictSearch_getCParams(int const compressionLevel, size_t const dictSize)7677{7678ZSTD_compressionParameters cParams = ZSTD_getCParams_internal(compressionLevel, 0, dictSize, ZSTD_cpm_createCDict);7679switch (cParams.strategy) {7680case ZSTD_fast:7681case ZSTD_dfast:7682break;7683case ZSTD_greedy:7684case ZSTD_lazy:7685case ZSTD_lazy2:7686cParams.hashLog += ZSTD_LAZY_DDSS_BUCKET_LOG;7687break;7688case ZSTD_btlazy2:7689case ZSTD_btopt:7690case ZSTD_btultra:7691case ZSTD_btultra2:7692break;7693}7694return cParams;7695}76967697static int ZSTD_dedicatedDictSearch_isSupported(7698ZSTD_compressionParameters const* cParams)7699{7700return (cParams->strategy >= ZSTD_greedy)7701&& (cParams->strategy <= ZSTD_lazy2)7702&& (cParams->hashLog > cParams->chainLog)7703&& (cParams->chainLog <= 24);7704}77057706/**7707* Reverses the adjustment applied to cparams when enabling dedicated dict7708* search. This is used to recover the params set to be used in the working7709* context. (Otherwise, those tables would also grow.)7710*/7711static void ZSTD_dedicatedDictSearch_revertCParams(7712ZSTD_compressionParameters* cParams) {7713switch (cParams->strategy) {7714case ZSTD_fast:7715case ZSTD_dfast:7716break;7717case ZSTD_greedy:7718case ZSTD_lazy:7719case ZSTD_lazy2:7720cParams->hashLog -= ZSTD_LAZY_DDSS_BUCKET_LOG;7721if (cParams->hashLog < ZSTD_HASHLOG_MIN) {7722cParams->hashLog = ZSTD_HASHLOG_MIN;7723}7724break;7725case ZSTD_btlazy2:7726case ZSTD_btopt:7727case ZSTD_btultra:7728case ZSTD_btultra2:7729break;7730}7731}77327733static U64 ZSTD_getCParamRowSize(U64 srcSizeHint, size_t dictSize, ZSTD_CParamMode_e mode)7734{7735switch (mode) {7736case ZSTD_cpm_unknown:7737case ZSTD_cpm_noAttachDict:7738case ZSTD_cpm_createCDict:7739break;7740case ZSTD_cpm_attachDict:7741dictSize = 0;7742break;7743default:7744assert(0);7745break;7746}7747{ int const unknown = srcSizeHint == ZSTD_CONTENTSIZE_UNKNOWN;7748size_t const addedSize = unknown && dictSize > 0 ? 500 : 0;7749return unknown && dictSize == 0 ? ZSTD_CONTENTSIZE_UNKNOWN : srcSizeHint+dictSize+addedSize;7750}7751}77527753/*! ZSTD_getCParams_internal() :7754* @return ZSTD_compressionParameters structure for a selected compression level, srcSize and dictSize.7755* Note: srcSizeHint 0 means 0, use ZSTD_CONTENTSIZE_UNKNOWN for unknown.7756* Use dictSize == 0 for unknown or unused.7757* Note: `mode` controls how we treat the `dictSize`. See docs for `ZSTD_CParamMode_e`. */7758static ZSTD_compressionParameters ZSTD_getCParams_internal(int compressionLevel, unsigned long long srcSizeHint, size_t dictSize, ZSTD_CParamMode_e mode)7759{7760U64 const rSize = ZSTD_getCParamRowSize(srcSizeHint, dictSize, mode);7761U32 const tableID = (rSize <= 256 KB) + (rSize <= 128 KB) + (rSize <= 16 KB);7762int row;7763DEBUGLOG(5, "ZSTD_getCParams_internal (cLevel=%i)", compressionLevel);77647765/* row */7766if (compressionLevel == 0) row = ZSTD_CLEVEL_DEFAULT; /* 0 == default */7767else if (compressionLevel < 0) row = 0; /* entry 0 is baseline for fast mode */7768else if (compressionLevel > ZSTD_MAX_CLEVEL) row = ZSTD_MAX_CLEVEL;7769else row = compressionLevel;77707771{ ZSTD_compressionParameters cp = ZSTD_defaultCParameters[tableID][row];7772DEBUGLOG(5, "ZSTD_getCParams_internal selected tableID: %u row: %u strat: %u", tableID, row, (U32)cp.strategy);7773/* acceleration factor */7774if (compressionLevel < 0) {7775int const clampedCompressionLevel = MAX(ZSTD_minCLevel(), compressionLevel);7776cp.targetLength = (unsigned)(-clampedCompressionLevel);7777}7778/* refine parameters based on srcSize & dictSize */7779return ZSTD_adjustCParams_internal(cp, srcSizeHint, dictSize, mode, ZSTD_ps_auto);7780}7781}77827783/*! ZSTD_getCParams() :7784* @return ZSTD_compressionParameters structure for a selected compression level, srcSize and dictSize.7785* Size values are optional, provide 0 if not known or unused */7786ZSTD_compressionParameters ZSTD_getCParams(int compressionLevel, unsigned long long srcSizeHint, size_t dictSize)7787{7788if (srcSizeHint == 0) srcSizeHint = ZSTD_CONTENTSIZE_UNKNOWN;7789return ZSTD_getCParams_internal(compressionLevel, srcSizeHint, dictSize, ZSTD_cpm_unknown);7790}77917792/*! ZSTD_getParams() :7793* same idea as ZSTD_getCParams()7794* @return a `ZSTD_parameters` structure (instead of `ZSTD_compressionParameters`).7795* Fields of `ZSTD_frameParameters` are set to default values */7796static ZSTD_parameters7797ZSTD_getParams_internal(int compressionLevel, unsigned long long srcSizeHint, size_t dictSize, ZSTD_CParamMode_e mode)7798{7799ZSTD_parameters params;7800ZSTD_compressionParameters const cParams = ZSTD_getCParams_internal(compressionLevel, srcSizeHint, dictSize, mode);7801DEBUGLOG(5, "ZSTD_getParams (cLevel=%i)", compressionLevel);7802ZSTD_memset(¶ms, 0, sizeof(params));7803params.cParams = cParams;7804params.fParams.contentSizeFlag = 1;7805return params;7806}78077808/*! ZSTD_getParams() :7809* same idea as ZSTD_getCParams()7810* @return a `ZSTD_parameters` structure (instead of `ZSTD_compressionParameters`).7811* Fields of `ZSTD_frameParameters` are set to default values */7812ZSTD_parameters ZSTD_getParams(int compressionLevel, unsigned long long srcSizeHint, size_t dictSize)7813{7814if (srcSizeHint == 0) srcSizeHint = ZSTD_CONTENTSIZE_UNKNOWN;7815return ZSTD_getParams_internal(compressionLevel, srcSizeHint, dictSize, ZSTD_cpm_unknown);7816}78177818void ZSTD_registerSequenceProducer(7819ZSTD_CCtx* zc,7820void* extSeqProdState,7821ZSTD_sequenceProducer_F extSeqProdFunc)7822{7823assert(zc != NULL);7824ZSTD_CCtxParams_registerSequenceProducer(7825&zc->requestedParams, extSeqProdState, extSeqProdFunc7826);7827}78287829void ZSTD_CCtxParams_registerSequenceProducer(7830ZSTD_CCtx_params* params,7831void* extSeqProdState,7832ZSTD_sequenceProducer_F extSeqProdFunc)7833{7834assert(params != NULL);7835if (extSeqProdFunc != NULL) {7836params->extSeqProdFunc = extSeqProdFunc;7837params->extSeqProdState = extSeqProdState;7838} else {7839params->extSeqProdFunc = NULL;7840params->extSeqProdState = NULL;7841}7842}784378447845