The optimal block splitter stores up to 196 split points and then needs one additional partition entry for the terminal sequence boundary consumed by the C block-emission loop. The previous array declaration provided only the split slots, so a maximally partitioned block could write the terminal boundary past the projected Rust/C state. Reserve the extra entry and document the layout; retain focused tests for equal-cost and estimation-error cases so the splitter continues to avoid unnecessary or invalid partitions. Test Plan: - Focused block-split Rust tests -- 7 passed - `make -B -C lib -j2 lib` -- passed - `cargo +nightly fmt --manifest-path rust/Cargo.toml -- --check` -- passed - Scoped `git diff --check` -- passed
5756 lines
258 KiB
C
5756 lines
258 KiB
C
/*
|
|
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
|
* 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 "../common/allocations.h" /* ZSTD_customMalloc, ZSTD_customCalloc, ZSTD_customFree */
|
|
#include "../common/zstd_deps.h" /* INT_MAX, ZSTD_memset, ZSTD_memcpy */
|
|
#include "../common/mem.h"
|
|
#include "../common/error_private.h"
|
|
#include "hist.h" /* HIST_countFast_wksp */
|
|
#define FSE_STATIC_LINKING_ONLY /* FSE_encodeSymbol */
|
|
#include "../common/fse.h"
|
|
#include "../common/huf.h"
|
|
#include "zstd_compress_internal.h"
|
|
#include "zstd_compress_sequences.h"
|
|
#include "zstd_compress_literals.h"
|
|
#include "zstd_fast.h"
|
|
#include "zstd_double_fast.h"
|
|
#include "zstd_lazy.h"
|
|
#include "zstd_opt.h"
|
|
#include "zstd_ldm.h"
|
|
#include "zstd_compress_superblock.h"
|
|
#include "../common/bits.h" /* ZSTD_highbit32 */
|
|
|
|
/* Frame serialization lives in Rust. Keep its interface scalar so the
|
|
* large, configuration-sensitive CCtx parameter structure stays in C. */
|
|
size_t ZSTD_rust_writeFrameHeader(void* dst, size_t dstCapacity,
|
|
int noDictIDFlag, int checksumFlag,
|
|
int contentSizeFlag, int format,
|
|
U32 windowLog, U64 pledgedSrcSize,
|
|
U32 dictID);
|
|
void ZSTD_rust_writeBlockHeader(void* op, size_t cSize, size_t blockSize,
|
|
U32 lastBlock);
|
|
size_t ZSTD_rust_writeEpilogue(void* dst, size_t dstCapacity, int* stage,
|
|
int noDictIDFlag, int checksumFlag,
|
|
int contentSizeFlag, int format, U32 windowLog,
|
|
U32 checksum);
|
|
int ZSTD_rust_updateFrameProgression(unsigned long long* consumedSrcSize,
|
|
unsigned long long* producedCSize,
|
|
unsigned long long pledgedSrcSizePlusOne,
|
|
size_t srcSize, size_t cSize,
|
|
size_t fhSize);
|
|
size_t ZSTD_rust_setPledgedSrcSize(int streamStage,
|
|
unsigned long long pledgedSrcSize,
|
|
unsigned long long* pledgedSrcSizePlusOne);
|
|
ZSTD_frameProgression ZSTD_rust_frameProgression(U64 consumedSrcSize,
|
|
size_t buffered,
|
|
U64 producedCSize);
|
|
size_t ZSTD_rust_resetCCtxForSimpleCompression(void* cctx);
|
|
size_t ZSTD_rust_prepareCCtxForSimpleCompression(void* cctx,
|
|
size_t srcSize,
|
|
int compressionLevel);
|
|
int ZSTD_rust_compressCCtxStrategy(size_t srcSize, int compressionLevel);
|
|
size_t ZSTD_rust_resetCCtxForSimpleCompressionSession(void* cctx);
|
|
void ZSTD_rust_markSimpleCompression2Complete(void* cctx);
|
|
size_t ZSTD_compress2_c(ZSTD_CCtx* cctx,
|
|
void* dst, size_t dstCapacity,
|
|
const void* src, size_t srcSize);
|
|
size_t ZSTD_compressStream2_c(ZSTD_CCtx* cctx,
|
|
ZSTD_outBuffer* output,
|
|
ZSTD_inBuffer* input,
|
|
ZSTD_EndDirective endOp);
|
|
int ZSTD_rust_simpleCompress2Level(const void* cctx, size_t srcSize);
|
|
int ZSTD_rust_simpleCompressStream2Level(const void* cctx, size_t srcSize);
|
|
void ZSTD_rust_reduceIndex(U32* hashTable, U32 hashSize,
|
|
U32* chainTable, U32 chainSize,
|
|
U32* hashTable3, U32 hashSize3,
|
|
U32 reducerValue, int preserveChainMark);
|
|
void ZSTD_rust_copyCDictTableIntoCCtx(U32* dst, U32 const* src,
|
|
size_t tableSize, int tagged);
|
|
U64 ZSTD_rust_advanceHashSalt(U64 hashSalt, U64 hashSaltEntropy);
|
|
int ZSTD_rust_indexTooCloseToMax(size_t nextSrcBaseOffset);
|
|
int ZSTD_rust_dictTooBig(size_t loadedDictSize);
|
|
enum {
|
|
ZSTD_RUST_TARGET_CBLOCK_ACTION_RAW = 0,
|
|
ZSTD_RUST_TARGET_CBLOCK_ACTION_RLE = 1,
|
|
ZSTD_RUST_TARGET_CBLOCK_ACTION_COMPRESSED = 2,
|
|
ZSTD_RUST_TARGET_CBLOCK_ACTION_ERROR = 3
|
|
};
|
|
int ZSTD_rust_targetCBlockSizeAction(int bss, int isFirstBlock,
|
|
int maybeRLE, int isRLE,
|
|
size_t cSize, size_t srcSize,
|
|
int strategy);
|
|
size_t ZSTD_rust_nextInputSizeHint(int inBufferMode,
|
|
size_t blockSizeMax,
|
|
size_t stableInNotConsumed,
|
|
size_t inBuffTarget,
|
|
size_t inBuffPos);
|
|
size_t ZSTD_rust_CStreamInSize(void);
|
|
size_t ZSTD_rust_CStreamOutSize(void);
|
|
size_t ZSTD_rust_sizeofCDict(size_t objectSize, size_t workspaceSize);
|
|
size_t ZSTD_rust_sizeofLocalDict(int dictBufferPresent, size_t dictSize,
|
|
size_t cdictSize);
|
|
size_t ZSTD_rust_sizeofCCtx(size_t objectSize, size_t workspaceSize,
|
|
size_t localDictSize, size_t mtctxSize);
|
|
size_t ZSTD_rust_estimateWorkspaceSize(size_t cctxSpace,
|
|
size_t tmpWorkSpace,
|
|
size_t blockStateSpace,
|
|
size_t ldmSpace,
|
|
size_t ldmSeqSpace,
|
|
size_t matchStateSize,
|
|
size_t tokenSpace,
|
|
size_t bufferSpace,
|
|
size_t externalSeqSpace);
|
|
size_t ZSTD_rust_maxEstimateCCtxSize(size_t estimate0, size_t estimate1,
|
|
size_t estimate2, size_t estimate3);
|
|
ZSTD_inBuffer ZSTD_rust_inBufferForEndFlush(int inBufferMode,
|
|
const void* expectedSrc,
|
|
size_t expectedSize,
|
|
size_t expectedPos);
|
|
size_t ZSTD_rust_endStreamRemaining(size_t remainingToFlush,
|
|
int frameEnded, int checksumFlag);
|
|
size_t ZSTD_rust_checkBufferStability(
|
|
int inBufferMode, int outBufferMode,
|
|
const void* expectedInSrc, size_t expectedInPos,
|
|
const void* inputSrc, size_t inputPos,
|
|
size_t expectedOutBufferSize, size_t outputSize, size_t outputPos);
|
|
|
|
/* Context-free compression-parameter selection and sizing leaves live in
|
|
* Rust (rust/src/zstd_compress_params.rs). This file retains
|
|
* configuration-sensitive policy: the C-preprocessor construction of the
|
|
* excluded-block-compressor mask, private ZSTD_CCtx_params handling, and
|
|
* sanitizer workspace policy, which it feeds to the leaves as explicit
|
|
* scalar inputs. The ZSTD_CParamMode_e and ZSTD_ParamSwitch_e enums are
|
|
* passed as int; the Rust side mirrors their values. */
|
|
int ZSTD_rust_params_maxCLevel(void);
|
|
int ZSTD_rust_params_minCLevel(void);
|
|
int ZSTD_rust_params_defaultCLevel(void);
|
|
ZSTD_bounds ZSTD_rust_params_getBounds(int param);
|
|
size_t ZSTD_rust_params_checkCParams(ZSTD_compressionParameters cParams);
|
|
void ZSTD_rust_params_assertEqualCParams(ZSTD_compressionParameters cParams1,
|
|
ZSTD_compressionParameters cParams2);
|
|
ZSTD_compressionParameters
|
|
ZSTD_rust_params_clampCParams(ZSTD_compressionParameters cParams);
|
|
U32 ZSTD_rust_params_cycleLog(U32 hashLog, int strategy);
|
|
ZSTD_compressionParameters
|
|
ZSTD_rust_params_selectCParams(int compressionLevel, U64 srcSizeHint,
|
|
size_t dictSize, int mode);
|
|
ZSTD_compressionParameters
|
|
ZSTD_rust_params_adjustCParams(ZSTD_compressionParameters cParams, U64 srcSize,
|
|
size_t dictSize, int mode,
|
|
int useRowMatchFinder);
|
|
ZSTD_compressionParameters ZSTD_rust_params_applyStrategyExclusions(
|
|
ZSTD_compressionParameters cParams, U32 exclusionMask);
|
|
ZSTD_compressionParameters ZSTD_rust_params_getCParamsFromCCtxParams(
|
|
int compressionLevel, int cctxSrcSizeHint, U64 srcSizeHint,
|
|
size_t dictSize, int mode, int enableLdm, U32 ldmDefaultWindowLog,
|
|
ZSTD_compressionParameters overrides, int useRowMatchFinder,
|
|
U32 exclusionMask);
|
|
ZSTD_parameters ZSTD_rust_params_makeParams(ZSTD_compressionParameters cParams);
|
|
size_t ZSTD_rust_params_maxNbSeq(size_t blockSize, U32 minMatch,
|
|
int useSequenceProducer);
|
|
size_t ZSTD_rust_params_resolveMaxBlockSize(size_t maxBlockSize);
|
|
size_t ZSTD_rust_params_getBlockSize(size_t maxBlockSize, U32 windowLog);
|
|
void ZSTD_rust_params_overrideCParams(ZSTD_compressionParameters* cParams,
|
|
const ZSTD_compressionParameters* overrides);
|
|
int ZSTD_rust_params_resolveExternalSequenceValidation(int mode);
|
|
int ZSTD_rust_params_rowMatchFinderSupported(int strategy);
|
|
int ZSTD_rust_params_rowMatchFinderUsed(int strategy, int mode);
|
|
int ZSTD_rust_params_selectBlockCompressor(int strategy, int mode);
|
|
int ZSTD_rust_params_resolveRowMatchFinderMode(
|
|
int mode, ZSTD_compressionParameters cParams);
|
|
int ZSTD_rust_params_resolveBlockSplitterMode(
|
|
int mode, ZSTD_compressionParameters cParams);
|
|
int ZSTD_rust_params_allocateChainTable(int strategy, int mode, int forDDSDict);
|
|
int ZSTD_rust_params_resolveEnableLdm(
|
|
int mode, ZSTD_compressionParameters cParams);
|
|
int ZSTD_rust_params_resolveExternalRepcodeSearch(int mode, int cLevel);
|
|
int ZSTD_rust_params_cdictIndicesAreTagged(ZSTD_compressionParameters cParams);
|
|
int ZSTD_rust_params_dedicatedDictSearchIsSupported(ZSTD_compressionParameters cParams);
|
|
ZSTD_compressionParameters
|
|
ZSTD_rust_params_dedicatedDictSearch_getCParams(ZSTD_compressionParameters cParams);
|
|
ZSTD_compressionParameters
|
|
ZSTD_rust_params_dedicatedDictSearch_revertCParams(ZSTD_compressionParameters cParams);
|
|
int ZSTD_rust_params_shouldAttachDict(int strategy, int dedicatedDictSearch,
|
|
U64 pledgedSrcSize, int attachDictPref,
|
|
int forceWindow);
|
|
int ZSTD_rust_params_getCParamMode(int cdict_present, int cdict_strategy,
|
|
int cdict_dedicated_search,
|
|
U64 pledgedSrcSize,
|
|
int params_attachDictPref,
|
|
int params_forceWindow);
|
|
|
|
/* CCtx parameter state is mirrored by rust/src/zstd_compress_params_api.rs.
|
|
* Rust owns parameter bounds and clamping; C exposes only the
|
|
* build-configuration values required by that narrow ABI. */
|
|
ZSTD_bounds ZSTD_rust_cctx_params_get_bounds(int param);
|
|
size_t ZSTD_rust_cctx_params_clamp_bounds(int param, int* value);
|
|
int ZSTD_rust_cctx_params_within_bounds(int param, int value);
|
|
int ZSTD_rust_cctx_params_is_multithreaded(void);
|
|
int ZSTD_rust_cctx_params_nb_workers_max(void);
|
|
int ZSTD_rust_cctx_params_job_size_min(void);
|
|
int ZSTD_rust_cctx_params_job_size_max(void);
|
|
int ZSTD_rust_isUpdateAuthorized(int param);
|
|
ZSTD_CCtx_params* ZSTD_rust_createCCtxParams(ZSTD_customMem customMem);
|
|
size_t ZSTD_rust_freeCCtxParams(ZSTD_CCtx_params* params);
|
|
size_t ZSTD_rust_CCtxParams_init_advanced(ZSTD_CCtx_params* cctxParams,
|
|
ZSTD_parameters params);
|
|
void ZSTD_rust_CCtxParams_setZstdParams(ZSTD_CCtx_params* cctxParams,
|
|
const ZSTD_parameters* params);
|
|
int ZSTD_rust_useTargetCBlockSize(const ZSTD_CCtx_params* cctxParams);
|
|
int ZSTD_rust_blockSplitterEnabled(ZSTD_CCtx_params* cctxParams);
|
|
|
|
#define ZSTD_RUST_CCTX_PARAMS_ASSERT(name, condition) \
|
|
typedef char name[(condition) ? 1 : -1]
|
|
ZSTD_RUST_CCTX_PARAMS_ASSERT(ZSTD_rust_cctx_params_ldm_size, sizeof(ldmParams_t) == 24);
|
|
ZSTD_RUST_CCTX_PARAMS_ASSERT(ZSTD_rust_cctx_params_custom_mem_size,
|
|
sizeof(ZSTD_customMem) == (sizeof(void*) == 8 ? 24 : 12));
|
|
ZSTD_RUST_CCTX_PARAMS_ASSERT(ZSTD_rust_cctx_params_size,
|
|
sizeof(ZSTD_CCtx_params) == (sizeof(void*) == 8 ? 224 : 180));
|
|
ZSTD_RUST_CCTX_PARAMS_ASSERT(ZSTD_rust_cctx_params_format_offset,
|
|
offsetof(ZSTD_CCtx_params, format) == 0);
|
|
ZSTD_RUST_CCTX_PARAMS_ASSERT(ZSTD_rust_cctx_params_cparams_offset,
|
|
offsetof(ZSTD_CCtx_params, cParams) == 4);
|
|
ZSTD_RUST_CCTX_PARAMS_ASSERT(ZSTD_rust_cctx_params_fparams_offset,
|
|
offsetof(ZSTD_CCtx_params, fParams) == 32);
|
|
ZSTD_RUST_CCTX_PARAMS_ASSERT(ZSTD_rust_cctx_params_level_offset,
|
|
offsetof(ZSTD_CCtx_params, compressionLevel) == 44);
|
|
ZSTD_RUST_CCTX_PARAMS_ASSERT(ZSTD_rust_cctx_params_force_window_offset,
|
|
offsetof(ZSTD_CCtx_params, forceWindow) == 48);
|
|
ZSTD_RUST_CCTX_PARAMS_ASSERT(ZSTD_rust_cctx_params_target_block_offset,
|
|
offsetof(ZSTD_CCtx_params, targetCBlockSize) == (sizeof(void*) == 8 ? 56 : 52));
|
|
ZSTD_RUST_CCTX_PARAMS_ASSERT(ZSTD_rust_cctx_params_src_hint_offset,
|
|
offsetof(ZSTD_CCtx_params, srcSizeHint) == (sizeof(void*) == 8 ? 64 : 56));
|
|
ZSTD_RUST_CCTX_PARAMS_ASSERT(ZSTD_rust_cctx_params_attach_offset,
|
|
offsetof(ZSTD_CCtx_params, attachDictPref) == (sizeof(void*) == 8 ? 68 : 60));
|
|
ZSTD_RUST_CCTX_PARAMS_ASSERT(ZSTD_rust_cctx_params_literal_mode_offset,
|
|
offsetof(ZSTD_CCtx_params, literalCompressionMode) == (sizeof(void*) == 8 ? 72 : 64));
|
|
ZSTD_RUST_CCTX_PARAMS_ASSERT(ZSTD_rust_cctx_params_workers_offset,
|
|
offsetof(ZSTD_CCtx_params, nbWorkers) == (sizeof(void*) == 8 ? 76 : 68));
|
|
ZSTD_RUST_CCTX_PARAMS_ASSERT(ZSTD_rust_cctx_params_job_size_offset,
|
|
offsetof(ZSTD_CCtx_params, jobSize) == (sizeof(void*) == 8 ? 80 : 72));
|
|
ZSTD_RUST_CCTX_PARAMS_ASSERT(ZSTD_rust_cctx_params_overlap_offset,
|
|
offsetof(ZSTD_CCtx_params, overlapLog) == (sizeof(void*) == 8 ? 88 : 76));
|
|
ZSTD_RUST_CCTX_PARAMS_ASSERT(ZSTD_rust_cctx_params_rsyncable_offset,
|
|
offsetof(ZSTD_CCtx_params, rsyncable) == (sizeof(void*) == 8 ? 92 : 80));
|
|
ZSTD_RUST_CCTX_PARAMS_ASSERT(ZSTD_rust_cctx_params_ldm_offset,
|
|
offsetof(ZSTD_CCtx_params, ldmParams) == (sizeof(void*) == 8 ? 96 : 84));
|
|
ZSTD_RUST_CCTX_PARAMS_ASSERT(ZSTD_rust_cctx_params_dedicated_dict_offset,
|
|
offsetof(ZSTD_CCtx_params, enableDedicatedDictSearch) == (sizeof(void*) == 8 ? 120 : 108));
|
|
ZSTD_RUST_CCTX_PARAMS_ASSERT(ZSTD_rust_cctx_params_in_buffer_offset,
|
|
offsetof(ZSTD_CCtx_params, inBufferMode) == (sizeof(void*) == 8 ? 124 : 112));
|
|
ZSTD_RUST_CCTX_PARAMS_ASSERT(ZSTD_rust_cctx_params_out_buffer_offset,
|
|
offsetof(ZSTD_CCtx_params, outBufferMode) == (sizeof(void*) == 8 ? 128 : 116));
|
|
ZSTD_RUST_CCTX_PARAMS_ASSERT(ZSTD_rust_cctx_params_delimiters_offset,
|
|
offsetof(ZSTD_CCtx_params, blockDelimiters) == (sizeof(void*) == 8 ? 132 : 120));
|
|
ZSTD_RUST_CCTX_PARAMS_ASSERT(ZSTD_rust_cctx_params_validate_offset,
|
|
offsetof(ZSTD_CCtx_params, validateSequences) == (sizeof(void*) == 8 ? 136 : 124));
|
|
ZSTD_RUST_CCTX_PARAMS_ASSERT(ZSTD_rust_cctx_params_post_splitter_offset,
|
|
offsetof(ZSTD_CCtx_params, postBlockSplitter) == (sizeof(void*) == 8 ? 140 : 128));
|
|
ZSTD_RUST_CCTX_PARAMS_ASSERT(ZSTD_rust_cctx_params_pre_splitter_offset,
|
|
offsetof(ZSTD_CCtx_params, preBlockSplitter_level) == (sizeof(void*) == 8 ? 144 : 132));
|
|
ZSTD_RUST_CCTX_PARAMS_ASSERT(ZSTD_rust_cctx_params_max_block_offset,
|
|
offsetof(ZSTD_CCtx_params, maxBlockSize) == (sizeof(void*) == 8 ? 152 : 136));
|
|
ZSTD_RUST_CCTX_PARAMS_ASSERT(ZSTD_rust_cctx_params_row_matcher_offset,
|
|
offsetof(ZSTD_CCtx_params, useRowMatchFinder) == (sizeof(void*) == 8 ? 160 : 140));
|
|
ZSTD_RUST_CCTX_PARAMS_ASSERT(ZSTD_rust_cctx_params_deterministic_prefix_offset,
|
|
offsetof(ZSTD_CCtx_params, deterministicRefPrefix) == (sizeof(void*) == 8 ? 164 : 144));
|
|
ZSTD_RUST_CCTX_PARAMS_ASSERT(ZSTD_rust_cctx_params_custom_mem_offset,
|
|
offsetof(ZSTD_CCtx_params, customMem) == (sizeof(void*) == 8 ? 168 : 148));
|
|
ZSTD_RUST_CCTX_PARAMS_ASSERT(ZSTD_rust_cctx_params_prefetch_offset,
|
|
offsetof(ZSTD_CCtx_params, prefetchCDictTables) == (sizeof(void*) == 8 ? 192 : 160));
|
|
ZSTD_RUST_CCTX_PARAMS_ASSERT(ZSTD_rust_cctx_params_fallback_offset,
|
|
offsetof(ZSTD_CCtx_params, enableMatchFinderFallback) == (sizeof(void*) == 8 ? 196 : 164));
|
|
ZSTD_RUST_CCTX_PARAMS_ASSERT(ZSTD_rust_cctx_params_state_offset,
|
|
offsetof(ZSTD_CCtx_params, extSeqProdState) == (sizeof(void*) == 8 ? 200 : 168));
|
|
ZSTD_RUST_CCTX_PARAMS_ASSERT(ZSTD_rust_cctx_params_function_offset,
|
|
offsetof(ZSTD_CCtx_params, extSeqProdFunc) == (sizeof(void*) == 8 ? 208 : 172));
|
|
ZSTD_RUST_CCTX_PARAMS_ASSERT(ZSTD_rust_cctx_params_repcode_offset,
|
|
offsetof(ZSTD_CCtx_params, searchForExternalRepcodes) == (sizeof(void*) == 8 ? 216 : 176));
|
|
#undef ZSTD_RUST_CCTX_PARAMS_ASSERT
|
|
|
|
typedef struct {
|
|
U32 hashLog3Max;
|
|
size_t matchTSize;
|
|
size_t optimalTSize;
|
|
size_t asanRedzoneSize;
|
|
} ZSTD_rustMatchStateSizing;
|
|
size_t ZSTD_rust_params_estimateMatchStateSize(
|
|
ZSTD_compressionParameters cParams, int useRowMatchFinder,
|
|
int enableDedicatedDictSearch, U32 forCCtx,
|
|
const ZSTD_rustMatchStateSizing* sizing);
|
|
|
|
typedef struct {
|
|
size_t cdictSize;
|
|
size_t hufWorkspaceSize;
|
|
U32 hashLog3Max;
|
|
size_t matchTSize;
|
|
size_t optimalTSize;
|
|
size_t asanRedzoneSize;
|
|
} ZSTD_rustCDictSizing;
|
|
size_t ZSTD_rust_params_estimateCDictSizeFromCParams(
|
|
size_t dictSize, ZSTD_compressionParameters cParams,
|
|
int dictLoadMethod, const ZSTD_rustCDictSizing* sizing);
|
|
|
|
/* Sequence statistics and seqStore entropy compression live in Rust
|
|
* (rust/src/zstd_compress_stats.rs), which also exports ZSTD_seqToCodes()
|
|
* under its original name. The shims below extract the sequence store, the
|
|
* entropy-table leaves, and the only two ZSTD_CCtx_params fields these paths
|
|
* read (the strategy and the literals-compression switch), so the private
|
|
* parameter structure layout never crosses the language boundary. The
|
|
* shared leaf layouts are pinned by the compile-time asserts that follow. */
|
|
size_t ZSTD_rust_entropyCompressSeqStore_internal(
|
|
void* dst, size_t dstCapacity,
|
|
const void* literals, size_t litSize,
|
|
const SeqStore_t* seqStorePtr,
|
|
const ZSTD_entropyCTables_t* prevEntropy,
|
|
ZSTD_entropyCTables_t* nextEntropy,
|
|
int strategy, int disableLiteralCompression,
|
|
void* entropyWorkspace, size_t entropyWkspSize,
|
|
int bmi2);
|
|
size_t ZSTD_rust_entropyCompressSeqStore(
|
|
const SeqStore_t* seqStorePtr,
|
|
const ZSTD_entropyCTables_t* prevEntropy,
|
|
ZSTD_entropyCTables_t* nextEntropy,
|
|
int strategy, int disableLiteralCompression,
|
|
void* dst, size_t dstCapacity,
|
|
size_t srcSize,
|
|
void* entropyWorkspace, size_t entropyWkspSize,
|
|
int bmi2);
|
|
size_t ZSTD_rust_buildBlockEntropyStats(
|
|
const SeqStore_t* seqStorePtr,
|
|
const ZSTD_entropyCTables_t* prevEntropy,
|
|
ZSTD_entropyCTables_t* nextEntropy,
|
|
int strategy, int disableLiteralCompression,
|
|
ZSTD_entropyCTablesMetadata_t* entropyMetadata,
|
|
void* workspace, size_t wkspSize);
|
|
size_t ZSTD_rust_estimateBlockSize(
|
|
const BYTE* literals, size_t litSize,
|
|
const BYTE* ofCodeTable, const BYTE* llCodeTable,
|
|
const BYTE* mlCodeTable, size_t nbSeq,
|
|
const ZSTD_entropyCTables_t* entropy,
|
|
const ZSTD_entropyCTablesMetadata_t* entropyMetadata,
|
|
void* workspace, size_t wkspSize,
|
|
int writeLitEntropy, int writeSeqEntropy);
|
|
size_t ZSTD_rust_copyBlockSequences(
|
|
SeqCollector* seqCollector, const SeqStore_t* seqStore,
|
|
const U32 prevRepcodes[ZSTD_REP_NUM]);
|
|
void ZSTD_rust_resetCompressedBlockState(ZSTD_compressedBlockState_t* bs);
|
|
void ZSTD_rust_invalidateRepCodes(U32 rep[ZSTD_REP_NUM]);
|
|
typedef char ZSTD_rust_invalidate_rep_count[(ZSTD_REP_NUM == 3) ? 1 : -1];
|
|
void ZSTD_rust_confirmRepcodesAndEntropyTables(
|
|
ZSTD_compressedBlockState_t** prevCBlock,
|
|
ZSTD_compressedBlockState_t** nextCBlock);
|
|
void ZSTD_rust_storeLastLiterals(SeqStore_t* seqStorePtr,
|
|
const BYTE* anchor, size_t lastLLSize);
|
|
void ZSTD_rust_resetSeqStore(SeqStore_t* ssPtr);
|
|
size_t ZSTD_rust_fastSequenceLengthSum(const ZSTD_Sequence* seqBuf,
|
|
size_t seqBufSize);
|
|
void ZSTD_rust_validateSeqStore(const SeqStore_t* seqStore, U32 minMatch);
|
|
size_t ZSTD_rust_convertSequencesNoRepcodes(
|
|
SeqDef* dstSeqs, const ZSTD_Sequence* inSeqs, size_t nbSequences);
|
|
BlockSummary ZSTD_rust_get1BlockSummary(const ZSTD_Sequence* seqs,
|
|
size_t nbSeqs);
|
|
int ZSTD_rust_isRLE(const BYTE* src, size_t length);
|
|
int ZSTD_rust_maybeRLE(const SeqStore_t* seqStore);
|
|
size_t ZSTD_rust_postProcessSequenceProducerResult(
|
|
ZSTD_Sequence* outSeqs, size_t nbExternalSeqs,
|
|
size_t outSeqsCapacity, size_t srcSize);
|
|
size_t ZSTD_rust_countSeqStoreLiteralsBytes(const SeqStore_t* seqStore);
|
|
size_t ZSTD_rust_countSeqStoreMatchBytes(const SeqStore_t* seqStore);
|
|
void ZSTD_rust_deriveSeqStoreChunk(SeqStore_t* resultSeqStore,
|
|
const SeqStore_t* originalSeqStore,
|
|
size_t startIdx, size_t endIdx);
|
|
size_t ZSTD_rust_deriveBlockSplits(
|
|
U32* partitions, U32 nbSeq,
|
|
const SeqStore_t* originalSeqStore,
|
|
SeqStore_t* fullSeqStoreChunk,
|
|
SeqStore_t* firstHalfSeqStore,
|
|
SeqStore_t* secondHalfSeqStore,
|
|
const ZSTD_entropyCTables_t* prevEntropy,
|
|
ZSTD_entropyCTables_t* nextEntropy,
|
|
int strategy, int disableLiteralCompression,
|
|
ZSTD_entropyCTablesMetadata_t* entropyMetadata,
|
|
void* workspace, size_t workspaceSize);
|
|
void ZSTD_rust_seqStore_resolveOffCodes(U32 dRep[ZSTD_REP_NUM],
|
|
U32 cRep[ZSTD_REP_NUM],
|
|
const SeqStore_t* seqStore,
|
|
U32 nbSeq);
|
|
U32 ZSTD_rust_resolveRepcodeToRawOffset(const U32 rep[ZSTD_REP_NUM],
|
|
U32 offBase, U32 ll0);
|
|
U32 ZSTD_rust_finalizeOffBase(U32 rawOffset, const U32 rep[ZSTD_REP_NUM], U32 ll0);
|
|
size_t ZSTD_rust_blockSizeExplicitDelimiter(const ZSTD_Sequence* inSeqs,
|
|
size_t inSeqsSize, U32 seqIdx);
|
|
size_t ZSTD_rust_determineBlockSize(int mode, size_t blockSize, size_t remaining,
|
|
const ZSTD_Sequence* inSeqs, size_t inSeqsSize,
|
|
U32 seqIdx);
|
|
int ZSTD_rust_selectSequenceCopier(int mode);
|
|
size_t ZSTD_rust_loadCEntropy(ZSTD_compressedBlockState_t* bs, void* workspace,
|
|
const void* dict, size_t dictSize);
|
|
size_t ZSTD_rust_transferSequencesWBlockDelim(
|
|
SeqStore_t* seqStore, ZSTD_SequencePosition* seqPos,
|
|
const ZSTD_Sequence* inSeqs, size_t inSeqsSize,
|
|
const BYTE* src, size_t blockSize, int externalRepSearch,
|
|
const U32 prevRepcodes[ZSTD_REP_NUM],
|
|
U32 nextRepcodes[ZSTD_REP_NUM], U32 dictSize,
|
|
int validateSequences, U32 minMatch, U32 windowLog,
|
|
int useSequenceProducer);
|
|
size_t ZSTD_rust_transferSequencesNoDelim(
|
|
SeqStore_t* seqStore, ZSTD_SequencePosition* seqPos,
|
|
const ZSTD_Sequence* inSeqs, size_t inSeqsSize,
|
|
const BYTE* src, size_t blockSize,
|
|
const U32 prevRepcodes[ZSTD_REP_NUM],
|
|
U32 nextRepcodes[ZSTD_REP_NUM], U32 dictSize,
|
|
int validateSequences, U32 minMatch, U32 windowLog,
|
|
int useSequenceProducer);
|
|
size_t ZSTD_rust_optimalBlockSize(const void* src, size_t srcSize,
|
|
size_t blockSizeMax, int splitLevel,
|
|
int strategy, S64 savings,
|
|
void* workspace, size_t workspaceSize);
|
|
|
|
typedef char ZSTD_rust_stats_seqdef_layout[(sizeof(SeqDef) == 8) ? 1 : -1];
|
|
typedef char ZSTD_rust_stats_block_summary_layout[
|
|
(sizeof(BlockSummary) == 3 * sizeof(size_t)) ? 1 : -1];
|
|
typedef char ZSTD_rust_stats_seqstore_long_length_pos[
|
|
(offsetof(SeqStore_t, longLengthPos) == 9 * sizeof(size_t) + 4) ? 1 : -1];
|
|
typedef char ZSTD_rust_stats_seqstore_layout[
|
|
(sizeof(SeqStore_t) == 9 * sizeof(size_t) + 8) ? 1 : -1];
|
|
typedef char ZSTD_rust_stats_huf_layout[
|
|
(sizeof(ZSTD_hufCTables_t) == 258 * sizeof(size_t)) ? 1 : -1];
|
|
typedef char ZSTD_rust_stats_fse_layout[(sizeof(ZSTD_fseCTables_t) == 3552) ? 1 : -1];
|
|
typedef char ZSTD_rust_stats_entropy_fse_offset[
|
|
(offsetof(ZSTD_entropyCTables_t, fse) == sizeof(ZSTD_hufCTables_t)) ? 1 : -1];
|
|
typedef char ZSTD_rust_stats_huf_metadata_buffer[
|
|
(offsetof(ZSTD_hufCTablesMetadata_t, hufDesBuffer) == 4
|
|
&& ZSTD_MAX_HUF_HEADER_SIZE == 128) ? 1 : -1];
|
|
typedef char ZSTD_rust_stats_fse_metadata_buffer[
|
|
(offsetof(ZSTD_fseCTablesMetadata_t, fseTablesBuffer) == 12
|
|
&& ZSTD_MAX_FSE_HEADERS_SIZE == 133) ? 1 : -1];
|
|
typedef char ZSTD_rust_stats_entropy_metadata_layout[
|
|
(offsetof(ZSTD_entropyCTablesMetadata_t, fseMetadata)
|
|
== sizeof(ZSTD_hufCTablesMetadata_t)) ? 1 : -1];
|
|
typedef char ZSTD_rust_stats_sequence_layout[(sizeof(ZSTD_Sequence) == 16) ? 1 : -1];
|
|
typedef char ZSTD_rust_stats_sequence_position_layout[
|
|
(sizeof(ZSTD_SequencePosition) == 2 * sizeof(U32) + sizeof(size_t)
|
|
&& offsetof(ZSTD_SequencePosition, posInSrc) == 2 * sizeof(U32)) ? 1 : -1];
|
|
typedef char ZSTD_rust_stats_seqcollector_layout[
|
|
(offsetof(SeqCollector, seqStart) == sizeof(size_t)
|
|
&& offsetof(SeqCollector, seqIndex) == 2 * sizeof(size_t)
|
|
&& sizeof(SeqCollector) == 4 * sizeof(size_t)) ? 1 : -1];
|
|
|
|
#if ZSTD_ADDRESS_SANITIZER && !defined (ZSTD_ASAN_DONT_POISON_WORKSPACE)
|
|
# define ZSTD_RUST_ASAN_REDZONE_SIZE ((size_t)ZSTD_CWKSP_ASAN_REDZONE_SIZE)
|
|
#else
|
|
# define ZSTD_RUST_ASAN_REDZONE_SIZE ((size_t)0)
|
|
#endif
|
|
|
|
/* ***************************************************************
|
|
* Tuning parameters
|
|
*****************************************************************/
|
|
/*!
|
|
* COMPRESS_HEAPMODE :
|
|
* Select how default decompression function ZSTD_compress() allocates its context,
|
|
* on stack (0, default), or into heap (1).
|
|
* Note that functions with explicit context such as ZSTD_compressCCtx() are unaffected.
|
|
*/
|
|
#ifndef ZSTD_COMPRESS_HEAPMODE
|
|
# define ZSTD_COMPRESS_HEAPMODE 0
|
|
#endif
|
|
|
|
/*!
|
|
* ZSTD_HASHLOG3_MAX :
|
|
* Maximum size of the hash table dedicated to find 3-bytes matches,
|
|
* in log format, aka 17 => 1 << 17 == 128Ki positions.
|
|
* This structure is only used in zstd_opt.
|
|
* Since allocation is centralized for all strategies, it has to be known here.
|
|
* The actual (selected) size of the hash table is then stored in ZSTD_MatchState_t.hashLog3,
|
|
* so that zstd_opt.c doesn't need to know about this constant.
|
|
*/
|
|
#ifndef ZSTD_HASHLOG3_MAX
|
|
# define ZSTD_HASHLOG3_MAX 17
|
|
#endif
|
|
|
|
/*-*************************************
|
|
* Helper functions
|
|
***************************************/
|
|
/* ZSTD_compressBound() lives in rust/src/zstd_compress_api.rs. Keep this
|
|
* translation unit for the context implementation, which still calls the
|
|
* exported ABI symbol. */
|
|
|
|
|
|
/*-*************************************
|
|
* Context memory management
|
|
***************************************/
|
|
struct ZSTD_CDict_s {
|
|
const void* dictContent;
|
|
size_t dictContentSize;
|
|
ZSTD_dictContentType_e dictContentType; /* The dictContentType the CDict was created with */
|
|
U32* entropyWorkspace; /* entropy workspace of HUF_WORKSPACE_SIZE bytes */
|
|
ZSTD_cwksp workspace;
|
|
ZSTD_MatchState_t matchState;
|
|
ZSTD_compressedBlockState_t cBlockState;
|
|
ZSTD_customMem customMem;
|
|
U32 dictID;
|
|
int compressionLevel; /* 0 indicates that advanced API was used to select CDict params */
|
|
ZSTD_ParamSwitch_e useRowMatchFinder; /* Indicates whether the CDict was created with params that would use
|
|
* row-based matchfinder. Unless the cdict is reloaded, we will use
|
|
* the same greedy/lazy matchfinder at compression time.
|
|
*/
|
|
}; /* 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);
|
|
ZSTD_memset(cctx, 0, sizeof(*cctx));
|
|
cctx->customMem = memManager;
|
|
cctx->bmi2 = ZSTD_cpuSupportsBmi2();
|
|
{ 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_customMalloc(sizeof(ZSTD_CCtx), customMem);
|
|
if (!cctx) return NULL;
|
|
ZSTD_initCCtx(cctx, customMem);
|
|
return cctx;
|
|
}
|
|
}
|
|
|
|
ZSTD_CCtx* ZSTD_initStaticCCtx(void* workspace, size_t workspaceSize)
|
|
{
|
|
ZSTD_cwksp ws;
|
|
ZSTD_CCtx* cctx;
|
|
if (workspaceSize <= sizeof(ZSTD_CCtx)) return NULL; /* minimum size */
|
|
if ((size_t)workspace & 7) return NULL; /* must be 8-aligned */
|
|
ZSTD_cwksp_init(&ws, workspace, workspaceSize, ZSTD_cwksp_static_alloc);
|
|
|
|
cctx = (ZSTD_CCtx*)ZSTD_cwksp_reserve_object(&ws, sizeof(ZSTD_CCtx));
|
|
if (cctx == NULL) return NULL;
|
|
|
|
ZSTD_memset(cctx, 0, sizeof(ZSTD_CCtx));
|
|
ZSTD_cwksp_move(&cctx->workspace, &ws);
|
|
cctx->staticSize = workspaceSize;
|
|
|
|
/* statically sized space. tmpWorkspace never moves (but prev/next block swap places) */
|
|
if (!ZSTD_cwksp_check_available(&cctx->workspace, TMP_WORKSPACE_SIZE + 2 * sizeof(ZSTD_compressedBlockState_t))) return NULL;
|
|
cctx->blockState.prevCBlock = (ZSTD_compressedBlockState_t*)ZSTD_cwksp_reserve_object(&cctx->workspace, sizeof(ZSTD_compressedBlockState_t));
|
|
cctx->blockState.nextCBlock = (ZSTD_compressedBlockState_t*)ZSTD_cwksp_reserve_object(&cctx->workspace, sizeof(ZSTD_compressedBlockState_t));
|
|
cctx->tmpWorkspace = ZSTD_cwksp_reserve_object(&cctx->workspace, TMP_WORKSPACE_SIZE);
|
|
cctx->tmpWkspSize = TMP_WORKSPACE_SIZE;
|
|
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_customFree(cctx->localDict.dictBuffer, cctx->customMem);
|
|
ZSTD_freeCDict(cctx->localDict.cdict);
|
|
ZSTD_memset(&cctx->localDict, 0, sizeof(cctx->localDict));
|
|
ZSTD_memset(&cctx->prefixDict, 0, sizeof(cctx->prefixDict));
|
|
cctx->cdict = NULL;
|
|
}
|
|
|
|
static size_t ZSTD_sizeof_localDict(ZSTD_localDict dict)
|
|
{
|
|
size_t const cdictSize = ZSTD_sizeof_CDict(dict.cdict);
|
|
return ZSTD_rust_sizeofLocalDict(dict.dictBuffer != NULL, dict.dictSize,
|
|
cdictSize);
|
|
}
|
|
|
|
static void ZSTD_freeCCtxContent(ZSTD_CCtx* cctx)
|
|
{
|
|
assert(cctx != NULL);
|
|
assert(cctx->staticSize == 0);
|
|
ZSTD_clearAllDicts(cctx);
|
|
#ifdef ZSTD_MULTITHREAD
|
|
ZSTDMT_freeCCtx(cctx->mtctx); cctx->mtctx = NULL;
|
|
#endif
|
|
ZSTD_cwksp_free(&cctx->workspace, cctx->customMem);
|
|
}
|
|
|
|
size_t ZSTD_freeCCtx(ZSTD_CCtx* cctx)
|
|
{
|
|
DEBUGLOG(3, "ZSTD_freeCCtx (address: %p)", (void*)cctx);
|
|
if (cctx==NULL) return 0; /* support free on NULL */
|
|
RETURN_ERROR_IF(cctx->staticSize, memory_allocation,
|
|
"not compatible with static CCtx");
|
|
{ int cctxInWorkspace = ZSTD_cwksp_owns_buffer(&cctx->workspace, cctx);
|
|
ZSTD_freeCCtxContent(cctx);
|
|
if (!cctxInWorkspace) ZSTD_customFree(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 */
|
|
{
|
|
/* cctx may be in the workspace */
|
|
size_t const objectSize = cctx->workspace.workspace == cctx ? 0 : sizeof(*cctx);
|
|
size_t const workspaceSize = ZSTD_cwksp_sizeof(&cctx->workspace);
|
|
size_t const localDictSize = ZSTD_sizeof_localDict(cctx->localDict);
|
|
size_t const mtctxSize = ZSTD_sizeof_mtctx(cctx);
|
|
return ZSTD_rust_sizeofCCtx(objectSize, workspaceSize, localDictSize,
|
|
mtctxSize);
|
|
}
|
|
}
|
|
|
|
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); }
|
|
|
|
/* Returns true if the strategy supports using a row based matchfinder */
|
|
static int ZSTD_rowMatchFinderSupported(const ZSTD_strategy strategy) {
|
|
return ZSTD_rust_params_rowMatchFinderSupported((int)strategy);
|
|
}
|
|
|
|
/* Returns true if the strategy and useRowMatchFinder mode indicate that we will use the row based matchfinder
|
|
* for this compression.
|
|
*/
|
|
static int ZSTD_rowMatchFinderUsed(const ZSTD_strategy strategy, const ZSTD_ParamSwitch_e mode) {
|
|
assert(mode != ZSTD_ps_auto);
|
|
return ZSTD_rust_params_rowMatchFinderUsed((int)strategy, (int)mode);
|
|
}
|
|
|
|
/* Returns row matchfinder usage given an initial mode and cParams */
|
|
static ZSTD_ParamSwitch_e ZSTD_resolveRowMatchFinderMode(ZSTD_ParamSwitch_e mode,
|
|
const ZSTD_compressionParameters* const cParams) {
|
|
return (ZSTD_ParamSwitch_e)ZSTD_rust_params_resolveRowMatchFinderMode(
|
|
(int)mode, *cParams);
|
|
}
|
|
|
|
/* Returns block splitter usage (generally speaking, when using slower/stronger compression modes) */
|
|
static ZSTD_ParamSwitch_e ZSTD_resolveBlockSplitterMode(ZSTD_ParamSwitch_e mode,
|
|
const ZSTD_compressionParameters* const cParams) {
|
|
return (ZSTD_ParamSwitch_e)ZSTD_rust_params_resolveBlockSplitterMode(
|
|
(int)mode, *cParams);
|
|
}
|
|
|
|
/* Returns 1 if the arguments indicate that we should allocate a chainTable, 0 otherwise */
|
|
static int ZSTD_allocateChainTable(const ZSTD_strategy strategy,
|
|
const ZSTD_ParamSwitch_e useRowMatchFinder,
|
|
const U32 forDDSDict) {
|
|
assert(useRowMatchFinder != ZSTD_ps_auto);
|
|
return ZSTD_rust_params_allocateChainTable(
|
|
(int)strategy, (int)useRowMatchFinder, (int)forDDSDict);
|
|
}
|
|
|
|
/* Returns ZSTD_ps_enable if compression parameters are such that we should
|
|
* enable long distance matching (wlog >= 27, strategy >= btopt).
|
|
* Returns ZSTD_ps_disable otherwise.
|
|
*/
|
|
static ZSTD_ParamSwitch_e ZSTD_resolveEnableLdm(ZSTD_ParamSwitch_e mode,
|
|
const ZSTD_compressionParameters* const cParams) {
|
|
return (ZSTD_ParamSwitch_e)ZSTD_rust_params_resolveEnableLdm(
|
|
(int)mode, *cParams);
|
|
}
|
|
|
|
static int ZSTD_resolveExternalSequenceValidation(int mode) {
|
|
return ZSTD_rust_params_resolveExternalSequenceValidation(mode);
|
|
}
|
|
|
|
/* Resolves maxBlockSize to the default if no value is present. */
|
|
static size_t ZSTD_resolveMaxBlockSize(size_t maxBlockSize) {
|
|
return ZSTD_rust_params_resolveMaxBlockSize(maxBlockSize);
|
|
}
|
|
|
|
static ZSTD_ParamSwitch_e ZSTD_resolveExternalRepcodeSearch(ZSTD_ParamSwitch_e value, int cLevel) {
|
|
return (ZSTD_ParamSwitch_e)ZSTD_rust_params_resolveExternalRepcodeSearch(
|
|
(int)value, cLevel);
|
|
}
|
|
|
|
/* Returns 1 if compression parameters are such that CDict hashtable and chaintable indices are tagged.
|
|
* If so, the tags need to be removed in ZSTD_resetCCtx_byCopyingCDict. */
|
|
static int ZSTD_CDictIndicesAreTagged(const ZSTD_compressionParameters* const cParams) {
|
|
return ZSTD_rust_params_cdictIndicesAreTagged(*cParams);
|
|
}
|
|
|
|
static ZSTD_CCtx_params ZSTD_makeCCtxParamsFromCParams(
|
|
ZSTD_compressionParameters cParams)
|
|
{
|
|
ZSTD_CCtx_params cctxParams;
|
|
/* should not matter, as all cParams are presumed properly defined */
|
|
ZSTD_CCtxParams_init(&cctxParams, ZSTD_CLEVEL_DEFAULT);
|
|
cctxParams.cParams = cParams;
|
|
|
|
/* Adjust advanced params according to cParams */
|
|
cctxParams.ldmParams.enableLdm = ZSTD_resolveEnableLdm(cctxParams.ldmParams.enableLdm, &cParams);
|
|
if (cctxParams.ldmParams.enableLdm == ZSTD_ps_enable) {
|
|
ZSTD_ldm_adjustParameters(&cctxParams.ldmParams, &cParams);
|
|
assert(cctxParams.ldmParams.hashLog >= cctxParams.ldmParams.bucketSizeLog);
|
|
assert(cctxParams.ldmParams.hashRateLog < 32);
|
|
}
|
|
cctxParams.postBlockSplitter = ZSTD_resolveBlockSplitterMode(cctxParams.postBlockSplitter, &cParams);
|
|
cctxParams.useRowMatchFinder = ZSTD_resolveRowMatchFinderMode(cctxParams.useRowMatchFinder, &cParams);
|
|
cctxParams.validateSequences = ZSTD_resolveExternalSequenceValidation(cctxParams.validateSequences);
|
|
cctxParams.maxBlockSize = ZSTD_resolveMaxBlockSize(cctxParams.maxBlockSize);
|
|
cctxParams.searchForExternalRepcodes = ZSTD_resolveExternalRepcodeSearch(cctxParams.searchForExternalRepcodes,
|
|
cctxParams.compressionLevel);
|
|
assert(!ZSTD_checkCParams(cParams));
|
|
return cctxParams;
|
|
}
|
|
|
|
static ZSTD_CCtx_params* ZSTD_createCCtxParams_advanced(
|
|
ZSTD_customMem customMem)
|
|
{
|
|
return ZSTD_rust_createCCtxParams(customMem);
|
|
}
|
|
|
|
ZSTD_CCtx_params* ZSTD_createCCtxParams(void)
|
|
{
|
|
return ZSTD_createCCtxParams_advanced(ZSTD_defaultCMem);
|
|
}
|
|
|
|
size_t ZSTD_freeCCtxParams(ZSTD_CCtx_params* params)
|
|
{
|
|
return ZSTD_rust_freeCCtxParams(params);
|
|
}
|
|
|
|
#define ZSTD_NO_CLEVEL 0
|
|
|
|
/**
|
|
* Initializes `cctxParams` from `params` and `compressionLevel`.
|
|
* @param compressionLevel If params are derived from a compression level then that compression level, otherwise ZSTD_NO_CLEVEL.
|
|
*/
|
|
static void
|
|
ZSTD_CCtxParams_init_internal(ZSTD_CCtx_params* cctxParams,
|
|
const ZSTD_parameters* params,
|
|
int compressionLevel)
|
|
{
|
|
assert(!ZSTD_checkCParams(params->cParams));
|
|
ZSTD_memset(cctxParams, 0, sizeof(*cctxParams));
|
|
cctxParams->cParams = params->cParams;
|
|
cctxParams->fParams = params->fParams;
|
|
/* Should not matter, as all cParams are presumed properly defined.
|
|
* But, set it for tracing anyway.
|
|
*/
|
|
cctxParams->compressionLevel = compressionLevel;
|
|
cctxParams->useRowMatchFinder = ZSTD_resolveRowMatchFinderMode(cctxParams->useRowMatchFinder, ¶ms->cParams);
|
|
cctxParams->postBlockSplitter = ZSTD_resolveBlockSplitterMode(cctxParams->postBlockSplitter, ¶ms->cParams);
|
|
cctxParams->ldmParams.enableLdm = ZSTD_resolveEnableLdm(cctxParams->ldmParams.enableLdm, ¶ms->cParams);
|
|
cctxParams->validateSequences = ZSTD_resolveExternalSequenceValidation(cctxParams->validateSequences);
|
|
cctxParams->maxBlockSize = ZSTD_resolveMaxBlockSize(cctxParams->maxBlockSize);
|
|
cctxParams->searchForExternalRepcodes = ZSTD_resolveExternalRepcodeSearch(cctxParams->searchForExternalRepcodes, compressionLevel);
|
|
DEBUGLOG(4, "ZSTD_CCtxParams_init_internal: useRowMatchFinder=%d, useBlockSplitter=%d ldm=%d",
|
|
cctxParams->useRowMatchFinder, cctxParams->postBlockSplitter, cctxParams->ldmParams.enableLdm);
|
|
}
|
|
|
|
size_t ZSTD_CCtxParams_init_advanced(ZSTD_CCtx_params* cctxParams, ZSTD_parameters params)
|
|
{
|
|
return ZSTD_rust_CCtxParams_init_advanced(cctxParams, params);
|
|
}
|
|
|
|
/**
|
|
* Sets cctxParams' cParams and fParams from params, but otherwise leaves them alone.
|
|
* @param params Validated zstd parameters.
|
|
*/
|
|
static void ZSTD_CCtxParams_setZstdParams(
|
|
ZSTD_CCtx_params* cctxParams, const ZSTD_parameters* params)
|
|
{
|
|
assert(!ZSTD_checkCParams(params->cParams));
|
|
ZSTD_rust_CCtxParams_setZstdParams(cctxParams, params);
|
|
}
|
|
|
|
ZSTD_bounds ZSTD_cParam_getBounds(ZSTD_cParameter param)
|
|
{
|
|
return ZSTD_rust_cctx_params_get_bounds((int)param);
|
|
}
|
|
|
|
int ZSTD_rust_cctx_params_is_multithreaded(void)
|
|
{
|
|
#ifdef ZSTD_MULTITHREAD
|
|
return 1;
|
|
#else
|
|
return 0;
|
|
#endif
|
|
}
|
|
|
|
int ZSTD_rust_cctx_params_nb_workers_max(void)
|
|
{
|
|
#ifdef ZSTD_MULTITHREAD
|
|
return ZSTDMT_NBWORKERS_MAX;
|
|
#else
|
|
return 0;
|
|
#endif
|
|
}
|
|
|
|
int ZSTD_rust_cctx_params_job_size_min(void)
|
|
{
|
|
#ifdef ZSTD_MULTITHREAD
|
|
return ZSTDMT_JOBSIZE_MIN;
|
|
#else
|
|
return 0;
|
|
#endif
|
|
}
|
|
|
|
int ZSTD_rust_cctx_params_job_size_max(void)
|
|
{
|
|
#ifdef ZSTD_MULTITHREAD
|
|
return ZSTDMT_JOBSIZE_MAX;
|
|
#else
|
|
return 0;
|
|
#endif
|
|
}
|
|
|
|
#define BOUNDCHECK(cParam, val) \
|
|
do { \
|
|
RETURN_ERROR_IF(!ZSTD_cParam_withinBounds(cParam,val), \
|
|
parameter_outOfBound, "Param out of bounds"); \
|
|
} while (0)
|
|
|
|
|
|
static int ZSTD_isUpdateAuthorized(ZSTD_cParameter param)
|
|
{
|
|
return ZSTD_rust_isUpdateAuthorized((int)param);
|
|
}
|
|
|
|
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, "can only set params in cctx init stage");
|
|
} }
|
|
|
|
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_enableDedicatedDictSearch:
|
|
case ZSTD_c_enableLongDistanceMatching:
|
|
case ZSTD_c_ldmHashLog:
|
|
case ZSTD_c_ldmMinMatch:
|
|
case ZSTD_c_ldmBucketSizeLog:
|
|
case ZSTD_c_targetCBlockSize:
|
|
case ZSTD_c_srcSizeHint:
|
|
case ZSTD_c_stableInBuffer:
|
|
case ZSTD_c_stableOutBuffer:
|
|
case ZSTD_c_blockDelimiters:
|
|
case ZSTD_c_validateSequences:
|
|
case ZSTD_c_splitAfterSequences:
|
|
case ZSTD_c_blockSplitterLevel:
|
|
case ZSTD_c_useRowMatchFinder:
|
|
case ZSTD_c_deterministicRefPrefix:
|
|
case ZSTD_c_prefetchCDictTables:
|
|
case ZSTD_c_enableSeqProducerFallback:
|
|
case ZSTD_c_maxBlockSize:
|
|
case ZSTD_c_repcodeResolution:
|
|
break;
|
|
|
|
default: RETURN_ERROR(parameter_unsupported, "unknown parameter");
|
|
}
|
|
{ size_t const result = ZSTD_CCtxParams_setParameter(&cctx->requestedParams, param, value);
|
|
if (!ZSTD_isError(result) && param == ZSTD_c_maxBlockSize) {
|
|
cctx->rustSimpleCompress2MaxBlockSizeSet = 1;
|
|
}
|
|
return result;
|
|
}
|
|
}
|
|
|
|
size_t ZSTD_CCtx_getParameter(ZSTD_CCtx const* cctx, ZSTD_cParameter param, int* value)
|
|
{
|
|
return ZSTD_CCtxParams_getParameter(&cctx->requestedParams, param, value);
|
|
}
|
|
|
|
/** 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,
|
|
"The context is in the wrong stage!");
|
|
RETURN_ERROR_IF(cctx->cdict, stage_wrong,
|
|
"Can't override parameters with cdict attached (some must "
|
|
"be inherited from the cdict).");
|
|
|
|
cctx->requestedParams = *params;
|
|
return 0;
|
|
}
|
|
|
|
size_t ZSTD_CCtx_setCParams(ZSTD_CCtx* cctx, ZSTD_compressionParameters cparams)
|
|
{
|
|
ZSTD_STATIC_ASSERT(sizeof(cparams) == 7 * 4 /* all params are listed below */);
|
|
DEBUGLOG(4, "ZSTD_CCtx_setCParams");
|
|
/* only update if all parameters are valid */
|
|
FORWARD_IF_ERROR(ZSTD_checkCParams(cparams), "");
|
|
FORWARD_IF_ERROR(ZSTD_CCtx_setParameter(cctx, ZSTD_c_windowLog, (int)cparams.windowLog), "");
|
|
FORWARD_IF_ERROR(ZSTD_CCtx_setParameter(cctx, ZSTD_c_chainLog, (int)cparams.chainLog), "");
|
|
FORWARD_IF_ERROR(ZSTD_CCtx_setParameter(cctx, ZSTD_c_hashLog, (int)cparams.hashLog), "");
|
|
FORWARD_IF_ERROR(ZSTD_CCtx_setParameter(cctx, ZSTD_c_searchLog, (int)cparams.searchLog), "");
|
|
FORWARD_IF_ERROR(ZSTD_CCtx_setParameter(cctx, ZSTD_c_minMatch, (int)cparams.minMatch), "");
|
|
FORWARD_IF_ERROR(ZSTD_CCtx_setParameter(cctx, ZSTD_c_targetLength, (int)cparams.targetLength), "");
|
|
FORWARD_IF_ERROR(ZSTD_CCtx_setParameter(cctx, ZSTD_c_strategy, (int)cparams.strategy), "");
|
|
return 0;
|
|
}
|
|
|
|
size_t ZSTD_CCtx_setFParams(ZSTD_CCtx* cctx, ZSTD_frameParameters fparams)
|
|
{
|
|
ZSTD_STATIC_ASSERT(sizeof(fparams) == 3 * 4 /* all params are listed below */);
|
|
DEBUGLOG(4, "ZSTD_CCtx_setFParams");
|
|
FORWARD_IF_ERROR(ZSTD_CCtx_setParameter(cctx, ZSTD_c_contentSizeFlag, fparams.contentSizeFlag != 0), "");
|
|
FORWARD_IF_ERROR(ZSTD_CCtx_setParameter(cctx, ZSTD_c_checksumFlag, fparams.checksumFlag != 0), "");
|
|
FORWARD_IF_ERROR(ZSTD_CCtx_setParameter(cctx, ZSTD_c_dictIDFlag, fparams.noDictIDFlag == 0), "");
|
|
return 0;
|
|
}
|
|
|
|
size_t ZSTD_CCtx_setParams(ZSTD_CCtx* cctx, ZSTD_parameters params)
|
|
{
|
|
DEBUGLOG(4, "ZSTD_CCtx_setParams");
|
|
/* First check cParams, because we want to update all or none. */
|
|
FORWARD_IF_ERROR(ZSTD_checkCParams(params.cParams), "");
|
|
/* Next set fParams, because this could fail if the cctx isn't in init stage. */
|
|
FORWARD_IF_ERROR(ZSTD_CCtx_setFParams(cctx, params.fParams), "");
|
|
/* Finally set cParams, which should succeed. */
|
|
FORWARD_IF_ERROR(ZSTD_CCtx_setCParams(cctx, params.cParams), "");
|
|
return 0;
|
|
}
|
|
|
|
size_t ZSTD_CCtx_setPledgedSrcSize(ZSTD_CCtx* cctx, unsigned long long pledgedSrcSize)
|
|
{
|
|
DEBUGLOG(4, "ZSTD_CCtx_setPledgedSrcSize to %llu bytes", pledgedSrcSize);
|
|
return ZSTD_rust_setPledgedSrcSize((int)cctx->streamStage, pledgedSrcSize,
|
|
&cctx->pledgedSrcSizePlusOne);
|
|
}
|
|
|
|
static ZSTD_compressionParameters ZSTD_dedicatedDictSearch_getCParams(
|
|
int const compressionLevel,
|
|
size_t const dictSize);
|
|
static void ZSTD_dedicatedDictSearch_revertCParams(
|
|
ZSTD_compressionParameters* cParams);
|
|
|
|
/**
|
|
* Initializes the local dictionary using requested parameters.
|
|
* NOTE: Initialization does not employ the pledged src size,
|
|
* because the dictionary may be used for multiple compressions.
|
|
*/
|
|
static size_t ZSTD_initLocalDict(ZSTD_CCtx* cctx)
|
|
{
|
|
ZSTD_localDict* const dl = &cctx->localDict;
|
|
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) {
|
|
/* Local dictionary already initialized. */
|
|
assert(cctx->cdict == dl->cdict);
|
|
return 0;
|
|
}
|
|
assert(dl->dictSize > 0);
|
|
assert(cctx->cdict == NULL);
|
|
assert(cctx->prefixDict.dict == NULL);
|
|
|
|
dl->cdict = ZSTD_createCDict_advanced2(
|
|
dl->dict,
|
|
dl->dictSize,
|
|
ZSTD_dlm_byRef,
|
|
dl->dictContentType,
|
|
&cctx->requestedParams,
|
|
cctx->customMem);
|
|
RETURN_ERROR_IF(!dl->cdict, memory_allocation, "ZSTD_createCDict_advanced failed");
|
|
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)
|
|
{
|
|
DEBUGLOG(4, "ZSTD_CCtx_loadDictionary_advanced (size: %u)", (U32)dictSize);
|
|
RETURN_ERROR_IF(cctx->streamStage != zcss_init, stage_wrong,
|
|
"Can't load a dictionary when cctx is not in init stage.");
|
|
ZSTD_clearAllDicts(cctx); /* erase any previously set dictionary */
|
|
if (dict == NULL || dictSize == 0) /* no dictionary */
|
|
return 0;
|
|
if (dictLoadMethod == ZSTD_dlm_byRef) {
|
|
cctx->localDict.dict = dict;
|
|
} else {
|
|
/* copy dictionary content inside CCtx to own its lifetime */
|
|
void* dictBuffer;
|
|
RETURN_ERROR_IF(cctx->staticSize, memory_allocation,
|
|
"static CCtx can't allocate for an internal copy of dictionary");
|
|
dictBuffer = ZSTD_customMalloc(dictSize, cctx->customMem);
|
|
RETURN_ERROR_IF(dictBuffer==NULL, memory_allocation,
|
|
"allocation failed for dictionary content");
|
|
ZSTD_memcpy(dictBuffer, dict, dictSize);
|
|
cctx->localDict.dictBuffer = dictBuffer; /* owned ptr to free */
|
|
cctx->localDict.dict = dictBuffer; /* read-only reference */
|
|
}
|
|
cctx->localDict.dictSize = dictSize;
|
|
cctx->localDict.dictContentType = dictContentType;
|
|
return 0;
|
|
}
|
|
|
|
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);
|
|
}
|
|
|
|
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,
|
|
"Can't ref a dict when ctx not in init stage.");
|
|
/* Free the existing local cdict (if any) to save memory. */
|
|
ZSTD_clearAllDicts(cctx);
|
|
cctx->cdict = cdict;
|
|
return 0;
|
|
}
|
|
|
|
size_t ZSTD_CCtx_refThreadPool(ZSTD_CCtx* cctx, ZSTD_threadPool* pool)
|
|
{
|
|
RETURN_ERROR_IF(cctx->streamStage != zcss_init, stage_wrong,
|
|
"Can't ref a pool when ctx not in init stage.");
|
|
cctx->pool = pool;
|
|
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,
|
|
"Can't ref a prefix when ctx not in init stage.");
|
|
ZSTD_clearAllDicts(cctx);
|
|
if (prefix != NULL && prefixSize > 0) {
|
|
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)
|
|
{
|
|
cctx->rustSimpleCompress2Completed = 0;
|
|
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,
|
|
"Reset parameters is only possible during init stage.");
|
|
ZSTD_clearAllDicts(cctx);
|
|
cctx->rustSimpleCompress2MaxBlockSizeSet = 0;
|
|
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)
|
|
{
|
|
return ZSTD_rust_params_checkCParams(cParams);
|
|
}
|
|
|
|
/** ZSTD_clampCParams() :
|
|
* make CParam values within valid range.
|
|
* @return : valid CParams */
|
|
static ZSTD_compressionParameters
|
|
ZSTD_clampCParams(ZSTD_compressionParameters cParams)
|
|
{
|
|
return ZSTD_rust_params_clampCParams(cParams);
|
|
}
|
|
|
|
/** ZSTD_cycleLog() :
|
|
* condition for correct operation : hashLog > 1 */
|
|
U32 ZSTD_cycleLog(U32 hashLog, ZSTD_strategy strat)
|
|
{
|
|
return ZSTD_rust_params_cycleLog(hashLog, (int)strat);
|
|
}
|
|
|
|
static U32 ZSTD_getCParamsExclusionMask(void);
|
|
|
|
/** 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.
|
|
* `mode` is the mode for parameter adjustment. See docs for `ZSTD_CParamMode_e`.
|
|
* note : `srcSize==0` means 0!
|
|
* 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,
|
|
ZSTD_CParamMode_e mode,
|
|
ZSTD_ParamSwitch_e useRowMatchFinder)
|
|
{
|
|
assert(ZSTD_checkCParams(cPar)==0);
|
|
|
|
/* Cascade the selected strategy down to the next-highest one built into
|
|
* this binary. The C preprocessor constructs the mask so Rust does not
|
|
* need to mirror this build's active ZSTD_EXCLUDE_* definitions. */
|
|
cPar = ZSTD_rust_params_applyStrategyExclusions(
|
|
cPar, ZSTD_getCParamsExclusionMask());
|
|
|
|
/* The remaining adjustment logic is context-free and lives in Rust. The
|
|
* short-cache and row-hash tag widths the leaf assumes are fixed
|
|
* private-header constants; keep them checked here. */
|
|
ZSTD_STATIC_ASSERT(ZSTD_SHORT_CACHE_TAG_BITS == 8);
|
|
ZSTD_STATIC_ASSERT(ZSTD_ROW_HASH_TAG_BITS == 8);
|
|
return ZSTD_rust_params_adjustCParams(cPar, (U64)srcSize, dictSize,
|
|
(int)mode, (int)useRowMatchFinder);
|
|
}
|
|
|
|
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) */
|
|
if (srcSize == 0) srcSize = ZSTD_CONTENTSIZE_UNKNOWN;
|
|
return ZSTD_adjustCParams_internal(cPar, srcSize, dictSize, ZSTD_cpm_unknown, ZSTD_ps_auto);
|
|
}
|
|
|
|
static ZSTD_compressionParameters ZSTD_getCParams_internal(int compressionLevel, unsigned long long srcSizeHint, size_t dictSize, ZSTD_CParamMode_e mode);
|
|
static ZSTD_parameters ZSTD_getParams_internal(int compressionLevel, unsigned long long srcSizeHint, size_t dictSize, ZSTD_CParamMode_e mode);
|
|
|
|
enum {
|
|
ZSTD_RUST_PARAMS_EXCLUDE_BTULTRA = 1u << 0,
|
|
ZSTD_RUST_PARAMS_EXCLUDE_BTOPT = 1u << 1,
|
|
ZSTD_RUST_PARAMS_EXCLUDE_BTLAZY2 = 1u << 2,
|
|
ZSTD_RUST_PARAMS_EXCLUDE_LAZY2 = 1u << 3,
|
|
ZSTD_RUST_PARAMS_EXCLUDE_LAZY = 1u << 4,
|
|
ZSTD_RUST_PARAMS_EXCLUDE_GREEDY = 1u << 5,
|
|
ZSTD_RUST_PARAMS_EXCLUDE_DFAST = 1u << 6
|
|
};
|
|
|
|
static U32 ZSTD_getCParamsExclusionMask(void)
|
|
{
|
|
U32 mask = 0;
|
|
#ifdef ZSTD_EXCLUDE_BTULTRA_BLOCK_COMPRESSOR
|
|
mask |= ZSTD_RUST_PARAMS_EXCLUDE_BTULTRA;
|
|
#endif
|
|
#ifdef ZSTD_EXCLUDE_BTOPT_BLOCK_COMPRESSOR
|
|
mask |= ZSTD_RUST_PARAMS_EXCLUDE_BTOPT;
|
|
#endif
|
|
#ifdef ZSTD_EXCLUDE_BTLAZY2_BLOCK_COMPRESSOR
|
|
mask |= ZSTD_RUST_PARAMS_EXCLUDE_BTLAZY2;
|
|
#endif
|
|
#ifdef ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR
|
|
mask |= ZSTD_RUST_PARAMS_EXCLUDE_LAZY2;
|
|
#endif
|
|
#ifdef ZSTD_EXCLUDE_LAZY_BLOCK_COMPRESSOR
|
|
mask |= ZSTD_RUST_PARAMS_EXCLUDE_LAZY;
|
|
#endif
|
|
#ifdef ZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR
|
|
mask |= ZSTD_RUST_PARAMS_EXCLUDE_GREEDY;
|
|
#endif
|
|
#ifdef ZSTD_EXCLUDE_DFAST_BLOCK_COMPRESSOR
|
|
mask |= ZSTD_RUST_PARAMS_EXCLUDE_DFAST;
|
|
#endif
|
|
return mask;
|
|
}
|
|
|
|
ZSTD_compressionParameters ZSTD_getCParamsFromCCtxParams(
|
|
const ZSTD_CCtx_params* CCtxParams, U64 srcSizeHint, size_t dictSize, ZSTD_CParamMode_e mode)
|
|
{
|
|
return ZSTD_rust_params_getCParamsFromCCtxParams(
|
|
CCtxParams->compressionLevel, CCtxParams->srcSizeHint,
|
|
srcSizeHint, dictSize, (int)mode,
|
|
(int)CCtxParams->ldmParams.enableLdm,
|
|
ZSTD_LDM_DEFAULT_WINDOW_LOG, CCtxParams->cParams,
|
|
(int)CCtxParams->useRowMatchFinder,
|
|
ZSTD_getCParamsExclusionMask());
|
|
}
|
|
|
|
static size_t
|
|
ZSTD_sizeof_matchState(const ZSTD_compressionParameters* const cParams,
|
|
const ZSTD_ParamSwitch_e useRowMatchFinder,
|
|
const int enableDedicatedDictSearch,
|
|
const U32 forCCtx)
|
|
{
|
|
ZSTD_rustMatchStateSizing sizing;
|
|
sizing.hashLog3Max = ZSTD_HASHLOG3_MAX;
|
|
sizing.matchTSize = sizeof(ZSTD_match_t);
|
|
sizing.optimalTSize = sizeof(ZSTD_optimal_t);
|
|
sizing.asanRedzoneSize = ZSTD_RUST_ASAN_REDZONE_SIZE;
|
|
|
|
/* The Rust leaf hardcodes the frozen format bounds and workspace rules;
|
|
* keep them checked against the private headers here. */
|
|
ZSTD_STATIC_ASSERT(MaxML == 52 && MaxLL == 35 && MaxOff == 31);
|
|
ZSTD_STATIC_ASSERT(Litbits == 8 && ZSTD_OPT_SIZE == 4099);
|
|
ZSTD_STATIC_ASSERT(ZSTD_CWKSP_ALIGNMENT_BYTES == 64);
|
|
/* tables are guaranteed to be sized in multiples of 64 bytes (or 16 uint32_t) */
|
|
ZSTD_STATIC_ASSERT(ZSTD_HASHLOG_MIN >= 4 && ZSTD_WINDOWLOG_MIN >= 4 && ZSTD_CHAINLOG_MIN >= 4);
|
|
assert(useRowMatchFinder != ZSTD_ps_auto);
|
|
|
|
return ZSTD_rust_params_estimateMatchStateSize(*cParams,
|
|
(int)useRowMatchFinder,
|
|
enableDedicatedDictSearch,
|
|
forCCtx, &sizing);
|
|
}
|
|
|
|
/* Helper function for calculating memory requirements.
|
|
* Gives a tighter bound than ZSTD_sequenceBound() by taking minMatch into account. */
|
|
static size_t ZSTD_maxNbSeq(size_t blockSize, unsigned minMatch, int useSequenceProducer) {
|
|
return ZSTD_rust_params_maxNbSeq(blockSize, minMatch, useSequenceProducer);
|
|
}
|
|
|
|
static size_t ZSTD_estimateCCtxSize_usingCCtxParams_internal(
|
|
const ZSTD_compressionParameters* cParams,
|
|
const ldmParams_t* ldmParams,
|
|
const int isStatic,
|
|
const ZSTD_ParamSwitch_e useRowMatchFinder,
|
|
const size_t buffInSize,
|
|
const size_t buffOutSize,
|
|
const U64 pledgedSrcSize,
|
|
int useSequenceProducer,
|
|
size_t maxBlockSize)
|
|
{
|
|
size_t const windowSize = (size_t) BOUNDED(1ULL, 1ULL << cParams->windowLog, pledgedSrcSize);
|
|
size_t const blockSize = MIN(ZSTD_resolveMaxBlockSize(maxBlockSize), windowSize);
|
|
size_t const maxNbSeq = ZSTD_maxNbSeq(blockSize, cParams->minMatch, useSequenceProducer);
|
|
size_t const tokenSpace = ZSTD_cwksp_alloc_size(WILDCOPY_OVERLENGTH + blockSize)
|
|
+ ZSTD_cwksp_aligned64_alloc_size(maxNbSeq * sizeof(SeqDef))
|
|
+ 3 * ZSTD_cwksp_alloc_size(maxNbSeq * sizeof(BYTE));
|
|
size_t const tmpWorkSpace = ZSTD_cwksp_alloc_size(TMP_WORKSPACE_SIZE);
|
|
size_t const blockStateSpace = 2 * ZSTD_cwksp_alloc_size(sizeof(ZSTD_compressedBlockState_t));
|
|
size_t const matchStateSize = ZSTD_sizeof_matchState(cParams, useRowMatchFinder, /* enableDedicatedDictSearch */ 0, /* forCCtx */ 1);
|
|
|
|
size_t const ldmSpace = ZSTD_ldm_getTableSize(*ldmParams);
|
|
size_t const maxNbLdmSeq = ZSTD_ldm_getMaxNbSeq(*ldmParams, blockSize);
|
|
size_t const ldmSeqSpace = ldmParams->enableLdm == ZSTD_ps_enable ?
|
|
ZSTD_cwksp_aligned64_alloc_size(maxNbLdmSeq * sizeof(rawSeq)) : 0;
|
|
|
|
|
|
size_t const bufferSpace = ZSTD_cwksp_alloc_size(buffInSize)
|
|
+ ZSTD_cwksp_alloc_size(buffOutSize);
|
|
|
|
size_t const cctxSpace = isStatic ? ZSTD_cwksp_alloc_size(sizeof(ZSTD_CCtx)) : 0;
|
|
|
|
size_t const maxNbExternalSeq = ZSTD_sequenceBound(blockSize);
|
|
size_t const externalSeqSpace = useSequenceProducer
|
|
? ZSTD_cwksp_aligned64_alloc_size(maxNbExternalSeq * sizeof(ZSTD_Sequence))
|
|
: 0;
|
|
|
|
size_t const neededSpace = ZSTD_rust_estimateWorkspaceSize(
|
|
cctxSpace, tmpWorkSpace, blockStateSpace, ldmSpace, ldmSeqSpace,
|
|
matchStateSize, tokenSpace, bufferSpace, externalSeqSpace);
|
|
|
|
DEBUGLOG(5, "estimate workspace : %u", (U32)neededSpace);
|
|
return neededSpace;
|
|
}
|
|
|
|
size_t ZSTD_estimateCCtxSize_usingCCtxParams(const ZSTD_CCtx_params* params)
|
|
{
|
|
ZSTD_compressionParameters const cParams =
|
|
ZSTD_getCParamsFromCCtxParams(params, ZSTD_CONTENTSIZE_UNKNOWN, 0, ZSTD_cpm_noAttachDict);
|
|
ZSTD_ParamSwitch_e const useRowMatchFinder = ZSTD_resolveRowMatchFinderMode(params->useRowMatchFinder,
|
|
&cParams);
|
|
|
|
RETURN_ERROR_IF(params->nbWorkers > 0, GENERIC, "Estimate CCtx size is supported for single-threaded compression only.");
|
|
/* estimateCCtxSize is for one-shot compression. So no buffers should
|
|
* be needed. However, we still allocate two 0-sized buffers, which can
|
|
* take space under ASAN. */
|
|
return ZSTD_estimateCCtxSize_usingCCtxParams_internal(
|
|
&cParams, ¶ms->ldmParams, 1, useRowMatchFinder, 0, 0, ZSTD_CONTENTSIZE_UNKNOWN, ZSTD_hasExtSeqProd(params), params->maxBlockSize);
|
|
}
|
|
|
|
size_t ZSTD_estimateCCtxSize_usingCParams(ZSTD_compressionParameters cParams)
|
|
{
|
|
ZSTD_CCtx_params initialParams = ZSTD_makeCCtxParamsFromCParams(cParams);
|
|
if (ZSTD_rowMatchFinderSupported(cParams.strategy)) {
|
|
/* Pick bigger of not using and using row-based matchfinder for greedy and lazy strategies */
|
|
size_t noRowCCtxSize;
|
|
size_t rowCCtxSize;
|
|
initialParams.useRowMatchFinder = ZSTD_ps_disable;
|
|
noRowCCtxSize = ZSTD_estimateCCtxSize_usingCCtxParams(&initialParams);
|
|
initialParams.useRowMatchFinder = ZSTD_ps_enable;
|
|
rowCCtxSize = ZSTD_estimateCCtxSize_usingCCtxParams(&initialParams);
|
|
return MAX(noRowCCtxSize, rowCCtxSize);
|
|
} else {
|
|
return ZSTD_estimateCCtxSize_usingCCtxParams(&initialParams);
|
|
}
|
|
}
|
|
|
|
static size_t ZSTD_estimateCCtxSize_internal(int compressionLevel)
|
|
{
|
|
int tier = 0;
|
|
size_t estimates[4];
|
|
static const unsigned long long srcSizeTiers[4] = {16 KB, 128 KB, 256 KB, ZSTD_CONTENTSIZE_UNKNOWN};
|
|
for (; tier < 4; ++tier) {
|
|
/* Choose the set of cParams for a given level across all srcSizes that give the largest cctxSize */
|
|
ZSTD_compressionParameters const cParams = ZSTD_getCParams_internal(compressionLevel, srcSizeTiers[tier], 0, ZSTD_cpm_noAttachDict);
|
|
estimates[tier] = ZSTD_estimateCCtxSize_usingCParams(cParams);
|
|
}
|
|
return ZSTD_rust_maxEstimateCCtxSize(
|
|
estimates[0], estimates[1], estimates[2], estimates[3]);
|
|
}
|
|
|
|
size_t ZSTD_estimateCCtxSize(int compressionLevel)
|
|
{
|
|
int level;
|
|
size_t memBudget = 0;
|
|
for (level=MIN(compressionLevel, 1); level<=compressionLevel; level++) {
|
|
/* Ensure monotonically increasing memory usage as compression level increases */
|
|
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, ZSTD_CONTENTSIZE_UNKNOWN, 0, ZSTD_cpm_noAttachDict);
|
|
size_t const blockSize = MIN(ZSTD_resolveMaxBlockSize(params->maxBlockSize), (size_t)1 << cParams.windowLog);
|
|
size_t const inBuffSize = (params->inBufferMode == ZSTD_bm_buffered)
|
|
? ((size_t)1 << cParams.windowLog) + blockSize
|
|
: 0;
|
|
size_t const outBuffSize = (params->outBufferMode == ZSTD_bm_buffered)
|
|
? ZSTD_compressBound(blockSize) + 1
|
|
: 0;
|
|
ZSTD_ParamSwitch_e const useRowMatchFinder = ZSTD_resolveRowMatchFinderMode(params->useRowMatchFinder, ¶ms->cParams);
|
|
|
|
return ZSTD_estimateCCtxSize_usingCCtxParams_internal(
|
|
&cParams, ¶ms->ldmParams, 1, useRowMatchFinder, inBuffSize, outBuffSize,
|
|
ZSTD_CONTENTSIZE_UNKNOWN, ZSTD_hasExtSeqProd(params), params->maxBlockSize);
|
|
}
|
|
}
|
|
|
|
size_t ZSTD_estimateCStreamSize_usingCParams(ZSTD_compressionParameters cParams)
|
|
{
|
|
ZSTD_CCtx_params initialParams = ZSTD_makeCCtxParamsFromCParams(cParams);
|
|
if (ZSTD_rowMatchFinderSupported(cParams.strategy)) {
|
|
/* Pick bigger of not using and using row-based matchfinder for greedy and lazy strategies */
|
|
size_t noRowCCtxSize;
|
|
size_t rowCCtxSize;
|
|
initialParams.useRowMatchFinder = ZSTD_ps_disable;
|
|
noRowCCtxSize = ZSTD_estimateCStreamSize_usingCCtxParams(&initialParams);
|
|
initialParams.useRowMatchFinder = ZSTD_ps_enable;
|
|
rowCCtxSize = ZSTD_estimateCStreamSize_usingCCtxParams(&initialParams);
|
|
return MAX(noRowCCtxSize, rowCCtxSize);
|
|
} else {
|
|
return ZSTD_estimateCStreamSize_usingCCtxParams(&initialParams);
|
|
}
|
|
}
|
|
|
|
static size_t ZSTD_estimateCStreamSize_internal(int compressionLevel)
|
|
{
|
|
ZSTD_compressionParameters const cParams = ZSTD_getCParams_internal(compressionLevel, ZSTD_CONTENTSIZE_UNKNOWN, 0, ZSTD_cpm_noAttachDict);
|
|
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
|
|
{
|
|
size_t const buffered = (cctx->inBuff == NULL) ? 0 :
|
|
cctx->inBuffPos - cctx->inToCompress;
|
|
if (buffered) assert(cctx->inBuffPos >= cctx->inToCompress);
|
|
assert(buffered <= ZSTD_BLOCKSIZE_MAX);
|
|
return ZSTD_rust_frameProgression(cctx->consumedSrcSize, buffered,
|
|
cctx->producedCSize);
|
|
} }
|
|
|
|
/*! 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 void ZSTD_assertEqualCParams(ZSTD_compressionParameters cParams1,
|
|
ZSTD_compressionParameters cParams2)
|
|
{
|
|
ZSTD_rust_params_assertEqualCParams(cParams1, cParams2);
|
|
}
|
|
|
|
void ZSTD_reset_compressedBlockState(ZSTD_compressedBlockState_t* bs)
|
|
{
|
|
ZSTD_rust_resetCompressedBlockState(bs);
|
|
}
|
|
|
|
/*! 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_rust_windowClear((size_t)(ms->window.nextSrc - ms->window.base),
|
|
&ms->window.lowLimit, &ms->window.dictLimit);
|
|
|
|
ms->nextToUpdate = ms->window.dictLimit;
|
|
ms->loadedDictEnd = 0;
|
|
ms->opt.litLengthSum = 0; /* force reset of btopt stats */
|
|
ms->dictMatchState = NULL;
|
|
}
|
|
|
|
/**
|
|
* Controls, for this matchState reset, whether the tables need to be cleared /
|
|
* prepared for the coming compression (ZSTDcrp_makeClean), or whether the
|
|
* tables can be left unclean (ZSTDcrp_leaveDirty), because we know that a
|
|
* subsequent operation will overwrite the table space anyways (e.g., copying
|
|
* the matchState contents in from a CDict).
|
|
*/
|
|
typedef enum {
|
|
ZSTDcrp_makeClean,
|
|
ZSTDcrp_leaveDirty
|
|
} ZSTD_compResetPolicy_e;
|
|
|
|
/**
|
|
* Controls, for this matchState reset, whether indexing can continue where it
|
|
* left off (ZSTDirp_continue), or whether it needs to be restarted from zero
|
|
* (ZSTDirp_reset).
|
|
*/
|
|
typedef enum {
|
|
ZSTDirp_continue,
|
|
ZSTDirp_reset
|
|
} ZSTD_indexResetPolicy_e;
|
|
|
|
typedef enum {
|
|
ZSTD_resetTarget_CDict,
|
|
ZSTD_resetTarget_CCtx
|
|
} ZSTD_resetTarget_e;
|
|
|
|
/* Mixes in the hashSalt and hashSaltEntropy to create a new hashSalt */
|
|
static void ZSTD_advanceHashSalt(ZSTD_MatchState_t* ms) {
|
|
ms->hashSalt = ZSTD_rust_advanceHashSalt(ms->hashSalt, (U64)ms->hashSaltEntropy);
|
|
}
|
|
|
|
static size_t
|
|
ZSTD_reset_matchState(ZSTD_MatchState_t* ms,
|
|
ZSTD_cwksp* ws,
|
|
const ZSTD_compressionParameters* cParams,
|
|
const ZSTD_ParamSwitch_e useRowMatchFinder,
|
|
const ZSTD_compResetPolicy_e crp,
|
|
const ZSTD_indexResetPolicy_e forceResetIndex,
|
|
const ZSTD_resetTarget_e forWho)
|
|
{
|
|
/* disable chain table allocation for fast or row-based strategies */
|
|
size_t const chainSize = ZSTD_allocateChainTable(cParams->strategy, useRowMatchFinder,
|
|
ms->dedicatedDictSearch && (forWho == ZSTD_resetTarget_CDict))
|
|
? ((size_t)1 << cParams->chainLog)
|
|
: 0;
|
|
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 = hashLog3 ? ((size_t)1) << hashLog3 : 0;
|
|
|
|
DEBUGLOG(4, "reset indices : %u", forceResetIndex == ZSTDirp_reset);
|
|
assert(useRowMatchFinder != ZSTD_ps_auto);
|
|
if (forceResetIndex == ZSTDirp_reset) {
|
|
ZSTD_window_init(&ms->window);
|
|
ZSTD_cwksp_mark_tables_dirty(ws);
|
|
}
|
|
|
|
ms->hashLog3 = hashLog3;
|
|
ms->lazySkipping = 0;
|
|
|
|
ZSTD_invalidateMatchState(ms);
|
|
|
|
assert(!ZSTD_cwksp_reserve_failed(ws)); /* check that allocation hasn't already failed */
|
|
|
|
ZSTD_cwksp_clear_tables(ws);
|
|
|
|
DEBUGLOG(5, "reserving table space");
|
|
/* table Space */
|
|
ms->hashTable = (U32*)ZSTD_cwksp_reserve_table(ws, hSize * sizeof(U32));
|
|
ms->chainTable = (U32*)ZSTD_cwksp_reserve_table(ws, chainSize * sizeof(U32));
|
|
ms->hashTable3 = (U32*)ZSTD_cwksp_reserve_table(ws, h3Size * sizeof(U32));
|
|
RETURN_ERROR_IF(ZSTD_cwksp_reserve_failed(ws), memory_allocation,
|
|
"failed a workspace allocation in ZSTD_reset_matchState");
|
|
|
|
DEBUGLOG(4, "reset table : %u", crp!=ZSTDcrp_leaveDirty);
|
|
if (crp!=ZSTDcrp_leaveDirty) {
|
|
/* reset tables only */
|
|
ZSTD_cwksp_clean_tables(ws);
|
|
}
|
|
|
|
if (ZSTD_rowMatchFinderUsed(cParams->strategy, useRowMatchFinder)) {
|
|
/* Row match finder needs an additional table of hashes ("tags") */
|
|
size_t const tagTableSize = hSize;
|
|
/* We want to generate a new salt in case we reset a Cctx, but we always want to use
|
|
* 0 when we reset a Cdict */
|
|
if(forWho == ZSTD_resetTarget_CCtx) {
|
|
ms->tagTable = (BYTE*) ZSTD_cwksp_reserve_aligned_init_once(ws, tagTableSize);
|
|
ZSTD_advanceHashSalt(ms);
|
|
} else {
|
|
/* When we are not salting we want to always memset the memory */
|
|
ms->tagTable = (BYTE*) ZSTD_cwksp_reserve_aligned64(ws, tagTableSize);
|
|
ZSTD_memset(ms->tagTable, 0, tagTableSize);
|
|
ms->hashSalt = 0;
|
|
}
|
|
{ /* Switch to 32-entry rows if searchLog is 5 (or more) */
|
|
U32 const rowLog = BOUNDED(4, cParams->searchLog, 6);
|
|
assert(cParams->hashLog >= rowLog);
|
|
ms->rowHashLog = cParams->hashLog - rowLog;
|
|
}
|
|
}
|
|
|
|
/* opt parser space */
|
|
if ((forWho == ZSTD_resetTarget_CCtx) && (cParams->strategy >= ZSTD_btopt)) {
|
|
DEBUGLOG(4, "reserving optimal parser space");
|
|
ms->opt.litFreq = (unsigned*)ZSTD_cwksp_reserve_aligned64(ws, (1<<Litbits) * sizeof(unsigned));
|
|
ms->opt.litLengthFreq = (unsigned*)ZSTD_cwksp_reserve_aligned64(ws, (MaxLL+1) * sizeof(unsigned));
|
|
ms->opt.matchLengthFreq = (unsigned*)ZSTD_cwksp_reserve_aligned64(ws, (MaxML+1) * sizeof(unsigned));
|
|
ms->opt.offCodeFreq = (unsigned*)ZSTD_cwksp_reserve_aligned64(ws, (MaxOff+1) * sizeof(unsigned));
|
|
ms->opt.matchTable = (ZSTD_match_t*)ZSTD_cwksp_reserve_aligned64(ws, ZSTD_OPT_SIZE * sizeof(ZSTD_match_t));
|
|
ms->opt.priceTable = (ZSTD_optimal_t*)ZSTD_cwksp_reserve_aligned64(ws, ZSTD_OPT_SIZE * sizeof(ZSTD_optimal_t));
|
|
}
|
|
|
|
ms->cParams = *cParams;
|
|
|
|
RETURN_ERROR_IF(ZSTD_cwksp_reserve_failed(ws), memory_allocation,
|
|
"failed a workspace allocation in ZSTD_reset_matchState");
|
|
return 0;
|
|
}
|
|
|
|
/* 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 ZSTD_rust_indexTooCloseToMax((size_t)(w.nextSrc - w.base));
|
|
}
|
|
|
|
/** ZSTD_dictTooBig():
|
|
* When dictionaries are larger than ZSTD_CHUNKSIZE_MAX they can't be loaded in
|
|
* one go generically. So we ensure that in that case we reset the tables to zero,
|
|
* so that we can load as much of the dictionary as possible.
|
|
*/
|
|
static int ZSTD_dictTooBig(size_t const loadedDictSize)
|
|
{
|
|
return ZSTD_rust_dictTooBig(loadedDictSize);
|
|
}
|
|
|
|
/*! ZSTD_resetCCtx_internal() :
|
|
* @param loadedDictSize The size of the dictionary to be loaded
|
|
* into the context, if any. If no dictionary is used, or the
|
|
* dictionary is being attached / copied, then pass 0.
|
|
* note : `params` are assumed fully validated at this stage.
|
|
*/
|
|
static size_t ZSTD_resetCCtx_internal(ZSTD_CCtx* zc,
|
|
ZSTD_CCtx_params const* params,
|
|
U64 const pledgedSrcSize,
|
|
size_t const loadedDictSize,
|
|
ZSTD_compResetPolicy_e const crp,
|
|
ZSTD_buffered_policy_e const zbuff)
|
|
{
|
|
ZSTD_cwksp* const ws = &zc->workspace;
|
|
DEBUGLOG(4, "ZSTD_resetCCtx_internal: pledgedSrcSize=%u, wlog=%u, useRowMatchFinder=%d useBlockSplitter=%d",
|
|
(U32)pledgedSrcSize, params->cParams.windowLog, (int)params->useRowMatchFinder, (int)params->postBlockSplitter);
|
|
assert(!ZSTD_isError(ZSTD_checkCParams(params->cParams)));
|
|
|
|
zc->isFirstBlock = 1;
|
|
|
|
/* Set applied params early so we can modify them for LDM,
|
|
* and point params at the applied params.
|
|
*/
|
|
zc->appliedParams = *params;
|
|
params = &zc->appliedParams;
|
|
|
|
assert(params->useRowMatchFinder != ZSTD_ps_auto);
|
|
assert(params->postBlockSplitter != ZSTD_ps_auto);
|
|
assert(params->ldmParams.enableLdm != ZSTD_ps_auto);
|
|
assert(params->maxBlockSize != 0);
|
|
if (params->ldmParams.enableLdm == ZSTD_ps_enable) {
|
|
/* Adjust long distance matching parameters */
|
|
ZSTD_ldm_adjustParameters(&zc->appliedParams.ldmParams, ¶ms->cParams);
|
|
assert(params->ldmParams.hashLog >= params->ldmParams.bucketSizeLog);
|
|
assert(params->ldmParams.hashRateLog < 32);
|
|
}
|
|
|
|
{ size_t const windowSize = MAX(1, (size_t)MIN(((U64)1 << params->cParams.windowLog), pledgedSrcSize));
|
|
size_t const blockSize = MIN(params->maxBlockSize, windowSize);
|
|
size_t const maxNbSeq = ZSTD_maxNbSeq(blockSize, params->cParams.minMatch, ZSTD_hasExtSeqProd(params));
|
|
size_t const buffOutSize = (zbuff == ZSTDb_buffered && params->outBufferMode == ZSTD_bm_buffered)
|
|
? ZSTD_compressBound(blockSize) + 1
|
|
: 0;
|
|
size_t const buffInSize = (zbuff == ZSTDb_buffered && params->inBufferMode == ZSTD_bm_buffered)
|
|
? windowSize + blockSize
|
|
: 0;
|
|
size_t const maxNbLdmSeq = ZSTD_ldm_getMaxNbSeq(params->ldmParams, blockSize);
|
|
|
|
int const indexTooClose = ZSTD_indexTooCloseToMax(zc->blockState.matchState.window);
|
|
int const dictTooBig = ZSTD_dictTooBig(loadedDictSize);
|
|
ZSTD_indexResetPolicy_e needsIndexReset =
|
|
(indexTooClose || dictTooBig || !zc->initialized) ? ZSTDirp_reset : ZSTDirp_continue;
|
|
|
|
size_t const neededSpace =
|
|
ZSTD_estimateCCtxSize_usingCCtxParams_internal(
|
|
¶ms->cParams, ¶ms->ldmParams, zc->staticSize != 0, params->useRowMatchFinder,
|
|
buffInSize, buffOutSize, pledgedSrcSize, ZSTD_hasExtSeqProd(params), params->maxBlockSize);
|
|
|
|
FORWARD_IF_ERROR(neededSpace, "cctx size estimate failed!");
|
|
|
|
if (!zc->staticSize) ZSTD_cwksp_bump_oversized_duration(ws, 0);
|
|
|
|
{ /* Check if workspace is large enough, alloc a new one if needed */
|
|
int const workspaceTooSmall = ZSTD_cwksp_sizeof(ws) < neededSpace;
|
|
int const workspaceWasteful = ZSTD_cwksp_check_wasteful(ws, neededSpace);
|
|
int resizeWorkspace = workspaceTooSmall || workspaceWasteful;
|
|
DEBUGLOG(4, "Need %zu B workspace", neededSpace);
|
|
DEBUGLOG(4, "windowSize: %zu - blockSize: %zu", windowSize, blockSize);
|
|
|
|
if (resizeWorkspace) {
|
|
DEBUGLOG(4, "Resize workspaceSize from %zuKB to %zuKB",
|
|
ZSTD_cwksp_sizeof(ws) >> 10,
|
|
neededSpace >> 10);
|
|
|
|
RETURN_ERROR_IF(zc->staticSize, memory_allocation, "static cctx : no resize");
|
|
|
|
needsIndexReset = ZSTDirp_reset;
|
|
|
|
ZSTD_cwksp_free(ws, zc->customMem);
|
|
FORWARD_IF_ERROR(ZSTD_cwksp_create(ws, neededSpace, zc->customMem), "");
|
|
|
|
DEBUGLOG(5, "reserving object space");
|
|
/* Statically sized space.
|
|
* tmpWorkspace never moves,
|
|
* though prev/next block swap places */
|
|
assert(ZSTD_cwksp_check_available(ws, 2 * sizeof(ZSTD_compressedBlockState_t)));
|
|
zc->blockState.prevCBlock = (ZSTD_compressedBlockState_t*) ZSTD_cwksp_reserve_object(ws, sizeof(ZSTD_compressedBlockState_t));
|
|
RETURN_ERROR_IF(zc->blockState.prevCBlock == NULL, memory_allocation, "couldn't allocate prevCBlock");
|
|
zc->blockState.nextCBlock = (ZSTD_compressedBlockState_t*) ZSTD_cwksp_reserve_object(ws, sizeof(ZSTD_compressedBlockState_t));
|
|
RETURN_ERROR_IF(zc->blockState.nextCBlock == NULL, memory_allocation, "couldn't allocate nextCBlock");
|
|
zc->tmpWorkspace = ZSTD_cwksp_reserve_object(ws, TMP_WORKSPACE_SIZE);
|
|
RETURN_ERROR_IF(zc->tmpWorkspace == NULL, memory_allocation, "couldn't allocate tmpWorkspace");
|
|
zc->tmpWkspSize = TMP_WORKSPACE_SIZE;
|
|
} }
|
|
|
|
ZSTD_cwksp_clear(ws);
|
|
|
|
/* init params */
|
|
zc->blockState.matchState.cParams = params->cParams;
|
|
zc->blockState.matchState.prefetchCDictTables = params->prefetchCDictTables == ZSTD_ps_enable;
|
|
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->blockSizeMax = blockSize;
|
|
|
|
XXH64_reset(&zc->xxhState, 0);
|
|
zc->stage = ZSTDcs_init;
|
|
zc->dictID = 0;
|
|
zc->dictContentSize = 0;
|
|
|
|
ZSTD_reset_compressedBlockState(zc->blockState.prevCBlock);
|
|
|
|
FORWARD_IF_ERROR(ZSTD_reset_matchState(
|
|
&zc->blockState.matchState,
|
|
ws,
|
|
¶ms->cParams,
|
|
params->useRowMatchFinder,
|
|
crp,
|
|
needsIndexReset,
|
|
ZSTD_resetTarget_CCtx), "");
|
|
|
|
zc->seqStore.sequencesStart = (SeqDef*)ZSTD_cwksp_reserve_aligned64(ws, maxNbSeq * sizeof(SeqDef));
|
|
|
|
/* ldm hash table */
|
|
if (params->ldmParams.enableLdm == ZSTD_ps_enable) {
|
|
/* TODO: avoid memset? */
|
|
size_t const ldmHSize = ((size_t)1) << params->ldmParams.hashLog;
|
|
zc->ldmState.hashTable = (ldmEntry_t*)ZSTD_cwksp_reserve_aligned64(ws, ldmHSize * sizeof(ldmEntry_t));
|
|
ZSTD_memset(zc->ldmState.hashTable, 0, ldmHSize * sizeof(ldmEntry_t));
|
|
zc->ldmSequences = (rawSeq*)ZSTD_cwksp_reserve_aligned64(ws, maxNbLdmSeq * sizeof(rawSeq));
|
|
zc->maxNbLdmSequences = maxNbLdmSeq;
|
|
|
|
ZSTD_window_init(&zc->ldmState.window);
|
|
zc->ldmState.loadedDictEnd = 0;
|
|
}
|
|
|
|
/* reserve space for block-level external sequences */
|
|
if (ZSTD_hasExtSeqProd(params)) {
|
|
size_t const maxNbExternalSeq = ZSTD_sequenceBound(blockSize);
|
|
zc->extSeqBufCapacity = maxNbExternalSeq;
|
|
zc->extSeqBuf =
|
|
(ZSTD_Sequence*)ZSTD_cwksp_reserve_aligned64(ws, maxNbExternalSeq * sizeof(ZSTD_Sequence));
|
|
}
|
|
|
|
/* buffers */
|
|
|
|
/* ZSTD_wildcopy() is used to copy into the literals buffer,
|
|
* so we have to oversize the buffer by WILDCOPY_OVERLENGTH bytes.
|
|
*/
|
|
zc->seqStore.litStart = ZSTD_cwksp_reserve_buffer(ws, blockSize + WILDCOPY_OVERLENGTH);
|
|
zc->seqStore.maxNbLit = blockSize;
|
|
|
|
zc->bufferedPolicy = zbuff;
|
|
zc->inBuffSize = buffInSize;
|
|
zc->inBuff = (char*)ZSTD_cwksp_reserve_buffer(ws, buffInSize);
|
|
zc->outBuffSize = buffOutSize;
|
|
zc->outBuff = (char*)ZSTD_cwksp_reserve_buffer(ws, buffOutSize);
|
|
|
|
/* ldm bucketOffsets table */
|
|
if (params->ldmParams.enableLdm == ZSTD_ps_enable) {
|
|
/* TODO: avoid memset? */
|
|
size_t const numBuckets =
|
|
((size_t)1) << (params->ldmParams.hashLog -
|
|
params->ldmParams.bucketSizeLog);
|
|
zc->ldmState.bucketOffsets = ZSTD_cwksp_reserve_buffer(ws, numBuckets);
|
|
ZSTD_memset(zc->ldmState.bucketOffsets, 0, numBuckets);
|
|
}
|
|
|
|
/* sequences storage */
|
|
ZSTD_referenceExternalSequences(zc, NULL, 0);
|
|
zc->seqStore.maxNbSeq = maxNbSeq;
|
|
zc->seqStore.llCode = ZSTD_cwksp_reserve_buffer(ws, maxNbSeq * sizeof(BYTE));
|
|
zc->seqStore.mlCode = ZSTD_cwksp_reserve_buffer(ws, maxNbSeq * sizeof(BYTE));
|
|
zc->seqStore.ofCode = ZSTD_cwksp_reserve_buffer(ws, maxNbSeq * sizeof(BYTE));
|
|
|
|
DEBUGLOG(3, "wksp: finished allocating, %zd bytes remain available", ZSTD_cwksp_available_space(ws));
|
|
assert(ZSTD_cwksp_estimated_space_within_bounds(ws, neededSpace));
|
|
|
|
zc->initialized = 1;
|
|
|
|
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) {
|
|
ZSTD_compressedBlockState_t* const prevCBlock = cctx->blockState.prevCBlock;
|
|
ZSTD_rust_invalidateRepCodes(prevCBlock->rep);
|
|
assert(!ZSTD_window_hasExtDict(cctx->blockState.matchState.window));
|
|
}
|
|
|
|
static int ZSTD_shouldAttachDict(const ZSTD_CDict* cdict,
|
|
const ZSTD_CCtx_params* params,
|
|
U64 pledgedSrcSize)
|
|
{
|
|
return ZSTD_rust_params_shouldAttachDict(
|
|
cdict->matchState.cParams.strategy,
|
|
cdict->matchState.dedicatedDictSearch,
|
|
pledgedSrcSize,
|
|
(int)params->attachDictPref,
|
|
params->forceWindow);
|
|
}
|
|
|
|
static size_t
|
|
ZSTD_resetCCtx_byAttachingCDict(ZSTD_CCtx* cctx,
|
|
const ZSTD_CDict* cdict,
|
|
ZSTD_CCtx_params params,
|
|
U64 pledgedSrcSize,
|
|
ZSTD_buffered_policy_e zbuff)
|
|
{
|
|
DEBUGLOG(4, "ZSTD_resetCCtx_byAttachingCDict() pledgedSrcSize=%llu",
|
|
(unsigned long long)pledgedSrcSize);
|
|
{
|
|
ZSTD_compressionParameters adjusted_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. */
|
|
/* pledgedSrcSize == 0 means 0! */
|
|
|
|
if (cdict->matchState.dedicatedDictSearch) {
|
|
ZSTD_dedicatedDictSearch_revertCParams(&adjusted_cdict_cParams);
|
|
}
|
|
|
|
params.cParams = ZSTD_adjustCParams_internal(adjusted_cdict_cParams, pledgedSrcSize,
|
|
cdict->dictContentSize, ZSTD_cpm_attachDict,
|
|
params.useRowMatchFinder);
|
|
params.cParams.windowLog = windowLog;
|
|
params.useRowMatchFinder = cdict->useRowMatchFinder; /* cdict overrides */
|
|
FORWARD_IF_ERROR(ZSTD_resetCCtx_internal(cctx, ¶ms, pledgedSrcSize,
|
|
/* loadedDictSize */ 0,
|
|
ZSTDcrp_makeClean, zbuff), "");
|
|
assert(cctx->appliedParams.cParams.strategy == adjusted_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_rust_windowClear(
|
|
(size_t)(cctx->blockState.matchState.window.nextSrc -
|
|
cctx->blockState.matchState.window.base),
|
|
&cctx->blockState.matchState.window.lowLimit,
|
|
&cctx->blockState.matchState.window.dictLimit);
|
|
}
|
|
/* loadedDictEnd is expressed within the referential of the active context */
|
|
cctx->blockState.matchState.loadedDictEnd = cctx->blockState.matchState.window.dictLimit;
|
|
} }
|
|
|
|
cctx->dictID = cdict->dictID;
|
|
cctx->dictContentSize = cdict->dictContentSize;
|
|
|
|
/* copy block state */
|
|
ZSTD_memcpy(cctx->blockState.prevCBlock, &cdict->cBlockState, sizeof(cdict->cBlockState));
|
|
|
|
return 0;
|
|
}
|
|
|
|
static void ZSTD_copyCDictTableIntoCCtx(U32* dst, U32 const* src, size_t tableSize,
|
|
ZSTD_compressionParameters const* cParams) {
|
|
ZSTD_STATIC_ASSERT(ZSTD_SHORT_CACHE_TAG_BITS == 8);
|
|
ZSTD_rust_copyCDictTableIntoCCtx(dst, src, tableSize,
|
|
ZSTD_CDictIndicesAreTagged(cParams));
|
|
}
|
|
|
|
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;
|
|
|
|
assert(!cdict->matchState.dedicatedDictSearch);
|
|
DEBUGLOG(4, "ZSTD_resetCCtx_byCopyingCDict() pledgedSrcSize=%llu",
|
|
(unsigned long long)pledgedSrcSize);
|
|
|
|
{ unsigned const windowLog = params.cParams.windowLog;
|
|
assert(windowLog != 0);
|
|
/* Copy only compression parameters related to tables. */
|
|
params.cParams = *cdict_cParams;
|
|
params.cParams.windowLog = windowLog;
|
|
params.useRowMatchFinder = cdict->useRowMatchFinder;
|
|
FORWARD_IF_ERROR(ZSTD_resetCCtx_internal(cctx, ¶ms, pledgedSrcSize,
|
|
/* loadedDictSize */ 0,
|
|
ZSTDcrp_leaveDirty, 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);
|
|
}
|
|
|
|
ZSTD_cwksp_mark_tables_dirty(&cctx->workspace);
|
|
assert(params.useRowMatchFinder != ZSTD_ps_auto);
|
|
|
|
/* copy tables */
|
|
{ size_t const chainSize = ZSTD_allocateChainTable(cdict_cParams->strategy, cdict->useRowMatchFinder, 0 /* DDS guaranteed disabled */)
|
|
? ((size_t)1 << cdict_cParams->chainLog)
|
|
: 0;
|
|
size_t const hSize = (size_t)1 << cdict_cParams->hashLog;
|
|
|
|
ZSTD_copyCDictTableIntoCCtx(cctx->blockState.matchState.hashTable,
|
|
cdict->matchState.hashTable,
|
|
hSize, cdict_cParams);
|
|
|
|
/* Do not copy cdict's chainTable if cctx has parameters such that it would not use chainTable */
|
|
if (ZSTD_allocateChainTable(cctx->appliedParams.cParams.strategy, cctx->appliedParams.useRowMatchFinder, 0 /* forDDSDict */)) {
|
|
ZSTD_copyCDictTableIntoCCtx(cctx->blockState.matchState.chainTable,
|
|
cdict->matchState.chainTable,
|
|
chainSize, cdict_cParams);
|
|
}
|
|
/* copy tag table */
|
|
if (ZSTD_rowMatchFinderUsed(cdict_cParams->strategy, cdict->useRowMatchFinder)) {
|
|
size_t const tagTableSize = hSize;
|
|
ZSTD_memcpy(cctx->blockState.matchState.tagTable,
|
|
cdict->matchState.tagTable,
|
|
tagTableSize);
|
|
cctx->blockState.matchState.hashSalt = cdict->matchState.hashSalt;
|
|
}
|
|
}
|
|
|
|
/* Zero the hashTable3, since the cdict never fills it */
|
|
assert(cctx->blockState.matchState.hashLog3 <= 31);
|
|
{ U32 const h3log = cctx->blockState.matchState.hashLog3;
|
|
size_t const h3Size = h3log ? ((size_t)1 << h3log) : 0;
|
|
assert(cdict->matchState.hashLog3 == 0);
|
|
ZSTD_memset(cctx->blockState.matchState.hashTable3, 0, h3Size * sizeof(U32));
|
|
}
|
|
|
|
ZSTD_cwksp_mark_tables_clean(&cctx->workspace);
|
|
|
|
/* 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;
|
|
cctx->dictContentSize = cdict->dictContentSize;
|
|
|
|
/* copy block state */
|
|
ZSTD_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,
|
|
const 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)
|
|
{
|
|
RETURN_ERROR_IF(srcCCtx->stage!=ZSTDcs_init, stage_wrong,
|
|
"Can't copy a ctx that's not in init stage.");
|
|
DEBUGLOG(5, "ZSTD_copyCCtx_internal");
|
|
ZSTD_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;
|
|
assert(srcCCtx->appliedParams.useRowMatchFinder != ZSTD_ps_auto);
|
|
assert(srcCCtx->appliedParams.postBlockSplitter != ZSTD_ps_auto);
|
|
assert(srcCCtx->appliedParams.ldmParams.enableLdm != ZSTD_ps_auto);
|
|
params.useRowMatchFinder = srcCCtx->appliedParams.useRowMatchFinder;
|
|
params.postBlockSplitter = srcCCtx->appliedParams.postBlockSplitter;
|
|
params.ldmParams = srcCCtx->appliedParams.ldmParams;
|
|
params.fParams = fParams;
|
|
params.maxBlockSize = srcCCtx->appliedParams.maxBlockSize;
|
|
ZSTD_resetCCtx_internal(dstCCtx, ¶ms, pledgedSrcSize,
|
|
/* loadedDictSize */ 0,
|
|
ZSTDcrp_leaveDirty, 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);
|
|
}
|
|
|
|
ZSTD_cwksp_mark_tables_dirty(&dstCCtx->workspace);
|
|
|
|
/* copy tables */
|
|
{ size_t const chainSize = ZSTD_allocateChainTable(srcCCtx->appliedParams.cParams.strategy,
|
|
srcCCtx->appliedParams.useRowMatchFinder,
|
|
0 /* forDDSDict */)
|
|
? ((size_t)1 << srcCCtx->appliedParams.cParams.chainLog)
|
|
: 0;
|
|
size_t const hSize = (size_t)1 << srcCCtx->appliedParams.cParams.hashLog;
|
|
U32 const h3log = srcCCtx->blockState.matchState.hashLog3;
|
|
size_t const h3Size = h3log ? ((size_t)1 << h3log) : 0;
|
|
|
|
ZSTD_memcpy(dstCCtx->blockState.matchState.hashTable,
|
|
srcCCtx->blockState.matchState.hashTable,
|
|
hSize * sizeof(U32));
|
|
ZSTD_memcpy(dstCCtx->blockState.matchState.chainTable,
|
|
srcCCtx->blockState.matchState.chainTable,
|
|
chainSize * sizeof(U32));
|
|
ZSTD_memcpy(dstCCtx->blockState.matchState.hashTable3,
|
|
srcCCtx->blockState.matchState.hashTable3,
|
|
h3Size * sizeof(U32));
|
|
}
|
|
|
|
ZSTD_cwksp_mark_tables_clean(&dstCCtx->workspace);
|
|
|
|
/* 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;
|
|
dstCCtx->dictContentSize = srcCCtx->dictContentSize;
|
|
|
|
/* copy block state */
|
|
ZSTD_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 = srcCCtx->bufferedPolicy;
|
|
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);
|
|
}
|
|
|
|
|
|
/*! 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;
|
|
U32* chainTable = NULL;
|
|
U32 chainSize = 0;
|
|
U32* hashTable3 = NULL;
|
|
U32 hashSize3 = 0;
|
|
|
|
if (ZSTD_allocateChainTable(params->cParams.strategy, params->useRowMatchFinder, (U32)ms->dedicatedDictSearch)) {
|
|
chainTable = ms->chainTable;
|
|
chainSize = (U32)1 << params->cParams.chainLog;
|
|
}
|
|
|
|
if (ms->hashLog3) {
|
|
hashTable3 = ms->hashTable3;
|
|
hashSize3 = (U32)1 << ms->hashLog3;
|
|
}
|
|
|
|
ZSTD_rust_reduceIndex(ms->hashTable, hSize,
|
|
chainTable, chainSize,
|
|
hashTable3, hashSize3,
|
|
reducerValue,
|
|
params->cParams.strategy == ZSTD_btlazy2);
|
|
}
|
|
|
|
|
|
/*-*******************************************************
|
|
* Block entropic compression
|
|
*********************************************************/
|
|
|
|
/* See doc/zstd_compression_format.md for detailed format description */
|
|
|
|
/* ZSTD_seqToCodes() lives in rust/src/zstd_compress_stats.rs. */
|
|
|
|
/* ZSTD_useTargetCBlockSize():
|
|
* Returns if target compressed block size param is being used.
|
|
* If used, compression will do best effort to make a compressed block size to be around targetCBlockSize.
|
|
* Returns 1 if true, 0 otherwise. */
|
|
static int ZSTD_useTargetCBlockSize(const ZSTD_CCtx_params* cctxParams)
|
|
{
|
|
DEBUGLOG(5, "ZSTD_useTargetCBlockSize (targetCBlockSize=%zu)", cctxParams->targetCBlockSize);
|
|
return ZSTD_rust_useTargetCBlockSize(cctxParams);
|
|
}
|
|
|
|
/* ZSTD_blockSplitterEnabled():
|
|
* Returns if block splitting param is being used
|
|
* If used, compression will do best effort to split a block in order to improve compression ratio.
|
|
* At the time this function is called, the parameter must be finalized.
|
|
* Returns 1 if true, 0 otherwise. */
|
|
static int ZSTD_blockSplitterEnabled(ZSTD_CCtx_params* cctxParams)
|
|
{
|
|
DEBUGLOG(5, "ZSTD_blockSplitterEnabled (postBlockSplitter=%d)", cctxParams->postBlockSplitter);
|
|
return ZSTD_rust_blockSplitterEnabled(cctxParams);
|
|
}
|
|
|
|
/* ZSTD_buildSequencesStatistics() and the ZSTD_entropyCompressSeqStore*()
|
|
* implementations live in rust/src/zstd_compress_stats.rs. The wrappers
|
|
* below keep the original signatures and extract the only two
|
|
* ZSTD_CCtx_params fields those paths read. */
|
|
|
|
MEM_STATIC size_t
|
|
ZSTD_entropyCompressSeqStore_internal(
|
|
void* dst, size_t dstCapacity,
|
|
const void* literals, size_t litSize,
|
|
const SeqStore_t* seqStorePtr,
|
|
const ZSTD_entropyCTables_t* prevEntropy,
|
|
ZSTD_entropyCTables_t* nextEntropy,
|
|
const ZSTD_CCtx_params* cctxParams,
|
|
void* entropyWorkspace, size_t entropyWkspSize,
|
|
const int bmi2)
|
|
{
|
|
return ZSTD_rust_entropyCompressSeqStore_internal(
|
|
dst, dstCapacity,
|
|
literals, litSize,
|
|
seqStorePtr, prevEntropy, nextEntropy,
|
|
(int)cctxParams->cParams.strategy,
|
|
ZSTD_literalsCompressionIsDisabled(cctxParams),
|
|
entropyWorkspace, entropyWkspSize, bmi2);
|
|
}
|
|
|
|
static size_t
|
|
ZSTD_entropyCompressSeqStore(
|
|
const SeqStore_t* seqStorePtr,
|
|
const ZSTD_entropyCTables_t* prevEntropy,
|
|
ZSTD_entropyCTables_t* nextEntropy,
|
|
const ZSTD_CCtx_params* cctxParams,
|
|
void* dst, size_t dstCapacity,
|
|
size_t srcSize,
|
|
void* entropyWorkspace, size_t entropyWkspSize,
|
|
int bmi2)
|
|
{
|
|
return ZSTD_rust_entropyCompressSeqStore(
|
|
seqStorePtr, prevEntropy, nextEntropy,
|
|
(int)cctxParams->cParams.strategy,
|
|
ZSTD_literalsCompressionIsDisabled(cctxParams),
|
|
dst, dstCapacity,
|
|
srcSize,
|
|
entropyWorkspace, entropyWkspSize,
|
|
bmi2);
|
|
}
|
|
|
|
/* ZSTD_selectBlockCompressor() :
|
|
* Not static, but internal use only (used by long distance matcher)
|
|
* assumption : strat is a valid strategy */
|
|
ZSTD_BlockCompressor_f ZSTD_selectBlockCompressor(ZSTD_strategy strat, ZSTD_ParamSwitch_e useRowMatchFinder, ZSTD_dictMode_e dictMode)
|
|
{
|
|
static const ZSTD_BlockCompressor_f blockCompressor[4][ZSTD_STRATEGY_MAX+1] = {
|
|
{ ZSTD_compressBlock_fast /* default for 0 */,
|
|
ZSTD_compressBlock_fast,
|
|
ZSTD_COMPRESSBLOCK_DOUBLEFAST,
|
|
ZSTD_COMPRESSBLOCK_GREEDY,
|
|
ZSTD_COMPRESSBLOCK_LAZY,
|
|
ZSTD_COMPRESSBLOCK_LAZY2,
|
|
ZSTD_COMPRESSBLOCK_BTLAZY2,
|
|
ZSTD_COMPRESSBLOCK_BTOPT,
|
|
ZSTD_COMPRESSBLOCK_BTULTRA,
|
|
ZSTD_COMPRESSBLOCK_BTULTRA2
|
|
},
|
|
{ ZSTD_compressBlock_fast_extDict /* default for 0 */,
|
|
ZSTD_compressBlock_fast_extDict,
|
|
ZSTD_COMPRESSBLOCK_DOUBLEFAST_EXTDICT,
|
|
ZSTD_COMPRESSBLOCK_GREEDY_EXTDICT,
|
|
ZSTD_COMPRESSBLOCK_LAZY_EXTDICT,
|
|
ZSTD_COMPRESSBLOCK_LAZY2_EXTDICT,
|
|
ZSTD_COMPRESSBLOCK_BTLAZY2_EXTDICT,
|
|
ZSTD_COMPRESSBLOCK_BTOPT_EXTDICT,
|
|
ZSTD_COMPRESSBLOCK_BTULTRA_EXTDICT,
|
|
ZSTD_COMPRESSBLOCK_BTULTRA_EXTDICT
|
|
},
|
|
{ ZSTD_compressBlock_fast_dictMatchState /* default for 0 */,
|
|
ZSTD_compressBlock_fast_dictMatchState,
|
|
ZSTD_COMPRESSBLOCK_DOUBLEFAST_DICTMATCHSTATE,
|
|
ZSTD_COMPRESSBLOCK_GREEDY_DICTMATCHSTATE,
|
|
ZSTD_COMPRESSBLOCK_LAZY_DICTMATCHSTATE,
|
|
ZSTD_COMPRESSBLOCK_LAZY2_DICTMATCHSTATE,
|
|
ZSTD_COMPRESSBLOCK_BTLAZY2_DICTMATCHSTATE,
|
|
ZSTD_COMPRESSBLOCK_BTOPT_DICTMATCHSTATE,
|
|
ZSTD_COMPRESSBLOCK_BTULTRA_DICTMATCHSTATE,
|
|
ZSTD_COMPRESSBLOCK_BTULTRA_DICTMATCHSTATE
|
|
},
|
|
{ NULL /* default for 0 */,
|
|
NULL,
|
|
NULL,
|
|
ZSTD_COMPRESSBLOCK_GREEDY_DEDICATEDDICTSEARCH,
|
|
ZSTD_COMPRESSBLOCK_LAZY_DEDICATEDDICTSEARCH,
|
|
ZSTD_COMPRESSBLOCK_LAZY2_DEDICATEDDICTSEARCH,
|
|
NULL,
|
|
NULL,
|
|
NULL,
|
|
NULL }
|
|
};
|
|
ZSTD_BlockCompressor_f selectedCompressor;
|
|
int selectedCompressorIndex;
|
|
ZSTD_STATIC_ASSERT((unsigned)ZSTD_fast == 1);
|
|
|
|
assert(ZSTD_cParam_withinBounds(ZSTD_c_strategy, (int)strat));
|
|
DEBUGLOG(5, "Selected block compressor: dictMode=%d strat=%d rowMatchfinder=%d", (int)dictMode, (int)strat, (int)useRowMatchFinder);
|
|
selectedCompressorIndex = ZSTD_rust_params_selectBlockCompressor(
|
|
(int)strat, (int)useRowMatchFinder);
|
|
if (selectedCompressorIndex < 3) {
|
|
static const ZSTD_BlockCompressor_f rowBasedBlockCompressors[4][3] = {
|
|
{
|
|
ZSTD_COMPRESSBLOCK_GREEDY_ROW,
|
|
ZSTD_COMPRESSBLOCK_LAZY_ROW,
|
|
ZSTD_COMPRESSBLOCK_LAZY2_ROW
|
|
},
|
|
{
|
|
ZSTD_COMPRESSBLOCK_GREEDY_EXTDICT_ROW,
|
|
ZSTD_COMPRESSBLOCK_LAZY_EXTDICT_ROW,
|
|
ZSTD_COMPRESSBLOCK_LAZY2_EXTDICT_ROW
|
|
},
|
|
{
|
|
ZSTD_COMPRESSBLOCK_GREEDY_DICTMATCHSTATE_ROW,
|
|
ZSTD_COMPRESSBLOCK_LAZY_DICTMATCHSTATE_ROW,
|
|
ZSTD_COMPRESSBLOCK_LAZY2_DICTMATCHSTATE_ROW
|
|
},
|
|
{
|
|
ZSTD_COMPRESSBLOCK_GREEDY_DEDICATEDDICTSEARCH_ROW,
|
|
ZSTD_COMPRESSBLOCK_LAZY_DEDICATEDDICTSEARCH_ROW,
|
|
ZSTD_COMPRESSBLOCK_LAZY2_DEDICATEDDICTSEARCH_ROW
|
|
}
|
|
};
|
|
DEBUGLOG(5, "Selecting a row-based matchfinder");
|
|
assert(useRowMatchFinder != ZSTD_ps_auto);
|
|
selectedCompressor = rowBasedBlockCompressors[(int)dictMode][selectedCompressorIndex];
|
|
} else {
|
|
selectedCompressor = blockCompressor[(int)dictMode][selectedCompressorIndex - 3];
|
|
}
|
|
assert(selectedCompressor != NULL);
|
|
return selectedCompressor;
|
|
}
|
|
|
|
static void ZSTD_storeLastLiterals(SeqStore_t* seqStorePtr,
|
|
const BYTE* anchor, size_t lastLLSize)
|
|
{
|
|
ZSTD_rust_storeLastLiterals(seqStorePtr, anchor, lastLLSize);
|
|
}
|
|
|
|
void ZSTD_resetSeqStore(SeqStore_t* ssPtr)
|
|
{
|
|
ZSTD_rust_resetSeqStore(ssPtr);
|
|
}
|
|
|
|
/* ZSTD_postProcessSequenceProducerResult() :
|
|
* Validates and post-processes sequences obtained through the external matchfinder API:
|
|
* - Checks whether nbExternalSeqs represents an error condition.
|
|
* - Appends a block delimiter to outSeqs if one is not already present.
|
|
* See zstd.h for context regarding block delimiters.
|
|
* Returns the number of sequences after post-processing, or an error code. */
|
|
static size_t ZSTD_postProcessSequenceProducerResult(
|
|
ZSTD_Sequence* outSeqs, size_t nbExternalSeqs, size_t outSeqsCapacity, size_t srcSize
|
|
) {
|
|
return ZSTD_rust_postProcessSequenceProducerResult(
|
|
outSeqs, nbExternalSeqs, outSeqsCapacity, srcSize);
|
|
}
|
|
|
|
/* ZSTD_fastSequenceLengthSum() :
|
|
* Returns sum(litLen) + sum(matchLen) + lastLits for *seqBuf*.
|
|
* Similar to another function in zstd_compress.c (determine_blockSize),
|
|
* except it doesn't check for a block delimiter to end summation.
|
|
* Removing the early exit allows the compiler to auto-vectorize (https://godbolt.org/z/cY1cajz9P).
|
|
* This function can be deleted and replaced by determine_blockSize after we resolve issue #3456. */
|
|
static size_t ZSTD_fastSequenceLengthSum(ZSTD_Sequence const* seqBuf, size_t seqBufSize) {
|
|
return ZSTD_rust_fastSequenceLengthSum(seqBuf, seqBufSize);
|
|
}
|
|
|
|
/**
|
|
* Function to validate sequences produced by a block compressor.
|
|
*/
|
|
static void ZSTD_validateSeqStore(const SeqStore_t* seqStore, const ZSTD_compressionParameters* cParams)
|
|
{
|
|
#if DEBUGLEVEL >= 1
|
|
ZSTD_rust_validateSeqStore(seqStore, (U32)cParams->minMatch);
|
|
#else
|
|
(void)seqStore;
|
|
(void)cParams;
|
|
#endif
|
|
}
|
|
|
|
static size_t
|
|
ZSTD_transferSequences_wBlockDelim(ZSTD_CCtx* cctx,
|
|
ZSTD_SequencePosition* seqPos,
|
|
const ZSTD_Sequence* const inSeqs, size_t inSeqsSize,
|
|
const void* src, size_t blockSize,
|
|
ZSTD_ParamSwitch_e externalRepSearch);
|
|
|
|
typedef enum { ZSTDbss_compress, ZSTDbss_noCompress } ZSTD_BuildSeqStore_e;
|
|
|
|
static size_t ZSTD_buildSeqStore(ZSTD_CCtx* zc, const void* src, size_t srcSize)
|
|
{
|
|
ZSTD_MatchState_t* const ms = &zc->blockState.matchState;
|
|
DEBUGLOG(5, "ZSTD_buildSeqStore (srcSize=%zu)", srcSize);
|
|
assert(srcSize <= ZSTD_BLOCKSIZE_MAX);
|
|
/* Assert that we have correctly flushed the ctx params into the ms's copy */
|
|
ZSTD_assertEqualCParams(zc->appliedParams.cParams, ms->cParams);
|
|
/* TODO: See 3090. We reduced MIN_CBLOCK_SIZE from 3 to 2 so to compensate we are adding
|
|
* additional 1. We need to revisit and change this logic to be more consistent */
|
|
if (srcSize < MIN_CBLOCK_SIZE+ZSTD_blockHeaderSize+1+1) {
|
|
if (zc->appliedParams.cParams.strategy >= ZSTD_btopt) {
|
|
ZSTD_ldm_skipRawSeqStoreBytes(&zc->externSeqStore, srcSize);
|
|
} else {
|
|
ZSTD_ldm_skipSequences(&zc->externSeqStore, srcSize, zc->appliedParams.cParams.minMatch);
|
|
}
|
|
return ZSTDbss_noCompress; /* don't even attempt compression below a certain srcSize */
|
|
}
|
|
ZSTD_resetSeqStore(&(zc->seqStore));
|
|
/* required for optimal parser to read stats from dictionary */
|
|
ms->opt.symbolCosts = &zc->blockState.prevCBlock->entropy;
|
|
/* tell the optimal parser how we expect to compress literals */
|
|
ms->opt.literalCompressionMode = zc->appliedParams.literalCompressionMode;
|
|
/* a gap between an attached dict and the current window is not safe,
|
|
* they must remain adjacent,
|
|
* and when that stops being the case, the dict must be unset */
|
|
assert(ms->dictMatchState == NULL || ms->loadedDictEnd == ms->window.dictLimit);
|
|
|
|
/* limited update after a very long match */
|
|
{ const BYTE* const base = ms->window.base;
|
|
const BYTE* const istart = (const BYTE*)src;
|
|
const U32 curr = (U32)(istart-base);
|
|
if (sizeof(ptrdiff_t)==8) assert(istart - base < (ptrdiff_t)(U32)(-1)); /* ensure no overflow */
|
|
if (curr > ms->nextToUpdate + 384)
|
|
ms->nextToUpdate = curr - MIN(192, (U32)(curr - ms->nextToUpdate - 384));
|
|
}
|
|
|
|
/* select and store sequences */
|
|
{ ZSTD_dictMode_e const dictMode = ZSTD_matchState_dictMode(ms);
|
|
size_t lastLLSize;
|
|
{ int i;
|
|
for (i = 0; i < ZSTD_REP_NUM; ++i)
|
|
zc->blockState.nextCBlock->rep[i] = zc->blockState.prevCBlock->rep[i];
|
|
}
|
|
if (zc->externSeqStore.pos < zc->externSeqStore.size) {
|
|
assert(zc->appliedParams.ldmParams.enableLdm == ZSTD_ps_disable);
|
|
|
|
/* External matchfinder + LDM is technically possible, just not implemented yet.
|
|
* We need to revisit soon and implement it. */
|
|
RETURN_ERROR_IF(
|
|
ZSTD_hasExtSeqProd(&zc->appliedParams),
|
|
parameter_combination_unsupported,
|
|
"Long-distance matching with external sequence producer enabled is not currently supported."
|
|
);
|
|
|
|
/* Updates ldmSeqStore.pos */
|
|
lastLLSize =
|
|
ZSTD_ldm_blockCompress(&zc->externSeqStore,
|
|
ms, &zc->seqStore,
|
|
zc->blockState.nextCBlock->rep,
|
|
zc->appliedParams.useRowMatchFinder,
|
|
src, srcSize);
|
|
assert(zc->externSeqStore.pos <= zc->externSeqStore.size);
|
|
} else if (zc->appliedParams.ldmParams.enableLdm == ZSTD_ps_enable) {
|
|
RawSeqStore_t ldmSeqStore = kNullRawSeqStore;
|
|
|
|
/* External matchfinder + LDM is technically possible, just not implemented yet.
|
|
* We need to revisit soon and implement it. */
|
|
RETURN_ERROR_IF(
|
|
ZSTD_hasExtSeqProd(&zc->appliedParams),
|
|
parameter_combination_unsupported,
|
|
"Long-distance matching with external sequence producer enabled is not currently supported."
|
|
);
|
|
|
|
ldmSeqStore.seq = zc->ldmSequences;
|
|
ldmSeqStore.capacity = zc->maxNbLdmSequences;
|
|
/* Updates ldmSeqStore.size */
|
|
FORWARD_IF_ERROR(ZSTD_ldm_generateSequences(&zc->ldmState, &ldmSeqStore,
|
|
&zc->appliedParams.ldmParams,
|
|
src, srcSize), "");
|
|
/* Updates ldmSeqStore.pos */
|
|
lastLLSize =
|
|
ZSTD_ldm_blockCompress(&ldmSeqStore,
|
|
ms, &zc->seqStore,
|
|
zc->blockState.nextCBlock->rep,
|
|
zc->appliedParams.useRowMatchFinder,
|
|
src, srcSize);
|
|
assert(ldmSeqStore.pos == ldmSeqStore.size);
|
|
} else if (ZSTD_hasExtSeqProd(&zc->appliedParams)) {
|
|
assert(
|
|
zc->extSeqBufCapacity >= ZSTD_sequenceBound(srcSize)
|
|
);
|
|
assert(zc->appliedParams.extSeqProdFunc != NULL);
|
|
|
|
{ U32 const windowSize = (U32)1 << zc->appliedParams.cParams.windowLog;
|
|
|
|
size_t const nbExternalSeqs = (zc->appliedParams.extSeqProdFunc)(
|
|
zc->appliedParams.extSeqProdState,
|
|
zc->extSeqBuf,
|
|
zc->extSeqBufCapacity,
|
|
src, srcSize,
|
|
NULL, 0, /* dict and dictSize, currently not supported */
|
|
zc->appliedParams.compressionLevel,
|
|
windowSize
|
|
);
|
|
|
|
size_t const nbPostProcessedSeqs = ZSTD_postProcessSequenceProducerResult(
|
|
zc->extSeqBuf,
|
|
nbExternalSeqs,
|
|
zc->extSeqBufCapacity,
|
|
srcSize
|
|
);
|
|
|
|
/* Return early if there is no error, since we don't need to worry about last literals */
|
|
if (!ZSTD_isError(nbPostProcessedSeqs)) {
|
|
ZSTD_SequencePosition seqPos = {0,0,0};
|
|
size_t const seqLenSum = ZSTD_fastSequenceLengthSum(zc->extSeqBuf, nbPostProcessedSeqs);
|
|
RETURN_ERROR_IF(seqLenSum > srcSize, externalSequences_invalid, "External sequences imply too large a block!");
|
|
FORWARD_IF_ERROR(
|
|
ZSTD_transferSequences_wBlockDelim(
|
|
zc, &seqPos,
|
|
zc->extSeqBuf, nbPostProcessedSeqs,
|
|
src, srcSize,
|
|
zc->appliedParams.searchForExternalRepcodes
|
|
),
|
|
"Failed to copy external sequences to seqStore!"
|
|
);
|
|
ms->ldmSeqStore = NULL;
|
|
DEBUGLOG(5, "Copied %lu sequences from external sequence producer to internal seqStore.", (unsigned long)nbExternalSeqs);
|
|
return ZSTDbss_compress;
|
|
}
|
|
|
|
/* Propagate the error if fallback is disabled */
|
|
if (!zc->appliedParams.enableMatchFinderFallback) {
|
|
return nbPostProcessedSeqs;
|
|
}
|
|
|
|
/* Fallback to software matchfinder */
|
|
{ ZSTD_BlockCompressor_f const blockCompressor =
|
|
ZSTD_selectBlockCompressor(
|
|
zc->appliedParams.cParams.strategy,
|
|
zc->appliedParams.useRowMatchFinder,
|
|
dictMode);
|
|
ms->ldmSeqStore = NULL;
|
|
DEBUGLOG(
|
|
5,
|
|
"External sequence producer returned error code %lu. Falling back to internal parser.",
|
|
(unsigned long)nbExternalSeqs
|
|
);
|
|
lastLLSize = blockCompressor(ms, &zc->seqStore, zc->blockState.nextCBlock->rep, src, srcSize);
|
|
} }
|
|
} else { /* not long range mode and no external matchfinder */
|
|
ZSTD_BlockCompressor_f const blockCompressor = ZSTD_selectBlockCompressor(
|
|
zc->appliedParams.cParams.strategy,
|
|
zc->appliedParams.useRowMatchFinder,
|
|
dictMode);
|
|
ms->ldmSeqStore = NULL;
|
|
lastLLSize = blockCompressor(ms, &zc->seqStore, zc->blockState.nextCBlock->rep, src, srcSize);
|
|
}
|
|
{ const BYTE* const lastLiterals = (const BYTE*)src + srcSize - lastLLSize;
|
|
ZSTD_storeLastLiterals(&zc->seqStore, lastLiterals, lastLLSize);
|
|
} }
|
|
ZSTD_validateSeqStore(&zc->seqStore, &zc->appliedParams.cParams);
|
|
return ZSTDbss_compress;
|
|
}
|
|
|
|
static size_t ZSTD_copyBlockSequences(SeqCollector* seqCollector, const SeqStore_t* seqStore, const U32 prevRepcodes[ZSTD_REP_NUM])
|
|
{
|
|
/* The implementation lives in rust/src/zstd_compress_stats.rs. */
|
|
return ZSTD_rust_copyBlockSequences(seqCollector, seqStore, prevRepcodes);
|
|
}
|
|
|
|
/* ZSTD_sequenceBound() lives in rust/src/zstd_compress_api.rs. */
|
|
|
|
size_t ZSTD_generateSequences(ZSTD_CCtx* zc, ZSTD_Sequence* outSeqs,
|
|
size_t outSeqsSize, const void* src, size_t srcSize)
|
|
{
|
|
const size_t dstCapacity = ZSTD_compressBound(srcSize);
|
|
void* dst; /* Make C90 happy. */
|
|
SeqCollector seqCollector;
|
|
{
|
|
int targetCBlockSize;
|
|
FORWARD_IF_ERROR(ZSTD_CCtx_getParameter(zc, ZSTD_c_targetCBlockSize, &targetCBlockSize), "");
|
|
RETURN_ERROR_IF(targetCBlockSize != 0, parameter_unsupported, "targetCBlockSize != 0");
|
|
}
|
|
{
|
|
int nbWorkers;
|
|
FORWARD_IF_ERROR(ZSTD_CCtx_getParameter(zc, ZSTD_c_nbWorkers, &nbWorkers), "");
|
|
RETURN_ERROR_IF(nbWorkers != 0, parameter_unsupported, "nbWorkers != 0");
|
|
}
|
|
|
|
dst = ZSTD_customMalloc(dstCapacity, ZSTD_defaultCMem);
|
|
RETURN_ERROR_IF(dst == NULL, memory_allocation, "NULL pointer!");
|
|
|
|
seqCollector.collectSequences = 1;
|
|
seqCollector.seqStart = outSeqs;
|
|
seqCollector.seqIndex = 0;
|
|
seqCollector.maxSequences = outSeqsSize;
|
|
zc->seqCollector = seqCollector;
|
|
|
|
{
|
|
const size_t ret = ZSTD_compress2(zc, dst, dstCapacity, src, srcSize);
|
|
ZSTD_customFree(dst, ZSTD_defaultCMem);
|
|
FORWARD_IF_ERROR(ret, "ZSTD_compress2 failed");
|
|
}
|
|
assert(zc->seqCollector.seqIndex <= ZSTD_sequenceBound(srcSize));
|
|
return zc->seqCollector.seqIndex;
|
|
}
|
|
|
|
/* ZSTD_mergeBlockDelimiters() lives in rust/src/zstd_compress_api.rs. */
|
|
|
|
/* Unrolled loop to read four size_ts of input at a time. Returns 1 if is RLE, 0 if not. */
|
|
static int ZSTD_isRLE(const BYTE* src, size_t length) {
|
|
return ZSTD_rust_isRLE(src, length);
|
|
}
|
|
|
|
/* Returns true if the given block may be RLE.
|
|
* This is just a heuristic based on the compressibility.
|
|
* It may return both false positives and false negatives.
|
|
*/
|
|
static int ZSTD_maybeRLE(SeqStore_t const* seqStore)
|
|
{
|
|
return ZSTD_rust_maybeRLE(seqStore);
|
|
}
|
|
|
|
static void
|
|
ZSTD_blockState_confirmRepcodesAndEntropyTables(ZSTD_blockState_t* const bs)
|
|
{
|
|
ZSTD_rust_confirmRepcodesAndEntropyTables(
|
|
&bs->prevCBlock, &bs->nextCBlock);
|
|
}
|
|
|
|
/* Writes the block header */
|
|
static void
|
|
writeBlockHeader(void* op, size_t cSize, size_t blockSize, U32 lastBlock)
|
|
{
|
|
ZSTD_rust_writeBlockHeader(op, cSize, blockSize, lastBlock);
|
|
DEBUGLOG(5, "writeBlockHeader: cSize: %zu blockSize: %zu lastBlock: %u", cSize, blockSize, lastBlock);
|
|
}
|
|
|
|
/** ZSTD_buildBlockEntropyStats() :
|
|
* Builds entropy for the block.
|
|
* Requires workspace size ENTROPY_WORKSPACE_SIZE
|
|
* @return : 0 on success, or an error code
|
|
* Note : also employed in superblock
|
|
*
|
|
* The implementation, together with its literals/sequences/dummy helpers,
|
|
* lives in rust/src/zstd_compress_stats.rs.
|
|
*/
|
|
size_t ZSTD_buildBlockEntropyStats(
|
|
const SeqStore_t* seqStorePtr,
|
|
const ZSTD_entropyCTables_t* prevEntropy,
|
|
ZSTD_entropyCTables_t* nextEntropy,
|
|
const ZSTD_CCtx_params* cctxParams,
|
|
ZSTD_entropyCTablesMetadata_t* entropyMetadata,
|
|
void* workspace, size_t wkspSize)
|
|
{
|
|
return ZSTD_rust_buildBlockEntropyStats(
|
|
seqStorePtr, prevEntropy, nextEntropy,
|
|
(int)cctxParams->cParams.strategy,
|
|
ZSTD_literalsCompressionIsDisabled(cctxParams),
|
|
entropyMetadata,
|
|
workspace, wkspSize);
|
|
}
|
|
|
|
/* The block-size estimator is implemented in Rust; C retains the stateful
|
|
* block-splitting recursion and the entropy-table ownership. */
|
|
static size_t
|
|
ZSTD_estimateBlockSize(const BYTE* literals, size_t litSize,
|
|
const BYTE* ofCodeTable,
|
|
const BYTE* llCodeTable,
|
|
const BYTE* mlCodeTable,
|
|
size_t nbSeq,
|
|
const ZSTD_entropyCTables_t* entropy,
|
|
const ZSTD_entropyCTablesMetadata_t* entropyMetadata,
|
|
void* workspace, size_t wkspSize,
|
|
int writeLitEntropy, int writeSeqEntropy)
|
|
{
|
|
return ZSTD_rust_estimateBlockSize(
|
|
literals, litSize,
|
|
ofCodeTable, llCodeTable, mlCodeTable, nbSeq,
|
|
entropy, entropyMetadata,
|
|
workspace, wkspSize,
|
|
writeLitEntropy, writeSeqEntropy);
|
|
}
|
|
|
|
/* Builds entropy statistics and uses them for blocksize estimation.
|
|
*
|
|
* @return: estimated compressed size of the seqStore, or a zstd error.
|
|
*/
|
|
UNUSED_ATTR static size_t
|
|
ZSTD_buildEntropyStatisticsAndEstimateSubBlockSize(SeqStore_t* seqStore, ZSTD_CCtx* zc)
|
|
{
|
|
ZSTD_entropyCTablesMetadata_t* const entropyMetadata = &zc->blockSplitCtx.entropyMetadata;
|
|
DEBUGLOG(6, "ZSTD_buildEntropyStatisticsAndEstimateSubBlockSize()");
|
|
FORWARD_IF_ERROR(ZSTD_buildBlockEntropyStats(seqStore,
|
|
&zc->blockState.prevCBlock->entropy,
|
|
&zc->blockState.nextCBlock->entropy,
|
|
&zc->appliedParams,
|
|
entropyMetadata,
|
|
zc->tmpWorkspace, zc->tmpWkspSize), "");
|
|
return ZSTD_estimateBlockSize(
|
|
seqStore->litStart, (size_t)(seqStore->lit - seqStore->litStart),
|
|
seqStore->ofCode, seqStore->llCode, seqStore->mlCode,
|
|
(size_t)(seqStore->sequences - seqStore->sequencesStart),
|
|
&zc->blockState.nextCBlock->entropy,
|
|
entropyMetadata,
|
|
zc->tmpWorkspace, zc->tmpWkspSize,
|
|
(int)(entropyMetadata->hufMetadata.hType == set_compressed), 1);
|
|
}
|
|
|
|
/* Returns literals bytes represented in a seqStore */
|
|
static size_t ZSTD_countSeqStoreLiteralsBytes(const SeqStore_t* const seqStore)
|
|
{
|
|
return ZSTD_rust_countSeqStoreLiteralsBytes(seqStore);
|
|
}
|
|
|
|
/* Returns match bytes represented in a seqStore */
|
|
static size_t ZSTD_countSeqStoreMatchBytes(const SeqStore_t* const seqStore)
|
|
{
|
|
return ZSTD_rust_countSeqStoreMatchBytes(seqStore);
|
|
}
|
|
|
|
/* Derives the seqStore that is a chunk of the originalSeqStore from [startIdx, endIdx).
|
|
* Stores the result in resultSeqStore.
|
|
*/
|
|
static void ZSTD_deriveSeqStoreChunk(SeqStore_t* resultSeqStore,
|
|
const SeqStore_t* originalSeqStore,
|
|
size_t startIdx, size_t endIdx)
|
|
{
|
|
ZSTD_rust_deriveSeqStoreChunk(resultSeqStore, originalSeqStore,
|
|
startIdx, endIdx);
|
|
}
|
|
|
|
/**
|
|
* ZSTD_seqStore_resolveOffCodes() reconciles any possible divergences in offset history that may arise
|
|
* due to emission of RLE/raw blocks that disturb the offset history,
|
|
* and replaces any repcodes within the seqStore that may be invalid.
|
|
*
|
|
* dRepcodes are updated as would be on the decompression side.
|
|
* cRepcodes are updated exactly in accordance with the seqStore.
|
|
*
|
|
* Note : this function assumes seq->offBase respects the following numbering scheme :
|
|
* 0 : invalid
|
|
* 1-3 : repcode 1-3
|
|
* 4+ : real_offset+3
|
|
*/
|
|
static void
|
|
ZSTD_seqStore_resolveOffCodes(Repcodes_t* const dRepcodes, Repcodes_t* const cRepcodes,
|
|
const SeqStore_t* const seqStore, U32 const nbSeq)
|
|
{
|
|
ZSTD_rust_seqStore_resolveOffCodes(dRepcodes->rep, cRepcodes->rep,
|
|
seqStore, nbSeq);
|
|
}
|
|
|
|
/* ZSTD_compressSeqStore_singleBlock():
|
|
* Compresses a seqStore into a block with a block header, into the buffer dst.
|
|
*
|
|
* Returns the total size of that block (including header) or a ZSTD error code.
|
|
*/
|
|
static size_t
|
|
ZSTD_compressSeqStore_singleBlock(ZSTD_CCtx* zc,
|
|
const SeqStore_t* const seqStore,
|
|
Repcodes_t* const dRep, Repcodes_t* const cRep,
|
|
void* dst, size_t dstCapacity,
|
|
const void* src, size_t srcSize,
|
|
U32 lastBlock, U32 isPartition)
|
|
{
|
|
const U32 rleMaxLength = 25;
|
|
BYTE* op = (BYTE*)dst;
|
|
const BYTE* ip = (const BYTE*)src;
|
|
size_t cSize;
|
|
size_t cSeqsSize;
|
|
|
|
/* In case of an RLE or raw block, the simulated decompression repcode history must be reset */
|
|
Repcodes_t const dRepOriginal = *dRep;
|
|
DEBUGLOG(5, "ZSTD_compressSeqStore_singleBlock");
|
|
if (isPartition)
|
|
ZSTD_seqStore_resolveOffCodes(dRep, cRep, seqStore, (U32)(seqStore->sequences - seqStore->sequencesStart));
|
|
|
|
RETURN_ERROR_IF(dstCapacity < ZSTD_blockHeaderSize, dstSize_tooSmall, "Block header doesn't fit");
|
|
cSeqsSize = ZSTD_entropyCompressSeqStore(seqStore,
|
|
&zc->blockState.prevCBlock->entropy, &zc->blockState.nextCBlock->entropy,
|
|
&zc->appliedParams,
|
|
op + ZSTD_blockHeaderSize, dstCapacity - ZSTD_blockHeaderSize,
|
|
srcSize,
|
|
zc->tmpWorkspace, zc->tmpWkspSize /* statically allocated in resetCCtx */,
|
|
zc->bmi2);
|
|
FORWARD_IF_ERROR(cSeqsSize, "ZSTD_entropyCompressSeqStore failed!");
|
|
|
|
if (!zc->isFirstBlock &&
|
|
cSeqsSize < rleMaxLength &&
|
|
ZSTD_isRLE((BYTE const*)src, srcSize)) {
|
|
/* We don't want to emit our first block as a RLE even if it qualifies because
|
|
* doing so will cause the decoder (cli only) to throw a "should consume all input error."
|
|
* This is only an issue for zstd <= v1.4.3
|
|
*/
|
|
cSeqsSize = 1;
|
|
}
|
|
|
|
/* Sequence collection not supported when block splitting */
|
|
if (zc->seqCollector.collectSequences) {
|
|
FORWARD_IF_ERROR(ZSTD_copyBlockSequences(&zc->seqCollector, seqStore, dRepOriginal.rep), "copyBlockSequences failed");
|
|
ZSTD_blockState_confirmRepcodesAndEntropyTables(&zc->blockState);
|
|
return 0;
|
|
}
|
|
|
|
if (cSeqsSize == 0) {
|
|
cSize = ZSTD_rust_noCompressBlock(op, dstCapacity, ip, srcSize, lastBlock);
|
|
FORWARD_IF_ERROR(cSize, "Nocompress block failed");
|
|
DEBUGLOG(5, "Writing out nocompress block, size: %zu", cSize);
|
|
*dRep = dRepOriginal; /* reset simulated decompression repcode history */
|
|
} else if (cSeqsSize == 1) {
|
|
cSize = ZSTD_rust_rleCompressBlock(op, dstCapacity, *ip, srcSize, lastBlock);
|
|
FORWARD_IF_ERROR(cSize, "RLE compress block failed");
|
|
DEBUGLOG(5, "Writing out RLE block, size: %zu", cSize);
|
|
*dRep = dRepOriginal; /* reset simulated decompression repcode history */
|
|
} else {
|
|
ZSTD_blockState_confirmRepcodesAndEntropyTables(&zc->blockState);
|
|
writeBlockHeader(op, cSeqsSize, srcSize, lastBlock);
|
|
cSize = ZSTD_blockHeaderSize + cSeqsSize;
|
|
DEBUGLOG(5, "Writing out compressed block, size: %zu", cSize);
|
|
}
|
|
|
|
if (zc->blockState.prevCBlock->entropy.fse.offcode_repeatMode == FSE_repeat_valid)
|
|
zc->blockState.prevCBlock->entropy.fse.offcode_repeatMode = FSE_repeat_check;
|
|
|
|
return cSize;
|
|
}
|
|
|
|
/* Base recursive function.
|
|
* Populates a table with intra-block partition indices that can improve compression ratio.
|
|
*
|
|
* @return: number of splits made (which equals the size of the partition table - 1).
|
|
*/
|
|
static size_t ZSTD_deriveBlockSplits(ZSTD_CCtx* zc, U32 partitions[], U32 nbSeq)
|
|
{
|
|
return ZSTD_rust_deriveBlockSplits(
|
|
partitions, nbSeq,
|
|
&zc->seqStore,
|
|
&zc->blockSplitCtx.fullSeqStoreChunk,
|
|
&zc->blockSplitCtx.firstHalfSeqStore,
|
|
&zc->blockSplitCtx.secondHalfSeqStore,
|
|
&zc->blockState.prevCBlock->entropy,
|
|
&zc->blockState.nextCBlock->entropy,
|
|
(int)zc->appliedParams.cParams.strategy,
|
|
ZSTD_literalsCompressionIsDisabled(&zc->appliedParams),
|
|
&zc->blockSplitCtx.entropyMetadata,
|
|
zc->tmpWorkspace,
|
|
zc->tmpWkspSize);
|
|
}
|
|
|
|
/* ZSTD_compressBlock_splitBlock():
|
|
* Attempts to split a given block into multiple blocks to improve compression ratio.
|
|
*
|
|
* Returns combined size of all blocks (which includes headers), or a ZSTD error code.
|
|
*/
|
|
static size_t
|
|
ZSTD_compressBlock_splitBlock_internal(ZSTD_CCtx* zc,
|
|
void* dst, size_t dstCapacity,
|
|
const void* src, size_t blockSize,
|
|
U32 lastBlock, U32 nbSeq)
|
|
{
|
|
size_t cSize = 0;
|
|
const BYTE* ip = (const BYTE*)src;
|
|
BYTE* op = (BYTE*)dst;
|
|
size_t i = 0;
|
|
size_t srcBytesTotal = 0;
|
|
U32* const partitions = zc->blockSplitCtx.partitions; /* splits plus the terminal boundary */
|
|
SeqStore_t* const nextSeqStore = &zc->blockSplitCtx.nextSeqStore;
|
|
SeqStore_t* const currSeqStore = &zc->blockSplitCtx.currSeqStore;
|
|
size_t const numSplits = ZSTD_deriveBlockSplits(zc, partitions, nbSeq);
|
|
|
|
/* If a block is split and some partitions are emitted as RLE/uncompressed, then repcode history
|
|
* may become invalid. In order to reconcile potentially invalid repcodes, we keep track of two
|
|
* separate repcode histories that simulate repcode history on compression and decompression side,
|
|
* and use the histories to determine whether we must replace a particular repcode with its raw offset.
|
|
*
|
|
* 1) cRep gets updated for each partition, regardless of whether the block was emitted as uncompressed
|
|
* or RLE. This allows us to retrieve the offset value that an invalid repcode references within
|
|
* a nocompress/RLE block.
|
|
* 2) dRep gets updated only for compressed partitions, and when a repcode gets replaced, will use
|
|
* the replacement offset value rather than the original repcode to update the repcode history.
|
|
* dRep also will be the final repcode history sent to the next block.
|
|
*
|
|
* See ZSTD_seqStore_resolveOffCodes() for more details.
|
|
*/
|
|
Repcodes_t dRep;
|
|
Repcodes_t cRep;
|
|
ZSTD_memcpy(dRep.rep, zc->blockState.prevCBlock->rep, sizeof(Repcodes_t));
|
|
ZSTD_memcpy(cRep.rep, zc->blockState.prevCBlock->rep, sizeof(Repcodes_t));
|
|
ZSTD_memset(nextSeqStore, 0, sizeof(SeqStore_t));
|
|
|
|
DEBUGLOG(5, "ZSTD_compressBlock_splitBlock_internal (dstCapacity=%u, dictLimit=%u, nextToUpdate=%u)",
|
|
(unsigned)dstCapacity, (unsigned)zc->blockState.matchState.window.dictLimit,
|
|
(unsigned)zc->blockState.matchState.nextToUpdate);
|
|
|
|
if (numSplits == 0) {
|
|
size_t cSizeSingleBlock =
|
|
ZSTD_compressSeqStore_singleBlock(zc, &zc->seqStore,
|
|
&dRep, &cRep,
|
|
op, dstCapacity,
|
|
ip, blockSize,
|
|
lastBlock, 0 /* isPartition */);
|
|
FORWARD_IF_ERROR(cSizeSingleBlock, "Compressing single block from splitBlock_internal() failed!");
|
|
DEBUGLOG(5, "ZSTD_compressBlock_splitBlock_internal: No splits");
|
|
assert(zc->blockSizeMax <= ZSTD_BLOCKSIZE_MAX);
|
|
assert(cSizeSingleBlock <= zc->blockSizeMax + ZSTD_blockHeaderSize);
|
|
return cSizeSingleBlock;
|
|
}
|
|
|
|
ZSTD_deriveSeqStoreChunk(currSeqStore, &zc->seqStore, 0, partitions[0]);
|
|
for (i = 0; i <= numSplits; ++i) {
|
|
size_t cSizeChunk;
|
|
U32 const lastPartition = (i == numSplits);
|
|
U32 lastBlockEntireSrc = 0;
|
|
|
|
size_t srcBytes = ZSTD_countSeqStoreLiteralsBytes(currSeqStore) + ZSTD_countSeqStoreMatchBytes(currSeqStore);
|
|
srcBytesTotal += srcBytes;
|
|
if (lastPartition) {
|
|
/* This is the final partition, need to account for possible last literals */
|
|
srcBytes += blockSize - srcBytesTotal;
|
|
lastBlockEntireSrc = lastBlock;
|
|
} else {
|
|
ZSTD_deriveSeqStoreChunk(nextSeqStore, &zc->seqStore, partitions[i], partitions[i+1]);
|
|
}
|
|
|
|
cSizeChunk = ZSTD_compressSeqStore_singleBlock(zc, currSeqStore,
|
|
&dRep, &cRep,
|
|
op, dstCapacity,
|
|
ip, srcBytes,
|
|
lastBlockEntireSrc, 1 /* isPartition */);
|
|
DEBUGLOG(5, "Estimated size: %zu vs %zu : actual size",
|
|
ZSTD_buildEntropyStatisticsAndEstimateSubBlockSize(currSeqStore, zc), cSizeChunk);
|
|
FORWARD_IF_ERROR(cSizeChunk, "Compressing chunk failed!");
|
|
|
|
ip += srcBytes;
|
|
op += cSizeChunk;
|
|
dstCapacity -= cSizeChunk;
|
|
cSize += cSizeChunk;
|
|
*currSeqStore = *nextSeqStore;
|
|
assert(cSizeChunk <= zc->blockSizeMax + ZSTD_blockHeaderSize);
|
|
}
|
|
/* cRep and dRep may have diverged during the compression.
|
|
* If so, we use the dRep repcodes for the next block.
|
|
*/
|
|
ZSTD_memcpy(zc->blockState.prevCBlock->rep, dRep.rep, sizeof(Repcodes_t));
|
|
return cSize;
|
|
}
|
|
|
|
static size_t
|
|
ZSTD_compressBlock_splitBlock(ZSTD_CCtx* zc,
|
|
void* dst, size_t dstCapacity,
|
|
const void* src, size_t srcSize, U32 lastBlock)
|
|
{
|
|
U32 nbSeq;
|
|
size_t cSize;
|
|
DEBUGLOG(5, "ZSTD_compressBlock_splitBlock");
|
|
assert(zc->appliedParams.postBlockSplitter == ZSTD_ps_enable);
|
|
|
|
{ const size_t bss = ZSTD_buildSeqStore(zc, src, srcSize);
|
|
FORWARD_IF_ERROR(bss, "ZSTD_buildSeqStore failed");
|
|
if (bss == ZSTDbss_noCompress) {
|
|
if (zc->blockState.prevCBlock->entropy.fse.offcode_repeatMode == FSE_repeat_valid)
|
|
zc->blockState.prevCBlock->entropy.fse.offcode_repeatMode = FSE_repeat_check;
|
|
RETURN_ERROR_IF(zc->seqCollector.collectSequences, sequenceProducer_failed, "Uncompressible block");
|
|
cSize = ZSTD_rust_noCompressBlock(dst, dstCapacity, src, srcSize, lastBlock);
|
|
FORWARD_IF_ERROR(cSize, "ZSTD_noCompressBlock failed");
|
|
DEBUGLOG(5, "ZSTD_compressBlock_splitBlock: Nocompress block");
|
|
return cSize;
|
|
}
|
|
nbSeq = (U32)(zc->seqStore.sequences - zc->seqStore.sequencesStart);
|
|
}
|
|
|
|
cSize = ZSTD_compressBlock_splitBlock_internal(zc, dst, dstCapacity, src, srcSize, lastBlock, nbSeq);
|
|
FORWARD_IF_ERROR(cSize, "Splitting blocks failed!");
|
|
return cSize;
|
|
}
|
|
|
|
static size_t
|
|
ZSTD_compressBlock_internal(ZSTD_CCtx* zc,
|
|
void* dst, size_t dstCapacity,
|
|
const void* src, size_t srcSize, U32 frame)
|
|
{
|
|
/* This is an estimated upper bound for the length of an rle block.
|
|
* This isn't the actual upper bound.
|
|
* Finding the real threshold needs further investigation.
|
|
*/
|
|
const U32 rleMaxLength = 25;
|
|
size_t cSize;
|
|
const BYTE* ip = (const BYTE*)src;
|
|
BYTE* op = (BYTE*)dst;
|
|
DEBUGLOG(5, "ZSTD_compressBlock_internal (dstCapacity=%u, dictLimit=%u, nextToUpdate=%u)",
|
|
(unsigned)dstCapacity, (unsigned)zc->blockState.matchState.window.dictLimit,
|
|
(unsigned)zc->blockState.matchState.nextToUpdate);
|
|
|
|
{ const size_t bss = ZSTD_buildSeqStore(zc, src, srcSize);
|
|
FORWARD_IF_ERROR(bss, "ZSTD_buildSeqStore failed");
|
|
if (bss == ZSTDbss_noCompress) {
|
|
RETURN_ERROR_IF(zc->seqCollector.collectSequences, sequenceProducer_failed, "Uncompressible block");
|
|
cSize = 0;
|
|
goto out;
|
|
}
|
|
}
|
|
|
|
if (zc->seqCollector.collectSequences) {
|
|
FORWARD_IF_ERROR(ZSTD_copyBlockSequences(&zc->seqCollector, ZSTD_getSeqStore(zc), zc->blockState.prevCBlock->rep), "copyBlockSequences failed");
|
|
ZSTD_blockState_confirmRepcodesAndEntropyTables(&zc->blockState);
|
|
return 0;
|
|
}
|
|
|
|
/* encode sequences and literals */
|
|
cSize = ZSTD_entropyCompressSeqStore(&zc->seqStore,
|
|
&zc->blockState.prevCBlock->entropy, &zc->blockState.nextCBlock->entropy,
|
|
&zc->appliedParams,
|
|
dst, dstCapacity,
|
|
srcSize,
|
|
zc->tmpWorkspace, zc->tmpWkspSize /* statically allocated in resetCCtx */,
|
|
zc->bmi2);
|
|
|
|
if (frame &&
|
|
/* We don't want to emit our first block as a RLE even if it qualifies because
|
|
* doing so will cause the decoder (cli only) to throw a "should consume all input error."
|
|
* This is only an issue for zstd <= v1.4.3
|
|
*/
|
|
!zc->isFirstBlock &&
|
|
cSize < rleMaxLength &&
|
|
ZSTD_isRLE(ip, srcSize))
|
|
{
|
|
cSize = 1;
|
|
op[0] = ip[0];
|
|
}
|
|
|
|
out:
|
|
if (!ZSTD_isError(cSize) && cSize > 1) {
|
|
ZSTD_blockState_confirmRepcodesAndEntropyTables(&zc->blockState);
|
|
}
|
|
/* We check that dictionaries have offset codes available for the first
|
|
* block. After the first block, the offcode table might not have large
|
|
* enough codes to represent the offsets in the data.
|
|
*/
|
|
if (zc->blockState.prevCBlock->entropy.fse.offcode_repeatMode == FSE_repeat_valid)
|
|
zc->blockState.prevCBlock->entropy.fse.offcode_repeatMode = FSE_repeat_check;
|
|
|
|
return cSize;
|
|
}
|
|
|
|
static size_t ZSTD_compressBlock_targetCBlockSize_body(ZSTD_CCtx* zc,
|
|
void* dst, size_t dstCapacity,
|
|
const void* src, size_t srcSize,
|
|
const size_t bss, U32 lastBlock)
|
|
{
|
|
int const isCompress = bss == ZSTDbss_compress;
|
|
int maybeRLE = 0;
|
|
int isRLE = 0;
|
|
int action;
|
|
|
|
DEBUGLOG(6, "Attempting ZSTD_compressSuperBlock()");
|
|
if (isCompress) {
|
|
maybeRLE = ZSTD_maybeRLE(&zc->seqStore);
|
|
isRLE = ZSTD_isRLE((BYTE const*)src, srcSize);
|
|
}
|
|
|
|
action = ZSTD_rust_targetCBlockSizeAction(
|
|
(int)bss, (int)zc->isFirstBlock, maybeRLE, isRLE,
|
|
0, srcSize, (int)zc->appliedParams.cParams.strategy);
|
|
if (action == ZSTD_RUST_TARGET_CBLOCK_ACTION_RLE) {
|
|
return ZSTD_rust_rleCompressBlock(dst, dstCapacity, *(BYTE const*)src, srcSize, lastBlock);
|
|
}
|
|
|
|
if (isCompress) {
|
|
/* Attempt superblock compression.
|
|
*
|
|
* Note that compressed size of ZSTD_compressSuperBlock() is not bound by the
|
|
* standard ZSTD_compressBound(). This is a problem, because even if we have
|
|
* space now, taking an extra byte now could cause us to run out of space later
|
|
* and violate ZSTD_compressBound().
|
|
*
|
|
* Define blockBound(blockSize) = blockSize + ZSTD_blockHeaderSize.
|
|
*
|
|
* In order to respect ZSTD_compressBound() we must attempt to emit a raw
|
|
* uncompressed block in these cases:
|
|
* * cSize == 0: Return code for an uncompressed block.
|
|
* * cSize == dstSize_tooSmall: We may have expanded beyond blockBound(srcSize).
|
|
* ZSTD_noCompressBlock() will return dstSize_tooSmall if we are really out of
|
|
* output space.
|
|
* * cSize >= blockBound(srcSize): We have expanded the block too much so
|
|
* emit an uncompressed block.
|
|
*/
|
|
{ size_t const cSize =
|
|
ZSTD_compressSuperBlock(zc, dst, dstCapacity, src, srcSize, lastBlock);
|
|
action = ZSTD_rust_targetCBlockSizeAction(
|
|
(int)bss, (int)zc->isFirstBlock, 0, 0,
|
|
cSize, srcSize, (int)zc->appliedParams.cParams.strategy);
|
|
if (action == ZSTD_RUST_TARGET_CBLOCK_ACTION_ERROR) {
|
|
FORWARD_IF_ERROR(cSize, "ZSTD_compressSuperBlock failed");
|
|
}
|
|
if (action == ZSTD_RUST_TARGET_CBLOCK_ACTION_COMPRESSED) {
|
|
ZSTD_blockState_confirmRepcodesAndEntropyTables(&zc->blockState);
|
|
return cSize;
|
|
}
|
|
}
|
|
} /* if (bss == ZSTDbss_compress)*/
|
|
|
|
DEBUGLOG(6, "Resorting to ZSTD_noCompressBlock()");
|
|
/* Superblock compression failed, attempt to emit a single no compress block.
|
|
* The decoder will be able to stream this block since it is uncompressed.
|
|
*/
|
|
return ZSTD_rust_noCompressBlock(dst, dstCapacity, src, srcSize, lastBlock);
|
|
}
|
|
|
|
static size_t ZSTD_compressBlock_targetCBlockSize(ZSTD_CCtx* zc,
|
|
void* dst, size_t dstCapacity,
|
|
const void* src, size_t srcSize,
|
|
U32 lastBlock)
|
|
{
|
|
size_t cSize = 0;
|
|
const size_t bss = ZSTD_buildSeqStore(zc, src, srcSize);
|
|
DEBUGLOG(5, "ZSTD_compressBlock_targetCBlockSize (dstCapacity=%u, dictLimit=%u, nextToUpdate=%u, srcSize=%zu)",
|
|
(unsigned)dstCapacity, (unsigned)zc->blockState.matchState.window.dictLimit, (unsigned)zc->blockState.matchState.nextToUpdate, srcSize);
|
|
FORWARD_IF_ERROR(bss, "ZSTD_buildSeqStore failed");
|
|
|
|
cSize = ZSTD_compressBlock_targetCBlockSize_body(zc, dst, dstCapacity, src, srcSize, bss, lastBlock);
|
|
FORWARD_IF_ERROR(cSize, "ZSTD_compressBlock_targetCBlockSize_body failed");
|
|
|
|
if (zc->blockState.prevCBlock->entropy.fse.offcode_repeatMode == FSE_repeat_valid)
|
|
zc->blockState.prevCBlock->entropy.fse.offcode_repeatMode = FSE_repeat_check;
|
|
|
|
return cSize;
|
|
}
|
|
|
|
static void ZSTD_overflowCorrectIfNeeded(ZSTD_MatchState_t* ms,
|
|
ZSTD_cwksp* ws,
|
|
ZSTD_CCtx_params const* params,
|
|
void const* ip,
|
|
void const* iend)
|
|
{
|
|
U32 const cycleLog = ZSTD_cycleLog(params->cParams.chainLog, params->cParams.strategy);
|
|
U32 const maxDist = (U32)1 << params->cParams.windowLog;
|
|
if (ZSTD_window_needOverflowCorrection(ms->window, cycleLog, maxDist, ms->loadedDictEnd, ip, iend)) {
|
|
U32 const correction = ZSTD_window_correctOverflow(&ms->window, cycleLog, maxDist, ip);
|
|
ZSTD_STATIC_ASSERT(ZSTD_CHAINLOG_MAX <= 30);
|
|
ZSTD_STATIC_ASSERT(ZSTD_WINDOWLOG_MAX_32 <= 30);
|
|
ZSTD_STATIC_ASSERT(ZSTD_WINDOWLOG_MAX <= 31);
|
|
ZSTD_cwksp_mark_tables_dirty(ws);
|
|
ZSTD_reduceIndex(ms, params, correction);
|
|
ZSTD_cwksp_mark_tables_clean(ws);
|
|
if (ms->nextToUpdate < correction) ms->nextToUpdate = 0;
|
|
else ms->nextToUpdate -= correction;
|
|
/* invalidate dictionaries on overflow correction */
|
|
ms->loadedDictEnd = 0;
|
|
ms->dictMatchState = NULL;
|
|
}
|
|
}
|
|
|
|
#include "zstd_preSplit.h"
|
|
|
|
static size_t ZSTD_optimalBlockSize(ZSTD_CCtx* cctx, const void* src, size_t srcSize, size_t blockSizeMax, int splitLevel, ZSTD_strategy strat, S64 savings)
|
|
{
|
|
return ZSTD_rust_optimalBlockSize(src, srcSize, blockSizeMax, splitLevel,
|
|
(int)strat, savings,
|
|
cctx->tmpWorkspace, cctx->tmpWkspSize);
|
|
}
|
|
|
|
/*! ZSTD_compress_frameChunk() :
|
|
* Compress a chunk of data into one or multiple blocks.
|
|
* All blocks will be terminated, all input will be consumed.
|
|
* Function will issue an error if there is not enough `dstCapacity` to hold the compressed content.
|
|
* Frame is supposed already started (header already produced)
|
|
* @return : compressed size, or an error code
|
|
*/
|
|
static size_t ZSTD_compress_frameChunk(ZSTD_CCtx* cctx,
|
|
void* dst, size_t dstCapacity,
|
|
const void* src, size_t srcSize,
|
|
U32 lastFrameChunk)
|
|
{
|
|
size_t blockSizeMax = cctx->blockSizeMax;
|
|
size_t remaining = srcSize;
|
|
const BYTE* ip = (const BYTE*)src;
|
|
BYTE* const ostart = (BYTE*)dst;
|
|
BYTE* op = ostart;
|
|
U32 const maxDist = (U32)1 << cctx->appliedParams.cParams.windowLog;
|
|
S64 savings = (S64)cctx->consumedSrcSize - (S64)cctx->producedCSize;
|
|
|
|
assert(cctx->appliedParams.cParams.windowLog <= ZSTD_WINDOWLOG_MAX);
|
|
|
|
DEBUGLOG(5, "ZSTD_compress_frameChunk (srcSize=%u, blockSizeMax=%u)", (unsigned)srcSize, (unsigned)blockSizeMax);
|
|
if (cctx->appliedParams.fParams.checksumFlag && srcSize)
|
|
XXH64_update(&cctx->xxhState, src, srcSize);
|
|
|
|
while (remaining) {
|
|
ZSTD_MatchState_t* const ms = &cctx->blockState.matchState;
|
|
size_t const blockSize = ZSTD_optimalBlockSize(cctx,
|
|
ip, remaining,
|
|
blockSizeMax,
|
|
cctx->appliedParams.preBlockSplitter_level,
|
|
cctx->appliedParams.cParams.strategy,
|
|
savings);
|
|
U32 const lastBlock = lastFrameChunk & (blockSize == remaining);
|
|
assert(blockSize <= remaining);
|
|
|
|
/* TODO: See 3090. We reduced MIN_CBLOCK_SIZE from 3 to 2 so to compensate we are adding
|
|
* additional 1. We need to revisit and change this logic to be more consistent */
|
|
RETURN_ERROR_IF(dstCapacity < ZSTD_blockHeaderSize + MIN_CBLOCK_SIZE + 1,
|
|
dstSize_tooSmall,
|
|
"not enough space to store compressed block");
|
|
|
|
ZSTD_overflowCorrectIfNeeded(
|
|
ms, &cctx->workspace, &cctx->appliedParams, ip, ip + blockSize);
|
|
ZSTD_checkDictValidity(&ms->window, ip + blockSize, maxDist, &ms->loadedDictEnd, &ms->dictMatchState);
|
|
ZSTD_window_enforceMaxDist(&ms->window, ip, maxDist, &ms->loadedDictEnd, &ms->dictMatchState);
|
|
|
|
/* Ensure hash/chain table insertion resumes no sooner than lowlimit */
|
|
if (ms->nextToUpdate < ms->window.lowLimit) ms->nextToUpdate = ms->window.lowLimit;
|
|
|
|
{ size_t cSize;
|
|
if (ZSTD_useTargetCBlockSize(&cctx->appliedParams)) {
|
|
cSize = ZSTD_compressBlock_targetCBlockSize(cctx, op, dstCapacity, ip, blockSize, lastBlock);
|
|
FORWARD_IF_ERROR(cSize, "ZSTD_compressBlock_targetCBlockSize failed");
|
|
assert(cSize > 0);
|
|
assert(cSize <= blockSize + ZSTD_blockHeaderSize);
|
|
} else if (ZSTD_blockSplitterEnabled(&cctx->appliedParams)) {
|
|
cSize = ZSTD_compressBlock_splitBlock(cctx, op, dstCapacity, ip, blockSize, lastBlock);
|
|
FORWARD_IF_ERROR(cSize, "ZSTD_compressBlock_splitBlock failed");
|
|
assert(cSize > 0 || cctx->seqCollector.collectSequences == 1);
|
|
} else {
|
|
cSize = ZSTD_compressBlock_internal(cctx,
|
|
op+ZSTD_blockHeaderSize, dstCapacity-ZSTD_blockHeaderSize,
|
|
ip, blockSize, 1 /* frame */);
|
|
FORWARD_IF_ERROR(cSize, "ZSTD_compressBlock_internal failed");
|
|
|
|
if (cSize == 0) { /* block is not compressible */
|
|
cSize = ZSTD_rust_noCompressBlock(op, dstCapacity, ip, blockSize, lastBlock);
|
|
FORWARD_IF_ERROR(cSize, "ZSTD_noCompressBlock failed");
|
|
} else {
|
|
ZSTD_rust_writeBlockHeader(op, cSize, blockSize, lastBlock);
|
|
cSize += ZSTD_blockHeaderSize;
|
|
}
|
|
} /* if (ZSTD_useTargetCBlockSize(&cctx->appliedParams))*/
|
|
|
|
/* @savings is employed to ensure that splitting doesn't worsen expansion of incompressible data.
|
|
* Without splitting, the maximum expansion is 3 bytes per full block.
|
|
* An adversarial input could attempt to fudge the split detector,
|
|
* and make it split incompressible data, resulting in more block headers.
|
|
* Note that, since ZSTD_COMPRESSBOUND() assumes a worst case scenario of 1KB per block,
|
|
* and the splitter never creates blocks that small (current lower limit is 8 KB),
|
|
* there is already no risk to expand beyond ZSTD_COMPRESSBOUND() limit.
|
|
* But if the goal is to not expand by more than 3-bytes per 128 KB full block,
|
|
* then yes, it becomes possible to make the block splitter oversplit incompressible data.
|
|
* Using @savings, we enforce an even more conservative condition,
|
|
* requiring the presence of enough savings (at least 3 bytes) to authorize splitting,
|
|
* otherwise only full blocks are used.
|
|
* But being conservative is fine,
|
|
* since splitting barely compressible blocks is not fruitful anyway */
|
|
savings += (S64)blockSize - (S64)cSize;
|
|
|
|
ip += blockSize;
|
|
assert(remaining >= blockSize);
|
|
remaining -= blockSize;
|
|
op += cSize;
|
|
assert(dstCapacity >= cSize);
|
|
dstCapacity -= cSize;
|
|
cctx->isFirstBlock = 0;
|
|
DEBUGLOG(5, "ZSTD_compress_frameChunk: adding a block of size %u",
|
|
(unsigned)cSize);
|
|
} }
|
|
|
|
if (lastFrameChunk && (op>ostart)) cctx->stage = ZSTDcs_ending;
|
|
return (size_t)(op-ostart);
|
|
}
|
|
|
|
|
|
static size_t ZSTD_writeFrameHeader(void* dst, size_t dstCapacity,
|
|
const ZSTD_CCtx_params* params,
|
|
U64 pledgedSrcSize, U32 dictID)
|
|
{
|
|
return ZSTD_rust_writeFrameHeader(dst, dstCapacity,
|
|
params->fParams.noDictIDFlag,
|
|
params->fParams.checksumFlag,
|
|
params->fParams.contentSizeFlag,
|
|
(int)params->format,
|
|
params->cParams.windowLog,
|
|
pledgedSrcSize, dictID);
|
|
}
|
|
|
|
void ZSTD_referenceExternalSequences(ZSTD_CCtx* cctx, rawSeq* seq, size_t nbSeq)
|
|
{
|
|
assert(cctx->stage == ZSTDcs_init);
|
|
assert(nbSeq == 0 || cctx->appliedParams.ldmParams.enableLdm != ZSTD_ps_enable);
|
|
cctx->externSeqStore.seq = seq;
|
|
cctx->externSeqStore.size = nbSeq;
|
|
cctx->externSeqStore.capacity = nbSeq;
|
|
cctx->externSeqStore.pos = 0;
|
|
cctx->externSeqStore.posInSequence = 0;
|
|
}
|
|
|
|
|
|
static size_t ZSTD_compressContinue_internal (ZSTD_CCtx* cctx,
|
|
void* dst, size_t dstCapacity,
|
|
const void* src, size_t srcSize,
|
|
U32 frame, U32 lastFrameChunk)
|
|
{
|
|
ZSTD_MatchState_t* const ms = &cctx->blockState.matchState;
|
|
size_t fhSize = 0;
|
|
|
|
DEBUGLOG(5, "ZSTD_compressContinue_internal, stage: %u, srcSize: %u",
|
|
cctx->stage, (unsigned)srcSize);
|
|
RETURN_ERROR_IF(cctx->stage==ZSTDcs_created, stage_wrong,
|
|
"missing init (ZSTD_compressBegin)");
|
|
|
|
if (frame && (cctx->stage==ZSTDcs_init)) {
|
|
fhSize = ZSTD_writeFrameHeader(dst, dstCapacity, &cctx->appliedParams,
|
|
cctx->pledgedSrcSizePlusOne-1, cctx->dictID);
|
|
FORWARD_IF_ERROR(fhSize, "ZSTD_writeFrameHeader failed");
|
|
assert(fhSize <= dstCapacity);
|
|
dstCapacity -= fhSize;
|
|
dst = (char*)dst + fhSize;
|
|
cctx->stage = ZSTDcs_ongoing;
|
|
}
|
|
|
|
if (!srcSize) return fhSize; /* do not generate an empty block if no input */
|
|
|
|
if (!ZSTD_window_update(&ms->window, src, srcSize, ms->forceNonContiguous)) {
|
|
ms->forceNonContiguous = 0;
|
|
ms->nextToUpdate = ms->window.dictLimit;
|
|
}
|
|
if (cctx->appliedParams.ldmParams.enableLdm == ZSTD_ps_enable) {
|
|
ZSTD_window_update(&cctx->ldmState.window, src, srcSize, /* forceNonContiguous */ 0);
|
|
}
|
|
|
|
if (!frame) {
|
|
/* overflow check and correction for block mode */
|
|
ZSTD_overflowCorrectIfNeeded(
|
|
ms, &cctx->workspace, &cctx->appliedParams,
|
|
src, (BYTE const*)src + srcSize);
|
|
}
|
|
|
|
DEBUGLOG(5, "ZSTD_compressContinue_internal (blockSize=%u)", (unsigned)cctx->blockSizeMax);
|
|
{ size_t const cSize = frame ?
|
|
ZSTD_compress_frameChunk (cctx, dst, dstCapacity, src, srcSize, lastFrameChunk) :
|
|
ZSTD_compressBlock_internal (cctx, dst, dstCapacity, src, srcSize, 0 /* frame */);
|
|
int srcSizeWrong;
|
|
FORWARD_IF_ERROR(cSize, "%s", frame ? "ZSTD_compress_frameChunk failed" : "ZSTD_compressBlock_internal failed");
|
|
srcSizeWrong = ZSTD_rust_updateFrameProgression(
|
|
&cctx->consumedSrcSize, &cctx->producedCSize,
|
|
cctx->pledgedSrcSizePlusOne, srcSize, cSize, fhSize);
|
|
assert(!(cctx->appliedParams.fParams.contentSizeFlag && cctx->pledgedSrcSizePlusOne == 0));
|
|
if (cctx->pledgedSrcSizePlusOne != 0) { /* control src size */
|
|
ZSTD_STATIC_ASSERT(ZSTD_CONTENTSIZE_UNKNOWN == (unsigned long long)-1);
|
|
RETURN_ERROR_IF(
|
|
srcSizeWrong,
|
|
srcSize_wrong,
|
|
"error : pledgedSrcSize = %u, while realSrcSize >= %u",
|
|
(unsigned)cctx->pledgedSrcSizePlusOne-1,
|
|
(unsigned)cctx->consumedSrcSize);
|
|
}
|
|
return cSize + fhSize;
|
|
}
|
|
}
|
|
|
|
size_t ZSTD_compressContinue_public(ZSTD_CCtx* cctx,
|
|
void* dst, size_t dstCapacity,
|
|
const void* src, size_t srcSize)
|
|
{
|
|
DEBUGLOG(5, "ZSTD_compressContinue (srcSize=%u)", (unsigned)srcSize);
|
|
return ZSTD_compressContinue_internal(cctx, dst, dstCapacity, src, srcSize, 1 /* frame mode */, 0 /* last chunk */);
|
|
}
|
|
|
|
/* NOTE: Must just wrap ZSTD_compressContinue_public() */
|
|
size_t ZSTD_compressContinue(ZSTD_CCtx* cctx,
|
|
void* dst, size_t dstCapacity,
|
|
const void* src, size_t srcSize)
|
|
{
|
|
return ZSTD_compressContinue_public(cctx, dst, dstCapacity, src, srcSize);
|
|
}
|
|
|
|
static size_t ZSTD_getBlockSize_deprecated(const ZSTD_CCtx* cctx)
|
|
{
|
|
ZSTD_compressionParameters const cParams = cctx->appliedParams.cParams;
|
|
assert(!ZSTD_checkCParams(cParams));
|
|
return ZSTD_rust_params_getBlockSize(cctx->appliedParams.maxBlockSize, cParams.windowLog);
|
|
}
|
|
|
|
/* NOTE: Must just wrap ZSTD_getBlockSize_deprecated() */
|
|
size_t ZSTD_getBlockSize(const ZSTD_CCtx* cctx)
|
|
{
|
|
return ZSTD_getBlockSize_deprecated(cctx);
|
|
}
|
|
|
|
/* NOTE: Must just wrap ZSTD_compressBlock_deprecated() */
|
|
size_t ZSTD_compressBlock_deprecated(ZSTD_CCtx* cctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize)
|
|
{
|
|
DEBUGLOG(5, "ZSTD_compressBlock: srcSize = %u", (unsigned)srcSize);
|
|
{ size_t const blockSizeMax = ZSTD_getBlockSize_deprecated(cctx);
|
|
RETURN_ERROR_IF(srcSize > blockSizeMax, srcSize_wrong, "input is larger than a block"); }
|
|
|
|
return ZSTD_compressContinue_internal(cctx, dst, dstCapacity, src, srcSize, 0 /* frame mode */, 0 /* last chunk */);
|
|
}
|
|
|
|
/* NOTE: Must just wrap ZSTD_compressBlock_deprecated() */
|
|
size_t ZSTD_compressBlock(ZSTD_CCtx* cctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize)
|
|
{
|
|
return ZSTD_compressBlock_deprecated(cctx, dst, dstCapacity, src, srcSize);
|
|
}
|
|
|
|
/*! ZSTD_loadDictionaryContent() :
|
|
* @return : 0, or an error code
|
|
*/
|
|
static size_t
|
|
ZSTD_loadDictionaryContent(ZSTD_MatchState_t* ms,
|
|
ldmState_t* ls,
|
|
ZSTD_cwksp* ws,
|
|
ZSTD_CCtx_params const* params,
|
|
const void* src, size_t srcSize,
|
|
ZSTD_dictTableLoadMethod_e dtlm,
|
|
ZSTD_tableFillPurpose_e tfp)
|
|
{
|
|
const BYTE* ip = (const BYTE*) src;
|
|
const BYTE* const iend = ip + srcSize;
|
|
int const loadLdmDict = params->ldmParams.enableLdm == ZSTD_ps_enable && ls != NULL;
|
|
|
|
/* Assert that the ms params match the params we're being given */
|
|
ZSTD_assertEqualCParams(params->cParams, ms->cParams);
|
|
|
|
{ /* Ensure large dictionaries can't cause index overflow */
|
|
|
|
/* Allow the dictionary to set indices up to exactly ZSTD_CURRENT_MAX.
|
|
* Dictionaries right at the edge will immediately trigger overflow
|
|
* correction, but I don't want to insert extra constraints here.
|
|
*/
|
|
U32 maxDictSize = ZSTD_CURRENT_MAX - ZSTD_WINDOW_START_INDEX;
|
|
|
|
int const CDictTaggedIndices = ZSTD_CDictIndicesAreTagged(¶ms->cParams);
|
|
if (CDictTaggedIndices && tfp == ZSTD_tfp_forCDict) {
|
|
/* Some dictionary matchfinders in zstd use "short cache",
|
|
* which treats the lower ZSTD_SHORT_CACHE_TAG_BITS of each
|
|
* CDict hashtable entry as a tag rather than as part of an index.
|
|
* When short cache is used, we need to truncate the dictionary
|
|
* so that its indices don't overlap with the tag. */
|
|
U32 const shortCacheMaxDictSize = (1u << (32 - ZSTD_SHORT_CACHE_TAG_BITS)) - ZSTD_WINDOW_START_INDEX;
|
|
maxDictSize = MIN(maxDictSize, shortCacheMaxDictSize);
|
|
assert(!loadLdmDict);
|
|
}
|
|
|
|
/* If the dictionary is too large, only load the suffix of the dictionary. */
|
|
if (srcSize > maxDictSize) {
|
|
ip = iend - maxDictSize;
|
|
src = ip;
|
|
srcSize = maxDictSize;
|
|
}
|
|
}
|
|
|
|
if (srcSize > ZSTD_CHUNKSIZE_MAX) {
|
|
/* We must have cleared our windows when our source is this large. */
|
|
assert(ZSTD_window_isEmpty(ms->window));
|
|
if (loadLdmDict) assert(ZSTD_window_isEmpty(ls->window));
|
|
}
|
|
ZSTD_window_update(&ms->window, src, srcSize, /* forceNonContiguous */ 0);
|
|
|
|
DEBUGLOG(4, "ZSTD_loadDictionaryContent: useRowMatchFinder=%d", (int)params->useRowMatchFinder);
|
|
|
|
if (loadLdmDict) { /* Load the entire dict into LDM matchfinders. */
|
|
DEBUGLOG(4, "ZSTD_loadDictionaryContent: Trigger loadLdmDict");
|
|
ZSTD_window_update(&ls->window, src, srcSize, /* forceNonContiguous */ 0);
|
|
ls->loadedDictEnd = params->forceWindow ? 0 : (U32)(iend - ls->window.base);
|
|
ZSTD_ldm_fillHashTable(ls, ip, iend, ¶ms->ldmParams);
|
|
DEBUGLOG(4, "ZSTD_loadDictionaryContent: ZSTD_ldm_fillHashTable completes");
|
|
}
|
|
|
|
/* If the dict is larger than we can reasonably index in our tables, only load the suffix. */
|
|
{ U32 maxDictSize = 1U << MIN(MAX(params->cParams.hashLog + 3, params->cParams.chainLog + 1), 31);
|
|
if (srcSize > maxDictSize) {
|
|
ip = iend - maxDictSize;
|
|
src = ip;
|
|
srcSize = maxDictSize;
|
|
}
|
|
}
|
|
|
|
ms->nextToUpdate = (U32)(ip - ms->window.base);
|
|
ms->loadedDictEnd = params->forceWindow ? 0 : (U32)(iend - ms->window.base);
|
|
ms->forceNonContiguous = params->deterministicRefPrefix;
|
|
|
|
if (srcSize <= HASH_READ_SIZE) return 0;
|
|
|
|
ZSTD_overflowCorrectIfNeeded(ms, ws, params, ip, iend);
|
|
|
|
switch(params->cParams.strategy)
|
|
{
|
|
case ZSTD_fast:
|
|
ZSTD_fillHashTable(ms, iend, dtlm, tfp);
|
|
break;
|
|
case ZSTD_dfast:
|
|
#ifndef ZSTD_EXCLUDE_DFAST_BLOCK_COMPRESSOR
|
|
ZSTD_fillDoubleHashTable(ms, iend, dtlm, tfp);
|
|
#else
|
|
assert(0); /* shouldn't be called: cparams should've been adjusted. */
|
|
#endif
|
|
break;
|
|
|
|
case ZSTD_greedy:
|
|
case ZSTD_lazy:
|
|
case ZSTD_lazy2:
|
|
#if !defined(ZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR) \
|
|
|| !defined(ZSTD_EXCLUDE_LAZY_BLOCK_COMPRESSOR) \
|
|
|| !defined(ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR)
|
|
assert(srcSize >= HASH_READ_SIZE);
|
|
if (ms->dedicatedDictSearch) {
|
|
assert(ms->chainTable != NULL);
|
|
ZSTD_dedicatedDictSearch_lazy_loadDictionary(ms, iend-HASH_READ_SIZE);
|
|
} else {
|
|
assert(params->useRowMatchFinder != ZSTD_ps_auto);
|
|
if (params->useRowMatchFinder == ZSTD_ps_enable) {
|
|
size_t const tagTableSize = ((size_t)1 << params->cParams.hashLog);
|
|
ZSTD_memset(ms->tagTable, 0, tagTableSize);
|
|
ZSTD_row_update(ms, iend-HASH_READ_SIZE);
|
|
DEBUGLOG(4, "Using row-based hash table for lazy dict");
|
|
} else {
|
|
ZSTD_insertAndFindFirstIndex(ms, iend-HASH_READ_SIZE);
|
|
DEBUGLOG(4, "Using chain-based hash table for lazy dict");
|
|
}
|
|
}
|
|
#else
|
|
assert(0); /* shouldn't be called: cparams should've been adjusted. */
|
|
#endif
|
|
break;
|
|
|
|
case ZSTD_btlazy2: /* we want the dictionary table fully sorted */
|
|
case ZSTD_btopt:
|
|
case ZSTD_btultra:
|
|
case ZSTD_btultra2:
|
|
#if !defined(ZSTD_EXCLUDE_BTLAZY2_BLOCK_COMPRESSOR) \
|
|
|| !defined(ZSTD_EXCLUDE_BTOPT_BLOCK_COMPRESSOR) \
|
|
|| !defined(ZSTD_EXCLUDE_BTULTRA_BLOCK_COMPRESSOR)
|
|
assert(srcSize >= HASH_READ_SIZE);
|
|
DEBUGLOG(4, "Fill %u bytes into the Binary Tree", (unsigned)srcSize);
|
|
ZSTD_updateTree(ms, iend-HASH_READ_SIZE, iend);
|
|
#else
|
|
assert(0); /* shouldn't be called: cparams should've been adjusted. */
|
|
#endif
|
|
break;
|
|
|
|
default:
|
|
assert(0); /* not possible : not a valid strategy id */
|
|
}
|
|
|
|
ms->nextToUpdate = (U32)(iend - ms->window.base);
|
|
return 0;
|
|
}
|
|
|
|
|
|
/* Dictionary entropy-header loading lives in Rust; C keeps the public internal
|
|
* symbol and the dictionary-content orchestration around it. */
|
|
size_t ZSTD_loadCEntropy(ZSTD_compressedBlockState_t* bs, void* workspace,
|
|
const void* const dict, size_t dictSize)
|
|
{
|
|
return ZSTD_rust_loadCEntropy(bs, workspace, dict, dictSize);
|
|
}
|
|
|
|
/* Dictionary format :
|
|
* See :
|
|
* https://github.com/facebook/zstd/blob/release/doc/zstd_compression_format.md#dictionary-format
|
|
*/
|
|
/*! ZSTD_loadZstdDictionary() :
|
|
* @return : dictID, or an error code
|
|
* assumptions : magic number supposed already checked
|
|
* dictSize supposed >= 8
|
|
*/
|
|
static size_t ZSTD_loadZstdDictionary(ZSTD_compressedBlockState_t* bs,
|
|
ZSTD_MatchState_t* ms,
|
|
ZSTD_cwksp* ws,
|
|
ZSTD_CCtx_params const* params,
|
|
const void* dict, size_t dictSize,
|
|
ZSTD_dictTableLoadMethod_e dtlm,
|
|
ZSTD_tableFillPurpose_e tfp,
|
|
void* workspace)
|
|
{
|
|
const BYTE* dictPtr = (const BYTE*)dict;
|
|
const BYTE* const dictEnd = dictPtr + dictSize;
|
|
size_t dictID;
|
|
size_t eSize;
|
|
ZSTD_STATIC_ASSERT(HUF_WORKSPACE_SIZE >= (1<<MAX(MLFSELog,LLFSELog)));
|
|
assert(dictSize >= 8);
|
|
assert(MEM_readLE32(dictPtr) == ZSTD_MAGIC_DICTIONARY);
|
|
|
|
dictID = params->fParams.noDictIDFlag ? 0 : MEM_readLE32(dictPtr + 4 /* skip magic number */ );
|
|
eSize = ZSTD_loadCEntropy(bs, workspace, dict, dictSize);
|
|
FORWARD_IF_ERROR(eSize, "ZSTD_loadCEntropy failed");
|
|
dictPtr += eSize;
|
|
|
|
{
|
|
size_t const dictContentSize = (size_t)(dictEnd - dictPtr);
|
|
FORWARD_IF_ERROR(ZSTD_loadDictionaryContent(
|
|
ms, NULL, ws, params, dictPtr, dictContentSize, dtlm, tfp), "");
|
|
}
|
|
return dictID;
|
|
}
|
|
|
|
/** ZSTD_compress_insertDictionary() :
|
|
* @return : dictID, or an error code */
|
|
static size_t
|
|
ZSTD_compress_insertDictionary(ZSTD_compressedBlockState_t* bs,
|
|
ZSTD_MatchState_t* ms,
|
|
ldmState_t* ls,
|
|
ZSTD_cwksp* ws,
|
|
const ZSTD_CCtx_params* params,
|
|
const void* dict, size_t dictSize,
|
|
ZSTD_dictContentType_e dictContentType,
|
|
ZSTD_dictTableLoadMethod_e dtlm,
|
|
ZSTD_tableFillPurpose_e tfp,
|
|
void* workspace)
|
|
{
|
|
DEBUGLOG(4, "ZSTD_compress_insertDictionary (dictSize=%u)", (U32)dictSize);
|
|
if ((dict==NULL) || (dictSize<8)) {
|
|
RETURN_ERROR_IF(dictContentType == ZSTD_dct_fullDict, dictionary_wrong, "");
|
|
return 0;
|
|
}
|
|
|
|
ZSTD_reset_compressedBlockState(bs);
|
|
|
|
/* dict restricted modes */
|
|
if (dictContentType == ZSTD_dct_rawContent)
|
|
return ZSTD_loadDictionaryContent(ms, ls, ws, params, dict, dictSize, dtlm, tfp);
|
|
|
|
if (MEM_readLE32(dict) != ZSTD_MAGIC_DICTIONARY) {
|
|
if (dictContentType == ZSTD_dct_auto) {
|
|
DEBUGLOG(4, "raw content dictionary detected");
|
|
return ZSTD_loadDictionaryContent(
|
|
ms, ls, ws, params, dict, dictSize, dtlm, tfp);
|
|
}
|
|
RETURN_ERROR_IF(dictContentType == ZSTD_dct_fullDict, dictionary_wrong, "");
|
|
assert(0); /* impossible */
|
|
}
|
|
|
|
/* dict as full zstd dictionary */
|
|
return ZSTD_loadZstdDictionary(
|
|
bs, ms, ws, params, dict, dictSize, dtlm, tfp, workspace);
|
|
}
|
|
|
|
#define ZSTD_USE_CDICT_PARAMS_SRCSIZE_CUTOFF (128 KB)
|
|
#define ZSTD_USE_CDICT_PARAMS_DICTSIZE_MULTIPLIER (6ULL)
|
|
|
|
/*! ZSTD_compressBegin_internal() :
|
|
* Assumption : either @dict OR @cdict (or none) is non-NULL, never both
|
|
* @return : 0, or an error code */
|
|
static size_t ZSTD_compressBegin_internal(ZSTD_CCtx* cctx,
|
|
const void* dict, size_t dictSize,
|
|
ZSTD_dictContentType_e dictContentType,
|
|
ZSTD_dictTableLoadMethod_e dtlm,
|
|
const ZSTD_CDict* cdict,
|
|
const ZSTD_CCtx_params* params, U64 pledgedSrcSize,
|
|
ZSTD_buffered_policy_e zbuff)
|
|
{
|
|
size_t const dictContentSize = cdict ? cdict->dictContentSize : dictSize;
|
|
#if ZSTD_TRACE
|
|
cctx->traceCtx = (ZSTD_trace_compress_begin != NULL) ? ZSTD_trace_compress_begin(cctx) : 0;
|
|
#endif
|
|
DEBUGLOG(4, "ZSTD_compressBegin_internal: wlog=%u", params->cParams.windowLog);
|
|
/* params are supposed to be fully validated at this point */
|
|
assert(!ZSTD_isError(ZSTD_checkCParams(params->cParams)));
|
|
assert(!((dict) && (cdict))); /* either dict or cdict, not both */
|
|
if ( (cdict)
|
|
&& (cdict->dictContentSize > 0)
|
|
&& ( pledgedSrcSize < ZSTD_USE_CDICT_PARAMS_SRCSIZE_CUTOFF
|
|
|| pledgedSrcSize < cdict->dictContentSize * ZSTD_USE_CDICT_PARAMS_DICTSIZE_MULTIPLIER
|
|
|| pledgedSrcSize == ZSTD_CONTENTSIZE_UNKNOWN
|
|
|| cdict->compressionLevel == 0)
|
|
&& (params->attachDictPref != ZSTD_dictForceLoad) ) {
|
|
return ZSTD_resetCCtx_usingCDict(cctx, cdict, params, pledgedSrcSize, zbuff);
|
|
}
|
|
|
|
FORWARD_IF_ERROR( ZSTD_resetCCtx_internal(cctx, params, pledgedSrcSize,
|
|
dictContentSize,
|
|
ZSTDcrp_makeClean, zbuff) , "");
|
|
{ size_t const dictID = cdict ?
|
|
ZSTD_compress_insertDictionary(
|
|
cctx->blockState.prevCBlock, &cctx->blockState.matchState,
|
|
&cctx->ldmState, &cctx->workspace, &cctx->appliedParams, cdict->dictContent,
|
|
cdict->dictContentSize, cdict->dictContentType, dtlm,
|
|
ZSTD_tfp_forCCtx, cctx->tmpWorkspace)
|
|
: ZSTD_compress_insertDictionary(
|
|
cctx->blockState.prevCBlock, &cctx->blockState.matchState,
|
|
&cctx->ldmState, &cctx->workspace, &cctx->appliedParams, dict, dictSize,
|
|
dictContentType, dtlm, ZSTD_tfp_forCCtx, cctx->tmpWorkspace);
|
|
FORWARD_IF_ERROR(dictID, "ZSTD_compress_insertDictionary failed");
|
|
assert(dictID <= UINT_MAX);
|
|
cctx->dictID = (U32)dictID;
|
|
cctx->dictContentSize = dictContentSize;
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
size_t ZSTD_compressBegin_advanced_internal(ZSTD_CCtx* cctx,
|
|
const void* dict, size_t dictSize,
|
|
ZSTD_dictContentType_e dictContentType,
|
|
ZSTD_dictTableLoadMethod_e dtlm,
|
|
const ZSTD_CDict* cdict,
|
|
const ZSTD_CCtx_params* params,
|
|
unsigned long long pledgedSrcSize)
|
|
{
|
|
DEBUGLOG(4, "ZSTD_compressBegin_advanced_internal: wlog=%u", params->cParams.windowLog);
|
|
/* compression parameters verification and optimization */
|
|
FORWARD_IF_ERROR( ZSTD_checkCParams(params->cParams) , "");
|
|
return ZSTD_compressBegin_internal(cctx,
|
|
dict, dictSize, dictContentType, dtlm,
|
|
cdict,
|
|
params, pledgedSrcSize,
|
|
ZSTDb_not_buffered);
|
|
}
|
|
|
|
/*! ZSTD_compressBegin_advanced() :
|
|
* @return : 0, or an error code */
|
|
size_t ZSTD_compressBegin_advanced(ZSTD_CCtx* cctx,
|
|
const void* dict, size_t dictSize,
|
|
ZSTD_parameters params, unsigned long long pledgedSrcSize)
|
|
{
|
|
ZSTD_CCtx_params cctxParams;
|
|
ZSTD_CCtxParams_init_internal(&cctxParams, ¶ms, ZSTD_NO_CLEVEL);
|
|
return ZSTD_compressBegin_advanced_internal(cctx,
|
|
dict, dictSize, ZSTD_dct_auto, ZSTD_dtlm_fast,
|
|
NULL /*cdict*/,
|
|
&cctxParams, pledgedSrcSize);
|
|
}
|
|
|
|
static size_t
|
|
ZSTD_compressBegin_usingDict_deprecated(ZSTD_CCtx* cctx, const void* dict, size_t dictSize, int compressionLevel)
|
|
{
|
|
ZSTD_CCtx_params cctxParams;
|
|
{ ZSTD_parameters const params = ZSTD_getParams_internal(compressionLevel, ZSTD_CONTENTSIZE_UNKNOWN, dictSize, ZSTD_cpm_noAttachDict);
|
|
ZSTD_CCtxParams_init_internal(&cctxParams, ¶ms, (compressionLevel == 0) ? ZSTD_CLEVEL_DEFAULT : compressionLevel);
|
|
}
|
|
DEBUGLOG(4, "ZSTD_compressBegin_usingDict (dictSize=%u)", (unsigned)dictSize);
|
|
return ZSTD_compressBegin_internal(cctx, dict, dictSize, ZSTD_dct_auto, ZSTD_dtlm_fast, NULL,
|
|
&cctxParams, ZSTD_CONTENTSIZE_UNKNOWN, ZSTDb_not_buffered);
|
|
}
|
|
|
|
size_t
|
|
ZSTD_compressBegin_usingDict(ZSTD_CCtx* cctx, const void* dict, size_t dictSize, int compressionLevel)
|
|
{
|
|
return ZSTD_compressBegin_usingDict_deprecated(cctx, dict, dictSize, compressionLevel);
|
|
}
|
|
|
|
size_t ZSTD_compressBegin(ZSTD_CCtx* cctx, int compressionLevel)
|
|
{
|
|
return ZSTD_compressBegin_usingDict_deprecated(cctx, NULL, 0, compressionLevel);
|
|
}
|
|
|
|
|
|
/*! ZSTD_writeEpilogue() :
|
|
* Ends a frame.
|
|
* @return : nb of bytes written into dst (or an error code) */
|
|
static size_t ZSTD_writeEpilogue(ZSTD_CCtx* cctx, void* dst, size_t dstCapacity)
|
|
{
|
|
U32 const checksum = cctx->appliedParams.fParams.checksumFlag
|
|
? (U32)XXH64_digest(&cctx->xxhState)
|
|
: 0;
|
|
DEBUGLOG(4, "ZSTD_writeEpilogue");
|
|
if (cctx->appliedParams.fParams.checksumFlag)
|
|
DEBUGLOG(4, "ZSTD_writeEpilogue: write checksum : %08X", (unsigned)checksum);
|
|
return ZSTD_rust_writeEpilogue(
|
|
dst, dstCapacity, (int*)&cctx->stage,
|
|
cctx->appliedParams.fParams.noDictIDFlag,
|
|
cctx->appliedParams.fParams.checksumFlag,
|
|
cctx->appliedParams.fParams.contentSizeFlag,
|
|
(int)cctx->appliedParams.format,
|
|
cctx->appliedParams.cParams.windowLog,
|
|
checksum);
|
|
}
|
|
|
|
void ZSTD_CCtx_trace(ZSTD_CCtx* cctx, size_t extraCSize)
|
|
{
|
|
#if ZSTD_TRACE
|
|
if (cctx->traceCtx && ZSTD_trace_compress_end != NULL) {
|
|
int const streaming = cctx->inBuffSize > 0 || cctx->outBuffSize > 0 || cctx->appliedParams.nbWorkers > 0;
|
|
ZSTD_Trace trace;
|
|
ZSTD_memset(&trace, 0, sizeof(trace));
|
|
trace.version = ZSTD_VERSION_NUMBER;
|
|
trace.streaming = streaming;
|
|
trace.dictionaryID = cctx->dictID;
|
|
trace.dictionarySize = cctx->dictContentSize;
|
|
trace.uncompressedSize = cctx->consumedSrcSize;
|
|
trace.compressedSize = cctx->producedCSize + extraCSize;
|
|
trace.params = &cctx->appliedParams;
|
|
trace.cctx = cctx;
|
|
ZSTD_trace_compress_end(cctx->traceCtx, &trace);
|
|
}
|
|
cctx->traceCtx = 0;
|
|
#else
|
|
(void)cctx;
|
|
(void)extraCSize;
|
|
#endif
|
|
}
|
|
|
|
size_t ZSTD_compressEnd_public(ZSTD_CCtx* cctx,
|
|
void* dst, size_t dstCapacity,
|
|
const void* src, size_t srcSize)
|
|
{
|
|
size_t endResult;
|
|
size_t const cSize = ZSTD_compressContinue_internal(cctx,
|
|
dst, dstCapacity, src, srcSize,
|
|
1 /* frame mode */, 1 /* last chunk */);
|
|
FORWARD_IF_ERROR(cSize, "ZSTD_compressContinue_internal failed");
|
|
endResult = ZSTD_writeEpilogue(cctx, (char*)dst + cSize, dstCapacity-cSize);
|
|
FORWARD_IF_ERROR(endResult, "ZSTD_writeEpilogue failed");
|
|
assert(!(cctx->appliedParams.fParams.contentSizeFlag && cctx->pledgedSrcSizePlusOne == 0));
|
|
if (cctx->pledgedSrcSizePlusOne != 0) { /* control src size */
|
|
ZSTD_STATIC_ASSERT(ZSTD_CONTENTSIZE_UNKNOWN == (unsigned long long)-1);
|
|
DEBUGLOG(4, "end of frame : controlling src size");
|
|
RETURN_ERROR_IF(
|
|
cctx->pledgedSrcSizePlusOne != cctx->consumedSrcSize+1,
|
|
srcSize_wrong,
|
|
"error : pledgedSrcSize = %u, while realSrcSize = %u",
|
|
(unsigned)cctx->pledgedSrcSizePlusOne-1,
|
|
(unsigned)cctx->consumedSrcSize);
|
|
}
|
|
ZSTD_CCtx_trace(cctx, endResult);
|
|
return cSize + endResult;
|
|
}
|
|
|
|
/* NOTE: Must just wrap ZSTD_compressEnd_public() */
|
|
size_t ZSTD_compressEnd(ZSTD_CCtx* cctx,
|
|
void* dst, size_t dstCapacity,
|
|
const void* src, size_t srcSize)
|
|
{
|
|
return ZSTD_compressEnd_public(cctx, dst, dstCapacity, src, srcSize);
|
|
}
|
|
|
|
size_t ZSTD_compress_advanced (ZSTD_CCtx* cctx,
|
|
void* dst, size_t dstCapacity,
|
|
const void* src, size_t srcSize,
|
|
const void* dict,size_t dictSize,
|
|
ZSTD_parameters params)
|
|
{
|
|
DEBUGLOG(4, "ZSTD_compress_advanced");
|
|
FORWARD_IF_ERROR(ZSTD_checkCParams(params.cParams), "");
|
|
ZSTD_CCtxParams_init_internal(&cctx->simpleApiParams, ¶ms, ZSTD_NO_CLEVEL);
|
|
return ZSTD_compress_advanced_internal(cctx,
|
|
dst, dstCapacity,
|
|
src, srcSize,
|
|
dict, dictSize,
|
|
&cctx->simpleApiParams);
|
|
}
|
|
|
|
/* Internal */
|
|
size_t ZSTD_compress_advanced_internal(
|
|
ZSTD_CCtx* cctx,
|
|
void* dst, size_t dstCapacity,
|
|
const void* src, size_t srcSize,
|
|
const void* dict,size_t dictSize,
|
|
const ZSTD_CCtx_params* params)
|
|
{
|
|
DEBUGLOG(4, "ZSTD_compress_advanced_internal (srcSize:%u)", (unsigned)srcSize);
|
|
FORWARD_IF_ERROR( ZSTD_compressBegin_internal(cctx,
|
|
dict, dictSize, ZSTD_dct_auto, ZSTD_dtlm_fast, NULL,
|
|
params, srcSize, ZSTDb_not_buffered) , "");
|
|
return ZSTD_compressEnd_public(cctx, dst, dstCapacity, src, srcSize);
|
|
}
|
|
|
|
size_t ZSTD_compress_usingDict(ZSTD_CCtx* cctx,
|
|
void* dst, size_t dstCapacity,
|
|
const void* src, size_t srcSize,
|
|
const void* dict, size_t dictSize,
|
|
int compressionLevel)
|
|
{
|
|
{
|
|
ZSTD_parameters const params = ZSTD_getParams_internal(compressionLevel, srcSize, dict ? dictSize : 0, ZSTD_cpm_noAttachDict);
|
|
assert(params.fParams.contentSizeFlag == 1);
|
|
ZSTD_CCtxParams_init_internal(&cctx->simpleApiParams, ¶ms, (compressionLevel == 0) ? ZSTD_CLEVEL_DEFAULT: compressionLevel);
|
|
}
|
|
DEBUGLOG(4, "ZSTD_compress_usingDict (srcSize=%u)", (unsigned)srcSize);
|
|
return ZSTD_compress_advanced_internal(cctx, dst, dstCapacity, src, srcSize, dict, dictSize, &cctx->simpleApiParams);
|
|
}
|
|
|
|
/* ZSTD_compressCCtx() is implemented by rust/src/zstd_compress.rs. */
|
|
|
|
/* The Rust simple API still needs the C-owned context reset, but does not
|
|
* cross the private context layout. */
|
|
int ZSTD_rust_compressCCtxStrategy(size_t srcSize, int compressionLevel)
|
|
{
|
|
ZSTD_parameters const params = ZSTD_getParams_internal(
|
|
compressionLevel, srcSize, 0, ZSTD_cpm_noAttachDict);
|
|
return (int)params.cParams.strategy;
|
|
}
|
|
|
|
size_t ZSTD_rust_resetCCtxForSimpleCompression(void* cctx)
|
|
{
|
|
return ZSTD_CCtx_reset((ZSTD_CCtx*)cctx, ZSTD_reset_session_and_parameters);
|
|
}
|
|
|
|
size_t ZSTD_rust_prepareCCtxForSimpleCompression(void* opaqueCctx,
|
|
size_t srcSize,
|
|
int compressionLevel)
|
|
{
|
|
ZSTD_CCtx* const cctx = (ZSTD_CCtx*)opaqueCctx;
|
|
ZSTD_CCtx_params params;
|
|
ZSTD_parameters const zstdParams = ZSTD_getParams_internal(
|
|
compressionLevel, srcSize, 0, ZSTD_cpm_noAttachDict);
|
|
ZSTD_CCtxParams_init_internal(
|
|
¶ms, &zstdParams,
|
|
compressionLevel == 0 ? ZSTD_CLEVEL_DEFAULT : compressionLevel);
|
|
FORWARD_IF_ERROR(ZSTD_compressBegin_internal(
|
|
cctx, NULL, 0, ZSTD_dct_auto, ZSTD_dtlm_fast, NULL,
|
|
¶ms, srcSize, ZSTDb_not_buffered), "");
|
|
return ZSTD_CCtx_reset(cctx, ZSTD_reset_session_only);
|
|
}
|
|
|
|
size_t ZSTD_rust_resetCCtxForSimpleCompressionSession(void* cctx)
|
|
{
|
|
return ZSTD_CCtx_reset((ZSTD_CCtx*)cctx, ZSTD_reset_session_only);
|
|
}
|
|
|
|
void ZSTD_rust_markSimpleCompression2Complete(void* cctx)
|
|
{
|
|
((ZSTD_CCtx*)cctx)->rustSimpleCompress2Completed = 1;
|
|
}
|
|
|
|
/* Return the requested level when the context has only the parameters that
|
|
* the Rust frame path currently implements. All other contexts continue
|
|
* through ZSTD_compress2_c(), preserving the full C stateful implementation
|
|
* while this boundary is migrated incrementally. */
|
|
int ZSTD_rust_simpleCompress2Level(const void* opaqueCctx, size_t srcSize)
|
|
{
|
|
ZSTD_CCtx const* const cctx = (ZSTD_CCtx const*)opaqueCctx;
|
|
ZSTD_CCtx_params const* const params = cctx ? &cctx->requestedParams : NULL;
|
|
ZSTD_compressionParameters const cParams = params
|
|
? ZSTD_getCParams_internal(params->compressionLevel,
|
|
srcSize, 0,
|
|
ZSTD_cpm_noAttachDict)
|
|
: (ZSTD_compressionParameters){ 0 };
|
|
if (params == NULL
|
|
|| params->format != ZSTD_f_zstd1
|
|
|| params->fParams.contentSizeFlag == 0
|
|
|| params->fParams.checksumFlag != 0
|
|
|| params->cParams.windowLog != 0
|
|
|| params->cParams.chainLog != 0
|
|
|| params->cParams.hashLog != 0
|
|
|| params->cParams.searchLog != 0
|
|
|| params->cParams.minMatch != 0
|
|
|| params->cParams.targetLength != 0
|
|
|| params->cParams.strategy != 0
|
|
|| params->forceWindow != 0
|
|
|| params->targetCBlockSize != 0
|
|
|| params->srcSizeHint != 0
|
|
|| params->attachDictPref != ZSTD_dictDefaultAttach
|
|
|| params->literalCompressionMode != (ZSTD_ParamSwitch_e)ZSTD_lcm_auto
|
|
|| params->nbWorkers != 0
|
|
|| params->jobSize != 0
|
|
|| params->overlapLog != 0
|
|
|| params->rsyncable != 0
|
|
|| params->ldmParams.enableLdm != ZSTD_ps_auto
|
|
|| params->ldmParams.hashLog != 0
|
|
|| (params->ldmParams.bucketSizeLog != 0
|
|
&& params->ldmParams.bucketSizeLog != 9999)
|
|
|| params->ldmParams.minMatchLength != 0
|
|
|| (params->ldmParams.hashRateLog != 0
|
|
&& params->ldmParams.hashRateLog != 9999)
|
|
|| params->ldmParams.windowLog != 0
|
|
|| params->enableDedicatedDictSearch != 0
|
|
|| params->inBufferMode != ZSTD_bm_buffered
|
|
|| params->outBufferMode != ZSTD_bm_buffered
|
|
|| params->blockDelimiters != ZSTD_sf_noBlockDelimiters
|
|
|| params->validateSequences != 0
|
|
|| params->postBlockSplitter != ZSTD_ps_auto
|
|
|| params->preBlockSplitter_level != 0
|
|
|| params->maxBlockSize != 0
|
|
|| cctx->rustSimpleCompress2MaxBlockSizeSet != 0
|
|
|| params->useRowMatchFinder != ZSTD_ps_auto
|
|
|| params->deterministicRefPrefix != 0
|
|
|| params->prefetchCDictTables != ZSTD_ps_auto
|
|
|| params->enableMatchFinderFallback != 0
|
|
|| params->extSeqProdFunc != NULL
|
|
|| params->searchForExternalRepcodes != ZSTD_ps_auto
|
|
|| cctx->pool != NULL
|
|
|| cctx->seqCollector.collectSequences != 0
|
|
|| cctx->cdict != NULL
|
|
|| cctx->prefixDict.dict != NULL
|
|
|| cctx->localDict.dict != NULL
|
|
|| cctx->localDict.dictBuffer != NULL
|
|
|| cctx->localDict.cdict != NULL) {
|
|
return (-2147483647 - 1);
|
|
}
|
|
/* The Rust frame leaf currently implements only the fast and double-fast
|
|
* match finders. Keep lazy and optimal strategies on the stateful path,
|
|
* which owns their strategy-specific match-table lifecycle. */
|
|
if (cParams.strategy != ZSTD_fast && cParams.strategy != ZSTD_dfast) {
|
|
return (-2147483647 - 1);
|
|
}
|
|
return params->compressionLevel;
|
|
}
|
|
|
|
/* Return the simple level only while a new stream frame can be initialized.
|
|
* Rust handles this complete-input case; all other stream states stay on the
|
|
* original implementation so partial output and advanced buffering remain
|
|
* governed by the C state machine. */
|
|
int ZSTD_rust_simpleCompressStream2Level(const void* opaqueCctx, size_t srcSize)
|
|
{
|
|
ZSTD_CCtx const* const cctx = (ZSTD_CCtx const*)opaqueCctx;
|
|
if (cctx == NULL
|
|
|| cctx->streamStage != zcss_init
|
|
|| cctx->pledgedSrcSizePlusOne != 0
|
|
|| cctx->rustSimpleCompress2Completed != 0) {
|
|
return (-2147483647 - 1);
|
|
}
|
|
return ZSTD_rust_simpleCompress2Level(opaqueCctx, srcSize);
|
|
}
|
|
|
|
/* ZSTD_compress() is implemented by rust/src/zstd_compress.rs. */
|
|
|
|
|
|
/* ===== Dictionary API ===== */
|
|
|
|
/*! ZSTD_estimateCDictSize_advanced() :
|
|
* Estimate amount of memory that will be needed to create a dictionary with following arguments */
|
|
size_t ZSTD_estimateCDictSize_advanced(
|
|
size_t dictSize, ZSTD_compressionParameters cParams,
|
|
ZSTD_dictLoadMethod_e dictLoadMethod)
|
|
{
|
|
ZSTD_rustCDictSizing sizing;
|
|
sizing.cdictSize = sizeof(ZSTD_CDict);
|
|
sizing.hufWorkspaceSize = HUF_WORKSPACE_SIZE;
|
|
sizing.hashLog3Max = ZSTD_HASHLOG3_MAX;
|
|
sizing.matchTSize = sizeof(ZSTD_match_t);
|
|
sizing.optimalTSize = sizeof(ZSTD_optimal_t);
|
|
sizing.asanRedzoneSize = ZSTD_RUST_ASAN_REDZONE_SIZE;
|
|
return ZSTD_rust_params_estimateCDictSizeFromCParams(
|
|
dictSize, cParams, (int)dictLoadMethod, &sizing);
|
|
}
|
|
|
|
size_t ZSTD_estimateCDictSize(size_t dictSize, int compressionLevel)
|
|
{
|
|
ZSTD_compressionParameters const cParams = ZSTD_getCParams_internal(compressionLevel, ZSTD_CONTENTSIZE_UNKNOWN, dictSize, ZSTD_cpm_createCDict);
|
|
return ZSTD_estimateCDictSize_advanced(dictSize, cParams, ZSTD_dlm_byCopy);
|
|
}
|
|
|
|
size_t ZSTD_sizeof_CDict(const ZSTD_CDict* cdict)
|
|
{
|
|
size_t objectSize, workspaceSize;
|
|
if (cdict==NULL) return 0; /* support sizeof on NULL */
|
|
DEBUGLOG(5, "sizeof(*cdict) : %u", (unsigned)sizeof(*cdict));
|
|
/* cdict may be in the workspace */
|
|
objectSize = cdict->workspace.workspace == cdict ? 0 : sizeof(*cdict);
|
|
workspaceSize = ZSTD_cwksp_sizeof(&cdict->workspace);
|
|
return ZSTD_rust_sizeofCDict(objectSize, workspaceSize);
|
|
}
|
|
|
|
static size_t ZSTD_initCDict_internal(
|
|
ZSTD_CDict* cdict,
|
|
const void* dictBuffer, size_t dictSize,
|
|
ZSTD_dictLoadMethod_e dictLoadMethod,
|
|
ZSTD_dictContentType_e dictContentType,
|
|
ZSTD_CCtx_params params)
|
|
{
|
|
DEBUGLOG(3, "ZSTD_initCDict_internal (dictContentType:%u)", (unsigned)dictContentType);
|
|
assert(!ZSTD_checkCParams(params.cParams));
|
|
cdict->matchState.cParams = params.cParams;
|
|
cdict->matchState.dedicatedDictSearch = params.enableDedicatedDictSearch;
|
|
if ((dictLoadMethod == ZSTD_dlm_byRef) || (!dictBuffer) || (!dictSize)) {
|
|
cdict->dictContent = dictBuffer;
|
|
} else {
|
|
void *internalBuffer = ZSTD_cwksp_reserve_object(&cdict->workspace, ZSTD_cwksp_align(dictSize, sizeof(void*)));
|
|
RETURN_ERROR_IF(!internalBuffer, memory_allocation, "NULL pointer!");
|
|
cdict->dictContent = internalBuffer;
|
|
ZSTD_memcpy(internalBuffer, dictBuffer, dictSize);
|
|
}
|
|
cdict->dictContentSize = dictSize;
|
|
cdict->dictContentType = dictContentType;
|
|
|
|
cdict->entropyWorkspace = (U32*)ZSTD_cwksp_reserve_object(&cdict->workspace, HUF_WORKSPACE_SIZE);
|
|
|
|
|
|
/* Reset the state to no dictionary */
|
|
ZSTD_reset_compressedBlockState(&cdict->cBlockState);
|
|
FORWARD_IF_ERROR(ZSTD_reset_matchState(
|
|
&cdict->matchState,
|
|
&cdict->workspace,
|
|
¶ms.cParams,
|
|
params.useRowMatchFinder,
|
|
ZSTDcrp_makeClean,
|
|
ZSTDirp_reset,
|
|
ZSTD_resetTarget_CDict), "");
|
|
/* (Maybe) load the dictionary
|
|
* Skips loading the dictionary if it is < 8 bytes.
|
|
*/
|
|
{ params.compressionLevel = ZSTD_CLEVEL_DEFAULT;
|
|
params.fParams.contentSizeFlag = 1;
|
|
{ size_t const dictID = ZSTD_compress_insertDictionary(
|
|
&cdict->cBlockState, &cdict->matchState, NULL, &cdict->workspace,
|
|
¶ms, cdict->dictContent, cdict->dictContentSize,
|
|
dictContentType, ZSTD_dtlm_full, ZSTD_tfp_forCDict, cdict->entropyWorkspace);
|
|
FORWARD_IF_ERROR(dictID, "ZSTD_compress_insertDictionary failed");
|
|
assert(dictID <= (size_t)(U32)-1);
|
|
cdict->dictID = (U32)dictID;
|
|
}
|
|
}
|
|
|
|
return 0;
|
|
}
|
|
|
|
static ZSTD_CDict*
|
|
ZSTD_createCDict_advanced_internal(size_t dictSize,
|
|
ZSTD_dictLoadMethod_e dictLoadMethod,
|
|
ZSTD_compressionParameters cParams,
|
|
ZSTD_ParamSwitch_e useRowMatchFinder,
|
|
int enableDedicatedDictSearch,
|
|
ZSTD_customMem customMem)
|
|
{
|
|
if ((!customMem.customAlloc) ^ (!customMem.customFree)) return NULL;
|
|
DEBUGLOG(3, "ZSTD_createCDict_advanced_internal (dictSize=%u)", (unsigned)dictSize);
|
|
|
|
{ size_t const workspaceSize =
|
|
ZSTD_cwksp_alloc_size(sizeof(ZSTD_CDict)) +
|
|
ZSTD_cwksp_alloc_size(HUF_WORKSPACE_SIZE) +
|
|
ZSTD_sizeof_matchState(&cParams, useRowMatchFinder, enableDedicatedDictSearch, /* forCCtx */ 0) +
|
|
(dictLoadMethod == ZSTD_dlm_byRef ? 0
|
|
: ZSTD_cwksp_alloc_size(ZSTD_cwksp_align(dictSize, sizeof(void*))));
|
|
void* const workspace = ZSTD_customMalloc(workspaceSize, customMem);
|
|
ZSTD_cwksp ws;
|
|
ZSTD_CDict* cdict;
|
|
|
|
if (!workspace) {
|
|
ZSTD_customFree(workspace, customMem);
|
|
return NULL;
|
|
}
|
|
|
|
ZSTD_cwksp_init(&ws, workspace, workspaceSize, ZSTD_cwksp_dynamic_alloc);
|
|
|
|
cdict = (ZSTD_CDict*)ZSTD_cwksp_reserve_object(&ws, sizeof(ZSTD_CDict));
|
|
assert(cdict != NULL);
|
|
ZSTD_cwksp_move(&cdict->workspace, &ws);
|
|
cdict->customMem = customMem;
|
|
cdict->compressionLevel = ZSTD_NO_CLEVEL; /* signals advanced API usage */
|
|
cdict->useRowMatchFinder = useRowMatchFinder;
|
|
return cdict;
|
|
}
|
|
}
|
|
|
|
ZSTD_CDict* ZSTD_createCDict_advanced(const void* dictBuffer, size_t dictSize,
|
|
ZSTD_dictLoadMethod_e dictLoadMethod,
|
|
ZSTD_dictContentType_e dictContentType,
|
|
ZSTD_compressionParameters cParams,
|
|
ZSTD_customMem customMem)
|
|
{
|
|
ZSTD_CCtx_params cctxParams;
|
|
ZSTD_memset(&cctxParams, 0, sizeof(cctxParams));
|
|
DEBUGLOG(3, "ZSTD_createCDict_advanced, dictSize=%u, mode=%u", (unsigned)dictSize, (unsigned)dictContentType);
|
|
ZSTD_CCtxParams_init(&cctxParams, 0);
|
|
cctxParams.cParams = cParams;
|
|
cctxParams.customMem = customMem;
|
|
return ZSTD_createCDict_advanced2(
|
|
dictBuffer, dictSize,
|
|
dictLoadMethod, dictContentType,
|
|
&cctxParams, customMem);
|
|
}
|
|
|
|
ZSTD_CDict* ZSTD_createCDict_advanced2(
|
|
const void* dict, size_t dictSize,
|
|
ZSTD_dictLoadMethod_e dictLoadMethod,
|
|
ZSTD_dictContentType_e dictContentType,
|
|
const ZSTD_CCtx_params* originalCctxParams,
|
|
ZSTD_customMem customMem)
|
|
{
|
|
ZSTD_CCtx_params cctxParams = *originalCctxParams;
|
|
ZSTD_compressionParameters cParams;
|
|
ZSTD_CDict* cdict;
|
|
|
|
DEBUGLOG(3, "ZSTD_createCDict_advanced2, dictSize=%u, mode=%u", (unsigned)dictSize, (unsigned)dictContentType);
|
|
if (!customMem.customAlloc ^ !customMem.customFree) return NULL;
|
|
|
|
if (cctxParams.enableDedicatedDictSearch) {
|
|
cParams = ZSTD_dedicatedDictSearch_getCParams(
|
|
cctxParams.compressionLevel, dictSize);
|
|
ZSTD_rust_params_overrideCParams(&cParams, &cctxParams.cParams);
|
|
} else {
|
|
cParams = ZSTD_getCParamsFromCCtxParams(
|
|
&cctxParams, ZSTD_CONTENTSIZE_UNKNOWN, dictSize, ZSTD_cpm_createCDict);
|
|
}
|
|
|
|
if (!ZSTD_rust_params_dedicatedDictSearchIsSupported(cParams)) {
|
|
/* Fall back to non-DDSS params */
|
|
cctxParams.enableDedicatedDictSearch = 0;
|
|
cParams = ZSTD_getCParamsFromCCtxParams(
|
|
&cctxParams, ZSTD_CONTENTSIZE_UNKNOWN, dictSize, ZSTD_cpm_createCDict);
|
|
}
|
|
|
|
DEBUGLOG(3, "ZSTD_createCDict_advanced2: DedicatedDictSearch=%u", cctxParams.enableDedicatedDictSearch);
|
|
cctxParams.cParams = cParams;
|
|
cctxParams.useRowMatchFinder = ZSTD_resolveRowMatchFinderMode(cctxParams.useRowMatchFinder, &cParams);
|
|
|
|
cdict = ZSTD_createCDict_advanced_internal(dictSize,
|
|
dictLoadMethod, cctxParams.cParams,
|
|
cctxParams.useRowMatchFinder, cctxParams.enableDedicatedDictSearch,
|
|
customMem);
|
|
|
|
if (!cdict || ZSTD_isError( ZSTD_initCDict_internal(cdict,
|
|
dict, dictSize,
|
|
dictLoadMethod, dictContentType,
|
|
cctxParams) )) {
|
|
ZSTD_freeCDict(cdict);
|
|
return NULL;
|
|
}
|
|
|
|
return cdict;
|
|
}
|
|
|
|
ZSTD_CDict* ZSTD_createCDict(const void* dict, size_t dictSize, int compressionLevel)
|
|
{
|
|
ZSTD_compressionParameters cParams = ZSTD_getCParams_internal(compressionLevel, ZSTD_CONTENTSIZE_UNKNOWN, dictSize, ZSTD_cpm_createCDict);
|
|
ZSTD_CDict* const cdict = ZSTD_createCDict_advanced(dict, dictSize,
|
|
ZSTD_dlm_byCopy, ZSTD_dct_auto,
|
|
cParams, ZSTD_defaultCMem);
|
|
if (cdict)
|
|
cdict->compressionLevel = (compressionLevel == 0) ? ZSTD_CLEVEL_DEFAULT : compressionLevel;
|
|
return cdict;
|
|
}
|
|
|
|
ZSTD_CDict* ZSTD_createCDict_byReference(const void* dict, size_t dictSize, int compressionLevel)
|
|
{
|
|
ZSTD_compressionParameters cParams = ZSTD_getCParams_internal(compressionLevel, ZSTD_CONTENTSIZE_UNKNOWN, dictSize, ZSTD_cpm_createCDict);
|
|
ZSTD_CDict* const cdict = ZSTD_createCDict_advanced(dict, dictSize,
|
|
ZSTD_dlm_byRef, ZSTD_dct_auto,
|
|
cParams, ZSTD_defaultCMem);
|
|
if (cdict)
|
|
cdict->compressionLevel = (compressionLevel == 0) ? ZSTD_CLEVEL_DEFAULT : compressionLevel;
|
|
return cdict;
|
|
}
|
|
|
|
size_t ZSTD_freeCDict(ZSTD_CDict* cdict)
|
|
{
|
|
if (cdict==NULL) return 0; /* support free on NULL */
|
|
{ ZSTD_customMem const cMem = cdict->customMem;
|
|
int cdictInWorkspace = ZSTD_cwksp_owns_buffer(&cdict->workspace, cdict);
|
|
ZSTD_cwksp_free(&cdict->workspace, cMem);
|
|
if (!cdictInWorkspace) {
|
|
ZSTD_customFree(cdict, cMem);
|
|
}
|
|
return 0;
|
|
}
|
|
}
|
|
|
|
/*! ZSTD_initStaticCDict_advanced() :
|
|
* Generate a digested dictionary in provided memory area.
|
|
* workspace: The memory area to emplace the dictionary into.
|
|
* Provided pointer must 8-bytes aligned.
|
|
* It must outlive dictionary usage.
|
|
* workspaceSize: Use ZSTD_estimateCDictSize()
|
|
* to determine how large workspace must be.
|
|
* cParams : use ZSTD_getCParams() to transform a compression level
|
|
* into its relevant cParams.
|
|
* @return : pointer to ZSTD_CDict*, or NULL if error (size too small)
|
|
* Note : there is no corresponding "free" function.
|
|
* Since workspace was allocated externally, it must be freed externally.
|
|
*/
|
|
const ZSTD_CDict* ZSTD_initStaticCDict(
|
|
void* workspace, size_t workspaceSize,
|
|
const void* dict, size_t dictSize,
|
|
ZSTD_dictLoadMethod_e dictLoadMethod,
|
|
ZSTD_dictContentType_e dictContentType,
|
|
ZSTD_compressionParameters cParams)
|
|
{
|
|
ZSTD_ParamSwitch_e const useRowMatchFinder = ZSTD_resolveRowMatchFinderMode(ZSTD_ps_auto, &cParams);
|
|
/* enableDedicatedDictSearch == 1 ensures matchstate is not too small in case this CDict will be used for DDS + row hash */
|
|
size_t const matchStateSize = ZSTD_sizeof_matchState(&cParams, useRowMatchFinder, /* enableDedicatedDictSearch */ 1, /* forCCtx */ 0);
|
|
size_t const neededSize = ZSTD_cwksp_alloc_size(sizeof(ZSTD_CDict))
|
|
+ (dictLoadMethod == ZSTD_dlm_byRef ? 0
|
|
: ZSTD_cwksp_alloc_size(ZSTD_cwksp_align(dictSize, sizeof(void*))))
|
|
+ ZSTD_cwksp_alloc_size(HUF_WORKSPACE_SIZE)
|
|
+ matchStateSize;
|
|
ZSTD_CDict* cdict;
|
|
ZSTD_CCtx_params params;
|
|
|
|
DEBUGLOG(4, "ZSTD_initStaticCDict (dictSize==%u)", (unsigned)dictSize);
|
|
if ((size_t)workspace & 7) return NULL; /* 8-aligned */
|
|
|
|
{
|
|
ZSTD_cwksp ws;
|
|
ZSTD_cwksp_init(&ws, workspace, workspaceSize, ZSTD_cwksp_static_alloc);
|
|
cdict = (ZSTD_CDict*)ZSTD_cwksp_reserve_object(&ws, sizeof(ZSTD_CDict));
|
|
if (cdict == NULL) return NULL;
|
|
ZSTD_cwksp_move(&cdict->workspace, &ws);
|
|
}
|
|
|
|
if (workspaceSize < neededSize) return NULL;
|
|
|
|
ZSTD_CCtxParams_init(¶ms, 0);
|
|
params.cParams = cParams;
|
|
params.useRowMatchFinder = useRowMatchFinder;
|
|
cdict->useRowMatchFinder = useRowMatchFinder;
|
|
cdict->compressionLevel = ZSTD_NO_CLEVEL;
|
|
|
|
if (ZSTD_isError( ZSTD_initCDict_internal(cdict,
|
|
dict, dictSize,
|
|
dictLoadMethod, dictContentType,
|
|
params) ))
|
|
return NULL;
|
|
|
|
return cdict;
|
|
}
|
|
|
|
ZSTD_compressionParameters ZSTD_getCParamsFromCDict(const ZSTD_CDict* cdict)
|
|
{
|
|
assert(cdict != NULL);
|
|
return cdict->matchState.cParams;
|
|
}
|
|
|
|
/*! ZSTD_getDictID_fromCDict() :
|
|
* Provides the dictID of the dictionary loaded into `cdict`.
|
|
* If @return == 0, the dictionary is not conformant to Zstandard specification, or empty.
|
|
* Non-conformant dictionaries can still be loaded, but as content-only dictionaries. */
|
|
unsigned ZSTD_getDictID_fromCDict(const ZSTD_CDict* cdict)
|
|
{
|
|
if (cdict==NULL) return 0;
|
|
return cdict->dictID;
|
|
}
|
|
|
|
/* ZSTD_compressBegin_usingCDict_internal() :
|
|
* Implementation of various ZSTD_compressBegin_usingCDict* functions.
|
|
*/
|
|
static size_t ZSTD_compressBegin_usingCDict_internal(
|
|
ZSTD_CCtx* const cctx, const ZSTD_CDict* const cdict,
|
|
ZSTD_frameParameters const fParams, unsigned long long const pledgedSrcSize)
|
|
{
|
|
ZSTD_CCtx_params cctxParams;
|
|
DEBUGLOG(4, "ZSTD_compressBegin_usingCDict_internal");
|
|
RETURN_ERROR_IF(cdict==NULL, dictionary_wrong, "NULL pointer!");
|
|
/* Initialize the cctxParams from the cdict */
|
|
{
|
|
ZSTD_parameters params;
|
|
params.fParams = fParams;
|
|
params.cParams = ( pledgedSrcSize < ZSTD_USE_CDICT_PARAMS_SRCSIZE_CUTOFF
|
|
|| pledgedSrcSize < cdict->dictContentSize * ZSTD_USE_CDICT_PARAMS_DICTSIZE_MULTIPLIER
|
|
|| pledgedSrcSize == ZSTD_CONTENTSIZE_UNKNOWN
|
|
|| cdict->compressionLevel == 0 ) ?
|
|
ZSTD_getCParamsFromCDict(cdict)
|
|
: ZSTD_getCParams(cdict->compressionLevel,
|
|
pledgedSrcSize,
|
|
cdict->dictContentSize);
|
|
ZSTD_CCtxParams_init_internal(&cctxParams, ¶ms, cdict->compressionLevel);
|
|
}
|
|
/* Increase window log to fit the entire dictionary and source if the
|
|
* source size is known. Limit the increase to 19, which is the
|
|
* window log for compression level 1 with the largest source size.
|
|
*/
|
|
if (pledgedSrcSize != ZSTD_CONTENTSIZE_UNKNOWN) {
|
|
U32 const limitedSrcSize = (U32)MIN(pledgedSrcSize, 1U << 19);
|
|
U32 const limitedSrcLog = limitedSrcSize > 1 ? ZSTD_highbit32(limitedSrcSize - 1) + 1 : 1;
|
|
cctxParams.cParams.windowLog = MAX(cctxParams.cParams.windowLog, limitedSrcLog);
|
|
}
|
|
return ZSTD_compressBegin_internal(cctx,
|
|
NULL, 0, ZSTD_dct_auto, ZSTD_dtlm_fast,
|
|
cdict,
|
|
&cctxParams, pledgedSrcSize,
|
|
ZSTDb_not_buffered);
|
|
}
|
|
|
|
|
|
/* ZSTD_compressBegin_usingCDict_advanced() :
|
|
* This function is DEPRECATED.
|
|
* cdict must be != NULL */
|
|
size_t ZSTD_compressBegin_usingCDict_advanced(
|
|
ZSTD_CCtx* const cctx, const ZSTD_CDict* const cdict,
|
|
ZSTD_frameParameters const fParams, unsigned long long const pledgedSrcSize)
|
|
{
|
|
return ZSTD_compressBegin_usingCDict_internal(cctx, cdict, fParams, pledgedSrcSize);
|
|
}
|
|
|
|
/* ZSTD_compressBegin_usingCDict() :
|
|
* cdict must be != NULL */
|
|
size_t ZSTD_compressBegin_usingCDict_deprecated(ZSTD_CCtx* cctx, const ZSTD_CDict* cdict)
|
|
{
|
|
ZSTD_frameParameters const fParams = { 0 /*content*/, 0 /*checksum*/, 0 /*noDictID*/ };
|
|
return ZSTD_compressBegin_usingCDict_internal(cctx, cdict, fParams, ZSTD_CONTENTSIZE_UNKNOWN);
|
|
}
|
|
|
|
size_t ZSTD_compressBegin_usingCDict(ZSTD_CCtx* cctx, const ZSTD_CDict* cdict)
|
|
{
|
|
return ZSTD_compressBegin_usingCDict_deprecated(cctx, cdict);
|
|
}
|
|
|
|
/*! ZSTD_compress_usingCDict_internal():
|
|
* Implementation of various ZSTD_compress_usingCDict* functions.
|
|
*/
|
|
static size_t ZSTD_compress_usingCDict_internal(ZSTD_CCtx* cctx,
|
|
void* dst, size_t dstCapacity,
|
|
const void* src, size_t srcSize,
|
|
const ZSTD_CDict* cdict, ZSTD_frameParameters fParams)
|
|
{
|
|
FORWARD_IF_ERROR(ZSTD_compressBegin_usingCDict_internal(cctx, cdict, fParams, srcSize), ""); /* will check if cdict != NULL */
|
|
return ZSTD_compressEnd_public(cctx, dst, dstCapacity, src, srcSize);
|
|
}
|
|
|
|
/*! ZSTD_compress_usingCDict_advanced():
|
|
* This function is DEPRECATED.
|
|
*/
|
|
size_t ZSTD_compress_usingCDict_advanced(ZSTD_CCtx* cctx,
|
|
void* dst, size_t dstCapacity,
|
|
const void* src, size_t srcSize,
|
|
const ZSTD_CDict* cdict, ZSTD_frameParameters fParams)
|
|
{
|
|
return ZSTD_compress_usingCDict_internal(cctx, dst, dstCapacity, src, srcSize, cdict, fParams);
|
|
}
|
|
|
|
/*! ZSTD_compress_usingCDict() :
|
|
* Compression using a digested Dictionary.
|
|
* Faster startup than ZSTD_compress_usingDict(), recommended when same dictionary is used multiple times.
|
|
* Note that compression parameters are decided at CDict creation time
|
|
* while frame parameters are hardcoded */
|
|
size_t ZSTD_compress_usingCDict(ZSTD_CCtx* cctx,
|
|
void* dst, size_t dstCapacity,
|
|
const void* src, size_t srcSize,
|
|
const ZSTD_CDict* cdict)
|
|
{
|
|
ZSTD_frameParameters const fParams = { 1 /*content*/, 0 /*checksum*/, 0 /*noDictID*/ };
|
|
return ZSTD_compress_usingCDict_internal(cctx, dst, dstCapacity, src, srcSize, cdict, fParams);
|
|
}
|
|
|
|
|
|
|
|
/* ******************************************************************
|
|
* Streaming
|
|
********************************************************************/
|
|
|
|
ZSTD_CStream* ZSTD_createCStream(void)
|
|
{
|
|
DEBUGLOG(3, "ZSTD_createCStream");
|
|
return ZSTD_createCStream_advanced(ZSTD_defaultCMem);
|
|
}
|
|
|
|
ZSTD_CStream* ZSTD_initStaticCStream(void *workspace, size_t workspaceSize)
|
|
{
|
|
return ZSTD_initStaticCCtx(workspace, workspaceSize);
|
|
}
|
|
|
|
ZSTD_CStream* ZSTD_createCStream_advanced(ZSTD_customMem customMem)
|
|
{ /* CStream and CCtx are now same object */
|
|
return ZSTD_createCCtx_advanced(customMem);
|
|
}
|
|
|
|
size_t ZSTD_freeCStream(ZSTD_CStream* zcs)
|
|
{
|
|
return ZSTD_freeCCtx(zcs); /* same object */
|
|
}
|
|
|
|
|
|
|
|
/*====== Initialization ======*/
|
|
|
|
size_t ZSTD_CStreamInSize(void) { return ZSTD_rust_CStreamInSize(); }
|
|
|
|
size_t ZSTD_CStreamOutSize(void)
|
|
{
|
|
return ZSTD_rust_CStreamOutSize();
|
|
}
|
|
|
|
static ZSTD_CParamMode_e ZSTD_getCParamMode(ZSTD_CDict const* cdict, ZSTD_CCtx_params const* params, U64 pledgedSrcSize)
|
|
{
|
|
int const cdict_present = cdict != NULL;
|
|
int const cdict_strategy = cdict_present ? cdict->matchState.cParams.strategy : 0;
|
|
int const cdict_dedicated_search = cdict_present ? cdict->matchState.dedicatedDictSearch : 0;
|
|
return (ZSTD_CParamMode_e)ZSTD_rust_params_getCParamMode(
|
|
cdict_present,
|
|
cdict_strategy,
|
|
cdict_dedicated_search,
|
|
pledgedSrcSize,
|
|
(int)params->attachDictPref,
|
|
params->forceWindow);
|
|
}
|
|
|
|
/* ZSTD_resetCStream():
|
|
* pledgedSrcSize == 0 means "unknown" */
|
|
size_t ZSTD_resetCStream(ZSTD_CStream* zcs, unsigned long long pss)
|
|
{
|
|
/* temporary : 0 interpreted as "unknown" during transition period.
|
|
* Users willing to specify "unknown" **must** use ZSTD_CONTENTSIZE_UNKNOWN.
|
|
* 0 will be interpreted as "empty" in the future.
|
|
*/
|
|
U64 const pledgedSrcSize = (pss==0) ? ZSTD_CONTENTSIZE_UNKNOWN : pss;
|
|
DEBUGLOG(4, "ZSTD_resetCStream: pledgedSrcSize = %u", (unsigned)pledgedSrcSize);
|
|
FORWARD_IF_ERROR( ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only) , "");
|
|
FORWARD_IF_ERROR( ZSTD_CCtx_setPledgedSrcSize(zcs, pledgedSrcSize) , "");
|
|
return 0;
|
|
}
|
|
|
|
/*! ZSTD_initCStream_internal() :
|
|
* Note : for lib/compress only. Used by zstdmt_compress.c.
|
|
* Assumption 1 : params are valid
|
|
* Assumption 2 : either dict, or cdict, is defined, not both */
|
|
size_t ZSTD_initCStream_internal(ZSTD_CStream* zcs,
|
|
const void* dict, size_t dictSize, const ZSTD_CDict* cdict,
|
|
const ZSTD_CCtx_params* params,
|
|
unsigned long long pledgedSrcSize)
|
|
{
|
|
DEBUGLOG(4, "ZSTD_initCStream_internal");
|
|
FORWARD_IF_ERROR( ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only) , "");
|
|
FORWARD_IF_ERROR( ZSTD_CCtx_setPledgedSrcSize(zcs, pledgedSrcSize) , "");
|
|
assert(!ZSTD_isError(ZSTD_checkCParams(params->cParams)));
|
|
zcs->requestedParams = *params;
|
|
assert(!((dict) && (cdict))); /* either dict or cdict, not both */
|
|
if (dict) {
|
|
FORWARD_IF_ERROR( ZSTD_CCtx_loadDictionary(zcs, dict, dictSize) , "");
|
|
} else {
|
|
/* Dictionary is cleared if !cdict */
|
|
FORWARD_IF_ERROR( ZSTD_CCtx_refCDict(zcs, cdict) , "");
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
/* ZSTD_initCStream_usingCDict_advanced() :
|
|
* same as ZSTD_initCStream_usingCDict(), with control over frame parameters */
|
|
size_t ZSTD_initCStream_usingCDict_advanced(ZSTD_CStream* zcs,
|
|
const ZSTD_CDict* cdict,
|
|
ZSTD_frameParameters fParams,
|
|
unsigned long long pledgedSrcSize)
|
|
{
|
|
DEBUGLOG(4, "ZSTD_initCStream_usingCDict_advanced");
|
|
FORWARD_IF_ERROR( ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only) , "");
|
|
FORWARD_IF_ERROR( ZSTD_CCtx_setPledgedSrcSize(zcs, pledgedSrcSize) , "");
|
|
zcs->requestedParams.fParams = fParams;
|
|
FORWARD_IF_ERROR( ZSTD_CCtx_refCDict(zcs, cdict) , "");
|
|
return 0;
|
|
}
|
|
|
|
/* note : cdict must outlive compression session */
|
|
size_t ZSTD_initCStream_usingCDict(ZSTD_CStream* zcs, const ZSTD_CDict* cdict)
|
|
{
|
|
DEBUGLOG(4, "ZSTD_initCStream_usingCDict");
|
|
FORWARD_IF_ERROR( ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only) , "");
|
|
FORWARD_IF_ERROR( ZSTD_CCtx_refCDict(zcs, cdict) , "");
|
|
return 0;
|
|
}
|
|
|
|
|
|
/* ZSTD_initCStream_advanced() :
|
|
* pledgedSrcSize must be exact.
|
|
* if srcSize is not known at init time, use value ZSTD_CONTENTSIZE_UNKNOWN.
|
|
* dict is loaded with default parameters ZSTD_dct_auto and ZSTD_dlm_byCopy. */
|
|
size_t ZSTD_initCStream_advanced(ZSTD_CStream* zcs,
|
|
const void* dict, size_t dictSize,
|
|
ZSTD_parameters params, unsigned long long pss)
|
|
{
|
|
/* for compatibility with older programs relying on this behavior.
|
|
* Users should now specify ZSTD_CONTENTSIZE_UNKNOWN.
|
|
* This line will be removed in the future.
|
|
*/
|
|
U64 const pledgedSrcSize = (pss==0 && params.fParams.contentSizeFlag==0) ? ZSTD_CONTENTSIZE_UNKNOWN : pss;
|
|
DEBUGLOG(4, "ZSTD_initCStream_advanced");
|
|
FORWARD_IF_ERROR( ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only) , "");
|
|
FORWARD_IF_ERROR( ZSTD_CCtx_setPledgedSrcSize(zcs, pledgedSrcSize) , "");
|
|
FORWARD_IF_ERROR( ZSTD_checkCParams(params.cParams) , "");
|
|
ZSTD_CCtxParams_setZstdParams(&zcs->requestedParams, ¶ms);
|
|
FORWARD_IF_ERROR( ZSTD_CCtx_loadDictionary(zcs, dict, dictSize) , "");
|
|
return 0;
|
|
}
|
|
|
|
size_t ZSTD_initCStream_usingDict(ZSTD_CStream* zcs, const void* dict, size_t dictSize, int compressionLevel)
|
|
{
|
|
DEBUGLOG(4, "ZSTD_initCStream_usingDict");
|
|
FORWARD_IF_ERROR( ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only) , "");
|
|
FORWARD_IF_ERROR( ZSTD_CCtx_setParameter(zcs, ZSTD_c_compressionLevel, compressionLevel) , "");
|
|
FORWARD_IF_ERROR( ZSTD_CCtx_loadDictionary(zcs, dict, dictSize) , "");
|
|
return 0;
|
|
}
|
|
|
|
size_t ZSTD_initCStream_srcSize(ZSTD_CStream* zcs, int compressionLevel, unsigned long long pss)
|
|
{
|
|
/* temporary : 0 interpreted as "unknown" during transition period.
|
|
* Users willing to specify "unknown" **must** use ZSTD_CONTENTSIZE_UNKNOWN.
|
|
* 0 will be interpreted as "empty" in the future.
|
|
*/
|
|
U64 const pledgedSrcSize = (pss==0) ? ZSTD_CONTENTSIZE_UNKNOWN : pss;
|
|
DEBUGLOG(4, "ZSTD_initCStream_srcSize");
|
|
FORWARD_IF_ERROR( ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only) , "");
|
|
FORWARD_IF_ERROR( ZSTD_CCtx_refCDict(zcs, NULL) , "");
|
|
FORWARD_IF_ERROR( ZSTD_CCtx_setParameter(zcs, ZSTD_c_compressionLevel, compressionLevel) , "");
|
|
FORWARD_IF_ERROR( ZSTD_CCtx_setPledgedSrcSize(zcs, pledgedSrcSize) , "");
|
|
return 0;
|
|
}
|
|
|
|
size_t ZSTD_initCStream(ZSTD_CStream* zcs, int compressionLevel)
|
|
{
|
|
DEBUGLOG(4, "ZSTD_initCStream");
|
|
FORWARD_IF_ERROR( ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only) , "");
|
|
FORWARD_IF_ERROR( ZSTD_CCtx_refCDict(zcs, NULL) , "");
|
|
FORWARD_IF_ERROR( ZSTD_CCtx_setParameter(zcs, ZSTD_c_compressionLevel, compressionLevel) , "");
|
|
return 0;
|
|
}
|
|
|
|
/*====== Compression ======*/
|
|
|
|
static size_t ZSTD_nextInputSizeHint(const ZSTD_CCtx* cctx)
|
|
{
|
|
int const inBufferMode = (int)cctx->appliedParams.inBufferMode;
|
|
if (inBufferMode == ZSTD_bm_stable) {
|
|
return ZSTD_rust_nextInputSizeHint(inBufferMode,
|
|
cctx->blockSizeMax,
|
|
cctx->stableIn_notConsumed,
|
|
cctx->inBuffTarget,
|
|
cctx->inBuffPos);
|
|
}
|
|
assert(inBufferMode == ZSTD_bm_buffered);
|
|
return ZSTD_rust_nextInputSizeHint(inBufferMode,
|
|
cctx->blockSizeMax,
|
|
cctx->stableIn_notConsumed,
|
|
cctx->inBuffTarget,
|
|
cctx->inBuffPos);
|
|
}
|
|
|
|
/** ZSTD_compressStream_generic():
|
|
* internal function for all *compressStream*() variants
|
|
* @return : hint size for next input to complete ongoing block */
|
|
static size_t ZSTD_compressStream_generic(ZSTD_CStream* zcs,
|
|
ZSTD_outBuffer* output,
|
|
ZSTD_inBuffer* input,
|
|
ZSTD_EndDirective const flushMode)
|
|
{
|
|
const char* const istart = (assert(input != NULL), (const char*)input->src);
|
|
const char* const iend = (istart != NULL) ? istart + input->size : istart;
|
|
const char* ip = (istart != NULL) ? istart + input->pos : istart;
|
|
char* const ostart = (assert(output != NULL), (char*)output->dst);
|
|
char* const oend = (ostart != NULL) ? ostart + output->size : ostart;
|
|
char* op = (ostart != NULL) ? ostart + output->pos : ostart;
|
|
U32 someMoreWork = 1;
|
|
|
|
/* check expectations */
|
|
DEBUGLOG(5, "ZSTD_compressStream_generic, flush=%i, srcSize = %zu", (int)flushMode, input->size - input->pos);
|
|
assert(zcs != NULL);
|
|
if (zcs->appliedParams.inBufferMode == ZSTD_bm_stable) {
|
|
assert(input->pos >= zcs->stableIn_notConsumed);
|
|
input->pos -= zcs->stableIn_notConsumed;
|
|
if (ip) ip -= zcs->stableIn_notConsumed;
|
|
zcs->stableIn_notConsumed = 0;
|
|
}
|
|
if (zcs->appliedParams.inBufferMode == ZSTD_bm_buffered) {
|
|
assert(zcs->inBuff != NULL);
|
|
assert(zcs->inBuffSize > 0);
|
|
}
|
|
if (zcs->appliedParams.outBufferMode == ZSTD_bm_buffered) {
|
|
assert(zcs->outBuff != NULL);
|
|
assert(zcs->outBuffSize > 0);
|
|
}
|
|
if (input->src == NULL) assert(input->size == 0);
|
|
assert(input->pos <= input->size);
|
|
if (output->dst == NULL) assert(output->size == 0);
|
|
assert(output->pos <= output->size);
|
|
assert((U32)flushMode <= (U32)ZSTD_e_end);
|
|
|
|
while (someMoreWork) {
|
|
switch(zcs->streamStage)
|
|
{
|
|
case zcss_init:
|
|
RETURN_ERROR(init_missing, "call ZSTD_initCStream() first!");
|
|
|
|
case zcss_load:
|
|
if ( (flushMode == ZSTD_e_end)
|
|
&& ( (size_t)(oend-op) >= ZSTD_compressBound((size_t)(iend-ip)) /* Enough output space */
|
|
|| zcs->appliedParams.outBufferMode == ZSTD_bm_stable) /* OR we are allowed to return dstSizeTooSmall */
|
|
&& (zcs->inBuffPos == 0) ) {
|
|
/* shortcut to compression pass directly into output buffer */
|
|
size_t const cSize = ZSTD_compressEnd_public(zcs,
|
|
op, (size_t)(oend-op),
|
|
ip, (size_t)(iend-ip));
|
|
DEBUGLOG(4, "ZSTD_compressEnd : cSize=%u", (unsigned)cSize);
|
|
FORWARD_IF_ERROR(cSize, "ZSTD_compressEnd failed");
|
|
ip = iend;
|
|
op += cSize;
|
|
zcs->frameEnded = 1;
|
|
ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only);
|
|
someMoreWork = 0; break;
|
|
}
|
|
/* complete loading into inBuffer in buffered mode */
|
|
if (zcs->appliedParams.inBufferMode == ZSTD_bm_buffered) {
|
|
size_t const toLoad = zcs->inBuffTarget - zcs->inBuffPos;
|
|
size_t const loaded = ZSTD_limitCopy(
|
|
zcs->inBuff + zcs->inBuffPos, toLoad,
|
|
ip, (size_t)(iend-ip));
|
|
zcs->inBuffPos += loaded;
|
|
if (ip) ip += loaded;
|
|
if ( (flushMode == ZSTD_e_continue)
|
|
&& (zcs->inBuffPos < zcs->inBuffTarget) ) {
|
|
/* not enough input to fill full block : stop here */
|
|
someMoreWork = 0; break;
|
|
}
|
|
if ( (flushMode == ZSTD_e_flush)
|
|
&& (zcs->inBuffPos == zcs->inToCompress) ) {
|
|
/* empty */
|
|
someMoreWork = 0; break;
|
|
}
|
|
} else {
|
|
assert(zcs->appliedParams.inBufferMode == ZSTD_bm_stable);
|
|
if ( (flushMode == ZSTD_e_continue)
|
|
&& ( (size_t)(iend - ip) < zcs->blockSizeMax) ) {
|
|
/* can't compress a full block : stop here */
|
|
zcs->stableIn_notConsumed = (size_t)(iend - ip);
|
|
ip = iend; /* pretend to have consumed input */
|
|
someMoreWork = 0; break;
|
|
}
|
|
if ( (flushMode == ZSTD_e_flush)
|
|
&& (ip == iend) ) {
|
|
/* empty */
|
|
someMoreWork = 0; break;
|
|
}
|
|
}
|
|
/* compress current block (note : this stage cannot be stopped in the middle) */
|
|
DEBUGLOG(5, "stream compression stage (flushMode==%u)", flushMode);
|
|
{ int const inputBuffered = (zcs->appliedParams.inBufferMode == ZSTD_bm_buffered);
|
|
void* cDst;
|
|
size_t cSize;
|
|
size_t oSize = (size_t)(oend-op);
|
|
size_t const iSize = inputBuffered ? zcs->inBuffPos - zcs->inToCompress
|
|
: MIN((size_t)(iend - ip), zcs->blockSizeMax);
|
|
if (oSize >= ZSTD_compressBound(iSize) || zcs->appliedParams.outBufferMode == ZSTD_bm_stable)
|
|
cDst = op; /* compress into output buffer, to skip flush stage */
|
|
else
|
|
cDst = zcs->outBuff, oSize = zcs->outBuffSize;
|
|
if (inputBuffered) {
|
|
unsigned const lastBlock = (flushMode == ZSTD_e_end) && (ip==iend);
|
|
cSize = lastBlock ?
|
|
ZSTD_compressEnd_public(zcs, cDst, oSize,
|
|
zcs->inBuff + zcs->inToCompress, iSize) :
|
|
ZSTD_compressContinue_public(zcs, cDst, oSize,
|
|
zcs->inBuff + zcs->inToCompress, iSize);
|
|
FORWARD_IF_ERROR(cSize, "%s", lastBlock ? "ZSTD_compressEnd failed" : "ZSTD_compressContinue failed");
|
|
zcs->frameEnded = lastBlock;
|
|
/* prepare next block */
|
|
zcs->inBuffTarget = zcs->inBuffPos + zcs->blockSizeMax;
|
|
if (zcs->inBuffTarget > zcs->inBuffSize)
|
|
zcs->inBuffPos = 0, zcs->inBuffTarget = zcs->blockSizeMax;
|
|
DEBUGLOG(5, "inBuffTarget:%u / inBuffSize:%u",
|
|
(unsigned)zcs->inBuffTarget, (unsigned)zcs->inBuffSize);
|
|
if (!lastBlock)
|
|
assert(zcs->inBuffTarget <= zcs->inBuffSize);
|
|
zcs->inToCompress = zcs->inBuffPos;
|
|
} else { /* !inputBuffered, hence ZSTD_bm_stable */
|
|
unsigned const lastBlock = (flushMode == ZSTD_e_end) && (ip + iSize == iend);
|
|
cSize = lastBlock ?
|
|
ZSTD_compressEnd_public(zcs, cDst, oSize, ip, iSize) :
|
|
ZSTD_compressContinue_public(zcs, cDst, oSize, ip, iSize);
|
|
/* Consume the input prior to error checking to mirror buffered mode. */
|
|
if (ip) ip += iSize;
|
|
FORWARD_IF_ERROR(cSize, "%s", lastBlock ? "ZSTD_compressEnd failed" : "ZSTD_compressContinue failed");
|
|
zcs->frameEnded = lastBlock;
|
|
if (lastBlock) assert(ip == iend);
|
|
}
|
|
if (cDst == op) { /* no need to flush */
|
|
op += cSize;
|
|
if (zcs->frameEnded) {
|
|
DEBUGLOG(5, "Frame completed directly in outBuffer");
|
|
someMoreWork = 0;
|
|
ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only);
|
|
}
|
|
break;
|
|
}
|
|
zcs->outBuffContentSize = cSize;
|
|
zcs->outBuffFlushedSize = 0;
|
|
zcs->streamStage = zcss_flush; /* pass-through to flush stage */
|
|
}
|
|
ZSTD_FALLTHROUGH;
|
|
case zcss_flush:
|
|
DEBUGLOG(5, "flush stage");
|
|
assert(zcs->appliedParams.outBufferMode == ZSTD_bm_buffered);
|
|
{ size_t const toFlush = zcs->outBuffContentSize - zcs->outBuffFlushedSize;
|
|
size_t const flushed = ZSTD_limitCopy(op, (size_t)(oend-op),
|
|
zcs->outBuff + zcs->outBuffFlushedSize, toFlush);
|
|
DEBUGLOG(5, "toFlush: %u into %u ==> flushed: %u",
|
|
(unsigned)toFlush, (unsigned)(oend-op), (unsigned)flushed);
|
|
if (flushed)
|
|
op += flushed;
|
|
zcs->outBuffFlushedSize += flushed;
|
|
if (toFlush!=flushed) {
|
|
/* flush not fully completed, presumably because dst is too small */
|
|
assert(op==oend);
|
|
someMoreWork = 0;
|
|
break;
|
|
}
|
|
zcs->outBuffContentSize = zcs->outBuffFlushedSize = 0;
|
|
if (zcs->frameEnded) {
|
|
DEBUGLOG(5, "Frame completed on flush");
|
|
someMoreWork = 0;
|
|
ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only);
|
|
break;
|
|
}
|
|
zcs->streamStage = zcss_load;
|
|
break;
|
|
}
|
|
|
|
default: /* impossible */
|
|
assert(0);
|
|
}
|
|
}
|
|
|
|
input->pos = (size_t)(ip - istart);
|
|
output->pos = (size_t)(op - ostart);
|
|
if (zcs->frameEnded) return 0;
|
|
return ZSTD_nextInputSizeHint(zcs);
|
|
}
|
|
|
|
static size_t ZSTD_nextInputSizeHint_MTorST(const ZSTD_CCtx* cctx)
|
|
{
|
|
#ifdef ZSTD_MULTITHREAD
|
|
if (cctx->appliedParams.nbWorkers >= 1) {
|
|
assert(cctx->mtctx != NULL);
|
|
return ZSTDMT_nextInputSizeHint(cctx->mtctx);
|
|
}
|
|
#endif
|
|
return ZSTD_nextInputSizeHint(cctx);
|
|
|
|
}
|
|
|
|
size_t ZSTD_compressStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output, ZSTD_inBuffer* input)
|
|
{
|
|
FORWARD_IF_ERROR( ZSTD_compressStream2(zcs, output, input, ZSTD_e_continue) , "");
|
|
return ZSTD_nextInputSizeHint_MTorST(zcs);
|
|
}
|
|
|
|
/* After a compression call set the expected input/output buffer.
|
|
* This is validated at the start of the next compression call.
|
|
*/
|
|
static void
|
|
ZSTD_setBufferExpectations(ZSTD_CCtx* cctx, const ZSTD_outBuffer* output, const ZSTD_inBuffer* input)
|
|
{
|
|
DEBUGLOG(5, "ZSTD_setBufferExpectations (for advanced stable in/out modes)");
|
|
if (cctx->appliedParams.inBufferMode == ZSTD_bm_stable) {
|
|
cctx->expectedInBuffer = *input;
|
|
}
|
|
if (cctx->appliedParams.outBufferMode == ZSTD_bm_stable) {
|
|
cctx->expectedOutBufferSize = output->size - output->pos;
|
|
}
|
|
}
|
|
|
|
/* Validate that the input/output buffers match the expectations set by
|
|
* ZSTD_setBufferExpectations.
|
|
*/
|
|
static size_t ZSTD_checkBufferStability(ZSTD_CCtx const* cctx,
|
|
ZSTD_outBuffer const* output,
|
|
ZSTD_inBuffer const* input)
|
|
{
|
|
return ZSTD_rust_checkBufferStability(
|
|
(int)cctx->appliedParams.inBufferMode,
|
|
(int)cctx->appliedParams.outBufferMode,
|
|
cctx->expectedInBuffer.src,
|
|
cctx->expectedInBuffer.pos,
|
|
input->src,
|
|
input->pos,
|
|
cctx->expectedOutBufferSize,
|
|
output->size,
|
|
output->pos);
|
|
}
|
|
|
|
/*
|
|
* If @endOp == ZSTD_e_end, @inSize becomes pledgedSrcSize.
|
|
* Otherwise, it's ignored.
|
|
* @return: 0 on success, or a ZSTD_error code otherwise.
|
|
*/
|
|
static size_t ZSTD_CCtx_init_compressStream2(ZSTD_CCtx* cctx,
|
|
ZSTD_EndDirective endOp,
|
|
size_t inSize)
|
|
{
|
|
ZSTD_CCtx_params params = cctx->requestedParams;
|
|
ZSTD_prefixDict const prefixDict = cctx->prefixDict;
|
|
FORWARD_IF_ERROR( ZSTD_initLocalDict(cctx) , ""); /* Init the local dict if present. */
|
|
ZSTD_memset(&cctx->prefixDict, 0, sizeof(cctx->prefixDict)); /* single usage */
|
|
assert(prefixDict.dict==NULL || cctx->cdict==NULL); /* only one can be set */
|
|
if (cctx->cdict && !cctx->localDict.cdict) {
|
|
/* Let the cdict's compression level take priority over the requested params.
|
|
* But do not take the cdict's compression level if the "cdict" is actually a localDict
|
|
* generated from ZSTD_initLocalDict().
|
|
*/
|
|
params.compressionLevel = cctx->cdict->compressionLevel;
|
|
}
|
|
DEBUGLOG(4, "ZSTD_CCtx_init_compressStream2 : transparent init stage");
|
|
if (endOp == ZSTD_e_end) cctx->pledgedSrcSizePlusOne = inSize + 1; /* auto-determine pledgedSrcSize */
|
|
|
|
{ size_t const dictSize = prefixDict.dict
|
|
? prefixDict.dictSize
|
|
: (cctx->cdict ? cctx->cdict->dictContentSize : 0);
|
|
ZSTD_CParamMode_e const mode = ZSTD_getCParamMode(cctx->cdict, ¶ms, cctx->pledgedSrcSizePlusOne - 1);
|
|
params.cParams = ZSTD_getCParamsFromCCtxParams(
|
|
¶ms, cctx->pledgedSrcSizePlusOne-1,
|
|
dictSize, mode);
|
|
}
|
|
|
|
params.postBlockSplitter = ZSTD_resolveBlockSplitterMode(params.postBlockSplitter, ¶ms.cParams);
|
|
params.ldmParams.enableLdm = ZSTD_resolveEnableLdm(params.ldmParams.enableLdm, ¶ms.cParams);
|
|
params.useRowMatchFinder = ZSTD_resolveRowMatchFinderMode(params.useRowMatchFinder, ¶ms.cParams);
|
|
params.validateSequences = ZSTD_resolveExternalSequenceValidation(params.validateSequences);
|
|
params.maxBlockSize = ZSTD_resolveMaxBlockSize(params.maxBlockSize);
|
|
params.searchForExternalRepcodes = ZSTD_resolveExternalRepcodeSearch(params.searchForExternalRepcodes, params.compressionLevel);
|
|
|
|
#ifdef ZSTD_MULTITHREAD
|
|
/* If external matchfinder is enabled, make sure to fail before checking job size (for consistency) */
|
|
RETURN_ERROR_IF(
|
|
ZSTD_hasExtSeqProd(¶ms) && params.nbWorkers >= 1,
|
|
parameter_combination_unsupported,
|
|
"External sequence producer isn't supported with nbWorkers >= 1"
|
|
);
|
|
|
|
if ((cctx->pledgedSrcSizePlusOne-1) <= ZSTDMT_JOBSIZE_MIN) {
|
|
params.nbWorkers = 0; /* do not invoke multi-threading when src size is too small */
|
|
}
|
|
if (params.nbWorkers > 0) {
|
|
# if ZSTD_TRACE
|
|
cctx->traceCtx = (ZSTD_trace_compress_begin != NULL) ? ZSTD_trace_compress_begin(cctx) : 0;
|
|
# endif
|
|
/* mt context creation */
|
|
if (cctx->mtctx == NULL) {
|
|
DEBUGLOG(4, "ZSTD_compressStream2: creating new mtctx for nbWorkers=%u",
|
|
params.nbWorkers);
|
|
cctx->mtctx = ZSTDMT_createCCtx_advanced((U32)params.nbWorkers, cctx->customMem, cctx->pool);
|
|
RETURN_ERROR_IF(cctx->mtctx == NULL, memory_allocation, "NULL pointer!");
|
|
}
|
|
/* mt compression */
|
|
DEBUGLOG(4, "call ZSTDMT_initCStream_internal as nbWorkers=%u", params.nbWorkers);
|
|
FORWARD_IF_ERROR( ZSTDMT_initCStream_internal(
|
|
cctx->mtctx,
|
|
prefixDict.dict, prefixDict.dictSize, prefixDict.dictContentType,
|
|
cctx->cdict, params, cctx->pledgedSrcSizePlusOne-1) , "");
|
|
cctx->dictID = cctx->cdict ? cctx->cdict->dictID : 0;
|
|
cctx->dictContentSize = cctx->cdict ? cctx->cdict->dictContentSize : prefixDict.dictSize;
|
|
cctx->consumedSrcSize = 0;
|
|
cctx->producedCSize = 0;
|
|
cctx->streamStage = zcss_load;
|
|
cctx->appliedParams = params;
|
|
} else
|
|
#endif /* ZSTD_MULTITHREAD */
|
|
{ U64 const pledgedSrcSize = cctx->pledgedSrcSizePlusOne - 1;
|
|
assert(!ZSTD_isError(ZSTD_checkCParams(params.cParams)));
|
|
FORWARD_IF_ERROR( ZSTD_compressBegin_internal(cctx,
|
|
prefixDict.dict, prefixDict.dictSize, prefixDict.dictContentType, ZSTD_dtlm_fast,
|
|
cctx->cdict,
|
|
¶ms, pledgedSrcSize,
|
|
ZSTDb_buffered) , "");
|
|
assert(cctx->appliedParams.nbWorkers == 0);
|
|
cctx->inToCompress = 0;
|
|
cctx->inBuffPos = 0;
|
|
if (cctx->appliedParams.inBufferMode == ZSTD_bm_buffered) {
|
|
/* for small input: avoid automatic flush on reaching end of block, since
|
|
* it would require to add a 3-bytes null block to end frame
|
|
*/
|
|
cctx->inBuffTarget = cctx->blockSizeMax + (cctx->blockSizeMax == pledgedSrcSize);
|
|
} else {
|
|
cctx->inBuffTarget = 0;
|
|
}
|
|
cctx->outBuffContentSize = cctx->outBuffFlushedSize = 0;
|
|
cctx->streamStage = zcss_load;
|
|
cctx->frameEnded = 0;
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
/* @return provides a minimum amount of data remaining to be flushed from internal buffers
|
|
*/
|
|
size_t ZSTD_compressStream2_c( ZSTD_CCtx* cctx,
|
|
ZSTD_outBuffer* output,
|
|
ZSTD_inBuffer* input,
|
|
ZSTD_EndDirective endOp)
|
|
{
|
|
DEBUGLOG(5, "ZSTD_compressStream2, endOp=%u ", (unsigned)endOp);
|
|
/* check conditions */
|
|
RETURN_ERROR_IF(output->pos > output->size, dstSize_tooSmall, "invalid output buffer");
|
|
RETURN_ERROR_IF(input->pos > input->size, srcSize_wrong, "invalid input buffer");
|
|
RETURN_ERROR_IF((U32)endOp > (U32)ZSTD_e_end, parameter_outOfBound, "invalid endDirective");
|
|
assert(cctx != NULL);
|
|
|
|
/* transparent initialization stage */
|
|
if (cctx->rustSimpleCompress2Completed) {
|
|
if (endOp == ZSTD_e_end
|
|
&& cctx->streamStage == zcss_init
|
|
&& cctx->pledgedSrcSizePlusOne == 0
|
|
&& ZSTD_rust_simpleCompress2Level(
|
|
cctx, input->size - input->pos) != (-2147483647 - 1)) {
|
|
void* const dst = output->dst ?
|
|
(char*)output->dst + output->pos : output->dst;
|
|
const void* const src = input->src ?
|
|
(const char*)input->src + input->pos : input->src;
|
|
size_t const result = ZSTD_compress2(
|
|
cctx, dst, output->size - output->pos,
|
|
src, input->size - input->pos);
|
|
cctx->rustSimpleCompress2Completed = 0;
|
|
if (!ZSTD_isError(result)) {
|
|
output->pos += result;
|
|
input->pos = input->size;
|
|
return 0;
|
|
}
|
|
}
|
|
/* A different streaming directive or an advanced parameter means the
|
|
* frame can no longer reuse the one-shot Rust result. */
|
|
cctx->rustSimpleCompress2Completed = 0;
|
|
}
|
|
|
|
if (cctx->streamStage == zcss_init) {
|
|
size_t const inputSize = input->size - input->pos; /* no obligation to start from pos==0 */
|
|
size_t const totalInputSize = inputSize + cctx->stableIn_notConsumed;
|
|
if ( (cctx->requestedParams.inBufferMode == ZSTD_bm_stable) /* input is presumed stable, across invocations */
|
|
&& (endOp == ZSTD_e_continue) /* no flush requested, more input to come */
|
|
&& (totalInputSize < ZSTD_BLOCKSIZE_MAX) ) { /* not even reached one block yet */
|
|
if (cctx->stableIn_notConsumed) { /* not the first time */
|
|
/* check stable source guarantees */
|
|
RETURN_ERROR_IF(input->src != cctx->expectedInBuffer.src, stabilityCondition_notRespected, "stableInBuffer condition not respected: wrong src pointer");
|
|
RETURN_ERROR_IF(input->pos != cctx->expectedInBuffer.size, stabilityCondition_notRespected, "stableInBuffer condition not respected: externally modified pos");
|
|
}
|
|
/* pretend input was consumed, to give a sense forward progress */
|
|
input->pos = input->size;
|
|
/* save stable inBuffer, for later control, and flush/end */
|
|
cctx->expectedInBuffer = *input;
|
|
/* but actually input wasn't consumed, so keep track of position from where compression shall resume */
|
|
cctx->stableIn_notConsumed += inputSize;
|
|
/* don't initialize yet, wait for the first block of flush() order, for better parameters adaptation */
|
|
return ZSTD_FRAMEHEADERSIZE_MIN(cctx->requestedParams.format); /* at least some header to produce */
|
|
}
|
|
FORWARD_IF_ERROR(ZSTD_CCtx_init_compressStream2(cctx, endOp, totalInputSize), "compressStream2 initialization failed");
|
|
ZSTD_setBufferExpectations(cctx, output, input); /* Set initial buffer expectations now that we've initialized */
|
|
}
|
|
/* end of transparent initialization stage */
|
|
|
|
FORWARD_IF_ERROR(ZSTD_checkBufferStability(cctx, output, input), "invalid buffers");
|
|
/* compression stage */
|
|
#ifdef ZSTD_MULTITHREAD
|
|
if (cctx->appliedParams.nbWorkers > 0) {
|
|
size_t flushMin;
|
|
if (cctx->cParamsChanged) {
|
|
ZSTDMT_updateCParams_whileCompressing(cctx->mtctx, &cctx->requestedParams);
|
|
cctx->cParamsChanged = 0;
|
|
}
|
|
if (cctx->stableIn_notConsumed) {
|
|
assert(cctx->appliedParams.inBufferMode == ZSTD_bm_stable);
|
|
/* some early data was skipped - make it available for consumption */
|
|
assert(input->pos >= cctx->stableIn_notConsumed);
|
|
input->pos -= cctx->stableIn_notConsumed;
|
|
cctx->stableIn_notConsumed = 0;
|
|
}
|
|
for (;;) {
|
|
size_t const ipos = input->pos;
|
|
size_t const opos = output->pos;
|
|
flushMin = ZSTDMT_compressStream_generic(cctx->mtctx, output, input, endOp);
|
|
cctx->consumedSrcSize += (U64)(input->pos - ipos);
|
|
cctx->producedCSize += (U64)(output->pos - opos);
|
|
if ( ZSTD_isError(flushMin)
|
|
|| (endOp == ZSTD_e_end && flushMin == 0) ) { /* compression completed */
|
|
if (flushMin == 0)
|
|
ZSTD_CCtx_trace(cctx, 0);
|
|
ZSTD_CCtx_reset(cctx, ZSTD_reset_session_only);
|
|
}
|
|
FORWARD_IF_ERROR(flushMin, "ZSTDMT_compressStream_generic failed");
|
|
|
|
if (endOp == ZSTD_e_continue) {
|
|
/* We only require some progress with ZSTD_e_continue, not maximal progress.
|
|
* We're done if we've consumed or produced any bytes, or either buffer is
|
|
* full.
|
|
*/
|
|
if (input->pos != ipos || output->pos != opos || input->pos == input->size || output->pos == output->size)
|
|
break;
|
|
} else {
|
|
assert(endOp == ZSTD_e_flush || endOp == ZSTD_e_end);
|
|
/* We require maximal progress. We're done when the flush is complete or the
|
|
* output buffer is full.
|
|
*/
|
|
if (flushMin == 0 || output->pos == output->size)
|
|
break;
|
|
}
|
|
}
|
|
DEBUGLOG(5, "completed ZSTD_compressStream2 delegating to ZSTDMT_compressStream_generic");
|
|
/* Either we don't require maximum forward progress, we've finished the
|
|
* flush, or we are out of output space.
|
|
*/
|
|
assert(endOp == ZSTD_e_continue || flushMin == 0 || output->pos == output->size);
|
|
ZSTD_setBufferExpectations(cctx, output, input);
|
|
return flushMin;
|
|
}
|
|
#endif /* ZSTD_MULTITHREAD */
|
|
FORWARD_IF_ERROR( ZSTD_compressStream_generic(cctx, output, input, endOp) , "");
|
|
DEBUGLOG(5, "completed ZSTD_compressStream2");
|
|
ZSTD_setBufferExpectations(cctx, output, input);
|
|
return cctx->outBuffContentSize - cctx->outBuffFlushedSize; /* remaining to flush */
|
|
}
|
|
|
|
size_t ZSTD_compressStream2_simpleArgs (
|
|
ZSTD_CCtx* cctx,
|
|
void* dst, size_t dstCapacity, size_t* dstPos,
|
|
const void* src, size_t srcSize, size_t* srcPos,
|
|
ZSTD_EndDirective endOp)
|
|
{
|
|
ZSTD_outBuffer output;
|
|
ZSTD_inBuffer input;
|
|
output.dst = dst;
|
|
output.size = dstCapacity;
|
|
output.pos = *dstPos;
|
|
input.src = src;
|
|
input.size = srcSize;
|
|
input.pos = *srcPos;
|
|
/* ZSTD_compressStream2() will check validity of dstPos and srcPos */
|
|
{ size_t const cErr = ZSTD_compressStream2(cctx, &output, &input, endOp);
|
|
*dstPos = output.pos;
|
|
*srcPos = input.pos;
|
|
return cErr;
|
|
}
|
|
}
|
|
|
|
size_t ZSTD_compress2_c(ZSTD_CCtx* cctx,
|
|
void* dst, size_t dstCapacity,
|
|
const void* src, size_t srcSize)
|
|
{
|
|
ZSTD_bufferMode_e const originalInBufferMode = cctx->requestedParams.inBufferMode;
|
|
ZSTD_bufferMode_e const originalOutBufferMode = cctx->requestedParams.outBufferMode;
|
|
DEBUGLOG(4, "ZSTD_compress2 (srcSize=%u)", (unsigned)srcSize);
|
|
ZSTD_CCtx_reset(cctx, ZSTD_reset_session_only);
|
|
/* Enable stable input/output buffers. */
|
|
cctx->requestedParams.inBufferMode = ZSTD_bm_stable;
|
|
cctx->requestedParams.outBufferMode = ZSTD_bm_stable;
|
|
{ size_t oPos = 0;
|
|
size_t iPos = 0;
|
|
size_t const result = ZSTD_compressStream2_simpleArgs(cctx,
|
|
dst, dstCapacity, &oPos,
|
|
src, srcSize, &iPos,
|
|
ZSTD_e_end);
|
|
/* Reset to the original values. */
|
|
cctx->requestedParams.inBufferMode = originalInBufferMode;
|
|
cctx->requestedParams.outBufferMode = originalOutBufferMode;
|
|
|
|
FORWARD_IF_ERROR(result, "ZSTD_compressStream2_simpleArgs failed");
|
|
if (result != 0) { /* compression not completed, due to lack of output space */
|
|
assert(oPos == dstCapacity);
|
|
RETURN_ERROR(dstSize_tooSmall, "");
|
|
}
|
|
assert(iPos == srcSize); /* all input is expected consumed */
|
|
return oPos;
|
|
}
|
|
}
|
|
|
|
/* Returns an offset code, given a sequence's raw offset, the ongoing repcode array, and whether litLength == 0 */
|
|
static U32 ZSTD_finalizeOffBase(U32 rawOffset, const U32 rep[ZSTD_REP_NUM], U32 ll0)
|
|
{
|
|
return ZSTD_rust_finalizeOffBase(rawOffset, rep, ll0);
|
|
}
|
|
|
|
/* This function scans through an array of ZSTD_Sequence,
|
|
* storing the sequences it reads, until it reaches a block delimiter.
|
|
* Note that the block delimiter includes the last literals of the block.
|
|
* @blockSize must be == sum(sequence_lengths).
|
|
* @returns @blockSize on success, and a ZSTD_error otherwise.
|
|
*/
|
|
static size_t
|
|
ZSTD_transferSequences_wBlockDelim(ZSTD_CCtx* cctx,
|
|
ZSTD_SequencePosition* seqPos,
|
|
const ZSTD_Sequence* const inSeqs, size_t inSeqsSize,
|
|
const void* src, size_t blockSize,
|
|
ZSTD_ParamSwitch_e externalRepSearch)
|
|
{
|
|
U32 dictSize;
|
|
|
|
if (cctx->cdict) {
|
|
dictSize = (U32)cctx->cdict->dictContentSize;
|
|
} else if (cctx->prefixDict.dict) {
|
|
dictSize = (U32)cctx->prefixDict.dictSize;
|
|
} else {
|
|
dictSize = 0;
|
|
}
|
|
return ZSTD_rust_transferSequencesWBlockDelim(
|
|
&cctx->seqStore, seqPos, inSeqs, inSeqsSize,
|
|
(const BYTE*)src, blockSize, (int)externalRepSearch,
|
|
cctx->blockState.prevCBlock->rep,
|
|
cctx->blockState.nextCBlock->rep, dictSize,
|
|
cctx->appliedParams.validateSequences,
|
|
cctx->appliedParams.cParams.minMatch,
|
|
cctx->appliedParams.cParams.windowLog,
|
|
ZSTD_hasExtSeqProd(&cctx->appliedParams));
|
|
}
|
|
|
|
/*
|
|
* This function attempts to scan through @blockSize bytes in @src
|
|
* represented by the sequences in @inSeqs,
|
|
* storing any (partial) sequences.
|
|
*
|
|
* Occasionally, we may want to reduce the actual number of bytes consumed from @src
|
|
* to avoid splitting a match, notably if it would produce a match smaller than MINMATCH.
|
|
*
|
|
* @returns the number of bytes consumed from @src, necessarily <= @blockSize.
|
|
* Otherwise, it may return a ZSTD error if something went wrong.
|
|
*/
|
|
static size_t
|
|
ZSTD_transferSequences_noDelim(ZSTD_CCtx* cctx,
|
|
ZSTD_SequencePosition* seqPos,
|
|
const ZSTD_Sequence* const inSeqs, size_t inSeqsSize,
|
|
const void* src, size_t blockSize,
|
|
ZSTD_ParamSwitch_e externalRepSearch)
|
|
{
|
|
size_t dictSize;
|
|
|
|
if (cctx->cdict) {
|
|
dictSize = cctx->cdict->dictContentSize;
|
|
} else if (cctx->prefixDict.dict) {
|
|
dictSize = cctx->prefixDict.dictSize;
|
|
} else {
|
|
dictSize = 0;
|
|
}
|
|
(void)externalRepSearch;
|
|
return ZSTD_rust_transferSequencesNoDelim(
|
|
&cctx->seqStore, seqPos, inSeqs, inSeqsSize,
|
|
(const BYTE*)src, blockSize,
|
|
cctx->blockState.prevCBlock->rep,
|
|
cctx->blockState.nextCBlock->rep, (U32)dictSize,
|
|
cctx->appliedParams.validateSequences,
|
|
cctx->appliedParams.cParams.minMatch,
|
|
cctx->appliedParams.cParams.windowLog,
|
|
ZSTD_hasExtSeqProd(&cctx->appliedParams));
|
|
}
|
|
|
|
/* @seqPos represents a position within @inSeqs,
|
|
* it is read and updated by this function,
|
|
* once the goal to produce a block of size @blockSize is reached.
|
|
* @return: nb of bytes consumed from @src, necessarily <= @blockSize.
|
|
*/
|
|
typedef size_t (*ZSTD_SequenceCopier_f)(ZSTD_CCtx* cctx,
|
|
ZSTD_SequencePosition* seqPos,
|
|
const ZSTD_Sequence* const inSeqs, size_t inSeqsSize,
|
|
const void* src, size_t blockSize,
|
|
ZSTD_ParamSwitch_e externalRepSearch);
|
|
|
|
static ZSTD_SequenceCopier_f ZSTD_selectSequenceCopier(ZSTD_SequenceFormat_e mode)
|
|
{
|
|
switch (ZSTD_rust_selectSequenceCopier((int)mode)) {
|
|
case ZSTD_sf_explicitBlockDelimiters:
|
|
return ZSTD_transferSequences_wBlockDelim;
|
|
case ZSTD_sf_noBlockDelimiters:
|
|
default:
|
|
return ZSTD_transferSequences_noDelim;
|
|
}
|
|
}
|
|
|
|
static size_t determine_blockSize(ZSTD_SequenceFormat_e mode,
|
|
size_t blockSize, size_t remaining,
|
|
const ZSTD_Sequence* inSeqs, size_t inSeqsSize,
|
|
ZSTD_SequencePosition seqPos)
|
|
{
|
|
DEBUGLOG(6, "determine_blockSize : remainingSize = %zu", remaining);
|
|
assert(mode == ZSTD_sf_noBlockDelimiters || mode == ZSTD_sf_explicitBlockDelimiters);
|
|
return ZSTD_rust_determineBlockSize((int)mode, blockSize, remaining,
|
|
inSeqs, inSeqsSize, seqPos.idx);
|
|
}
|
|
|
|
/* Compress all provided sequences, block-by-block.
|
|
*
|
|
* Returns the cumulative size of all compressed blocks (including their headers),
|
|
* otherwise a ZSTD error.
|
|
*/
|
|
static size_t
|
|
ZSTD_compressSequences_internal(ZSTD_CCtx* cctx,
|
|
void* dst, size_t dstCapacity,
|
|
const ZSTD_Sequence* inSeqs, size_t inSeqsSize,
|
|
const void* src, size_t srcSize)
|
|
{
|
|
size_t cSize = 0;
|
|
size_t remaining = srcSize;
|
|
ZSTD_SequencePosition seqPos = {0, 0, 0};
|
|
|
|
const BYTE* ip = (BYTE const*)src;
|
|
BYTE* op = (BYTE*)dst;
|
|
ZSTD_SequenceCopier_f const sequenceCopier = ZSTD_selectSequenceCopier(cctx->appliedParams.blockDelimiters);
|
|
|
|
DEBUGLOG(4, "ZSTD_compressSequences_internal srcSize: %zu, inSeqsSize: %zu", srcSize, inSeqsSize);
|
|
/* Special case: empty frame */
|
|
if (remaining == 0) {
|
|
U32 const cBlockHeader24 = 1 /* last block */ + (((U32)bt_raw)<<1);
|
|
RETURN_ERROR_IF(dstCapacity<4, dstSize_tooSmall, "No room for empty frame block header");
|
|
MEM_writeLE32(op, cBlockHeader24);
|
|
op += ZSTD_blockHeaderSize;
|
|
dstCapacity -= ZSTD_blockHeaderSize;
|
|
cSize += ZSTD_blockHeaderSize;
|
|
}
|
|
|
|
while (remaining) {
|
|
size_t compressedSeqsSize;
|
|
size_t cBlockSize;
|
|
size_t blockSize = determine_blockSize(cctx->appliedParams.blockDelimiters,
|
|
cctx->blockSizeMax, remaining,
|
|
inSeqs, inSeqsSize, seqPos);
|
|
U32 const lastBlock = (blockSize == remaining);
|
|
FORWARD_IF_ERROR(blockSize, "Error while trying to determine block size");
|
|
assert(blockSize <= remaining);
|
|
ZSTD_resetSeqStore(&cctx->seqStore);
|
|
|
|
blockSize = sequenceCopier(cctx,
|
|
&seqPos, inSeqs, inSeqsSize,
|
|
ip, blockSize,
|
|
cctx->appliedParams.searchForExternalRepcodes);
|
|
FORWARD_IF_ERROR(blockSize, "Bad sequence copy");
|
|
|
|
/* If blocks are too small, emit as a nocompress block */
|
|
/* TODO: See 3090. We reduced MIN_CBLOCK_SIZE from 3 to 2 so to compensate we are adding
|
|
* additional 1. We need to revisit and change this logic to be more consistent */
|
|
if (blockSize < MIN_CBLOCK_SIZE+ZSTD_blockHeaderSize+1+1) {
|
|
cBlockSize = ZSTD_rust_noCompressBlock(op, dstCapacity, ip, blockSize, lastBlock);
|
|
FORWARD_IF_ERROR(cBlockSize, "Nocompress block failed");
|
|
DEBUGLOG(5, "Block too small (%zu): data remains uncompressed: cSize=%zu", blockSize, cBlockSize);
|
|
cSize += cBlockSize;
|
|
ip += blockSize;
|
|
op += cBlockSize;
|
|
remaining -= blockSize;
|
|
dstCapacity -= cBlockSize;
|
|
continue;
|
|
}
|
|
|
|
RETURN_ERROR_IF(dstCapacity < ZSTD_blockHeaderSize, dstSize_tooSmall, "not enough dstCapacity to write a new compressed block");
|
|
compressedSeqsSize = ZSTD_entropyCompressSeqStore(&cctx->seqStore,
|
|
&cctx->blockState.prevCBlock->entropy, &cctx->blockState.nextCBlock->entropy,
|
|
&cctx->appliedParams,
|
|
op + ZSTD_blockHeaderSize /* Leave space for block header */, dstCapacity - ZSTD_blockHeaderSize,
|
|
blockSize,
|
|
cctx->tmpWorkspace, cctx->tmpWkspSize /* statically allocated in resetCCtx */,
|
|
cctx->bmi2);
|
|
FORWARD_IF_ERROR(compressedSeqsSize, "Compressing sequences of block failed");
|
|
DEBUGLOG(5, "Compressed sequences size: %zu", compressedSeqsSize);
|
|
|
|
if (!cctx->isFirstBlock &&
|
|
ZSTD_maybeRLE(&cctx->seqStore) &&
|
|
ZSTD_isRLE(ip, blockSize)) {
|
|
/* Note: don't emit the first block as RLE even if it qualifies because
|
|
* doing so will cause the decoder (cli <= v1.4.3 only) to throw an (invalid) error
|
|
* "should consume all input error."
|
|
*/
|
|
compressedSeqsSize = 1;
|
|
}
|
|
|
|
if (compressedSeqsSize == 0) {
|
|
/* ZSTD_noCompressBlock writes the block header as well */
|
|
cBlockSize = ZSTD_rust_noCompressBlock(op, dstCapacity, ip, blockSize, lastBlock);
|
|
FORWARD_IF_ERROR(cBlockSize, "ZSTD_noCompressBlock failed");
|
|
DEBUGLOG(5, "Writing out nocompress block, size: %zu", cBlockSize);
|
|
} else if (compressedSeqsSize == 1) {
|
|
cBlockSize = ZSTD_rust_rleCompressBlock(op, dstCapacity, *ip, blockSize, lastBlock);
|
|
FORWARD_IF_ERROR(cBlockSize, "ZSTD_rleCompressBlock failed");
|
|
DEBUGLOG(5, "Writing out RLE block, size: %zu", cBlockSize);
|
|
} else {
|
|
/* Error checking and repcodes update */
|
|
ZSTD_blockState_confirmRepcodesAndEntropyTables(&cctx->blockState);
|
|
if (cctx->blockState.prevCBlock->entropy.fse.offcode_repeatMode == FSE_repeat_valid)
|
|
cctx->blockState.prevCBlock->entropy.fse.offcode_repeatMode = FSE_repeat_check;
|
|
|
|
/* Write block header into beginning of block*/
|
|
ZSTD_rust_writeBlockHeader(op, compressedSeqsSize, blockSize, lastBlock);
|
|
cBlockSize = ZSTD_blockHeaderSize + compressedSeqsSize;
|
|
DEBUGLOG(5, "Writing out compressed block, size: %zu", cBlockSize);
|
|
}
|
|
|
|
cSize += cBlockSize;
|
|
|
|
if (lastBlock) {
|
|
break;
|
|
} else {
|
|
ip += blockSize;
|
|
op += cBlockSize;
|
|
remaining -= blockSize;
|
|
dstCapacity -= cBlockSize;
|
|
cctx->isFirstBlock = 0;
|
|
}
|
|
DEBUGLOG(5, "cSize running total: %zu (remaining dstCapacity=%zu)", cSize, dstCapacity);
|
|
}
|
|
|
|
DEBUGLOG(4, "cSize final total: %zu", cSize);
|
|
return cSize;
|
|
}
|
|
|
|
size_t ZSTD_compressSequences(ZSTD_CCtx* cctx,
|
|
void* dst, size_t dstCapacity,
|
|
const ZSTD_Sequence* inSeqs, size_t inSeqsSize,
|
|
const void* src, size_t srcSize)
|
|
{
|
|
BYTE* op = (BYTE*)dst;
|
|
size_t cSize = 0;
|
|
|
|
/* Transparent initialization stage, same as compressStream2() */
|
|
DEBUGLOG(4, "ZSTD_compressSequences (nbSeqs=%zu,dstCapacity=%zu)", inSeqsSize, dstCapacity);
|
|
assert(cctx != NULL);
|
|
FORWARD_IF_ERROR(ZSTD_CCtx_init_compressStream2(cctx, ZSTD_e_end, srcSize), "CCtx initialization failed");
|
|
|
|
/* Begin writing output, starting with frame header */
|
|
{ size_t const frameHeaderSize = ZSTD_writeFrameHeader(op, dstCapacity,
|
|
&cctx->appliedParams, srcSize, cctx->dictID);
|
|
op += frameHeaderSize;
|
|
assert(frameHeaderSize <= dstCapacity);
|
|
dstCapacity -= frameHeaderSize;
|
|
cSize += frameHeaderSize;
|
|
}
|
|
if (cctx->appliedParams.fParams.checksumFlag && srcSize) {
|
|
XXH64_update(&cctx->xxhState, src, srcSize);
|
|
}
|
|
|
|
/* Now generate compressed blocks */
|
|
{ size_t const cBlocksSize = ZSTD_compressSequences_internal(cctx,
|
|
op, dstCapacity,
|
|
inSeqs, inSeqsSize,
|
|
src, srcSize);
|
|
FORWARD_IF_ERROR(cBlocksSize, "Compressing blocks failed!");
|
|
cSize += cBlocksSize;
|
|
assert(cBlocksSize <= dstCapacity);
|
|
dstCapacity -= cBlocksSize;
|
|
}
|
|
|
|
/* Complete with frame checksum, if needed */
|
|
if (cctx->appliedParams.fParams.checksumFlag) {
|
|
U32 const checksum = (U32) XXH64_digest(&cctx->xxhState);
|
|
RETURN_ERROR_IF(dstCapacity<4, dstSize_tooSmall, "no room for checksum");
|
|
DEBUGLOG(4, "Write checksum : %08X", (unsigned)checksum);
|
|
MEM_writeLE32((char*)dst + cSize, checksum);
|
|
cSize += 4;
|
|
}
|
|
|
|
DEBUGLOG(4, "Final compressed size: %zu", cSize);
|
|
return cSize;
|
|
}
|
|
|
|
/* Sequence conversion is implemented in Rust; this wrapper keeps the
|
|
* existing C-side block orchestration and long-length bookkeeping intact. */
|
|
static size_t convertSequences_noRepcodes(
|
|
SeqDef* dstSeqs,
|
|
const ZSTD_Sequence* inSeqs,
|
|
size_t nbSequences)
|
|
{
|
|
return ZSTD_rust_convertSequencesNoRepcodes(dstSeqs, inSeqs, nbSequences);
|
|
}
|
|
|
|
/*
|
|
* Precondition: Sequences must end on an explicit Block Delimiter
|
|
* @return: 0 on success, or an error code.
|
|
* Note: Sequence validation functionality has been disabled (removed).
|
|
* This is helpful to generate a lean main pipeline, improving performance.
|
|
* It may be re-inserted later.
|
|
*/
|
|
size_t ZSTD_convertBlockSequences(ZSTD_CCtx* cctx,
|
|
const ZSTD_Sequence* const inSeqs, size_t nbSequences,
|
|
int repcodeResolution)
|
|
{
|
|
Repcodes_t updatedRepcodes;
|
|
size_t seqNb = 0;
|
|
|
|
DEBUGLOG(5, "ZSTD_convertBlockSequences (nbSequences = %zu)", nbSequences);
|
|
|
|
RETURN_ERROR_IF(nbSequences >= cctx->seqStore.maxNbSeq, externalSequences_invalid,
|
|
"Not enough memory allocated. Try adjusting ZSTD_c_minMatch.");
|
|
|
|
ZSTD_memcpy(updatedRepcodes.rep, cctx->blockState.prevCBlock->rep, sizeof(Repcodes_t));
|
|
|
|
/* check end condition */
|
|
assert(nbSequences >= 1);
|
|
assert(inSeqs[nbSequences-1].matchLength == 0);
|
|
assert(inSeqs[nbSequences-1].offset == 0);
|
|
|
|
/* Convert Sequences from public format to internal format */
|
|
if (!repcodeResolution) {
|
|
size_t const longl = convertSequences_noRepcodes(cctx->seqStore.sequencesStart, inSeqs, nbSequences-1);
|
|
cctx->seqStore.sequences = cctx->seqStore.sequencesStart + nbSequences-1;
|
|
if (longl) {
|
|
DEBUGLOG(5, "long length");
|
|
assert(cctx->seqStore.longLengthType == ZSTD_llt_none);
|
|
if (longl <= nbSequences-1) {
|
|
DEBUGLOG(5, "long match length detected at pos %zu", longl-1);
|
|
cctx->seqStore.longLengthType = ZSTD_llt_matchLength;
|
|
cctx->seqStore.longLengthPos = (U32)(longl-1);
|
|
} else {
|
|
DEBUGLOG(5, "long literals length detected at pos %zu", longl-nbSequences);
|
|
assert(longl <= 2* (nbSequences-1));
|
|
cctx->seqStore.longLengthType = ZSTD_llt_literalLength;
|
|
cctx->seqStore.longLengthPos = (U32)(longl-(nbSequences-1)-1);
|
|
}
|
|
}
|
|
} else {
|
|
for (seqNb = 0; seqNb < nbSequences - 1 ; seqNb++) {
|
|
U32 const litLength = inSeqs[seqNb].litLength;
|
|
U32 const matchLength = inSeqs[seqNb].matchLength;
|
|
U32 const ll0 = (litLength == 0);
|
|
U32 const offBase = ZSTD_finalizeOffBase(inSeqs[seqNb].offset, updatedRepcodes.rep, ll0);
|
|
|
|
DEBUGLOG(6, "Storing sequence: (of: %u, ml: %u, ll: %u)", offBase, matchLength, litLength);
|
|
ZSTD_storeSeqOnly(&cctx->seqStore, litLength, offBase, matchLength);
|
|
ZSTD_updateRep(updatedRepcodes.rep, offBase, ll0);
|
|
}
|
|
}
|
|
|
|
/* If we skipped repcode search while parsing, we need to update repcodes now */
|
|
if (!repcodeResolution && nbSequences > 1) {
|
|
U32* const rep = updatedRepcodes.rep;
|
|
|
|
if (nbSequences >= 4) {
|
|
U32 lastSeqIdx = (U32)nbSequences - 2; /* index of last full sequence */
|
|
rep[2] = inSeqs[lastSeqIdx - 2].offset;
|
|
rep[1] = inSeqs[lastSeqIdx - 1].offset;
|
|
rep[0] = inSeqs[lastSeqIdx].offset;
|
|
} else if (nbSequences == 3) {
|
|
rep[2] = rep[0];
|
|
rep[1] = inSeqs[0].offset;
|
|
rep[0] = inSeqs[1].offset;
|
|
} else {
|
|
assert(nbSequences == 2);
|
|
rep[2] = rep[1];
|
|
rep[1] = rep[0];
|
|
rep[0] = inSeqs[0].offset;
|
|
}
|
|
}
|
|
|
|
ZSTD_memcpy(cctx->blockState.nextCBlock->rep, updatedRepcodes.rep, sizeof(Repcodes_t));
|
|
|
|
return 0;
|
|
}
|
|
|
|
BlockSummary ZSTD_get1BlockSummary(const ZSTD_Sequence* seqs, size_t nbSeqs)
|
|
{
|
|
return ZSTD_rust_get1BlockSummary(seqs, nbSeqs);
|
|
}
|
|
|
|
|
|
static size_t
|
|
ZSTD_compressSequencesAndLiterals_internal(ZSTD_CCtx* cctx,
|
|
void* dst, size_t dstCapacity,
|
|
const ZSTD_Sequence* inSeqs, size_t nbSequences,
|
|
const void* literals, size_t litSize, size_t srcSize)
|
|
{
|
|
size_t remaining = srcSize;
|
|
size_t cSize = 0;
|
|
BYTE* op = (BYTE*)dst;
|
|
int const repcodeResolution = (cctx->appliedParams.searchForExternalRepcodes == ZSTD_ps_enable);
|
|
assert(cctx->appliedParams.searchForExternalRepcodes != ZSTD_ps_auto);
|
|
|
|
DEBUGLOG(4, "ZSTD_compressSequencesAndLiterals_internal: nbSeqs=%zu, litSize=%zu", nbSequences, litSize);
|
|
RETURN_ERROR_IF(nbSequences == 0, externalSequences_invalid, "Requires at least 1 end-of-block");
|
|
|
|
/* Special case: empty frame */
|
|
if ((nbSequences == 1) && (inSeqs[0].litLength == 0)) {
|
|
U32 const cBlockHeader24 = 1 /* last block */ + (((U32)bt_raw)<<1);
|
|
RETURN_ERROR_IF(dstCapacity<3, dstSize_tooSmall, "No room for empty frame block header");
|
|
MEM_writeLE24(op, cBlockHeader24);
|
|
op += ZSTD_blockHeaderSize;
|
|
dstCapacity -= ZSTD_blockHeaderSize;
|
|
cSize += ZSTD_blockHeaderSize;
|
|
}
|
|
|
|
while (nbSequences) {
|
|
size_t compressedSeqsSize, cBlockSize, conversionStatus;
|
|
BlockSummary const block = ZSTD_get1BlockSummary(inSeqs, nbSequences);
|
|
U32 const lastBlock = (block.nbSequences == nbSequences);
|
|
FORWARD_IF_ERROR(block.nbSequences, "Error while trying to determine nb of sequences for a block");
|
|
assert(block.nbSequences <= nbSequences);
|
|
RETURN_ERROR_IF(block.litSize > litSize, externalSequences_invalid, "discrepancy: Sequences require more literals than present in buffer");
|
|
ZSTD_resetSeqStore(&cctx->seqStore);
|
|
|
|
conversionStatus = ZSTD_convertBlockSequences(cctx,
|
|
inSeqs, block.nbSequences,
|
|
repcodeResolution);
|
|
FORWARD_IF_ERROR(conversionStatus, "Bad sequence conversion");
|
|
inSeqs += block.nbSequences;
|
|
nbSequences -= block.nbSequences;
|
|
remaining -= block.blockSize;
|
|
|
|
/* Note: when blockSize is very small, other variant send it uncompressed.
|
|
* Here, we still send the sequences, because we don't have the original source to send it uncompressed.
|
|
* One could imagine in theory reproducing the source from the sequences,
|
|
* but that's complex and costly memory intensive, and goes against the objectives of this variant. */
|
|
|
|
RETURN_ERROR_IF(dstCapacity < ZSTD_blockHeaderSize, dstSize_tooSmall, "not enough dstCapacity to write a new compressed block");
|
|
|
|
compressedSeqsSize = ZSTD_entropyCompressSeqStore_internal(
|
|
op + ZSTD_blockHeaderSize /* Leave space for block header */, dstCapacity - ZSTD_blockHeaderSize,
|
|
literals, block.litSize,
|
|
&cctx->seqStore,
|
|
&cctx->blockState.prevCBlock->entropy, &cctx->blockState.nextCBlock->entropy,
|
|
&cctx->appliedParams,
|
|
cctx->tmpWorkspace, cctx->tmpWkspSize /* statically allocated in resetCCtx */,
|
|
cctx->bmi2);
|
|
FORWARD_IF_ERROR(compressedSeqsSize, "Compressing sequences of block failed");
|
|
/* note: the spec forbids for any compressed block to be larger than maximum block size */
|
|
if (compressedSeqsSize > cctx->blockSizeMax) compressedSeqsSize = 0;
|
|
DEBUGLOG(5, "Compressed sequences size: %zu", compressedSeqsSize);
|
|
litSize -= block.litSize;
|
|
literals = (const char*)literals + block.litSize;
|
|
|
|
/* Note: difficult to check source for RLE block when only Literals are provided,
|
|
* but it could be considered from analyzing the sequence directly */
|
|
|
|
if (compressedSeqsSize == 0) {
|
|
/* Sending uncompressed blocks is out of reach, because the source is not provided.
|
|
* In theory, one could use the sequences to regenerate the source, like a decompressor,
|
|
* but it's complex, and memory hungry, killing the purpose of this variant.
|
|
* Current outcome: generate an error code.
|
|
*/
|
|
RETURN_ERROR(cannotProduce_uncompressedBlock, "ZSTD_compressSequencesAndLiterals cannot generate an uncompressed block");
|
|
} else {
|
|
assert(compressedSeqsSize > 1); /* no RLE */
|
|
/* Error checking and repcodes update */
|
|
ZSTD_blockState_confirmRepcodesAndEntropyTables(&cctx->blockState);
|
|
if (cctx->blockState.prevCBlock->entropy.fse.offcode_repeatMode == FSE_repeat_valid)
|
|
cctx->blockState.prevCBlock->entropy.fse.offcode_repeatMode = FSE_repeat_check;
|
|
|
|
/* Write block header into beginning of block*/
|
|
ZSTD_rust_writeBlockHeader(op, compressedSeqsSize, block.blockSize, lastBlock);
|
|
cBlockSize = ZSTD_blockHeaderSize + compressedSeqsSize;
|
|
DEBUGLOG(5, "Writing out compressed block, size: %zu", cBlockSize);
|
|
}
|
|
|
|
cSize += cBlockSize;
|
|
op += cBlockSize;
|
|
dstCapacity -= cBlockSize;
|
|
cctx->isFirstBlock = 0;
|
|
DEBUGLOG(5, "cSize running total: %zu (remaining dstCapacity=%zu)", cSize, dstCapacity);
|
|
|
|
if (lastBlock) {
|
|
assert(nbSequences == 0);
|
|
break;
|
|
}
|
|
}
|
|
|
|
RETURN_ERROR_IF(litSize != 0, externalSequences_invalid, "literals must be entirely and exactly consumed");
|
|
RETURN_ERROR_IF(remaining != 0, externalSequences_invalid, "Sequences must represent a total of exactly srcSize=%zu", srcSize);
|
|
DEBUGLOG(4, "cSize final total: %zu", cSize);
|
|
return cSize;
|
|
}
|
|
|
|
size_t
|
|
ZSTD_compressSequencesAndLiterals(ZSTD_CCtx* cctx,
|
|
void* dst, size_t dstCapacity,
|
|
const ZSTD_Sequence* inSeqs, size_t inSeqsSize,
|
|
const void* literals, size_t litSize, size_t litCapacity,
|
|
size_t decompressedSize)
|
|
{
|
|
BYTE* op = (BYTE*)dst;
|
|
size_t cSize = 0;
|
|
|
|
/* Transparent initialization stage, same as compressStream2() */
|
|
DEBUGLOG(4, "ZSTD_compressSequencesAndLiterals (dstCapacity=%zu)", dstCapacity);
|
|
assert(cctx != NULL);
|
|
if (litCapacity < litSize) {
|
|
RETURN_ERROR(workSpace_tooSmall, "literals buffer is not large enough: must be at least 8 bytes larger than litSize (risk of read out-of-bound)");
|
|
}
|
|
FORWARD_IF_ERROR(ZSTD_CCtx_init_compressStream2(cctx, ZSTD_e_end, decompressedSize), "CCtx initialization failed");
|
|
|
|
if (cctx->appliedParams.blockDelimiters == ZSTD_sf_noBlockDelimiters) {
|
|
RETURN_ERROR(frameParameter_unsupported, "This mode is only compatible with explicit delimiters");
|
|
}
|
|
if (cctx->appliedParams.validateSequences) {
|
|
RETURN_ERROR(parameter_unsupported, "This mode is not compatible with Sequence validation");
|
|
}
|
|
if (cctx->appliedParams.fParams.checksumFlag) {
|
|
RETURN_ERROR(frameParameter_unsupported, "this mode is not compatible with frame checksum");
|
|
}
|
|
|
|
/* Begin writing output, starting with frame header */
|
|
{ size_t const frameHeaderSize = ZSTD_writeFrameHeader(op, dstCapacity,
|
|
&cctx->appliedParams, decompressedSize, cctx->dictID);
|
|
op += frameHeaderSize;
|
|
assert(frameHeaderSize <= dstCapacity);
|
|
dstCapacity -= frameHeaderSize;
|
|
cSize += frameHeaderSize;
|
|
}
|
|
|
|
/* Now generate compressed blocks */
|
|
{ size_t const cBlocksSize = ZSTD_compressSequencesAndLiterals_internal(cctx,
|
|
op, dstCapacity,
|
|
inSeqs, inSeqsSize,
|
|
literals, litSize, decompressedSize);
|
|
FORWARD_IF_ERROR(cBlocksSize, "Compressing blocks failed!");
|
|
cSize += cBlocksSize;
|
|
assert(cBlocksSize <= dstCapacity);
|
|
dstCapacity -= cBlocksSize;
|
|
}
|
|
|
|
DEBUGLOG(4, "Final compressed size: %zu", cSize);
|
|
return cSize;
|
|
}
|
|
|
|
/*====== Finalize ======*/
|
|
|
|
static ZSTD_inBuffer inBuffer_forEndFlush(const ZSTD_CStream* zcs)
|
|
{
|
|
return ZSTD_rust_inBufferForEndFlush(zcs->appliedParams.inBufferMode,
|
|
zcs->expectedInBuffer.src,
|
|
zcs->expectedInBuffer.size,
|
|
zcs->expectedInBuffer.pos);
|
|
}
|
|
|
|
/*! ZSTD_flushStream() :
|
|
* @return : amount of data remaining to flush */
|
|
size_t ZSTD_flushStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output)
|
|
{
|
|
ZSTD_inBuffer input = inBuffer_forEndFlush(zcs);
|
|
input.size = input.pos; /* do not ingest more input during flush */
|
|
return ZSTD_compressStream2(zcs, output, &input, ZSTD_e_flush);
|
|
}
|
|
|
|
size_t ZSTD_endStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output)
|
|
{
|
|
ZSTD_inBuffer input = inBuffer_forEndFlush(zcs);
|
|
size_t const remainingToFlush = ZSTD_compressStream2(zcs, output, &input, ZSTD_e_end);
|
|
FORWARD_IF_ERROR(remainingToFlush , "ZSTD_compressStream2(,,ZSTD_e_end) failed");
|
|
if (zcs->appliedParams.nbWorkers > 0) return remainingToFlush; /* minimal estimation */
|
|
/* single thread mode : attempt to calculate remaining to flush more precisely */
|
|
{ size_t const toFlush = ZSTD_rust_endStreamRemaining(
|
|
remainingToFlush, zcs->frameEnded,
|
|
zcs->appliedParams.fParams.checksumFlag);
|
|
DEBUGLOG(4, "ZSTD_endStream : remaining to flush : %u", (unsigned)toFlush);
|
|
return toFlush;
|
|
}
|
|
}
|
|
|
|
|
|
/*-===== Pre-defined compression levels =====-*/
|
|
/* The compression-level tables (formerly included from clevels.h) live in
|
|
* rust/src/zstd_compress_params.rs. */
|
|
|
|
int ZSTD_maxCLevel(void) { return ZSTD_rust_params_maxCLevel(); }
|
|
int ZSTD_minCLevel(void) { return ZSTD_rust_params_minCLevel(); }
|
|
int ZSTD_defaultCLevel(void) { return ZSTD_rust_params_defaultCLevel(); }
|
|
|
|
static ZSTD_compressionParameters ZSTD_dedicatedDictSearch_getCParams(int const compressionLevel, size_t const dictSize)
|
|
{
|
|
ZSTD_compressionParameters const cParams =
|
|
ZSTD_getCParams_internal(compressionLevel, 0, dictSize, ZSTD_cpm_createCDict);
|
|
return ZSTD_rust_params_dedicatedDictSearch_getCParams(cParams);
|
|
}
|
|
|
|
/**
|
|
* Reverses the adjustment applied to cparams when enabling dedicated dict
|
|
* search. This is used to recover the params set to be used in the working
|
|
* context. (Otherwise, those tables would also grow.)
|
|
*/
|
|
static void ZSTD_dedicatedDictSearch_revertCParams(
|
|
ZSTD_compressionParameters* cParams) {
|
|
*cParams = ZSTD_rust_params_dedicatedDictSearch_revertCParams(*cParams);
|
|
}
|
|
|
|
/*! ZSTD_getCParams_internal() :
|
|
* @return ZSTD_compressionParameters structure for a selected compression level, srcSize and dictSize.
|
|
* Note: srcSizeHint 0 means 0, use ZSTD_CONTENTSIZE_UNKNOWN for unknown.
|
|
* Use dictSize == 0 for unknown or unused.
|
|
* Note: `mode` controls how we treat the `dictSize`. See docs for `ZSTD_CParamMode_e`. */
|
|
static ZSTD_compressionParameters ZSTD_getCParams_internal(int compressionLevel, unsigned long long srcSizeHint, size_t dictSize, ZSTD_CParamMode_e mode)
|
|
{
|
|
/* Table selection is context-free and lives in Rust; the adjustment step
|
|
* stays behind ZSTD_adjustCParams_internal() so this build's strategy
|
|
* cascade applies. */
|
|
ZSTD_compressionParameters const cp = ZSTD_rust_params_selectCParams(
|
|
compressionLevel, srcSizeHint, dictSize, (int)mode);
|
|
return ZSTD_adjustCParams_internal(cp, srcSizeHint, dictSize, mode, ZSTD_ps_auto);
|
|
}
|
|
|
|
/*! ZSTD_getCParams() :
|
|
* @return ZSTD_compressionParameters structure for a selected compression level, srcSize and dictSize.
|
|
* Size values are optional, provide 0 if not known or unused */
|
|
ZSTD_compressionParameters ZSTD_getCParams(int compressionLevel, unsigned long long srcSizeHint, size_t dictSize)
|
|
{
|
|
if (srcSizeHint == 0) srcSizeHint = ZSTD_CONTENTSIZE_UNKNOWN;
|
|
return ZSTD_getCParams_internal(compressionLevel, srcSizeHint, dictSize, ZSTD_cpm_unknown);
|
|
}
|
|
|
|
/*! ZSTD_getParams() :
|
|
* same idea as ZSTD_getCParams()
|
|
* @return a `ZSTD_parameters` structure (instead of `ZSTD_compressionParameters`).
|
|
* Fields of `ZSTD_frameParameters` are set to default values */
|
|
static ZSTD_parameters
|
|
ZSTD_getParams_internal(int compressionLevel, unsigned long long srcSizeHint, size_t dictSize, ZSTD_CParamMode_e mode)
|
|
{
|
|
ZSTD_compressionParameters const cParams = ZSTD_getCParams_internal(compressionLevel, srcSizeHint, dictSize, mode);
|
|
DEBUGLOG(5, "ZSTD_getParams (cLevel=%i)", compressionLevel);
|
|
return ZSTD_rust_params_makeParams(cParams);
|
|
}
|
|
|
|
/*! ZSTD_getParams() :
|
|
* same idea as ZSTD_getCParams()
|
|
* @return a `ZSTD_parameters` structure (instead of `ZSTD_compressionParameters`).
|
|
* Fields of `ZSTD_frameParameters` are set to default values */
|
|
ZSTD_parameters ZSTD_getParams(int compressionLevel, unsigned long long srcSizeHint, size_t dictSize)
|
|
{
|
|
if (srcSizeHint == 0) srcSizeHint = ZSTD_CONTENTSIZE_UNKNOWN;
|
|
return ZSTD_getParams_internal(compressionLevel, srcSizeHint, dictSize, ZSTD_cpm_unknown);
|
|
}
|
|
|
|
void ZSTD_registerSequenceProducer(
|
|
ZSTD_CCtx* zc,
|
|
void* extSeqProdState,
|
|
ZSTD_sequenceProducer_F extSeqProdFunc)
|
|
{
|
|
assert(zc != NULL);
|
|
ZSTD_CCtxParams_registerSequenceProducer(
|
|
&zc->requestedParams, extSeqProdState, extSeqProdFunc
|
|
);
|
|
}
|