sark-http 0.40.0

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

use o3::{
    alloc,
    buffer::{
        self,
        pool::{self, state},
    },
};

use crate::payload::{
    compress::{Backing, Error, Frozen},
    crc32::Hasher,
};

const HEADER: [u8; 10] = [0x1f, 0x8b, 8, 0, 0, 0, 0, 0, 0, 0xff];
const TRAILER: usize = 8;
const FRAMING: usize = HEADER.len() + TRAILER;

unsafe extern "C" {
    fn malloc(size: usize) -> *mut std::ffi::c_void;
    fn free(ptr: *mut std::ffi::c_void);
}

pub(super) struct Codec {
    compressor: NonNull<libdeflate_sys::libdeflate_compressor>,
    checksum: Hasher,
}

impl Codec {
    pub(super) fn try_new() -> Result<Self, alloc::Error> {
        let options = libdeflate_sys::libdeflate_options {
            sizeof_options: size_of::<libdeflate_sys::libdeflate_options>(),
            malloc_func: Some(malloc),
            free_func: Some(free),
        };
        // SAFETY: libdeflate copies the allocator pair and accepts level 1.
        let codec =
            NonNull::new(unsafe { libdeflate_sys::libdeflate_alloc_compressor_ex(1, &options) })
                .ok_or(alloc::Error::Exhausted)?;
        Ok(Self {
            compressor: codec,
            checksum: Hasher::new(),
        })
    }

    pub(super) fn encode(
        &mut self,
        pool: &mut pool::Pool<state::Initialized, Backing>,
        src: &[u8],
        maximum: usize,
    ) -> Result<Frozen, Error> {
        let mut lease = pool.acquire().ok_or(Error::Exhausted)?;
        let mut output: buffer::raw::Output<'_, _> = (&mut lease).into();
        let (header, body) = output.as_mut_slice()[..maximum].split_at_mut(HEADER.len());
        // SAFETY: this worker owns the compressor and the input and output are disjoint.
        // Both callers reserve the trailer inside this fixed slot.
        let wrote = unsafe {
            libdeflate_sys::libdeflate_deflate_compress(
                self.compressor.as_ptr(),
                src.as_ptr().cast(),
                src.len(),
                body.as_mut_ptr().cast(),
                body.len() - TRAILER,
            )
        };
        let wrote = num::NonZero::new(wrote).ok_or(Error::Output { capacity: maximum })?;
        header.copy_from_slice(&HEADER);
        let mut checksum = self.checksum.clone();
        checksum.update(src);
        // SAFETY: a nonzero native result fits the supplied room, leaving eight bytes.
        let trailer = unsafe { body.get_unchecked_mut(wrote.get()..wrote.get() + TRAILER) };
        trailer[..4].copy_from_slice(&checksum.finalize().to_le_bytes());
        trailer[4..].copy_from_slice(&(src.len() as u32).to_le_bytes());
        // SAFETY: header, native output and trailer are initialized in this slot.
        unsafe { output.complete(num::NonZero::new_unchecked(wrote.get() + FRAMING)) };
        Ok(Frozen(lease.freeze()))
    }
}

impl Drop for Codec {
    fn drop(&mut self) {
        // SAFETY: this is the unique pointer returned by alloc_compressor_ex.
        unsafe { libdeflate_sys::libdeflate_free_compressor(self.compressor.as_ptr()) };
    }
}