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 recovered in a single pass; otherwise this falls
256/// back to the streaming decoder (as the C++/Python/Go bindings do).
257/// Raw LZ4 can use this incremental fallback without a capacity hint.
258pub fn decompress(algo: Algorithm, data: &[u8]) -> Result<Vec<u8>, Error> {
259 match decompress_one_shot(algo, data)? {
260 Some(out) => Ok(out),
261 // Wire format does not carry the size (zlib, gzip, brotli, bz2, xz,
262 // raw LZ4): stream-decompress the whole buffer, bounded by the same cap
263 // as the one-shot path.
264 None => {
265 use std::io::Read;
266 let mut r = Decompressor::new(data, algo)?;
267 // SAFETY: plain scalar getter.
268 r.set_max_output(unsafe { ffi::cu_get_max_decompressed_size() });
269 let mut out = Vec::new();
270 r.read_to_end(&mut out).map_err(stream::io_to_error)?;
271 Ok(out)
272 }
273 }
274}
275
276/// Decompress `data` into at most `capacity` bytes. The capacity is an upper
277/// bound on the output, allocated up front; the result holds only the bytes
278/// written. Skips the size probe and streaming fallback for every algorithm.
279pub fn decompress_with_capacity(
280 algo: Algorithm,
281 data: &[u8],
282 capacity: usize,
283) -> Result<Vec<u8>, Error> {
284 let mut out: Vec<u8> = Vec::new();
285 if out.try_reserve_exact(capacity).is_err() {
286 return Err(Error {
287 code: Status::Oom,
288 message: format!("compress-utils: cannot allocate {capacity} bytes of output"),
289 });
290 }
291 out.resize(capacity, 0);
292 let mut out_len = out.len();
293 // SAFETY: valid slices; out_len is in/out and starts at out's length.
294 let st = unsafe {
295 ffi::cu_decompress(
296 algo.to_raw(),
297 data.as_ptr(),
298 data.len(),
299 out.as_mut_ptr(),
300 &mut out_len,
301 )
302 };
303 check(st)?;
304 out.truncate(out_len);
305 Ok(out)
306}
307
308/// Attempt the size-hint + one-shot path. `Ok(None)` means the caller should
309/// fall back to streaming (size not recoverable from the wire format).
310fn decompress_one_shot(algo: Algorithm, data: &[u8]) -> Result<Option<Vec<u8>>, Error> {
311 let mut hint: usize = 0;
312 // SAFETY: valid slice, valid out pointer.
313 let st = unsafe {
314 ffi::cu_decompress_size_hint(algo.to_raw(), data.as_ptr(), data.len(), &mut hint)
315 };
316 match st {
317 ffi::CU_OK => {
318 // Never blindly allocate the reported size: a malformed header can
319 // claim a bogus, enormous length (some codecs' size_hint does not
320 // fully validate), and `vec![0u8; hint]` would abort the process on
321 // OOM. Try to reserve; if that fails, fall back to streaming, which
322 // decodes incrementally and rejects the bad input via the
323 // no-progress guard.
324 let mut out: Vec<u8> = Vec::new();
325 if out.try_reserve_exact(hint).is_err() {
326 return Ok(None);
327 }
328 out.resize(hint, 0);
329 let mut out_len = out.len();
330 // SAFETY: as above; out sized to the reported hint.
331 let st2 = unsafe {
332 ffi::cu_decompress(
333 algo.to_raw(),
334 data.as_ptr(),
335 data.len(),
336 out.as_mut_ptr(),
337 &mut out_len,
338 )
339 };
340 match st2 {
341 ffi::CU_OK => {
342 out.truncate(out_len);
343 Ok(Some(out))
344 }
345 ffi::CU_ERR_SIZE_UNKNOWN | ffi::CU_ERR_BUF_TOO_SMALL => Ok(None),
346 other => Err(error_from(other)),
347 }
348 }
349 ffi::CU_ERR_SIZE_UNKNOWN => Ok(None),
350 other => Err(error_from(other)),
351 }
352}
353
354// Re-exported for the streaming module to construct/report errors uniformly.
355pub(crate) use self::check as check_status;
356pub(crate) use self::error_from as make_error;