Improve: Enable zstd multi-thread compression for client

This commit is contained in:
yuanyuanxiang
2025-08-13 04:54:33 +08:00
parent 303b5ef824
commit e779fb0b51
8 changed files with 95 additions and 7 deletions

42
common/zstd_wrapper.c Normal file
View File

@@ -0,0 +1,42 @@
#include "zstd_wrapper.h"
#include <string.h> // memcpy
size_t zstd_compress_auto(
ZSTD_CCtx* cctx,
void* dst, size_t dstCapacity,
const void* src, size_t srcSize,
size_t threshold
) {
// 检查输入有效性
if (!cctx || !dst || !src) {
return ZSTD_error_GENERIC;
}
// --- 小数据或库不支持多线程 → 退回到单线程 ZSTD_compress2 ---
if (srcSize < threshold) {
return ZSTD_compress2(cctx, dst, dstCapacity, src, srcSize);
}
// --- 多线程流式压缩 ---
ZSTD_inBuffer input = {src, srcSize, 0};
ZSTD_outBuffer output = {dst, dstCapacity, 0};
// 循环压缩输入数据
size_t ret = 0;
while (input.pos < input.size) {
ret = ZSTD_compressStream2(cctx, &output, &input, ZSTD_e_continue);
if (ZSTD_isError(ret)) break;
// 输出缓冲区已满(理论上不应发生,因 dstCapacity >= ZSTD_compressBound
if (output.pos == output.size) {
return ZSTD_error_dstSize_tooSmall;
}
}
// 结束压缩(确保所有线程完成)
if (!ZSTD_isError(ret)) {
ret = ZSTD_compressStream2(cctx, &output, &input, ZSTD_e_end);
}
return ZSTD_isError(ret) ? ret : output.pos;
}

31
common/zstd_wrapper.h Normal file
View File

@@ -0,0 +1,31 @@
#ifndef ZSTD_WRAPPER_H
#define ZSTD_WRAPPER_H
#include "zstd/zstd.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* 智能压缩函数(自动选择单线程/多线程)
* @param cctx 压缩上下文(需提前创建)
* @param dst 输出缓冲区
* @param dstCapacity 输出缓冲区大小
* @param src 输入数据
* @param srcSize 输入数据大小
* @param threshold 触发多线程的最小数据大小(建议 >= 1MB
* @return 压缩后的数据大小(错误码通过 ZSTD_isError() 检查)
*/
size_t zstd_compress_auto(
ZSTD_CCtx* cctx,
void* dst, size_t dstCapacity,
const void* src, size_t srcSize,
size_t threshold
);
#ifdef __cplusplus
}
#endif
#endif // ZSTD_WRAPPER_H