diff --git a/lib/compress/zstdmt_compress.c b/lib/compress/zstdmt_compress.c index ed63e2163..c3d912073 100644 --- a/lib/compress/zstdmt_compress.c +++ b/lib/compress/zstdmt_compress.c @@ -344,6 +344,7 @@ ZSTDMT_RustCCtxPool* ZSTDMT_rust_cctx_pool_create(unsigned nbWorkers, ZSTD_customMem cMem); void ZSTDMT_rust_cctx_pool_free(ZSTDMT_RustCCtxPool* pool); size_t ZSTDMT_rust_cctx_pool_sizeof(const ZSTDMT_RustCCtxPool* pool); +size_t ZSTDMT_rust_sizeofCCtxPool(size_t wrapperSize, size_t rustPoolSize); ZSTDMT_RustCCtxPool* ZSTDMT_rust_cctx_pool_expand(ZSTDMT_RustCCtxPool* pool, unsigned nbWorkers); ZSTD_CCtx* ZSTDMT_rust_cctx_pool_get(ZSTDMT_RustCCtxPool* pool); @@ -401,8 +402,10 @@ static ZSTDMT_CCtxPool* ZSTDMT_expandCCtxPool(ZSTDMT_CCtxPool* srcPool, /* only works during initialization phase, not during compression */ static size_t ZSTDMT_sizeof_CCtxPool(ZSTDMT_CCtxPool* cctxPool) { + size_t rustPoolSize; if (cctxPool == NULL) return 0; - return sizeof(*cctxPool) + ZSTDMT_rust_cctx_pool_sizeof(cctxPool->rustPool); + rustPoolSize = ZSTDMT_rust_cctx_pool_sizeof(cctxPool->rustPool); + return ZSTDMT_rust_sizeofCCtxPool(sizeof(*cctxPool), rustPoolSize); } static ZSTD_CCtx* ZSTDMT_getCCtx(ZSTDMT_CCtxPool* cctxPool) diff --git a/rust/src/zstdmt_compress.rs b/rust/src/zstdmt_compress.rs index 3b8c2abfc..056a35e93 100644 --- a/rust/src/zstdmt_compress.rs +++ b/rust/src/zstdmt_compress.rs @@ -939,6 +939,16 @@ pub unsafe extern "C" fn ZSTDMT_rust_cctx_pool_sizeof(pool: *const RustCCtxPool) .saturating_add(total_cctx_size) } +#[inline] +fn sizeof_cctx_pool(wrapper_size: usize, rust_pool_size: usize) -> usize { + wrapper_size.wrapping_add(rust_pool_size) +} + +#[no_mangle] +pub extern "C" fn ZSTDMT_rust_sizeofCCtxPool(wrapperSize: usize, rustPoolSize: usize) -> usize { + sizeof_cctx_pool(wrapperSize, rustPoolSize) +} + #[no_mangle] pub unsafe extern "C" fn ZSTDMT_rust_cctx_pool_expand( pool: *mut RustCCtxPool, @@ -1580,4 +1590,22 @@ mod tests { 1usize << 25 ); } + + #[test] + fn cctx_pool_size_addition_handles_zero_components() { + assert_eq!(sizeof_cctx_pool(0, 0), 0); + assert_eq!(sizeof_cctx_pool(37, 0), 37); + assert_eq!(sizeof_cctx_pool(0, 53), 53); + } + + #[test] + fn cctx_pool_size_addition_preserves_ordinary_sum() { + assert_eq!(sizeof_cctx_pool(128, 4096), 4224); + } + + #[test] + fn cctx_pool_size_addition_wraps_like_c_size_t() { + assert_eq!(sizeof_cctx_pool(usize::MAX, 1), 0); + assert_eq!(sizeof_cctx_pool(usize::MAX - 7, 11), 3); + } }