Skip to main content

sark_http/payload/response/
declared.rs

1use std::marker::PhantomData;
2
3use super::{dispatch, headers, status::Code};
4use crate::{h1, payload};
5
6/// An input-independent response whose fields and body are admitted constants.
7pub trait Spec: Sized {
8    const STATUS: Code;
9    const FIELDS: headers::Group<'static>;
10    const BODY: &'static [u8];
11    const HEAD: Head<Reply<Self>>;
12}
13
14pub struct Reply<D>(PhantomData<fn() -> D>);
15
16impl<D: Spec> Reply<D> {
17    pub const VALUE: Self = Self(PhantomData);
18}
19
20impl<'req, 'd, D, S: Spec> dispatch::Response<'req, 'd, D> for Reply<S> {
21    type Kind = dispatch::Sync;
22    type Stream = dispatch::Never;
23    type Bound = o3::buffer::resident::bound::Unbounded;
24    const BODY: payload::Kind = payload::Kind::Inline;
25    const DECLARED: Option<Head<Self>> = Some(S::HEAD);
26
27    fn consume<W: dispatch::Transaction<'req, 'd, Stream = dispatch::Never>>(
28        self,
29        writer: W,
30    ) -> W::Done {
31        writer.fixed(S::STATUS, S::FIELDS, payload::fixed::Body::new(S::BODY))
32    }
33}
34
35/// Immutable HTTP/1 framing for the exact declared reply.
36pub struct Head<R> {
37    status: Code,
38    prefix: &'static [u8],
39    body: &'static [u8],
40    reply: PhantomData<fn() -> R>,
41}
42
43impl<D: Spec> Head<Reply<D>> {
44    const LENGTH: ([u8; 20], usize) = h1::codec::numbers::decimal_length(D::BODY.len());
45    const PARTS: [&'static [u8]; 9] = [
46        b" ",
47        &D::STATUS.as_bytes(),
48        b" ",
49        match D::STATUS.reason() {
50            Some(reason) => reason.as_bytes(),
51            None => b"",
52        },
53        b"\r\n",
54        D::FIELDS.wire(),
55        h1::CONTENT_LENGTH,
56        Self::LENGTH.0.split_at(Self::LENGTH.1).1,
57        b"\r\n",
58    ];
59    pub const LEN: usize = {
60        let mut len = 0;
61        let mut i = 0;
62        while i < Self::PARTS.len() {
63            len += Self::PARTS[i].len();
64            i += 1;
65        }
66        len
67    };
68
69    pub const fn new<const N: usize>() -> Self {
70        let bytes = &const {
71            assert!(N == Self::LEN, "length");
72            let mut bytes = [0; N];
73            let mut rest = bytes.as_mut_slice();
74            let mut i = 0;
75            while i < Self::PARTS.len() {
76                let part = Self::PARTS[i];
77                let (dst, next) = rest.split_at_mut(part.len());
78                dst.copy_from_slice(part);
79                rest = next;
80                i += 1;
81            }
82            bytes
83        };
84        Self {
85            status: D::STATUS,
86            prefix: bytes,
87            body: D::BODY,
88            reply: PhantomData,
89        }
90    }
91}
92
93impl<R> Head<R> {
94    pub fn parts(&self) -> (Code, &'static [u8], &'static [u8]) {
95        (self.status, self.prefix, self.body)
96    }
97}