#[doc(hidden)]
pub mod base64;
pub mod date;
pub mod head;
pub mod metadata;
pub mod raw;
pub mod scan;
pub mod storage;
pub mod text;
use std::{iter::Copied, marker::PhantomData, slice};
use o3::buffer::write;
pub use storage::{Name, Value};
pub type Lower<T> = storage::Lower<T, ()>;
#[macro_export]
macro_rules! field_literal {
($value:expr $(,)?) => {
const {
match $value {
::core::result::Result::Ok(value) => value,
::core::result::Result::Err(_) => ::core::panic!("literal"),
}
}
};
}
use metadata::map::record;
use storage::encoded;
pub use crate::field_literal as literal;
use crate::payload::response::{headers::Application, status};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Error {
Empty,
InvalidByte { index: usize, byte: u8 },
}
#[repr(u8)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Indexing {
#[default]
Allowed,
Never,
}
impl Indexing {
pub(in crate::field) const fn from_byte(value: u8) -> Option<Self> {
match value {
0 => Some(Self::Allowed),
1 => Some(Self::Never),
_ => None,
}
}
pub(in crate::field) const fn from_never(never: bool) -> Self {
if never { Self::Never } else { Self::Allowed }
}
}
pub trait Encode: encoded::Encoded {
fn encoded_len(&self) -> usize;
fn try_write<W: write::Sink>(self, out: &mut W) -> Result<(), W::Error>;
}
pub trait Sink<'field, Scope: Copy = ()> {
fn entry(&mut self, field: Entry<'field, Scope>);
fn group(&mut self, group: &Group<'field, Scope>) {
for entry in group.entries() {
self.entry(*entry);
}
}
fn field(&mut self, name: storage::Lower<&'field [u8], Scope>, value: Value<&'field [u8]>) {
self.entry(Entry::new(name, value));
}
fn encoded_with<E: Encode>(
&mut self,
name: storage::Lower<&'field [u8], Scope>,
value: E,
indexing: Indexing,
);
fn generated<E: Encode>(&mut self, name: storage::Lower<&'field [u8], Scope>, value: E) {
self.encoded_with(name, value, Indexing::Allowed);
}
}
pub trait Source<Scope: Copy = ()> {
fn emit<'field>(&'field self, sink: &mut impl Sink<'field, Scope>);
}
pub trait AsValue {
fn as_value(&self) -> Value<&[u8]>;
}
impl<T: storage::Bytes> AsValue for Value<T> {
fn as_value(&self) -> Value<&[u8]> {
Value(self.0.as_bytes())
}
}
impl<T: storage::Bytes> Encode for Value<T> {
fn encoded_len(&self) -> usize {
self.as_bytes().len()
}
fn try_write<W: write::Sink>(self, out: &mut W) -> Result<(), W::Error> {
let Self(owner) = self;
out.write_slice(owner.as_bytes())
}
}
impl<Scope: Copy, S: Source<Scope> + ?Sized> Source<Scope> for &S {
fn emit<'field>(&'field self, sink: &mut impl Sink<'field, Scope>) {
(**self).emit(sink);
}
}
impl<Scope: Copy, A: Source<Scope>, B: Source<Scope>> Source<Scope> for (A, B) {
fn emit<'field>(&'field self, sink: &mut impl Sink<'field, Scope>) {
self.0.emit(sink);
self.1.emit(sink);
}
}
impl<Scope: Copy> Source<Scope> for Option<Entry<'_, Scope>> {
fn emit<'field>(&'field self, sink: &mut impl Sink<'field, Scope>) {
self.as_slice().emit(sink);
}
}
impl<Scope: Copy> Source<Scope> for [Entry<'_, Scope>] {
fn emit<'field>(&'field self, sink: &mut impl Sink<'field, Scope>) {
for field in self {
sink.entry(*field);
}
}
}
impl<Scope: Copy, const N: usize> Source<Scope> for [Entry<'_, Scope>; N] {
fn emit<'field>(&'field self, sink: &mut impl Sink<'field, Scope>) {
self.as_slice().emit(sink);
}
}
impl<Scope: Copy> Source<Scope> for Vec<Entry<'_, Scope>> {
fn emit<'field>(&'field self, sink: &mut impl Sink<'field, Scope>) {
self.as_slice().emit(sink);
}
}
impl<'entry, 'value, Scope: Copy> Source<Scope>
for Copied<slice::Iter<'entry, Entry<'value, Scope>>>
where
'value: 'entry,
{
fn emit<'field>(&'field self, sink: &mut impl Sink<'field, Scope>) {
for field in self.clone() {
sink.entry(field);
}
}
}
impl<'entry, 'value, Scope: Copy> Source<Scope> for slice::Iter<'entry, Entry<'value, Scope>>
where
'value: 'entry,
{
fn emit<'field>(&'field self, sink: &mut impl Sink<'field, Scope>) {
for field in self.clone() {
sink.entry(*field);
}
}
}
impl Source<Application> for () {
fn emit<'field>(&'field self, _: &mut impl Sink<'field, Application>) {}
}
pub(crate) fn trim_ows_start(mut value: &[u8]) -> &[u8] {
while let [b' ' | b'\t', rest @ ..] = value {
value = rest;
}
value
}
impl Error {
pub fn trim_ows(value: &[u8]) -> &[u8] {
let mut value = trim_ows_start(value);
while matches!(value.last(), Some(b' ' | b'\t')) {
value = &value[..value.len() - 1];
}
value
}
pub const fn name(name: &[u8]) -> Result<(), Self> {
if name.is_empty() {
return Err(Self::Empty);
}
let mut index = 0;
while index < name.len() {
let byte = name[index];
if !Self::is_name_byte(byte) {
return Err(Self::InvalidByte { index, byte });
}
index += 1;
}
Ok(())
}
pub const fn is_name_byte(byte: u8) -> bool {
byte.is_ascii_alphanumeric()
| (byte == b'!')
| (byte.wrapping_sub(b'#') <= b'\'' - b'#')
| (byte.wrapping_sub(b'*') <= b'+' - b'*')
| (byte.wrapping_sub(b'-') <= b'.' - b'-')
| (byte.wrapping_sub(b'^') <= b'`' - b'^')
| (byte == b'|')
| (byte == b'~')
}
pub const fn value(value: &[u8]) -> Result<(), Self> {
let mut index = 0;
while index < value.len() {
let byte = value[index];
if !Self::is_text(byte) {
return Err(Self::InvalidByte { index, byte });
}
index += 1;
}
Ok(())
}
pub const fn is_text(byte: u8) -> bool {
((byte >= 0x20) & (byte != 0x7f)) | (byte == b'\t')
}
}
pub struct Response<F> {
value: Value<[u8; 3]>,
fields: F,
}
impl<F> Response<F> {
pub const fn new(status: status::Code, fields: F) -> Self {
Self {
value: Value(status.as_bytes()),
fields,
}
}
}
impl<F: Source<Application>> Source for Response<F> {
fn emit<'field>(&'field self, sink: &mut impl Sink<'field>) {
sink.entry(Entry::pseudo(Pseudo::Status, self.value.borrow()));
self.fields.emit(sink);
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(transparent)]
pub struct Entry<'a, Scope = ()>(record::Entry<'a>, PhantomData<fn() -> Scope>);
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Pseudo {
Method,
Scheme,
Authority,
Path,
Protocol,
Status,
}
impl<'a> Entry<'a> {
pub const fn content_length<const N: usize>() -> Entry<'static> {
let digits = &const { crate::h1::codec::numbers::decimal_length(N) };
Entry::from_record(record::Entry::new(
head::Name::ContentLength.wire(),
digits.0.split_at(digits.1).1,
))
}
pub(in crate::field) const fn from_record(field: record::Entry<'a>) -> Self {
Self(field, PhantomData)
}
pub const fn pseudo(name: Pseudo, value: Value<&'a [u8]>) -> Self {
let name = match name {
Pseudo::Method => b":method".as_slice(),
Pseudo::Scheme => b":scheme".as_slice(),
Pseudo::Authority => b":authority".as_slice(),
Pseudo::Path => b":path".as_slice(),
Pseudo::Protocol => b":protocol".as_slice(),
Pseudo::Status => b":status".as_slice(),
};
Self::from_record(record::Entry::new(name, value.0))
}
}
impl<'a, Scope> Entry<'a, Scope> {
pub const fn new(name: storage::Lower<&'a [u8], Scope>, value: Value<&'a [u8]>) -> Self {
Self(record::Entry::new(name.get(), value.0), PhantomData)
}
pub const fn with_index(self, indexing: Indexing) -> Self {
Self(self.0.with_index(indexing), PhantomData)
}
pub const fn name(self) -> &'a [u8] {
self.0.name
}
pub const fn value(self) -> Value<&'a [u8]> {
Value(self.0.value)
}
pub const fn indexing(self) -> Indexing {
self.0.indexing
}
pub const fn as_record(&self) -> record::Entry<'a> {
self.0
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Group<'a, Scope = ()> {
entries: &'a [Entry<'a, Scope>],
wire: &'a [u8],
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Mismatch {
pub offset: usize,
pub expected: Option<u8>,
pub actual: Option<u8>,
}
struct Cursor<'a> {
wire: &'a [u8],
offset: usize,
}
impl<'a, Scope: Copy> Group<'a, Scope> {
pub const fn try_new(
entries: &'a [Entry<'a, Scope>],
wire: &'a [u8],
) -> Result<Self, Mismatch> {
let mut cursor = Cursor { wire, offset: 0 };
let mut index = 0;
while index < entries.len() {
let entry = entries[index];
let parts = [entry.name(), b": ", entry.value().get(), b"\r\n"];
let mut part = 0;
while part < parts.len() {
if let Err(error) = cursor.check(parts[part]) {
return Err(error);
}
part += 1;
}
index += 1;
}
if let Some((&actual, _)) = cursor.wire.split_first() {
return Err(Mismatch {
offset: cursor.offset,
expected: None,
actual: Some(actual),
});
}
Ok(Self { entries, wire })
}
pub const fn entries(&self) -> &'a [Entry<'a, Scope>] {
self.entries
}
pub const fn wire(&self) -> &'a [u8] {
self.wire
}
}
impl<Scope: Copy> Source<Scope> for Group<'_, Scope> {
fn emit<'field>(&'field self, sink: &mut impl Sink<'field, Scope>) {
sink.group(self);
}
}
impl<'field, S: Sink<'field>> Sink<'field, Application> for S {
fn entry(&mut self, entry: Entry<'field, Application>) {
Sink::entry(self, Entry::from_record(entry.0));
}
fn encoded_with<E: Encode>(
&mut self,
name: storage::Lower<&'field [u8], Application>,
value: E,
indexing: Indexing,
) {
Sink::encoded_with(self, name.into_inner(), value, indexing);
}
}
impl Cursor<'_> {
const fn check(&mut self, expected: &[u8]) -> Result<(), Mismatch> {
let mut index = 0;
while index < expected.len() {
let byte = expected[index];
let (actual, rest) = match self.wire.split_first() {
Some((&actual, rest)) => (Some(actual), rest),
None => (None, self.wire),
};
if !matches!(actual, Some(actual) if actual == byte) {
return Err(Mismatch {
offset: self.offset,
expected: Some(byte),
actual,
});
}
self.wire = rest;
self.offset += 1;
index += 1;
}
Ok(())
}
}