Skip to main content

sark_http/field/
mod.rs

1#[doc(hidden)]
2pub mod base64;
3pub mod date;
4pub mod head;
5pub mod metadata;
6pub mod raw;
7pub mod scan;
8pub mod storage;
9pub mod text;
10
11use std::{convert::Infallible, iter::Copied, marker::PhantomData, slice};
12
13pub use storage::{Name, Value};
14pub type Lower<T> = storage::Lower<T, ()>;
15
16/// Requires successful field admission at compile time.
17/// Invalid input fails during constant evaluation.
18#[macro_export]
19macro_rules! field_literal {
20    ($value:expr $(,)?) => {
21        const {
22            match $value {
23                ::core::result::Result::Ok(value) => value,
24                ::core::result::Result::Err(_) => ::core::panic!("literal"),
25            }
26        }
27    };
28}
29
30use metadata::map::record;
31use storage::encoded;
32
33pub use crate::field_literal as literal;
34use crate::payload::response::{headers::Application, status};
35
36#[derive(Clone, Copy, Debug, PartialEq, Eq)]
37pub enum Error {
38    Empty,
39    InvalidByte { index: usize, byte: u8 },
40}
41
42/// Compression permission retained with one HTTP field line.
43#[repr(u8)]
44#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
45pub enum Indexing {
46    #[default]
47    Allowed,
48    Never,
49}
50
51impl Indexing {
52    pub(in crate::field) const fn from_byte(value: u8) -> Option<Self> {
53        match value {
54            0 => Some(Self::Allowed),
55            1 => Some(Self::Never),
56            _ => None,
57        }
58    }
59
60    pub(in crate::field) const fn from_never(never: bool) -> Self {
61        if never { Self::Never } else { Self::Allowed }
62    }
63}
64
65/// Writes one generated field value into its protocol encoder.
66pub trait Writer {
67    fn write_byte(&mut self, byte: u8);
68
69    fn write_slice(&mut self, bytes: &[u8]);
70}
71
72/// A generated field value with an exact encoded length.
73pub trait Encode: encoded::Encoded {
74    fn encoded_len(&self) -> usize;
75
76    /// Stops at the first rejected fragment and preserves its exact error.
77    fn try_write<E>(self, emit: impl FnMut(&[u8]) -> Result<(), E>) -> Result<(), E>;
78
79    fn encode(self, out: &mut impl Writer)
80    where
81        Self: Sized,
82    {
83        match self.try_write(|bytes| {
84            out.write_slice(bytes);
85            Ok::<_, Infallible>(())
86        }) {
87            Ok(()) => {}
88            Err(never) => match never {},
89        }
90    }
91}
92
93/// Receives one synchronous semantic field plan without staging storage.
94pub trait Sink<'field, Scope: Copy = ()> {
95    fn entry(&mut self, field: Entry<'field, Scope>);
96
97    /// Emits a preencoded group while retaining each field's indexing policy.
98    fn group(&mut self, group: &Group<'field, Scope>) {
99        for entry in group.entries() {
100            self.entry(*entry);
101        }
102    }
103
104    fn field(&mut self, name: storage::Lower<&'field [u8], Scope>, value: Value<&'field [u8]>) {
105        self.entry(Entry::new(name, value));
106    }
107
108    fn encoded_with<E: Encode>(
109        &mut self,
110        name: storage::Lower<&'field [u8], Scope>,
111        value: E,
112        indexing: Indexing,
113    );
114
115    /// Emits a newly generated value with indexing permitted.
116    fn generated<E: Encode>(&mut self, name: storage::Lower<&'field [u8], Scope>, value: E) {
117        self.encoded_with(name, value, Indexing::Allowed);
118    }
119}
120
121/// Borrows and synchronously emits one semantic field plan.
122pub trait Source<Scope: Copy = ()> {
123    fn emit<'field>(&'field self, sink: &mut impl Sink<'field, Scope>);
124}
125
126/// Borrows the exact bytes of a typed outgoing field value.
127pub trait AsValue {
128    fn as_value(&self) -> Value<&[u8]>;
129}
130
131impl<T: storage::Bytes> AsValue for Value<T> {
132    fn as_value(&self) -> Value<&[u8]> {
133        Value(self.0.as_bytes())
134    }
135}
136
137impl<T: storage::Bytes> Encode for Value<T> {
138    fn encoded_len(&self) -> usize {
139        self.as_bytes().len()
140    }
141
142    fn try_write<E>(self, mut emit: impl FnMut(&[u8]) -> Result<(), E>) -> Result<(), E> {
143        let Self(owner) = self;
144        emit(owner.as_bytes())
145    }
146}
147
148impl<W: Writer + ?Sized> Writer for &mut W {
149    fn write_byte(&mut self, byte: u8) {
150        (**self).write_byte(byte);
151    }
152
153    fn write_slice(&mut self, bytes: &[u8]) {
154        (**self).write_slice(bytes);
155    }
156}
157
158impl<Scope: Copy, S: Source<Scope> + ?Sized> Source<Scope> for &S {
159    fn emit<'field>(&'field self, sink: &mut impl Sink<'field, Scope>) {
160        (**self).emit(sink);
161    }
162}
163
164impl<Scope: Copy> Source<Scope> for [Entry<'_, Scope>] {
165    fn emit<'field>(&'field self, sink: &mut impl Sink<'field, Scope>) {
166        for field in self {
167            sink.entry(*field);
168        }
169    }
170}
171
172impl<Scope: Copy, const N: usize> Source<Scope> for [Entry<'_, Scope>; N] {
173    fn emit<'field>(&'field self, sink: &mut impl Sink<'field, Scope>) {
174        self.as_slice().emit(sink);
175    }
176}
177
178impl<Scope: Copy> Source<Scope> for Vec<Entry<'_, Scope>> {
179    fn emit<'field>(&'field self, sink: &mut impl Sink<'field, Scope>) {
180        self.as_slice().emit(sink);
181    }
182}
183
184impl<'entry, 'value, Scope: Copy> Source<Scope>
185    for Copied<slice::Iter<'entry, Entry<'value, Scope>>>
186where
187    'value: 'entry,
188{
189    fn emit<'field>(&'field self, sink: &mut impl Sink<'field, Scope>) {
190        for field in self.clone() {
191            sink.entry(field);
192        }
193    }
194}
195
196impl<'entry, 'value, Scope: Copy> Source<Scope> for slice::Iter<'entry, Entry<'value, Scope>>
197where
198    'value: 'entry,
199{
200    fn emit<'field>(&'field self, sink: &mut impl Sink<'field, Scope>) {
201        for field in self.clone() {
202            sink.entry(*field);
203        }
204    }
205}
206
207impl Source<Application> for () {
208    fn emit<'field>(&'field self, _: &mut impl Sink<'field, Application>) {}
209}
210
211pub(crate) fn trim_ows_start(mut value: &[u8]) -> &[u8] {
212    while let [b' ' | b'\t', rest @ ..] = value {
213        value = rest;
214    }
215    value
216}
217
218impl Error {
219    pub fn trim_ows(value: &[u8]) -> &[u8] {
220        let mut value = trim_ows_start(value);
221        while matches!(value.last(), Some(b' ' | b'\t')) {
222            value = &value[..value.len() - 1];
223        }
224        value
225    }
226
227    pub const fn name(name: &[u8]) -> Result<(), Self> {
228        if name.is_empty() {
229            return Err(Self::Empty);
230        }
231        let mut index = 0;
232        while index < name.len() {
233            let byte = name[index];
234            if !Self::is_name_byte(byte) {
235                return Err(Self::InvalidByte { index, byte });
236            }
237            index += 1;
238        }
239        Ok(())
240    }
241
242    pub const fn is_name_byte(byte: u8) -> bool {
243        byte.is_ascii_alphanumeric()
244            | (byte == b'!')
245            | (byte.wrapping_sub(b'#') <= b'\'' - b'#')
246            | (byte.wrapping_sub(b'*') <= b'+' - b'*')
247            | (byte.wrapping_sub(b'-') <= b'.' - b'-')
248            | (byte.wrapping_sub(b'^') <= b'`' - b'^')
249            | (byte == b'|')
250            | (byte == b'~')
251    }
252
253    pub const fn value(value: &[u8]) -> Result<(), Self> {
254        let mut index = 0;
255        while index < value.len() {
256            let byte = value[index];
257            if !Self::is_text(byte) {
258                return Err(Self::InvalidByte { index, byte });
259            }
260            index += 1;
261        }
262        Ok(())
263    }
264
265    pub const fn is_text(byte: u8) -> bool {
266        ((byte >= 0x20) & (byte != 0x7f)) | (byte == b'\t')
267    }
268}
269
270/// HTTP/2 and HTTP/3 response fields prefixed by `:status`.
271pub struct Response<F> {
272    value: Value<[u8; 3]>,
273    fields: F,
274}
275
276impl<F> Response<F> {
277    pub const fn new(status: status::Code, fields: F) -> Self {
278        Self {
279            value: Value(status.as_bytes()),
280            fields,
281        }
282    }
283}
284
285impl<F: Source<Application>> Source for Response<F> {
286    fn emit<'field>(&'field self, sink: &mut impl Sink<'field>) {
287        sink.entry(Entry::pseudo(Pseudo::Status, self.value.borrow()));
288        self.fields.emit(sink);
289    }
290}
291
292/// One admitted HTTP field whose borrowed bytes cannot change during emission.
293#[derive(Clone, Copy, Debug, PartialEq, Eq)]
294#[repr(transparent)]
295pub struct Entry<'a, Scope = ()>(record::Entry<'a>, PhantomData<fn() -> Scope>);
296
297/// A pseudo-field supported by HTTP/2 and HTTP/3.
298#[derive(Clone, Copy, Debug, PartialEq, Eq)]
299pub enum Pseudo {
300    Method,
301    Scheme,
302    Authority,
303    Path,
304    Protocol,
305    Status,
306}
307
308impl<'a> Entry<'a> {
309    pub(in crate::field) const fn from_record(field: record::Entry<'a>) -> Self {
310        Self(field, PhantomData)
311    }
312
313    pub const fn pseudo(name: Pseudo, value: Value<&'a [u8]>) -> Self {
314        let name = match name {
315            Pseudo::Method => b":method".as_slice(),
316            Pseudo::Scheme => b":scheme".as_slice(),
317            Pseudo::Authority => b":authority".as_slice(),
318            Pseudo::Path => b":path".as_slice(),
319            Pseudo::Protocol => b":protocol".as_slice(),
320            Pseudo::Status => b":status".as_slice(),
321        };
322        Self::from_record(record::Entry::new(name, value.0))
323    }
324}
325
326impl<'a, Scope> Entry<'a, Scope> {
327    pub const fn new(name: storage::Lower<&'a [u8], Scope>, value: Value<&'a [u8]>) -> Self {
328        Self(record::Entry::new(name.get(), value.0), PhantomData)
329    }
330
331    pub const fn with_index(self, indexing: Indexing) -> Self {
332        Self(self.0.with_index(indexing), PhantomData)
333    }
334
335    pub const fn name(self) -> &'a [u8] {
336        self.0.name
337    }
338
339    pub const fn value(self) -> Value<&'a [u8]> {
340        Value(self.0.value)
341    }
342
343    pub const fn indexing(self) -> Indexing {
344        self.0.indexing
345    }
346
347    pub const fn as_record(&self) -> record::Entry<'a> {
348        self.0
349    }
350}
351
352/// Immutable fields paired with their exact name/value line encoding.
353#[derive(Clone, Copy, Debug, PartialEq, Eq)]
354pub struct Group<'a, Scope = ()> {
355    entries: &'a [Entry<'a, Scope>],
356    wire: &'a [u8],
357}
358
359/// The first byte where a field sequence and its wire encoding differ.
360#[derive(Clone, Copy, Debug, PartialEq, Eq)]
361pub struct Mismatch {
362    pub offset: usize,
363    pub expected: Option<u8>,
364    pub actual: Option<u8>,
365}
366
367struct Cursor<'a> {
368    wire: &'a [u8],
369    offset: usize,
370}
371
372impl<'a, Scope: Copy> Group<'a, Scope> {
373    pub const fn try_new(
374        entries: &'a [Entry<'a, Scope>],
375        wire: &'a [u8],
376    ) -> Result<Self, Mismatch> {
377        let mut cursor = Cursor { wire, offset: 0 };
378        let mut index = 0;
379        while index < entries.len() {
380            let entry = entries[index];
381            let parts = [entry.name(), b": ", entry.value().get(), b"\r\n"];
382            let mut part = 0;
383            while part < parts.len() {
384                if let Err(error) = cursor.check(parts[part]) {
385                    return Err(error);
386                }
387                part += 1;
388            }
389            index += 1;
390        }
391        if let Some((&actual, _)) = cursor.wire.split_first() {
392            return Err(Mismatch {
393                offset: cursor.offset,
394                expected: None,
395                actual: Some(actual),
396            });
397        }
398        Ok(Self { entries, wire })
399    }
400
401    pub const fn entries(&self) -> &'a [Entry<'a, Scope>] {
402        self.entries
403    }
404
405    pub const fn wire(&self) -> &'a [u8] {
406        self.wire
407    }
408}
409
410impl<Scope: Copy> Source<Scope> for Group<'_, Scope> {
411    fn emit<'field>(&'field self, sink: &mut impl Sink<'field, Scope>) {
412        sink.group(self);
413    }
414}
415
416impl<'field, S: Sink<'field>> Sink<'field, Application> for S {
417    fn entry(&mut self, entry: Entry<'field, Application>) {
418        Sink::entry(self, Entry::from_record(entry.0));
419    }
420
421    fn encoded_with<E: Encode>(
422        &mut self,
423        name: storage::Lower<&'field [u8], Application>,
424        value: E,
425        indexing: Indexing,
426    ) {
427        Sink::encoded_with(self, name.into_inner(), value, indexing);
428    }
429}
430
431impl Cursor<'_> {
432    const fn check(&mut self, expected: &[u8]) -> Result<(), Mismatch> {
433        let mut index = 0;
434        while index < expected.len() {
435            let byte = expected[index];
436            let (actual, rest) = match self.wire.split_first() {
437                Some((&actual, rest)) => (Some(actual), rest),
438                None => (None, self.wire),
439            };
440            if !matches!(actual, Some(actual) if actual == byte) {
441                return Err(Mismatch {
442                    offset: self.offset,
443                    expected: Some(byte),
444                    actual,
445                });
446            }
447            self.wire = rest;
448            self.offset += 1;
449            index += 1;
450        }
451        Ok(())
452    }
453}