use std::fmt;
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum UriError {
Syntax,
Relative,
}
impl fmt::Display for UriError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::Syntax => "not an RFC 3986 URI",
Self::Relative => "a relative reference where an RFC 3986 URI is required",
})
}
}
impl std::error::Error for UriError {}
pub fn check_uri(s: &str) -> Result<(), UriError> {
if iri_string::types::UriStr::new(s).is_ok() {
return Ok(());
}
if iri_string::types::UriReferenceStr::new(s).is_ok() {
Err(UriError::Relative)
} else {
Err(UriError::Syntax)
}
}
pub fn check_uri_reference(s: &str) -> Result<(), UriError> {
iri_string::types::UriReferenceStr::new(s)
.map(|_| ())
.map_err(|_| UriError::Syntax)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn rfc3986_examples_are_uris() {
for u in [
"ftp://ftp.is.co.za/rfc/rfc1808.txt",
"http://www.ietf.org/rfc/rfc2396.txt",
"ldap://[2001:db8::7]/c=GB?objectClass?one",
"mailto:John.Doe@example.com",
"news:comp.infosystems.www.servers.unix",
"tel:+1-816-555-1212",
"telnet://192.0.2.16:80/",
"urn:oasis:names:specification:docbook:dtd:xml:4.1.2",
] {
assert_eq!(check_uri(u), Ok(()), "{u}");
}
}
#[test]
fn relative_references() {
for r in ["g", "./g", "g/", "/g", "//g", "?y", "g?y", "#s", "../g"] {
assert_eq!(check_uri(r), Err(UriError::Relative), "{r}");
assert_eq!(check_uri_reference(r), Ok(()), "{r}");
}
}
#[test]
fn syntax_errors() {
for s in [
"https://example.com/a b",
"https://example.com/ü",
"https://example.com/%zz",
"",
] {
assert_eq!(
check_uri(s),
if s.is_empty() {
Err(UriError::Relative)
} else {
Err(UriError::Syntax)
},
"{s:?}"
);
}
assert_eq!(
check_uri_reference("https://example.com/a b"),
Err(UriError::Syntax)
);
}
}