Skip to main content

sark_http/h1/field/
value.rs

1use crate::field::{self, scan};
2
3#[derive(Clone, Copy, Debug, PartialEq, Eq)]
4pub enum Error {
5    Empty,
6    InvalidByte,
7    Overflow,
8    InvalidOrdering,
9}
10
11pub(super) fn token(value: &[u8]) -> Result<(&[u8], &[u8]), Error> {
12    let (token, tail) = scan::split_token(value);
13    if token.is_empty() {
14        return Err(if value.is_empty() {
15            Error::Empty
16        } else {
17            Error::InvalidByte
18        });
19    }
20    Ok((token, field::trim_ows_start(tail)))
21}
22
23pub(super) fn item(value: &[u8]) -> Result<&[u8], Error> {
24    let Some((b'"', tail)) = value.split_first() else {
25        return token(value).map(|(_, tail)| tail);
26    };
27    let mut bytes = tail.iter();
28    while let Some(&byte) = bytes.next() {
29        match byte {
30            b'"' => return Ok(field::trim_ows_start(bytes.as_slice())),
31            b'\\' => {
32                let escaped = bytes.next().ok_or(Error::InvalidByte)?;
33                if !matches!(escaped, b'\t' | b' ' | 0x21..=0x7e | 0x80..=0xff) {
34                    return Err(Error::InvalidByte);
35                }
36            }
37            b'\t' | b' ' | b'!' | 0x23..=0x5b | 0x5d..=0x7e | 0x80..=0xff => {}
38            0..=8 | 10..=31 | 0x7f => return Err(Error::InvalidByte),
39        }
40    }
41    Err(Error::InvalidByte)
42}