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::{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! field_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::field_literal as literal;
36use crate::payload::response::{headers::Application, status};
37
38#[derive(Clone, Copy, Debug, PartialEq, Eq)]
39pub enum Error {
40 Empty,
41 InvalidByte { index: usize, byte: u8 },
42}
43
44#[repr(u8)]
46#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
47pub enum Indexing {
48 #[default]
49 Allowed,
50 Never,
51}
52
53impl Indexing {
54 pub(in crate::field) const fn from_byte(value: u8) -> Option<Self> {
55 match value {
56 0 => Some(Self::Allowed),
57 1 => Some(Self::Never),
58 _ => None,
59 }
60 }
61
62 pub(in crate::field) const fn from_never(never: bool) -> Self {
63 if never { Self::Never } else { Self::Allowed }
64 }
65}
66
67pub trait Encode: encoded::Encoded {
69 fn encoded_len(&self) -> usize;
70
71 fn try_write<W: write::Sink>(self, out: &mut W) -> Result<(), W::Error>;
73}
74
75pub trait Sink<'field, Scope: Copy = ()> {
77 fn entry(&mut self, field: Entry<'field, Scope>);
78
79 fn group(&mut self, group: &Group<'field, Scope>) {
81 for entry in group.entries() {
82 self.entry(*entry);
83 }
84 }
85
86 fn field(&mut self, name: storage::Lower<&'field [u8], Scope>, value: Value<&'field [u8]>) {
87 self.entry(Entry::new(name, value));
88 }
89
90 fn encoded_with<E: Encode>(
91 &mut self,
92 name: storage::Lower<&'field [u8], Scope>,
93 value: E,
94 indexing: Indexing,
95 );
96
97 fn generated<E: Encode>(&mut self, name: storage::Lower<&'field [u8], Scope>, value: E) {
99 self.encoded_with(name, value, Indexing::Allowed);
100 }
101}
102
103pub trait Source<Scope: Copy = ()> {
105 fn emit<'field>(&'field self, sink: &mut impl Sink<'field, Scope>);
106}
107
108pub trait AsValue {
110 fn as_value(&self) -> Value<&[u8]>;
111}
112
113impl<T: storage::Bytes> AsValue for Value<T> {
114 fn as_value(&self) -> Value<&[u8]> {
115 Value(self.0.as_bytes())
116 }
117}
118
119impl<T: storage::Bytes> Encode for Value<T> {
120 fn encoded_len(&self) -> usize {
121 self.as_bytes().len()
122 }
123
124 fn try_write<W: write::Sink>(self, out: &mut W) -> Result<(), W::Error> {
125 let Self(owner) = self;
126 out.write_slice(owner.as_bytes())
127 }
128}
129
130impl<Scope: Copy, S: Source<Scope> + ?Sized> Source<Scope> for &S {
131 fn emit<'field>(&'field self, sink: &mut impl Sink<'field, Scope>) {
132 (**self).emit(sink);
133 }
134}
135
136impl<Scope: Copy, A: Source<Scope>, B: Source<Scope>> Source<Scope> for (A, B) {
137 fn emit<'field>(&'field self, sink: &mut impl Sink<'field, Scope>) {
138 self.0.emit(sink);
139 self.1.emit(sink);
140 }
141}
142
143impl<Scope: Copy> Source<Scope> for Option<Entry<'_, Scope>> {
144 fn emit<'field>(&'field self, sink: &mut impl Sink<'field, Scope>) {
145 self.as_slice().emit(sink);
146 }
147}
148
149impl<Scope: Copy> Source<Scope> for [Entry<'_, Scope>] {
150 fn emit<'field>(&'field self, sink: &mut impl Sink<'field, Scope>) {
151 for field in self {
152 sink.entry(*field);
153 }
154 }
155}
156
157impl<Scope: Copy, const N: usize> Source<Scope> for [Entry<'_, Scope>; N] {
158 fn emit<'field>(&'field self, sink: &mut impl Sink<'field, Scope>) {
159 self.as_slice().emit(sink);
160 }
161}
162
163impl<Scope: Copy> Source<Scope> for Vec<Entry<'_, Scope>> {
164 fn emit<'field>(&'field self, sink: &mut impl Sink<'field, Scope>) {
165 self.as_slice().emit(sink);
166 }
167}
168
169impl<'entry, 'value, Scope: Copy> Source<Scope>
170 for Copied<slice::Iter<'entry, Entry<'value, Scope>>>
171where
172 'value: 'entry,
173{
174 fn emit<'field>(&'field self, sink: &mut impl Sink<'field, Scope>) {
175 for field in self.clone() {
176 sink.entry(field);
177 }
178 }
179}
180
181impl<'entry, 'value, Scope: Copy> Source<Scope> for slice::Iter<'entry, Entry<'value, Scope>>
182where
183 'value: 'entry,
184{
185 fn emit<'field>(&'field self, sink: &mut impl Sink<'field, Scope>) {
186 for field in self.clone() {
187 sink.entry(*field);
188 }
189 }
190}
191
192impl Source<Application> for () {
193 fn emit<'field>(&'field self, _: &mut impl Sink<'field, Application>) {}
194}
195
196pub(crate) fn trim_ows_start(mut value: &[u8]) -> &[u8] {
197 while let [b' ' | b'\t', rest @ ..] = value {
198 value = rest;
199 }
200 value
201}
202
203impl Error {
204 pub fn trim_ows(value: &[u8]) -> &[u8] {
205 let mut value = trim_ows_start(value);
206 while matches!(value.last(), Some(b' ' | b'\t')) {
207 value = &value[..value.len() - 1];
208 }
209 value
210 }
211
212 pub const fn name(name: &[u8]) -> Result<(), Self> {
213 if name.is_empty() {
214 return Err(Self::Empty);
215 }
216 let mut index = 0;
217 while index < name.len() {
218 let byte = name[index];
219 if !Self::is_name_byte(byte) {
220 return Err(Self::InvalidByte { index, byte });
221 }
222 index += 1;
223 }
224 Ok(())
225 }
226
227 pub const fn is_name_byte(byte: u8) -> bool {
228 byte.is_ascii_alphanumeric()
229 | (byte == b'!')
230 | (byte.wrapping_sub(b'#') <= b'\'' - b'#')
231 | (byte.wrapping_sub(b'*') <= b'+' - b'*')
232 | (byte.wrapping_sub(b'-') <= b'.' - b'-')
233 | (byte.wrapping_sub(b'^') <= b'`' - b'^')
234 | (byte == b'|')
235 | (byte == b'~')
236 }
237
238 pub const fn value(value: &[u8]) -> Result<(), Self> {
239 let mut index = 0;
240 while index < value.len() {
241 let byte = value[index];
242 if !Self::is_text(byte) {
243 return Err(Self::InvalidByte { index, byte });
244 }
245 index += 1;
246 }
247 Ok(())
248 }
249
250 pub const fn is_text(byte: u8) -> bool {
251 ((byte >= 0x20) & (byte != 0x7f)) | (byte == b'\t')
252 }
253}
254
255pub struct Response<F> {
257 value: Value<[u8; 3]>,
258 fields: F,
259}
260
261impl<F> Response<F> {
262 pub const fn new(status: status::Code, fields: F) -> Self {
263 Self {
264 value: Value(status.as_bytes()),
265 fields,
266 }
267 }
268}
269
270impl<F: Source<Application>> Source for Response<F> {
271 fn emit<'field>(&'field self, sink: &mut impl Sink<'field>) {
272 sink.entry(Entry::pseudo(Pseudo::Status, self.value.borrow()));
273 self.fields.emit(sink);
274 }
275}
276
277#[derive(Clone, Copy, Debug, PartialEq, Eq)]
279#[repr(transparent)]
280pub struct Entry<'a, Scope = ()>(record::Entry<'a>, PhantomData<fn() -> Scope>);
281
282#[derive(Clone, Copy, Debug, PartialEq, Eq)]
284pub enum Pseudo {
285 Method,
286 Scheme,
287 Authority,
288 Path,
289 Protocol,
290 Status,
291}
292
293impl<'a> Entry<'a> {
294 pub const fn content_length<const N: usize>() -> Entry<'static> {
295 let digits = &const { crate::h1::codec::numbers::decimal_length(N) };
296 Entry::from_record(record::Entry::new(
297 head::Name::ContentLength.wire(),
298 digits.0.split_at(digits.1).1,
299 ))
300 }
301
302 pub(in crate::field) const fn from_record(field: record::Entry<'a>) -> Self {
303 Self(field, PhantomData)
304 }
305
306 pub const fn pseudo(name: Pseudo, value: Value<&'a [u8]>) -> Self {
307 let name = match name {
308 Pseudo::Method => b":method".as_slice(),
309 Pseudo::Scheme => b":scheme".as_slice(),
310 Pseudo::Authority => b":authority".as_slice(),
311 Pseudo::Path => b":path".as_slice(),
312 Pseudo::Protocol => b":protocol".as_slice(),
313 Pseudo::Status => b":status".as_slice(),
314 };
315 Self::from_record(record::Entry::new(name, value.0))
316 }
317}
318
319impl<'a, Scope> Entry<'a, Scope> {
320 pub const fn new(name: storage::Lower<&'a [u8], Scope>, value: Value<&'a [u8]>) -> Self {
321 Self(record::Entry::new(name.get(), value.0), PhantomData)
322 }
323
324 pub const fn with_index(self, indexing: Indexing) -> Self {
325 Self(self.0.with_index(indexing), PhantomData)
326 }
327
328 pub const fn name(self) -> &'a [u8] {
329 self.0.name
330 }
331
332 pub const fn value(self) -> Value<&'a [u8]> {
333 Value(self.0.value)
334 }
335
336 pub const fn indexing(self) -> Indexing {
337 self.0.indexing
338 }
339
340 pub const fn as_record(&self) -> record::Entry<'a> {
341 self.0
342 }
343}
344
345#[derive(Clone, Copy, Debug, PartialEq, Eq)]
347pub struct Group<'a, Scope = ()> {
348 entries: &'a [Entry<'a, Scope>],
349 wire: &'a [u8],
350}
351
352#[derive(Clone, Copy, Debug, PartialEq, Eq)]
354pub struct Mismatch {
355 pub offset: usize,
356 pub expected: Option<u8>,
357 pub actual: Option<u8>,
358}
359
360struct Cursor<'a> {
361 wire: &'a [u8],
362 offset: usize,
363}
364
365impl<'a, Scope: Copy> Group<'a, Scope> {
366 pub const fn try_new(
367 entries: &'a [Entry<'a, Scope>],
368 wire: &'a [u8],
369 ) -> Result<Self, Mismatch> {
370 let mut cursor = Cursor { wire, offset: 0 };
371 let mut index = 0;
372 while index < entries.len() {
373 let entry = entries[index];
374 let parts = [entry.name(), b": ", entry.value().get(), b"\r\n"];
375 let mut part = 0;
376 while part < parts.len() {
377 if let Err(error) = cursor.check(parts[part]) {
378 return Err(error);
379 }
380 part += 1;
381 }
382 index += 1;
383 }
384 if let Some((&actual, _)) = cursor.wire.split_first() {
385 return Err(Mismatch {
386 offset: cursor.offset,
387 expected: None,
388 actual: Some(actual),
389 });
390 }
391 Ok(Self { entries, wire })
392 }
393
394 pub const fn entries(&self) -> &'a [Entry<'a, Scope>] {
395 self.entries
396 }
397
398 pub const fn wire(&self) -> &'a [u8] {
399 self.wire
400 }
401}
402
403impl<Scope: Copy> Source<Scope> for Group<'_, Scope> {
404 fn emit<'field>(&'field self, sink: &mut impl Sink<'field, Scope>) {
405 sink.group(self);
406 }
407}
408
409impl<'field, S: Sink<'field>> Sink<'field, Application> for S {
410 fn entry(&mut self, entry: Entry<'field, Application>) {
411 Sink::entry(self, Entry::from_record(entry.0));
412 }
413
414 fn encoded_with<E: Encode>(
415 &mut self,
416 name: storage::Lower<&'field [u8], Application>,
417 value: E,
418 indexing: Indexing,
419 ) {
420 Sink::encoded_with(self, name.into_inner(), value, indexing);
421 }
422}
423
424impl Cursor<'_> {
425 const fn check(&mut self, expected: &[u8]) -> Result<(), Mismatch> {
426 let mut index = 0;
427 while index < expected.len() {
428 let byte = expected[index];
429 let (actual, rest) = match self.wire.split_first() {
430 Some((&actual, rest)) => (Some(actual), rest),
431 None => (None, self.wire),
432 };
433 if !matches!(actual, Some(actual) if actual == byte) {
434 return Err(Mismatch {
435 offset: self.offset,
436 expected: Some(byte),
437 actual,
438 });
439 }
440 self.wire = rest;
441 self.offset += 1;
442 index += 1;
443 }
444 Ok(())
445 }
446}