Skip to main content

sark_http/field/text/
mod.rs

1//! ASCII field and request-value parsing helpers.
2
3pub mod percent;
4
5pub(crate) const fn hex(byte: u8) -> Option<u8> {
6    match byte {
7        b'0'..=b'9' => Some(byte - b'0'),
8        b'a'..=b'f' => Some(byte - b'a' + 10),
9        b'A'..=b'F' => Some(byte - b'A' + 10),
10        _ => None,
11    }
12}
13
14pub struct Ascii<'a> {
15    bytes: &'a [u8],
16}
17
18#[derive(Clone, Copy, Debug, PartialEq, Eq)]
19pub enum IntError {
20    Empty,
21    InvalidByte,
22    Overflow,
23}
24
25impl<'a> Ascii<'a> {
26    pub const fn new(bytes: &'a [u8]) -> Self {
27        Self { bytes }
28    }
29
30    pub fn parse_usize(&self) -> Result<usize, IntError> {
31        Ok(parse::<{ usize::MAX as u64 }, false>(self.bytes)?.0 as usize)
32    }
33
34    pub fn parse_prefix(&self) -> Result<(usize, usize), IntError> {
35        let (value, end) = parse::<{ usize::MAX as u64 }, true>(self.bytes)?;
36        Ok((value as usize, end))
37    }
38
39    pub fn parse_u64(&self) -> Result<u64, IntError> {
40        Ok(parse::<{ u64::MAX }, false>(self.bytes)?.0)
41    }
42}
43
44fn parse<const MAX: u64, const PREFIX: bool>(bytes: &[u8]) -> Result<(u64, usize), IntError> {
45    if bytes.is_empty() {
46        return Err(IntError::Empty);
47    }
48
49    let checked = bytes.len() > MAX.ilog10() as usize;
50    let mut value = 0u64;
51    let mut end = 0usize;
52    for &byte in bytes {
53        if !byte.is_ascii_digit() {
54            if PREFIX && end != 0 {
55                break;
56            }
57            return Err(IntError::InvalidByte);
58        }
59        let digit = u64::from(byte - b'0');
60        if checked && (value > MAX / 10 || value == MAX / 10 && digit > MAX % 10) {
61            return Err(IntError::Overflow);
62        }
63        value = value * 10 + digit;
64        if PREFIX {
65            end += 1;
66        }
67    }
68    Ok((value, end))
69}