Skip to main content

sark_http/h1/field/
mod.rs

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