sark-http 0.40.0

HTTP wire types, semantics, codecs, and ownership invariants for Sark
Documentation
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() }>>;

/// Compression storage selected when constructing a protocol connection.
pub trait Compression: Sized {
    fn try_new() -> Result<Self, alloc::Error>;

    /// Returns a smaller gzip body or keeps the original bytes unchanged.
    fn encode(&mut self, bytes: &[u8]) -> Option<Frozen>;

    fn try_encode(&mut self, bytes: &[u8]) -> Result<Frozen, Error>;
}

/// A completed gzip member retaining its original output slot.
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);
}

/// Level 1 closes nonfinal blocks at 65,535 bytes or 8,192 matches of at least four bytes.
/// At most eight blocks and three extra stored chunks fit with framing in one slot.
const MAX_INPUT: usize = 262_035;
/// libdeflate 1.27 at level 1 emits stored blocks through 51 bytes.
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)
    }
}