sark-http 0.40.0

HTTP wire types, semantics, codecs, and ownership invariants for Sark
Documentation
//! Admitted application response headers and their emission contract.

pub mod list;

pub use list::List;

use std::marker::PhantomData;

use crate::{field, payload::compress::dynamic};

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Error {
    Managed,
    Syntax(field::Error),
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Application {}

pub type Name<T> = field::storage::Lower<T, Application>;
pub type Entry<'a> = field::Entry<'a, Application>;

/// Immutable fields paired with their exact name/value line encoding.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Group<'a, Scope = Application> {
    entries: &'a [field::Entry<'a, Scope>],
    wire: &'a [u8],
}

/// The first byte where a field sequence and its wire encoding differ.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Mismatch {
    pub offset: usize,
    pub expected: Option<u8>,
    pub actual: Option<u8>,
}

struct Cursor<'a> {
    wire: &'a [u8],
    offset: usize,
}

impl<'a, Scope: Copy> Group<'a, Scope> {
    pub const fn try_new(
        entries: &'a [field::Entry<'a, Scope>],
        wire: &'a [u8],
    ) -> Result<Self, Mismatch> {
        let mut cursor = Cursor { wire, offset: 0 };
        let mut index = 0;
        while index < entries.len() {
            let entry = entries[index];
            let parts = [entry.name(), b": ", entry.value().get(), b"\r\n"];
            let mut part = 0;
            while part < parts.len() {
                if let Err(error) = cursor.check(parts[part]) {
                    return Err(error);
                }
                part += 1;
            }
            index += 1;
        }
        if let Some((&actual, _)) = cursor.wire.split_first() {
            return Err(Mismatch {
                offset: cursor.offset,
                expected: None,
                actual: Some(actual),
            });
        }
        Ok(Self { entries, wire })
    }

    pub const fn entries(&self) -> &'a [field::Entry<'a, Scope>] {
        self.entries
    }

    pub const fn wire(&self) -> &'a [u8] {
        self.wire
    }

    pub const fn section_size(&self) -> Option<usize> {
        let extra = dynamic::ENTRY_OVERHEAD - b": \r\n".len();
        let Some(extra) = self.entries.len().checked_mul(extra) else {
            return None;
        };
        self.wire.len().checked_add(extra)
    }
}

impl Cursor<'_> {
    const fn check(&mut self, expected: &[u8]) -> Result<(), Mismatch> {
        let mut index = 0;
        while index < expected.len() {
            let byte = expected[index];
            let (actual, rest) = match self.wire.split_first() {
                Some((&actual, rest)) => (Some(actual), rest),
                None => (None, self.wire),
            };
            if !matches!(actual, Some(actual) if actual == byte) {
                return Err(Mismatch {
                    offset: self.offset,
                    expected: Some(byte),
                    actual,
                });
            }
            self.wire = rest;
            self.offset += 1;
            index += 1;
        }
        Ok(())
    }
}

pub trait Fields: Sized {
    const FIELDS: Group<'static>;

    fn emit<'field, Out: field::Sink<'field, Application>>(out: Out) -> Result<Out, Out::Error> {
        out.group(&Self::FIELDS)
    }
}

pub struct Line<D, const I: usize>(PhantomData<fn() -> D>);

impl<D: Fields, const I: usize> field::Constant<Application> for Line<D, I> {
    const ENTRY: Entry<'static> = D::FIELDS.entries()[I];
}

impl<D: Fields> field::Source<Application> for PhantomData<D> {
    const SECTION_SIZE: Option<usize> = D::FIELDS.section_size();

    fn emit<'field, Out: field::Sink<'field, Application>>(
        &'field self,
        out: Out,
    ) -> Result<Out, Out::Error> {
        field::Sink::<Application>::declared::<D>(out)
    }
}

impl<Scope: Copy> field::Source<Scope> for Group<'_, Scope> {
    fn emit<'field, Out: field::Sink<'field, Scope>>(
        &'field self,
        sink: Out,
    ) -> Result<Out, Out::Error> {
        sink.group(self)
    }
}