Skip to main content

sark_http/h1/field/
mod.rs

1//! HTTP/1 field syntax and borrow-free field state.
2
3use crate::field::{
4    self,
5    text::{Ascii, IntError},
6};
7
8mod cursor;
9mod entry;
10pub mod expect;
11pub mod scan;
12pub mod syntax;
13mod transfer;
14pub mod value;
15
16pub(in crate::h1) use cursor::{Cursor, End};
17pub use entry::Entry;
18pub use transfer::Transfer;
19
20pub(in crate::h1) enum Progress<'owner> {
21    Field(Entry<'owner>),
22    More,
23    End(End),
24}
25
26const _: () = assert!(core::mem::size_of::<Progress<'_>>() == 64);
27
28#[derive(Clone, Copy, PartialEq, Eq)]
29pub(in crate::h1) struct Limit {
30    count: u32,
31    line_bytes: u32,
32}
33
34impl Limit {
35    pub(in crate::h1) const fn new(count: usize, line: usize) -> Self {
36        Self {
37            count: Self::narrow(count),
38            line_bytes: Self::narrow(line),
39        }
40    }
41
42    const fn narrow(value: usize) -> u32 {
43        if value > u32::MAX as usize {
44            u32::MAX
45        } else {
46            value as u32
47        }
48    }
49}
50
51#[derive(Clone, Copy, Debug, PartialEq, Eq)]
52pub enum Error {
53    DuplicateContentLength,
54    ContentLengthWithTransferEncoding,
55    InvalidContentLength(IntError),
56    InvalidTransferEncoding(value::Error),
57}
58
59/// Accumulated connection-option semantics shared by request and response
60/// scanners. Unknown valid tokens are intentionally ignored; malformed token
61/// bytes fail admission.
62#[repr(transparent)]
63#[derive(Clone, Copy, Default, PartialEq, Eq)]
64pub struct Connection(u8);
65
66#[derive(Clone, Copy, Debug, PartialEq, Eq)]
67pub struct TokenError {
68    pub index: usize,
69    pub byte: u8,
70}
71
72impl Connection {
73    pub(crate) const CLOSE: Self = Self(1 << 0);
74    pub(crate) const KEEP_ALIVE: Self = Self(1 << 1);
75    const UPGRADE: u8 = 1 << 2;
76
77    pub fn try_push(mut self, value: &[u8]) -> Result<Self, TokenError> {
78        let mut rest = value;
79        while !rest.is_empty() {
80            let (token, tail) = field::scan::split_token(field::trim_ows_start(rest));
81            if token.eq_ignore_ascii_case(b"close") {
82                self.0 |= Self::CLOSE.0;
83            } else if token.eq_ignore_ascii_case(b"keep-alive") {
84                self.0 |= Self::KEEP_ALIVE.0;
85            } else if token.eq_ignore_ascii_case(b"upgrade") {
86                self.0 |= Self::UPGRADE;
87            }
88            let [first, ..] = tail else { break };
89            match field::trim_ows_start(tail) {
90                [b',', next @ ..] => rest = next,
91                [] => break,
92                _ => {
93                    return Err(TokenError {
94                        index: value.len() - tail.len(),
95                        byte: *first,
96                    });
97                }
98            }
99        }
100        Ok(self)
101    }
102
103    /// Merges connection options that were parsed by another scanner branch.
104    #[doc(hidden)]
105    pub fn append(&mut self, fields: Self) {
106        self.0 |= fields.0;
107    }
108
109    pub const fn is_close(self) -> bool {
110        self.0 & Self::CLOSE.0 != 0
111    }
112
113    pub const fn is_keep(self) -> bool {
114        self.0 & Self::KEEP_ALIVE.0 != 0
115    }
116
117    pub const fn is_upgrade(self) -> bool {
118        self.0 & Self::UPGRADE != 0
119    }
120}
121
122/// Advisory persistence parameters accumulated across every `Keep-Alive`
123/// field. Malformed and unknown parameters are ignored because they cannot
124/// change message framing; the shortest valid timeout wins deterministically.
125#[derive(Clone, Copy, Default, PartialEq, Eq)]
126pub struct KeepAlive {
127    timeout: Option<u64>,
128}
129
130impl KeepAlive {
131    pub(crate) fn parse(mut prior: Option<u64>, value: &[u8]) -> Option<u64> {
132        for raw in value.split(|byte| *byte == b',') {
133            let param = field::Error::trim_ows(raw);
134            let Some(split) = param.iter().position(|byte| *byte == b'=') else {
135                continue;
136            };
137            let name = field::Error::trim_ows(&param[..split]);
138            if !name.eq_ignore_ascii_case(b"timeout") {
139                continue;
140            }
141            let Ok(timeout) = Ascii::new(field::Error::trim_ows(&param[split + 1..])).parse_u64()
142            else {
143                continue;
144            };
145            prior = Some(prior.map_or(timeout, |current| current.min(timeout)));
146        }
147        prior
148    }
149
150    pub(crate) const fn new(timeout: Option<u64>) -> Self {
151        Self { timeout }
152    }
153
154    pub const fn timeout_secs(self) -> Option<u64> {
155        self.timeout
156    }
157}
158
159const _: () = assert!(core::mem::size_of::<Connection>() == 1);