grippo 0.1.0

Parse, match and scrub data at scale.
Documentation
// Project:   grippo
// File:      src/uri/java.rs
// Purpose:   URI parts as java.net.URI reads them, with the java.net.URL fallback
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! URI parts as `java.net.URI` reads them, falling back to `java.net.URL`
//! where `URI` throws, and nothing where both do.
//!
//! The rules come from the JDK's `URI$Parser` and `URL` constructor: RFC
//! 2396's legal characters, a scheme name required before the first colon
//! ahead of any `/`, `?` or `#`, an authority that is server-based only
//! when its host and port both read, and a fallback that knows six
//! protocols, trims the text and decodes nothing.

use std::borrow::Cow;
use std::net::Ipv6Addr;

use super::percent::{self, Mode};
use super::{UriRef, split};

/// Which Java parser took the text.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Reading {
    /// `java.net.URI`, hierarchical. Its getters decode the path and query once.
    Uri,
    /// `java.net.URI`, opaque: a scheme whose remainder doesn't start with
    /// `/`, such as `mailto:`. Only the scheme and fragment are set.
    Opaque,
    /// The `java.net.URL` fallback, read from the text with leading and
    /// trailing spaces and controls trimmed. It decodes nothing.
    Url,
}

/// A URI's parts as the Java reading reports them. Each part borrows the text.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct JavaParts<'a> {
    /// Which Java parser took the text.
    pub reading: Reading,
    /// The scheme, as written.
    pub scheme: Option<&'a str>,
    /// The user info before the authority's `@`.
    pub user_info: Option<&'a str>,
    /// The host, non-empty. Under [`Reading::Uri`] only a server-based
    /// authority has one, so a registry authority such as `m1:1,m2:2` has none.
    pub host: Option<&'a str>,
    /// The port, where it reads as a `u32`.
    pub port: Option<u32>,
    /// The path as written. `Some("")` where an authority has no path, and
    /// `None` where neither is there.
    pub path: Option<&'a str>,
    /// The query as written.
    pub query: Option<&'a str>,
    /// The fragment, never decoded.
    pub fragment: Option<&'a str>,
}

impl<'a> JavaParts<'a> {
    /// The user info before its first `:`, or all of it.
    #[must_use]
    pub fn username(&self) -> Option<&'a str> {
        self.user_info
            .map(|info| info.split_once(':').map_or(info, |(name, _)| name))
    }

    /// The user info after its first `:`.
    #[must_use]
    pub fn password(&self) -> Option<&'a str> {
        self.user_info
            .and_then(|info| info.split_once(':'))
            .map(|(_, password)| password)
    }

    /// The path as `getPath` returns it: decoded once under
    /// [`Reading::Uri`], with bad UTF-8 as U+FFFD, and as written otherwise.
    #[must_use]
    pub fn decoded_path(&self) -> Option<Cow<'a, str>> {
        self.path.map(|path| self.decoded(path))
    }

    /// The query as `getQuery` returns it, decoded as [`Self::decoded_path`] is.
    #[must_use]
    pub fn decoded_query(&self) -> Option<Cow<'a, str>> {
        self.query.map(|query| self.decoded(query))
    }

    fn decoded(&self, part: &'a str) -> Cow<'a, str> {
        match self.reading {
            Reading::Uri => percent::decode(part, Mode::URI).unwrap_or(Cow::Borrowed(part)),
            Reading::Opaque | Reading::Url => Cow::Borrowed(part),
        }
    }
}

/// `text`'s parts as `java.net.URI` reads them, or as `java.net.URL` does
/// where `URI` throws, or `None` where both throw or the text is empty.
#[must_use]
pub fn parts(text: &str) -> Option<JavaParts<'_>> {
    if text.is_empty() {
        return None;
    }
    let whole = split(text);
    let uri_legal = uri_legal(text, &whole);
    let (uri, reading) = if uri_legal {
        (whole, Reading::Uri)
    } else {
        let uri = split(url_spec(text));
        if !url_parses(&uri) {
            return None;
        }
        (uri, Reading::Url)
    };

    if let Some(scheme) = uri_legal.then(|| opaque_scheme(text)).flatten() {
        return Some(JavaParts {
            reading: Reading::Opaque,
            scheme: Some(scheme),
            user_info: None,
            host: None,
            port: None,
            path: None,
            query: None,
            fragment: uri.fragment,
        });
    }

    let server = !uri_legal || server_authority(&uri);
    let path = if uri.path.is_empty() {
        uri.host.map(|_| uri.path)
    } else {
        Some(uri.path)
    };
    Some(JavaParts {
        reading,
        scheme: uri.scheme,
        user_info: uri.user_info,
        host: uri.host.filter(|host| server && !host.is_empty()),
        port: uri
            .port
            .filter(|_| server)
            .and_then(|port| port.parse::<u32>().ok()),
        path,
        query: uri.query,
        fragment: uri.fragment,
    })
}

/// Whether `java.net.URI` accepts every character of `text` and its authority.
///
/// The legal set is RFC 2396's unreserved, reserved and escaped characters
/// plus any non-ASCII character that is neither a control nor a space. The
/// path's set has no bracket, where the query's does.
fn uri_legal(text: &str, uri: &UriRef<'_>) -> bool {
    if !scheme_prefix_legal(text) || !authority_legal(uri) {
        return false;
    }
    let bytes = text.as_bytes();
    let mut i = 0;
    while i < bytes.len() {
        let b = bytes[i];
        if !b.is_ascii() {
            i += 1;
            continue;
        }
        if b == b'%' {
            let hex = bytes.get(i + 1..i + 3);
            if !hex.is_some_and(|h| h.iter().all(u8::is_ascii_hexdigit)) {
                return false;
            }
            i += 3;
            continue;
        }
        if !(b.is_ascii_alphanumeric() || b"-_.!~*'();/?:@&=+$,[]#".contains(&b)) {
            return false;
        }
        i += 1;
    }
    if uri.path.contains(['[', ']']) {
        return false;
    }
    text.chars().all(|c| !c.is_control() && !is_space_char(c))
}

/// Whether the first colon before any `/`, `?` or `#` has a scheme name in
/// front, which `URI$Parser` demands of it.
fn scheme_prefix_legal(text: &str) -> bool {
    let stop = text.find(['/', '?', '#']).unwrap_or(text.len());
    match text[..stop].find(':') {
        Some(0) => false,
        Some(colon) => super::is_scheme(&text[..colon]),
        None => true,
    }
}

/// Whether the authority's brackets, if any, are a host's IPv6 literal, the
/// one place either authority reading takes them.
fn authority_legal(uri: &UriRef<'_>) -> bool {
    let bracketed = |part: &str| part.contains(['[', ']']);
    if uri.user_info.is_some_and(bracketed) || uri.port.is_some_and(bracketed) {
        return false;
    }
    match uri.host {
        Some(host) if bracketed(host) => ipv6_reference(host),
        _ => true,
    }
}

/// Whether `host` is a bracketed IPv6 address, an RFC 6874 zone id allowed after it.
fn ipv6_reference(host: &str) -> bool {
    let Some(inner) = host.strip_prefix('[').and_then(|h| h.strip_suffix(']')) else {
        return false;
    };
    let address = inner.split_once('%').map_or(inner, |(head, _)| head);
    address.parse::<Ipv6Addr>().is_ok()
}

/// The text `java.net.URL` parses: characters at or below a space trimmed off both ends.
fn url_spec(text: &str) -> &str {
    text.trim_matches(|c: char| c <= ' ')
}

/// The scheme of a URI `java.net.URI` reads as opaque.
fn opaque_scheme(text: &str) -> Option<&str> {
    let stop = text.find(['/', '?', '#']).unwrap_or(text.len());
    let colon = text[..stop].find(':')?;
    let scheme = &text[..colon];
    if !super::is_scheme(scheme) {
        return None;
    }
    let part = &text[colon + 1..text.find('#').unwrap_or(text.len())];
    (!part.is_empty() && !part.starts_with('/')).then_some(scheme)
}

/// Java's `Character.isSpaceChar`: the Unicode space separators.
const fn is_space_char(c: char) -> bool {
    matches!(
        c,
        ' ' | '\u{a0}' | '\u{1680}' | '\u{2000}'
            ..='\u{200a}' | '\u{2028}' | '\u{2029}' | '\u{202f}' | '\u{205f}' | '\u{3000}'
    )
}

/// Whether `java.net.URI` reads the authority as server-based: a hostname,
/// IPv4 address or bracketed IPv6 host and a port of digits only, both at once.
fn server_authority(uri: &UriRef<'_>) -> bool {
    let Some(host) = uri.host else {
        return false;
    };
    if !uri
        .port
        .is_none_or(|port| port.bytes().all(|b| b.is_ascii_digit()))
    {
        return false;
    }
    if let Some(inner) = host.strip_prefix('[') {
        return inner.ends_with(']');
    }
    ipv4_address(host) || hostname(host)
}

/// Java's `parseIPv4Address`: four groups of one to three digits up to 255,
/// leading zeros allowed, which `Ipv4Addr`'s parse refuses.
fn ipv4_address(host: &str) -> bool {
    let mut groups = 0_usize;
    for group in host.split('.') {
        groups += 1;
        if group.is_empty() || group.len() > 3 || !group.bytes().all(|b| b.is_ascii_digit()) {
            return false;
        }
        if group.parse::<u16>().is_ok_and(|octet| octet > 255) {
            return false;
        }
    }
    groups == 4
}

/// Java's `parseHostname`: labels of ASCII letters, digits and inner
/// dashes, one trailing dot allowed, and a qualified name's last label
/// starting with a letter.
fn hostname(host: &str) -> bool {
    let trimmed = host
        .strip_suffix('.')
        .filter(|head| !head.is_empty())
        .unwrap_or(host);
    let mut labels = 0_usize;
    let mut last_first = 0_u8;
    for label in trimmed.split('.') {
        let bytes = label.as_bytes();
        let (Some(&first), Some(&end)) = (bytes.first(), bytes.last()) else {
            return false;
        };
        if !first.is_ascii_alphanumeric()
            || !end.is_ascii_alphanumeric()
            || !bytes
                .iter()
                .all(|b| b.is_ascii_alphanumeric() || *b == b'-')
        {
            return false;
        }
        labels += 1;
        last_first = first;
    }
    labels == 1 || last_first.is_ascii_alphabetic()
}

/// Whether the `java.net.URL` fallback parses: a protocol the JDK ships a
/// handler for, a bracketed host that is an IPv6 address, and a port that
/// is empty or digits.
fn url_parses(uri: &UriRef<'_>) -> bool {
    let Some(scheme) = uri.scheme else {
        return false;
    };
    let known = ["http", "https", "file", "ftp", "jar", "mailto"];
    if !known.iter().any(|name| scheme.eq_ignore_ascii_case(name)) {
        return false;
    }
    if uri
        .host
        .is_some_and(|host| host.starts_with('[') && !ipv6_reference(host))
    {
        return false;
    }
    uri.port
        .is_none_or(|port| port.bytes().all(|b| b.is_ascii_digit()))
}