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;
26
27mod ffi;
28pub mod stream;
29
30pub use stream::{Compressor, Decompressor, IntoPartsError};
31
32/// A sensible middle-of-the-road compression level, matching the C++, Python
33/// and Go bindings. Levels run 1 (fastest) ..= 10 (smallest).
34pub const DEFAULT_LEVEL: i32 = 5;
35
36/// A compression algorithm. Values match the `CU_ALGO_*` constants in the C ABI.
37#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
38#[non_exhaustive]
39pub enum Algorithm {
40    /// Zstandard — frames carry the content size.
41    Zstd,
42    /// Brotli — raw Brotli stream.
43    Brotli,
44    /// zlib — DEFLATE with the zlib wrapper (RFC 1950).
45    Zlib,
46    /// bzip2.
47    Bz2,
48    /// LZ4 — LZ4 frame format (`.lz4`).
49    Lz4,
50    /// XZ — `.xz` stream with CRC64.
51    Xz,
52    /// Alias for [`Algorithm::Xz`]; produces `.xz` frames.
53    Lzma,
54    /// Snappy — raw Snappy block format.
55    Snappy,
56    /// gzip — DEFLATE with the gzip wrapper (RFC 1952).
57    Gzip,
58    /// Raw RFC 1951 DEFLATE.
59    Deflate,
60    /// Raw LZ4 block, without framing or a size prefix. Supports incremental decoding.
61    Lz4Raw,
62    /// Raw LZO1X block. Decompression only.
63    Lzo,
64}
65
66impl Algorithm {
67    fn to_raw(self) -> std::os::raw::c_int {
68        match self {
69            Algorithm::Zstd => ffi::CU_ALGO_ZSTD,
70            Algorithm::Brotli => ffi::CU_ALGO_BROTLI,
71            Algorithm::Zlib => ffi::CU_ALGO_ZLIB,
72            Algorithm::Bz2 => ffi::CU_ALGO_BZ2,
73            Algorithm::Lz4 => ffi::CU_ALGO_LZ4,
74            Algorithm::Xz => ffi::CU_ALGO_XZ,
75            Algorithm::Lzma => ffi::CU_ALGO_LZMA,
76            Algorithm::Snappy => ffi::CU_ALGO_SNAPPY,
77            Algorithm::Gzip => ffi::CU_ALGO_GZIP,
78            Algorithm::Deflate => ffi::CU_ALGO_DEFLATE,
79            Algorithm::Lz4Raw => ffi::CU_ALGO_LZ4_RAW,
80            Algorithm::Lzo => ffi::CU_ALGO_LZO,
81        }
82    }
83
84    /// The lowercase canonical name (`"zstd"`, `"brotli"`, ...).
85    pub fn name(self) -> &'static str {
86        // SAFETY: cu_algorithm_name returns a static NUL-terminated string or
87        // NULL; the enum values are always valid, so NULL never occurs here.
88        unsafe {
89            let p = ffi::cu_algorithm_name(self.to_raw());
90            if p.is_null() {
91                ""
92            } else {
93                CStr::from_ptr(p).to_str().unwrap_or("")
94            }
95        }
96    }
97
98    /// Whether this algorithm was compiled into the linked library.
99    pub fn available(self) -> bool {
100        // SAFETY: pure query over a valid enum value.
101        unsafe { ffi::cu_algorithm_available(self.to_raw()) != 0 }
102    }
103
104    /// The maximum compressed size for `in_len` input bytes — a safe upper
105    /// bound for sizing a one-shot output buffer.
106    pub fn compress_bound(self, in_len: usize) -> usize {
107        // SAFETY: pure query over a valid enum value.
108        unsafe { ffi::cu_compress_bound(in_len, self.to_raw()) }
109    }
110}
111
112impl fmt::Display for Algorithm {
113    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
114        f.write_str(self.name())
115    }
116}
117
118/// A C ABI status code, carried on [`Error`] so callers can match on the exact
119/// failure. Values match the `CU_ERR_*` constants.
120#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
121#[non_exhaustive]
122pub enum Status {
123    InvalidArg,
124    InvalidLevel,
125    BufTooSmall,
126    SizeUnknown,
127    UnsupportedAlgo,
128    Compression,
129    Decompression,
130    Truncated,
131    SizeLimit,
132    StreamFinished,
133    StreamState,
134    Oom,
135    Internal,
136    /// A code not recognised by this binding (carries the raw value).
137    Other(i32),
138}
139
140impl Status {
141    // `c_int` is i32 on every current Rust target, so clippy sees the cast as
142    // redundant — but it is a real narrowing on any target where it isn't.
143    #[allow(clippy::unnecessary_cast)]
144    fn from_raw(code: std::os::raw::c_int) -> Status {
145        match code {
146            ffi::CU_ERR_INVALID_ARG => Status::InvalidArg,
147            ffi::CU_ERR_INVALID_LEVEL => Status::InvalidLevel,
148            ffi::CU_ERR_BUF_TOO_SMALL => Status::BufTooSmall,
149            ffi::CU_ERR_SIZE_UNKNOWN => Status::SizeUnknown,
150            ffi::CU_ERR_UNSUPPORTED_ALGO => Status::UnsupportedAlgo,
151            ffi::CU_ERR_COMPRESSION => Status::Compression,
152            ffi::CU_ERR_DECOMPRESSION => Status::Decompression,
153            ffi::CU_ERR_TRUNCATED => Status::Truncated,
154            ffi::CU_ERR_SIZE_LIMIT => Status::SizeLimit,
155            ffi::CU_ERR_STREAM_FINISHED => Status::StreamFinished,
156            ffi::CU_ERR_STREAM_STATE => Status::StreamState,
157            ffi::CU_ERR_OOM => Status::Oom,
158            ffi::CU_ERR_INTERNAL => Status::Internal,
159            other => Status::Other(other as i32),
160        }
161    }
162}
163
164/// An error returned by the library: a [`Status`] code plus the human-readable
165/// message the C core reported.
166#[derive(Debug, Clone, PartialEq, Eq)]
167pub struct Error {
168    /// The status code, for programmatic matching.
169    pub code: Status,
170    /// The human-readable message (from `cu_strerror` + `cu_last_error`).
171    pub message: String,
172}
173
174impl fmt::Display for Error {
175    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
176        f.write_str(&self.message)
177    }
178}
179
180impl std::error::Error for Error {}
181
182/// Build an [`Error`] from a non-OK status. Reads `cu_last_error()`, which is
183/// thread-local, so this must run on the thread that made the failing call —
184/// true for every call site here (all synchronous).
185fn error_from(code: std::os::raw::c_int) -> Error {
186    // SAFETY: both return static / thread-local NUL-terminated strings.
187    let mut message = unsafe {
188        let p = ffi::cu_strerror(code);
189        CStr::from_ptr(p).to_string_lossy().into_owned()
190    };
191    unsafe {
192        let d = ffi::cu_last_error();
193        if !d.is_null() {
194            let detail = CStr::from_ptr(d).to_string_lossy();
195            if !detail.is_empty() {
196                message.push_str(": ");
197                message.push_str(&detail);
198            }
199        }
200    }
201    Error {
202        code: Status::from_raw(code),
203        message,
204    }
205}
206
207/// Convert a raw status into `Result<(), Error>`.
208fn check(code: std::os::raw::c_int) -> Result<(), Error> {
209    if code == ffi::CU_OK {
210        Ok(())
211    } else {
212        Err(error_from(code))
213    }
214}
215
216/// The linked library version string (`"MAJOR.MINOR.PATCH"`).
217pub fn version() -> &'static str {
218    // SAFETY: cu_version returns a static NUL-terminated string.
219    unsafe { CStr::from_ptr(ffi::cu_version()).to_str().unwrap_or("") }
220}
221
222/// Set a global cap on the output size [`decompress`] and
223/// [`decompress_with_capacity`] will accept, for every algorithm. Defaults to
224/// 1 GiB; `0` disables the cap. A [`Decompressor`] has no limit unless set
225/// with [`Decompressor::set_max_output`].
226pub fn set_max_decompressed_size(bytes: usize) {
227    // SAFETY: plain scalar setter, thread-safe per the C ABI contract.
228    unsafe { ffi::cu_set_max_decompressed_size(bytes) }
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 decoded straight into one right-sized allocation; otherwise the C core decodes into a buffer it grows (bounded by the same cap as the sized path) and the result is copied out of it once. Raw LZ4 can use this growing decode without a capacity hint.
256pub fn decompress(algo: Algorithm, data: &[u8]) -> Result<Vec<u8>, Error> {
257    let mut hint: usize = 0;
258    // SAFETY: valid slice, valid out pointer.
259    let st = unsafe {
260        ffi::cu_decompress_size_hint(algo.to_raw(), data.as_ptr(), data.len(), &mut hint)
261    };
262    match st {
263        ffi::CU_OK => {
264            // Never blindly allocate the reported size: a malformed header can claim a bogus, enormous length (some codecs' size_hint does not fully validate), and an infallible allocation would abort the process on OOM. If it can't be reserved, the core's growing decode takes over: it allocates only as real output appears, and rejects the bad input.
265            let mut out: Vec<u8> = Vec::new();
266            if out.try_reserve_exact(hint).is_ok() {
267                match decode_into_spare(algo, data, &mut out, hint) {
268                    ffi::CU_OK => return Ok(out),
269                    // A hint that was short of the real size.
270                    ffi::CU_ERR_SIZE_UNKNOWN | ffi::CU_ERR_BUF_TOO_SMALL => {}
271                    other => return Err(error_from(other)),
272                }
273            }
274        }
275        ffi::CU_ERR_SIZE_UNKNOWN => {}
276        other => return Err(error_from(other)),
277    }
278    decompress_alloc(algo, data)
279}
280
281/// Decompress `data` into at most `capacity` bytes. The capacity is an upper
282/// bound on the output, allocated up front; the result holds only the bytes
283/// written. Skips the size probe and the growing decode for every algorithm.
284pub fn decompress_with_capacity(
285    algo: Algorithm,
286    data: &[u8],
287    capacity: usize,
288) -> Result<Vec<u8>, Error> {
289    let mut out: Vec<u8> = Vec::new();
290    if out.try_reserve_exact(capacity).is_err() {
291        return Err(oom(capacity));
292    }
293    check(decode_into_spare(algo, data, &mut out, capacity))?;
294    Ok(out)
295}
296
297/// Decodes `data` into the first `cap` bytes of `out`'s spare capacity, which are left uninitialized until the codec writes them, and sets `out`'s length to the bytes written on success. Returns the raw status; `out` stays empty on failure. `out` must be empty with at least `cap` bytes of capacity.
298fn decode_into_spare(
299    algo: Algorithm,
300    data: &[u8],
301    out: &mut Vec<u8>,
302    cap: usize,
303) -> std::os::raw::c_int {
304    debug_assert!(out.is_empty() && out.capacity() >= cap);
305    let mut out_len = cap;
306    // SAFETY: `data` is a valid slice; the spare capacity is valid for `cap` bytes of writes (an empty one yields a non-null dangling pointer, which the C side accepts for zero capacity); out_len is in/out.
307    let st = unsafe {
308        ffi::cu_decompress(
309            algo.to_raw(),
310            data.as_ptr(),
311            data.len(),
312            out.spare_capacity_mut().as_mut_ptr().cast::<u8>(),
313            &mut out_len,
314        )
315    };
316    if st == ffi::CU_OK {
317        assert!(
318            out_len <= cap,
319            "compress-utils: decoder reported more output than the buffer holds"
320        );
321        // SAFETY: the codec initialized the first out_len <= capacity bytes.
322        unsafe { out.set_len(out_len) };
323    }
324    st
325}
326
327/// Decodes into a buffer the C core allocates and grows (for a format that doesn't record its size), then copies it once into a `Vec`.
328fn decompress_alloc(algo: Algorithm, data: &[u8]) -> Result<Vec<u8>, Error> {
329    let mut buf: *mut u8 = std::ptr::null_mut();
330    let mut len: usize = 0;
331    // SAFETY: valid slice; out pointers are valid. On success the core hands over a malloc'd buffer that is released with cu_buffer_free below.
332    let st = unsafe {
333        ffi::cu_decompress_alloc(algo.to_raw(), data.as_ptr(), data.len(), &mut buf, &mut len)
334    };
335    check(st)?;
336    let mut out: Vec<u8> = Vec::new();
337    let copied = out.try_reserve_exact(len).is_ok();
338    if copied {
339        // SAFETY: on success `buf` holds `len` initialized bytes.
340        out.extend_from_slice(unsafe { std::slice::from_raw_parts(buf, len) });
341    }
342    // SAFETY: `buf` came from cu_decompress_alloc and isn't used after this.
343    unsafe { ffi::cu_buffer_free(buf.cast()) };
344    if copied {
345        Ok(out)
346    } else {
347        Err(oom(len))
348    }
349}
350
351fn oom(bytes: usize) -> Error {
352    Error {
353        code: Status::Oom,
354        message: format!("compress-utils: cannot allocate {bytes} bytes of output"),
355    }
356}
357
358// Re-exported for the streaming module to construct/report errors uniformly.
359pub(crate) use self::check as check_status;
360pub(crate) use self::error_from as make_error;