pub(super) fn file_url_local(path: &str) -> Option<&str> {
if path.len() < 5 || !path.as_bytes()[..5].eq_ignore_ascii_case(b"file:") {
return None;
}
let rest = &path[5..];
Some(
rest.strip_prefix("//")
.map_or(rest, |authority| authority.find('/').map_or("", |i| &authority[i..])),
)
}
pub(super) fn is_network_url(path: &str) -> bool {
let Some(idx) = path.find("://") else {
return false;
};
let scheme = &path[..idx];
let well_formed_scheme = scheme.starts_with(|c: char| c.is_ascii_alphabetic())
&& scheme.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'+' | b'-' | b'.'));
well_formed_scheme && has_host(&path[idx + 3..])
}
fn has_host(after_scheme: &str) -> bool {
let authority = after_scheme.split('/').next().unwrap_or("");
!authority.is_empty() && authority != "." && authority != ".."
}
pub(crate) fn is_url(path: &str) -> bool {
file_url_local(path).is_some() || is_network_url(path)
}
#[cfg(test)]
mod tests {
use super::{file_url_local, is_url};
use proptest::prelude::*;
proptest! {
#[test]
fn a_file_url_names_the_local_path_inside_it(
path in "(/[a-zA-Z0-9_.]{1,6}){1,4}",
scheme in "[fF][iI][lL][eE]",
host in "[a-z]{1,6}",
) {
for url in [format!("{scheme}://{path}"), format!("{scheme}:{path}"), format!("{scheme}://{host}{path}")] {
prop_assert_eq!(file_url_local(&url), Some(path.as_str()), "{}", url);
prop_assert!(is_url(&url), "{}", url);
}
}
#[test]
fn a_path_or_a_hostless_scheme_is_not_a_url(
path in "(/[a-zA-Z0-9_]{1,6}){1,4}",
scheme in "[a-z][a-z0-9+.-]{0,5}",
) {
prop_assert!(!is_url(&path));
let hostless = format!("{scheme}://..{path}");
prop_assert!(scheme.eq_ignore_ascii_case("file") || !is_url(&hostless), "{}", hostless);
let hosted = format!("{scheme}://example.com{path}");
prop_assert!(is_url(&hosted), "{}", hosted);
}
}
}