sark-http 0.40.0

HTTP wire types, semantics, codecs, and ownership invariants for Sark
Documentation
use crate::{
    field::metadata::{
        block, packed,
        section::{rules, state::decode::Head},
    },
    request::{Error, Layout, Source, checked_span},
};

/// A layout validated against the immutable owner carried with it.
pub struct Bound<O> {
    pub(super) owner: O,
    pub(super) layout: Layout,
}

impl<O> Bound<O> {
    pub fn into_parts(self) -> (O, Layout) {
        (self.owner, self.layout)
    }
}

impl<O: Source> Bound<O> {
    pub fn try_bind(owner: O, layout: Layout) -> Result<Self, Error> {
        if !layout.is_valid(owner.as_ref()) {
            return Err(Error::InvalidRange);
        }
        Ok(Self { owner, layout })
    }
}

impl TryFrom<Head<rules::RetainRaw>> for Bound<packed::Decoded> {
    type Error = Error;

    fn try_from(head: Head<rules::RetainRaw>) -> Result<Self, Error> {
        let (owner, _, plan) = head.into_parts();
        let (mut path, mut path_len, mut pseudo, mut host) = (None, None, None, None);
        for (field, range) in owner.ranges() {
            match field.name {
                b":path" => {
                    let value = field.value;
                    path = Some(range);
                    path_len = if value == b"*" {
                        None
                    } else {
                        Some(value.iter().position(|&b| b == b'?').unwrap_or(value.len()))
                    };
                }
                b":authority" => pseudo = Some(range),
                b"host" => host = Some(range),
                _ => {}
            }
        }
        let layout = Layout::from_spans(
            checked_span(path)?,
            path_len,
            checked_span(pseudo)?,
            checked_span(host)?,
            plan,
        )?;
        if plan.form() == block::Form::Asterisk && path_len.is_some() {
            return Err(Error::InvalidRange);
        }
        Ok(Self { owner, layout })
    }
}