use std::ffi::CStr;
use std::fmt;
mod ffi;
pub mod stream;
pub use stream::{Compressor, Decompressor, IntoPartsError};
pub const DEFAULT_LEVEL: i32 = 5;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Algorithm {
Zstd,
Brotli,
Zlib,
Bz2,
Lz4,
Xz,
Lzma,
Snappy,
Gzip,
Deflate,
Lz4Raw,
Lzo,
}
impl Algorithm {
fn to_raw(self) -> std::os::raw::c_int {
match self {
Algorithm::Zstd => ffi::CU_ALGO_ZSTD,
Algorithm::Brotli => ffi::CU_ALGO_BROTLI,
Algorithm::Zlib => ffi::CU_ALGO_ZLIB,
Algorithm::Bz2 => ffi::CU_ALGO_BZ2,
Algorithm::Lz4 => ffi::CU_ALGO_LZ4,
Algorithm::Xz => ffi::CU_ALGO_XZ,
Algorithm::Lzma => ffi::CU_ALGO_LZMA,
Algorithm::Snappy => ffi::CU_ALGO_SNAPPY,
Algorithm::Gzip => ffi::CU_ALGO_GZIP,
Algorithm::Deflate => ffi::CU_ALGO_DEFLATE,
Algorithm::Lz4Raw => ffi::CU_ALGO_LZ4_RAW,
Algorithm::Lzo => ffi::CU_ALGO_LZO,
}
}
pub fn name(self) -> &'static str {
unsafe {
let p = ffi::cu_algorithm_name(self.to_raw());
if p.is_null() {
""
} else {
CStr::from_ptr(p).to_str().unwrap_or("")
}
}
}
pub fn available(self) -> bool {
unsafe { ffi::cu_algorithm_available(self.to_raw()) != 0 }
}
pub fn compress_bound(self, in_len: usize) -> usize {
unsafe { ffi::cu_compress_bound(in_len, self.to_raw()) }
}
}
impl fmt::Display for Algorithm {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.name())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Status {
InvalidArg,
InvalidLevel,
BufTooSmall,
SizeUnknown,
UnsupportedAlgo,
Compression,
Decompression,
Truncated,
SizeLimit,
StreamFinished,
StreamState,
Oom,
Internal,
Other(i32),
}
impl Status {
#[allow(clippy::unnecessary_cast)]
fn from_raw(code: std::os::raw::c_int) -> Status {
match code {
ffi::CU_ERR_INVALID_ARG => Status::InvalidArg,
ffi::CU_ERR_INVALID_LEVEL => Status::InvalidLevel,
ffi::CU_ERR_BUF_TOO_SMALL => Status::BufTooSmall,
ffi::CU_ERR_SIZE_UNKNOWN => Status::SizeUnknown,
ffi::CU_ERR_UNSUPPORTED_ALGO => Status::UnsupportedAlgo,
ffi::CU_ERR_COMPRESSION => Status::Compression,
ffi::CU_ERR_DECOMPRESSION => Status::Decompression,
ffi::CU_ERR_TRUNCATED => Status::Truncated,
ffi::CU_ERR_SIZE_LIMIT => Status::SizeLimit,
ffi::CU_ERR_STREAM_FINISHED => Status::StreamFinished,
ffi::CU_ERR_STREAM_STATE => Status::StreamState,
ffi::CU_ERR_OOM => Status::Oom,
ffi::CU_ERR_INTERNAL => Status::Internal,
other => Status::Other(other as i32),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Error {
pub code: Status,
pub message: String,
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.message)
}
}
impl std::error::Error for Error {}
fn error_from(code: std::os::raw::c_int) -> Error {
let mut message = unsafe {
let p = ffi::cu_strerror(code);
CStr::from_ptr(p).to_string_lossy().into_owned()
};
unsafe {
let d = ffi::cu_last_error();
if !d.is_null() {
let detail = CStr::from_ptr(d).to_string_lossy();
if !detail.is_empty() {
message.push_str(": ");
message.push_str(&detail);
}
}
}
Error {
code: Status::from_raw(code),
message,
}
}
fn check(code: std::os::raw::c_int) -> Result<(), Error> {
if code == ffi::CU_OK {
Ok(())
} else {
Err(error_from(code))
}
}
pub fn version() -> &'static str {
unsafe { CStr::from_ptr(ffi::cu_version()).to_str().unwrap_or("") }
}
pub fn set_max_decompressed_size(bytes: usize) {
unsafe { ffi::cu_set_max_decompressed_size(bytes) }
}
pub fn compress(algo: Algorithm, data: &[u8], level: i32) -> Result<Vec<u8>, Error> {
let bound = algo.compress_bound(data.len());
let mut out = vec![0u8; bound];
let mut out_len = out.len();
let st = unsafe {
ffi::cu_compress(
algo.to_raw(),
data.as_ptr(),
data.len(),
out.as_mut_ptr(),
&mut out_len,
level,
)
};
check(st)?;
out.truncate(out_len);
Ok(out)
}
pub fn decompress(algo: Algorithm, data: &[u8]) -> Result<Vec<u8>, Error> {
let mut hint: usize = 0;
let st = unsafe {
ffi::cu_decompress_size_hint(algo.to_raw(), data.as_ptr(), data.len(), &mut hint)
};
match st {
ffi::CU_OK => {
let mut out: Vec<u8> = Vec::new();
if out.try_reserve_exact(hint).is_ok() {
match decode_into_spare(algo, data, &mut out, hint) {
ffi::CU_OK => return Ok(out),
ffi::CU_ERR_SIZE_UNKNOWN | ffi::CU_ERR_BUF_TOO_SMALL => {}
other => return Err(error_from(other)),
}
}
}
ffi::CU_ERR_SIZE_UNKNOWN => {}
other => return Err(error_from(other)),
}
decompress_alloc(algo, data)
}
pub fn decompress_with_capacity(
algo: Algorithm,
data: &[u8],
capacity: usize,
) -> Result<Vec<u8>, Error> {
let mut out: Vec<u8> = Vec::new();
if out.try_reserve_exact(capacity).is_err() {
return Err(oom(capacity));
}
check(decode_into_spare(algo, data, &mut out, capacity))?;
Ok(out)
}
fn decode_into_spare(
algo: Algorithm,
data: &[u8],
out: &mut Vec<u8>,
cap: usize,
) -> std::os::raw::c_int {
debug_assert!(out.is_empty() && out.capacity() >= cap);
let mut out_len = cap;
let st = unsafe {
ffi::cu_decompress(
algo.to_raw(),
data.as_ptr(),
data.len(),
out.spare_capacity_mut().as_mut_ptr().cast::<u8>(),
&mut out_len,
)
};
if st == ffi::CU_OK {
assert!(
out_len <= cap,
"compress-utils: decoder reported more output than the buffer holds"
);
unsafe { out.set_len(out_len) };
}
st
}
fn decompress_alloc(algo: Algorithm, data: &[u8]) -> Result<Vec<u8>, Error> {
let mut buf: *mut u8 = std::ptr::null_mut();
let mut len: usize = 0;
let st = unsafe {
ffi::cu_decompress_alloc(algo.to_raw(), data.as_ptr(), data.len(), &mut buf, &mut len)
};
check(st)?;
let mut out: Vec<u8> = Vec::new();
let copied = out.try_reserve_exact(len).is_ok();
if copied {
out.extend_from_slice(unsafe { std::slice::from_raw_parts(buf, len) });
}
unsafe { ffi::cu_buffer_free(buf.cast()) };
if copied {
Ok(out)
} else {
Err(oom(len))
}
}
fn oom(bytes: usize) -> Error {
Error {
code: Status::Oom,
message: format!("compress-utils: cannot allocate {bytes} bytes of output"),
}
}
pub(crate) use self::check as check_status;
pub(crate) use self::error_from as make_error;