Files
zstd-rs/lib/compress/zstd_compress.c
T
ddidderr bd7fbc81fc feat(compress): move end-of-frame orchestration into Rust
Move ZSTD_compressEnd_public's continuation, epilogue placement, pledged-size validation, trace ordering, and output accounting into the Rust compression projection. Keep CCtx-dependent continuation, checksum/epilogue, and trace behavior behind opaque C callbacks with compile-time ABI layout checks.

Test Plan:
- ulimit -v 41943040; CARGO_BUILD_JOBS=1 cargo test --manifest-path rust/Cargo.toml compress_end_ -- --test-threads=1
- ulimit -v 41943040; make -B -C lib -j1 lib
- ulimit -v 41943040; make -B -C programs -j1 zstd
- ulimit -v 41943040; make -B -C tests -j1 test-cli-tests
2026-07-19 10:52:09 +02:00

5861 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);
typedef size_t (*ZSTD_rust_compress2Reset_f)(void* context);
typedef void (*ZSTD_rust_compress2SetBufferModes_f)(
void* context, int inBufferMode, int outBufferMode);
typedef size_t (*ZSTD_rust_compress2StreamEnd_f)(
void* context, void* dst, size_t dstCapacity, size_t* dstPos,
const void* src, size_t srcSize, size_t* srcPos);
typedef struct {
void* callbackContext;
ZSTD_rust_compress2Reset_f resetSession;
ZSTD_rust_compress2SetBufferModes_f setBufferModes;
ZSTD_rust_compress2StreamEnd_f compressStreamEnd;
int originalInBufferMode;
int originalOutBufferMode;
} ZSTD_rust_compress2State;
size_t ZSTD_rust_compress2(const ZSTD_rust_compress2State* state,
void* dst, size_t dstCapacity,
const void* src, size_t srcSize);
typedef char ZSTD_rust_compress2_state_layout[
(offsetof(ZSTD_rust_compress2State, callbackContext) == 0
&& offsetof(ZSTD_rust_compress2State, resetSession) == sizeof(void*)
&& offsetof(ZSTD_rust_compress2State, setBufferModes)
== 2 * sizeof(void*)
&& offsetof(ZSTD_rust_compress2State, compressStreamEnd)
== 3 * sizeof(void*)
&& offsetof(ZSTD_rust_compress2State, originalInBufferMode)
== 4 * sizeof(void*)
&& offsetof(ZSTD_rust_compress2State, originalOutBufferMode)
== 4 * sizeof(void*) + sizeof(int)
&& sizeof(ZSTD_rust_compress2State)
== 4 * sizeof(void*) + 2 * sizeof(int))
? 1 : -1];
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);
/* The frame-chunk loop is Rust-owned. Its callbacks keep the private
* ZSTD_CCtx and match-state layout in C: Rust only drives the block loop and
* passes this context back to these C-owned state-preparation/dispatch seams. */
typedef void (*ZSTD_rust_frameChunkPrepare_f)(void* context,
const void* src,
size_t blockSize);
typedef size_t (*ZSTD_rust_frameChunkCompress_f)(void* context,
void* dst,
size_t dstCapacity,
const void* src,
size_t srcSize,
U32 lastBlock);
typedef void (*ZSTD_rust_frameChunkChecksum_f)(void* state,
const void* src,
size_t srcSize);
typedef struct {
void* callbackContext;
void* tmpWorkspace;
void* checksumState;
int* isFirstBlock;
ZSTD_compressionStage_e* stage;
size_t tmpWkspSize;
size_t blockSizeMax;
S64 savings;
int preBlockSplitterLevel;
int strategy;
int useTargetCBlockSize;
int blockSplitterEnabled;
int checksumFlag;
int endingStage;
ZSTD_rust_frameChunkPrepare_f prepareBlock;
ZSTD_rust_frameChunkCompress_f compressTarget;
ZSTD_rust_frameChunkCompress_f compressSplit;
ZSTD_rust_frameChunkCompress_f compressInternal;
ZSTD_rust_frameChunkChecksum_f updateChecksum;
} ZSTD_rust_frameChunkState;
size_t ZSTD_rust_compressFrameChunk(
const ZSTD_rust_frameChunkState* state,
void* dst, size_t dstCapacity,
const void* src, size_t srcSize,
U32 lastFrameChunk);
typedef char ZSTD_rust_frame_chunk_state_layout[
(offsetof(ZSTD_rust_frameChunkState, callbackContext) == 0
&& offsetof(ZSTD_rust_frameChunkState, tmpWorkspace) == sizeof(void*)
&& offsetof(ZSTD_rust_frameChunkState, checksumState) == 2 * sizeof(void*)
&& offsetof(ZSTD_rust_frameChunkState, isFirstBlock) == 3 * sizeof(void*)
&& offsetof(ZSTD_rust_frameChunkState, stage) == 4 * sizeof(void*)
&& offsetof(ZSTD_rust_frameChunkState, tmpWkspSize) == 5 * sizeof(void*)
&& offsetof(ZSTD_rust_frameChunkState, blockSizeMax) == 6 * sizeof(void*)
&& offsetof(ZSTD_rust_frameChunkState, savings) == 7 * sizeof(void*)
&& offsetof(ZSTD_rust_frameChunkState, preBlockSplitterLevel)
== 7 * sizeof(void*) + sizeof(S64)
&& offsetof(ZSTD_rust_frameChunkState, strategy)
== 7 * sizeof(void*) + sizeof(S64) + sizeof(int)
&& offsetof(ZSTD_rust_frameChunkState, useTargetCBlockSize)
== 7 * sizeof(void*) + sizeof(S64) + 2 * sizeof(int)
&& offsetof(ZSTD_rust_frameChunkState, blockSplitterEnabled)
== 7 * sizeof(void*) + sizeof(S64) + 3 * sizeof(int)
&& offsetof(ZSTD_rust_frameChunkState, checksumFlag)
== 7 * sizeof(void*) + sizeof(S64) + 4 * sizeof(int)
&& offsetof(ZSTD_rust_frameChunkState, endingStage)
== 7 * sizeof(void*) + sizeof(S64) + 5 * sizeof(int)
&& offsetof(ZSTD_rust_frameChunkState, prepareBlock)
== 7 * sizeof(void*) + sizeof(S64) + 6 * sizeof(int)
&& sizeof(ZSTD_rust_frameChunkState)
== 12 * sizeof(void*) + sizeof(S64) + 6 * sizeof(int))
? 1 : -1];
/* The high-level continue/block entry points are Rust-owned. This projection
* carries only mutable scalar state and C callbacks; the private CCtx and
* match-state layout never crosses the ABI. */
typedef size_t (*ZSTD_rust_compressContinueHeader_f)(void* context,
void* dst,
size_t dstCapacity);
typedef void (*ZSTD_rust_compressContinueWindow_f)(void* context,
const void* src,
size_t srcSize);
typedef size_t (*ZSTD_rust_compressContinueBlock_f)(void* context,
void* dst,
size_t dstCapacity,
const void* src,
size_t srcSize,
U32 lastFrameChunk);
typedef struct {
void* callbackContext;
ZSTD_rust_compressContinueHeader_f writeFrameHeader;
ZSTD_rust_compressContinueWindow_f updateWindow;
ZSTD_rust_compressContinueWindow_f correctOverflow;
ZSTD_rust_compressContinueBlock_f compressFrameChunk;
ZSTD_rust_compressContinueBlock_f compressBlock;
ZSTD_compressionStage_e* stage;
unsigned long long* consumedSrcSize;
unsigned long long* producedCSize;
U64 pledgedSrcSizePlusOne;
size_t blockSizeMax;
int checkBlockSize;
} ZSTD_rust_compressContinueState;
size_t ZSTD_rust_compressContinue(
const ZSTD_rust_compressContinueState* state,
void* dst, size_t dstCapacity,
const void* src, size_t srcSize,
U32 frame, U32 lastFrameChunk);
typedef char ZSTD_rust_compress_continue_state_layout[
(offsetof(ZSTD_rust_compressContinueState, callbackContext) == 0
&& offsetof(ZSTD_rust_compressContinueState, writeFrameHeader) == sizeof(void*)
&& offsetof(ZSTD_rust_compressContinueState, updateWindow) == 2 * sizeof(void*)
&& offsetof(ZSTD_rust_compressContinueState, correctOverflow) == 3 * sizeof(void*)
&& offsetof(ZSTD_rust_compressContinueState, compressFrameChunk) == 4 * sizeof(void*)
&& offsetof(ZSTD_rust_compressContinueState, compressBlock) == 5 * sizeof(void*)
&& offsetof(ZSTD_rust_compressContinueState, stage) == 6 * sizeof(void*)
&& offsetof(ZSTD_rust_compressContinueState, consumedSrcSize) == 7 * sizeof(void*)
&& offsetof(ZSTD_rust_compressContinueState, producedCSize) == 8 * sizeof(void*)
&& offsetof(ZSTD_rust_compressContinueState, pledgedSrcSizePlusOne) == 9 * sizeof(void*)
&& offsetof(ZSTD_rust_compressContinueState, blockSizeMax)
== 9 * sizeof(void*) + sizeof(U64)
&& offsetof(ZSTD_rust_compressContinueState, checkBlockSize)
== 9 * sizeof(void*) + sizeof(U64) + sizeof(size_t)
&& sizeof(ZSTD_rust_compressContinueState)
== (sizeof(void*) == 8 ? 96 : 52))
? 1 : -1];
/* Rust owns the end-of-frame orchestration. The callbacks retain the
* private CCtx-dependent continue, epilogue, and trace operations in C. */
typedef size_t (*ZSTD_rust_compressEndContinue_f)(void* context,
void* dst,
size_t dstCapacity,
const void* src,
size_t srcSize,
U32 frame,
U32 lastFrameChunk);
typedef size_t (*ZSTD_rust_compressEndEpilogue_f)(void* context,
void* dst,
size_t dstCapacity);
typedef void (*ZSTD_rust_compressEndTrace_f)(void* context,
size_t extraCSize);
typedef struct {
void* callbackContext;
ZSTD_rust_compressEndContinue_f compressContinue;
ZSTD_rust_compressEndEpilogue_f writeEpilogue;
ZSTD_rust_compressEndTrace_f trace;
unsigned long long* consumedSrcSize;
U64 pledgedSrcSizePlusOne;
int contentSizeFlag;
} ZSTD_rust_compressEndState;
size_t ZSTD_rust_compressEnd(const ZSTD_rust_compressEndState* state,
void* dst, size_t dstCapacity,
const void* src, size_t srcSize);
typedef char ZSTD_rust_compress_end_state_layout[
(offsetof(ZSTD_rust_compressEndState, callbackContext) == 0
&& offsetof(ZSTD_rust_compressEndState, compressContinue)
== sizeof(void*)
&& offsetof(ZSTD_rust_compressEndState, writeEpilogue)
== 2 * sizeof(void*)
&& offsetof(ZSTD_rust_compressEndState, trace)
== 3 * sizeof(void*)
&& offsetof(ZSTD_rust_compressEndState, consumedSrcSize)
== 4 * sizeof(void*)
&& offsetof(ZSTD_rust_compressEndState, pledgedSrcSizePlusOne)
== 5 * sizeof(void*)
&& offsetof(ZSTD_rust_compressEndState, contentSizeFlag)
== 5 * sizeof(void*) + sizeof(U64)
&& sizeof(ZSTD_rust_compressEndState)
== (sizeof(void*) == 8 ? 56 : 32))
? 1 : -1];
/* Rust owns the single-threaded buffered/stable stream state machine. The
* projection contains only stream bookkeeping and callback slots; operations
* which still need the private CCtx layout remain C callbacks. */
typedef size_t (*ZSTD_rust_compressStreamBlock_f)(
void* context, void* dst, size_t dstCapacity,
const void* src, size_t srcSize);
typedef size_t (*ZSTD_rust_compressStreamReset_f)(void* context);
typedef struct {
void* callbackContext;
int inBufferMode;
int outBufferMode;
ZSTD_cStreamStage* streamStage;
size_t blockSizeMax;
size_t* stableInNotConsumed;
void* inBuff;
size_t inBuffSize;
size_t* inToCompress;
size_t* inBuffPos;
size_t* inBuffTarget;
void* outBuff;
size_t outBuffSize;
size_t* outBuffContentSize;
size_t* outBuffFlushedSize;
U32* frameEnded;
ZSTD_rust_compressStreamBlock_f compressContinue;
ZSTD_rust_compressStreamBlock_f compressEnd;
ZSTD_rust_compressStreamReset_f resetSession;
} ZSTD_rust_compressStreamState;
size_t ZSTD_rust_compressStreamGeneric(
const ZSTD_rust_compressStreamState* state,
ZSTD_outBuffer* output, ZSTD_inBuffer* input, int flushMode);
typedef char ZSTD_rust_compress_stream_state_layout[
(offsetof(ZSTD_rust_compressStreamState, callbackContext) == 0
&& offsetof(ZSTD_rust_compressStreamState, inBufferMode) == sizeof(void*)
&& offsetof(ZSTD_rust_compressStreamState, outBufferMode)
== sizeof(void*) + sizeof(int)
&& offsetof(ZSTD_rust_compressStreamState, streamStage)
== sizeof(void*) + 2 * sizeof(int)
&& offsetof(ZSTD_rust_compressStreamState, blockSizeMax)
== 2 * sizeof(void*) + 2 * sizeof(int)
&& offsetof(ZSTD_rust_compressStreamState, stableInNotConsumed)
== 3 * sizeof(void*) + 2 * sizeof(int)
&& offsetof(ZSTD_rust_compressStreamState, inBuff)
== 4 * sizeof(void*) + 2 * sizeof(int)
&& offsetof(ZSTD_rust_compressStreamState, inBuffSize)
== 5 * sizeof(void*) + 2 * sizeof(int)
&& offsetof(ZSTD_rust_compressStreamState, inToCompress)
== 5 * sizeof(void*) + 2 * sizeof(int) + sizeof(size_t)
&& offsetof(ZSTD_rust_compressStreamState, inBuffPos)
== 6 * sizeof(void*) + 2 * sizeof(int) + sizeof(size_t)
&& offsetof(ZSTD_rust_compressStreamState, inBuffTarget)
== 7 * sizeof(void*) + 2 * sizeof(int) + sizeof(size_t)
&& offsetof(ZSTD_rust_compressStreamState, outBuff)
== 8 * sizeof(void*) + 2 * sizeof(int) + sizeof(size_t)
&& offsetof(ZSTD_rust_compressStreamState, outBuffSize)
== 9 * sizeof(void*) + 2 * sizeof(int) + sizeof(size_t)
&& offsetof(ZSTD_rust_compressStreamState, outBuffContentSize)
== 9 * sizeof(void*) + 2 * sizeof(int) + 2 * sizeof(size_t)
&& offsetof(ZSTD_rust_compressStreamState, outBuffFlushedSize)
== 10 * sizeof(void*) + 2 * sizeof(int) + 2 * sizeof(size_t)
&& offsetof(ZSTD_rust_compressStreamState, frameEnded)
== 11 * sizeof(void*) + 2 * sizeof(int) + 2 * sizeof(size_t)
&& offsetof(ZSTD_rust_compressStreamState, compressContinue)
== 12 * sizeof(void*) + 2 * sizeof(int) + 2 * sizeof(size_t)
&& offsetof(ZSTD_rust_compressStreamState, compressEnd)
== 13 * sizeof(void*) + 2 * sizeof(int) + 2 * sizeof(size_t)
&& offsetof(ZSTD_rust_compressStreamState, resetSession)
== 14 * sizeof(void*) + 2 * sizeof(int) + 2 * sizeof(size_t)
&& sizeof(ZSTD_rust_compressStreamState)
== 15 * sizeof(void*) + 2 * sizeof(int) + 2 * sizeof(size_t))
? 1 : -1];
/* Rust owns only the high-level transparent initialization policy. The
* parameter object, dictionary/context layouts, allocator, trace state, and
* codec entry points stay behind these scalar/opaque callbacks. */
typedef struct {
const void* prefixDict;
size_t prefixDictSize;
int prefixDictContentType;
const void* cdict;
int cdictIsLocal;
int cdictCompressionLevel;
size_t cdictDictContentSize;
} ZSTD_rust_compressStreamInitDictionaryState;
typedef size_t (*ZSTD_rust_compressStreamInitLocalDict_f)(void* context);
typedef void (*ZSTD_rust_compressStreamInitRefreshCDict_f)(
void* context, ZSTD_rust_compressStreamInitDictionaryState* state);
typedef void (*ZSTD_rust_compressStreamInitClearPrefix_f)(void* context);
typedef void (*ZSTD_rust_compressStreamInitAssertDictionaries_f)(
void* context, const void* prefixDict);
typedef void (*ZSTD_rust_compressStreamInitSetLevel_f)(void* params, int level);
typedef void (*ZSTD_rust_compressStreamInitDebug_f)(void* context);
typedef U64 (*ZSTD_rust_compressStreamInitGetPledged_f)(void* context);
typedef void (*ZSTD_rust_compressStreamInitSetPledged_f)(void* context, size_t inSize);
typedef int (*ZSTD_rust_compressStreamInitGetCParamMode_f)(
void* params, const void* cdict, U64 pledgedSrcSize);
typedef void (*ZSTD_rust_compressStreamInitBuildCParams_f)(
void* params, U64 pledgedSrcSize, size_t dictSize, int mode);
typedef void (*ZSTD_rust_compressStreamInitResolveParams_f)(
void* params, int operation);
typedef unsigned (*ZSTD_rust_compressStreamInitGetNbWorkers_f)(void* params);
typedef void (*ZSTD_rust_compressStreamInitSetNbWorkers_f)(
void* params, unsigned nbWorkers);
typedef int (*ZSTD_rust_compressStreamInitHasExtSeqProd_f)(void* params);
typedef void (*ZSTD_rust_compressStreamInitTrace_f)(void* context);
typedef void* (*ZSTD_rust_compressStreamInitGetMTContext_f)(void* context);
typedef size_t (*ZSTD_rust_compressStreamInitCreateMTContext_f)(
void* context, unsigned nbWorkers);
typedef size_t (*ZSTD_rust_compressStreamInitMT_f)(
void* context, void* mtctx,
const ZSTD_rust_compressStreamInitDictionaryState* dictionaries,
void* params, U64 pledgedSrcSize);
typedef void (*ZSTD_rust_compressStreamInitCommitMT_f)(
void* context,
const ZSTD_rust_compressStreamInitDictionaryState* dictionaries,
void* params);
typedef void (*ZSTD_rust_compressStreamInitCheckCParams_f)(void* params);
typedef size_t (*ZSTD_rust_compressStreamInitBegin_f)(
void* context,
const ZSTD_rust_compressStreamInitDictionaryState* dictionaries,
void* params, U64 pledgedSrcSize);
typedef void (*ZSTD_rust_compressStreamInitAssertOrdinary_f)(void* context);
typedef int (*ZSTD_rust_compressStreamInitGetBufferMode_f)(void* context);
typedef size_t (*ZSTD_rust_compressStreamInitGetBlockSize_f)(void* context);
typedef void (*ZSTD_rust_compressStreamInitCommitOrdinary_f)(
void* context, size_t inBuffTarget);
typedef struct {
void* callbackContext;
void* params;
ZSTD_rust_compressStreamInitDictionaryState* dictionaries;
int endOp;
size_t inSize;
int multithreaded;
size_t mtJobSizeMin;
ZSTD_rust_compressStreamInitLocalDict_f initLocalDict;
ZSTD_rust_compressStreamInitRefreshCDict_f refreshCDict;
ZSTD_rust_compressStreamInitClearPrefix_f clearPrefix;
ZSTD_rust_compressStreamInitAssertDictionaries_f assertDictionaries;
ZSTD_rust_compressStreamInitSetLevel_f setCompressionLevel;
ZSTD_rust_compressStreamInitDebug_f debugInit;
ZSTD_rust_compressStreamInitGetPledged_f getPledgedSrcSizePlusOne;
ZSTD_rust_compressStreamInitSetPledged_f setPledgedSrcSize;
ZSTD_rust_compressStreamInitGetCParamMode_f getCParamMode;
ZSTD_rust_compressStreamInitBuildCParams_f buildCParams;
ZSTD_rust_compressStreamInitResolveParams_f resolveParams;
ZSTD_rust_compressStreamInitGetNbWorkers_f getNbWorkers;
ZSTD_rust_compressStreamInitSetNbWorkers_f setNbWorkers;
ZSTD_rust_compressStreamInitHasExtSeqProd_f hasExtSeqProd;
ZSTD_rust_compressStreamInitTrace_f traceBegin;
ZSTD_rust_compressStreamInitGetMTContext_f getMTContext;
ZSTD_rust_compressStreamInitCreateMTContext_f createMTContext;
ZSTD_rust_compressStreamInitMT_f initMT;
ZSTD_rust_compressStreamInitCommitMT_f commitMT;
ZSTD_rust_compressStreamInitCheckCParams_f checkCParams;
ZSTD_rust_compressStreamInitBegin_f compressBegin;
ZSTD_rust_compressStreamInitAssertOrdinary_f assertOrdinary;
ZSTD_rust_compressStreamInitGetBufferMode_f getBufferMode;
ZSTD_rust_compressStreamInitGetBlockSize_f getBlockSize;
ZSTD_rust_compressStreamInitCommitOrdinary_f commitOrdinary;
} ZSTD_rust_compressStreamInitState;
typedef char ZSTD_rust_compress_stream_init_dictionary_layout[
(offsetof(ZSTD_rust_compressStreamInitDictionaryState, prefixDict) == 0
&& offsetof(ZSTD_rust_compressStreamInitDictionaryState, prefixDictSize)
== sizeof(void*)
&& offsetof(ZSTD_rust_compressStreamInitDictionaryState, prefixDictContentType)
== 2 * sizeof(void*)
&& offsetof(ZSTD_rust_compressStreamInitDictionaryState, cdict)
== 3 * sizeof(void*)
&& offsetof(ZSTD_rust_compressStreamInitDictionaryState, cdictIsLocal)
== 4 * sizeof(void*)
&& offsetof(ZSTD_rust_compressStreamInitDictionaryState, cdictCompressionLevel)
== 4 * sizeof(void*) + sizeof(int)
&& offsetof(ZSTD_rust_compressStreamInitDictionaryState, cdictDictContentSize)
== 4 * sizeof(void*) + 2 * sizeof(int)
&& sizeof(ZSTD_rust_compressStreamInitDictionaryState)
== (sizeof(void*) == 8 ? 48 : 28))
? 1 : -1];
typedef char ZSTD_rust_compress_stream_init_state_layout[
(offsetof(ZSTD_rust_compressStreamInitState, callbackContext) == 0
&& offsetof(ZSTD_rust_compressStreamInitState, params) == sizeof(void*)
&& offsetof(ZSTD_rust_compressStreamInitState, dictionaries)
== 2 * sizeof(void*)
&& offsetof(ZSTD_rust_compressStreamInitState, endOp)
== 3 * sizeof(void*)
&& offsetof(ZSTD_rust_compressStreamInitState, inSize)
== 4 * sizeof(void*)
&& offsetof(ZSTD_rust_compressStreamInitState, multithreaded)
== 4 * sizeof(void*) + sizeof(size_t)
&& offsetof(ZSTD_rust_compressStreamInitState, mtJobSizeMin)
== 5 * sizeof(void*) + sizeof(size_t)
&& sizeof(ZSTD_rust_compressStreamInitState)
== (sizeof(void*) == 8 ? 256 : 128))
? 1 : -1];
size_t ZSTD_rust_compressStreamInit(
const ZSTD_rust_compressStreamInitState* state);
/* The target-sized block body only needs this narrow projection of ZSTD_CCtx.
* Matchfinder/window state, sequence-store construction, and outer repeat-mode
* cleanup remain in C. */
typedef struct {
const SeqStore_t* seqStore;
ZSTD_compressedBlockState_t** prevCBlock;
ZSTD_compressedBlockState_t** nextCBlock;
void* tmpWorkspace;
size_t tmpWkspSize;
int strategy;
int disableLiteralCompression;
int bmi2;
U32 windowLog;
size_t targetCBlockSize;
int isFirstBlock;
} ZSTD_rust_targetCBlockSizeState;
size_t ZSTD_rust_compressBlockTargetCBlockSize(
const ZSTD_rust_targetCBlockSizeState* state,
void* dst, size_t dstCapacity,
const void* src, size_t srcSize,
int bss, U32 lastBlock);
size_t ZSTD_rust_compressBlockTargetCBlockSizeAfterBuild(
const ZSTD_rust_targetCBlockSizeState* state,
void* dst, size_t dstCapacity,
const void* src, size_t srcSize,
int bss, U32 lastBlock);
typedef char ZSTD_rust_target_cblock_state_layout[
(offsetof(ZSTD_rust_targetCBlockSizeState, seqStore) == 0
&& offsetof(ZSTD_rust_targetCBlockSizeState, prevCBlock) == sizeof(void*)
&& offsetof(ZSTD_rust_targetCBlockSizeState, nextCBlock) == 2 * sizeof(void*)
&& offsetof(ZSTD_rust_targetCBlockSizeState, tmpWorkspace) == 3 * sizeof(void*)
&& offsetof(ZSTD_rust_targetCBlockSizeState, tmpWkspSize) == 4 * sizeof(void*)
&& offsetof(ZSTD_rust_targetCBlockSizeState, strategy) == 5 * sizeof(void*)
&& offsetof(ZSTD_rust_targetCBlockSizeState, disableLiteralCompression)
== 5 * sizeof(void*) + sizeof(int)
&& offsetof(ZSTD_rust_targetCBlockSizeState, bmi2)
== 5 * sizeof(void*) + 2 * sizeof(int)
&& offsetof(ZSTD_rust_targetCBlockSizeState, windowLog)
== 5 * sizeof(void*) + 3 * sizeof(int)
&& offsetof(ZSTD_rust_targetCBlockSizeState, targetCBlockSize)
== 5 * sizeof(void*) + 4 * sizeof(int)
&& offsetof(ZSTD_rust_targetCBlockSizeState, isFirstBlock)
== 5 * sizeof(void*) + 4 * sizeof(int) + sizeof(size_t)
&& sizeof(ZSTD_rust_targetCBlockSizeState)
== (sizeof(void*) == 8 ? 72 : 44))
? 1 : -1];
/* The post-split partition loop only needs this projection of ZSTD_CCtx.
* Split discovery remains in the surrounding C function; the Rust body owns
* partition accounting, repcode simulation, and per-partition emission. */
typedef struct {
const SeqStore_t* seqStore;
const U32* partitions;
SeqStore_t* nextSeqStore;
SeqStore_t* currSeqStore;
ZSTD_compressedBlockState_t** prevCBlock;
ZSTD_compressedBlockState_t** nextCBlock;
void* tmpWorkspace;
size_t tmpWkspSize;
SeqCollector* seqCollector;
size_t blockSizeMax;
int strategy;
int disableLiteralCompression;
int bmi2;
int isFirstBlock;
} ZSTD_rust_splitBlockState;
size_t ZSTD_rust_compressBlockSplit(
const ZSTD_rust_splitBlockState* state,
void* dst, size_t dstCapacity,
const void* src, size_t blockSize,
U32 lastBlock, size_t numSplits);
size_t ZSTD_rust_compressBlockSplitAfterBuild(
const ZSTD_rust_splitBlockState* state,
void* dst, size_t dstCapacity,
const void* src, size_t blockSize,
U32 lastBlock, size_t numSplits, int bss);
typedef char ZSTD_rust_split_block_state_layout[
(offsetof(ZSTD_rust_splitBlockState, seqStore) == 0
&& offsetof(ZSTD_rust_splitBlockState, partitions) == sizeof(void*)
&& offsetof(ZSTD_rust_splitBlockState, nextSeqStore) == 2 * sizeof(void*)
&& offsetof(ZSTD_rust_splitBlockState, currSeqStore) == 3 * sizeof(void*)
&& offsetof(ZSTD_rust_splitBlockState, prevCBlock) == 4 * sizeof(void*)
&& offsetof(ZSTD_rust_splitBlockState, nextCBlock) == 5 * sizeof(void*)
&& offsetof(ZSTD_rust_splitBlockState, tmpWorkspace) == 6 * sizeof(void*)
&& offsetof(ZSTD_rust_splitBlockState, tmpWkspSize) == 7 * sizeof(void*)
&& offsetof(ZSTD_rust_splitBlockState, seqCollector) == 8 * sizeof(void*)
&& offsetof(ZSTD_rust_splitBlockState, blockSizeMax) == 9 * sizeof(void*)
&& offsetof(ZSTD_rust_splitBlockState, strategy) == 10 * sizeof(void*)
&& offsetof(ZSTD_rust_splitBlockState, disableLiteralCompression)
== 10 * sizeof(void*) + sizeof(int)
&& offsetof(ZSTD_rust_splitBlockState, bmi2)
== 10 * sizeof(void*) + 2 * sizeof(int)
&& offsetof(ZSTD_rust_splitBlockState, isFirstBlock)
== 10 * sizeof(void*) + 3 * sizeof(int)
&& sizeof(ZSTD_rust_splitBlockState)
== 10 * sizeof(void*) + 4 * sizeof(int))
? 1 : -1];
/* The ordinary sequence-block body only needs this projection of ZSTD_CCtx.
* Sequence-store construction and the no-compress fallback remain in C. */
typedef struct {
const SeqStore_t* seqStore;
ZSTD_compressedBlockState_t** prevCBlock;
ZSTD_compressedBlockState_t** nextCBlock;
void* tmpWorkspace;
size_t tmpWkspSize;
SeqCollector* seqCollector;
int strategy;
int disableLiteralCompression;
int bmi2;
int isFirstBlock;
} ZSTD_rust_blockInternalState;
size_t ZSTD_rust_compressBlockInternal(
const ZSTD_rust_blockInternalState* state,
void* dst, size_t dstCapacity,
const void* src, size_t srcSize,
U32 frame);
size_t ZSTD_rust_compressBlockInternalAfterBuild(
const ZSTD_rust_blockInternalState* state,
void* dst, size_t dstCapacity,
const void* src, size_t srcSize,
U32 frame, int bss);
typedef char ZSTD_rust_block_internal_state_layout[
(offsetof(ZSTD_rust_blockInternalState, seqStore) == 0
&& offsetof(ZSTD_rust_blockInternalState, prevCBlock) == sizeof(void*)
&& offsetof(ZSTD_rust_blockInternalState, nextCBlock) == 2 * sizeof(void*)
&& offsetof(ZSTD_rust_blockInternalState, tmpWorkspace) == 3 * sizeof(void*)
&& offsetof(ZSTD_rust_blockInternalState, tmpWkspSize) == 4 * sizeof(void*)
&& offsetof(ZSTD_rust_blockInternalState, seqCollector) == 5 * sizeof(void*)
&& offsetof(ZSTD_rust_blockInternalState, strategy) == 6 * sizeof(void*)
&& offsetof(ZSTD_rust_blockInternalState, disableLiteralCompression)
== 6 * sizeof(void*) + sizeof(int)
&& offsetof(ZSTD_rust_blockInternalState, bmi2)
== 6 * sizeof(void*) + 2 * sizeof(int)
&& offsetof(ZSTD_rust_blockInternalState, isFirstBlock)
== 6 * sizeof(void*) + 3 * sizeof(int)
&& sizeof(ZSTD_rust_blockInternalState)
== 6 * sizeof(void*) + 4 * sizeof(int))
? 1 : -1];
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_getCParamsInternal(
int compressionLevel, U64 srcSizeHint, size_t dictSize, int mode,
U32 exclusionMask);
ZSTD_parameters ZSTD_rust_params_getParamsInternal(
int compressionLevel, U64 srcSizeHint, size_t dictSize, int mode,
U32 exclusionMask);
ZSTD_compressionParameters ZSTD_rust_params_getCParams(
int compressionLevel, U64 srcSizeHint, size_t dictSize,
U32 exclusionMask);
ZSTD_parameters ZSTD_rust_params_getParams(
int compressionLevel, U64 srcSizeHint, size_t dictSize,
U32 exclusionMask);
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_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);
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);
BlockSummary ZSTD_rust_get1BlockSummary(const ZSTD_Sequence* seqs,
size_t nbSeqs);
size_t ZSTD_rust_postProcessSequenceProducerResult(
ZSTD_Sequence* outSeqs, size_t nbExternalSeqs,
size_t outSeqsCapacity, size_t srcSize);
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);
U32 ZSTD_rust_resolveRepcodeToRawOffset(const U32 rep[ZSTD_REP_NUM],
U32 offBase, U32 ll0);
size_t ZSTD_rust_loadCEntropy(ZSTD_compressedBlockState_t* bs, void* workspace,
const void* dict, size_t dictSize);
/* Rust owns dictionary-ingestion policy. The content loader remains a narrow
* callback because it needs configuration-sensitive C-private layouts. */
typedef size_t (*ZSTD_rust_loadDictionaryContent_f)(
void* matchState, void* ldmState, void* workspaceState,
const void* params, const void* src, size_t srcSize,
int dtlm, int tfp);
size_t ZSTD_rust_compressInsertDictionary(
ZSTD_compressedBlockState_t* bs,
void* matchState, void* ldmState, void* workspaceState,
const void* params, const void* dict, size_t dictSize,
int dictContentType, int dtlm, int tfp,
void* workspace, int noDictIDFlag,
ZSTD_rust_loadDictionaryContent_f loadDictionaryContent);
/* CCtx dictionary attachment policy lives in Rust. These callbacks keep
* the private CCtx, local/prefix dictionary layouts, allocator, and CDict
* lifetime operations in C. */
typedef void (*ZSTD_rust_CCtxDictionaryClear_f)(void* context);
typedef size_t (*ZSTD_rust_CCtxAssignLocalDict_f)(
void* context, const void* dict, size_t dictSize,
int dictLoadMethod, int dictContentType);
typedef void (*ZSTD_rust_CCtxAssignCDict_f)(
void* context, const void* cdict);
typedef void (*ZSTD_rust_CCtxAssignPrefixDict_f)(
void* context, const void* prefix, size_t prefixSize,
int dictContentType);
size_t ZSTD_rust_CCtx_loadDictionaryAdvanced(
void* context, int streamStage,
const void* dict, size_t dictSize,
int dictLoadMethod, int dictContentType,
ZSTD_rust_CCtxDictionaryClear_f clearDictionaries,
ZSTD_rust_CCtxAssignLocalDict_f assignLocalDict);
size_t ZSTD_rust_CCtx_refCDict(
void* context, int streamStage, const void* cdict,
ZSTD_rust_CCtxDictionaryClear_f clearDictionaries,
ZSTD_rust_CCtxAssignCDict_f assignCDict);
size_t ZSTD_rust_CCtx_refPrefixAdvanced(
void* context, int streamStage,
const void* prefix, size_t prefixSize, int dictContentType,
ZSTD_rust_CCtxDictionaryClear_f clearDictionaries,
ZSTD_rust_CCtxAssignPrefixDict_f assignPrefixDict);
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_optimalBlockSize(const void* src, size_t srcSize,
size_t blockSizeMax, int splitLevel,
int strategy, S64 savings,
void* workspace, size_t workspaceSize);
/* Sequence-store construction is Rust-owned at the orchestration boundary.
* Matchfinder, LDM, and external sequence-producer operations retain access
* to the private CCtx through these narrow C callbacks. */
typedef void (*ZSTD_rust_buildSeqStoreSkip_f)(void* context, size_t srcSize);
typedef void (*ZSTD_rust_buildSeqStorePrepare_f)(void* context,
const void* src,
size_t srcSize);
typedef size_t (*ZSTD_rust_buildSeqStoreSelect_f)(
void* context, SeqStore_t* seqStore, U32 nextRep[ZSTD_REP_NUM],
const void* src, size_t srcSize, int* seqStoreComplete);
typedef struct {
SeqStore_t* seqStore;
ZSTD_compressedBlockState_t** prevCBlock;
ZSTD_compressedBlockState_t** nextCBlock;
void* callbackContext;
U32 minMatch;
int validateSeqStore;
ZSTD_rust_buildSeqStoreSkip_f skipSmallBlock;
ZSTD_rust_buildSeqStorePrepare_f prepareMatchState;
ZSTD_rust_buildSeqStoreSelect_f selectSequences;
} ZSTD_rust_buildSeqStoreState;
size_t ZSTD_rust_buildSeqStore(const ZSTD_rust_buildSeqStoreState* state,
const void* src, size_t srcSize);
typedef char ZSTD_rust_build_seq_store_state_layout[
(offsetof(ZSTD_rust_buildSeqStoreState, seqStore) == 0
&& offsetof(ZSTD_rust_buildSeqStoreState, prevCBlock) == sizeof(void*)
&& offsetof(ZSTD_rust_buildSeqStoreState, nextCBlock) == 2 * sizeof(void*)
&& offsetof(ZSTD_rust_buildSeqStoreState, callbackContext) == 3 * sizeof(void*)
&& offsetof(ZSTD_rust_buildSeqStoreState, minMatch) == 4 * sizeof(void*)
&& offsetof(ZSTD_rust_buildSeqStoreState, validateSeqStore)
== 4 * sizeof(void*) + sizeof(U32)
&& offsetof(ZSTD_rust_buildSeqStoreState, skipSmallBlock)
== 4 * sizeof(void*) + sizeof(U32) + sizeof(int)
&& offsetof(ZSTD_rust_buildSeqStoreState, prepareMatchState)
== 5 * sizeof(void*) + sizeof(U32) + sizeof(int)
&& offsetof(ZSTD_rust_buildSeqStoreState, selectSequences)
== 6 * sizeof(void*) + sizeof(U32) + sizeof(int)
&& sizeof(ZSTD_rust_buildSeqStoreState)
== 7 * sizeof(void*) + sizeof(U32) + sizeof(int))
? 1 : -1];
/* The sequence-compression loop receives only the state it actually reads or
* updates. In particular, neither ZSTD_CCtx nor a C function pointer crosses
* the Rust ABI. */
typedef struct {
SeqStore_t* seqStore;
ZSTD_compressedBlockState_t** prevCBlock;
ZSTD_compressedBlockState_t** nextCBlock;
void* tmpWorkspace;
size_t tmpWkspSize;
size_t blockSizeMax;
int bmi2;
int blockDelimiters;
int strategy;
int disableLiteralCompression;
int searchForExternalRepcodes;
int validateSequences;
U32 minMatch;
U32 windowLog;
U32 dictSize;
int useSequenceProducer;
int* isFirstBlock;
} ZSTD_rust_sequenceCompressionState;
size_t ZSTD_rust_compressSequencesInternal(
const ZSTD_rust_sequenceCompressionState* state,
void* dst, size_t dstCapacity,
const ZSTD_Sequence* inSeqs, size_t inSeqsSize,
const void* src, size_t srcSize);
typedef char ZSTD_rust_sequence_state_layout[
(offsetof(ZSTD_rust_sequenceCompressionState, seqStore) == 0
&& offsetof(ZSTD_rust_sequenceCompressionState, prevCBlock) == sizeof(void*)
&& offsetof(ZSTD_rust_sequenceCompressionState, nextCBlock) == 2 * sizeof(void*)
&& offsetof(ZSTD_rust_sequenceCompressionState, tmpWorkspace) == 3 * sizeof(void*)
&& offsetof(ZSTD_rust_sequenceCompressionState, tmpWkspSize) == 4 * sizeof(void*)
&& offsetof(ZSTD_rust_sequenceCompressionState, blockSizeMax) == 5 * sizeof(void*)
&& offsetof(ZSTD_rust_sequenceCompressionState, bmi2) == 6 * sizeof(void*)
&& offsetof(ZSTD_rust_sequenceCompressionState, minMatch)
== 6 * sizeof(void*) + 6 * sizeof(int)
&& offsetof(ZSTD_rust_sequenceCompressionState, useSequenceProducer)
== 6 * sizeof(void*) + 3 * sizeof(U32) + 6 * sizeof(int)
&& offsetof(ZSTD_rust_sequenceCompressionState, isFirstBlock)
== 6 * sizeof(void*) + 3 * sizeof(U32) + 7 * sizeof(int)
&& sizeof(ZSTD_rust_sequenceCompressionState)
== offsetof(ZSTD_rust_sequenceCompressionState, isFirstBlock) + sizeof(void*))
? 1 : -1];
/* The external-sequence/literals block loop keeps sequence conversion as a
* C-private callback because it still reads the opaque CCtx. Everything
* else it mutates is passed through this explicit projection. */
typedef size_t (*ZSTD_rust_sequenceLiteralsConvert_f)(
void* context, const ZSTD_Sequence* inSeqs, size_t nbSequences,
int repcodeResolution);
typedef struct {
SeqStore_t* seqStore;
ZSTD_compressedBlockState_t** prevCBlock;
ZSTD_compressedBlockState_t** nextCBlock;
void* tmpWorkspace;
size_t tmpWkspSize;
size_t blockSizeMax;
int bmi2;
int strategy;
int disableLiteralCompression;
int repcodeResolution;
int* isFirstBlock;
void* callbackContext;
ZSTD_rust_sequenceLiteralsConvert_f convertBlockSequences;
} ZSTD_rust_sequenceLiteralsState;
size_t ZSTD_rust_compressSequencesAndLiteralsInternal(
const ZSTD_rust_sequenceLiteralsState* state,
void* dst, size_t dstCapacity,
const ZSTD_Sequence* inSeqs, size_t nbSequences,
const void* literals, size_t litSize, size_t srcSize);
/* Public sequence conversion uses only the sequence store and the two
* compressed-block state slots. Keep the C entry point for existing callers,
* but move its conversion logic behind this explicit Rust projection. */
typedef struct {
SeqStore_t* seqStore;
ZSTD_compressedBlockState_t** prevCBlock;
ZSTD_compressedBlockState_t** nextCBlock;
} ZSTD_rust_convertBlockSequencesState;
size_t ZSTD_rust_convertBlockSequences(
const ZSTD_rust_convertBlockSequencesState* state,
const ZSTD_Sequence* inSeqs, size_t nbSequences,
int repcodeResolution);
typedef char ZSTD_rust_convert_block_sequences_state_layout[
(offsetof(ZSTD_rust_convertBlockSequencesState, seqStore) == 0
&& offsetof(ZSTD_rust_convertBlockSequencesState, prevCBlock) == sizeof(void*)
&& offsetof(ZSTD_rust_convertBlockSequencesState, nextCBlock) == 2 * sizeof(void*)
&& sizeof(ZSTD_rust_convertBlockSequencesState) == 3 * sizeof(void*))
? 1 : -1];
typedef char ZSTD_rust_sequence_literals_state_layout[
(offsetof(ZSTD_rust_sequenceLiteralsState, seqStore) == 0
&& offsetof(ZSTD_rust_sequenceLiteralsState, prevCBlock) == sizeof(void*)
&& offsetof(ZSTD_rust_sequenceLiteralsState, nextCBlock) == 2 * sizeof(void*)
&& offsetof(ZSTD_rust_sequenceLiteralsState, tmpWorkspace) == 3 * sizeof(void*)
&& offsetof(ZSTD_rust_sequenceLiteralsState, tmpWkspSize) == 4 * sizeof(void*)
&& offsetof(ZSTD_rust_sequenceLiteralsState, blockSizeMax) == 5 * sizeof(void*)
&& offsetof(ZSTD_rust_sequenceLiteralsState, bmi2) == 6 * sizeof(void*)
&& offsetof(ZSTD_rust_sequenceLiteralsState, strategy) == 6 * sizeof(void*) + sizeof(int)
&& offsetof(ZSTD_rust_sequenceLiteralsState, disableLiteralCompression) == 6 * sizeof(void*) + 2 * sizeof(int)
&& offsetof(ZSTD_rust_sequenceLiteralsState, repcodeResolution) == 6 * sizeof(void*) + 3 * sizeof(int)
&& offsetof(ZSTD_rust_sequenceLiteralsState, isFirstBlock)
== 6 * sizeof(void*) + 4 * sizeof(int)
&& offsetof(ZSTD_rust_sequenceLiteralsState, callbackContext)
== 6 * sizeof(void*) + 4 * sizeof(int) + sizeof(void*)
&& offsetof(ZSTD_rust_sequenceLiteralsState, convertBlockSequences)
== 6 * sizeof(void*) + 4 * sizeof(int) + 2 * sizeof(void*)
&& sizeof(ZSTD_rust_sequenceLiteralsState)
== 6 * sizeof(void*) + 4 * sizeof(int) + 3 * sizeof(void*))
? 1 : -1];
/* The public sequence APIs keep their CCtx initialization, frame header, and
* checksum state in C, but Rust owns the ordering and output accounting. The
* two block-loop projections above are populated by the initialization
* callback after the private CCtx has been initialized. */
typedef struct ZSTD_rust_sequenceApiState_s ZSTD_rust_sequenceApiState;
typedef size_t (*ZSTD_rust_sequenceApiInit_f)(
void* context, size_t pledgedSrcSize,
ZSTD_rust_sequenceApiState* state);
typedef size_t (*ZSTD_rust_sequenceApiWriteFrameHeader_f)(
void* context, void* dst, size_t dstCapacity, size_t pledgedSrcSize);
typedef void (*ZSTD_rust_sequenceApiUpdateChecksum_f)(
void* context, const void* src, size_t srcSize);
typedef U32 (*ZSTD_rust_sequenceApiDigestChecksum_f)(void* context);
typedef void (*ZSTD_rust_sequenceApiWriteChecksum_f)(
void* context, void* dst, U32 checksum);
struct ZSTD_rust_sequenceApiState_s {
void* callbackContext;
ZSTD_rust_sequenceCompressionState* sequenceState;
ZSTD_rust_sequenceLiteralsState* sequenceLiteralsState;
ZSTD_rust_sequenceApiInit_f init;
ZSTD_rust_sequenceApiWriteFrameHeader_f writeFrameHeader;
ZSTD_rust_sequenceApiUpdateChecksum_f updateChecksum;
ZSTD_rust_sequenceApiDigestChecksum_f digestChecksum;
ZSTD_rust_sequenceApiWriteChecksum_f writeChecksum;
int checksumFlag;
int blockDelimiters;
int validateSequences;
};
size_t ZSTD_rust_compressSequences(
ZSTD_rust_sequenceApiState* state,
void* dst, size_t dstCapacity,
const ZSTD_Sequence* inSeqs, size_t inSeqsSize,
const void* src, size_t srcSize);
size_t ZSTD_rust_compressSequencesAndLiterals(
ZSTD_rust_sequenceApiState* state,
void* dst, size_t dstCapacity,
const ZSTD_Sequence* inSeqs, size_t inSeqsSize,
const void* literals, size_t litSize, size_t litCapacity,
size_t decompressedSize);
typedef char ZSTD_rust_sequence_api_state_layout[
(offsetof(ZSTD_rust_sequenceApiState, callbackContext) == 0
&& offsetof(ZSTD_rust_sequenceApiState, sequenceState)
== sizeof(void*)
&& offsetof(ZSTD_rust_sequenceApiState, sequenceLiteralsState)
== 2 * sizeof(void*)
&& offsetof(ZSTD_rust_sequenceApiState, init)
== 3 * sizeof(void*)
&& offsetof(ZSTD_rust_sequenceApiState, writeFrameHeader)
== 4 * sizeof(void*)
&& offsetof(ZSTD_rust_sequenceApiState, updateChecksum)
== 5 * sizeof(void*)
&& offsetof(ZSTD_rust_sequenceApiState, digestChecksum)
== 6 * sizeof(void*)
&& offsetof(ZSTD_rust_sequenceApiState, writeChecksum)
== 7 * sizeof(void*)
&& offsetof(ZSTD_rust_sequenceApiState, checksumFlag)
== 8 * sizeof(void*)
&& offsetof(ZSTD_rust_sequenceApiState, blockDelimiters)
== 8 * sizeof(void*) + sizeof(int)
&& offsetof(ZSTD_rust_sequenceApiState, validateSequences)
== 8 * sizeof(void*) + 2 * sizeof(int)
&& sizeof(ZSTD_rust_sequenceApiState)
== (sizeof(void*) == 8 ? 80 : 44))
? 1 : -1];
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 void ZSTD_clearAllDicts_callback(void* context)
{
ZSTD_clearAllDicts((ZSTD_CCtx*)context);
}
static size_t ZSTD_assignLocalDict_callback(
void* context, const void* dict, size_t dictSize,
int dictLoadMethod, int dictContentType)
{
ZSTD_CCtx* const cctx = (ZSTD_CCtx*)context;
ZSTD_localDict* const localDict = &cctx->localDict;
if (dictLoadMethod == ZSTD_dlm_byRef) {
localDict->dict = dict;
} else {
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);
localDict->dictBuffer = dictBuffer; /* owned ptr to free */
localDict->dict = dictBuffer; /* read-only reference */
}
localDict->dictSize = dictSize;
localDict->dictContentType = (ZSTD_dictContentType_e)dictContentType;
return 0;
}
static void ZSTD_assignCDict_callback(void* context, const void* cdict)
{
((ZSTD_CCtx*)context)->cdict = (const ZSTD_CDict*)cdict;
}
static void ZSTD_assignPrefixDict_callback(
void* context, const void* prefix, size_t prefixSize,
int dictContentType)
{
ZSTD_CCtx* const cctx = (ZSTD_CCtx*)context;
if (prefix != NULL && prefixSize > 0) {
cctx->prefixDict.dict = prefix;
cctx->prefixDict.dictSize = prefixSize;
cctx->prefixDict.dictContentType = (ZSTD_dictContentType_e)dictContentType;
}
}
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, &params->cParams);
cctxParams->postBlockSplitter = ZSTD_resolveBlockSplitterMode(cctxParams->postBlockSplitter, &params->cParams);
cctxParams->ldmParams.enableLdm = ZSTD_resolveEnableLdm(cctxParams->ldmParams.enableLdm, &params->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 ZSTD_rust_CCtx_loadDictionaryAdvanced(
cctx, (int)cctx->streamStage,
dict, dictSize, (int)dictLoadMethod, (int)dictContentType,
ZSTD_clearAllDicts_callback, ZSTD_assignLocalDict_callback);
}
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 ZSTD_rust_CCtx_refCDict(
cctx, (int)cctx->streamStage, cdict,
ZSTD_clearAllDicts_callback, ZSTD_assignCDict_callback);
}
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 ZSTD_rust_CCtx_refPrefixAdvanced(
cctx, (int)cctx->streamStage,
prefix, prefixSize, (int)dictContentType,
ZSTD_clearAllDicts_callback, ZSTD_assignPrefixDict_callback);
}
/*! 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, &params->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, &params->cParams);
return ZSTD_estimateCCtxSize_usingCCtxParams_internal(
&cParams, &params->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, &params->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(
&params->cParams, &params->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,
&params->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, &params, 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, &params, 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, &params, 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);
}
/* 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;
}
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);
}
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 void ZSTD_rust_buildSeqStore_skipSmallBlock(void* context, size_t srcSize)
{
ZSTD_CCtx* const zc = (ZSTD_CCtx*)context;
if (zc->appliedParams.cParams.strategy >= ZSTD_btopt) {
ZSTD_ldm_skipRawSeqStoreBytes(&zc->externSeqStore, srcSize);
} else {
ZSTD_ldm_skipSequences(&zc->externSeqStore, srcSize,
zc->appliedParams.cParams.minMatch);
}
}
static void ZSTD_rust_buildSeqStore_prepareMatchState(void* context,
const void* src,
size_t srcSize)
{
ZSTD_CCtx* const zc = (ZSTD_CCtx*)context;
ZSTD_MatchState_t* const ms = &zc->blockState.matchState;
DEBUGLOG(5, "ZSTD_buildSeqStore (srcSize=%zu)", srcSize);
(void)srcSize;
/* Assert that we have correctly flushed the ctx params into the ms's copy. */
ZSTD_assertEqualCParams(zc->appliedParams.cParams, ms->cParams);
/* 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));
if (curr > ms->nextToUpdate + 384)
ms->nextToUpdate = curr - MIN(192, (U32)(curr - ms->nextToUpdate - 384));
}
}
static size_t ZSTD_rust_buildSeqStore_selectSequences(
void* context, SeqStore_t* seqStore, U32 nextRep[ZSTD_REP_NUM],
const void* src, size_t srcSize, int* seqStoreComplete)
{
ZSTD_CCtx* const zc = (ZSTD_CCtx*)context;
ZSTD_MatchState_t* const ms = &zc->blockState.matchState;
ZSTD_dictMode_e const dictMode = ZSTD_matchState_dictMode(ms);
size_t lastLLSize;
*seqStoreComplete = 0;
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. */
RETURN_ERROR_IF(
ZSTD_hasExtSeqProd(&zc->appliedParams),
parameter_combination_unsupported,
"Long-distance matching with external sequence producer enabled is not currently supported."
);
lastLLSize = ZSTD_ldm_blockCompress(
&zc->externSeqStore, ms, seqStore, nextRep,
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. */
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;
FORWARD_IF_ERROR(ZSTD_ldm_generateSequences(
&zc->ldmState, &ldmSeqStore, &zc->appliedParams.ldmParams,
src, srcSize), "");
lastLLSize = ZSTD_ldm_blockCompress(
&ldmSeqStore, ms, seqStore, nextRep,
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,
zc->appliedParams.compressionLevel, windowSize);
size_t const nbPostProcessedSeqs = ZSTD_postProcessSequenceProducerResult(
zc->extSeqBuf, nbExternalSeqs,
zc->extSeqBufCapacity, srcSize);
/* Return early if there is no error, since the delimiter already
* carries the block's final 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;
*seqStoreComplete = 1;
DEBUGLOG(5, "Copied %lu sequences from external sequence producer to internal seqStore.",
(unsigned long)nbExternalSeqs);
return 0;
}
if (!zc->appliedParams.enableMatchFinderFallback)
return nbPostProcessedSeqs;
{ 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, seqStore, nextRep, src, srcSize);
}
}
} else {
ZSTD_BlockCompressor_f const blockCompressor = ZSTD_selectBlockCompressor(
zc->appliedParams.cParams.strategy,
zc->appliedParams.useRowMatchFinder, dictMode);
ms->ldmSeqStore = NULL;
lastLLSize = blockCompressor(ms, seqStore, nextRep, src, srcSize);
}
return lastLLSize;
}
static void ZSTD_initBuildSeqStoreState(
ZSTD_CCtx* zc, ZSTD_rust_buildSeqStoreState* state)
{
state->seqStore = &zc->seqStore;
state->prevCBlock = &zc->blockState.prevCBlock;
state->nextCBlock = &zc->blockState.nextCBlock;
state->callbackContext = zc;
state->minMatch = zc->appliedParams.cParams.minMatch;
#if DEBUGLEVEL >= 1
state->validateSeqStore = 1;
#else
state->validateSeqStore = 0;
#endif
state->skipSmallBlock = ZSTD_rust_buildSeqStore_skipSmallBlock;
state->prepareMatchState = ZSTD_rust_buildSeqStore_prepareMatchState;
state->selectSequences = ZSTD_rust_buildSeqStore_selectSequences;
}
static size_t ZSTD_buildSeqStore(ZSTD_CCtx* zc, const void* src, size_t srcSize)
{
ZSTD_rust_buildSeqStoreState state;
ZSTD_initBuildSeqStoreState(zc, &state);
return ZSTD_rust_buildSeqStore(&state, src, srcSize);
}
/* 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. */
/** 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);
}
/* 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, int bss)
{
ZSTD_rust_splitBlockState state;
U32* const partitions = zc->blockSplitCtx.partitions; /* splits plus the terminal boundary */
size_t numSplits = 0;
if (bss == ZSTDbss_compress) {
numSplits = ZSTD_deriveBlockSplits(zc, partitions, nbSeq);
FORWARD_IF_ERROR(numSplits, "Deriving block splits failed!");
}
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);
state.seqStore = &zc->seqStore;
state.partitions = partitions;
state.nextSeqStore = &zc->blockSplitCtx.nextSeqStore;
state.currSeqStore = &zc->blockSplitCtx.currSeqStore;
state.prevCBlock = &zc->blockState.prevCBlock;
state.nextCBlock = &zc->blockState.nextCBlock;
state.tmpWorkspace = zc->tmpWorkspace;
state.tmpWkspSize = zc->tmpWkspSize;
state.seqCollector = &zc->seqCollector;
state.blockSizeMax = zc->blockSizeMax;
state.strategy = (int)zc->appliedParams.cParams.strategy;
state.disableLiteralCompression = ZSTD_literalsCompressionIsDisabled(&zc->appliedParams);
state.bmi2 = zc->bmi2;
state.isFirstBlock = zc->isFirstBlock;
return ZSTD_rust_compressBlockSplitAfterBuild(
&state, dst, dstCapacity, src, blockSize, lastBlock,
numSplits, bss);
}
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;
size_t const bss = ZSTD_buildSeqStore(zc, src, srcSize);
DEBUGLOG(5, "ZSTD_compressBlock_splitBlock");
assert(zc->appliedParams.postBlockSplitter == ZSTD_ps_enable);
FORWARD_IF_ERROR(bss, "ZSTD_buildSeqStore failed");
nbSeq = (U32)(zc->seqStore.sequences - zc->seqStore.sequencesStart);
cSize = ZSTD_compressBlock_splitBlock_internal(
zc, dst, dstCapacity, src, srcSize, lastBlock, nbSeq, (int)bss);
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)
{
ZSTD_rust_blockInternalState state;
size_t const bss = ZSTD_buildSeqStore(zc, src, srcSize);
DEBUGLOG(5, "ZSTD_compressBlock_internal (dstCapacity=%u, dictLimit=%u, nextToUpdate=%u)",
(unsigned)dstCapacity, (unsigned)zc->blockState.matchState.window.dictLimit,
(unsigned)zc->blockState.matchState.nextToUpdate);
FORWARD_IF_ERROR(bss, "ZSTD_buildSeqStore failed");
state.seqStore = &zc->seqStore;
state.prevCBlock = &zc->blockState.prevCBlock;
state.nextCBlock = &zc->blockState.nextCBlock;
state.tmpWorkspace = zc->tmpWorkspace;
state.tmpWkspSize = zc->tmpWkspSize;
state.seqCollector = &zc->seqCollector;
state.strategy = (int)zc->appliedParams.cParams.strategy;
state.disableLiteralCompression = ZSTD_literalsCompressionIsDisabled(&zc->appliedParams);
state.bmi2 = zc->bmi2;
state.isFirstBlock = zc->isFirstBlock;
return ZSTD_rust_compressBlockInternalAfterBuild(
&state, dst, dstCapacity, src, srcSize, frame, (int)bss);
}
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;
size_t const 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");
{ ZSTD_rust_targetCBlockSizeState state;
state.seqStore = &zc->seqStore;
state.prevCBlock = &zc->blockState.prevCBlock;
state.nextCBlock = &zc->blockState.nextCBlock;
state.tmpWorkspace = zc->tmpWorkspace;
state.tmpWkspSize = zc->tmpWkspSize;
state.strategy = (int)zc->appliedParams.cParams.strategy;
state.disableLiteralCompression = ZSTD_literalsCompressionIsDisabled(&zc->appliedParams);
state.bmi2 = zc->bmi2;
state.windowLog = zc->appliedParams.cParams.windowLog;
state.targetCBlockSize = zc->appliedParams.targetCBlockSize;
state.isFirstBlock = zc->isFirstBlock;
cSize = ZSTD_rust_compressBlockTargetCBlockSizeAfterBuild(
&state, dst, dstCapacity, src, srcSize, (int)bss, lastBlock);
}
FORWARD_IF_ERROR(cSize, "ZSTD_compressBlock_targetCBlockSize_body failed");
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 void ZSTD_rust_frameChunk_prepareBlock(void* context,
const void* src,
size_t blockSize)
{
ZSTD_CCtx* const cctx = (ZSTD_CCtx*)context;
ZSTD_MatchState_t* const ms = &cctx->blockState.matchState;
U32 const maxDist = (U32)1 << cctx->appliedParams.cParams.windowLog;
ZSTD_overflowCorrectIfNeeded(
ms, &cctx->workspace, &cctx->appliedParams,
src, (const BYTE*)src + blockSize);
ZSTD_checkDictValidity(
&ms->window, (const BYTE*)src + blockSize, maxDist,
&ms->loadedDictEnd, &ms->dictMatchState);
ZSTD_window_enforceMaxDist(
&ms->window, src, 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;
}
static size_t ZSTD_rust_frameChunk_compressTarget(
void* context, void* dst, size_t dstCapacity,
const void* src, size_t srcSize, U32 lastBlock)
{
return ZSTD_compressBlock_targetCBlockSize(
(ZSTD_CCtx*)context, dst, dstCapacity, src, srcSize, lastBlock);
}
static size_t ZSTD_rust_frameChunk_compressSplit(
void* context, void* dst, size_t dstCapacity,
const void* src, size_t srcSize, U32 lastBlock)
{
return ZSTD_compressBlock_splitBlock(
(ZSTD_CCtx*)context, dst, dstCapacity, src, srcSize, lastBlock);
}
static size_t ZSTD_rust_frameChunk_compressInternal(
void* context, void* dst, size_t dstCapacity,
const void* src, size_t srcSize, U32 lastBlock)
{
(void)lastBlock;
return ZSTD_compressBlock_internal(
(ZSTD_CCtx*)context, dst, dstCapacity, src, srcSize,
1 /* frame */);
}
static void ZSTD_rust_frameChunk_updateChecksum(
void* state, const void* src, size_t srcSize)
{
(void)XXH64_update((XXH64_state_t*)state, src, srcSize);
}
/*! 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)
{
ZSTD_rust_frameChunkState state;
state.callbackContext = cctx;
state.tmpWorkspace = cctx->tmpWorkspace;
state.checksumState = &cctx->xxhState;
state.isFirstBlock = &cctx->isFirstBlock;
state.stage = &cctx->stage;
state.tmpWkspSize = cctx->tmpWkspSize;
state.blockSizeMax = cctx->blockSizeMax;
state.savings = (S64)cctx->consumedSrcSize - (S64)cctx->producedCSize;
state.preBlockSplitterLevel = cctx->appliedParams.preBlockSplitter_level;
state.strategy = (int)cctx->appliedParams.cParams.strategy;
state.useTargetCBlockSize = ZSTD_useTargetCBlockSize(&cctx->appliedParams);
state.blockSplitterEnabled = ZSTD_blockSplitterEnabled(&cctx->appliedParams);
state.checksumFlag = cctx->appliedParams.fParams.checksumFlag;
state.endingStage = (int)ZSTDcs_ending;
state.prepareBlock = ZSTD_rust_frameChunk_prepareBlock;
state.compressTarget = ZSTD_rust_frameChunk_compressTarget;
state.compressSplit = ZSTD_rust_frameChunk_compressSplit;
state.compressInternal = ZSTD_rust_frameChunk_compressInternal;
state.updateChecksum = ZSTD_rust_frameChunk_updateChecksum;
return ZSTD_rust_compressFrameChunk(
&state, dst, dstCapacity, src, srcSize, lastFrameChunk);
}
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);
}
static size_t ZSTD_rust_compressContinue_writeFrameHeader(
void* context, void* dst, size_t dstCapacity)
{
ZSTD_CCtx* const cctx = (ZSTD_CCtx*)context;
return ZSTD_writeFrameHeader(
dst, dstCapacity, &cctx->appliedParams,
cctx->pledgedSrcSizePlusOne - 1, cctx->dictID);
}
static void ZSTD_rust_compressContinue_updateWindow(
void* context, const void* src, size_t srcSize)
{
ZSTD_CCtx* const cctx = (ZSTD_CCtx*)context;
ZSTD_MatchState_t* const ms = &cctx->blockState.matchState;
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);
}
}
static void ZSTD_rust_compressContinue_correctOverflow(
void* context, const void* src, size_t srcSize)
{
ZSTD_CCtx* const cctx = (ZSTD_CCtx*)context;
ZSTD_MatchState_t* const ms = &cctx->blockState.matchState;
ZSTD_overflowCorrectIfNeeded(
ms, &cctx->workspace, &cctx->appliedParams,
src, (const BYTE*)src + srcSize);
}
static size_t ZSTD_rust_compressContinue_frameChunk(
void* context, void* dst, size_t dstCapacity,
const void* src, size_t srcSize, U32 lastFrameChunk)
{
return ZSTD_compress_frameChunk(
(ZSTD_CCtx*)context, dst, dstCapacity, src, srcSize,
lastFrameChunk);
}
static size_t ZSTD_rust_compressContinue_block(
void* context, void* dst, size_t dstCapacity,
const void* src, size_t srcSize, U32 lastFrameChunk)
{
(void)lastFrameChunk;
return ZSTD_compressBlock_internal(
(ZSTD_CCtx*)context, dst, dstCapacity, src, srcSize,
0 /* frame */);
}
static size_t ZSTD_compressContinue_dispatch(
ZSTD_CCtx* cctx, void* dst, size_t dstCapacity,
const void* src, size_t srcSize,
U32 frame, U32 lastFrameChunk,
size_t blockSizeMax, int checkBlockSize)
{
ZSTD_rust_compressContinueState state;
state.callbackContext = cctx;
state.writeFrameHeader = ZSTD_rust_compressContinue_writeFrameHeader;
state.updateWindow = ZSTD_rust_compressContinue_updateWindow;
state.correctOverflow = ZSTD_rust_compressContinue_correctOverflow;
state.compressFrameChunk = ZSTD_rust_compressContinue_frameChunk;
state.compressBlock = ZSTD_rust_compressContinue_block;
state.stage = &cctx->stage;
state.consumedSrcSize = &cctx->consumedSrcSize;
state.producedCSize = &cctx->producedCSize;
state.pledgedSrcSizePlusOne = cctx->pledgedSrcSizePlusOne;
state.blockSizeMax = blockSizeMax;
state.checkBlockSize = checkBlockSize;
return ZSTD_rust_compressContinue(
&state, dst, dstCapacity, src, srcSize, frame, lastFrameChunk);
}
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;
}
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_dispatch(
cctx, dst, dstCapacity, src, srcSize,
1 /* frame mode */, 0 /* last chunk */,
cctx->blockSizeMax, 0 /* block size already selected */);
}
/* 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);
return ZSTD_compressContinue_dispatch(
cctx, dst, dstCapacity, src, srcSize,
0 /* block mode */, 0 /* last chunk */,
ZSTD_getBlockSize_deprecated(cctx), 1 /* validate block size */);
}
/* 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(&params->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, &params->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);
}
/* Keep the match-state/content operation private to C. Rust passes only
* opaque pointers here after it has selected the dictionary path. */
static size_t ZSTD_loadDictionaryContent_callback(
void* matchState, void* ldmState, void* workspaceState,
const void* params, const void* src, size_t srcSize,
int dtlm, int tfp)
{
return ZSTD_loadDictionaryContent(
(ZSTD_MatchState_t*)matchState,
(ldmState_t*)ldmState,
(ZSTD_cwksp*)workspaceState,
(const ZSTD_CCtx_params*)params,
src, srcSize,
(ZSTD_dictTableLoadMethod_e)dtlm,
(ZSTD_tableFillPurpose_e)tfp);
}
/** 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)
{
int const noDictIDFlag = (params != NULL && dict != NULL && dictSize >= 8)
? params->fParams.noDictIDFlag
: 0;
DEBUGLOG(4, "ZSTD_compress_insertDictionary (dictSize=%u)", (U32)dictSize);
return ZSTD_rust_compressInsertDictionary(
bs, ms, ls, ws, params, dict, dictSize,
(int)dictContentType, (int)dtlm, (int)tfp,
workspace, noDictIDFlag,
ZSTD_loadDictionaryContent_callback);
}
#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, &params, 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, &params, (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
}
static size_t ZSTD_rust_compressEnd_continue(
void* context, void* dst, size_t dstCapacity,
const void* src, size_t srcSize, U32 frame, U32 lastFrameChunk)
{
ZSTD_CCtx* const cctx = (ZSTD_CCtx*)context;
return ZSTD_compressContinue_dispatch(
cctx, dst, dstCapacity, src, srcSize,
frame, lastFrameChunk, cctx->blockSizeMax,
0 /* block size already selected */);
}
static size_t ZSTD_rust_compressEnd_writeEpilogue(
void* context, void* dst, size_t dstCapacity)
{
return ZSTD_writeEpilogue((ZSTD_CCtx*)context, dst, dstCapacity);
}
static void ZSTD_rust_compressEnd_trace(void* context, size_t extraCSize)
{
ZSTD_CCtx_trace((ZSTD_CCtx*)context, extraCSize);
}
size_t ZSTD_compressEnd_public(ZSTD_CCtx* cctx,
void* dst, size_t dstCapacity,
const void* src, size_t srcSize)
{
ZSTD_rust_compressEndState state;
state.callbackContext = cctx;
state.compressContinue = ZSTD_rust_compressEnd_continue;
state.writeEpilogue = ZSTD_rust_compressEnd_writeEpilogue;
state.trace = ZSTD_rust_compressEnd_trace;
state.consumedSrcSize = &cctx->consumedSrcSize;
state.pledgedSrcSizePlusOne = cctx->pledgedSrcSizePlusOne;
state.contentSizeFlag = cctx->appliedParams.fParams.contentSizeFlag;
return ZSTD_rust_compressEnd(
&state, dst, dstCapacity, src, srcSize);
}
/* 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, &params, 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, &params, (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. */
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(
&params, &zstdParams,
compressionLevel == 0 ? ZSTD_CLEVEL_DEFAULT : compressionLevel);
FORWARD_IF_ERROR(ZSTD_compressBegin_internal(
cctx, NULL, 0, ZSTD_dct_auto, ZSTD_dtlm_fast, NULL,
&params, 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,
&params.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,
&params, 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(&params, 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, &params, 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, &params);
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_rust_compressStream_continue(
void* context, void* dst, size_t dstCapacity,
const void* src, size_t srcSize)
{
return ZSTD_compressContinue_public(
(ZSTD_CCtx*)context, dst, dstCapacity, src, srcSize);
}
static size_t ZSTD_rust_compressStream_end(
void* context, void* dst, size_t dstCapacity,
const void* src, size_t srcSize)
{
return ZSTD_compressEnd_public(
(ZSTD_CCtx*)context, dst, dstCapacity, src, srcSize);
}
static size_t ZSTD_rust_compressStream_reset(void* context)
{
return ZSTD_CCtx_reset((ZSTD_CCtx*)context, ZSTD_reset_session_only);
}
static size_t ZSTD_compressStream_generic(ZSTD_CStream* zcs,
ZSTD_outBuffer* output,
ZSTD_inBuffer* input,
ZSTD_EndDirective const flushMode)
{
ZSTD_rust_compressStreamState state;
state.callbackContext = zcs;
state.inBufferMode = (int)zcs->appliedParams.inBufferMode;
state.outBufferMode = (int)zcs->appliedParams.outBufferMode;
state.streamStage = &zcs->streamStage;
state.blockSizeMax = zcs->blockSizeMax;
state.stableInNotConsumed = &zcs->stableIn_notConsumed;
state.inBuff = zcs->inBuff;
state.inBuffSize = zcs->inBuffSize;
state.inToCompress = &zcs->inToCompress;
state.inBuffPos = &zcs->inBuffPos;
state.inBuffTarget = &zcs->inBuffTarget;
state.outBuff = zcs->outBuff;
state.outBuffSize = zcs->outBuffSize;
state.outBuffContentSize = &zcs->outBuffContentSize;
state.outBuffFlushedSize = &zcs->outBuffFlushedSize;
state.frameEnded = &zcs->frameEnded;
state.compressContinue = ZSTD_rust_compressStream_continue;
state.compressEnd = ZSTD_rust_compressStream_end;
state.resetSession = ZSTD_rust_compressStream_reset;
return ZSTD_rust_compressStreamGeneric(
&state, output, input, (int)flushMode);
}
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.
*/
enum {
ZSTD_RUST_INIT_RESOLVE_BLOCK_SPLITTER = 0,
ZSTD_RUST_INIT_RESOLVE_LDM = 1,
ZSTD_RUST_INIT_RESOLVE_ROW_MATCH_FINDER = 2,
ZSTD_RUST_INIT_RESOLVE_VALIDATE_SEQUENCES = 3,
ZSTD_RUST_INIT_RESOLVE_MAX_BLOCK_SIZE = 4,
ZSTD_RUST_INIT_RESOLVE_EXTERNAL_REPCODE_SEARCH = 5
};
static size_t ZSTD_rust_compressStreamInit_localDict(void* context)
{
return ZSTD_initLocalDict((ZSTD_CCtx*)context);
}
static void ZSTD_rust_compressStreamInit_refreshCDict(
void* context, ZSTD_rust_compressStreamInitDictionaryState* state)
{
ZSTD_CCtx const* const cctx = (ZSTD_CCtx const*)context;
state->cdict = cctx->cdict;
state->cdictIsLocal = cctx->localDict.cdict != NULL;
state->cdictCompressionLevel = cctx->cdict ? cctx->cdict->compressionLevel : 0;
state->cdictDictContentSize = cctx->cdict ? cctx->cdict->dictContentSize : 0;
}
static void ZSTD_rust_compressStreamInit_clearPrefix(void* context)
{
ZSTD_CCtx* const cctx = (ZSTD_CCtx*)context;
ZSTD_memset(&cctx->prefixDict, 0, sizeof(cctx->prefixDict));
}
static void ZSTD_rust_compressStreamInit_assertDictionaries(
void* context, const void* prefixDict)
{
ZSTD_CCtx const* const cctx = (ZSTD_CCtx const*)context;
(void)cctx;
(void)prefixDict;
assert(prefixDict == NULL || cctx->cdict == NULL);
}
static void ZSTD_rust_compressStreamInit_setLevel(void* params, int level)
{
((ZSTD_CCtx_params*)params)->compressionLevel = level;
}
static void ZSTD_rust_compressStreamInit_debug(void* context)
{
(void)context;
DEBUGLOG(4, "ZSTD_CCtx_init_compressStream2 : transparent init stage");
}
static U64 ZSTD_rust_compressStreamInit_getPledged(void* context)
{
return ((ZSTD_CCtx const*)context)->pledgedSrcSizePlusOne;
}
static void ZSTD_rust_compressStreamInit_setPledged(void* context, size_t inSize)
{
((ZSTD_CCtx*)context)->pledgedSrcSizePlusOne = inSize + 1;
}
static int ZSTD_rust_compressStreamInit_getCParamMode(
void* params, const void* cdict, U64 pledgedSrcSize)
{
return (int)ZSTD_getCParamMode(
(const ZSTD_CDict*)cdict, (const ZSTD_CCtx_params*)params, pledgedSrcSize);
}
static void ZSTD_rust_compressStreamInit_buildCParams(
void* params, U64 pledgedSrcSize, size_t dictSize, int mode)
{
ZSTD_CCtx_params* const cctxParams = (ZSTD_CCtx_params*)params;
cctxParams->cParams = ZSTD_getCParamsFromCCtxParams(
cctxParams, pledgedSrcSize, dictSize, (ZSTD_CParamMode_e)mode);
}
static void ZSTD_rust_compressStreamInit_resolveParams(void* params, int operation)
{
ZSTD_CCtx_params* const cctxParams = (ZSTD_CCtx_params*)params;
switch (operation) {
case ZSTD_RUST_INIT_RESOLVE_BLOCK_SPLITTER:
cctxParams->postBlockSplitter = ZSTD_resolveBlockSplitterMode(
cctxParams->postBlockSplitter, &cctxParams->cParams);
break;
case ZSTD_RUST_INIT_RESOLVE_LDM:
cctxParams->ldmParams.enableLdm = ZSTD_resolveEnableLdm(
cctxParams->ldmParams.enableLdm, &cctxParams->cParams);
break;
case ZSTD_RUST_INIT_RESOLVE_ROW_MATCH_FINDER:
cctxParams->useRowMatchFinder = ZSTD_resolveRowMatchFinderMode(
cctxParams->useRowMatchFinder, &cctxParams->cParams);
break;
case ZSTD_RUST_INIT_RESOLVE_VALIDATE_SEQUENCES:
cctxParams->validateSequences = ZSTD_resolveExternalSequenceValidation(
cctxParams->validateSequences);
break;
case ZSTD_RUST_INIT_RESOLVE_MAX_BLOCK_SIZE:
cctxParams->maxBlockSize = ZSTD_resolveMaxBlockSize(cctxParams->maxBlockSize);
break;
case ZSTD_RUST_INIT_RESOLVE_EXTERNAL_REPCODE_SEARCH:
cctxParams->searchForExternalRepcodes = ZSTD_resolveExternalRepcodeSearch(
cctxParams->searchForExternalRepcodes, cctxParams->compressionLevel);
break;
default:
assert(0);
break;
}
}
static unsigned ZSTD_rust_compressStreamInit_getNbWorkers(void* params)
{
return ((ZSTD_CCtx_params const*)params)->nbWorkers;
}
static void ZSTD_rust_compressStreamInit_setNbWorkers(void* params, unsigned nbWorkers)
{
((ZSTD_CCtx_params*)params)->nbWorkers = nbWorkers;
}
static int ZSTD_rust_compressStreamInit_hasExtSeqProd(void* params)
{
return ZSTD_hasExtSeqProd((ZSTD_CCtx_params const*)params);
}
static void ZSTD_rust_compressStreamInit_trace(void* context)
{
#if ZSTD_TRACE
ZSTD_CCtx* const cctx = (ZSTD_CCtx*)context;
cctx->traceCtx = (ZSTD_trace_compress_begin != NULL)
? ZSTD_trace_compress_begin(cctx) : 0;
#else
(void)context;
#endif
}
static void* ZSTD_rust_compressStreamInit_getMTContext(void* context)
{
#ifdef ZSTD_MULTITHREAD
return ((ZSTD_CCtx*)context)->mtctx;
#else
(void)context;
return NULL;
#endif
}
static size_t ZSTD_rust_compressStreamInit_createMTContext(
void* context, unsigned nbWorkers)
{
#ifdef ZSTD_MULTITHREAD
ZSTD_CCtx* const cctx = (ZSTD_CCtx*)context;
DEBUGLOG(4, "ZSTD_compressStream2: creating new mtctx for nbWorkers=%u", nbWorkers);
cctx->mtctx = ZSTDMT_createCCtx_advanced(
(U32)nbWorkers, cctx->customMem, cctx->pool);
RETURN_ERROR_IF(cctx->mtctx == NULL, memory_allocation, "NULL pointer!");
return 0;
#else
(void)context;
(void)nbWorkers;
return ERROR(memory_allocation);
#endif
}
static size_t ZSTD_rust_compressStreamInit_mt(
void* context, void* mtctx,
const ZSTD_rust_compressStreamInitDictionaryState* dictionaries,
void* params, U64 pledgedSrcSize)
{
#ifdef ZSTD_MULTITHREAD
(void)context;
DEBUGLOG(4, "call ZSTDMT_initCStream_internal as nbWorkers=%u",
((ZSTD_CCtx_params const*)params)->nbWorkers);
return ZSTDMT_initCStream_internal(
(ZSTDMT_CCtx*)mtctx,
dictionaries->prefixDict, dictionaries->prefixDictSize,
(ZSTD_dictContentType_e)dictionaries->prefixDictContentType,
(const ZSTD_CDict*)dictionaries->cdict,
*(const ZSTD_CCtx_params*)params, pledgedSrcSize);
#else
(void)context;
(void)mtctx;
(void)dictionaries;
(void)params;
(void)pledgedSrcSize;
return ERROR(memory_allocation);
#endif
}
static void ZSTD_rust_compressStreamInit_commitMT(
void* context,
const ZSTD_rust_compressStreamInitDictionaryState* dictionaries,
void* params)
{
#ifdef ZSTD_MULTITHREAD
ZSTD_CCtx* const cctx = (ZSTD_CCtx*)context;
cctx->dictID = cctx->cdict ? cctx->cdict->dictID : 0;
cctx->dictContentSize = cctx->cdict
? cctx->cdict->dictContentSize : dictionaries->prefixDictSize;
cctx->consumedSrcSize = 0;
cctx->producedCSize = 0;
cctx->streamStage = zcss_load;
cctx->appliedParams = *(const ZSTD_CCtx_params*)params;
#else
(void)context;
(void)dictionaries;
(void)params;
#endif
}
static void ZSTD_rust_compressStreamInit_checkCParams(void* params)
{
(void)params;
assert(!ZSTD_isError(ZSTD_checkCParams(
((ZSTD_CCtx_params const*)params)->cParams)));
}
static size_t ZSTD_rust_compressStreamInit_begin(
void* context,
const ZSTD_rust_compressStreamInitDictionaryState* dictionaries,
void* params, U64 pledgedSrcSize)
{
ZSTD_CCtx* const cctx = (ZSTD_CCtx*)context;
return ZSTD_compressBegin_internal(
cctx,
dictionaries->prefixDict, dictionaries->prefixDictSize,
(ZSTD_dictContentType_e)dictionaries->prefixDictContentType, ZSTD_dtlm_fast,
(const ZSTD_CDict*)dictionaries->cdict,
(const ZSTD_CCtx_params*)params, pledgedSrcSize, ZSTDb_buffered);
}
static void ZSTD_rust_compressStreamInit_assertOrdinary(void* context)
{
(void)context;
assert(((ZSTD_CCtx const*)context)->appliedParams.nbWorkers == 0);
}
static int ZSTD_rust_compressStreamInit_getBufferMode(void* context)
{
return (int)((ZSTD_CCtx const*)context)->appliedParams.inBufferMode;
}
static size_t ZSTD_rust_compressStreamInit_getBlockSize(void* context)
{
return ((ZSTD_CCtx const*)context)->blockSizeMax;
}
static void ZSTD_rust_compressStreamInit_commitOrdinary(
void* context, size_t inBuffTarget)
{
ZSTD_CCtx* const cctx = (ZSTD_CCtx*)context;
cctx->inToCompress = 0;
cctx->inBuffPos = 0;
cctx->inBuffTarget = inBuffTarget;
cctx->outBuffContentSize = cctx->outBuffFlushedSize = 0;
cctx->streamStage = zcss_load;
cctx->frameEnded = 0;
}
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;
ZSTD_rust_compressStreamInitDictionaryState dictionaries = {
prefixDict.dict,
prefixDict.dictSize,
(int)prefixDict.dictContentType,
NULL,
0,
0,
0
};
ZSTD_rust_compressStreamInitState state = {
cctx,
&params,
&dictionaries,
(int)endOp,
inSize,
#ifdef ZSTD_MULTITHREAD
1,
ZSTDMT_JOBSIZE_MIN,
#else
0,
0,
#endif
ZSTD_rust_compressStreamInit_localDict,
ZSTD_rust_compressStreamInit_refreshCDict,
ZSTD_rust_compressStreamInit_clearPrefix,
ZSTD_rust_compressStreamInit_assertDictionaries,
ZSTD_rust_compressStreamInit_setLevel,
ZSTD_rust_compressStreamInit_debug,
ZSTD_rust_compressStreamInit_getPledged,
ZSTD_rust_compressStreamInit_setPledged,
ZSTD_rust_compressStreamInit_getCParamMode,
ZSTD_rust_compressStreamInit_buildCParams,
ZSTD_rust_compressStreamInit_resolveParams,
ZSTD_rust_compressStreamInit_getNbWorkers,
ZSTD_rust_compressStreamInit_setNbWorkers,
ZSTD_rust_compressStreamInit_hasExtSeqProd,
ZSTD_rust_compressStreamInit_trace,
ZSTD_rust_compressStreamInit_getMTContext,
ZSTD_rust_compressStreamInit_createMTContext,
ZSTD_rust_compressStreamInit_mt,
ZSTD_rust_compressStreamInit_commitMT,
ZSTD_rust_compressStreamInit_checkCParams,
ZSTD_rust_compressStreamInit_begin,
ZSTD_rust_compressStreamInit_assertOrdinary,
ZSTD_rust_compressStreamInit_getBufferMode,
ZSTD_rust_compressStreamInit_getBlockSize,
ZSTD_rust_compressStreamInit_commitOrdinary
};
return ZSTD_rust_compressStreamInit(&state);
}
/* @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;
}
}
static size_t ZSTD_rust_compress2_resetSession(void* context)
{
return ZSTD_CCtx_reset((ZSTD_CCtx*)context, ZSTD_reset_session_only);
}
static void ZSTD_rust_compress2_setBufferModes(
void* context, int inBufferMode, int outBufferMode)
{
ZSTD_CCtx* const cctx = (ZSTD_CCtx*)context;
cctx->requestedParams.inBufferMode = (ZSTD_bufferMode_e)inBufferMode;
cctx->requestedParams.outBufferMode = (ZSTD_bufferMode_e)outBufferMode;
}
static size_t ZSTD_rust_compress2_streamEnd(
void* context, void* dst, size_t dstCapacity, size_t* dstPos,
const void* src, size_t srcSize, size_t* srcPos)
{
return ZSTD_compressStream2_simpleArgs(
(ZSTD_CCtx*)context, dst, dstCapacity, dstPos,
src, srcSize, srcPos, ZSTD_e_end);
}
size_t ZSTD_compress2_c(ZSTD_CCtx* cctx,
void* dst, size_t dstCapacity,
const void* src, size_t srcSize)
{
ZSTD_rust_compress2State state;
state.callbackContext = cctx;
state.resetSession = ZSTD_rust_compress2_resetSession;
state.setBufferModes = ZSTD_rust_compress2_setBufferModes;
state.compressStreamEnd = ZSTD_rust_compress2_streamEnd;
state.originalInBufferMode = (int)cctx->requestedParams.inBufferMode;
state.originalOutBufferMode = (int)cctx->requestedParams.outBufferMode;
DEBUGLOG(4, "ZSTD_compress2 (srcSize=%u)", (unsigned)srcSize);
return ZSTD_rust_compress2(&state, dst, dstCapacity, src, srcSize);
}
/* The explicit-delimiter adapter is also used by the external sequence
* producer path. Keep that C-context-facing call site separate from the
* Rust-owned compressSequences block loop. */
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));
}
/* The public symbol remains C-facing for fullbench and the sequence API, but
* the sequence-store conversion itself is Rust-owned. */
size_t ZSTD_convertBlockSequences(ZSTD_CCtx* cctx,
const ZSTD_Sequence* const inSeqs, size_t nbSequences,
int repcodeResolution)
{
ZSTD_rust_convertBlockSequencesState state;
DEBUGLOG(5, "ZSTD_convertBlockSequences (nbSequences = %zu)", nbSequences);
state.seqStore = &cctx->seqStore;
state.prevCBlock = &cctx->blockState.prevCBlock;
state.nextCBlock = &cctx->blockState.nextCBlock;
return ZSTD_rust_convertBlockSequences(
&state, inSeqs, nbSequences, repcodeResolution);
}
static size_t ZSTD_convertBlockSequencesForRust(
void* context, const ZSTD_Sequence* inSeqs, size_t nbSequences,
int repcodeResolution)
{
return ZSTD_convertBlockSequences((ZSTD_CCtx*)context, inSeqs, nbSequences,
repcodeResolution);
}
static void ZSTD_rust_sequenceApi_prepareStates(
ZSTD_CCtx* cctx,
ZSTD_rust_sequenceCompressionState* sequenceState,
ZSTD_rust_sequenceLiteralsState* sequenceLiteralsState)
{
U32 dictSize;
if (cctx->cdict) {
dictSize = (U32)cctx->cdict->dictContentSize;
} else if (cctx->prefixDict.dict) {
dictSize = (U32)cctx->prefixDict.dictSize;
} else {
dictSize = 0;
}
sequenceState->seqStore = &cctx->seqStore;
sequenceState->prevCBlock = &cctx->blockState.prevCBlock;
sequenceState->nextCBlock = &cctx->blockState.nextCBlock;
sequenceState->tmpWorkspace = cctx->tmpWorkspace;
sequenceState->tmpWkspSize = cctx->tmpWkspSize;
sequenceState->blockSizeMax = cctx->blockSizeMax;
sequenceState->bmi2 = cctx->bmi2;
sequenceState->blockDelimiters = (int)cctx->appliedParams.blockDelimiters;
sequenceState->strategy = (int)cctx->appliedParams.cParams.strategy;
sequenceState->disableLiteralCompression =
ZSTD_literalsCompressionIsDisabled(&cctx->appliedParams);
sequenceState->searchForExternalRepcodes =
(int)cctx->appliedParams.searchForExternalRepcodes;
sequenceState->validateSequences = cctx->appliedParams.validateSequences;
sequenceState->minMatch = cctx->appliedParams.cParams.minMatch;
sequenceState->windowLog = cctx->appliedParams.cParams.windowLog;
sequenceState->dictSize = dictSize;
sequenceState->useSequenceProducer = ZSTD_hasExtSeqProd(&cctx->appliedParams);
sequenceState->isFirstBlock = &cctx->isFirstBlock;
assert(cctx->appliedParams.searchForExternalRepcodes != ZSTD_ps_auto);
sequenceLiteralsState->seqStore = &cctx->seqStore;
sequenceLiteralsState->prevCBlock = &cctx->blockState.prevCBlock;
sequenceLiteralsState->nextCBlock = &cctx->blockState.nextCBlock;
sequenceLiteralsState->tmpWorkspace = cctx->tmpWorkspace;
sequenceLiteralsState->tmpWkspSize = cctx->tmpWkspSize;
sequenceLiteralsState->blockSizeMax = cctx->blockSizeMax;
sequenceLiteralsState->bmi2 = cctx->bmi2;
sequenceLiteralsState->strategy = (int)cctx->appliedParams.cParams.strategy;
sequenceLiteralsState->disableLiteralCompression =
ZSTD_literalsCompressionIsDisabled(&cctx->appliedParams);
sequenceLiteralsState->repcodeResolution =
(cctx->appliedParams.searchForExternalRepcodes == ZSTD_ps_enable);
sequenceLiteralsState->isFirstBlock = &cctx->isFirstBlock;
sequenceLiteralsState->callbackContext = cctx;
sequenceLiteralsState->convertBlockSequences =
ZSTD_convertBlockSequencesForRust;
}
static size_t ZSTD_rust_sequenceApi_init(
void* context, size_t pledgedSrcSize,
ZSTD_rust_sequenceApiState* state)
{
ZSTD_CCtx* const cctx = (ZSTD_CCtx*)context;
size_t initResult;
if (cctx == NULL || state == NULL
|| state->sequenceState == NULL
|| state->sequenceLiteralsState == NULL) {
return ERROR(GENERIC);
}
initResult = ZSTD_CCtx_init_compressStream2(
cctx, ZSTD_e_end, pledgedSrcSize);
if (ERR_isError(initResult)) {
return initResult;
}
ZSTD_rust_sequenceApi_prepareStates(
cctx, state->sequenceState, state->sequenceLiteralsState);
state->checksumFlag = cctx->appliedParams.fParams.checksumFlag;
state->blockDelimiters = (int)cctx->appliedParams.blockDelimiters;
state->validateSequences = cctx->appliedParams.validateSequences;
return 0;
}
static size_t ZSTD_rust_sequenceApi_writeFrameHeader(
void* context, void* dst, size_t dstCapacity, size_t pledgedSrcSize)
{
ZSTD_CCtx const* const cctx = (ZSTD_CCtx const*)context;
return ZSTD_writeFrameHeader(dst, dstCapacity, &cctx->appliedParams,
pledgedSrcSize, cctx->dictID);
}
static void ZSTD_rust_sequenceApi_updateChecksum(
void* context, const void* src, size_t srcSize)
{
ZSTD_CCtx* const cctx = (ZSTD_CCtx*)context;
(void)XXH64_update(&cctx->xxhState, src, srcSize);
}
static U32 ZSTD_rust_sequenceApi_digestChecksum(void* context)
{
ZSTD_CCtx const* const cctx = (ZSTD_CCtx const*)context;
return (U32)XXH64_digest(&cctx->xxhState);
}
static void ZSTD_rust_sequenceApi_writeChecksum(
void* context, void* dst, U32 checksum)
{
(void)context;
DEBUGLOG(4, "Write checksum : %08X", (unsigned)checksum);
MEM_writeLE32((char*)dst, checksum);
}
static void ZSTD_rust_sequenceApi_initState(
ZSTD_rust_sequenceApiState* state,
ZSTD_CCtx* cctx,
ZSTD_rust_sequenceCompressionState* sequenceState,
ZSTD_rust_sequenceLiteralsState* sequenceLiteralsState)
{
state->callbackContext = cctx;
state->sequenceState = sequenceState;
state->sequenceLiteralsState = sequenceLiteralsState;
state->init = ZSTD_rust_sequenceApi_init;
state->writeFrameHeader = ZSTD_rust_sequenceApi_writeFrameHeader;
state->updateChecksum = ZSTD_rust_sequenceApi_updateChecksum;
state->digestChecksum = ZSTD_rust_sequenceApi_digestChecksum;
state->writeChecksum = ZSTD_rust_sequenceApi_writeChecksum;
state->checksumFlag = 0;
state->blockDelimiters = 0;
state->validateSequences = 0;
}
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)
{
ZSTD_rust_sequenceCompressionState sequenceState;
ZSTD_rust_sequenceLiteralsState sequenceLiteralsState;
ZSTD_rust_sequenceApiState state;
DEBUGLOG(4, "ZSTD_compressSequences (nbSeqs=%zu,dstCapacity=%zu)",
inSeqsSize, dstCapacity);
assert(cctx != NULL);
ZSTD_rust_sequenceApi_initState(
&state, cctx, &sequenceState, &sequenceLiteralsState);
return ZSTD_rust_compressSequences(
&state, dst, dstCapacity, inSeqs, inSeqsSize, src, srcSize);
}
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)
{
ZSTD_rust_sequenceCompressionState sequenceState;
ZSTD_rust_sequenceLiteralsState sequenceLiteralsState;
ZSTD_rust_sequenceApiState state;
DEBUGLOG(4, "ZSTD_compressSequencesAndLiterals (dstCapacity=%zu)",
dstCapacity);
assert(cctx != NULL);
ZSTD_rust_sequenceApi_initState(
&state, cctx, &sequenceState, &sequenceLiteralsState);
return ZSTD_rust_compressSequencesAndLiterals(
&state, dst, dstCapacity, inSeqs, inSeqsSize, literals, litSize,
litCapacity, decompressedSize);
}
BlockSummary ZSTD_get1BlockSummary(const ZSTD_Sequence* seqs, size_t nbSeqs)
{
return ZSTD_rust_get1BlockSummary(seqs, nbSeqs);
}
/*====== 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)
{
return ZSTD_rust_params_getCParamsInternal(
compressionLevel, srcSizeHint, dictSize, (int)mode,
ZSTD_getCParamsExclusionMask());
}
/*! 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)
{
return ZSTD_rust_params_getCParams(
compressionLevel, srcSizeHint, dictSize,
ZSTD_getCParamsExclusionMask());
}
/*! 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)
{
DEBUGLOG(5, "ZSTD_getParams (cLevel=%i)", compressionLevel);
return ZSTD_rust_params_getParamsInternal(
compressionLevel, srcSizeHint, dictSize, (int)mode,
ZSTD_getCParamsExclusionMask());
}
/*! 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)
{
return ZSTD_rust_params_getParams(
compressionLevel, srcSizeHint, dictSize,
ZSTD_getCParamsExclusionMask());
}
void ZSTD_registerSequenceProducer(
ZSTD_CCtx* zc,
void* extSeqProdState,
ZSTD_sequenceProducer_F extSeqProdFunc)
{
assert(zc != NULL);
ZSTD_CCtxParams_registerSequenceProducer(
&zc->requestedParams, extSeqProdState, extSeqProdFunc
);
}