Skip to content
1        10        20        30        40        50        60        70        801use std::collections::HashMap;23/// Parses `application/x-www-form-urlencoded` while preserving repeated keys,4/// as used by checkbox groups in the ticket and lane forms.5pub fn parse_form(body: &[u8]) -> Result<HashMap<String, Vec<String>>, ()> {6    let mut fields: HashMap<String, Vec<String>> = HashMap::new();7    for pair in body8        .split(|byte| *byte == b'&')9        .filter(|pair| !pair.is_empty())10    {11        let (key, value) = match pair.iter().position(|byte| *byte == b'=') {12            Some(index) => (&pair[..index], &pair[index + 1..]),13            None => (pair, &[] as &[u8]),14        };15        fields16            .entry(decode_component(key)?)17            .or_default()18            .push(decode_component(value)?);19    }20    Ok(fields)21}2223fn decode_component(input: &[u8]) -> Result<String, ()> {24    let mut output = Vec::with_capacity(input.len());25    let mut index = 0;26    while index < input.len() {27        match input[index] {28            b'+' => {29                output.push(b' ');30                index += 1;31            }32            b'%' if index + 2 < input.len() => {33                let high = hex(input[index + 1]).ok_or(())?;34                let low = hex(input[index + 2]).ok_or(())?;35                output.push(high * 16 + low);36                index += 3;37            }38            b'%' => return Err(()),39            byte => {40                output.push(byte);41                index += 1;42            }43        }44    }45    String::from_utf8(output).map_err(|_| ())46}4748fn hex(byte: u8) -> Option<u8> {49    match byte {50        b'0'..=b'9' => Some(byte - b'0'),51        b'a'..=b'f' => Some(byte - b'a' + 10),52        b'A'..=b'F' => Some(byte - b'A' + 10),53        _ => None,54    }55}5657#[cfg(test)]58mod tests {59    use super::*;6061    #[test]62    fn repeated_form_fields_and_encoded_values_are_preserved() {63        let fields = parse_form(b"tag_ids=one&tag_ids=two&title=Ship+it%21").unwrap();64        assert_eq!(fields["tag_ids"], ["one".to_string(), "two".to_string()]);65        assert_eq!(fields["title"], ["Ship it!".to_string()]);66    }6768    #[test]69    fn malformed_percent_encoding_is_rejected() {70        assert!(parse_form(b"name=%Q0").is_err());71    }72}