Skip to main content

compress_bound

Function compress_bound 

Source
pub const fn compress_bound(src_size: usize) -> usize
Expand description

Worst-case compressed-frame size for an input of src_size bytes.

A destination buffer of this size is always large enough to hold the output of compress_slice_to_vec (or any single-frame compression) for an input of src_size bytes, so a caller sizing a fixed buffer once (the shape the C ZSTD_compress entry point needs) never has to grow it.

Mirrors the upstream ZSTD_COMPRESSBOUND formula exactly: src_size + (src_size >> 8) + margin, where margin is (128 KiB - src_size) >> 11 for inputs below 128 KiB and 0 otherwise. The margin guarantees bound(a) + bound(b) <= bound(a + b) for blocks of at least 128 KiB, which keeps multi-frame concatenation sizing sound.

Saturates at usize::MAX if the formula would overflow on a pathologically large src_size — no allocation that large can exist, so the saturated value is the correct “cannot fit” sentinel rather than a masked wrap.

use structured_zstd::encoding::{compress_bound, compress_slice_to_vec, CompressionLevel};
let data = [7u8; 4096];
assert!(compress_slice_to_vec(&data, CompressionLevel::Default).len() <= compress_bound(data.len()));