grippo 0.2.1

Parse, match and scrub data faster and more efficiently.
Documentation
// Project:   grippo
// File:      src/format/query.rs
// Purpose:   A query string or form body, application/x-www-form-urlencoded
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! `a=1&b=x+y`, as a URL's query or a form body writes it.
//!
//! Pairs split on `&` and a pair on its first `=`. A name and its value are
//! percent-decoded with `+` as a space, a `%` without two hex digits kept as
//! written and bytes that aren't UTF-8 as U+FFFD, the WHATWG reading. A name
//! written twice is written twice, so the sink holds a list. A pair with no
//! `=` has an empty value, and one with an empty name writes nothing.

use std::borrow::Cow;
use std::fmt::Write as _;

use memchr::memchr;

use crate::parse::{FieldSink, FieldValue, Hint, ParseError, Parsed, Parser};
use crate::path::key_part;
use crate::strmatch::Signature;
use crate::tier::MatcherTier;
use crate::uri::percent::{self, BadEscape, Mode, Plus, Utf8};

/// The WHATWG form reading: never fails.
const FORM: Mode = Mode {
    plus: Plus::Space,
    bad_escape: BadEscape::Keep,
    utf8: Utf8::Replace,
};

/// The query string parser, registered as `query`.
#[derive(Debug, Clone)]
pub struct Query {
    signature: Signature,
}

impl Default for Query {
    fn default() -> Self {
        Self::new()
    }
}

impl Query {
    /// A query string parser.
    #[must_use]
    pub fn new() -> Self {
        let signature = Signature::builder()
            .build()
            .unwrap_or_else(|_| unreachable!("invariant: an empty signature always builds"));
        Self { signature }
    }
}

/// `text` decoded, borrowed from the input where nothing changes. A raw byte
/// past ASCII in text that isn't UTF-8 decodes as its `%XX` would, so it can
/// join an escaped byte into one character.
fn decode(text: &[u8]) -> Cow<'_, str> {
    let decoded = std::str::from_utf8(text).map_or_else(
        |_| {
            let mut ascii = String::with_capacity(text.len() * 3);
            for &b in text {
                if b.is_ascii() {
                    ascii.push(char::from(b));
                } else {
                    let _ = write!(ascii, "%{b:02X}");
                }
            }
            percent::decode(&ascii, FORM).map(|d| Cow::Owned(d.into_owned()))
        },
        |text| percent::decode(text, FORM),
    );
    decoded.unwrap_or_else(|_| unreachable!("invariant: FORM keeps bad escapes and bad bytes"))
}

impl Parser for Query {
    fn hands_on_body(&self) -> bool {
        false
    }

    fn name(&self) -> &'static str {
        "query"
    }

    fn tier(&self) -> MatcherTier {
        MatcherTier::Field
    }

    fn signature(&self) -> &Signature {
        &self.signature
    }

    fn parse<'a>(
        &self,
        input: &'a [u8],
        out: &mut dyn FieldSink<'a>,
    ) -> Result<Parsed, ParseError> {
        let mut any = false;
        let mut start = 0;
        while start < input.len() {
            let end = memchr(b'&', &input[start..]).map_or(input.len(), |at| start + at);
            let pair = &input[start..end];
            start = end + 1;
            let (name, value) = pair.split_at(memchr(b'=', pair).unwrap_or(pair.len()));
            let value = value.get(1..).unwrap_or_default();
            let name = decode(name);
            if name.is_empty() {
                continue;
            }
            let value = match decode(value) {
                Cow::Borrowed(text) => FieldValue::borrowed(text.as_bytes(), Hint::Text),
                Cow::Owned(text) => FieldValue::owned(text.into_bytes(), Hint::Text),
            };
            out.field(&key_part(name), value);
            any = true;
        }
        Ok(if any { Parsed::Done } else { Parsed::NoMatch })
    }
}

#[cfg(test)]
mod tests {
    use proptest::prelude::*;

    use super::*;
    use crate::parse::Fields;

    type Rows = Vec<(String, String)>;

    fn read(input: &[u8]) -> (Parsed, Rows) {
        let mut out = Fields::new();
        let parsed = Query::new().parse(input, &mut out).unwrap();
        let rows = out
            .as_slice()
            .iter()
            .map(|(k, v)| (k.clone(), String::from_utf8(v.bytes.to_vec()).unwrap()))
            .collect();
        (parsed, rows)
    }

    /// What `form_urlencoded` reads, less pairs with an empty name, each
    /// name as the sink writes it.
    fn oracle(input: &[u8]) -> Rows {
        form_urlencoded::parse(input)
            .filter(|(k, _)| !k.is_empty())
            .map(|(k, v)| (key_part(k).into_owned(), v.into_owned()))
            .collect()
    }

    #[test]
    fn query_strings() {
        // An input, then the pairs it writes. None writes nothing.
        let rows: &[(&[u8], &[(&str, &str)])] = &[
            (b"a=1&b=x+y", &[("a", "1"), ("b", "x y")]),
            (b"q=caf%C3%A9&n=%41%42", &[("q", "caf\u{e9}"), ("n", "AB")]),
            (b"a=1&a=2&a=", &[("a", "1"), ("a", "2"), ("a", "")]),
            (b"flag&x=1", &[("flag", ""), ("x", "1")]),
            (b"a=b=c", &[("a", "b=c")]),
            (b"&&a=1&&", &[("a", "1")]),
            (
                b"bad=100%&pct=%+5&hex=%zz",
                &[("bad", "100%"), ("pct", "% 5"), ("hex", "%zz")],
            ),
            (b"u=%FF&v=\xff", &[("u", "\u{fffd}"), ("v", "\u{fffd}")]),
            (b"x=\xc3%A9&y=%C3\xa9", &[("x", "\u{e9}"), ("y", "\u{e9}")]),
            (b"my+key=1&a.b=2", &[("my key", "1"), (r#"["a.b"]"#, "2")]),
            (b"=x&%3D=y", &[("=", "y")]),
            (b"q=\"x\"", &[("q", "\"x\"")]),
            (b"", &[]),
            (b"&", &[]),
            (b"=1&=2", &[]),
        ];
        for (input, want) in rows {
            let shown = String::from_utf8_lossy(input);
            let (parsed, got) = read(input);
            let want: Rows = want
                .iter()
                .map(|(k, v)| ((*k).to_owned(), (*v).to_owned()))
                .collect();
            assert_eq!(got, want, "{shown}");
            assert_eq!(got, oracle(input), "{shown} against form_urlencoded");
            let done = if want.is_empty() {
                Parsed::NoMatch
            } else {
                Parsed::Done
            };
            assert_eq!(parsed, done, "{shown}");
        }
    }

    #[test]
    fn a_value_with_nothing_to_decode_is_borrowed() {
        let mut out = Fields::new();
        Query::new().parse(b"a=plain&b=x%20y", &mut out).unwrap();
        assert!(matches!(out.get("a").unwrap().bytes, Cow::Borrowed(_)));
        assert!(matches!(out.get("b").unwrap().bytes, Cow::Owned(_)));
    }

    proptest! {
        #[test]
        fn reads_as_form_urlencoded_does(input in prop::collection::vec(
            prop::sample::select(&b"ab=&+%2Fz\xc3\xa9\xff."[..]), 0..40)
        ) {
            prop_assert_eq!(read(&input).1, oracle(&input));
        }
    }
}