Skip to main content

serenade_form/
parse.rs

1//! `application/x-www-form-urlencoded` body parser.
2
3use std::collections::HashMap;
4
5use crate::FormError;
6
7/// Parses a URL-encoded form body into string fields (last value wins on duplicates).
8///
9/// # Errors
10///
11/// Returns [`FormError::InvalidEncoding`] when percent-decoding fails.
12pub fn parse_urlencoded(body: &[u8]) -> Result<HashMap<String, String>, FormError> {
13    let multi = parse_urlencoded_multi(body)?;
14    Ok(multi
15        .into_iter()
16        .map(|(key, values)| (key, values.into_iter().next_back().unwrap_or_default()))
17        .collect())
18}
19
20/// Parses a URL-encoded body keeping every value for each key (submission order).
21///
22/// # Errors
23///
24/// Returns [`FormError::InvalidEncoding`] when percent-decoding fails.
25pub fn parse_urlencoded_multi(body: &[u8]) -> Result<HashMap<String, Vec<String>>, FormError> {
26    let text = std::str::from_utf8(body).map_err(|_| FormError::InvalidEncoding)?;
27    let mut map = HashMap::new();
28    if text.is_empty() {
29        return Ok(map);
30    }
31    for pair in text.split('&') {
32        if pair.is_empty() {
33            continue;
34        }
35        let (raw_key, raw_value) = pair.split_once('=').unwrap_or((pair, ""));
36        let key = percent_decode(raw_key)?;
37        let value = percent_decode(raw_value)?;
38        map.entry(key).or_insert_with(Vec::new).push(value);
39    }
40    Ok(map)
41}
42
43fn percent_decode(input: &str) -> Result<String, FormError> {
44    let mut out = Vec::with_capacity(input.len());
45    let bytes = input.as_bytes();
46    let mut i = 0;
47    while i < bytes.len() {
48        match bytes[i] {
49            b'+' => {
50                out.push(b' ');
51                i += 1;
52            }
53            b'%' if i + 2 < bytes.len() => {
54                let hi = from_hex(bytes[i + 1])?;
55                let lo = from_hex(bytes[i + 2])?;
56                out.push((hi << 4) | lo);
57                i += 3;
58            }
59            b'%' => return Err(FormError::InvalidEncoding),
60            b => {
61                out.push(b);
62                i += 1;
63            }
64        }
65    }
66    String::from_utf8(out).map_err(|_| FormError::InvalidEncoding)
67}
68
69const fn from_hex(byte: u8) -> Result<u8, FormError> {
70    match byte {
71        b'0'..=b'9' => Ok(byte - b'0'),
72        b'a'..=b'f' => Ok(byte - b'a' + 10),
73        b'A'..=b'F' => Ok(byte - b'A' + 10),
74        _ => Err(FormError::InvalidEncoding),
75    }
76}