crates/kleene-graph/src/slices/frame.rs
//! Zstandard frames by mzstd (safe Rust): one frame per piece of a set that travels. The
//! same calls, level and limits the workspace's `zstd` shim makes, so the bytes are the same
//! as when kleene-graph called the shim; kleene-graph names no `zstd` package (a crate of
//! that name would bring the C library to a user without the shim's patch).
use std::io;
fn other(e: impl std::error::Error + Send + Sync + 'static) -> io::Error {
io::Error::other(e)
}
/// A compressor at one level, reused between calls.
pub(super) struct Compressor(mzstd::Compressor);
impl Compressor {
/// A compressor at `level`; a level mzstd does not have is refused.
pub(super) fn new(level: i32) -> io::Result<Self> {
let level = mzstd::Level::try_from(level).map_err(other)?;
mzstd::Compressor::new(mzstd::EncoderConfig::default().with_level(level))
.map(Self)
.map_err(other)
}
/// `source` as one Zstandard frame.
pub(super) fn compress(&mut self, source: &[u8]) -> io::Result<Vec<u8>> {
self.0.compress(source).map_err(other)
}
/// [`Compressor::compress`] appended to `out` (a vector with room allocates nothing);
/// the frame's length.
pub(super) fn compress_append(
&mut self,
source: &[u8],
out: &mut Vec<u8>,
) -> io::Result<usize> {
self.0
.compress_into(source, out)
.map(|r| r.len())
.map_err(other)
}
}
/// A decoder refusing more than `capacity` bytes of content.
fn decoder(capacity: usize) -> mzstd::Decompressor {
let limits = mzstd::DecodeLimits::DEFAULT.with_max_output_bytes(Some(capacity as u64));
mzstd::Decompressor::new(mzstd::DecoderConfig::default().with_limits(limits))
}
/// The frames in `source`, refused when they hold more than `capacity` bytes.
pub(super) fn decompress(source: &[u8], capacity: usize) -> io::Result<Vec<u8>> {
decoder(capacity).decompress(source).map_err(other)
}
/// A decompressor that keeps its decoder between calls of the same capacity.
#[derive(Default)]
pub(super) struct Decompressor {
/// The kept decoder, with its output limit.
kept: Option<(usize, mzstd::Decompressor)>,
}
impl Decompressor {
/// The frames in `source` appended to `out`, refused when they hold more than
/// `capacity` bytes; the decoder is kept for the next call of the same capacity (a
/// vector with room allocates nothing). Their content's length.
pub(super) fn decompress_append(
&mut self,
source: &[u8],
capacity: usize,
out: &mut Vec<u8>,
) -> io::Result<usize> {
if self.kept.as_ref().is_none_or(|k| k.0 != capacity) {
self.kept = Some((capacity, decoder(capacity)));
}
let (_, d) = self.kept.as_mut().expect("kept above");
d.decompress_into(source, out)
.map(|r| r.len())
.map_err(other)
}
}