sark-http 0.40.0

HTTP wire types, semantics, codecs, and ownership invariants for Sark
Documentation
use std::marker::PhantomData;

use super::{
    dispatch, headers,
    status::{self, Code},
};
use crate::{h1, payload};

/// An input-independent response whose fields and body are admitted constants.
pub trait Spec: headers::Fields {
    const STATUS: Code;
    const BODY: &'static [u8];
    const HEAD: Head<Reply<Self>>;
}

pub struct Reply<D>(PhantomData<fn() -> D>);

impl<D: Spec> Reply<D> {
    pub const VALUE: Self = Self(PhantomData);
}

impl<S: Spec> status::Constant for Reply<S> {
    const CODE: Code = S::STATUS;
}

impl<'req, 'd, Ranges: Copy + 'd, D, S: Spec> dispatch::Emit<'req, 'd, D, Ranges> for Reply<S> {
    type Kind = dispatch::Sync;
    type Stream = dispatch::Never;
    type Bound = o3::buffer::resident::bound::Unbounded;
    const BODY: payload::Kind = payload::Kind::Inline;
    const DECLARED: Option<Head<Self>> = Some(S::HEAD);

    fn consume<W: dispatch::Transaction<'req, 'd, dispatch::Never, Ranges>>(
        self,
        writer: W,
    ) -> W::Done {
        writer.fixed::<Self, _, _>((), PhantomData::<S>, payload::fixed::Body::new(S::BODY))
    }
}

/// Immutable HTTP/1 framing for the exact declared reply.
pub struct Head<R> {
    status: Code,
    prefix: &'static [u8],
    body: &'static [u8],
    reply: PhantomData<fn() -> R>,
}

impl<D: Spec> Head<Reply<D>> {
    const LENGTH: ([u8; 20], usize) = h1::codec::numbers::decimal_length(D::BODY.len());
    const PARTS: [&'static [u8]; 9] = [
        b" ",
        &D::STATUS.as_bytes(),
        b" ",
        match D::STATUS.reason() {
            Some(reason) => reason.as_bytes(),
            None => b"",
        },
        b"\r\n",
        D::FIELDS.wire(),
        h1::CONTENT_LENGTH,
        Self::LENGTH.0.split_at(Self::LENGTH.1).1,
        b"\r\n",
    ];
    pub const LEN: usize = {
        let mut len = 0;
        let mut i = 0;
        while i < Self::PARTS.len() {
            len += Self::PARTS[i].len();
            i += 1;
        }
        len
    };

    pub const fn new<const N: usize>() -> Self {
        let bytes = &const {
            assert!(N == Self::LEN, "length");
            let mut bytes = [0; N];
            let mut rest = bytes.as_mut_slice();
            let mut i = 0;
            while i < Self::PARTS.len() {
                let part = Self::PARTS[i];
                let (dst, next) = rest.split_at_mut(part.len());
                dst.copy_from_slice(part);
                rest = next;
                i += 1;
            }
            bytes
        };
        Self {
            status: D::STATUS,
            prefix: bytes,
            body: D::BODY,
            reply: PhantomData,
        }
    }
}

impl<R> Head<R> {
    pub fn parts(&self) -> (Code, &'static [u8], &'static [u8]) {
        (self.status, self.prefix, self.body)
    }
}