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::{borrow::Borrow, iter::Copied, marker::PhantomData, slice};
12
13use o3::buffer::write;
14
15pub use storage::{Name, Value};
16pub type Lower<T> = storage::Lower<T, ()>;
17
18#[macro_export]
21macro_rules! literal {
22 ($value:expr $(,)?) => {
23 const {
24 match $value {
25 ::core::result::Result::Ok(value) => value,
26 ::core::result::Result::Err(_) => ::core::panic!("literal"),
27 }
28 }
29 };
30}
31
32use metadata::map::record;
33use storage::encoded;
34
35pub use crate::literal;
36use crate::payload::{
37 compress::dynamic,
38 response::{
39 headers::{self, Application, Group},
40 status,
41 },
42};
43
44#[derive(Clone, Copy, Debug, PartialEq, Eq)]
45pub enum Error {
46 Empty,
47 InvalidByte { index: usize, byte: u8 },
48}
49
50#[repr(u8)]
52#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
53pub enum Indexing {
54 #[default]
55 Allowed,
56 Never,
57}
58
59impl Indexing {
60 pub(in crate::field) const fn from_byte(value: u8) -> Option<Self> {
61 match value {
62 0 => Some(Self::Allowed),
63 1 => Some(Self::Never),
64 _ => None,
65 }
66 }
67}
68
69pub trait Encode: encoded::Encoded {
71 fn encoded_len(&self) -> usize;
72
73 fn try_write<W: write::Sink>(self, out: &mut W) -> Result<(), W::Error>;
75}
76
77pub trait Constant<Scope: Copy = ()> {
78 const ENTRY: Entry<'static, Scope>;
79}
80
81pub trait Origin: Copy {
82 const FIELD: Option<Entry<'static>>;
83 fn record(&self) -> record::Entry<'_>;
84}
85
86impl Origin for record::Entry<'_> {
87 const FIELD: Option<Entry<'static>> = None;
88 fn record(&self) -> record::Entry<'_> {
89 *self
90 }
91}
92
93impl<C: Constant> Origin for PhantomData<C> {
94 const FIELD: Option<Entry<'static>> = Some(C::ENTRY);
95 fn record(&self) -> record::Entry<'_> {
96 C::ENTRY.as_record()
97 }
98}
99
100struct Wire<C>(PhantomData<fn() -> C>);
101
102impl<C: Constant<Application>> Constant for Wire<C> {
103 const ENTRY: Entry<'static> = Entry::from_record(C::ENTRY.as_record());
104}
105
106pub trait Sink<'field, Scope: Copy = ()>: Sized {
108 type Error;
109
110 fn entry(self, field: Entry<'field, Scope>) -> Result<Self, Self::Error>;
111
112 fn constant<C: Constant<Scope>>(self) -> Result<Self, Self::Error> {
113 self.entry(C::ENTRY)
114 }
115
116 fn declared<D: headers::Fields>(
117 self,
118 ) -> Result<Self, <Self as Sink<'field, Application>>::Error>
119 where
120 Self: Sink<'field, Application>,
121 {
122 <Self as Sink<'field, Application>>::group(self, &D::FIELDS)
123 }
124
125 fn group<'group: 'field, G: Borrow<Group<'group, Scope>> + ?Sized>(
127 mut self,
128 group: &G,
129 ) -> Result<Self, Self::Error>
130 where
131 Scope: 'group,
132 {
133 let group: &Group<'group, Scope> = group.borrow();
134 for entry in group.entries() {
135 self = self.entry(*entry)?;
136 }
137 Ok(self)
138 }
139
140 fn field(
141 self,
142 name: storage::Lower<&'field [u8], Scope>,
143 value: Value<&'field [u8]>,
144 ) -> Result<Self, Self::Error> {
145 self.entry(Entry::new(name, value))
146 }
147
148 fn encoded_with<E: Encode>(
149 self,
150 name: storage::Lower<&'field [u8], Scope>,
151 value: E,
152 indexing: Indexing,
153 ) -> Result<Self, Self::Error>;
154
155 fn generated<E: Encode>(
157 self,
158 name: storage::Lower<&'field [u8], Scope>,
159 value: E,
160 ) -> Result<Self, Self::Error> {
161 self.encoded_with(name, value, Indexing::Allowed)
162 }
163}
164
165pub trait Source<Scope: Copy = ()> {
167 const SECTION_SIZE: Option<usize> = None;
168
169 fn emit<'field, Out: Sink<'field, Scope>>(&'field self, sink: Out) -> Result<Out, Out::Error>;
170}
171
172pub struct Response<F, S = [u8; 3]> {
174 status: S,
175 fields: F,
176}
177
178impl<F> Response<F> {
179 pub const fn new(status: status::Code, fields: F) -> Self {
180 Self {
181 status: status.as_bytes(),
182 fields,
183 }
184 }
185
186 pub(crate) fn declared<S: status::Constant>(fields: F) -> Response<F, PhantomData<fn() -> S>> {
187 Response {
188 status: PhantomData,
189 fields,
190 }
191 }
192}
193
194impl<F: Source<Application>, S> Response<F, S> {
195 const SIZE: Option<usize> = match F::SECTION_SIZE {
196 Some(fields) => fields.checked_add(b":status".len() + 3 + dynamic::ENTRY_OVERHEAD),
197 None => None,
198 };
199}
200
201impl<F: Source<Application>> Source for Response<F> {
202 const SECTION_SIZE: Option<usize> = Self::SIZE;
203
204 fn emit<'field, Out: Sink<'field>>(&'field self, sink: Out) -> Result<Out, Out::Error> {
205 self.fields
206 .emit(sink.entry(Entry::pseudo(Pseudo::Status, Value(&self.status)))?)
207 }
208}
209
210impl<F, S: status::Constant> Constant for Response<F, PhantomData<fn() -> S>> {
211 const ENTRY: Entry<'static> =
212 Entry::pseudo(Pseudo::Status, Value(&const { S::CODE.as_bytes() }));
213}
214
215impl<F: Source<Application>, S: status::Constant> Source for Response<F, PhantomData<fn() -> S>> {
216 const SECTION_SIZE: Option<usize> = Self::SIZE;
217
218 fn emit<'field, Out: Sink<'field>>(&'field self, sink: Out) -> Result<Out, Out::Error> {
219 self.fields.emit(sink.constant::<Self>()?)
220 }
221}
222
223pub trait AsValue {
225 fn as_value(&self) -> Value<&[u8]>;
226}
227
228impl<T: storage::Bytes> AsValue for Value<T> {
229 fn as_value(&self) -> Value<&[u8]> {
230 Value(self.0.as_bytes())
231 }
232}
233
234impl<T: storage::Bytes> Encode for Value<T> {
235 fn encoded_len(&self) -> usize {
236 self.as_bytes().len()
237 }
238
239 fn try_write<W: write::Sink>(self, out: &mut W) -> Result<(), W::Error> {
240 let Self(owner) = self;
241 out.write_slice(owner.as_bytes())
242 }
243}
244
245impl<Scope: Copy, S: Source<Scope> + ?Sized> Source<Scope> for &S {
246 const SECTION_SIZE: Option<usize> = S::SECTION_SIZE;
247
248 fn emit<'field, Out: Sink<'field, Scope>>(&'field self, sink: Out) -> Result<Out, Out::Error> {
249 (**self).emit(sink)
250 }
251}
252
253impl<Scope: Copy, A: Source<Scope>, B: Source<Scope>> Source<Scope> for (A, B) {
254 fn emit<'field, Out: Sink<'field, Scope>>(&'field self, sink: Out) -> Result<Out, Out::Error> {
255 let sink = self.0.emit(sink)?;
256 self.1.emit(sink)
257 }
258}
259
260impl<Scope: Copy> Source<Scope> for Option<Entry<'_, Scope>> {
261 fn emit<'field, Out: Sink<'field, Scope>>(&'field self, sink: Out) -> Result<Out, Out::Error> {
262 self.as_slice().emit(sink)
263 }
264}
265
266impl<Scope: Copy> Source<Scope> for [Entry<'_, Scope>] {
267 fn emit<'field, Out: Sink<'field, Scope>>(
268 &'field self,
269 mut sink: Out,
270 ) -> Result<Out, Out::Error> {
271 for field in self {
272 sink = sink.entry(*field)?;
273 }
274 Ok(sink)
275 }
276}
277
278impl<Scope: Copy, const N: usize> Source<Scope> for [Entry<'_, Scope>; N] {
279 fn emit<'field, Out: Sink<'field, Scope>>(&'field self, sink: Out) -> Result<Out, Out::Error> {
280 self.as_slice().emit(sink)
281 }
282}
283
284impl<Scope: Copy> Source<Scope> for Vec<Entry<'_, Scope>> {
285 fn emit<'field, Out: Sink<'field, Scope>>(&'field self, sink: Out) -> Result<Out, Out::Error> {
286 self.as_slice().emit(sink)
287 }
288}
289
290impl<'entry, 'value, Scope: Copy> Source<Scope>
291 for Copied<slice::Iter<'entry, Entry<'value, Scope>>>
292where
293 'value: 'entry,
294{
295 fn emit<'field, Out: Sink<'field, Scope>>(
296 &'field self,
297 mut sink: Out,
298 ) -> Result<Out, Out::Error> {
299 for field in self.clone() {
300 sink = sink.entry(field)?;
301 }
302 Ok(sink)
303 }
304}
305
306impl<'entry, 'value, Scope: Copy> Source<Scope> for slice::Iter<'entry, Entry<'value, Scope>>
307where
308 'value: 'entry,
309{
310 fn emit<'field, Out: Sink<'field, Scope>>(
311 &'field self,
312 mut sink: Out,
313 ) -> Result<Out, Out::Error> {
314 for field in self.clone() {
315 sink = sink.entry(*field)?;
316 }
317 Ok(sink)
318 }
319}
320
321impl Source<Application> for () {
322 const SECTION_SIZE: Option<usize> = Some(0);
323
324 fn emit<'field, Out: Sink<'field, Application>>(
325 &'field self,
326 sink: Out,
327 ) -> Result<Out, Out::Error> {
328 Ok(sink)
329 }
330}
331
332pub(crate) fn trim_ows_start(mut value: &[u8]) -> &[u8] {
333 while let [b' ' | b'\t', rest @ ..] = value {
334 value = rest;
335 }
336 value
337}
338
339impl Error {
340 pub fn trim_ows(value: &[u8]) -> &[u8] {
341 let mut value = trim_ows_start(value);
342 while matches!(value.last(), Some(b' ' | b'\t')) {
343 value = &value[..value.len() - 1];
344 }
345 value
346 }
347
348 pub const fn name(name: &[u8]) -> Result<(), Self> {
349 if name.is_empty() {
350 return Err(Self::Empty);
351 }
352 let mut index = 0;
353 while index < name.len() {
354 let byte = name[index];
355 if !Self::is_name_byte(byte) {
356 return Err(Self::InvalidByte { index, byte });
357 }
358 index += 1;
359 }
360 Ok(())
361 }
362
363 pub const fn is_name_byte(byte: u8) -> bool {
364 byte.is_ascii_alphanumeric()
365 | (byte == b'!')
366 | (byte.wrapping_sub(b'#') <= b'\'' - b'#')
367 | (byte.wrapping_sub(b'*') <= b'+' - b'*')
368 | (byte.wrapping_sub(b'-') <= b'.' - b'-')
369 | (byte.wrapping_sub(b'^') <= b'`' - b'^')
370 | (byte == b'|')
371 | (byte == b'~')
372 }
373
374 pub const fn value(value: &[u8]) -> Result<(), Self> {
375 let mut index = 0;
376 while index < value.len() {
377 let byte = value[index];
378 if !Self::is_text(byte) {
379 return Err(Self::InvalidByte { index, byte });
380 }
381 index += 1;
382 }
383 Ok(())
384 }
385
386 pub const fn is_text(byte: u8) -> bool {
387 ((byte >= 0x20) & (byte != 0x7f)) | (byte == b'\t')
388 }
389}
390
391#[derive(Clone, Copy, Debug, PartialEq, Eq)]
393#[repr(transparent)]
394pub struct Entry<'a, Scope = ()>(record::Entry<'a>, PhantomData<fn() -> Scope>);
395
396#[derive(Clone, Copy, Debug, PartialEq, Eq)]
398pub enum Pseudo {
399 Method,
400 Scheme,
401 Authority,
402 Path,
403 Protocol,
404 Status,
405}
406
407impl<'a> Entry<'a> {
408 pub const fn content_length<const N: usize>() -> Entry<'static> {
409 let digits = &const { crate::h1::codec::numbers::decimal_length(N) };
410 Entry::from_record(record::Entry::new(
411 head::Name::ContentLength.wire(),
412 digits.0.split_at(digits.1).1,
413 ))
414 }
415
416 pub fn content_length_in(value: u64, digits: &'a mut std::fmt::NumBuffer<u64>) -> Self {
417 Self::from_record(record::Entry::new(
418 head::Name::ContentLength.wire(),
419 value.format_into(digits).as_bytes(),
420 ))
421 }
422
423 pub(in crate::field) const fn from_record(field: record::Entry<'a>) -> Self {
424 Self(field, PhantomData)
425 }
426
427 pub const fn pseudo(name: Pseudo, value: Value<&'a [u8]>) -> Self {
428 let name = match name {
429 Pseudo::Method => b":method".as_slice(),
430 Pseudo::Scheme => b":scheme".as_slice(),
431 Pseudo::Authority => b":authority".as_slice(),
432 Pseudo::Path => b":path".as_slice(),
433 Pseudo::Protocol => b":protocol".as_slice(),
434 Pseudo::Status => b":status".as_slice(),
435 };
436 Self::from_record(record::Entry::new(name, value.0))
437 }
438}
439
440impl<'a, Scope> Entry<'a, Scope> {
441 pub const fn new(name: storage::Lower<&'a [u8], Scope>, value: Value<&'a [u8]>) -> Self {
442 Self(record::Entry::new(name.get(), value.0), PhantomData)
443 }
444
445 pub const fn with_index(self, indexing: Indexing) -> Self {
446 Self(self.0.with_index(indexing), PhantomData)
447 }
448
449 pub const fn name(self) -> &'a [u8] {
450 self.0.name
451 }
452
453 pub const fn value(self) -> Value<&'a [u8]> {
454 Value(self.0.value)
455 }
456
457 pub const fn indexing(self) -> Indexing {
458 self.0.indexing
459 }
460
461 pub const fn as_record(&self) -> record::Entry<'a> {
462 self.0
463 }
464}
465
466impl<'field, S: Sink<'field>> Sink<'field, Application> for S {
467 type Error = <S as Sink<'field>>::Error;
468
469 fn constant<C: Constant<Application>>(self) -> Result<Self, <S as Sink<'field>>::Error> {
470 <S as Sink<'field>>::constant::<Wire<C>>(self)
471 }
472
473 fn declared<D: headers::Fields>(self) -> Result<Self, <S as Sink<'field, Application>>::Error> {
474 D::emit(self)
475 }
476
477 fn entry(self, entry: Entry<'field, Application>) -> Result<Self, <S as Sink<'field>>::Error> {
478 Sink::entry(self, Entry::from_record(entry.0))
479 }
480
481 fn encoded_with<E: Encode>(
482 self,
483 name: storage::Lower<&'field [u8], Application>,
484 value: E,
485 indexing: Indexing,
486 ) -> Result<Self, <S as Sink<'field>>::Error> {
487 Sink::encoded_with(self, name.into_inner(), value, indexing)
488 }
489}