Skip to main content

compress_utils/
lib.rs

1//! # compress-utils
2//!
3//! A unified, safe Rust interface to eight compression algorithms — Zstandard,
4//! Brotli, zlib, gzip, bzip2, LZ4, XZ/LZMA and Snappy — over a single C core.
5//! Every algorithm speaks the same API; switching codecs is a one-enum change.
6//!
7//! ```no_run
8//! use compress_utils::{compress, decompress, Algorithm};
9//!
10//! let data = b"the quick brown fox jumps over the lazy dog";
11//! let packed = compress(Algorithm::Zstd, data, 5)?;
12//! let restored = decompress(Algorithm::Zstd, &packed)?;
13//! assert_eq!(&restored, data);
14//! # Ok::<(), compress_utils::Error>(())
15//! ```
16//!
17//! For large or incremental data, use the streaming adapters [`Compressor`]
18//! (an [`std::io::Write`]) and [`Decompressor`] (an [`std::io::Read`]) in the
19//! [`stream`] module.
20
21use std::ffi::CStr;
22use std::fmt;
23use std::sync::atomic::{AtomicUsize, Ordering};
24
25mod ffi;
26pub mod stream;
27
28pub use stream::{Compressor, Decompressor};
29
30/// A sensible middle-of-the-road compression level, matching the C++, Python
31/// and Go bindings. Levels run 1 (fastest) ..= 10 (smallest).
32pub const DEFAULT_LEVEL: i32 = 5;
33
34/// A compression algorithm. Values match the `CU_ALGO_*` constants in the C ABI.
35#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
36#[non_exhaustive]
37pub enum Algorithm {
38    /// Zstandard — frames carry the content size.
39    Zstd,
40    /// Brotli — raw Brotli stream.
41    Brotli,
42    /// zlib — DEFLATE with the zlib wrapper (RFC 1950).
43    Zlib,
44    /// bzip2.
45    Bz2,
46    /// LZ4 — LZ4 frame format (`.lz4`).
47    Lz4,
48    /// XZ — `.xz` stream with CRC64.
49    Xz,
50    /// Alias for [`Algorithm::Xz`]; produces `.xz` frames.
51    Lzma,
52    /// Snappy — raw Snappy block format.
53    Snappy,
54    /// gzip — DEFLATE with the gzip wrapper (RFC 1952).
55    Gzip,
56}
57
58impl Algorithm {
59    fn to_raw(self) -> std::os::raw::c_int {
60        match self {
61            Algorithm::Zstd => ffi::CU_ALGO_ZSTD,
62            Algorithm::Brotli => ffi::CU_ALGO_BROTLI,
63            Algorithm::Zlib => ffi::CU_ALGO_ZLIB,
64            Algorithm::Bz2 => ffi::CU_ALGO_BZ2,
65            Algorithm::Lz4 => ffi::CU_ALGO_LZ4,
66            Algorithm::Xz => ffi::CU_ALGO_XZ,
67            Algorithm::Lzma => ffi::CU_ALGO_LZMA,
68            Algorithm::Snappy => ffi::CU_ALGO_SNAPPY,
69            Algorithm::Gzip => ffi::CU_ALGO_GZIP,
70        }
71    }
72
73    /// The lowercase canonical name (`"zstd"`, `"brotli"`, ...).
74    pub fn name(self) -> &'static str {
75        // SAFETY: cu_algorithm_name returns a static NUL-terminated string or
76        // NULL; the enum values are always valid, so NULL never occurs here.
77        unsafe {
78            let p = ffi::cu_algorithm_name(self.to_raw());
79            if p.is_null() {
80                ""
81            } else {
82                CStr::from_ptr(p).to_str().unwrap_or("")
83            }
84        }
85    }
86
87    /// Whether this algorithm was compiled into the linked library.
88    pub fn available(self) -> bool {
89        // SAFETY: pure query over a valid enum value.
90        unsafe { ffi::cu_algorithm_available(self.to_raw()) != 0 }
91    }
92
93    /// The maximum compressed size for `in_len` input bytes — a safe upper
94    /// bound for sizing a one-shot output buffer.
95    pub fn compress_bound(self, in_len: usize) -> usize {
96        // SAFETY: pure query over a valid enum value.
97        unsafe { ffi::cu_compress_bound(in_len, self.to_raw()) }
98    }
99}
100
101impl fmt::Display for Algorithm {
102    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
103        f.write_str(self.name())
104    }
105}
106
107/// A C ABI status code, carried on [`Error`] so callers can match on the exact
108/// failure. Values match the `CU_ERR_*` constants.
109#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
110#[non_exhaustive]
111pub enum Status {
112    InvalidArg,
113    InvalidLevel,
114    BufTooSmall,
115    SizeUnknown,
116    UnsupportedAlgo,
117    Compression,
118    Decompression,
119    Truncated,
120    SizeLimit,
121    StreamFinished,
122    StreamState,
123    Oom,
124    Internal,
125    /// A code not recognised by this binding (carries the raw value).
126    Other(i32),
127}
128
129impl Status {
130    // `c_int` is i32 on every current Rust target, so clippy sees the cast as
131    // redundant — but it is a real narrowing on any target where it isn't.
132    #[allow(clippy::unnecessary_cast)]
133    fn from_raw(code: std::os::raw::c_int) -> Status {
134        match code {
135            ffi::CU_ERR_INVALID_ARG => Status::InvalidArg,
136            ffi::CU_ERR_INVALID_LEVEL => Status::InvalidLevel,
137            ffi::CU_ERR_BUF_TOO_SMALL => Status::BufTooSmall,
138            ffi::CU_ERR_SIZE_UNKNOWN => Status::SizeUnknown,
139            ffi::CU_ERR_UNSUPPORTED_ALGO => Status::UnsupportedAlgo,
140            ffi::CU_ERR_COMPRESSION => Status::Compression,
141            ffi::CU_ERR_DECOMPRESSION => Status::Decompression,
142            ffi::CU_ERR_TRUNCATED => Status::Truncated,
143            ffi::CU_ERR_SIZE_LIMIT => Status::SizeLimit,
144            ffi::CU_ERR_STREAM_FINISHED => Status::StreamFinished,
145            ffi::CU_ERR_STREAM_STATE => Status::StreamState,
146            ffi::CU_ERR_OOM => Status::Oom,
147            ffi::CU_ERR_INTERNAL => Status::Internal,
148            other => Status::Other(other as i32),
149        }
150    }
151}
152
153/// An error returned by the library: a [`Status`] code plus the human-readable
154/// message the C core reported.
155#[derive(Debug, Clone, PartialEq, Eq)]
156pub struct Error {
157    /// The status code, for programmatic matching.
158    pub code: Status,
159    /// The human-readable message (from `cu_strerror` + `cu_last_error`).
160    pub message: String,
161}
162
163impl fmt::Display for Error {
164    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
165        f.write_str(&self.message)
166    }
167}
168
169impl std::error::Error for Error {}
170
171/// Build an [`Error`] from a non-OK status. Reads `cu_last_error()`, which is
172/// thread-local, so this must run on the thread that made the failing call —
173/// true for every call site here (all synchronous).
174fn error_from(code: std::os::raw::c_int) -> Error {
175    // SAFETY: both return static / thread-local NUL-terminated strings.
176    let mut message = unsafe {
177        let p = ffi::cu_strerror(code);
178        CStr::from_ptr(p).to_string_lossy().into_owned()
179    };
180    unsafe {
181        let d = ffi::cu_last_error();
182        if !d.is_null() {
183            let detail = CStr::from_ptr(d).to_string_lossy();
184            if !detail.is_empty() {
185                message.push_str(": ");
186                message.push_str(&detail);
187            }
188        }
189    }
190    Error {
191        code: Status::from_raw(code),
192        message,
193    }
194}
195
196/// Convert a raw status into `Result<(), Error>`.
197fn check(code: std::os::raw::c_int) -> Result<(), Error> {
198    if code == ffi::CU_OK {
199        Ok(())
200    } else {
201        Err(error_from(code))
202    }
203}
204
205/// The linked library version string (`"MAJOR.MINOR.PATCH"`).
206pub fn version() -> &'static str {
207    // SAFETY: cu_version returns a static NUL-terminated string.
208    unsafe { CStr::from_ptr(ffi::cu_version()).to_str().unwrap_or("") }
209}
210
211/// Mirror of the C core's decompressed-size cap (default 1 GiB, matching the C
212/// default). `usize::MAX` means "disabled". Consulted by [`decompress`] when it
213/// falls back to streaming for size-unknown formats — that path bypasses
214/// `cu_decompress`, so we re-apply the cap here to keep the decompress-to-memory
215/// API safe against decompression bombs (e.g. malformed xz that liblzma's
216/// legacy `.lzma` auto-detection expands without bound).
217static MAX_DECOMPRESSED: AtomicUsize = AtomicUsize::new(1024 * 1024 * 1024);
218
219/// Set a global cap on the output size one-shot [`decompress`] will accept.
220/// Defaults to 1 GiB; `0` disables the cap. Does not affect the streaming
221/// [`Decompressor`], which should enforce its own limit.
222pub fn set_max_decompressed_size(bytes: usize) {
223    // SAFETY: plain scalar setter, thread-safe per the C ABI contract.
224    unsafe { ffi::cu_set_max_decompressed_size(bytes) }
225    MAX_DECOMPRESSED.store(
226        if bytes == 0 { usize::MAX } else { bytes },
227        Ordering::Relaxed,
228    );
229}
230
231/// Compress `data` with `algo` at `level` (1 fastest ..= 10 smallest).
232pub fn compress(algo: Algorithm, data: &[u8], level: i32) -> Result<Vec<u8>, Error> {
233    let bound = algo.compress_bound(data.len());
234    let mut out = vec![0u8; bound];
235    let mut out_len = out.len();
236    // SAFETY: `data`/`out` pointers are valid for their lengths; empty slices
237    // yield non-null dangling pointers (Rust never hands out a null slice ptr),
238    // so no NULL-source special-casing is needed. out_len is in/out.
239    let st = unsafe {
240        ffi::cu_compress(
241            algo.to_raw(),
242            data.as_ptr(),
243            data.len(),
244            out.as_mut_ptr(),
245            &mut out_len,
246            level,
247        )
248    };
249    check(st)?;
250    out.truncate(out_len);
251    Ok(out)
252}
253
254/// Decompress `data` produced by `algo`. When the wire format records the
255/// decompressed size it is recovered in a single pass; otherwise this falls
256/// back to the streaming decoder (as the C++/Python/Go bindings do).
257pub fn decompress(algo: Algorithm, data: &[u8]) -> Result<Vec<u8>, Error> {
258    match decompress_one_shot(algo, data)? {
259        Some(out) => Ok(out),
260        // Wire format does not carry the size (zlib, gzip, brotli, bz2, raw
261        // lz4, snappy): stream-decompress the whole buffer, bounded by the same
262        // cap the C one-shot path enforces so a malformed bomb can't run us out
263        // of memory here.
264        None => {
265            use std::io::Read;
266            let mut r = Decompressor::new(data, algo)?;
267            let mut out = Vec::new();
268            let cap = MAX_DECOMPRESSED.load(Ordering::Relaxed);
269            if cap == usize::MAX {
270                // Cap disabled by the caller — honour their choice, unbounded.
271                r.read_to_end(&mut out).map_err(stream::io_to_error)?;
272            } else {
273                // Read at most cap+1 bytes; more than cap means it exceeded.
274                let limit = (cap as u64).saturating_add(1);
275                r.by_ref()
276                    .take(limit)
277                    .read_to_end(&mut out)
278                    .map_err(stream::io_to_error)?;
279                if out.len() > cap {
280                    return Err(Error {
281                        code: Status::SizeLimit,
282                        message: format!(
283                            "compress-utils: decompressed size exceeds cap of {cap} bytes"
284                        ),
285                    });
286                }
287            }
288            Ok(out)
289        }
290    }
291}
292
293/// Attempt the size-hint + one-shot path. `Ok(None)` means the caller should
294/// fall back to streaming (size not recoverable from the wire format).
295fn decompress_one_shot(algo: Algorithm, data: &[u8]) -> Result<Option<Vec<u8>>, Error> {
296    let mut hint: usize = 0;
297    // SAFETY: valid slice, valid out pointer.
298    let st = unsafe {
299        ffi::cu_decompress_size_hint(algo.to_raw(), data.as_ptr(), data.len(), &mut hint)
300    };
301    match st {
302        ffi::CU_OK => {
303            // Never blindly allocate the reported size: a malformed header can
304            // claim a bogus, enormous length (some codecs' size_hint does not
305            // fully validate), and `vec![0u8; hint]` would abort the process on
306            // OOM. Try to reserve; if that fails, fall back to streaming, which
307            // decodes incrementally and rejects the bad input via the
308            // no-progress guard.
309            let mut out: Vec<u8> = Vec::new();
310            if out.try_reserve_exact(hint).is_err() {
311                return Ok(None);
312            }
313            out.resize(hint, 0);
314            let mut out_len = out.len();
315            // SAFETY: as above; out sized to the reported hint.
316            let st2 = unsafe {
317                ffi::cu_decompress(
318                    algo.to_raw(),
319                    data.as_ptr(),
320                    data.len(),
321                    out.as_mut_ptr(),
322                    &mut out_len,
323                )
324            };
325            match st2 {
326                ffi::CU_OK => {
327                    out.truncate(out_len);
328                    Ok(Some(out))
329                }
330                ffi::CU_ERR_SIZE_UNKNOWN | ffi::CU_ERR_BUF_TOO_SMALL => Ok(None),
331                other => Err(error_from(other)),
332            }
333        }
334        ffi::CU_ERR_SIZE_UNKNOWN => Ok(None),
335        other => Err(error_from(other)),
336    }
337}
338
339// Re-exported for the streaming module to construct/report errors uniformly.
340pub(crate) use self::check as check_status;
341pub(crate) use self::error_from as make_error;