sark-http 0.40.0

HTTP wire types, semantics, codecs, and ownership invariants for Sark
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
#[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::{borrow::Borrow, iter::Copied, marker::PhantomData, slice};

use o3::buffer::write;

pub use storage::{Name, Value};
pub type Lower<T> = storage::Lower<T, ()>;

/// Requires successful field admission at compile time.
/// Invalid input fails during constant evaluation.
#[macro_export]
macro_rules! 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::literal;
use crate::payload::{
    compress::dynamic,
    response::{
        headers::{self, Application, Group},
        status,
    },
};

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Error {
    Empty,
    InvalidByte { index: usize, byte: u8 },
}

/// Compression permission retained with one HTTP field line.
#[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,
        }
    }
}

/// A generated field value with an exact encoded length.
pub trait Encode: encoded::Encoded {
    fn encoded_len(&self) -> usize;

    /// Stops at the first rejected fragment and preserves its exact error.
    fn try_write<W: write::Sink>(self, out: &mut W) -> Result<(), W::Error>;
}

pub trait Constant<Scope: Copy = ()> {
    const ENTRY: Entry<'static, Scope>;
}

pub trait Origin: Copy {
    const FIELD: Option<Entry<'static>>;
    fn record(&self) -> record::Entry<'_>;
}

impl Origin for record::Entry<'_> {
    const FIELD: Option<Entry<'static>> = None;
    fn record(&self) -> record::Entry<'_> {
        *self
    }
}

impl<C: Constant> Origin for PhantomData<C> {
    const FIELD: Option<Entry<'static>> = Some(C::ENTRY);
    fn record(&self) -> record::Entry<'_> {
        C::ENTRY.as_record()
    }
}

struct Wire<C>(PhantomData<fn() -> C>);

impl<C: Constant<Application>> Constant for Wire<C> {
    const ENTRY: Entry<'static> = Entry::from_record(C::ENTRY.as_record());
}

/// Receives one synchronous semantic field plan without staging storage.
pub trait Sink<'field, Scope: Copy = ()>: Sized {
    type Error;

    fn entry(self, field: Entry<'field, Scope>) -> Result<Self, Self::Error>;

    fn constant<C: Constant<Scope>>(self) -> Result<Self, Self::Error> {
        self.entry(C::ENTRY)
    }

    fn declared<D: headers::Fields>(
        self,
    ) -> Result<Self, <Self as Sink<'field, Application>>::Error>
    where
        Self: Sink<'field, Application>,
    {
        <Self as Sink<'field, Application>>::group(self, &D::FIELDS)
    }

    /// Emits a preencoded group while retaining each field's indexing policy.
    fn group<'group: 'field, G: Borrow<Group<'group, Scope>> + ?Sized>(
        mut self,
        group: &G,
    ) -> Result<Self, Self::Error>
    where
        Scope: 'group,
    {
        let group: &Group<'group, Scope> = group.borrow();
        for entry in group.entries() {
            self = self.entry(*entry)?;
        }
        Ok(self)
    }

    fn field(
        self,
        name: storage::Lower<&'field [u8], Scope>,
        value: Value<&'field [u8]>,
    ) -> Result<Self, Self::Error> {
        self.entry(Entry::new(name, value))
    }

    fn encoded_with<E: Encode>(
        self,
        name: storage::Lower<&'field [u8], Scope>,
        value: E,
        indexing: Indexing,
    ) -> Result<Self, Self::Error>;

    /// Emits a newly generated value with indexing permitted.
    fn generated<E: Encode>(
        self,
        name: storage::Lower<&'field [u8], Scope>,
        value: E,
    ) -> Result<Self, Self::Error> {
        self.encoded_with(name, value, Indexing::Allowed)
    }
}

/// Borrows and synchronously emits one semantic field plan.
pub trait Source<Scope: Copy = ()> {
    const SECTION_SIZE: Option<usize> = None;

    fn emit<'field, Out: Sink<'field, Scope>>(&'field self, sink: Out) -> Result<Out, Out::Error>;
}

/// HTTP/2 and HTTP/3 fields prefixed by the selected status.
pub struct Response<F, S = [u8; 3]> {
    status: S,
    fields: F,
}

impl<F> Response<F> {
    pub const fn new(status: status::Code, fields: F) -> Self {
        Self {
            status: status.as_bytes(),
            fields,
        }
    }

    pub(crate) fn declared<S: status::Constant>(fields: F) -> Response<F, PhantomData<fn() -> S>> {
        Response {
            status: PhantomData,
            fields,
        }
    }
}

impl<F: Source<Application>, S> Response<F, S> {
    const SIZE: Option<usize> = match F::SECTION_SIZE {
        Some(fields) => fields.checked_add(b":status".len() + 3 + dynamic::ENTRY_OVERHEAD),
        None => None,
    };
}

impl<F: Source<Application>> Source for Response<F> {
    const SECTION_SIZE: Option<usize> = Self::SIZE;

    fn emit<'field, Out: Sink<'field>>(&'field self, sink: Out) -> Result<Out, Out::Error> {
        self.fields
            .emit(sink.entry(Entry::pseudo(Pseudo::Status, Value(&self.status)))?)
    }
}

impl<F, S: status::Constant> Constant for Response<F, PhantomData<fn() -> S>> {
    const ENTRY: Entry<'static> =
        Entry::pseudo(Pseudo::Status, Value(&const { S::CODE.as_bytes() }));
}

impl<F: Source<Application>, S: status::Constant> Source for Response<F, PhantomData<fn() -> S>> {
    const SECTION_SIZE: Option<usize> = Self::SIZE;

    fn emit<'field, Out: Sink<'field>>(&'field self, sink: Out) -> Result<Out, Out::Error> {
        self.fields.emit(sink.constant::<Self>()?)
    }
}

/// Borrows the exact bytes of a typed outgoing field value.
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 {
    const SECTION_SIZE: Option<usize> = S::SECTION_SIZE;

    fn emit<'field, Out: Sink<'field, Scope>>(&'field self, sink: Out) -> Result<Out, Out::Error> {
        (**self).emit(sink)
    }
}

impl<Scope: Copy, A: Source<Scope>, B: Source<Scope>> Source<Scope> for (A, B) {
    fn emit<'field, Out: Sink<'field, Scope>>(&'field self, sink: Out) -> Result<Out, Out::Error> {
        let sink = self.0.emit(sink)?;
        self.1.emit(sink)
    }
}

impl<Scope: Copy> Source<Scope> for Option<Entry<'_, Scope>> {
    fn emit<'field, Out: Sink<'field, Scope>>(&'field self, sink: Out) -> Result<Out, Out::Error> {
        self.as_slice().emit(sink)
    }
}

impl<Scope: Copy> Source<Scope> for [Entry<'_, Scope>] {
    fn emit<'field, Out: Sink<'field, Scope>>(
        &'field self,
        mut sink: Out,
    ) -> Result<Out, Out::Error> {
        for field in self {
            sink = sink.entry(*field)?;
        }
        Ok(sink)
    }
}

impl<Scope: Copy, const N: usize> Source<Scope> for [Entry<'_, Scope>; N] {
    fn emit<'field, Out: Sink<'field, Scope>>(&'field self, sink: Out) -> Result<Out, Out::Error> {
        self.as_slice().emit(sink)
    }
}

impl<Scope: Copy> Source<Scope> for Vec<Entry<'_, Scope>> {
    fn emit<'field, Out: Sink<'field, Scope>>(&'field self, sink: Out) -> Result<Out, Out::Error> {
        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, Out: Sink<'field, Scope>>(
        &'field self,
        mut sink: Out,
    ) -> Result<Out, Out::Error> {
        for field in self.clone() {
            sink = sink.entry(field)?;
        }
        Ok(sink)
    }
}

impl<'entry, 'value, Scope: Copy> Source<Scope> for slice::Iter<'entry, Entry<'value, Scope>>
where
    'value: 'entry,
{
    fn emit<'field, Out: Sink<'field, Scope>>(
        &'field self,
        mut sink: Out,
    ) -> Result<Out, Out::Error> {
        for field in self.clone() {
            sink = sink.entry(*field)?;
        }
        Ok(sink)
    }
}

impl Source<Application> for () {
    const SECTION_SIZE: Option<usize> = Some(0);

    fn emit<'field, Out: Sink<'field, Application>>(
        &'field self,
        sink: Out,
    ) -> Result<Out, Out::Error> {
        Ok(sink)
    }
}

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')
    }
}

/// One admitted HTTP field whose borrowed bytes cannot change during emission.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(transparent)]
pub struct Entry<'a, Scope = ()>(record::Entry<'a>, PhantomData<fn() -> Scope>);

/// A pseudo-field supported by HTTP/2 and HTTP/3.
#[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 fn content_length_in(value: u64, digits: &'a mut std::fmt::NumBuffer<u64>) -> Self {
        Self::from_record(record::Entry::new(
            head::Name::ContentLength.wire(),
            value.format_into(digits).as_bytes(),
        ))
    }

    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
    }
}

impl<'field, S: Sink<'field>> Sink<'field, Application> for S {
    type Error = <S as Sink<'field>>::Error;

    fn constant<C: Constant<Application>>(self) -> Result<Self, <S as Sink<'field>>::Error> {
        <S as Sink<'field>>::constant::<Wire<C>>(self)
    }

    fn declared<D: headers::Fields>(self) -> Result<Self, <S as Sink<'field, Application>>::Error> {
        D::emit(self)
    }

    fn entry(self, entry: Entry<'field, Application>) -> Result<Self, <S as Sink<'field>>::Error> {
        Sink::entry(self, Entry::from_record(entry.0))
    }

    fn encoded_with<E: Encode>(
        self,
        name: storage::Lower<&'field [u8], Application>,
        value: E,
        indexing: Indexing,
    ) -> Result<Self, <S as Sink<'field>>::Error> {
        Sink::encoded_with(self, name.into_inner(), value, indexing)
    }
}