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