sark-http 0.40.0

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

use crate::{field::metadata::map::record::Span, payload::response};

pub mod buffer;
mod gate;
mod name;
mod plan;
mod scan;
pub mod table;
mod value;

pub use gate::{Gate, initial::Initial};
pub use name::Name;
pub use plan::Plan;
pub use scan::Scan;
pub use value::Value;

/// Message framing values admitted before the immutable field section is published.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Framing {
    length: u64,
    status: Option<NonZero<u16>>,
    method: Option<response::Method>,
    present: bool,
}

impl Framing {
    pub const fn content_length(self) -> Option<u64> {
        if self.present {
            Some(self.length)
        } else {
            None
        }
    }

    pub const fn status(self) -> Option<NonZero<u16>> {
        self.status
    }

    pub const fn method(self) -> Option<response::Method> {
        self.method
    }

    /// Carries the admitted message framing into incremental content accounting.
    pub fn content(self, method: response::Method) -> Result<(Content, u64), ContentError> {
        let length = self.content_length();
        if let Some(status) = self.status {
            match response::Content::new(method, status.get()) {
                response::Content::Tunnel => return Ok((Content::Tunnel, 0)),
                response::Content::Forbidden => {
                    if let Some(length) = length {
                        return Err(ContentError::ForbiddenLength { length });
                    }
                    return Ok((Content::Empty, 0));
                }
                response::Content::Suppressed => return Ok((Content::Empty, 0)),
                response::Content::Empty => {
                    if let Some(length) = length.filter(|&length| length != 0) {
                        return Err(ContentError::NonemptyLength { length });
                    }
                    return Ok((Content::Exact, 0));
                }
                response::Content::Allowed => {}
            }
        } else if self.method == Some(response::Method::Connect) {
            return Ok((Content::Tunnel, 0));
        }
        Ok(match length {
            Some(length) => (Content::Exact, length),
            None => (Content::Unbounded, 0),
        })
    }
}

/// Content mode kept separately from the remaining count to preserve compact stream state.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Content {
    #[default]
    Unbounded,
    Exact,
    Empty,
    Tunnel,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ContentError {
    ForbiddenLength { length: u64 },
    NonemptyLength { length: u64 },
    Exceeded { remaining: u64, actual: usize },
    Incomplete { remaining: u64 },
    Trailers,
}

impl Content {
    pub fn receive(
        self,
        remaining: u64,
        bytes: usize,
        finished: bool,
    ) -> Result<u64, ContentError> {
        let next = match self {
            Self::Unbounded | Self::Tunnel => return Ok(remaining),
            Self::Empty if bytes == 0 => return Ok(0),
            Self::Empty => {
                return Err(ContentError::Exceeded {
                    remaining: 0,
                    actual: bytes,
                });
            }
            Self::Exact => remaining
                .checked_sub(bytes as u64)
                .ok_or(ContentError::Exceeded {
                    remaining,
                    actual: bytes,
                })?,
        };
        if finished && next != 0 {
            return Err(ContentError::Incomplete { remaining: next });
        }
        Ok(next)
    }

    pub fn trailers(self, remaining: u64) -> Result<(), ContentError> {
        match self {
            Self::Unbounded => Ok(()),
            Self::Exact if remaining == 0 => Ok(()),
            Self::Exact => Err(ContentError::Incomplete { remaining }),
            Self::Empty | Self::Tunnel => Err(ContentError::Trailers),
        }
    }
}

const _: () = {
    assert!(core::mem::size_of::<Framing>() == 16);
    assert!(core::mem::size_of::<Option<Framing>>() == 16);
};

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Outcome<C> {
    Initial(C),
    Other,
    Rejected(Validation),
}

impl<C> Outcome<C> {
    const fn other(check: Validation) -> Self {
        match check {
            Validation::Valid => Self::Other,
            error => Self::Rejected(error),
        }
    }

    pub const fn validation(&self) -> Validation {
        match self {
            Self::Initial(_) | Self::Other => Validation::Valid,
            Self::Rejected(check) => *check,
        }
    }

    pub fn into_parts(self) -> (Option<C>, Validation) {
        match self {
            Self::Initial(control) => (Some(control), Validation::Valid),
            Self::Other => (None, Validation::Valid),
            Self::Rejected(check) => (None, check),
        }
    }
}

/// A classification bound to the immutable bytes that established it.
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct Named<'a> {
    span: Span<'a>,
    proof: Name,
}

impl<'a> Named<'a> {
    pub fn from_span(span: Span<'a>) -> Self {
        Self::from_scanned(span, Name::from_span(span))
    }

    pub const fn from_slice(bytes: &'a [u8]) -> Self {
        Self::from_scanned(Span::from_slice(bytes), Name::classify(bytes))
    }

    pub(crate) const fn from_scanned(span: Span<'a>, proof: Name) -> Self {
        Self { span, proof }
    }

    pub const fn span(self) -> Span<'a> {
        self.span
    }

    pub const fn proof(self) -> Name {
        self.proof
    }
}

/// Value bytes with their retained admission verdict.
/// A rejected source field remains rejected when its value is reused.
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct Valued<'a> {
    span: Span<'a>,
    validation: Validation,
}

impl<'a> Valued<'a> {
    pub fn from_span(span: Span<'a>) -> Self {
        Self::from_scanned(span, Value::from_span(span).finish())
    }

    pub(crate) const fn from_scanned(span: Span<'a>, check: Validation) -> Self {
        Self {
            span,
            validation: check,
        }
    }

    pub const fn span(self) -> Span<'a> {
        self.span
    }

    pub const fn validation(self) -> Validation {
        self.validation
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum Kind {
    Initial,
    Trailers,
    PushPromise,
}

/// Extended CONNECT capability advertised by the peer.
#[derive(Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum Connect {
    Disabled,
    Enabled,
}

/// Header validation rules selected by the wire protocol.
#[derive(Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum Version {
    Two,
    Three,
}

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[repr(u8)]
pub enum Validation {
    Valid,
    Malformed,
    RejectPush,
}

/// The message phase established by a valid compressed response status.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Response {
    Informational,
    Final,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum Form {
    Path,
    Asterisk,
    Connect,
    ExtendedConnect,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum Authority {
    None,
    Pseudo,
    Host,
    Target,
}

const _: () = {
    assert!(core::mem::size_of::<Connect>() == core::mem::size_of::<bool>());
    assert!(core::mem::align_of::<Connect>() == core::mem::align_of::<bool>());
    assert!(core::mem::size_of::<Version>() == core::mem::size_of::<bool>());
    assert!(core::mem::align_of::<Version>() == core::mem::align_of::<bool>());
};