Skip to main content

http_query/
accept_query.rs

1//! RFC 9651 Structured Fields handling for the `Accept-Query` header field.
2//!
3//! RFC 10008 ยง3 defines `Accept-Query` as a Structured Fields List of media
4//! ranges represented as Tokens or Strings, each optionally carrying
5//! parameters. Only the bare media-range values are surfaced here (parameters
6//! are recognized and stripped), which is what QUERY content negotiation needs.
7
8/// Parses one or more `Accept-Query` header field values into the list of
9/// advertised media ranges (unquoted, without parameters).
10pub fn parse_accept_query<I, S>(values: I) -> Vec<String>
11where
12    I: IntoIterator<Item = S>,
13    S: AsRef<str>,
14{
15    let mut items = Vec::new();
16    for value in values {
17        for member in split_sf_list(value.as_ref()) {
18            if let Some(media_range) = sf_member_value(&member) {
19                items.push(media_range);
20            }
21        }
22    }
23    items
24}
25
26/// Serializes media ranges into a valid Structured Fields List for the
27/// `Accept-Query` header field, quoting values that are not valid Tokens.
28pub fn format_accept_query<I, S>(media_types: I) -> String
29where
30    I: IntoIterator<Item = S>,
31    S: AsRef<str>,
32{
33    let parts: Vec<String> = media_types
34        .into_iter()
35        .filter_map(|media_type| {
36            let trimmed = media_type.as_ref().trim();
37            if trimmed.is_empty() {
38                None
39            } else if is_sf_token(trimmed) {
40                Some(trimmed.to_string())
41            } else {
42                Some(encode_sf_string(trimmed))
43            }
44        })
45        .collect();
46    parts.join(", ")
47}
48
49/// Reports whether `media_type` is covered by the advertised `media_range`,
50/// honoring the `*/*` and `type/*` wildcards. Comparison is case-insensitive.
51pub fn matches_media_range(media_range: &str, media_type: &str) -> bool {
52    let range = media_range.trim().to_ascii_lowercase();
53    let media_type = media_type.trim().to_ascii_lowercase();
54
55    if range.is_empty() {
56        return false;
57    }
58    if range == "*/*" {
59        return true;
60    }
61    if let Some(prefix) = range.strip_suffix('*') {
62        if prefix.ends_with('/') {
63            return media_type.starts_with(prefix);
64        }
65    }
66    range == media_type
67}
68
69fn split_sf_list(value: &str) -> Vec<String> {
70    let mut members = Vec::new();
71    let mut buf = String::new();
72    let mut in_string = false;
73    let mut escaped = false;
74
75    for c in value.chars() {
76        if in_string {
77            buf.push(c);
78            if escaped {
79                escaped = false;
80            } else if c == '\\' {
81                escaped = true;
82            } else if c == '"' {
83                in_string = false;
84            }
85            continue;
86        }
87        match c {
88            '"' => {
89                in_string = true;
90                buf.push(c);
91            }
92            ',' => members.push(std::mem::take(&mut buf)),
93            _ => buf.push(c),
94        }
95    }
96    members.push(buf);
97    members
98}
99
100fn sf_member_value(member: &str) -> Option<String> {
101    let member = member.trim();
102    if member.is_empty() {
103        return None;
104    }
105
106    // Strip parameters (everything from the first top-level ';').
107    let member = match index_top_level(member, b';') {
108        Some(i) => member[..i].trim(),
109        None => member,
110    };
111    if member.is_empty() {
112        return None;
113    }
114
115    if member.len() >= 2 && member.starts_with('"') && member.ends_with('"') {
116        Some(decode_sf_string(member))
117    } else {
118        Some(member.to_string())
119    }
120}
121
122fn index_top_level(value: &str, sep: u8) -> Option<usize> {
123    let bytes = value.as_bytes();
124    let mut in_string = false;
125    let mut escaped = false;
126
127    for (i, &c) in bytes.iter().enumerate() {
128        if in_string {
129            if escaped {
130                escaped = false;
131            } else if c == b'\\' {
132                escaped = true;
133            } else if c == b'"' {
134                in_string = false;
135            }
136        } else if c == b'"' {
137            in_string = true;
138        } else if c == sep {
139            return Some(i);
140        }
141    }
142    None
143}
144
145fn decode_sf_string(quoted: &str) -> String {
146    let inner = &quoted[1..quoted.len() - 1];
147    let mut out = String::with_capacity(inner.len());
148    let mut escaped = false;
149    for c in inner.chars() {
150        if escaped {
151            out.push(c);
152            escaped = false;
153        } else if c == '\\' {
154            escaped = true;
155        } else {
156            out.push(c);
157        }
158    }
159    out
160}
161
162fn encode_sf_string(s: &str) -> String {
163    let mut out = String::with_capacity(s.len() + 2);
164    out.push('"');
165    for c in s.chars() {
166        if c == '\\' || c == '"' {
167            out.push('\\');
168        }
169        out.push(c);
170    }
171    out.push('"');
172    out
173}
174
175fn is_sf_token(s: &str) -> bool {
176    let bytes = s.as_bytes();
177    let Some(&first) = bytes.first() else {
178        return false;
179    };
180    if !first.is_ascii_alphabetic() && first != b'*' {
181        return false;
182    }
183    bytes[1..]
184        .iter()
185        .all(|&c| is_tchar(c) || c == b':' || c == b'/')
186}
187
188fn is_tchar(c: u8) -> bool {
189    c.is_ascii_alphanumeric()
190        || matches!(
191            c,
192            b'!' | b'#'
193                | b'$'
194                | b'%'
195                | b'&'
196                | b'\''
197                | b'*'
198                | b'+'
199                | b'-'
200                | b'.'
201                | b'^'
202                | b'_'
203                | b'`'
204                | b'|'
205                | b'~'
206        )
207}
208
209#[cfg(test)]
210mod tests {
211    use super::*;
212
213    #[test]
214    fn parses_structured_fields() {
215        let got =
216            parse_accept_query([r#""application/jsonpath", application/sql;charset="UTF-8""#]);
217        assert_eq!(got, vec!["application/jsonpath", "application/sql"]);
218    }
219
220    #[test]
221    fn comma_inside_quotes_is_not_a_separator() {
222        let got = parse_accept_query([r#"application/foo;p="a,b", text/plain"#]);
223        assert_eq!(got, vec!["application/foo", "text/plain"]);
224    }
225
226    #[test]
227    fn formats_and_quotes_non_tokens() {
228        assert_eq!(
229            format_accept_query(["application/json", "application/sql"]),
230            "application/json, application/sql"
231        );
232        assert_eq!(format_accept_query(["3d/model"]), r#""3d/model""#);
233        assert_eq!(format_accept_query(["*/*", "image/*"]), "*/*, image/*");
234    }
235
236    #[test]
237    fn round_trips() {
238        let input = ["application/json", "3d/model", "application/sql"];
239        let formatted = format_accept_query(input);
240        assert_eq!(parse_accept_query([formatted]), input);
241    }
242
243    #[test]
244    fn matches_wildcards_case_insensitively() {
245        assert!(matches_media_range("application/json", "APPLICATION/JSON"));
246        assert!(matches_media_range("*/*", "anything/here"));
247        assert!(matches_media_range("image/*", "image/png"));
248        assert!(!matches_media_range("image/*", "text/plain"));
249        assert!(!matches_media_range("application/json", "application/xml"));
250    }
251}