Skip to main content

grippo/format/
uri.rs

1// Project:   grippo
2// File:      src/format/uri.rs
3// Purpose:   A URI reference as fields, one a part
4// Language:  Rust
5//
6// License:   Apache-2.0
7// Copyright: (c) 2026 HYPERI PTY LIMITED
8
9//! A URI reference as fields, split by [`crate::uri::split`].
10//!
11//! `scheme`, `user_info`, `host`, `port`, `path`, `query` and `fragment` are
12//! each a span of the input, written only where the reference has it.
13//! Nothing is decoded, so `uri > field("query"):query` reads the query's
14//! pairs.
15
16use crate::parse::{FieldSink, FieldValue, Hint, ParseError, Parsed, Parser};
17use crate::strmatch::Signature;
18use crate::tier::MatcherTier;
19
20/// The URI parser, registered as `uri`.
21#[derive(Debug, Clone)]
22pub struct Uri {
23    signature: Signature,
24}
25
26impl Default for Uri {
27    fn default() -> Self {
28        Self::new()
29    }
30}
31
32impl Uri {
33    /// A URI parser.
34    #[must_use]
35    pub fn new() -> Self {
36        let signature = Signature::builder()
37            .build()
38            .unwrap_or_else(|_| unreachable!("invariant: an empty signature always builds"));
39        Self { signature }
40    }
41}
42
43impl Parser for Uri {
44    fn hands_on_body(&self) -> bool {
45        false
46    }
47
48    fn name(&self) -> &'static str {
49        "uri"
50    }
51
52    fn tier(&self) -> MatcherTier {
53        MatcherTier::Field
54    }
55
56    fn signature(&self) -> &Signature {
57        &self.signature
58    }
59
60    /// Empty input or input that isn't UTF-8 is [`Parsed::NoMatch`].
61    fn parse<'a>(
62        &self,
63        input: &'a [u8],
64        out: &mut dyn FieldSink<'a>,
65    ) -> Result<Parsed, ParseError> {
66        let Ok(text) = std::str::from_utf8(input) else {
67            return Ok(Parsed::NoMatch);
68        };
69        if text.is_empty() {
70            return Ok(Parsed::NoMatch);
71        }
72        let parts = crate::uri::split(text);
73        let port_hint = |p: &str| {
74            if !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit()) {
75                Hint::Int
76            } else {
77                Hint::Text
78            }
79        };
80        let path = Some(parts.path).filter(|p| !p.is_empty());
81        for (name, value, hint) in [
82            ("scheme", parts.scheme, Hint::Text),
83            ("user_info", parts.user_info, Hint::Text),
84            ("host", parts.host, Hint::Text),
85            ("port", parts.port, parts.port.map_or(Hint::Text, port_hint)),
86            ("path", path, Hint::Text),
87            ("query", parts.query, Hint::Text),
88            ("fragment", parts.fragment, Hint::Text),
89        ] {
90            if let Some(value) = value {
91                out.field(name, FieldValue::borrowed(value.as_bytes(), hint));
92            }
93        }
94        Ok(Parsed::Done)
95    }
96}
97
98#[cfg(test)]
99mod tests {
100    use super::*;
101    use crate::parse::Fields;
102
103    fn read(input: &[u8]) -> (Parsed, Vec<(String, String, Hint)>) {
104        let mut out = Fields::new();
105        let parsed = Uri::new().parse(input, &mut out).unwrap();
106        let rows = out
107            .as_slice()
108            .iter()
109            .map(|(k, v)| {
110                (
111                    k.clone(),
112                    String::from_utf8(v.bytes.to_vec()).unwrap(),
113                    v.hint,
114                )
115            })
116            .collect();
117        (parsed, rows)
118    }
119
120    #[test]
121    fn references_split_into_fields() {
122        let t = Hint::Text;
123        // An input, then the fields it writes. None writes nothing.
124        let rows: &[(&[u8], &[(&str, &str, Hint)])] = &[
125            (
126                b"https://u:p@ex.com:8443/a/b?q=1&r=2#top",
127                &[
128                    ("scheme", "https", t),
129                    ("user_info", "u:p", t),
130                    ("host", "ex.com", t),
131                    ("port", "8443", Hint::Int),
132                    ("path", "/a/b", t),
133                    ("query", "q=1&r=2", t),
134                    ("fragment", "top", t),
135                ],
136            ),
137            (
138                b"/search?q=a+b",
139                &[("path", "/search", t), ("query", "q=a+b", t)],
140            ),
141            (b"?q=1", &[("query", "q=1", t)]),
142            (
143                b"http://[::1]:x/",
144                &[
145                    ("scheme", "http", t),
146                    ("host", "[::1]", t),
147                    ("port", "x", t),
148                    ("path", "/", t),
149                ],
150            ),
151            (b"file://", &[("scheme", "file", t), ("host", "", t)]),
152            (b"", &[]),
153            (b"/a\xff", &[]),
154        ];
155        for (input, want) in rows {
156            let shown = String::from_utf8_lossy(input);
157            let (parsed, got) = read(input);
158            let want: Vec<_> = want
159                .iter()
160                .map(|(k, v, h)| ((*k).to_owned(), (*v).to_owned(), *h))
161                .collect();
162            assert_eq!(got, want, "{shown}");
163            let done = if want.is_empty() {
164                Parsed::NoMatch
165            } else {
166                Parsed::Done
167            };
168            assert_eq!(parsed, done, "{shown}");
169        }
170    }
171
172    #[cfg(feature = "parse-query")]
173    #[test]
174    fn a_chain_reads_the_query_of_a_uri() {
175        use std::sync::Arc;
176
177        use crate::format::query::Query;
178        use crate::parse::{ParsePlan, Parsers, Status};
179
180        let mut parsers = Parsers::new();
181        parsers.register(Arc::new(Uri::new())).unwrap();
182        parsers.register(Arc::new(Query::new())).unwrap();
183        let plan = ParsePlan::chain(r#"uri > field("query"):query"#, &parsers).unwrap();
184        let mut state = plan.source_state();
185        let mut out = Fields::new();
186        let outcome = plan.parse(b"/s?q=caf%C3%A9&tag=a&tag=b", &mut state, &mut out);
187        assert_eq!(outcome.status, Status::Parsed, "{outcome:?}");
188        let all = |n: &str| -> Vec<String> {
189            out.get_all(n)
190                .map(|v| String::from_utf8_lossy(&v.bytes).into_owned())
191                .collect()
192        };
193        assert_eq!(all("path"), ["/s"]);
194        assert_eq!(all("query"), ["q=caf%C3%A9&tag=a&tag=b"]);
195        assert_eq!(all("query.q"), ["caf\u{e9}"]);
196        assert_eq!(all("query.tag"), ["a", "b"]);
197    }
198}