use crate::{Algorithm, Compression, Error, Sink};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Lz4 {
level: i64,
}
impl Lz4 {
pub const fn new() -> Self {
Lz4 { level: 0 }
}
pub const fn with_level(level: i64) -> Self {
Lz4 { level }
}
pub const fn level(&self) -> i64 {
self.level
}
pub fn set_level(&mut self, level: i64) -> Result<(), Error> {
if !(0..=12).contains(&level) {
return Err(Error::InvalidArgument("Level must be between 0 and 12".into()));
}
self.level = level;
Ok(())
}
pub const fn is_supported() -> bool {
cfg!(feature = "lz4")
}
pub fn compress_into<S: Sink + ?Sized>(&self, data: &[u8], out: &mut S) -> Result<(), Error> {
imp::compress(data, self.level, out)
}
pub fn decompress_into<S: Sink + ?Sized>(&self, data: &[u8], out: &mut S) -> Result<(), Error> {
imp::decompress(data, out)
}
}
impl Algorithm for Lz4 {
fn name(&self) -> &str {
Compression::LZ4
}
fn compress(&self, data: &[u8]) -> Result<Vec<u8>, Error> {
let mut out = Vec::new();
self.compress_into(data, &mut out)?;
Ok(out)
}
fn decompress(&self, data: &[u8]) -> Result<Vec<u8>, Error> {
let mut out = Vec::new();
self.decompress_into(data, &mut out)?;
Ok(out)
}
fn supported(&self) -> bool {
Self::is_supported()
}
}
#[cfg(feature = "lz4")]
mod imp {
use std::os::raw::{c_char, c_int};
use lz4_sys as l;
use crate::sink::{append, spare};
use crate::{Error, Sink};
const MAX_LEVEL: c_int = 12;
const MAX_RATIO: usize = 255;
const MARGIN: usize = 4096;
fn allocatable(size: usize) -> bool {
use std::alloc::{GlobalAlloc, Layout, System};
let Ok(layout) = Layout::from_size_align(size, 1) else { return false };
unsafe {
let block = System.alloc(layout);
if block.is_null() {
return false;
}
System.dealloc(block, layout);
}
true
}
fn data_error() -> Error {
Error::Codec("lz4_uncompress : data error".into())
}
fn input(data: &[u8]) -> *const c_char {
static BYTE: [u8; 1] = [0];
if data.is_empty() { BYTE.as_ptr().cast() } else { data.as_ptr().cast() }
}
pub(super) fn compress<S: Sink + ?Sized>(data: &[u8], level: i64, out: &mut S) -> Result<(), Error> {
let (len, level) = (data.len() as c_int, level as c_int);
let bound = unsafe { l::LZ4_compressBound(len) };
let size = bound as usize + 4;
let start = out.len();
if !out.grow(start + size) {
return Err(Error::Codec("lz4_compress : memory error".into()));
}
let (at, _) = spare(out);
let written = unsafe {
at.cast::<[u8; 4]>().write(len.to_le_bytes());
let block = at.add(4).cast::<c_char>();
match level {
0 => l::LZ4_compress_default(input(data), block, len, bound - 1),
1..=MAX_LEVEL => l::LZ4_compress_HC(input(data), block, len, bound - 1, level),
_ => {
return Err(Error::Codec(format!(
"lz4_compress: compression level ({level}) must be within 1..{MAX_LEVEL}"
)));
}
}
};
if written <= 0 {
return Err(Error::Codec("lz4_compress : data error".into()));
}
unsafe { out.set_len(start + 4 + written as usize) };
Ok(())
}
pub(super) fn decompress<S: Sink + ?Sized>(data: &[u8], out: &mut S) -> Result<(), Error> {
let len = data.len() as c_int;
let Some(prefix) = data.first_chunk::<4>().filter(|_| len >= 4) else {
return Err(data_error());
};
let size = i32::from_le_bytes(*prefix);
if size < 0 {
return Err(Error::Codec("lz4_uncompress : allocate size error".into()));
}
let block = &data[4..];
let capacity = (size as usize).min(block.len().saturating_mul(MAX_RATIO).saturating_add(MARGIN));
if capacity < size as usize && !allocatable(size.wrapping_add(1) as isize as usize) {
return Err(Error::Codec("lz4_uncompress : memory error".into()));
}
let decode = |at: *mut u8| {
unsafe { l::LZ4_decompress_safe(block.as_ptr().cast(), at.cast(), len - 4, capacity as c_int) }
};
let start = out.len();
if out.reserve(start + capacity) {
let (at, _) = spare(out);
let written = decode(at);
if written <= 0 {
return Err(data_error());
}
unsafe { out.set_len(start + written as usize) };
return Ok(());
}
let mut buffer = Vec::<u8>::new();
if buffer.try_reserve_exact(capacity).is_err() {
return Err(Error::Codec("lz4_uncompress : memory error".into()));
}
let written = decode(buffer.as_mut_ptr());
if written <= 0 {
return Err(data_error());
}
unsafe { buffer.set_len(written as usize) };
if !append(out, &buffer) {
return Err(Error::Codec("lz4_uncompress : memory error".into()));
}
Ok(())
}
}
#[cfg(not(feature = "lz4"))]
mod imp {
use crate::{Error, Sink};
pub(super) fn compress<S: Sink + ?Sized>(_: &[u8], _: i64, _: &mut S) -> Result<(), Error> {
Err(Error::undefined("lz4_compress"))
}
pub(super) fn decompress<S: Sink + ?Sized>(_: &[u8], _: &mut S) -> Result<(), Error> {
Err(Error::undefined("lz4_uncompress"))
}
}
#[cfg(all(test, feature = "lz4"))]
mod tests {
use super::*;
#[test]
fn levels() {
let mut lz4 = Lz4::new();
assert_eq!(lz4.set_level(13), Err(Error::InvalidArgument("Level must be between 0 and 12".into())));
let data = b"Lorem ipsum dolor sit amet ".repeat(500);
for level in 0..=12 {
lz4.set_level(level).unwrap();
assert_eq!(lz4.decompress(&lz4.compress(&data).unwrap()).unwrap(), data);
}
assert_eq!(
Lz4::with_level(13).compress(b"x"),
Err(Error::Codec("lz4_compress: compression level (13) must be within 1..12".into()))
);
}
#[test]
fn empty() {
let lz4 = Lz4::new();
assert_eq!(lz4.compress(b"").unwrap(), b"\0\0\0\0\0");
for level in 1..=12 {
assert_eq!(Lz4::with_level(level).compress(b"").unwrap(), b"\0\0\0\0\0");
}
assert_eq!(lz4.decompress(b"\0\0\0\0\0"), Err(Error::Codec("lz4_uncompress : data error".into())));
}
#[test]
fn prefixes() {
let lz4 = Lz4::new();
let body = lz4.compress(b"This is a demo string").unwrap();
assert_eq!(&body[..4], &21u32.to_le_bytes());
assert_eq!(lz4.decompress(b"abc"), Err(Error::Codec("lz4_uncompress : data error".into())));
assert_eq!(
lz4.decompress(b"\xff\xff\xff\xffabc"),
Err(Error::Codec("lz4_uncompress : allocate size error".into()))
);
let mut large = body.clone();
large[..4].copy_from_slice(&0x0fff_0000u32.to_le_bytes());
assert_eq!(lz4.decompress(&large).unwrap(), b"This is a demo string");
large[..4].copy_from_slice(&0x7fff_ffffu32.to_le_bytes());
assert_eq!(lz4.decompress(&large), Err(Error::Codec("lz4_uncompress : memory error".into())));
let mut small = body;
small[..4].copy_from_slice(&20u32.to_le_bytes());
assert_eq!(lz4.decompress(&small), Err(Error::Codec("lz4_uncompress : data error".into())));
assert_eq!(Lz4::with_level(1 << 32).compress(b"abc").unwrap(), lz4.compress(b"abc").unwrap());
}
}