1use std::collections::BTreeMap;
6use std::fmt;
7
8#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11pub struct BadQuery;
12
13impl fmt::Display for BadQuery {
14 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
15 f.write_str(concat!(
16 "the query names a parameter the route does not take, ",
17 "names one twice, or gives a value it cannot read"
18 ))
19 }
20}
21
22impl std::error::Error for BadQuery {}
23
24pub fn pairs(query: Option<&str>, names: &[&str]) -> Result<BTreeMap<String, String>, BadQuery> {
33 let mut read = BTreeMap::new();
34 for piece in query.unwrap_or("").split('&').filter(|p| !p.is_empty()) {
36 if !piece.contains('=') {
37 return Err(BadQuery);
38 }
39 let (name, value) = form_urlencoded::parse(piece.as_bytes())
40 .next()
41 .ok_or(BadQuery)?;
42 if !names.contains(&name.as_ref()) {
43 return Err(BadQuery);
44 }
45 if read.insert(name.into_owned(), value.into_owned()).is_some() {
46 return Err(BadQuery);
47 }
48 }
49 Ok(read)
50}
51
52#[must_use]
56pub fn names(query: Option<&str>, name: &str) -> bool {
57 query.unwrap_or("").split('&').any(|piece| {
58 form_urlencoded::parse(piece.as_bytes())
59 .next()
60 .is_some_and(|(named, _)| named == name)
61 })
62}
63
64#[cfg(test)]
65mod tests {
66 use super::*;
67
68 const NAMES: &[&str] = &["limit", "cursor", "since"];
69
70 fn read(query: &str) -> Result<Vec<(String, String)>, BadQuery> {
71 pairs(Some(query), NAMES).map(|p| p.into_iter().collect())
72 }
73
74 fn pair(name: &str, value: &str) -> (String, String) {
75 (name.to_owned(), value.to_owned())
76 }
77
78 #[test]
79 fn no_query_and_an_empty_one_are_no_parameters() {
80 assert_eq!(
81 pairs(None, NAMES),
82 Ok(BTreeMap::new()),
83 "no query string has no parameters"
84 );
85 assert_eq!(
86 read(""),
87 Ok(vec![]),
88 "an empty query string has none either"
89 );
90 }
91
92 #[test]
93 fn known_names_are_read_with_their_values_decoded() {
94 assert_eq!(
95 read("limit=10&since=2026-10-25T12%3A00%3A00%2B01%3A00"),
96 Ok(vec![
97 pair("limit", "10"),
98 pair("since", "2026-10-25T12:00:00+01:00")
99 ]),
100 "each value is percent-decoded"
101 );
102 assert_eq!(
103 read("cursor="),
104 Ok(vec![pair("cursor", "")]),
105 "a name with an empty value is given, with that value"
106 );
107 }
108
109 #[test]
110 fn an_unknown_name_is_refused() {
111 assert_eq!(
112 read("limit=10&offset=5"),
113 Err(BadQuery),
114 "offset is not a name this query takes"
115 );
116 assert_eq!(read("Limit=10"), Err(BadQuery), "names are exact");
117 }
118
119 #[test]
120 fn a_name_given_twice_is_refused() {
121 assert_eq!(
122 read("limit=10&limit=20"),
123 Err(BadQuery),
124 "two values would be ambiguous"
125 );
126 assert_eq!(
127 read("limit=10&limit=10"),
128 Err(BadQuery),
129 "a repeated name is refused even with the same value"
130 );
131 }
132
133 #[test]
134 fn a_name_with_no_equals_sign_is_refused() {
135 assert_eq!(
136 read("limit"),
137 Err(BadQuery),
138 "a parameter is a name, an equals sign and a value"
139 );
140 }
141}