use std::{borrow::Cow, fmt};
use crate::error::{ErrorKind, InvalidUrl};
use crate::quoting::{Component, unquote};
use crate::{chars, host::validate_host};
#[repr(transparent)]
pub struct Authority(str);
str_type!(Authority);
str_eq!(Authority);
impl Authority {
pub fn new(src: &str) -> Result<&Authority, InvalidUrl> {
validate_authority(src)?;
Ok(Authority::from_str_unchecked(src))
}
pub fn from_static(src: &'static str) -> &'static Authority {
match Authority::new(src) {
Ok(auth) => auth,
Err(e) => panic!("invalid static authority {src:?}: {e}"),
}
}
pub fn userinfo(&self) -> Option<&UserInfo> {
split(&self.0).0.map(UserInfo::from_str_unchecked)
}
pub fn host(&self) -> &str {
split(&self.0).1
}
pub fn port(&self) -> Option<Port<&str>> {
split(&self.0).2.and_then(Port::parse)
}
pub fn port_u16(&self) -> Option<u16> {
self.port().map(|p| p.as_u16())
}
pub fn host_port(&self) -> &str {
chars::rfind_byte(self.0.as_bytes(), b'@').map_or(&self.0, |i| &self.0[i + 1..])
}
}
pub(crate) fn split(s: &str) -> (Option<&str>, &str, Option<&str>) {
let (userinfo, hp) = match chars::rfind_byte(s.as_bytes(), b'@') {
Some(i) => (Some(&s[..i]), &s[i + 1..]),
None => (None, s),
};
if hp.starts_with('[') {
if let Some(end) = hp.find(']') {
let rest = &hp[end + 1..];
if rest.is_empty() {
return (userinfo, hp, None);
}
if let Some(port) = rest.strip_prefix(':') {
return (userinfo, &hp[..=end], Some(port));
}
}
return (userinfo, hp, None);
}
match chars::rfind_byte(hp.as_bytes(), b':') {
Some(i) => (userinfo, &hp[..i], Some(&hp[i + 1..])),
None => (userinfo, hp, None),
}
}
pub(crate) fn offset(outer: &str, inner: &str) -> usize {
inner.as_ptr() as usize - outer.as_ptr() as usize
}
pub(crate) fn validate_authority(s: &str) -> Result<(), InvalidUrl> {
let (userinfo, host, port) = split(s);
if let Some(userinfo) = userinfo {
chars::check(userinfo, &chars::USERINFO)?;
}
validate_host(host).map_err(|e| e.offset(offset(s, host)))?;
if let Some(port) = port {
parse_port(port).map_err(|e| e.offset(offset(s, port)))?;
}
Ok(())
}
pub(crate) fn parse_port(s: &str) -> Result<u16, InvalidUrl> {
if let Some(i) = s.bytes().position(|b| !b.is_ascii_digit()) {
return Err(InvalidUrl::at(ErrorKind::InvalidPort, i));
}
s.bytes()
.try_fold(0u16, |acc, b| {
acc.checked_mul(10)?.checked_add(u16::from(b - b'0'))
})
.ok_or(InvalidUrl::at(ErrorKind::PortOutOfRange, 0))
}
#[repr(transparent)]
pub struct UserInfo(str);
str_type!(UserInfo);
str_eq!(UserInfo);
impl UserInfo {
pub fn new(src: &str) -> Result<&UserInfo, InvalidUrl> {
chars::check(src, &chars::USERINFO)?;
Ok(UserInfo::from_str_unchecked(src))
}
pub fn username(&self) -> &str {
self.0.split_once(':').map_or(&self.0, |(user, _)| user)
}
pub fn password(&self) -> Option<&str> {
self.0.split_once(':').map(|(_, password)| password)
}
pub fn decoded_username(&self) -> Cow<'_, str> {
unquote(self.username(), Component::UserInfo)
}
pub fn decoded_password(&self) -> Option<Cow<'_, str>> {
self.password().map(|p| unquote(p, Component::UserInfo))
}
}
#[derive(Copy, Clone, Debug)]
pub struct Port<T> {
port: u16,
repr: T,
}
impl<'a> Port<&'a str> {
pub(crate) fn parse(repr: &'a str) -> Option<Self> {
let port = parse_port(repr).ok().filter(|_| !repr.is_empty())?;
Some(Port { port, repr })
}
}
impl<T> Port<T> {
pub const fn as_u16(&self) -> u16 {
self.port
}
}
impl<T: AsRef<str>> Port<T> {
pub fn as_str(&self) -> &str {
self.repr.as_ref()
}
}
impl<T> PartialEq<u16> for Port<T> {
fn eq(&self, other: &u16) -> bool {
self.port == *other
}
}
impl<T, U> PartialEq<Port<U>> for Port<T> {
fn eq(&self, other: &Port<U>) -> bool {
self.port == other.port
}
}
impl<T: AsRef<str>> fmt::Display for Port<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn split_authority() {
assert_eq!(split("a@b:1"), (Some("a"), "b", Some("1")));
assert_eq!(split("a:p@b"), (Some("a:p"), "b", None));
assert_eq!(split("[::1]:80"), (None, "[::1]", Some("80")));
assert_eq!(split("[::1]"), (None, "[::1]", None));
assert_eq!(split("[::1]x"), (None, "[::1]x", None));
assert_eq!(split("b:"), (None, "b", Some("")));
}
#[test]
fn split_long_authority() {
assert_eq!(
split("user:pass@word@example.com:8443"),
(Some("user:pass@word"), "example.com", Some("8443"))
);
assert_eq!(split("ab:cdefghijk"), (None, "ab", Some("cdefghijk")));
assert_eq!(split("a@bcdefghijk"), (Some("a"), "bcdefghijk", None));
assert_eq!(split("abcdefgh:1"), (None, "abcdefgh", Some("1")));
assert_eq!(split("example.com"), (None, "example.com", None));
assert_eq!(
split("user@[2001:db8::1]:443"),
(Some("user"), "[2001:db8::1]", Some("443"))
);
let auth = Authority::new("user:pw@example.com:8080").unwrap();
assert_eq!(auth.host_port(), "example.com:8080");
}
#[test]
fn strict() {
assert!(Authority::new("").is_ok());
assert!(Authority::new("u:p@h.com:").is_ok());
assert!(Authority::new("[::1]:65535").is_ok());
let err = Authority::new("u p@h").unwrap_err();
assert_eq!(err.kind(), ErrorKind::InvalidChar(' '));
assert_eq!(err.position(), Some(1));
let err = Authority::new("h:8x").unwrap_err();
assert_eq!(err.kind(), ErrorKind::InvalidPort);
assert_eq!(err.position(), Some(3));
let err = Authority::new("[::1").unwrap_err();
assert_eq!(err.kind(), ErrorKind::InvalidIpv6);
let err = Authority::new("1.2.3.256").unwrap_err();
assert_eq!(err.kind(), ErrorKind::InvalidIpv4);
}
#[test]
fn port() {
let p = Port::parse("0080").unwrap();
assert_eq!(p, 80);
assert_eq!(p.as_str(), "0080");
assert!(Port::parse("65536").is_none());
assert!(Port::parse("").is_none());
assert!(Port::parse("1a").is_none());
}
}