use crate::format::{self, PackError};
use std::cell::RefCell;
use std::ffi::c_char;
pub const LZVOLT_NOT_COMPRESSIBLE: i64 = 0;
pub const LZVOLT_E_NULL: i64 = -1;
pub const LZVOLT_E_TRUNCATED: i64 = -2;
pub const LZVOLT_E_BAD_OFFSET: i64 = -3;
pub const LZVOLT_E_LENGTH_MISMATCH: i64 = -4;
pub const LZVOLT_E_TOO_LARGE: i64 = -5;
pub const LZVOLT_E_NON_CANONICAL: i64 = -6;
pub const LZVOLT_E_OUTPUT_TOO_SMALL: i64 = -7;
fn code_for(e: PackError) -> i64 {
match e {
PackError::Truncated => LZVOLT_E_TRUNCATED,
PackError::BadOffset => LZVOLT_E_BAD_OFFSET,
PackError::LengthMismatch => LZVOLT_E_LENGTH_MISMATCH,
PackError::TooLarge => LZVOLT_E_TOO_LARGE,
PackError::NonCanonicalHeader => LZVOLT_E_NON_CANONICAL,
PackError::OutputTooSmall => LZVOLT_E_OUTPUT_TOO_SMALL,
}
}
unsafe fn as_slice<'a>(ptr: *const u8, len: usize) -> Option<&'a [u8]> {
if len == 0 {
return Some(&[]);
}
if ptr.is_null() {
return None;
}
Some(std::slice::from_raw_parts(ptr, len))
}
unsafe fn as_slice_mut<'a>(ptr: *mut u8, len: usize) -> Option<&'a mut [u8]> {
if len == 0 {
return Some(&mut []);
}
if ptr.is_null() {
return None;
}
Some(std::slice::from_raw_parts_mut(ptr, len))
}
thread_local! {
static SCRATCH: RefCell<Vec<u8>> = const { RefCell::new(Vec::new()) };
}
#[no_mangle]
pub extern "C" fn lzvolt_compress_bound(src_len: usize) -> usize {
src_len + src_len / 4 * 3 + src_len / 128 + 4 + 8 + 64
}
#[no_mangle]
pub extern "C" fn lzvolt_decompress_bound(declared: usize) -> usize {
format::decompressed_bound(declared)
}
#[no_mangle]
pub unsafe extern "C" fn lzvolt_compress(
src: *const u8,
src_len: usize,
dst: *mut u8,
dst_cap: usize,
) -> i64 {
let Some(input) = as_slice(src, src_len) else {
return LZVOLT_E_NULL;
};
let Some(out) = as_slice_mut(dst, dst_cap) else {
return LZVOLT_E_NULL;
};
SCRATCH.with(|cell| {
let mut buf = cell.borrow_mut();
if !format::pack(input, &mut buf) {
return LZVOLT_NOT_COMPRESSIBLE;
}
if buf.len() > out.len() {
return LZVOLT_E_OUTPUT_TOO_SMALL;
}
out[..buf.len()].copy_from_slice(&buf);
buf.len() as i64
})
}
#[no_mangle]
pub unsafe extern "C" fn lzvolt_declared_size(src: *const u8, src_len: usize) -> i64 {
let Some(input) = as_slice(src, src_len) else {
return LZVOLT_E_NULL;
};
match format::declared_len(input) {
Ok(n) => n as i64,
Err(e) => code_for(e),
}
}
#[no_mangle]
pub unsafe extern "C" fn lzvolt_decompress(
src: *const u8,
src_len: usize,
dst: *mut u8,
dst_cap: usize,
) -> i64 {
let Some(input) = as_slice(src, src_len) else {
return LZVOLT_E_NULL;
};
let Some(out) = as_slice_mut(dst, dst_cap) else {
return LZVOLT_E_NULL;
};
match format::unpack_into_slice(input, out) {
Ok(n) => n as i64,
Err(e) => code_for(e),
}
}
#[no_mangle]
pub unsafe extern "C" fn lzvolt_decompress_lz4(
src: *const u8,
src_len: usize,
dst: *mut u8,
dst_cap: usize,
declared: usize,
) -> i64 {
let Some(block) = as_slice(src, src_len) else {
return LZVOLT_E_NULL;
};
let Some(out) = as_slice_mut(dst, dst_cap) else {
return LZVOLT_E_NULL;
};
if out.len() < declared {
return LZVOLT_E_OUTPUT_TOO_SMALL;
}
SCRATCH.with(|cell| {
let mut buf = cell.borrow_mut();
match format::unpack_into(block, &mut buf, declared) {
Ok(()) => {
out[..buf.len()].copy_from_slice(&buf);
buf.len() as i64
}
Err(e) => code_for(e),
}
})
}
#[no_mangle]
pub extern "C" fn lzvolt_backend() -> *const c_char {
let s: &'static std::ffi::CStr = match crate::backend() {
"aarch64 assembly" => c"aarch64 assembly",
"x86-64 assembly" => c"x86-64 assembly",
"neon intrinsics" => c"neon intrinsics",
"sse2 intrinsics" => c"sse2 intrinsics",
_ => c"scalar",
};
s.as_ptr()
}
#[no_mangle]
pub extern "C" fn lzvolt_version() -> *const c_char {
concat!(env!("CARGO_PKG_VERSION"), "\0").as_ptr() as *const c_char
}
#[no_mangle]
pub extern "C" fn lzvolt_strerror(code: i64) -> *const c_char {
let s: &'static std::ffi::CStr = match code {
LZVOLT_NOT_COMPRESSIBLE => c"not compressible; store the bytes as they are",
LZVOLT_E_NULL => c"null pointer with a non-zero length",
LZVOLT_E_TRUNCATED => c"packed value ends mid-field",
LZVOLT_E_BAD_OFFSET => c"backward reference points before the output",
LZVOLT_E_LENGTH_MISMATCH => c"packed value does not produce its declared length",
LZVOLT_E_TOO_LARGE => c"packed value declares an implausible length",
LZVOLT_E_NON_CANONICAL => c"header is longer than its length needs",
LZVOLT_E_OUTPUT_TOO_SMALL => c"output buffer is smaller than the declared length",
_ => c"unknown error code",
};
s.as_ptr()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_c_entry_points_round_trip() {
let data: Vec<u8> = (0..4096u32)
.map(|i| b"the quick brown fox "[(i % 20) as usize])
.collect();
let mut packed = vec![0u8; lzvolt_compress_bound(data.len())];
let n = unsafe {
lzvolt_compress(data.as_ptr(), data.len(), packed.as_mut_ptr(), packed.len())
};
assert!(n > 0, "compress returned {n}");
let n = n as usize;
let declared = unsafe { lzvolt_declared_size(packed.as_ptr(), n) };
assert_eq!(declared, data.len() as i64);
let mut out = vec![0u8; lzvolt_decompress_bound(data.len())];
let got = unsafe { lzvolt_decompress(packed.as_ptr(), n, out.as_mut_ptr(), out.len()) };
assert_eq!(got, data.len() as i64);
assert_eq!(&out[..data.len()], &data[..]);
}
#[test]
fn the_c_entry_points_refuse_rather_than_crash() {
let mut dst = [0u8; 64];
assert_eq!(
unsafe { lzvolt_decompress(std::ptr::null(), 8, dst.as_mut_ptr(), dst.len()) },
LZVOLT_E_NULL
);
assert_eq!(
unsafe { lzvolt_compress(std::ptr::null(), 8, dst.as_mut_ptr(), dst.len()) },
LZVOLT_E_NULL
);
assert_eq!(
unsafe { lzvolt_decompress(dst.as_ptr(), 4, std::ptr::null_mut(), 8) },
LZVOLT_E_NULL
);
let r = unsafe { lzvolt_declared_size(std::ptr::null(), 0) };
assert_eq!(r, LZVOLT_E_TRUNCATED);
let data = vec![b'z'; 512];
let mut packed = vec![0u8; lzvolt_compress_bound(data.len())];
let n = unsafe {
lzvolt_compress(data.as_ptr(), data.len(), packed.as_mut_ptr(), packed.len())
} as usize;
let mut small = vec![0u8; data.len() - 1];
assert_eq!(
unsafe { lzvolt_decompress(packed.as_ptr(), n, small.as_mut_ptr(), small.len()) },
LZVOLT_E_OUTPUT_TOO_SMALL
);
let mut cramped = [0u8; 4];
assert_eq!(
unsafe {
lzvolt_compress(
data.as_ptr(),
data.len(),
cramped.as_mut_ptr(),
cramped.len(),
)
},
LZVOLT_E_OUTPUT_TOO_SMALL
);
}
#[test]
fn the_c_compressor_says_no_the_way_c_expects() {
let mut state = 0x9E37_79B9_7F4A_7C15u64;
let noise: Vec<u8> = (0..4096)
.map(|_| {
state ^= state << 13;
state ^= state >> 7;
state ^= state << 17;
state as u8
})
.collect();
let mut out = vec![0u8; lzvolt_compress_bound(noise.len())];
let n =
unsafe { lzvolt_compress(noise.as_ptr(), noise.len(), out.as_mut_ptr(), out.len()) };
assert_eq!(n, LZVOLT_NOT_COMPRESSIBLE);
}
#[test]
fn the_c_strings_are_nul_terminated() {
let v = unsafe { std::ffi::CStr::from_ptr(lzvolt_version()) };
assert_eq!(v.to_str().unwrap(), env!("CARGO_PKG_VERSION"));
let b = unsafe { std::ffi::CStr::from_ptr(lzvolt_backend()) };
assert_eq!(b.to_str().unwrap(), crate::backend());
for code in [
LZVOLT_NOT_COMPRESSIBLE,
LZVOLT_E_NULL,
LZVOLT_E_TRUNCATED,
LZVOLT_E_BAD_OFFSET,
LZVOLT_E_LENGTH_MISMATCH,
LZVOLT_E_TOO_LARGE,
LZVOLT_E_NON_CANONICAL,
LZVOLT_E_OUTPUT_TOO_SMALL,
-999,
] {
let s = unsafe { std::ffi::CStr::from_ptr(lzvolt_strerror(code)) };
assert!(!s.to_bytes().is_empty(), "no text for {code}");
}
}
}