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