use std::marker::PhantomData;
use super::{dispatch, headers, status::Code};
use crate::{h1, payload};
pub trait Spec: Sized {
const STATUS: Code;
const FIELDS: headers::Group<'static>;
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<'req, 'd, D, S: Spec> dispatch::Response<'req, 'd, D> 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, Stream = dispatch::Never>>(
self,
writer: W,
) -> W::Done {
writer.fixed(S::STATUS, S::FIELDS, payload::fixed::Body::new(S::BODY))
}
}
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)
}
}