sark_http/field/text/
mod.rs1pub 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_u8(&self) -> Result<u8, IntError> {
31 Ok(parse::<{ u8::MAX as u64 }, false>(self.bytes, 0)?.0 as u8)
32 }
33
34 pub fn parse_u16(&self) -> Result<u16, IntError> {
35 Ok(parse::<{ u16::MAX as u64 }, false>(self.bytes, 0)?.0 as u16)
36 }
37
38 pub fn parse_usize(&self) -> Result<usize, IntError> {
39 Ok(parse::<{ usize::MAX as u64 }, false>(self.bytes, 0)?.0 as usize)
40 }
41
42 pub fn parse_prefix(&self) -> Result<(usize, usize), IntError> {
43 let (value, end) = parse::<{ usize::MAX as u64 }, true>(self.bytes, 0)?;
44 Ok((value as usize, end))
45 }
46
47 pub fn parse_u64(&self) -> Result<u64, IntError> {
48 Ok(parse::<{ u64::MAX }, false>(self.bytes, 0)?.0)
49 }
50
51 pub fn extend_u64(&self, previous: Result<u64, IntError>) -> Result<u64, IntError> {
53 if self.bytes.is_empty() {
54 return previous;
55 }
56 let value = match previous {
57 Ok(value) => value,
58 Err(IntError::Empty) => 0,
59 Err(error) => return Err(error),
60 };
61 Ok(parse::<{ u64::MAX }, false>(self.bytes, value)?.0)
62 }
63}
64
65fn parse<const MAX: u64, const PREFIX: bool>(
66 bytes: &[u8],
67 mut value: u64,
68) -> Result<(u64, usize), IntError> {
69 if bytes.is_empty() {
70 return Err(IntError::Empty);
71 }
72
73 let checked = value != 0 || bytes.len() > MAX.ilog10() as usize;
74 let mut end = 0usize;
75 for &byte in bytes {
76 if !byte.is_ascii_digit() {
77 if PREFIX && end != 0 {
78 break;
79 }
80 return Err(IntError::InvalidByte);
81 }
82 let digit = u64::from(byte - b'0');
83 if checked && (value > MAX / 10 || value == MAX / 10 && digit > MAX % 10) {
84 return Err(IntError::Overflow);
85 }
86 value = value * 10 + digit;
87 if PREFIX {
88 end += 1;
89 }
90 }
91 Ok((value, end))
92}