use std::{num, ops::Deref};
use o3::{
alloc,
buffer::{
self,
pool::{self, owners, state},
},
};
#[doc(hidden)]
pub mod dynamic;
mod ffi;
pub mod inflate;
type Backing = owners::Plain<pool::Fixed<{ Gzip::SLOTS.get() }, { Gzip::CAPACITY.get() }>>;
pub trait Compression: Sized {
fn try_new() -> Result<Self, alloc::Error>;
fn encode(&mut self, bytes: &[u8]) -> Option<Frozen>;
fn try_encode(&mut self, bytes: &[u8]) -> Result<Frozen, Error>;
}
pub struct Frozen(pool::Span<Backing, pool::Owned, pool::Frozen>);
impl Deref for Frozen {
type Target = [u8];
fn deref(&self) -> &[u8] {
self.0.as_ref()
}
}
impl buffer::Residency for Frozen {
fn resident(&self) -> usize {
self.0.resident()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Error {
Unavailable,
Input { actual: usize, limit: usize },
Exhausted,
Output { capacity: usize },
}
pub struct Gzip {
pool: pool::Pool<state::Initialized, Backing>,
codec: ffi::Codec,
}
impl Gzip {
pub const SLOTS: num::NonZero<usize> = num::NonZero::<usize>::MIN.saturating_add(31);
pub const CAPACITY: num::NonZero<usize> =
num::NonZero::<usize>::MIN.saturating_add(256 * 1024 - 1);
}
const MAX_INPUT: usize = 262_035;
const MIN_COMPRESSIBLE: usize = 52;
impl Compression for Gzip {
fn try_new() -> Result<Self, alloc::Error> {
Ok(Self {
pool: pool::Pool::try_from(pool::Fixed::new())?,
codec: ffi::Codec::try_new()?,
})
}
fn encode(&mut self, src: &[u8]) -> Option<Frozen> {
if !(MIN_COMPRESSIBLE..=MAX_INPUT).contains(&src.len()) {
return None;
}
self.codec.encode(&mut self.pool, src, src.len() - 1).ok()
}
fn try_encode(&mut self, src: &[u8]) -> Result<Frozen, Error> {
if src.len() > MAX_INPUT {
return Err(Error::Input {
actual: src.len(),
limit: MAX_INPUT,
});
}
self.codec.encode(&mut self.pool, src, Self::CAPACITY.get())
}
}
impl Compression for () {
fn try_new() -> Result<Self, alloc::Error> {
Ok(())
}
fn encode(&mut self, _: &[u8]) -> Option<Frozen> {
None
}
fn try_encode(&mut self, _: &[u8]) -> Result<Frozen, Error> {
Err(Error::Unavailable)
}
}