grippo 0.2.2

Parse, match and scrub data faster and more efficiently.
Documentation
// Project:   grippo
// File:      src/format/uri.rs
// Purpose:   A URI reference as fields, one a part
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! A URI reference as fields, split by [`crate::uri::split`].
//!
//! `scheme`, `user_info`, `host`, `port`, `path`, `query` and `fragment` are
//! each a span of the input, written only where the reference has it.
//! Nothing is decoded, so `uri > field("query"):query` reads the query's
//! pairs.

use crate::parse::{FieldSink, FieldValue, Hint, ParseError, Parsed, Parser};
use crate::strmatch::Signature;
use crate::tier::MatcherTier;

/// The URI parser, registered as `uri`.
#[derive(Debug, Clone)]
pub struct Uri {
    signature: Signature,
}

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

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

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

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

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

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

    /// Empty input or input that isn't UTF-8 is [`Parsed::NoMatch`].
    fn parse<'a>(
        &self,
        input: &'a [u8],
        out: &mut dyn FieldSink<'a>,
    ) -> Result<Parsed, ParseError> {
        let Ok(text) = std::str::from_utf8(input) else {
            return Ok(Parsed::NoMatch);
        };
        if text.is_empty() {
            return Ok(Parsed::NoMatch);
        }
        let parts = crate::uri::split(text);
        let port_hint = |p: &str| {
            if !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit()) {
                Hint::Int
            } else {
                Hint::Text
            }
        };
        let path = Some(parts.path).filter(|p| !p.is_empty());
        for (name, value, hint) in [
            ("scheme", parts.scheme, Hint::Text),
            ("user_info", parts.user_info, Hint::Text),
            ("host", parts.host, Hint::Text),
            ("port", parts.port, parts.port.map_or(Hint::Text, port_hint)),
            ("path", path, Hint::Text),
            ("query", parts.query, Hint::Text),
            ("fragment", parts.fragment, Hint::Text),
        ] {
            if let Some(value) = value {
                out.field(name, FieldValue::borrowed(value.as_bytes(), hint));
            }
        }
        Ok(Parsed::Done)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::parse::Fields;

    fn read(input: &[u8]) -> (Parsed, Vec<(String, String, Hint)>) {
        let mut out = Fields::new();
        let parsed = Uri::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(),
                    v.hint,
                )
            })
            .collect();
        (parsed, rows)
    }

    #[test]
    fn references_split_into_fields() {
        let t = Hint::Text;
        // An input, then the fields it writes. None writes nothing.
        let rows: &[(&[u8], &[(&str, &str, Hint)])] = &[
            (
                b"https://u:p@ex.com:8443/a/b?q=1&r=2#top",
                &[
                    ("scheme", "https", t),
                    ("user_info", "u:p", t),
                    ("host", "ex.com", t),
                    ("port", "8443", Hint::Int),
                    ("path", "/a/b", t),
                    ("query", "q=1&r=2", t),
                    ("fragment", "top", t),
                ],
            ),
            (
                b"/search?q=a+b",
                &[("path", "/search", t), ("query", "q=a+b", t)],
            ),
            (b"?q=1", &[("query", "q=1", t)]),
            (
                b"http://[::1]:x/",
                &[
                    ("scheme", "http", t),
                    ("host", "[::1]", t),
                    ("port", "x", t),
                    ("path", "/", t),
                ],
            ),
            (b"file://", &[("scheme", "file", t), ("host", "", t)]),
            (b"", &[]),
            (b"/a\xff", &[]),
        ];
        for (input, want) in rows {
            let shown = String::from_utf8_lossy(input);
            let (parsed, got) = read(input);
            let want: Vec<_> = want
                .iter()
                .map(|(k, v, h)| ((*k).to_owned(), (*v).to_owned(), *h))
                .collect();
            assert_eq!(got, want, "{shown}");
            let done = if want.is_empty() {
                Parsed::NoMatch
            } else {
                Parsed::Done
            };
            assert_eq!(parsed, done, "{shown}");
        }
    }

    #[cfg(feature = "parse-query")]
    #[test]
    fn a_chain_reads_the_query_of_a_uri() {
        use std::sync::Arc;

        use crate::format::query::Query;
        use crate::parse::{ParsePlan, Parsers, Status};

        let mut parsers = Parsers::new();
        parsers.register(Arc::new(Uri::new())).unwrap();
        parsers.register(Arc::new(Query::new())).unwrap();
        let plan = ParsePlan::chain(r#"uri > field("query"):query"#, &parsers).unwrap();
        let mut state = plan.source_state();
        let mut out = Fields::new();
        let outcome = plan.parse(b"/s?q=caf%C3%A9&tag=a&tag=b", &mut state, &mut out);
        assert_eq!(outcome.status, Status::Parsed, "{outcome:?}");
        let all = |n: &str| -> Vec<String> {
            out.get_all(n)
                .map(|v| String::from_utf8_lossy(&v.bytes).into_owned())
                .collect()
        };
        assert_eq!(all("path"), ["/s"]);
        assert_eq!(all("query"), ["q=caf%C3%A9&tag=a&tag=b"]);
        assert_eq!(all("query.q"), ["caf\u{e9}"]);
        assert_eq!(all("query.tag"), ["a", "b"]);
    }
}