sark-http 0.39.0

HTTP wire types, semantics, codecs, and ownership invariants for Sark
Documentation
use std::num;

use miniz_oxide::deflate::core::{
    CompressorOxide, TDEFLFlush, TDEFLStatus, compress, create_comp_flags_from_zip_params,
};
use o3::{
    alloc,
    buffer::pool::{self, owners, state},
};

use crate::payload::crc32::Hasher;

#[doc(hidden)]
pub mod dynamic;
pub mod inflate;

/// Fixed gzip member framing: a 10-byte header and an 8-byte trailer.
const HEADER: usize = 10;
const TRAILER: usize = 8;
const FRAMING: usize = HEADER + TRAILER;
const MAX_INPUT: usize = {
    let mut len = Gzip::CAPACITY.get();
    while HEADER + len + (len >> 12) + (len >> 14) + (len >> 25) + 13 + TRAILER
        > Gzip::CAPACITY.get()
    {
        len -= 1;
    }
    len
};

/// Compression level handed to deflate within its closed 1..=10 range.
const LEVEL: i32 = 3;

/// 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]) -> Output;

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

#[doc(hidden)]
pub type Frozen = pool::Span<
    owners::Plain<pool::Fixed<{ Gzip::SLOTS.get() }, { Gzip::CAPACITY.get() }>>,
    pool::Owned,
    pool::Frozen,
>;

pub enum Output {
    Plain,
    Compressed(Frozen),
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Error {
    Unavailable,
    Input {
        actual: usize,
        limit: usize,
    },
    Exhausted,
    Deflate {
        status: TDEFLStatus,
        read: usize,
        wrote: usize,
    },
    Extent {
        wrote: usize,
        capacity: usize,
        maximum: usize,
    },
}

pub struct Gzip {
    compressor: Box<CompressorOxide>,
    checksum: Hasher,
    pool: pool::Pool<
        state::Initialized,
        owners::Plain<pool::Fixed<{ Gzip::SLOTS.get() }, { Gzip::CAPACITY.get() }>>,
    >,
}

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);

    fn try_compress(&mut self, src: &[u8], maximum: usize) -> Result<Frozen, Error> {
        let mut lease = self.pool.acquire().ok_or(Error::Exhausted)?;
        let mut output = lease.output();
        let capacity = output.len();
        let bytes = output.as_mut_slice();
        let room = capacity.checked_sub(FRAMING).ok_or(Error::Extent {
            wrote: 0,
            capacity,
            maximum,
        })?;
        self.compressor.reset();
        let (status, read, wrote) = compress(
            &mut self.compressor,
            src,
            &mut bytes[HEADER..HEADER + room],
            TDEFLFlush::Finish,
        );
        if status != TDEFLStatus::Done || read != src.len() {
            return Err(Error::Deflate {
                status,
                read,
                wrote,
            });
        }
        let written = wrote
            .checked_add(FRAMING)
            .filter(|written| *written <= capacity && *written <= maximum)
            .and_then(num::NonZero::new)
            .ok_or(Error::Extent {
                wrote,
                capacity,
                maximum,
            })?;
        bytes[..HEADER].copy_from_slice(&[0x1f, 0x8b, 0x08, 0, 0, 0, 0, 0, 0, 0xff]);
        let end = written.get() - TRAILER;
        let mut checksum = self.checksum.clone();
        checksum.update(src);
        bytes[end..end + 4].copy_from_slice(&checksum.finalize().to_le_bytes());
        // SAFETY: written bounds this unchanged output and includes the eight-byte trailer.
        unsafe { bytes.get_unchecked_mut(end + 4..written.get()) }
            .copy_from_slice(&(src.len() as u32).to_le_bytes());
        // SAFETY: deflate reported a complete stream and the exact nonzero extent
        // was bounded above while this output stayed borrowed by its owner.
        unsafe { output.complete(written) };
        Ok(lease.freeze())
    }
}

impl Compression for Gzip {
    fn try_new() -> Result<Self, alloc::Error> {
        let flags = create_comp_flags_from_zip_params(LEVEL, 0, 0);
        let compressor = alloc::BoxExt::try_new(CompressorOxide::new(flags))?;
        let checksum = Hasher::new();
        let pool = pool::Pool::try_from(pool::Fixed::new())?;
        Ok(Self {
            compressor,
            checksum,
            pool,
        })
    }

    fn encode(&mut self, src: &[u8]) -> Output {
        if !(FRAMING + 1..=MAX_INPUT).contains(&src.len()) {
            return Output::Plain;
        }
        match self.try_compress(src, src.len() - 1) {
            Ok(frozen) => Output::Compressed(frozen),
            Err(_) => Output::Plain,
        }
    }

    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.try_compress(src, Self::CAPACITY.get())
    }
}

impl Compression for () {
    fn try_new() -> Result<Self, alloc::Error> {
        Ok(())
    }

    fn encode(&mut self, _: &[u8]) -> Output {
        Output::Plain
    }

    fn try_encode(&mut self, _: &[u8]) -> Result<Frozen, Error> {
        Err(Error::Unavailable)
    }
}