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