#[cfg(feature = "showcase-zram")]
pub mod zram {
use trueno_zram_core::{Algorithm, CompressorBuilder, PAGE_SIZE};
#[derive(Debug, Clone)]
pub struct ZramConfig {
pub algorithm: Algorithm,
pub adaptive: bool,
pub min_savings: f64,
}
impl Default for ZramConfig {
fn default() -> Self {
Self {
algorithm: Algorithm::Lz4,
adaptive: true,
min_savings: 0.1, }
}
}
#[derive(Debug, Clone)]
pub struct ZramResult {
pub original_size: usize,
pub compressed_size: usize,
pub ratio: f64,
pub algorithm: String,
pub zero_page: bool,
}
impl ZramResult {
#[must_use]
pub fn new(original: usize, compressed: usize, algo: &str, zero: bool) -> Self {
let ratio = if compressed > 0 {
original as f64 / compressed as f64
} else {
f64::INFINITY
};
Self {
original_size: original,
compressed_size: compressed,
ratio,
algorithm: algo.to_string(),
zero_page: zero,
}
}
}
pub fn compress_kv_page(
data: &[u8],
config: &ZramConfig,
) -> Result<(Vec<u8>, ZramResult), String> {
if data.len() != PAGE_SIZE {
return Err(format!(
"Data must be exactly {} bytes, got {}",
PAGE_SIZE,
data.len()
));
}
if data.iter().all(|&b| b == 0) {
return Ok((
vec![0u8; 4],
ZramResult::new(PAGE_SIZE, 4, "same-fill", true),
));
}
let page_array: &[u8; PAGE_SIZE] = data
.try_into()
.map_err(|_| "Failed to convert slice to page array")?;
let compressor = CompressorBuilder::new()
.algorithm(config.algorithm)
.build()
.map_err(|e| format!("Failed to create compressor: {e}"))?;
let compressed = compressor
.compress(page_array)
.map_err(|e| format!("Compression failed: {e}"))?;
let algo_name = match config.algorithm {
Algorithm::None => "none",
Algorithm::Lz4 => "lz4",
Algorithm::Lz4Hc => "lz4hc",
Algorithm::Zstd { .. } => "zstd",
Algorithm::Adaptive => "adaptive",
};
let result = ZramResult::new(PAGE_SIZE, compressed.data.len(), algo_name, false);
Ok((compressed.data.clone(), result))
}
pub use trueno_zram_core::{Algorithm as ZramAlgorithm, PAGE_SIZE as ZRAM_PAGE_SIZE};
}
#[cfg(not(feature = "showcase-zram"))]
pub mod zram {
#[derive(Debug, Clone)]
pub struct ZramConfig {
pub algorithm: String,
pub adaptive: bool,
pub min_savings: f64,
}
impl Default for ZramConfig {
fn default() -> Self {
Self {
algorithm: "lz4".to_string(),
adaptive: true,
min_savings: 0.1,
}
}
}
#[derive(Debug, Clone)]
pub struct ZramResult {
pub original_size: usize,
pub compressed_size: usize,
pub ratio: f64,
pub zero_page: bool,
}
}
#[cfg(test)]
mod tests;