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};
const FORM: Mode = Mode {
plus: Plus::Space,
bad_escape: BadEscape::Keep,
utf8: Utf8::Replace,
};
#[derive(Debug, Clone)]
pub struct Query {
signature: Signature,
}
impl Default for Query {
fn default() -> Self {
Self::new()
}
}
impl Query {
#[must_use]
pub fn new() -> Self {
let signature = Signature::builder()
.build()
.unwrap_or_else(|_| unreachable!("invariant: an empty signature always builds"));
Self { signature }
}
}
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)
}
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() {
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));
}
}
}