| /* |
| * Copyright (c) 2016-present, Yann Collet, Facebook, Inc. |
| * All rights reserved. |
| * |
| * This source code is licensed under both the BSD-style license (found in the |
| * LICENSE file in the root directory of this source tree) and the GPLv2 (found |
| * in the COPYING file in the root directory of this source tree). |
| * You may select, at your option, one of the above-listed licenses. |
| */ |
| |
| /*-************************************* |
| * Dependencies |
| ***************************************/ |
| #include <limits.h> /* INT_MAX */ |
| #include <string.h> /* memset */ |
| #include "cpu.h" |
| #include "mem.h" |
| #include "hist.h" /* HIST_countFast_wksp */ |
| #define FSE_STATIC_LINKING_ONLY /* FSE_encodeSymbol */ |
| #include "fse.h" |
| #define HUF_STATIC_LINKING_ONLY |
| #include "huf.h" |
| #include "zstd_compress_internal.h" |
| #include "zstd_fast.h" |
| #include "zstd_double_fast.h" |
| #include "zstd_lazy.h" |
| #include "zstd_opt.h" |
| #include "zstd_ldm.h" |
| |
| |
| /*-************************************* |
| * Helper functions |
| ***************************************/ |
| size_t ZSTD_compressBound(size_t srcSize) { |
| return ZSTD_COMPRESSBOUND(srcSize); |
| } |
| |
| |
| /*-************************************* |
| * Context memory management |
| ***************************************/ |
| struct ZSTD_CDict_s { |
| void* dictBuffer; |
| const void* dictContent; |
| size_t dictContentSize; |
| void* workspace; |
| size_t workspaceSize; |
| ZSTD_matchState_t matchState; |
| ZSTD_compressedBlockState_t cBlockState; |
| ZSTD_customMem customMem; |
| U32 dictID; |
| }; /* typedef'd to ZSTD_CDict within "zstd.h" */ |
| |
| ZSTD_CCtx* ZSTD_createCCtx(void) |
| { |
| return ZSTD_createCCtx_advanced(ZSTD_defaultCMem); |
| } |
| |
| static void ZSTD_initCCtx(ZSTD_CCtx* cctx, ZSTD_customMem memManager) |
| { |
| assert(cctx != NULL); |
| memset(cctx, 0, sizeof(*cctx)); |
| cctx->customMem = memManager; |
| cctx->bmi2 = ZSTD_cpuid_bmi2(ZSTD_cpuid()); |
| { size_t const err = ZSTD_CCtx_reset(cctx, ZSTD_reset_parameters); |
| assert(!ZSTD_isError(err)); |
| (void)err; |
| } |
| } |
| |
| ZSTD_CCtx* ZSTD_createCCtx_advanced(ZSTD_customMem customMem) |
| { |
| ZSTD_STATIC_ASSERT(zcss_init==0); |
| ZSTD_STATIC_ASSERT(ZSTD_CONTENTSIZE_UNKNOWN==(0ULL - 1)); |
| if (!customMem.customAlloc ^ !customMem.customFree) return NULL; |
| { ZSTD_CCtx* const cctx = (ZSTD_CCtx*)ZSTD_malloc(sizeof(ZSTD_CCtx), customMem); |
| if (!cctx) return NULL; |
| ZSTD_initCCtx(cctx, customMem); |
| return cctx; |
| } |
| } |
| |
| ZSTD_CCtx* ZSTD_initStaticCCtx(void *workspace, size_t workspaceSize) |
| { |
| ZSTD_CCtx* const cctx = (ZSTD_CCtx*) workspace; |
| if (workspaceSize <= sizeof(ZSTD_CCtx)) return NULL; /* minimum size */ |
| if ((size_t)workspace & 7) return NULL; /* must be 8-aligned */ |
| memset(workspace, 0, workspaceSize); /* may be a bit generous, could memset be smaller ? */ |
| cctx->staticSize = workspaceSize; |
| cctx->workSpace = (void*)(cctx+1); |
| cctx->workSpaceSize = workspaceSize - sizeof(ZSTD_CCtx); |
| |
| /* statically sized space. entropyWorkspace never moves (but prev/next block swap places) */ |
| if (cctx->workSpaceSize < HUF_WORKSPACE_SIZE + 2 * sizeof(ZSTD_compressedBlockState_t)) return NULL; |
| assert(((size_t)cctx->workSpace & (sizeof(void*)-1)) == 0); /* ensure correct alignment */ |
| cctx->blockState.prevCBlock = (ZSTD_compressedBlockState_t*)cctx->workSpace; |
| cctx->blockState.nextCBlock = cctx->blockState.prevCBlock + 1; |
| { |
| void* const ptr = cctx->blockState.nextCBlock + 1; |
| cctx->entropyWorkspace = (U32*)ptr; |
| } |
| cctx->bmi2 = ZSTD_cpuid_bmi2(ZSTD_cpuid()); |
| return cctx; |
| } |
| |
| /** |
| * Clears and frees all of the dictionaries in the CCtx. |
| */ |
| static void ZSTD_clearAllDicts(ZSTD_CCtx* cctx) |
| { |
| ZSTD_free(cctx->localDict.dictBuffer, cctx->customMem); |
| ZSTD_freeCDict(cctx->localDict.cdict); |
| memset(&cctx->localDict, 0, sizeof(cctx->localDict)); |
| memset(&cctx->prefixDict, 0, sizeof(cctx->prefixDict)); |
| cctx->cdict = NULL; |
| } |
| |
| static size_t ZSTD_sizeof_localDict(ZSTD_localDict dict) |
| { |
| size_t const bufferSize = dict.dictBuffer != NULL ? dict.dictSize : 0; |
| size_t const cdictSize = ZSTD_sizeof_CDict(dict.cdict); |
| return bufferSize + cdictSize; |
| } |
| |
| static void ZSTD_freeCCtxContent(ZSTD_CCtx* cctx) |
| { |
| assert(cctx != NULL); |
| assert(cctx->staticSize == 0); |
| ZSTD_free(cctx->workSpace, cctx->customMem); cctx->workSpace = NULL; |
| ZSTD_clearAllDicts(cctx); |
| #ifdef ZSTD_MULTITHREAD |
| ZSTDMT_freeCCtx(cctx->mtctx); cctx->mtctx = NULL; |
| #endif |
| } |
| |
| size_t ZSTD_freeCCtx(ZSTD_CCtx* cctx) |
| { |
| if (cctx==NULL) return 0; /* support free on NULL */ |
| RETURN_ERROR_IF(cctx->staticSize, memory_allocation, |
| "not compatible with static CCtx"); |
| ZSTD_freeCCtxContent(cctx); |
| ZSTD_free(cctx, cctx->customMem); |
| return 0; |
| } |
| |
| |
| static size_t ZSTD_sizeof_mtctx(const ZSTD_CCtx* cctx) |
| { |
| #ifdef ZSTD_MULTITHREAD |
| return ZSTDMT_sizeof_CCtx(cctx->mtctx); |
| #else |
| (void)cctx; |
| return 0; |
| #endif |
| } |
| |
| |
| size_t ZSTD_sizeof_CCtx(const ZSTD_CCtx* cctx) |
| { |
| if (cctx==NULL) return 0; /* support sizeof on NULL */ |
| return sizeof(*cctx) + cctx->workSpaceSize |
| + ZSTD_sizeof_localDict(cctx->localDict) |
| + ZSTD_sizeof_mtctx(cctx); |
| } |
| |
| size_t ZSTD_sizeof_CStream(const ZSTD_CStream* zcs) |
| { |
| return ZSTD_sizeof_CCtx(zcs); /* same object */ |
| } |
| |
| /* private API call, for dictBuilder only */ |
| const seqStore_t* ZSTD_getSeqStore(const ZSTD_CCtx* ctx) { return &(ctx->seqStore); } |
| |
| static ZSTD_CCtx_params ZSTD_makeCCtxParamsFromCParams( |
| ZSTD_compressionParameters cParams) |
| { |
| ZSTD_CCtx_params cctxParams; |
| memset(&cctxParams, 0, sizeof(cctxParams)); |
| cctxParams.cParams = cParams; |
| cctxParams.compressionLevel = ZSTD_CLEVEL_DEFAULT; /* should not matter, as all cParams are presumed properly defined */ |
| assert(!ZSTD_checkCParams(cParams)); |
| cctxParams.fParams.contentSizeFlag = 1; |
| return cctxParams; |
| } |
| |
| static ZSTD_CCtx_params* ZSTD_createCCtxParams_advanced( |
| ZSTD_customMem customMem) |
| { |
| ZSTD_CCtx_params* params; |
| if (!customMem.customAlloc ^ !customMem.customFree) return NULL; |
| params = (ZSTD_CCtx_params*)ZSTD_calloc( |
| sizeof(ZSTD_CCtx_params), customMem); |
| if (!params) { return NULL; } |
| params->customMem = customMem; |
| params->compressionLevel = ZSTD_CLEVEL_DEFAULT; |
| params->fParams.contentSizeFlag = 1; |
| return params; |
| } |
| |
| ZSTD_CCtx_params* ZSTD_createCCtxParams(void) |
| { |
| return ZSTD_createCCtxParams_advanced(ZSTD_defaultCMem); |
| } |
| |
| size_t ZSTD_freeCCtxParams(ZSTD_CCtx_params* params) |
| { |
| if (params == NULL) { return 0; } |
| ZSTD_free(params, params->customMem); |
| return 0; |
| } |
| |
| size_t ZSTD_CCtxParams_reset(ZSTD_CCtx_params* params) |
| { |
| return ZSTD_CCtxParams_init(params, ZSTD_CLEVEL_DEFAULT); |
| } |
| |
| size_t ZSTD_CCtxParams_init(ZSTD_CCtx_params* cctxParams, int compressionLevel) { |
| RETURN_ERROR_IF(!cctxParams, GENERIC); |
| memset(cctxParams, 0, sizeof(*cctxParams)); |
| cctxParams->compressionLevel = compressionLevel; |
| cctxParams->fParams.contentSizeFlag = 1; |
| return 0; |
| } |
| |
| size_t ZSTD_CCtxParams_init_advanced(ZSTD_CCtx_params* cctxParams, ZSTD_parameters params) |
| { |
| RETURN_ERROR_IF(!cctxParams, GENERIC); |
| FORWARD_IF_ERROR( ZSTD_checkCParams(params.cParams) ); |
| memset(cctxParams, 0, sizeof(*cctxParams)); |
| cctxParams->cParams = params.cParams; |
| cctxParams->fParams = params.fParams; |
| cctxParams->compressionLevel = ZSTD_CLEVEL_DEFAULT; /* should not matter, as all cParams are presumed properly defined */ |
| assert(!ZSTD_checkCParams(params.cParams)); |
| return 0; |
| } |
| |
| /* ZSTD_assignParamsToCCtxParams() : |
| * params is presumed valid at this stage */ |
| static ZSTD_CCtx_params ZSTD_assignParamsToCCtxParams( |
| ZSTD_CCtx_params cctxParams, ZSTD_parameters params) |
| { |
| ZSTD_CCtx_params ret = cctxParams; |
| ret.cParams = params.cParams; |
| ret.fParams = params.fParams; |
| ret.compressionLevel = ZSTD_CLEVEL_DEFAULT; /* should not matter, as all cParams are presumed properly defined */ |
| assert(!ZSTD_checkCParams(params.cParams)); |
| return ret; |
| } |
| |
| ZSTD_bounds ZSTD_cParam_getBounds(ZSTD_cParameter param) |
| { |
| ZSTD_bounds bounds = { 0, 0, 0 }; |
| |
| switch(param) |
| { |
| case ZSTD_c_compressionLevel: |
| bounds.lowerBound = ZSTD_minCLevel(); |
| bounds.upperBound = ZSTD_maxCLevel(); |
| return bounds; |
| |
| case ZSTD_c_windowLog: |
| bounds.lowerBound = ZSTD_WINDOWLOG_MIN; |
| bounds.upperBound = ZSTD_WINDOWLOG_MAX; |
| return bounds; |
| |
| case ZSTD_c_hashLog: |
| bounds.lowerBound = ZSTD_HASHLOG_MIN; |
| bounds.upperBound = ZSTD_HASHLOG_MAX; |
| return bounds; |
| |
| case ZSTD_c_chainLog: |
| bounds.lowerBound = ZSTD_CHAINLOG_MIN; |
| bounds.upperBound = ZSTD_CHAINLOG_MAX; |
| return bounds; |
| |
| case ZSTD_c_searchLog: |
| bounds.lowerBound = ZSTD_SEARCHLOG_MIN; |
| bounds.upperBound = ZSTD_SEARCHLOG_MAX; |
| return bounds; |
| |
| case ZSTD_c_minMatch: |
| bounds.lowerBound = ZSTD_MINMATCH_MIN; |
| bounds.upperBound = ZSTD_MINMATCH_MAX; |
| return bounds; |
| |
| case ZSTD_c_targetLength: |
| bounds.lowerBound = ZSTD_TARGETLENGTH_MIN; |
| bounds.upperBound = ZSTD_TARGETLENGTH_MAX; |
| return bounds; |
| |
| case ZSTD_c_strategy: |
| bounds.lowerBound = ZSTD_STRATEGY_MIN; |
| bounds.upperBound = ZSTD_STRATEGY_MAX; |
| return bounds; |
| |
| case ZSTD_c_contentSizeFlag: |
| bounds.lowerBound = 0; |
| bounds.upperBound = 1; |
| return bounds; |
| |
| case ZSTD_c_checksumFlag: |
| bounds.lowerBound = 0; |
| bounds.upperBound = 1; |
| return bounds; |
| |
| case ZSTD_c_dictIDFlag: |
| bounds.lowerBound = 0; |
| bounds.upperBound = 1; |
| return bounds; |
| |
| case ZSTD_c_nbWorkers: |
| bounds.lowerBound = 0; |
| #ifdef ZSTD_MULTITHREAD |
| bounds.upperBound = ZSTDMT_NBWORKERS_MAX; |
| #else |
| bounds.upperBound = 0; |
| #endif |
| return bounds; |
| |
| case ZSTD_c_jobSize: |
| bounds.lowerBound = 0; |
| #ifdef ZSTD_MULTITHREAD |
| bounds.upperBound = ZSTDMT_JOBSIZE_MAX; |
| #else |
| bounds.upperBound = 0; |
| #endif |
| return bounds; |
| |
| case ZSTD_c_overlapLog: |
| bounds.lowerBound = ZSTD_OVERLAPLOG_MIN; |
| bounds.upperBound = ZSTD_OVERLAPLOG_MAX; |
| return bounds; |
| |
| case ZSTD_c_enableLongDistanceMatching: |
| bounds.lowerBound = 0; |
| bounds.upperBound = 1; |
| return bounds; |
| |
| case ZSTD_c_ldmHashLog: |
| bounds.lowerBound = ZSTD_LDM_HASHLOG_MIN; |
| bounds.upperBound = ZSTD_LDM_HASHLOG_MAX; |
| return bounds; |
| |
| case ZSTD_c_ldmMinMatch: |
| bounds.lowerBound = ZSTD_LDM_MINMATCH_MIN; |
| bounds.upperBound = ZSTD_LDM_MINMATCH_MAX; |
| return bounds; |
| |
| case ZSTD_c_ldmBucketSizeLog: |
| bounds.lowerBound = ZSTD_LDM_BUCKETSIZELOG_MIN; |
| bounds.upperBound = ZSTD_LDM_BUCKETSIZELOG_MAX; |
| return bounds; |
| |
| case ZSTD_c_ldmHashRateLog: |
| bounds.lowerBound = ZSTD_LDM_HASHRATELOG_MIN; |
| bounds.upperBound = ZSTD_LDM_HASHRATELOG_MAX; |
| return bounds; |
| |
| /* experimental parameters */ |
| case ZSTD_c_rsyncable: |
| bounds.lowerBound = 0; |
| bounds.upperBound = 1; |
| return bounds; |
| |
| case ZSTD_c_forceMaxWindow : |
| bounds.lowerBound = 0; |
| bounds.upperBound = 1; |
| return bounds; |
| |
| case ZSTD_c_format: |
| ZSTD_STATIC_ASSERT(ZSTD_f_zstd1 < ZSTD_f_zstd1_magicless); |
| bounds.lowerBound = ZSTD_f_zstd1; |
| bounds.upperBound = ZSTD_f_zstd1_magicless; /* note : how to ensure at compile time that this is the highest value enum ? */ |
| return bounds; |
| |
| case ZSTD_c_forceAttachDict: |
| ZSTD_STATIC_ASSERT(ZSTD_dictDefaultAttach < ZSTD_dictForceCopy); |
| bounds.lowerBound = ZSTD_dictDefaultAttach; |
| bounds.upperBound = ZSTD_dictForceCopy; /* note : how to ensure at compile time that this is the highest value enum ? */ |
| return bounds; |
| |
| case ZSTD_c_literalCompressionMode: |
| ZSTD_STATIC_ASSERT(ZSTD_lcm_auto < ZSTD_lcm_huffman && ZSTD_lcm_huffman < ZSTD_lcm_uncompressed); |
| bounds.lowerBound = ZSTD_lcm_auto; |
| bounds.upperBound = ZSTD_lcm_uncompressed; |
| return bounds; |
| |
| case ZSTD_c_targetCBlockSize: |
| bounds.lowerBound = ZSTD_TARGETCBLOCKSIZE_MIN; |
| bounds.upperBound = ZSTD_TARGETCBLOCKSIZE_MAX; |
| return bounds; |
| |
| default: |
| { ZSTD_bounds const boundError = { ERROR(parameter_unsupported), 0, 0 }; |
| return boundError; |
| } |
| } |
| } |
| |
| /* ZSTD_cParam_withinBounds: |
| * @return 1 if value is within cParam bounds, |
| * 0 otherwise */ |
| static int ZSTD_cParam_withinBounds(ZSTD_cParameter cParam, int value) |
| { |
| ZSTD_bounds const bounds = ZSTD_cParam_getBounds(cParam); |
| if (ZSTD_isError(bounds.error)) return 0; |
| if (value < bounds.lowerBound) return 0; |
| if (value > bounds.upperBound) return 0; |
| return 1; |
| } |
| |
| /* ZSTD_cParam_clampBounds: |
| * Clamps the value into the bounded range. |
| */ |
| static size_t ZSTD_cParam_clampBounds(ZSTD_cParameter cParam, int* value) |
| { |
| ZSTD_bounds const bounds = ZSTD_cParam_getBounds(cParam); |
| if (ZSTD_isError(bounds.error)) return bounds.error; |
| if (*value < bounds.lowerBound) *value = bounds.lowerBound; |
| if (*value > bounds.upperBound) *value = bounds.upperBound; |
| return 0; |
| } |
| |
| #define BOUNDCHECK(cParam, val) { \ |
| RETURN_ERROR_IF(!ZSTD_cParam_withinBounds(cParam,val), \ |
| parameter_outOfBound); \ |
| } |
| |
| |
| static int ZSTD_isUpdateAuthorized(ZSTD_cParameter param) |
| { |
| switch(param) |
| { |
| case ZSTD_c_compressionLevel: |
| case ZSTD_c_hashLog: |
| case ZSTD_c_chainLog: |
| case ZSTD_c_searchLog: |
| case ZSTD_c_minMatch: |
| case ZSTD_c_targetLength: |
| case ZSTD_c_strategy: |
| return 1; |
| |
| case ZSTD_c_format: |
| case ZSTD_c_windowLog: |
| case ZSTD_c_contentSizeFlag: |
| case ZSTD_c_checksumFlag: |
| case ZSTD_c_dictIDFlag: |
| case ZSTD_c_forceMaxWindow : |
| case ZSTD_c_nbWorkers: |
| case ZSTD_c_jobSize: |
| case ZSTD_c_overlapLog: |
| case ZSTD_c_rsyncable: |
| case ZSTD_c_enableLongDistanceMatching: |
| case ZSTD_c_ldmHashLog: |
| case ZSTD_c_ldmMinMatch: |
| case ZSTD_c_ldmBucketSizeLog: |
| case ZSTD_c_ldmHashRateLog: |
| case ZSTD_c_forceAttachDict: |
| case ZSTD_c_literalCompressionMode: |
| case ZSTD_c_targetCBlockSize: |
| default: |
| return 0; |
| } |
| } |
| |
| size_t ZSTD_CCtx_setParameter(ZSTD_CCtx* cctx, ZSTD_cParameter param, int value) |
| { |
| DEBUGLOG(4, "ZSTD_CCtx_setParameter (%i, %i)", (int)param, value); |
| if (cctx->streamStage != zcss_init) { |
| if (ZSTD_isUpdateAuthorized(param)) { |
| cctx->cParamsChanged = 1; |
| } else { |
| RETURN_ERROR(stage_wrong); |
| } } |
| |
| switch(param) |
| { |
| case ZSTD_c_nbWorkers: |
| RETURN_ERROR_IF((value!=0) && cctx->staticSize, parameter_unsupported, |
| "MT not compatible with static alloc"); |
| break; |
| |
| case ZSTD_c_compressionLevel: |
| case ZSTD_c_windowLog: |
| case ZSTD_c_hashLog: |
| case ZSTD_c_chainLog: |
| case ZSTD_c_searchLog: |
| case ZSTD_c_minMatch: |
| case ZSTD_c_targetLength: |
| case ZSTD_c_strategy: |
| case ZSTD_c_ldmHashRateLog: |
| case ZSTD_c_format: |
| case ZSTD_c_contentSizeFlag: |
| case ZSTD_c_checksumFlag: |
| case ZSTD_c_dictIDFlag: |
| case ZSTD_c_forceMaxWindow: |
| case ZSTD_c_forceAttachDict: |
| case ZSTD_c_literalCompressionMode: |
| case ZSTD_c_jobSize: |
| case ZSTD_c_overlapLog: |
| case ZSTD_c_rsyncable: |
| case ZSTD_c_enableLongDistanceMatching: |
| case ZSTD_c_ldmHashLog: |
| case ZSTD_c_ldmMinMatch: |
| case ZSTD_c_ldmBucketSizeLog: |
| case ZSTD_c_targetCBlockSize: |
| break; |
| |
| default: RETURN_ERROR(parameter_unsupported); |
| } |
| return ZSTD_CCtxParams_setParameter(&cctx->requestedParams, param, value); |
| } |
| |
| size_t ZSTD_CCtxParams_setParameter(ZSTD_CCtx_params* CCtxParams, |
| ZSTD_cParameter param, int value) |
| { |
| DEBUGLOG(4, "ZSTD_CCtxParams_setParameter (%i, %i)", (int)param, value); |
| switch(param) |
| { |
| case ZSTD_c_format : |
| BOUNDCHECK(ZSTD_c_format, value); |
| CCtxParams->format = (ZSTD_format_e)value; |
| return (size_t)CCtxParams->format; |
| |
| case ZSTD_c_compressionLevel : { |
| FORWARD_IF_ERROR(ZSTD_cParam_clampBounds(param, &value)); |
| if (value) { /* 0 : does not change current level */ |
| CCtxParams->compressionLevel = value; |
| } |
| if (CCtxParams->compressionLevel >= 0) return CCtxParams->compressionLevel; |
| return 0; /* return type (size_t) cannot represent negative values */ |
| } |
| |
| case ZSTD_c_windowLog : |
| if (value!=0) /* 0 => use default */ |
| BOUNDCHECK(ZSTD_c_windowLog, value); |
| CCtxParams->cParams.windowLog = value; |
| return CCtxParams->cParams.windowLog; |
| |
| case ZSTD_c_hashLog : |
| if (value!=0) /* 0 => use default */ |
| BOUNDCHECK(ZSTD_c_hashLog, value); |
| CCtxParams->cParams.hashLog = value; |
| return CCtxParams->cParams.hashLog; |
| |
| case ZSTD_c_chainLog : |
| if (value!=0) /* 0 => use default */ |
| BOUNDCHECK(ZSTD_c_chainLog, value); |
| CCtxParams->cParams.chainLog = value; |
| return CCtxParams->cParams.chainLog; |
| |
| case ZSTD_c_searchLog : |
| if (value!=0) /* 0 => use default */ |
| BOUNDCHECK(ZSTD_c_searchLog, value); |
| CCtxParams->cParams.searchLog = value; |
| return value; |
| |
| case ZSTD_c_minMatch : |
| if (value!=0) /* 0 => use default */ |
| BOUNDCHECK(ZSTD_c_minMatch, value); |
| CCtxParams->cParams.minMatch = value; |
| return CCtxParams->cParams.minMatch; |
| |
| case ZSTD_c_targetLength : |
| BOUNDCHECK(ZSTD_c_targetLength, value); |
| CCtxParams->cParams.targetLength = value; |
| return CCtxParams->cParams.targetLength; |
| |
| case ZSTD_c_strategy : |
| if (value!=0) /* 0 => use default */ |
| BOUNDCHECK(ZSTD_c_strategy, value); |
| CCtxParams->cParams.strategy = (ZSTD_strategy)value; |
| return (size_t)CCtxParams->cParams.strategy; |
| |
| case ZSTD_c_contentSizeFlag : |
| /* Content size written in frame header _when known_ (default:1) */ |
| DEBUGLOG(4, "set content size flag = %u", (value!=0)); |
| CCtxParams->fParams.contentSizeFlag = value != 0; |
| return CCtxParams->fParams.contentSizeFlag; |
| |
| case ZSTD_c_checksumFlag : |
| /* A 32-bits content checksum will be calculated and written at end of frame (default:0) */ |
| CCtxParams->fParams.checksumFlag = value != 0; |
| return CCtxParams->fParams.checksumFlag; |
| |
| case ZSTD_c_dictIDFlag : /* When applicable, dictionary's dictID is provided in frame header (default:1) */ |
| DEBUGLOG(4, "set dictIDFlag = %u", (value!=0)); |
| CCtxParams->fParams.noDictIDFlag = !value; |
| return !CCtxParams->fParams.noDictIDFlag; |
| |
| case ZSTD_c_forceMaxWindow : |
| CCtxParams->forceWindow = (value != 0); |
| return CCtxParams->forceWindow; |
| |
| case ZSTD_c_forceAttachDict : { |
| const ZSTD_dictAttachPref_e pref = (ZSTD_dictAttachPref_e)value; |
| BOUNDCHECK(ZSTD_c_forceAttachDict, pref); |
| CCtxParams->attachDictPref = pref; |
| return CCtxParams->attachDictPref; |
| } |
| |
| case ZSTD_c_literalCompressionMode : { |
| const ZSTD_literalCompressionMode_e lcm = (ZSTD_literalCompressionMode_e)value; |
| BOUNDCHECK(ZSTD_c_literalCompressionMode, lcm); |
| CCtxParams->literalCompressionMode = lcm; |
| return CCtxParams->literalCompressionMode; |
| } |
| |
| case ZSTD_c_nbWorkers : |
| #ifndef ZSTD_MULTITHREAD |
| RETURN_ERROR_IF(value!=0, parameter_unsupported, "not compiled with multithreading"); |
| return 0; |
| #else |
| FORWARD_IF_ERROR(ZSTD_cParam_clampBounds(param, &value)); |
| CCtxParams->nbWorkers = value; |
| return CCtxParams->nbWorkers; |
| #endif |
| |
| case ZSTD_c_jobSize : |
| #ifndef ZSTD_MULTITHREAD |
| RETURN_ERROR_IF(value!=0, parameter_unsupported, "not compiled with multithreading"); |
| return 0; |
| #else |
| /* Adjust to the minimum non-default value. */ |
| if (value != 0 && value < ZSTDMT_JOBSIZE_MIN) |
| value = ZSTDMT_JOBSIZE_MIN; |
| FORWARD_IF_ERROR(ZSTD_cParam_clampBounds(param, &value)); |
| assert(value >= 0); |
| CCtxParams->jobSize = value; |
| return CCtxParams->jobSize; |
| #endif |
| |
| case ZSTD_c_overlapLog : |
| #ifndef ZSTD_MULTITHREAD |
| RETURN_ERROR_IF(value!=0, parameter_unsupported, "not compiled with multithreading"); |
| return 0; |
| #else |
| FORWARD_IF_ERROR(ZSTD_cParam_clampBounds(ZSTD_c_overlapLog, &value)); |
| CCtxParams->overlapLog = value; |
| return CCtxParams->overlapLog; |
| #endif |
| |
| case ZSTD_c_rsyncable : |
| #ifndef ZSTD_MULTITHREAD |
| RETURN_ERROR_IF(value!=0, parameter_unsupported, "not compiled with multithreading"); |
| return 0; |
| #else |
| FORWARD_IF_ERROR(ZSTD_cParam_clampBounds(ZSTD_c_overlapLog, &value)); |
| CCtxParams->rsyncable = value; |
| return CCtxParams->rsyncable; |
| #endif |
| |
| case ZSTD_c_enableLongDistanceMatching : |
| CCtxParams->ldmParams.enableLdm = (value!=0); |
| return CCtxParams->ldmParams.enableLdm; |
| |
| case ZSTD_c_ldmHashLog : |
| if (value!=0) /* 0 ==> auto */ |
| BOUNDCHECK(ZSTD_c_ldmHashLog, value); |
| CCtxParams->ldmParams.hashLog = value; |
| return CCtxParams->ldmParams.hashLog; |
| |
| case ZSTD_c_ldmMinMatch : |
| if (value!=0) /* 0 ==> default */ |
| BOUNDCHECK(ZSTD_c_ldmMinMatch, value); |
| CCtxParams->ldmParams.minMatchLength = value; |
| return CCtxParams->ldmParams.minMatchLength; |
| |
| case ZSTD_c_ldmBucketSizeLog : |
| if (value!=0) /* 0 ==> default */ |
| BOUNDCHECK(ZSTD_c_ldmBucketSizeLog, value); |
| CCtxParams->ldmParams.bucketSizeLog = value; |
| return CCtxParams->ldmParams.bucketSizeLog; |
| |
| case ZSTD_c_ldmHashRateLog : |
| RETURN_ERROR_IF(value > ZSTD_WINDOWLOG_MAX - ZSTD_HASHLOG_MIN, |
| parameter_outOfBound); |
| CCtxParams->ldmParams.hashRateLog = value; |
| return CCtxParams->ldmParams.hashRateLog; |
| |
| case ZSTD_c_targetCBlockSize : |
| if (value!=0) /* 0 ==> default */ |
| BOUNDCHECK(ZSTD_c_targetCBlockSize, value); |
| CCtxParams->targetCBlockSize = value; |
| return CCtxParams->targetCBlockSize; |
| |
| default: RETURN_ERROR(parameter_unsupported, "unknown parameter"); |
| } |
| } |
| |
| size_t ZSTD_CCtx_getParameter(ZSTD_CCtx* cctx, ZSTD_cParameter param, int* value) |
| { |
| return ZSTD_CCtxParams_getParameter(&cctx->requestedParams, param, value); |
| } |
| |
| size_t ZSTD_CCtxParams_getParameter( |
| ZSTD_CCtx_params* CCtxParams, ZSTD_cParameter param, int* value) |
| { |
| switch(param) |
| { |
| case ZSTD_c_format : |
| *value = CCtxParams->format; |
| break; |
| case ZSTD_c_compressionLevel : |
| *value = CCtxParams->compressionLevel; |
| break; |
| case ZSTD_c_windowLog : |
| *value = (int)CCtxParams->cParams.windowLog; |
| break; |
| case ZSTD_c_hashLog : |
| *value = (int)CCtxParams->cParams.hashLog; |
| break; |
| case ZSTD_c_chainLog : |
| *value = (int)CCtxParams->cParams.chainLog; |
| break; |
| case ZSTD_c_searchLog : |
| *value = CCtxParams->cParams.searchLog; |
| break; |
| case ZSTD_c_minMatch : |
| *value = CCtxParams->cParams.minMatch; |
| break; |
| case ZSTD_c_targetLength : |
| *value = CCtxParams->cParams.targetLength; |
| break; |
| case ZSTD_c_strategy : |
| *value = (unsigned)CCtxParams->cParams.strategy; |
| break; |
| case ZSTD_c_contentSizeFlag : |
| *value = CCtxParams->fParams.contentSizeFlag; |
| break; |
| case ZSTD_c_checksumFlag : |
| *value = CCtxParams->fParams.checksumFlag; |
| break; |
| case ZSTD_c_dictIDFlag : |
| *value = !CCtxParams->fParams.noDictIDFlag; |
| break; |
| case ZSTD_c_forceMaxWindow : |
| *value = CCtxParams->forceWindow; |
| break; |
| case ZSTD_c_forceAttachDict : |
| *value = CCtxParams->attachDictPref; |
| break; |
| case ZSTD_c_literalCompressionMode : |
| *value = CCtxParams->literalCompressionMode; |
| break; |
| case ZSTD_c_nbWorkers : |
| #ifndef ZSTD_MULTITHREAD |
| assert(CCtxParams->nbWorkers == 0); |
| #endif |
| *value = CCtxParams->nbWorkers; |
| break; |
| case ZSTD_c_jobSize : |
| #ifndef ZSTD_MULTITHREAD |
| RETURN_ERROR(parameter_unsupported, "not compiled with multithreading"); |
| #else |
| assert(CCtxParams->jobSize <= INT_MAX); |
| *value = (int)CCtxParams->jobSize; |
| break; |
| #endif |
| case ZSTD_c_overlapLog : |
| #ifndef ZSTD_MULTITHREAD |
| RETURN_ERROR(parameter_unsupported, "not compiled with multithreading"); |
| #else |
| *value = CCtxParams->overlapLog; |
| break; |
| #endif |
| case ZSTD_c_rsyncable : |
| #ifndef ZSTD_MULTITHREAD |
| RETURN_ERROR(parameter_unsupported, "not compiled with multithreading"); |
| #else |
| *value = CCtxParams->rsyncable; |
| break; |
| #endif |
| case ZSTD_c_enableLongDistanceMatching : |
| *value = CCtxParams->ldmParams.enableLdm; |
| break; |
| case ZSTD_c_ldmHashLog : |
| *value = CCtxParams->ldmParams.hashLog; |
| break; |
| case ZSTD_c_ldmMinMatch : |
| *value = CCtxParams->ldmParams.minMatchLength; |
| break; |
| case ZSTD_c_ldmBucketSizeLog : |
| *value = CCtxParams->ldmParams.bucketSizeLog; |
| break; |
| case ZSTD_c_ldmHashRateLog : |
| *value = CCtxParams->ldmParams.hashRateLog; |
| break; |
| case ZSTD_c_targetCBlockSize : |
| *value = (int)CCtxParams->targetCBlockSize; |
| break; |
| default: RETURN_ERROR(parameter_unsupported, "unknown parameter"); |
| } |
| return 0; |
| } |
| |
| /** ZSTD_CCtx_setParametersUsingCCtxParams() : |
| * just applies `params` into `cctx` |
| * no action is performed, parameters are merely stored. |
| * If ZSTDMT is enabled, parameters are pushed to cctx->mtctx. |
| * This is possible even if a compression is ongoing. |
| * In which case, new parameters will be applied on the fly, starting with next compression job. |
| */ |
| size_t ZSTD_CCtx_setParametersUsingCCtxParams( |
| ZSTD_CCtx* cctx, const ZSTD_CCtx_params* params) |
| { |
| DEBUGLOG(4, "ZSTD_CCtx_setParametersUsingCCtxParams"); |
| RETURN_ERROR_IF(cctx->streamStage != zcss_init, stage_wrong); |
| RETURN_ERROR_IF(cctx->cdict, stage_wrong); |
| |
| cctx->requestedParams = *params; |
| return 0; |
| } |
| |
| ZSTDLIB_API size_t ZSTD_CCtx_setPledgedSrcSize(ZSTD_CCtx* cctx, unsigned long long pledgedSrcSize) |
| { |
| DEBUGLOG(4, "ZSTD_CCtx_setPledgedSrcSize to %u bytes", (U32)pledgedSrcSize); |
| RETURN_ERROR_IF(cctx->streamStage != zcss_init, stage_wrong); |
| cctx->pledgedSrcSizePlusOne = pledgedSrcSize+1; |
| return 0; |
| } |
| |
| /** |
| * Initializes the local dict using the requested parameters. |
| * NOTE: This does not use the pledged src size, because it may be used for more |
| * than one compression. |
| */ |
| static size_t ZSTD_initLocalDict(ZSTD_CCtx* cctx) |
| { |
| ZSTD_localDict* const dl = &cctx->localDict; |
| ZSTD_compressionParameters const cParams = ZSTD_getCParamsFromCCtxParams( |
| &cctx->requestedParams, 0, dl->dictSize); |
| if (dl->dict == NULL) { |
| /* No local dictionary. */ |
| assert(dl->dictBuffer == NULL); |
| assert(dl->cdict == NULL); |
| assert(dl->dictSize == 0); |
| return 0; |
| } |
| if (dl->cdict != NULL) { |
| assert(cctx->cdict == dl->cdict); |
| /* Local dictionary already initialized. */ |
| return 0; |
| } |
| assert(dl->dictSize > 0); |
| assert(cctx->cdict == NULL); |
| assert(cctx->prefixDict.dict == NULL); |
| |
| dl->cdict = ZSTD_createCDict_advanced( |
| dl->dict, |
| dl->dictSize, |
| ZSTD_dlm_byRef, |
| dl->dictContentType, |
| cParams, |
| cctx->customMem); |
| RETURN_ERROR_IF(!dl->cdict, memory_allocation); |
| cctx->cdict = dl->cdict; |
| return 0; |
| } |
| |
| size_t ZSTD_CCtx_loadDictionary_advanced( |
| ZSTD_CCtx* cctx, const void* dict, size_t dictSize, |
| ZSTD_dictLoadMethod_e dictLoadMethod, ZSTD_dictContentType_e dictContentType) |
| { |
| RETURN_ERROR_IF(cctx->streamStage != zcss_init, stage_wrong); |
| RETURN_ERROR_IF(cctx->staticSize, memory_allocation, |
| "no malloc for static CCtx"); |
| DEBUGLOG(4, "ZSTD_CCtx_loadDictionary_advanced (size: %u)", (U32)dictSize); |
| ZSTD_clearAllDicts(cctx); /* in case one already exists */ |
| if (dict == NULL || dictSize == 0) /* no dictionary mode */ |
| return 0; |
| if (dictLoadMethod == ZSTD_dlm_byRef) { |
| cctx->localDict.dict = dict; |
| } else { |
| void* dictBuffer = ZSTD_malloc(dictSize, cctx->customMem); |
| RETURN_ERROR_IF(!dictBuffer, memory_allocation); |
| memcpy(dictBuffer, dict, dictSize); |
| cctx->localDict.dictBuffer = dictBuffer; |
| cctx->localDict.dict = dictBuffer; |
| } |
| cctx->localDict.dictSize = dictSize; |
| cctx->localDict.dictContentType = dictContentType; |
| return 0; |
| } |
| |
| ZSTDLIB_API size_t ZSTD_CCtx_loadDictionary_byReference( |
| ZSTD_CCtx* cctx, const void* dict, size_t dictSize) |
| { |
| return ZSTD_CCtx_loadDictionary_advanced( |
| cctx, dict, dictSize, ZSTD_dlm_byRef, ZSTD_dct_auto); |
| } |
| |
| ZSTDLIB_API size_t ZSTD_CCtx_loadDictionary(ZSTD_CCtx* cctx, const void* dict, size_t dictSize) |
| { |
| return ZSTD_CCtx_loadDictionary_advanced( |
| cctx, dict, dictSize, ZSTD_dlm_byCopy, ZSTD_dct_auto); |
| } |
| |
| |
| size_t ZSTD_CCtx_refCDict(ZSTD_CCtx* cctx, const ZSTD_CDict* cdict) |
| { |
| RETURN_ERROR_IF(cctx->streamStage != zcss_init, stage_wrong); |
| /* Free the existing local cdict (if any) to save memory. */ |
| ZSTD_clearAllDicts(cctx); |
| cctx->cdict = cdict; |
| return 0; |
| } |
| |
| size_t ZSTD_CCtx_refPrefix(ZSTD_CCtx* cctx, const void* prefix, size_t prefixSize) |
| { |
| return ZSTD_CCtx_refPrefix_advanced(cctx, prefix, prefixSize, ZSTD_dct_rawContent); |
| } |
| |
| size_t ZSTD_CCtx_refPrefix_advanced( |
| ZSTD_CCtx* cctx, const void* prefix, size_t prefixSize, ZSTD_dictContentType_e dictContentType) |
| { |
| RETURN_ERROR_IF(cctx->streamStage != zcss_init, stage_wrong); |
| ZSTD_clearAllDicts(cctx); |
| cctx->prefixDict.dict = prefix; |
| cctx->prefixDict.dictSize = prefixSize; |
| cctx->prefixDict.dictContentType = dictContentType; |
| return 0; |
| } |
| |
| /*! ZSTD_CCtx_reset() : |
| * Also dumps dictionary */ |
| size_t ZSTD_CCtx_reset(ZSTD_CCtx* cctx, ZSTD_ResetDirective reset) |
| { |
| if ( (reset == ZSTD_reset_session_only) |
| || (reset == ZSTD_reset_session_and_parameters) ) { |
| cctx->streamStage = zcss_init; |
| cctx->pledgedSrcSizePlusOne = 0; |
| } |
| if ( (reset == ZSTD_reset_parameters) |
| || (reset == ZSTD_reset_session_and_parameters) ) { |
| RETURN_ERROR_IF(cctx->streamStage != zcss_init, stage_wrong); |
| ZSTD_clearAllDicts(cctx); |
| return ZSTD_CCtxParams_reset(&cctx->requestedParams); |
| } |
| return 0; |
| } |
| |
| |
| /** ZSTD_checkCParams() : |
| control CParam values remain within authorized range. |
| @return : 0, or an error code if one value is beyond authorized range */ |
| size_t ZSTD_checkCParams(ZSTD_compressionParameters cParams) |
| { |
| BOUNDCHECK(ZSTD_c_windowLog, (int)cParams.windowLog); |
| BOUNDCHECK(ZSTD_c_chainLog, (int)cParams.chainLog); |
| BOUNDCHECK(ZSTD_c_hashLog, (int)cParams.hashLog); |
| BOUNDCHECK(ZSTD_c_searchLog, (int)cParams.searchLog); |
| BOUNDCHECK(ZSTD_c_minMatch, (int)cParams.minMatch); |
| BOUNDCHECK(ZSTD_c_targetLength,(int)cParams.targetLength); |
| BOUNDCHECK(ZSTD_c_strategy, cParams.strategy); |
| return 0; |
| } |
| |
| /** ZSTD_clampCParams() : |
| * make CParam values within valid range. |
| * @return : valid CParams */ |
| static ZSTD_compressionParameters |
| ZSTD_clampCParams(ZSTD_compressionParameters cParams) |
| { |
| # define CLAMP_TYPE(cParam, val, type) { \ |
| ZSTD_bounds const bounds = ZSTD_cParam_getBounds(cParam); \ |
| if ((int)val<bounds.lowerBound) val=(type)bounds.lowerBound; \ |
| else if ((int)val>bounds.upperBound) val=(type)bounds.upperBound; \ |
| } |
| # define CLAMP(cParam, val) CLAMP_TYPE(cParam, val, unsigned) |
| CLAMP(ZSTD_c_windowLog, cParams.windowLog); |
| CLAMP(ZSTD_c_chainLog, cParams.chainLog); |
| CLAMP(ZSTD_c_hashLog, cParams.hashLog); |
| CLAMP(ZSTD_c_searchLog, cParams.searchLog); |
| CLAMP(ZSTD_c_minMatch, cParams.minMatch); |
| CLAMP(ZSTD_c_targetLength,cParams.targetLength); |
| CLAMP_TYPE(ZSTD_c_strategy,cParams.strategy, ZSTD_strategy); |
| return cParams; |
| } |
| |
| /** ZSTD_cycleLog() : |
| * condition for correct operation : hashLog > 1 */ |
| static U32 ZSTD_cycleLog(U32 hashLog, ZSTD_strategy strat) |
| { |
| U32 const btScale = ((U32)strat >= (U32)ZSTD_btlazy2); |
| return hashLog - btScale; |
| } |
| |
| /** ZSTD_adjustCParams_internal() : |
| * optimize `cPar` for a specified input (`srcSize` and `dictSize`). |
| * mostly downsize to reduce memory consumption and initialization latency. |
| * `srcSize` can be ZSTD_CONTENTSIZE_UNKNOWN when not known. |
| * note : for the time being, `srcSize==0` means "unknown" too, for compatibility with older convention. |
| * condition : cPar is presumed validated (can be checked using ZSTD_checkCParams()). */ |
| static ZSTD_compressionParameters |
| ZSTD_adjustCParams_internal(ZSTD_compressionParameters cPar, |
| unsigned long long srcSize, |
| size_t dictSize) |
| { |
| static const U64 minSrcSize = 513; /* (1<<9) + 1 */ |
| static const U64 maxWindowResize = 1ULL << (ZSTD_WINDOWLOG_MAX-1); |
| assert(ZSTD_checkCParams(cPar)==0); |
| |
| if (dictSize && (srcSize+1<2) /* ZSTD_CONTENTSIZE_UNKNOWN and 0 mean "unknown" */ ) |
| srcSize = minSrcSize; /* presumed small when there is a dictionary */ |
| else if (srcSize == 0) |
| srcSize = ZSTD_CONTENTSIZE_UNKNOWN; /* 0 == unknown : presumed large */ |
| |
| /* resize windowLog if input is small enough, to use less memory */ |
| if ( (srcSize < maxWindowResize) |
| && (dictSize < maxWindowResize) ) { |
| U32 const tSize = (U32)(srcSize + dictSize); |
| static U32 const hashSizeMin = 1 << ZSTD_HASHLOG_MIN; |
| U32 const srcLog = (tSize < hashSizeMin) ? ZSTD_HASHLOG_MIN : |
| ZSTD_highbit32(tSize-1) + 1; |
| if (cPar.windowLog > srcLog) cPar.windowLog = srcLog; |
| } |
| if (cPar.hashLog > cPar.windowLog+1) cPar.hashLog = cPar.windowLog+1; |
| { U32 const cycleLog = ZSTD_cycleLog(cPar.chainLog, cPar.strategy); |
| if (cycleLog > cPar.windowLog) |
| cPar.chainLog -= (cycleLog - cPar.windowLog); |
| } |
| |
| if (cPar.windowLog < ZSTD_WINDOWLOG_ABSOLUTEMIN) |
| cPar.windowLog = ZSTD_WINDOWLOG_ABSOLUTEMIN; /* minimum wlog required for valid frame header */ |
| |
| return cPar; |
| } |
| |
| ZSTD_compressionParameters |
| ZSTD_adjustCParams(ZSTD_compressionParameters cPar, |
| unsigned long long srcSize, |
| size_t dictSize) |
| { |
| cPar = ZSTD_clampCParams(cPar); /* resulting cPar is necessarily valid (all parameters within range) */ |
| return ZSTD_adjustCParams_internal(cPar, srcSize, dictSize); |
| } |
| |
| ZSTD_compressionParameters ZSTD_getCParamsFromCCtxParams( |
| const ZSTD_CCtx_params* CCtxParams, U64 srcSizeHint, size_t dictSize) |
| { |
| ZSTD_compressionParameters cParams = ZSTD_getCParams(CCtxParams->compressionLevel, srcSizeHint, dictSize); |
| if (CCtxParams->ldmParams.enableLdm) cParams.windowLog = ZSTD_LDM_DEFAULT_WINDOW_LOG; |
| if (CCtxParams->cParams.windowLog) cParams.windowLog = CCtxParams->cParams.windowLog; |
| if (CCtxParams->cParams.hashLog) cParams.hashLog = CCtxParams->cParams.hashLog; |
| if (CCtxParams->cParams.chainLog) cParams.chainLog = CCtxParams->cParams.chainLog; |
| if (CCtxParams->cParams.searchLog) cParams.searchLog = CCtxParams->cParams.searchLog; |
| if (CCtxParams->cParams.minMatch) cParams.minMatch = CCtxParams->cParams.minMatch; |
| if (CCtxParams->cParams.targetLength) cParams.targetLength = CCtxParams->cParams.targetLength; |
| if (CCtxParams->cParams.strategy) cParams.strategy = CCtxParams->cParams.strategy; |
| assert(!ZSTD_checkCParams(cParams)); |
| return ZSTD_adjustCParams_internal(cParams, srcSizeHint, dictSize); |
| } |
| |
| static size_t |
| ZSTD_sizeof_matchState(const ZSTD_compressionParameters* const cParams, |
| const U32 forCCtx) |
| { |
| size_t const chainSize = (cParams->strategy == ZSTD_fast) ? 0 : ((size_t)1 << cParams->chainLog); |
| size_t const hSize = ((size_t)1) << cParams->hashLog; |
| U32 const hashLog3 = (forCCtx && cParams->minMatch==3) ? MIN(ZSTD_HASHLOG3_MAX, cParams->windowLog) : 0; |
| size_t const h3Size = ((size_t)1) << hashLog3; |
| size_t const tableSpace = (chainSize + hSize + h3Size) * sizeof(U32); |
| size_t const optPotentialSpace = ((MaxML+1) + (MaxLL+1) + (MaxOff+1) + (1<<Litbits)) * sizeof(U32) |
| + (ZSTD_OPT_NUM+1) * (sizeof(ZSTD_match_t)+sizeof(ZSTD_optimal_t)); |
| size_t const optSpace = (forCCtx && (cParams->strategy >= ZSTD_btopt)) |
| ? optPotentialSpace |
| : 0; |
| DEBUGLOG(4, "chainSize: %u - hSize: %u - h3Size: %u", |
| (U32)chainSize, (U32)hSize, (U32)h3Size); |
| return tableSpace + optSpace; |
| } |
| |
| size_t ZSTD_estimateCCtxSize_usingCCtxParams(const ZSTD_CCtx_params* params) |
| { |
| RETURN_ERROR_IF(params->nbWorkers > 0, GENERIC, "Estimate CCtx size is supported for single-threaded compression only."); |
| { ZSTD_compressionParameters const cParams = |
| ZSTD_getCParamsFromCCtxParams(params, 0, 0); |
| size_t const blockSize = MIN(ZSTD_BLOCKSIZE_MAX, (size_t)1 << cParams.windowLog); |
| U32 const divider = (cParams.minMatch==3) ? 3 : 4; |
| size_t const maxNbSeq = blockSize / divider; |
| size_t const tokenSpace = WILDCOPY_OVERLENGTH + blockSize + 11*maxNbSeq; |
| size_t const entropySpace = HUF_WORKSPACE_SIZE; |
| size_t const blockStateSpace = 2 * sizeof(ZSTD_compressedBlockState_t); |
| size_t const matchStateSize = ZSTD_sizeof_matchState(&cParams, /* forCCtx */ 1); |
| |
| size_t const ldmSpace = ZSTD_ldm_getTableSize(params->ldmParams); |
| size_t const ldmSeqSpace = ZSTD_ldm_getMaxNbSeq(params->ldmParams, blockSize) * sizeof(rawSeq); |
| |
| size_t const neededSpace = entropySpace + blockStateSpace + tokenSpace + |
| matchStateSize + ldmSpace + ldmSeqSpace; |
| |
| DEBUGLOG(5, "sizeof(ZSTD_CCtx) : %u", (U32)sizeof(ZSTD_CCtx)); |
| DEBUGLOG(5, "estimate workSpace : %u", (U32)neededSpace); |
| return sizeof(ZSTD_CCtx) + neededSpace; |
| } |
| } |
| |
| size_t ZSTD_estimateCCtxSize_usingCParams(ZSTD_compressionParameters cParams) |
| { |
| ZSTD_CCtx_params const params = ZSTD_makeCCtxParamsFromCParams(cParams); |
| return ZSTD_estimateCCtxSize_usingCCtxParams(¶ms); |
| } |
| |
| static size_t ZSTD_estimateCCtxSize_internal(int compressionLevel) |
| { |
| ZSTD_compressionParameters const cParams = ZSTD_getCParams(compressionLevel, 0, 0); |
| return ZSTD_estimateCCtxSize_usingCParams(cParams); |
| } |
| |
| size_t ZSTD_estimateCCtxSize(int compressionLevel) |
| { |
| int level; |
| size_t memBudget = 0; |
| for (level=MIN(compressionLevel, 1); level<=compressionLevel; level++) { |
| size_t const newMB = ZSTD_estimateCCtxSize_internal(level); |
| if (newMB > memBudget) memBudget = newMB; |
| } |
| return memBudget; |
| } |
| |
| size_t ZSTD_estimateCStreamSize_usingCCtxParams(const ZSTD_CCtx_params* params) |
| { |
| RETURN_ERROR_IF(params->nbWorkers > 0, GENERIC, "Estimate CCtx size is supported for single-threaded compression only."); |
| { ZSTD_compressionParameters const cParams = |
| ZSTD_getCParamsFromCCtxParams(params, 0, 0); |
| size_t const CCtxSize = ZSTD_estimateCCtxSize_usingCCtxParams(params); |
| size_t const blockSize = MIN(ZSTD_BLOCKSIZE_MAX, (size_t)1 << cParams.windowLog); |
| size_t const inBuffSize = ((size_t)1 << cParams.windowLog) + blockSize; |
| size_t const outBuffSize = ZSTD_compressBound(blockSize) + 1; |
| size_t const streamingSize = inBuffSize + outBuffSize; |
| |
| return CCtxSize + streamingSize; |
| } |
| } |
| |
| size_t ZSTD_estimateCStreamSize_usingCParams(ZSTD_compressionParameters cParams) |
| { |
| ZSTD_CCtx_params const params = ZSTD_makeCCtxParamsFromCParams(cParams); |
| return ZSTD_estimateCStreamSize_usingCCtxParams(¶ms); |
| } |
| |
| static size_t ZSTD_estimateCStreamSize_internal(int compressionLevel) |
| { |
| ZSTD_compressionParameters const cParams = ZSTD_getCParams(compressionLevel, 0, 0); |
| return ZSTD_estimateCStreamSize_usingCParams(cParams); |
| } |
| |
| size_t ZSTD_estimateCStreamSize(int compressionLevel) |
| { |
| int level; |
| size_t memBudget = 0; |
| for (level=MIN(compressionLevel, 1); level<=compressionLevel; level++) { |
| size_t const newMB = ZSTD_estimateCStreamSize_internal(level); |
| if (newMB > memBudget) memBudget = newMB; |
| } |
| return memBudget; |
| } |
| |
| /* ZSTD_getFrameProgression(): |
| * tells how much data has been consumed (input) and produced (output) for current frame. |
| * able to count progression inside worker threads (non-blocking mode). |
| */ |
| ZSTD_frameProgression ZSTD_getFrameProgression(const ZSTD_CCtx* cctx) |
| { |
| #ifdef ZSTD_MULTITHREAD |
| if (cctx->appliedParams.nbWorkers > 0) { |
| return ZSTDMT_getFrameProgression(cctx->mtctx); |
| } |
| #endif |
| { ZSTD_frameProgression fp; |
| size_t const buffered = (cctx->inBuff == NULL) ? 0 : |
| cctx->inBuffPos - cctx->inToCompress; |
| if (buffered) assert(cctx->inBuffPos >= cctx->inToCompress); |
| assert(buffered <= ZSTD_BLOCKSIZE_MAX); |
| fp.ingested = cctx->consumedSrcSize + buffered; |
| fp.consumed = cctx->consumedSrcSize; |
| fp.produced = cctx->producedCSize; |
| fp.flushed = cctx->producedCSize; /* simplified; some data might still be left within streaming output buffer */ |
| fp.currentJobID = 0; |
| fp.nbActiveWorkers = 0; |
| return fp; |
| } } |
| |
| /*! ZSTD_toFlushNow() |
| * Only useful for multithreading scenarios currently (nbWorkers >= 1). |
| */ |
| size_t ZSTD_toFlushNow(ZSTD_CCtx* cctx) |
| { |
| #ifdef ZSTD_MULTITHREAD |
| if (cctx->appliedParams.nbWorkers > 0) { |
| return ZSTDMT_toFlushNow(cctx->mtctx); |
| } |
| #endif |
| (void)cctx; |
| return 0; /* over-simplification; could also check if context is currently running in streaming mode, and in which case, report how many bytes are left to be flushed within output buffer */ |
| } |
| |
| |
| |
| static U32 ZSTD_equivalentCParams(ZSTD_compressionParameters cParams1, |
| ZSTD_compressionParameters cParams2) |
| { |
| return (cParams1.hashLog == cParams2.hashLog) |
| & (cParams1.chainLog == cParams2.chainLog) |
| & (cParams1.strategy == cParams2.strategy) /* opt parser space */ |
| & ((cParams1.minMatch==3) == (cParams2.minMatch==3)); /* hashlog3 space */ |
| } |
| |
| static void ZSTD_assertEqualCParams(ZSTD_compressionParameters cParams1, |
| ZSTD_compressionParameters cParams2) |
| { |
| (void)cParams1; |
| (void)cParams2; |
| assert(cParams1.windowLog == cParams2.windowLog); |
| assert(cParams1.chainLog == cParams2.chainLog); |
| assert(cParams1.hashLog == cParams2.hashLog); |
| assert(cParams1.searchLog == cParams2.searchLog); |
| assert(cParams1.minMatch == cParams2.minMatch); |
| assert(cParams1.targetLength == cParams2.targetLength); |
| assert(cParams1.strategy == cParams2.strategy); |
| } |
| |
| /** The parameters are equivalent if ldm is not enabled in both sets or |
| * all the parameters are equivalent. */ |
| static U32 ZSTD_equivalentLdmParams(ldmParams_t ldmParams1, |
| ldmParams_t ldmParams2) |
| { |
| return (!ldmParams1.enableLdm && !ldmParams2.enableLdm) || |
| (ldmParams1.enableLdm == ldmParams2.enableLdm && |
| ldmParams1.hashLog == ldmParams2.hashLog && |
| ldmParams1.bucketSizeLog == ldmParams2.bucketSizeLog && |
| ldmParams1.minMatchLength == ldmParams2.minMatchLength && |
| ldmParams1.hashRateLog == ldmParams2.hashRateLog); |
| } |
| |
| typedef enum { ZSTDb_not_buffered, ZSTDb_buffered } ZSTD_buffered_policy_e; |
| |
| /* ZSTD_sufficientBuff() : |
| * check internal buffers exist for streaming if buffPol == ZSTDb_buffered . |
| * Note : they are assumed to be correctly sized if ZSTD_equivalentCParams()==1 */ |
| static U32 ZSTD_sufficientBuff(size_t bufferSize1, size_t maxNbSeq1, |
| size_t maxNbLit1, |
| ZSTD_buffered_policy_e buffPol2, |
| ZSTD_compressionParameters cParams2, |
| U64 pledgedSrcSize) |
| { |
| size_t const windowSize2 = MAX(1, (size_t)MIN(((U64)1 << cParams2.windowLog), pledgedSrcSize)); |
| size_t const blockSize2 = MIN(ZSTD_BLOCKSIZE_MAX, windowSize2); |
| size_t const maxNbSeq2 = blockSize2 / ((cParams2.minMatch == 3) ? 3 : 4); |
| size_t const maxNbLit2 = blockSize2; |
| size_t const neededBufferSize2 = (buffPol2==ZSTDb_buffered) ? windowSize2 + blockSize2 : 0; |
| DEBUGLOG(4, "ZSTD_sufficientBuff: is neededBufferSize2=%u <= bufferSize1=%u", |
| (U32)neededBufferSize2, (U32)bufferSize1); |
| DEBUGLOG(4, "ZSTD_sufficientBuff: is maxNbSeq2=%u <= maxNbSeq1=%u", |
| (U32)maxNbSeq2, (U32)maxNbSeq1); |
| DEBUGLOG(4, "ZSTD_sufficientBuff: is maxNbLit2=%u <= maxNbLit1=%u", |
| (U32)maxNbLit2, (U32)maxNbLit1); |
| return (maxNbLit2 <= maxNbLit1) |
| & (maxNbSeq2 <= maxNbSeq1) |
| & (neededBufferSize2 <= bufferSize1); |
| } |
| |
| /** Equivalence for resetCCtx purposes */ |
| static U32 ZSTD_equivalentParams(ZSTD_CCtx_params params1, |
| ZSTD_CCtx_params params2, |
| size_t buffSize1, |
| size_t maxNbSeq1, size_t maxNbLit1, |
| ZSTD_buffered_policy_e buffPol2, |
| U64 pledgedSrcSize) |
| { |
| DEBUGLOG(4, "ZSTD_equivalentParams: pledgedSrcSize=%u", (U32)pledgedSrcSize); |
| if (!ZSTD_equivalentCParams(params1.cParams, params2.cParams)) { |
| DEBUGLOG(4, "ZSTD_equivalentCParams() == 0"); |
| return 0; |
| } |
| if (!ZSTD_equivalentLdmParams(params1.ldmParams, params2.ldmParams)) { |
| DEBUGLOG(4, "ZSTD_equivalentLdmParams() == 0"); |
| return 0; |
| } |
| if (!ZSTD_sufficientBuff(buffSize1, maxNbSeq1, maxNbLit1, buffPol2, |
| params2.cParams, pledgedSrcSize)) { |
| DEBUGLOG(4, "ZSTD_sufficientBuff() == 0"); |
| return 0; |
| } |
| return 1; |
| } |
| |
| static void ZSTD_reset_compressedBlockState(ZSTD_compressedBlockState_t* bs) |
| { |
| int i; |
| for (i = 0; i < ZSTD_REP_NUM; ++i) |
| bs->rep[i] = repStartValue[i]; |
| bs->entropy.huf.repeatMode = HUF_repeat_none; |
| bs->entropy.fse.offcode_repeatMode = FSE_repeat_none; |
| bs->entropy.fse.matchlength_repeatMode = FSE_repeat_none; |
| bs->entropy.fse.litlength_repeatMode = FSE_repeat_none; |
| } |
| |
| /*! ZSTD_invalidateMatchState() |
| * Invalidate all the matches in the match finder tables. |
| * Requires nextSrc and base to be set (can be NULL). |
| */ |
| static void ZSTD_invalidateMatchState(ZSTD_matchState_t* ms) |
| { |
| ZSTD_window_clear(&ms->window); |
| |
| ms->nextToUpdate = ms->window.dictLimit; |
| ms->loadedDictEnd = 0; |
| ms->opt.litLengthSum = 0; /* force reset of btopt stats */ |
| ms->dictMatchState = NULL; |
| } |
| |
| /*! ZSTD_continueCCtx() : |
| * reuse CCtx without reset (note : requires no dictionary) */ |
| static size_t ZSTD_continueCCtx(ZSTD_CCtx* cctx, ZSTD_CCtx_params params, U64 pledgedSrcSize) |
| { |
| size_t const windowSize = MAX(1, (size_t)MIN(((U64)1 << params.cParams.windowLog), pledgedSrcSize)); |
| size_t const blockSize = MIN(ZSTD_BLOCKSIZE_MAX, windowSize); |
| DEBUGLOG(4, "ZSTD_continueCCtx: re-use context in place"); |
| |
| cctx->blockSize = blockSize; /* previous block size could be different even for same windowLog, due to pledgedSrcSize */ |
| cctx->appliedParams = params; |
| cctx->blockState.matchState.cParams = params.cParams; |
| cctx->pledgedSrcSizePlusOne = pledgedSrcSize+1; |
| cctx->consumedSrcSize = 0; |
| cctx->producedCSize = 0; |
| if (pledgedSrcSize == ZSTD_CONTENTSIZE_UNKNOWN) |
| cctx->appliedParams.fParams.contentSizeFlag = 0; |
| DEBUGLOG(4, "pledged content size : %u ; flag : %u", |
| (U32)pledgedSrcSize, cctx->appliedParams.fParams.contentSizeFlag); |
| cctx->stage = ZSTDcs_init; |
| cctx->dictID = 0; |
| if (params.ldmParams.enableLdm) |
| ZSTD_window_clear(&cctx->ldmState.window); |
| ZSTD_referenceExternalSequences(cctx, NULL, 0); |
| ZSTD_invalidateMatchState(&cctx->blockState.matchState); |
| ZSTD_reset_compressedBlockState(cctx->blockState.prevCBlock); |
| XXH64_reset(&cctx->xxhState, 0); |
| return 0; |
| } |
| |
| typedef enum { ZSTDcrp_continue, ZSTDcrp_noMemset } ZSTD_compResetPolicy_e; |
| |
| typedef enum { ZSTD_resetTarget_CDict, ZSTD_resetTarget_CCtx } ZSTD_resetTarget_e; |
| |
| static void* |
| ZSTD_reset_matchState(ZSTD_matchState_t* ms, |
| void* ptr, |
| const ZSTD_compressionParameters* cParams, |
| ZSTD_compResetPolicy_e const crp, ZSTD_resetTarget_e const forWho) |
| { |
| size_t const chainSize = (cParams->strategy == ZSTD_fast) ? 0 : ((size_t)1 << cParams->chainLog); |
| size_t const hSize = ((size_t)1) << cParams->hashLog; |
| U32 const hashLog3 = ((forWho == ZSTD_resetTarget_CCtx) && cParams->minMatch==3) ? MIN(ZSTD_HASHLOG3_MAX, cParams->windowLog) : 0; |
| size_t const h3Size = ((size_t)1) << hashLog3; |
| size_t const tableSpace = (chainSize + hSize + h3Size) * sizeof(U32); |
| |
| assert(((size_t)ptr & 3) == 0); |
| |
| ms->hashLog3 = hashLog3; |
| memset(&ms->window, 0, sizeof(ms->window)); |
| ms->window.dictLimit = 1; /* start from 1, so that 1st position is valid */ |
| ms->window.lowLimit = 1; /* it ensures first and later CCtx usages compress the same */ |
| ms->window.nextSrc = ms->window.base + 1; /* see issue #1241 */ |
| ZSTD_invalidateMatchState(ms); |
| |
| /* opt parser space */ |
| if ((forWho == ZSTD_resetTarget_CCtx) && (cParams->strategy >= ZSTD_btopt)) { |
| DEBUGLOG(4, "reserving optimal parser space"); |
| ms->opt.litFreq = (unsigned*)ptr; |
| ms->opt.litLengthFreq = ms->opt.litFreq + (1<<Litbits); |
| ms->opt.matchLengthFreq = ms->opt.litLengthFreq + (MaxLL+1); |
| ms->opt.offCodeFreq = ms->opt.matchLengthFreq + (MaxML+1); |
| ptr = ms->opt.offCodeFreq + (MaxOff+1); |
| ms->opt.matchTable = (ZSTD_match_t*)ptr; |
| ptr = ms->opt.matchTable + ZSTD_OPT_NUM+1; |
| ms->opt.priceTable = (ZSTD_optimal_t*)ptr; |
| ptr = ms->opt.priceTable + ZSTD_OPT_NUM+1; |
| } |
| |
| /* table Space */ |
| DEBUGLOG(4, "reset table : %u", crp!=ZSTDcrp_noMemset); |
| assert(((size_t)ptr & 3) == 0); /* ensure ptr is properly aligned */ |
| if (crp!=ZSTDcrp_noMemset) memset(ptr, 0, tableSpace); /* reset tables only */ |
| ms->hashTable = (U32*)(ptr); |
| ms->chainTable = ms->hashTable + hSize; |
| ms->hashTable3 = ms->chainTable + chainSize; |
| ptr = ms->hashTable3 + h3Size; |
| |
| ms->cParams = *cParams; |
| |
| assert(((size_t)ptr & 3) == 0); |
| return ptr; |
| } |
| |
| /* ZSTD_indexTooCloseToMax() : |
| * minor optimization : prefer memset() rather than reduceIndex() |
| * which is measurably slow in some circumstances (reported for Visual Studio). |
| * Works when re-using a context for a lot of smallish inputs : |
| * if all inputs are smaller than ZSTD_INDEXOVERFLOW_MARGIN, |
| * memset() will be triggered before reduceIndex(). |
| */ |
| #define ZSTD_INDEXOVERFLOW_MARGIN (16 MB) |
| static int ZSTD_indexTooCloseToMax(ZSTD_window_t w) |
| { |
| return (size_t)(w.nextSrc - w.base) > (ZSTD_CURRENT_MAX - ZSTD_INDEXOVERFLOW_MARGIN); |
| } |
| |
| #define ZSTD_WORKSPACETOOLARGE_FACTOR 3 /* define "workspace is too large" as this number of times larger than needed */ |
| #define ZSTD_WORKSPACETOOLARGE_MAXDURATION 128 /* when workspace is continuously too large |
| * during at least this number of times, |
| * context's memory usage is considered wasteful, |
| * because it's sized to handle a worst case scenario which rarely happens. |
| * In which case, resize it down to free some memory */ |
| |
| /*! ZSTD_resetCCtx_internal() : |
| note : `params` are assumed fully validated at this stage */ |
| static size_t ZSTD_resetCCtx_internal(ZSTD_CCtx* zc, |
| ZSTD_CCtx_params params, |
| U64 const pledgedSrcSize, |
| ZSTD_compResetPolicy_e const crp, |
| ZSTD_buffered_policy_e const zbuff) |
| { |
| DEBUGLOG(4, "ZSTD_resetCCtx_internal: pledgedSrcSize=%u, wlog=%u", |
| (U32)pledgedSrcSize, params.cParams.windowLog); |
| assert(!ZSTD_isError(ZSTD_checkCParams(params.cParams))); |
| |
| if (crp == ZSTDcrp_continue) { |
| if (ZSTD_equivalentParams(zc->appliedParams, params, |
| zc->inBuffSize, |
| zc->seqStore.maxNbSeq, zc->seqStore.maxNbLit, |
| zbuff, pledgedSrcSize) ) { |
| DEBUGLOG(4, "ZSTD_equivalentParams()==1 -> consider continue mode"); |
| zc->workSpaceOversizedDuration += (zc->workSpaceOversizedDuration > 0); /* if it was too large, it still is */ |
| if (zc->workSpaceOversizedDuration <= ZSTD_WORKSPACETOOLARGE_MAXDURATION) { |
| DEBUGLOG(4, "continue mode confirmed (wLog1=%u, blockSize1=%zu)", |
| zc->appliedParams.cParams.windowLog, zc->blockSize); |
| if (ZSTD_indexTooCloseToMax(zc->blockState.matchState.window)) { |
| /* prefer a reset, faster than a rescale */ |
| ZSTD_reset_matchState(&zc->blockState.matchState, |
| zc->entropyWorkspace + HUF_WORKSPACE_SIZE_U32, |
| ¶ms.cParams, |
| crp, ZSTD_resetTarget_CCtx); |
| } |
| return ZSTD_continueCCtx(zc, params, pledgedSrcSize); |
| } } } |
| DEBUGLOG(4, "ZSTD_equivalentParams()==0 -> reset CCtx"); |
| |
| if (params.ldmParams.enableLdm) { |
| /* Adjust long distance matching parameters */ |
| ZSTD_ldm_adjustParameters(¶ms.ldmParams, ¶ms.cParams); |
| assert(params.ldmParams.hashLog >= params.ldmParams.bucketSizeLog); |
| assert(params.ldmParams.hashRateLog < 32); |
| zc->ldmState.hashPower = ZSTD_rollingHash_primePower(params.ldmParams.minMatchLength); |
| } |
| |
| { size_t const windowSize = MAX(1, (size_t)MIN(((U64)1 << params.cParams.windowLog), pledgedSrcSize)); |
| size_t const blockSize = MIN(ZSTD_BLOCKSIZE_MAX, windowSize); |
| U32 const divider = (params.cParams.minMatch==3) ? 3 : 4; |
| size_t const maxNbSeq = blockSize / divider; |
| size_t const tokenSpace = WILDCOPY_OVERLENGTH + blockSize + 11*maxNbSeq; |
| size_t const buffOutSize = (zbuff==ZSTDb_buffered) ? ZSTD_compressBound(blockSize)+1 : 0; |
| size_t const buffInSize = (zbuff==ZSTDb_buffered) ? windowSize + blockSize : 0; |
| size_t const matchStateSize = ZSTD_sizeof_matchState(¶ms.cParams, /* forCCtx */ 1); |
| size_t const maxNbLdmSeq = ZSTD_ldm_getMaxNbSeq(params.ldmParams, blockSize); |
| void* ptr; /* used to partition workSpace */ |
| |
| /* Check if workSpace is large enough, alloc a new one if needed */ |
| { size_t const entropySpace = HUF_WORKSPACE_SIZE; |
| size_t const blockStateSpace = 2 * sizeof(ZSTD_compressedBlockState_t); |
| size_t const bufferSpace = buffInSize + buffOutSize; |
| size_t const ldmSpace = ZSTD_ldm_getTableSize(params.ldmParams); |
| size_t const ldmSeqSpace = maxNbLdmSeq * sizeof(rawSeq); |
| |
| size_t const neededSpace = entropySpace + blockStateSpace + ldmSpace + |
| ldmSeqSpace + matchStateSize + tokenSpace + |
| bufferSpace; |
| |
| int const workSpaceTooSmall = zc->workSpaceSize < neededSpace; |
| int const workSpaceTooLarge = zc->workSpaceSize > ZSTD_WORKSPACETOOLARGE_FACTOR * neededSpace; |
| int const workSpaceWasteful = workSpaceTooLarge && (zc->workSpaceOversizedDuration > ZSTD_WORKSPACETOOLARGE_MAXDURATION); |
| zc->workSpaceOversizedDuration = workSpaceTooLarge ? zc->workSpaceOversizedDuration+1 : 0; |
| |
| DEBUGLOG(4, "Need %zuKB workspace, including %zuKB for match state, and %zuKB for buffers", |
| neededSpace>>10, matchStateSize>>10, bufferSpace>>10); |
| DEBUGLOG(4, "windowSize: %zu - blockSize: %zu", windowSize, blockSize); |
| |
| if (workSpaceTooSmall || workSpaceWasteful) { |
| DEBUGLOG(4, "Resize workSpaceSize from %zuKB to %zuKB", |
| zc->workSpaceSize >> 10, |
| neededSpace >> 10); |
| |
| RETURN_ERROR_IF(zc->staticSize, memory_allocation, "static cctx : no resize"); |
| |
| zc->workSpaceSize = 0; |
| ZSTD_free(zc->workSpace, zc->customMem); |
| zc->workSpace = ZSTD_malloc(neededSpace, zc->customMem); |
| RETURN_ERROR_IF(zc->workSpace == NULL, memory_allocation); |
| zc->workSpaceSize = neededSpace; |
| zc->workSpaceOversizedDuration = 0; |
| |
| /* Statically sized space. |
| * entropyWorkspace never moves, |
| * though prev/next block swap places */ |
| assert(((size_t)zc->workSpace & 3) == 0); /* ensure correct alignment */ |
| assert(zc->workSpaceSize >= 2 * sizeof(ZSTD_compressedBlockState_t)); |
| zc->blockState.prevCBlock = (ZSTD_compressedBlockState_t*)zc->workSpace; |
| zc->blockState.nextCBlock = zc->blockState.prevCBlock + 1; |
| ptr = zc->blockState.nextCBlock + 1; |
| zc->entropyWorkspace = (U32*)ptr; |
| } } |
| |
| /* init params */ |
| zc->appliedParams = params; |
| zc->blockState.matchState.cParams = params.cParams; |
| zc->pledgedSrcSizePlusOne = pledgedSrcSize+1; |
| zc->consumedSrcSize = 0; |
| zc->producedCSize = 0; |
| if (pledgedSrcSize == ZSTD_CONTENTSIZE_UNKNOWN) |
| zc->appliedParams.fParams.contentSizeFlag = 0; |
| DEBUGLOG(4, "pledged content size : %u ; flag : %u", |
| (unsigned)pledgedSrcSize, zc->appliedParams.fParams.contentSizeFlag); |
| zc->blockSize = blockSize; |
| |
| XXH64_reset(&zc->xxhState, 0); |
| zc->stage = ZSTDcs_init; |
| zc->dictID = 0; |
| |
| ZSTD_reset_compressedBlockState(zc->blockState.prevCBlock); |
| |
| ptr = ZSTD_reset_matchState(&zc->blockState.matchState, |
| zc->entropyWorkspace + HUF_WORKSPACE_SIZE_U32, |
| ¶ms.cParams, |
| crp, ZSTD_resetTarget_CCtx); |
| |
| /* ldm hash table */ |
| /* initialize bucketOffsets table later for pointer alignment */ |
| if (params.ldmParams.enableLdm) { |
| size_t const ldmHSize = ((size_t)1) << params.ldmParams.hashLog; |
| memset(ptr, 0, ldmHSize * sizeof(ldmEntry_t)); |
| assert(((size_t)ptr & 3) == 0); /* ensure ptr is properly aligned */ |
| zc->ldmState.hashTable = (ldmEntry_t*)ptr; |
| ptr = zc->ldmState.hashTable + ldmHSize; |
| zc->ldmSequences = (rawSeq*)ptr; |
| ptr = zc->ldmSequences + maxNbLdmSeq; |
| zc->maxNbLdmSequences = maxNbLdmSeq; |
| |
| memset(&zc->ldmState.window, 0, sizeof(zc->ldmState.window)); |
| } |
| assert(((size_t)ptr & 3) == 0); /* ensure ptr is properly aligned */ |
| |
| /* sequences storage */ |
| zc->seqStore.maxNbSeq = maxNbSeq; |
| zc->seqStore.sequencesStart = (seqDef*)ptr; |
| ptr = zc->seqStore.sequencesStart + maxNbSeq; |
| zc->seqStore.llCode = (BYTE*) ptr; |
| zc->seqStore.mlCode = zc->seqStore.llCode + maxNbSeq; |
| zc->seqStore.ofCode = zc->seqStore.mlCode + maxNbSeq; |
| zc->seqStore.litStart = zc->seqStore.ofCode + maxNbSeq; |
| /* ZSTD_wildcopy() is used to copy into the literals buffer, |
| * so we have to oversize the buffer by WILDCOPY_OVERLENGTH bytes. |
| */ |
| zc->seqStore.maxNbLit = blockSize; |
| ptr = zc->seqStore.litStart + blockSize + WILDCOPY_OVERLENGTH; |
| |
| /* ldm bucketOffsets table */ |
| if (params.ldmParams.enableLdm) { |
| size_t const ldmBucketSize = |
| ((size_t)1) << (params.ldmParams.hashLog - |
| params.ldmParams.bucketSizeLog); |
| memset(ptr, 0, ldmBucketSize); |
| zc->ldmState.bucketOffsets = (BYTE*)ptr; |
| ptr = zc->ldmState.bucketOffsets + ldmBucketSize; |
| ZSTD_window_clear(&zc->ldmState.window); |
| } |
| ZSTD_referenceExternalSequences(zc, NULL, 0); |
| |
| /* buffers */ |
| zc->inBuffSize = buffInSize; |
| zc->inBuff = (char*)ptr; |
| zc->outBuffSize = buffOutSize; |
| zc->outBuff = zc->inBuff + buffInSize; |
| |
| return 0; |
| } |
| } |
| |
| /* ZSTD_invalidateRepCodes() : |
| * ensures next compression will not use repcodes from previous block. |
| * Note : only works with regular variant; |
| * do not use with extDict variant ! */ |
| void ZSTD_invalidateRepCodes(ZSTD_CCtx* cctx) { |
| int i; |
| for (i=0; i<ZSTD_REP_NUM; i++) cctx->blockState.prevCBlock->rep[i] = 0; |
| assert(!ZSTD_window_hasExtDict(cctx->blockState.matchState.window)); |
| } |
| |
| /* These are the approximate sizes for each strategy past which copying the |
| * dictionary tables into the working context is faster than using them |
| * in-place. |
| */ |
| static const size_t attachDictSizeCutoffs[ZSTD_STRATEGY_MAX+1] = { |
| 8 KB, /* unused */ |
| 8 KB, /* ZSTD_fast */ |
| 16 KB, /* ZSTD_dfast */ |
| 32 KB, /* ZSTD_greedy */ |
| 32 KB, /* ZSTD_lazy */ |
| 32 KB, /* ZSTD_lazy2 */ |
| 32 KB, /* ZSTD_btlazy2 */ |
| 32 KB, /* ZSTD_btopt */ |
| 8 KB, /* ZSTD_btultra */ |
| 8 KB /* ZSTD_btultra2 */ |
| }; |
| |
| static int ZSTD_shouldAttachDict(const ZSTD_CDict* cdict, |
| ZSTD_CCtx_params params, |
| U64 pledgedSrcSize) |
| { |
| size_t cutoff = attachDictSizeCutoffs[cdict->matchState.cParams.strategy]; |
| return ( pledgedSrcSize <= cutoff |
| || pledgedSrcSize == ZSTD_CONTENTSIZE_UNKNOWN |
| || params.attachDictPref == ZSTD_dictForceAttach ) |
| && params.attachDictPref != ZSTD_dictForceCopy |
| && !params.forceWindow; /* dictMatchState isn't correctly |
| * handled in _enforceMaxDist */ |
| } |
| |
| static size_t |
| ZSTD_resetCCtx_byAttachingCDict(ZSTD_CCtx* cctx, |
| const ZSTD_CDict* cdict, |
| ZSTD_CCtx_params params, |
| U64 pledgedSrcSize, |
| ZSTD_buffered_policy_e zbuff) |
| { |
| { const ZSTD_compressionParameters* const cdict_cParams = &cdict->matchState.cParams; |
| unsigned const windowLog = params.cParams.windowLog; |
| assert(windowLog != 0); |
| /* Resize working context table params for input only, since the dict |
| * has its own tables. */ |
| params.cParams = ZSTD_adjustCParams_internal(*cdict_cParams, pledgedSrcSize, 0); |
| params.cParams.windowLog = windowLog; |
| ZSTD_resetCCtx_internal(cctx, params, pledgedSrcSize, |
| ZSTDcrp_continue, zbuff); |
| assert(cctx->appliedParams.cParams.strategy == cdict_cParams->strategy); |
| } |
| |
| { const U32 cdictEnd = (U32)( cdict->matchState.window.nextSrc |
| - cdict->matchState.window.base); |
| const U32 cdictLen = cdictEnd - cdict->matchState.window.dictLimit; |
| if (cdictLen == 0) { |
| /* don't even attach dictionaries with no contents */ |
| DEBUGLOG(4, "skipping attaching empty dictionary"); |
| } else { |
| DEBUGLOG(4, "attaching dictionary into context"); |
| cctx->blockState.matchState.dictMatchState = &cdict->matchState; |
| |
| /* prep working match state so dict matches never have negative indices |
| * when they are translated to the working context's index space. */ |
| if (cctx->blockState.matchState.window.dictLimit < cdictEnd) { |
| cctx->blockState.matchState.window.nextSrc = |
| cctx->blockState.matchState.window.base + cdictEnd; |
| ZSTD_window_clear(&cctx->blockState.matchState.window); |
| } |
| /* loadedDictEnd is expressed within the referential of the active context */ |
| cctx->blockState.matchState.loadedDictEnd = cctx->blockState.matchState.window.dictLimit; |
| } } |
| |
| cctx->dictID = cdict->dictID; |
| |
| /* copy block state */ |
| memcpy(cctx->blockState.prevCBlock, &cdict->cBlockState, sizeof(cdict->cBlockState)); |
| |
| return 0; |
| } |
| |
| static size_t ZSTD_resetCCtx_byCopyingCDict(ZSTD_CCtx* cctx, |
| const ZSTD_CDict* cdict, |
| ZSTD_CCtx_params params, |
| U64 pledgedSrcSize, |
| ZSTD_buffered_policy_e zbuff) |
| { |
| const ZSTD_compressionParameters *cdict_cParams = &cdict->matchState.cParams; |
| |
| DEBUGLOG(4, "copying dictionary into context"); |
| |
| { unsigned const windowLog = params.cParams.windowLog; |
| assert(windowLog != 0); |
| /* Copy only compression parameters related to tables. */ |
| params.cParams = *cdict_cParams; |
| params.cParams.windowLog = windowLog; |
| ZSTD_resetCCtx_internal(cctx, params, pledgedSrcSize, |
| ZSTDcrp_noMemset, zbuff); |
| assert(cctx->appliedParams.cParams.strategy == cdict_cParams->strategy); |
| assert(cctx->appliedParams.cParams.hashLog == cdict_cParams->hashLog); |
| assert(cctx->appliedParams.cParams.chainLog == cdict_cParams->chainLog); |
| } |
| |
| /* copy tables */ |
| { size_t const chainSize = (cdict_cParams->strategy == ZSTD_fast) ? 0 : ((size_t)1 << cdict_cParams->chainLog); |
| size_t const hSize = (size_t)1 << cdict_cParams->hashLog; |
| size_t const tableSpace = (chainSize + hSize) * sizeof(U32); |
| assert((U32*)cctx->blockState.matchState.chainTable == (U32*)cctx->blockState.matchState.hashTable + hSize); /* chainTable must follow hashTable */ |
| assert((U32*)cctx->blockState.matchState.hashTable3 == (U32*)cctx->blockState.matchState.chainTable + chainSize); |
| assert((U32*)cdict->matchState.chainTable == (U32*)cdict->matchState.hashTable + hSize); /* chainTable must follow hashTable */ |
| assert((U32*)cdict->matchState.hashTable3 == (U32*)cdict->matchState.chainTable + chainSize); |
| memcpy(cctx->blockState.matchState.hashTable, cdict->matchState.hashTable, tableSpace); /* presumes all tables follow each other */ |
| } |
| |
| /* Zero the hashTable3, since the cdict never fills it */ |
| { size_t const h3Size = (size_t)1 << cctx->blockState.matchState.hashLog3; |
| assert(cdict->matchState.hashLog3 == 0); |
| memset(cctx->blockState.matchState.hashTable3, 0, h3Size * sizeof(U32)); |
| } |
| |
| /* copy dictionary offsets */ |
| { ZSTD_matchState_t const* srcMatchState = &cdict->matchState; |
| ZSTD_matchState_t* dstMatchState = &cctx->blockState.matchState; |
| dstMatchState->window = srcMatchState->window; |
| dstMatchState->nextToUpdate = srcMatchState->nextToUpdate; |
| dstMatchState->loadedDictEnd= srcMatchState->loadedDictEnd; |
| } |
| |
| cctx->dictID = cdict->dictID; |
| |
| /* copy block state */ |
| memcpy(cctx->blockState.prevCBlock, &cdict->cBlockState, sizeof(cdict->cBlockState)); |
| |
| return 0; |
| } |
| |
| /* We have a choice between copying the dictionary context into the working |
| * context, or referencing the dictionary context from the working context |
| * in-place. We decide here which strategy to use. */ |
| static size_t ZSTD_resetCCtx_usingCDict(ZSTD_CCtx* cctx, |
| const ZSTD_CDict* cdict, |
| ZSTD_CCtx_params params, |
| U64 pledgedSrcSize, |
| ZSTD_buffered_policy_e zbuff) |
| { |
| |
| DEBUGLOG(4, "ZSTD_resetCCtx_usingCDict (pledgedSrcSize=%u)", |
| (unsigned)pledgedSrcSize); |
| |
| if (ZSTD_shouldAttachDict(cdict, params, pledgedSrcSize)) { |
| return ZSTD_resetCCtx_byAttachingCDict( |
| cctx, cdict, params, pledgedSrcSize, zbuff); |
| } else { |
| return ZSTD_resetCCtx_byCopyingCDict( |
| cctx, cdict, params, pledgedSrcSize, zbuff); |
| } |
| } |
| |
| /*! ZSTD_copyCCtx_internal() : |
| * Duplicate an existing context `srcCCtx` into another one `dstCCtx`. |
| * Only works during stage ZSTDcs_init (i.e. after creation, but before first call to ZSTD_compressContinue()). |
| * The "context", in this case, refers to the hash and chain tables, |
| * entropy tables, and dictionary references. |
| * `windowLog` value is enforced if != 0, otherwise value is copied from srcCCtx. |
| * @return : 0, or an error code */ |
| static size_t ZSTD_copyCCtx_internal(ZSTD_CCtx* dstCCtx, |
| const ZSTD_CCtx* srcCCtx, |
| ZSTD_frameParameters fParams, |
| U64 pledgedSrcSize, |
| ZSTD_buffered_policy_e zbuff) |
| { |
| DEBUGLOG(5, "ZSTD_copyCCtx_internal"); |
| RETURN_ERROR_IF(srcCCtx->stage!=ZSTDcs_init, stage_wrong); |
| |
| memcpy(&dstCCtx->customMem, &srcCCtx->customMem, sizeof(ZSTD_customMem)); |
| { ZSTD_CCtx_params params = dstCCtx->requestedParams; |
| /* Copy only compression parameters related to tables. */ |
| params.cParams = srcCCtx->appliedParams.cParams; |
| params.fParams = fParams; |
| ZSTD_resetCCtx_internal(dstCCtx, params, pledgedSrcSize, |
| ZSTDcrp_noMemset, zbuff); |
| assert(dstCCtx->appliedParams.cParams.windowLog == srcCCtx->appliedParams.cParams.windowLog); |
| assert(dstCCtx->appliedParams.cParams.strategy == srcCCtx->appliedParams.cParams.strategy); |
| assert(dstCCtx->appliedParams.cParams.hashLog == srcCCtx->appliedParams.cParams.hashLog); |
| assert(dstCCtx->appliedParams.cParams.chainLog == srcCCtx->appliedParams.cParams.chainLog); |
| assert(dstCCtx->blockState.matchState.hashLog3 == srcCCtx->blockState.matchState.hashLog3); |
| } |
| |
| /* copy tables */ |
| { size_t const chainSize = (srcCCtx->appliedParams.cParams.strategy == ZSTD_fast) ? 0 : ((size_t)1 << srcCCtx->appliedParams.cParams.chainLog); |
| size_t const hSize = (size_t)1 << srcCCtx->appliedParams.cParams.hashLog; |
| size_t const h3Size = (size_t)1 << srcCCtx->blockState.matchState.hashLog3; |
| size_t const tableSpace = (chainSize + hSize + h3Size) * sizeof(U32); |
| assert((U32*)dstCCtx->blockState.matchState.chainTable == (U32*)dstCCtx->blockState.matchState.hashTable + hSize); /* chainTable must follow hashTable */ |
| assert((U32*)dstCCtx->blockState.matchState.hashTable3 == (U32*)dstCCtx->blockState.matchState.chainTable + chainSize); |
| memcpy(dstCCtx->blockState.matchState.hashTable, srcCCtx->blockState.matchState.hashTable, tableSpace); /* presumes all tables follow each other */ |
| } |
| |
| /* copy dictionary offsets */ |
| { |
| const ZSTD_matchState_t* srcMatchState = &srcCCtx->blockState.matchState; |
| ZSTD_matchState_t* dstMatchState = &dstCCtx->blockState.matchState; |
| dstMatchState->window = srcMatchState->window; |
| dstMatchState->nextToUpdate = srcMatchState->nextToUpdate; |
| dstMatchState->loadedDictEnd= srcMatchState->loadedDictEnd; |
| } |
| dstCCtx->dictID = srcCCtx->dictID; |
| |
| /* copy block state */ |
| memcpy(dstCCtx->blockState.prevCBlock, srcCCtx->blockState.prevCBlock, sizeof(*srcCCtx->blockState.prevCBlock)); |
| |
| return 0; |
| } |
| |
| /*! ZSTD_copyCCtx() : |
| * Duplicate an existing context `srcCCtx` into another one `dstCCtx`. |
| * Only works during stage ZSTDcs_init (i.e. after creation, but before first call to ZSTD_compressContinue()). |
| * pledgedSrcSize==0 means "unknown". |
| * @return : 0, or an error code */ |
| size_t ZSTD_copyCCtx(ZSTD_CCtx* dstCCtx, const ZSTD_CCtx* srcCCtx, unsigned long long pledgedSrcSize) |
| { |
| ZSTD_frameParameters fParams = { 1 /*content*/, 0 /*checksum*/, 0 /*noDictID*/ }; |
| ZSTD_buffered_policy_e const zbuff = (ZSTD_buffered_policy_e)(srcCCtx->inBuffSize>0); |
| ZSTD_STATIC_ASSERT((U32)ZSTDb_buffered==1); |
| if (pledgedSrcSize==0) pledgedSrcSize = ZSTD_CONTENTSIZE_UNKNOWN; |
| fParams.contentSizeFlag = (pledgedSrcSize != ZSTD_CONTENTSIZE_UNKNOWN); |
| |
| return ZSTD_copyCCtx_internal(dstCCtx, srcCCtx, |
| fParams, pledgedSrcSize, |
| zbuff); |
| } |
| |
| |
| #define ZSTD_ROWSIZE 16 |
| /*! ZSTD_reduceTable() : |
| * reduce table indexes by `reducerValue`, or squash to zero. |
| * PreserveMark preserves "unsorted mark" for btlazy2 strategy. |
| * It must be set to a clear 0/1 value, to remove branch during inlining. |
| * Presume table size is a multiple of ZSTD_ROWSIZE |
| * to help auto-vectorization */ |
| FORCE_INLINE_TEMPLATE void |
| ZSTD_reduceTable_internal (U32* const table, U32 const size, U32 const reducerValue, int const preserveMark) |
| { |
| int const nbRows = (int)size / ZSTD_ROWSIZE; |
| int cellNb = 0; |
| int rowNb; |
| assert((size & (ZSTD_ROWSIZE-1)) == 0); /* multiple of ZSTD_ROWSIZE */ |
| assert(size < (1U<<31)); /* can be casted to int */ |
| for (rowNb=0 ; rowNb < nbRows ; rowNb++) { |
| int column; |
| for (column=0; column<ZSTD_ROWSIZE; column++) { |
| if (preserveMark) { |
| U32 const adder = (table[cellNb] == ZSTD_DUBT_UNSORTED_MARK) ? reducerValue : 0; |
| table[cellNb] += adder; |
| } |
| if (table[cellNb] < reducerValue) table[cellNb] = 0; |
| else table[cellNb] -= reducerValue; |
| cellNb++; |
| } } |
| } |
| |
| static void ZSTD_reduceTable(U32* const table, U32 const size, U32 const reducerValue) |
| { |
| ZSTD_reduceTable_internal(table, size, reducerValue, 0); |
| } |
| |
| static void ZSTD_reduceTable_btlazy2(U32* const table, U32 const size, U32 const reducerValue) |
| { |
| ZSTD_reduceTable_internal(table, size, reducerValue, 1); |
| } |
| |
| /*! ZSTD_reduceIndex() : |
| * rescale all indexes to avoid future overflow (indexes are U32) */ |
| static void ZSTD_reduceIndex (ZSTD_matchState_t* ms, ZSTD_CCtx_params const* params, const U32 reducerValue) |
| { |
| { U32 const hSize = (U32)1 << params->cParams.hashLog; |
| ZSTD_reduceTable(ms->hashTable, hSize, reducerValue); |
| } |
| |
| if (params->cParams.strategy != ZSTD_fast) { |
| U32 const chainSize = (U32)1 << params->cParams.chainLog; |
| if (params->cParams.strategy == ZSTD_btlazy2) |
| ZSTD_reduceTable_btlazy2(ms->chainTable, chainSize, reducerValue); |
| else |
| ZSTD_reduceTable(ms->chainTable, chainSize, reducerValue); |
| } |
| |
| if (ms->hashLog3) { |
| U32 const h3Size = (U32)1 << ms->hashLog3; |
| ZSTD_reduceTable(ms->hashTable3, h3Size, reducerValue); |
| } |
| } |
| |
| |
| /*-******************************************************* |
| * Block entropic compression |
| *********************************************************/ |
| |
| /* See doc/zstd_compression_format.md for detailed format description */ |
| |
| static size_t ZSTD_noCompressBlock (void* dst, size_t dstCapacity, const void* src, size_t srcSize, U32 lastBlock) |
| { |
| U32 const cBlockHeader24 = lastBlock + (((U32)bt_raw)<<1) + (U32)(srcSize << 3); |
| RETURN_ERROR_IF(srcSize + ZSTD_blockHeaderSize > dstCapacity, |
| dstSize_tooSmall); |
| MEM_writeLE24(dst, cBlockHeader24); |
| memcpy((BYTE*)dst + ZSTD_blockHeaderSize, src, srcSize); |
| return ZSTD_blockHeaderSize + srcSize; |
| } |
| |
| static size_t ZSTD_noCompressLiterals (void* dst, size_t dstCapacity, const void* src, size_t srcSize) |
| { |
| BYTE* const ostart = (BYTE* const)dst; |
| U32 const flSize = 1 + (srcSize>31) + (srcSize>4095); |
| |
| RETURN_ERROR_IF(srcSize + flSize > dstCapacity, dstSize_tooSmall); |
| |
| switch(flSize) |
| { |
| case 1: /* 2 - 1 - 5 */ |
| ostart[0] = (BYTE)((U32)set_basic + (srcSize<<3)); |
| break; |
| case 2: /* 2 - 2 - 12 */ |
| MEM_writeLE16(ostart, (U16)((U32)set_basic + (1<<2) + (srcSize<<4))); |
| break; |
| case 3: /* 2 - 2 - 20 */ |
| MEM_writeLE32(ostart, (U32)((U32)set_basic + (3<<2) + (srcSize<<4))); |
| break; |
| default: /* not necessary : flSize is {1,2,3} */ |
| assert(0); |
| } |
| |
| memcpy(ostart + flSize, src, srcSize); |
| return srcSize + flSize; |
| } |
| |
| static size_t ZSTD_compressRleLiteralsBlock (void* dst, size_t dstCapacity, const void* src, size_t srcSize) |
| { |
| BYTE* const ostart = (BYTE* const)dst; |
| U32 const flSize = 1 + (srcSize>31) + (srcSize>4095); |
| |
| (void)dstCapacity; /* dstCapacity already guaranteed to be >=4, hence large enough */ |
| |
| switch(flSize) |
| { |
| case 1: /* 2 - 1 - 5 */ |
| ostart[0] = (BYTE)((U32)set_rle + (srcSize<<3)); |
| break; |
| case 2: /* 2 - 2 - 12 */ |
| MEM_writeLE16(ostart, (U16)((U32)set_rle + (1<<2) + (srcSize<<4))); |
| break; |
| case 3: /* 2 - 2 - 20 */ |
| MEM_writeLE32(ostart, (U32)((U32)set_rle + (3<<2) + (srcSize<<4))); |
| break; |
| default: /* not necessary : flSize is {1,2,3} */ |
| assert(0); |
| } |
| |
| ostart[flSize] = *(const BYTE*)src; |
| return flSize+1; |
| } |
| |
| |
| /* ZSTD_minGain() : |
| * minimum compression required |
| * to generate a compress block or a compressed literals section. |
| * note : use same formula for both situations */ |
| static size_t ZSTD_minGain(size_t srcSize, ZSTD_strategy strat) |
| { |
| U32 const minlog = (strat>=ZSTD_btultra) ? (U32)(strat) - 1 : 6; |
| ZSTD_STATIC_ASSERT(ZSTD_btultra == 8); |
| assert(ZSTD_cParam_withinBounds(ZSTD_c_strategy, strat)); |
| return (srcSize >> minlog) + 2; |
| } |
| |
| static size_t ZSTD_compressLiterals (ZSTD_hufCTables_t const* prevHuf, |
| ZSTD_hufCTables_t* nextHuf, |
| ZSTD_strategy strategy, int disableLiteralCompression, |
| void* dst, size_t dstCapacity, |
| const void* src, size_t srcSize, |
| void* workspace, size_t wkspSize, |
| const int bmi2) |
| { |
| size_t const minGain = ZSTD_minGain(srcSize, strategy); |
| size_t const lhSize = 3 + (srcSize >= 1 KB) + (srcSize >= 16 KB); |
| BYTE* const ostart = (BYTE*)dst; |
| U32 singleStream = srcSize < 256; |
| symbolEncodingType_e hType = set_compressed; |
| size_t cLitSize; |
| |
| DEBUGLOG(5,"ZSTD_compressLiterals (disableLiteralCompression=%i)", |
| disableLiteralCompression); |
| |
| /* Prepare nextEntropy assuming reusing the existing table */ |
| memcpy(nextHuf, prevHuf, sizeof(*prevHuf)); |
| |
| if (disableLiteralCompression) |
| return ZSTD_noCompressLiterals(dst, dstCapacity, src, srcSize); |
| |
| /* small ? don't even attempt compression (speed opt) */ |
| # define COMPRESS_LITERALS_SIZE_MIN 63 |
| { size_t const minLitSize = (prevHuf->repeatMode == HUF_repeat_valid) ? 6 : COMPRESS_LITERALS_SIZE_MIN; |
| if (srcSize <= minLitSize) return ZSTD_noCompressLiterals(dst, dstCapacity, src, srcSize); |
| } |
| |
| RETURN_ERROR_IF(dstCapacity < lhSize+1, dstSize_tooSmall, "not enough space for compression"); |
| { HUF_repeat repeat = prevHuf->repeatMode; |
| int const preferRepeat = strategy < ZSTD_lazy ? srcSize <= 1024 : 0; |
| if (repeat == HUF_repeat_valid && lhSize == 3) singleStream = 1; |
| cLitSize = singleStream ? HUF_compress1X_repeat(ostart+lhSize, dstCapacity-lhSize, src, srcSize, 255, 11, |
| workspace, wkspSize, (HUF_CElt*)nextHuf->CTable, &repeat, preferRepeat, bmi2) |
| : HUF_compress4X_repeat(ostart+lhSize, dstCapacity-lhSize, src, srcSize, 255, 11, |
| workspace, wkspSize, (HUF_CElt*)nextHuf->CTable, &repeat, preferRepeat, bmi2); |
| if (repeat != HUF_repeat_none) { |
| /* reused the existing table */ |
| hType = set_repeat; |
| } |
| } |
| |
| if ((cLitSize==0) | (cLitSize >= srcSize - minGain) | ERR_isError(cLitSize)) { |
| memcpy(nextHuf, prevHuf, sizeof(*prevHuf)); |
| return ZSTD_noCompressLiterals(dst, dstCapacity, src, srcSize); |
| } |
| if (cLitSize==1) { |
| memcpy(nextHuf, prevHuf, sizeof(*prevHuf)); |
| return ZSTD_compressRleLiteralsBlock(dst, dstCapacity, src, srcSize); |
| } |
| |
| if (hType == set_compressed) { |
| /* using a newly constructed table */ |
| nextHuf->repeatMode = HUF_repeat_check; |
| } |
| |
| /* Build header */ |
| switch(lhSize) |
| { |
| case 3: /* 2 - 2 - 10 - 10 */ |
| { U32 const lhc = hType + ((!singleStream) << 2) + ((U32)srcSize<<4) + ((U32)cLitSize<<14); |
| MEM_writeLE24(ostart, lhc); |
| break; |
| } |
| case 4: /* 2 - 2 - 14 - 14 */ |
| { U32 const lhc = hType + (2 << 2) + ((U32)srcSize<<4) + ((U32)cLitSize<<18); |
| MEM_writeLE32(ostart, lhc); |
| break; |
| } |
| case 5: /* 2 - 2 - 18 - 18 */ |
| { U32 const lhc = hType + (3 << 2) + ((U32)srcSize<<4) + ((U32)cLitSize<<22); |
| MEM_writeLE32(ostart, lhc); |
| ostart[4] = (BYTE)(cLitSize >> 10); |
| break; |
| } |
| default: /* not possible : lhSize is {3,4,5} */ |
| assert(0); |
| } |
| return lhSize+cLitSize; |
| } |
| |
| |
| void ZSTD_seqToCodes(const seqStore_t* seqStorePtr) |
| { |
| const seqDef* const sequences = seqStorePtr->sequencesStart; |
| BYTE* const llCodeTable = seqStorePtr->llCode; |
| BYTE* const ofCodeTable = seqStorePtr->ofCode; |
| BYTE* const mlCodeTable = seqStorePtr->mlCode; |
| U32 const nbSeq = (U32)(seqStorePtr->sequences - seqStorePtr->sequencesStart); |
| U32 u; |
| assert(nbSeq <= seqStorePtr->maxNbSeq); |
| for (u=0; u<nbSeq; u++) { |
| U32 const llv = sequences[u].litLength; |
| U32 const mlv = sequences[u].matchLength; |
| llCodeTable[u] = (BYTE)ZSTD_LLcode(llv); |
| ofCodeTable[u] = (BYTE)ZSTD_highbit32(sequences[u].offset); |
| mlCodeTable[u] = (BYTE)ZSTD_MLcode(mlv); |
| } |
| if (seqStorePtr->longLengthID==1) |
| llCodeTable[seqStorePtr->longLengthPos] = MaxLL; |
| if (seqStorePtr->longLengthID==2) |
| mlCodeTable[seqStorePtr->longLengthPos] = MaxML; |
| } |
| |
| |
| /** |
| * -log2(x / 256) lookup table for x in [0, 256). |
| * If x == 0: Return 0 |
| * Else: Return floor(-log2(x / 256) * 256) |
| */ |
| static unsigned const kInverseProbabilityLog256[256] = { |
| 0, 2048, 1792, 1642, 1536, 1453, 1386, 1329, 1280, 1236, 1197, 1162, |
| 1130, 1100, 1073, 1047, 1024, 1001, 980, 960, 941, 923, 906, 889, |
| 874, 859, 844, 830, 817, 804, 791, 779, 768, 756, 745, 734, |
| 724, 714, 704, 694, 685, 676, 667, 658, 650, 642, 633, 626, |
| 618, 610, 603, 595, 588, 581, 574, 567, 561, 554, 548, 542, |
| 535, 529, 523, 517, 512, 506, 500, 495, 489, 484, 478, 473, |
| 468, 463, 458, 453, 448, 443, 438, 434, 429, 424, 420, 415, |
| 411, 407, 402, 398, 394, 390, 386, 382, 377, 373, 370, 366, |
| 362, 358, 354, 350, 347, 343, 339, 336, 332, 329, 325, 322, |
| 318, 315, 311, 308, 305, 302, 298, 295, 292, 289, 286, 282, |
| 279, 276, 273, 270, 267, 264, 261, 258, 256, 253, 250, 247, |
| 244, 241, 239, 236, 233, 230, 228, 225, 222, 220, 217, 215, |
| 212, 209, 207, 204, 202, 199, 197, 194, 192, 190, 187, 185, |
| 182, 180, 178, 175, 173, 171, 168, 166, 164, 162, 159, 157, |
| 155, 153, 151, 149, 146, 144, 142, 140, 138, 136, 134, 132, |
| 130, 128, 126, 123, 121, 119, 117, 115, 114, 112, 110, 108, |
| 106, 104, 102, 100, 98, 96, 94, 93, 91, 89, 87, 85, |
| 83, 82, 80, 78, 76, 74, 73, 71, 69, 67, 66, 64, |
| 62, 61, 59, 57, 55, 54, 52, 50, 49, 47, 46, 44, |
| 42, 41, 39, 37, 36, 34, 33, 31, 30, 28, 26, 25, |
| 23, 22, 20, 19, 17, 16, 14, 13, 11, 10, 8, 7, |
| 5, 4, 2, 1, |
| }; |
| |
| |
| /** |
| * Returns the cost in bits of encoding the distribution described by count |
| * using the entropy bound. |
| */ |
| static size_t ZSTD_entropyCost(unsigned const* count, unsigned const max, size_t const total) |
| { |
| unsigned cost = 0; |
| unsigned s; |
| for (s = 0; s <= max; ++s) { |
| unsigned norm = (unsigned)((256 * count[s]) / total); |
| if (count[s] != 0 && norm == 0) |
| norm = 1; |
| assert(count[s] < total); |
| cost += count[s] * kInverseProbabilityLog256[norm]; |
| } |
| return cost >> 8; |
| } |
| |
| |
| /** |
| * Returns the cost in bits of encoding the distribution in count using the |
| * table described by norm. The max symbol support by norm is assumed >= max. |
| * norm must be valid for every symbol with non-zero probability in count. |
| */ |
| static size_t ZSTD_crossEntropyCost(short const* norm, unsigned accuracyLog, |
| unsigned const* count, unsigned const max) |
| { |
| unsigned const shift = 8 - accuracyLog; |
| size_t cost = 0; |
| unsigned s; |
| assert(accuracyLog <= 8); |
| for (s = 0; s <= max; ++s) { |
| unsigned const normAcc = norm[s] != -1 ? norm[s] : 1; |
| unsigned const norm256 = normAcc << shift; |
| assert(norm256 > 0); |
| assert(norm256 < 256); |
| cost += count[s] * kInverseProbabilityLog256[norm256]; |
| } |
| return cost >> 8; |
| } |
| |
| |
| static unsigned ZSTD_getFSEMaxSymbolValue(FSE_CTable const* ctable) { |
| void const* ptr = ctable; |
| U16 const* u16ptr = (U16 const*)ptr; |
| U32 const maxSymbolValue = MEM_read16(u16ptr + 1); |
| return maxSymbolValue; |
| } |
| |
| |
| /** |
| * Returns the cost in bits of encoding the distribution in count using ctable. |
| * Returns an error if ctable cannot represent all the symbols in count. |
| */ |
| static size_t ZSTD_fseBitCost( |
| FSE_CTable const* ctable, |
| unsigned const* count, |
| unsigned const max) |
| { |
| unsigned const kAccuracyLog = 8; |
| size_t cost = 0; |
| unsigned s; |
| FSE_CState_t cstate; |
| FSE_initCState(&cstate, ctable); |
| RETURN_ERROR_IF(ZSTD_getFSEMaxSymbolValue(ctable) < max, GENERIC, |
| "Repeat FSE_CTable has maxSymbolValue %u < %u", |
| ZSTD_getFSEMaxSymbolValue(ctable), max); |
| for (s = 0; s <= max; ++s) { |
| unsigned const tableLog = cstate.stateLog; |
| unsigned const badCost = (tableLog + 1) << kAccuracyLog; |
| unsigned const bitCost = FSE_bitCost(cstate.symbolTT, tableLog, s, kAccuracyLog); |
| if (count[s] == 0) |
| continue; |
| RETURN_ERROR_IF(bitCost >= badCost, GENERIC, |
| "Repeat FSE_CTable has Prob[%u] == 0", s); |
| cost += count[s] * bitCost; |
| } |
| return cost >> kAccuracyLog; |
| } |
| |
| /** |
| * Returns the cost in bytes of encoding the normalized count header. |
| * Returns an error if any of the helper functions return an error. |
| */ |
| static size_t ZSTD_NCountCost(unsigned const* count, unsigned const max, |
| size_t const nbSeq, unsigned const FSELog) |
| { |
| BYTE wksp[FSE_NCOUNTBOUND]; |
| S16 norm[MaxSeq + 1]; |
| const U32 tableLog = FSE_optimalTableLog(FSELog, nbSeq, max); |
| FORWARD_IF_ERROR(FSE_normalizeCount(norm, tableLog, count, nbSeq, max)); |
| return FSE_writeNCount(wksp, sizeof(wksp), norm, max, tableLog); |
| } |
| |
| |
| typedef enum { |
| ZSTD_defaultDisallowed = 0, |
| ZSTD_defaultAllowed = 1 |
| } ZSTD_defaultPolicy_e; |
| |
| MEM_STATIC symbolEncodingType_e |
| ZSTD_selectEncodingType( |
| FSE_repeat* repeatMode, unsigned const* count, unsigned const max, |
| size_t const mostFrequent, size_t nbSeq, unsigned const FSELog, |
| FSE_CTable const* prevCTable, |
| short const* defaultNorm, U32 defaultNormLog, |
| ZSTD_defaultPolicy_e const isDefaultAllowed, |
| ZSTD_strategy const strategy) |
| { |
| ZSTD_STATIC_ASSERT(ZSTD_defaultDisallowed == 0 && ZSTD_defaultAllowed != 0); |
| if (mostFrequent == nbSeq) { |
| *repeatMode = FSE_repeat_none; |
| if (isDefaultAllowed && nbSeq <= 2) { |
| /* Prefer set_basic over set_rle when there are 2 or less symbols, |
| * since RLE uses 1 byte, but set_basic uses 5-6 bits per symbol. |
| * If basic encoding isn't possible, always choose RLE. |
| */ |
| DEBUGLOG(5, "Selected set_basic"); |
| return set_basic; |
| } |
| DEBUGLOG(5, "Selected set_rle"); |
| return set_rle; |
| } |
| if (strategy < ZSTD_lazy) { |
| if (isDefaultAllowed) { |
| size_t const staticFse_nbSeq_max = 1000; |
| size_t const mult = 10 - strategy; |
| size_t const baseLog = 3; |
| size_t const dynamicFse_nbSeq_min = (((size_t)1 << defaultNormLog) * mult) >> baseLog; /* 28-36 for offset, 56-72 for lengths */ |
| assert(defaultNormLog >= 5 && defaultNormLog <= 6); /* xx_DEFAULTNORMLOG */ |
| assert(mult <= 9 && mult >= 7); |
| if ( (*repeatMode == FSE_repeat_valid) |
| && (nbSeq < staticFse_nbSeq_max) ) { |
| DEBUGLOG(5, "Selected set_repeat"); |
| return set_repeat; |
| } |
| if ( (nbSeq < dynamicFse_nbSeq_min) |
| || (mostFrequent < (nbSeq >> (defaultNormLog-1))) ) { |
| DEBUGLOG(5, "Selected set_basic"); |
| /* The format allows default tables to be repeated, but it isn't useful. |
| * When using simple heuristics to select encoding type, we don't want |
| * to confuse these tables with dictionaries. When running more careful |
| * analysis, we don't need to waste time checking both repeating tables |
| * and default tables. |
| */ |
| *repeatMode = FSE_repeat_none; |
| return set_basic; |
| } |
| } |
| } else { |
| size_t const basicCost = isDefaultAllowed ? ZSTD_crossEntropyCost(defaultNorm, defaultNormLog, count, max) : ERROR(GENERIC); |
| size_t const repeatCost = *repeatMode != FSE_repeat_none ? ZSTD_fseBitCost(prevCTable, count, max) : ERROR(GENERIC); |
| size_t const NCountCost = ZSTD_NCountCost(count, max, nbSeq, FSELog); |
| size_t const compressedCost = (NCountCost << 3) + ZSTD_entropyCost(count, max, nbSeq); |
| |
| if (isDefaultAllowed) { |
| assert(!ZSTD_isError(basicCost)); |
| assert(!(*repeatMode == FSE_repeat_valid && ZSTD_isError(repeatCost))); |
| } |
| assert(!ZSTD_isError(NCountCost)); |
| assert(compressedCost < ERROR(maxCode)); |
| DEBUGLOG(5, "Estimated bit costs: basic=%u\trepeat=%u\tcompressed=%u", |
| (unsigned)basicCost, (unsigned)repeatCost, (unsigned)compressedCost); |
| if (basicCost <= repeatCost && basicCost <= compressedCost) { |
| DEBUGLOG(5, "Selected set_basic"); |
| assert(isDefaultAllowed); |
| *repeatMode = FSE_repeat_none; |
| return set_basic; |
| } |
| if (repeatCost <= compressedCost) { |
| DEBUGLOG(5, "Selected set_repeat"); |
| assert(!ZSTD_isError(repeatCost)); |
| return set_repeat; |
| } |
| assert(compressedCost < basicCost && compressedCost < repeatCost); |
| } |
| DEBUGLOG(5, "Selected set_compressed"); |
| *repeatMode = FSE_repeat_check; |
| return set_compressed; |
| } |
| |
| MEM_STATIC size_t |
| ZSTD_buildCTable(void* dst, size_t dstCapacity, |
| FSE_CTable* nextCTable, U32 FSELog, symbolEncodingType_e type, |
| unsigned* count, U32 max, |
| const BYTE* codeTable, size_t nbSeq, |
| const S16* defaultNorm, U32 defaultNormLog, U32 defaultMax, |
| const FSE_CTable* prevCTable, size_t prevCTableSize, |
| void* workspace, size_t workspaceSize) |
| { |
| BYTE* op = (BYTE*)dst; |
| const BYTE* const oend = op + dstCapacity; |
| DEBUGLOG(6, "ZSTD_buildCTable (dstCapacity=%u)", (unsigned)dstCapacity); |
| |
| switch (type) { |
| case set_rle: |
| FORWARD_IF_ERROR(FSE_buildCTable_rle(nextCTable, (BYTE)max)); |
| RETURN_ERROR_IF(dstCapacity==0, dstSize_tooSmall); |
| *op = codeTable[0]; |
| return 1; |
| case set_repeat: |
| memcpy(nextCTable, prevCTable, prevCTableSize); |
| return 0; |
| case set_basic: |
| FORWARD_IF_ERROR(FSE_buildCTable_wksp(nextCTable, defaultNorm, defaultMax, defaultNormLog, workspace, workspaceSize)); /* note : could be pre-calculated */ |
| return 0; |
| case set_compressed: { |
| S16 norm[MaxSeq + 1]; |
| size_t nbSeq_1 = nbSeq; |
| const U32 tableLog = FSE_optimalTableLog(FSELog, nbSeq, max); |
| if (count[codeTable[nbSeq-1]] > 1) { |
| count[codeTable[nbSeq-1]]--; |
| nbSeq_1--; |
| } |
| assert(nbSeq_1 > 1); |
| FORWARD_IF_ERROR(FSE_normalizeCount(norm, tableLog, count, nbSeq_1, max)); |
| { size_t const NCountSize = FSE_writeNCount(op, oend - op, norm, max, tableLog); /* overflow protected */ |
| FORWARD_IF_ERROR(NCountSize); |
| FORWARD_IF_ERROR(FSE_buildCTable_wksp(nextCTable, norm, max, tableLog, workspace, workspaceSize)); |
| return NCountSize; |
| } |
| } |
| default: assert(0); RETURN_ERROR(GENERIC); |
| } |
| } |
| |
| FORCE_INLINE_TEMPLATE size_t |
| ZSTD_encodeSequences_body( |
| void* dst, size_t dstCapacity, |
| FSE_CTable const* CTable_MatchLength, BYTE const* mlCodeTable, |
| FSE_CTable const* CTable_OffsetBits, BYTE const* ofCodeTable, |
| FSE_CTable const* CTable_LitLength, BYTE const* llCodeTable, |
| seqDef const* sequences, size_t nbSeq, int longOffsets) |
| { |
| BIT_CStream_t blockStream; |
| FSE_CState_t stateMatchLength; |
| FSE_CState_t stateOffsetBits; |
| FSE_CState_t stateLitLength; |
| |
| RETURN_ERROR_IF( |
| ERR_isError(BIT_initCStream(&blockStream, dst, dstCapacity)), |
| dstSize_tooSmall, "not enough space remaining"); |
| DEBUGLOG(6, "available space for bitstream : %i (dstCapacity=%u)", |
| (int)(blockStream.endPtr - blockStream.startPtr), |
| (unsigned)dstCapacity); |
| |
| /* first symbols */ |
| FSE_initCState2(&stateMatchLength, CTable_MatchLength, mlCodeTable[nbSeq-1]); |
| FSE_initCState2(&stateOffsetBits, CTable_OffsetBits, ofCodeTable[nbSeq-1]); |
| FSE_initCState2(&stateLitLength, CTable_LitLength, llCodeTable[nbSeq-1]); |
| BIT_addBits(&blockStream, sequences[nbSeq-1].litLength, LL_bits[llCodeTable[nbSeq-1]]); |
| if (MEM_32bits()) BIT_flushBits(&blockStream); |
| BIT_addBits(&blockStream, sequences[nbSeq-1].matchLength, ML_bits[mlCodeTable[nbSeq-1]]); |
| if (MEM_32bits()) BIT_flushBits(&blockStream); |
| if (longOffsets) { |
| U32 const ofBits = ofCodeTable[nbSeq-1]; |
| int const extraBits = ofBits - MIN(ofBits, STREAM_ACCUMULATOR_MIN-1); |
| if (extraBits) { |
| BIT_addBits(&blockStream, sequences[nbSeq-1].offset, extraBits); |
| BIT_flushBits(&blockStream); |
| } |
| BIT_addBits(&blockStream, sequences[nbSeq-1].offset >> extraBits, |
| ofBits - extraBits); |
| } else { |
| BIT_addBits(&blockStream, sequences[nbSeq-1].offset, ofCodeTable[nbSeq-1]); |
| } |
| BIT_flushBits(&blockStream); |
| |
| { size_t n; |
| for (n=nbSeq-2 ; n<nbSeq ; n--) { /* intentional underflow */ |
| BYTE const llCode = llCodeTable[n]; |
| BYTE const ofCode = ofCodeTable[n]; |
| BYTE const mlCode = mlCodeTable[n]; |
| U32 const llBits = LL_bits[llCode]; |
| U32 const ofBits = ofCode; |
| U32 const mlBits = ML_bits[mlCode]; |
| DEBUGLOG(6, "encoding: litlen:%2u - matchlen:%2u - offCode:%7u", |
| (unsigned)sequences[n].litLength, |
| (unsigned)sequences[n].matchLength + MINMATCH, |
| (unsigned)sequences[n].offset); |
| /* 32b*/ /* 64b*/ |
| /* (7)*/ /* (7)*/ |
| FSE_encodeSymbol(&blockStream, &stateOffsetBits, ofCode); /* 15 */ /* 15 */ |
| FSE_encodeSymbol(&blockStream, &stateMatchLength, mlCode); /* 24 */ /* 24 */ |
| if (MEM_32bits()) BIT_flushBits(&blockStream); /* (7)*/ |
| FSE_encodeSymbol(&blockStream, &stateLitLength, llCode); /* 16 */ /* 33 */ |
| if (MEM_32bits() || (ofBits+mlBits+llBits >= 64-7-(LLFSELog+MLFSELog+OffFSELog))) |
| BIT_flushBits(&blockStream); /* (7)*/ |
| BIT_addBits(&blockStream, sequences[n].litLength, llBits); |
| if (MEM_32bits() && ((llBits+mlBits)>24)) BIT_flushBits(&blockStream); |
| BIT_addBits(&blockStream, sequences[n].matchLength, mlBits); |
| if (MEM_32bits() || (ofBits+mlBits+llBits > 56)) BIT_flushBits(&blockStream); |
| if (longOffsets) { |
| int const extraBits = ofBits - MIN(ofBits, STREAM_ACCUMULATOR_MIN-1); |
| if (extraBits) { |
| BIT_addBits(&blockStream, sequences[n].offset, extraBits); |
|