sark-http 0.40.0

HTTP wire types, semantics, codecs, and ownership invariants for Sark
Documentation
use o3::alloc::{self, array};

use crate::uri::target::{self, Absolute, Error, Head, Slash, Target};
use std::num::NonZero;

/// An admitted owned target whose canonical bytes are materialized on consumption.
/// Admission keeps the original buffer and checks every grammar and offset bound.
pub struct Plan {
    pub(super) value: String,
    pub(super) layout: Layout,
}

pub(super) struct Layout {
    pub(super) edit: Edit,
    pub(super) buffer: array::Plan<u8, usize>,
    pub(super) head: Head,
    pub(super) path_end: u32,
}

#[derive(Clone, Copy)]
pub(super) enum Edit {
    Keep,
    Slash,
    Http,
}

impl Layout {
    pub(super) fn parse(value: &str) -> Result<Self, Error> {
        let parsed = Absolute::parse(value)?;
        let origin = parsed.origin();
        let scheme = parsed.scheme().len();
        let end = value.len() - origin.value.len();
        let host = scheme + 3 + parsed.authority().host().len();
        let path = end.checked_add(origin.path_end()).ok_or(Error::Length)?;
        let head = Head::new(NonZero::new(target::narrow(scheme)?), host, end)?;
        let path_end = target::narrow(path)?;
        let (edit, extra) = match origin.slash {
            Slash::Present => (Edit::Keep, 0),
            Slash::Insert => (Edit::Slash, 1),
        };
        Self::new(edit, head, path_end, value.len() + extra)
    }

    fn new(edit: Edit, head: Head, path_end: u32, capacity: usize) -> Result<Self, Error> {
        let buffer = array::Plan::try_new(capacity).map_err(|alloc::Overflow| Error::Length)?;
        Ok(Self {
            edit,
            buffer,
            head,
            path_end,
        })
    }
}

impl Plan {
    pub fn parse(value: String) -> Result<Self, Error> {
        let layout = Layout::parse(&value)?;
        Ok(Self { value, layout })
    }

    /// Admits an HTTP authority with the root origin form.
    pub fn http(value: String) -> Result<Self, Error> {
        let parsed = target::authority(&value)?;
        let end = 7 + value.len();
        let capacity = end + 1;
        let head = Head::new(NonZero::new(4), 7 + parsed.host().len(), end)?;
        let layout = Layout::new(Edit::Http, head, target::narrow(capacity)?, capacity)?;
        Ok(Self { value, layout })
    }

    pub fn path(&self) -> &str {
        target::raw::planned_path(self)
    }

    /// Reuses an exact allocation and otherwise allocates the canonical bytes once.
    pub fn try_build(self) -> Result<Target, alloc::Exhausted> {
        target::raw::build(self)
    }
}