use std::convert::TryFrom;
use std::hash::{Hash, Hasher};
use std::str::FromStr;
use std::{cmp, fmt, str};
use bytes::Bytes;
use super::{ErrorKind, InvalidUri, Port, URI_CHARS};
use crate::byte_str::ByteStr;
#[derive(Clone)]
pub struct Authority {
pub(super) data: ByteStr,
}
impl Authority {
pub(super) fn empty() -> Self {
Authority {
data: ByteStr::new(),
}
}
pub(super) fn from_shared(s: Bytes) -> Result<Self, InvalidUri> {
let authority_end = Authority::parse_non_empty(&s[..])?;
if authority_end != s.len() {
return Err(ErrorKind::InvalidUriChar.into());
}
Ok(Authority {
data: unsafe { ByteStr::from_utf8_unchecked(s) },
})
}
pub fn from_static(src: &'static str) -> Self {
let s = src.as_bytes();
let b = Bytes::from_static(s);
let authority_end =
Authority::parse_non_empty(&b[..]).expect("static str is not valid authority");
if authority_end != b.len() {
panic!("static str is not valid authority");
}
Authority {
data: unsafe { ByteStr::from_utf8_unchecked(b) },
}
}
pub fn from_maybe_shared<T>(src: T) -> Result<Self, InvalidUri>
where
T: AsRef<[u8]> + 'static,
{
if_downcast_into!(T, Bytes, src, {
return Authority::from_shared(src);
});
Authority::try_from(src.as_ref())
}
pub(super) fn parse(s: &[u8]) -> Result<usize, InvalidUri> {
let mut colon_cnt = 0;
let mut start_bracket = false;
let mut end_bracket = false;
let mut has_percent = false;
let mut end = s.len();
let mut at_sign_pos = None;
for (i, &b) in s.iter().enumerate() {
match URI_CHARS[b as usize] {
b'/' | b'?' | b'#' => {
end = i;
break;
}
b':' => {
colon_cnt += 1;
}
b'[' => {
start_bracket = true;
if has_percent {
return Err(ErrorKind::InvalidAuthority.into());
}
}
b']' => {
end_bracket = true;
colon_cnt = 0;
has_percent = false;
}
b'@' => {
at_sign_pos = Some(i);
colon_cnt = 0;
has_percent = false;
}
0 if b == b'%' => {
has_percent = true;
}
0 => {
return Err(ErrorKind::InvalidUriChar.into());
}
_ => {}
}
}
if start_bracket ^ end_bracket {
return Err(ErrorKind::InvalidAuthority.into());
}
if colon_cnt > 1 {
return Err(ErrorKind::InvalidAuthority.into());
}
if end > 0 && at_sign_pos == Some(end - 1) {
return Err(ErrorKind::InvalidAuthority.into());
}
if has_percent {
return Err(ErrorKind::InvalidAuthority.into());
}
Ok(end)
}
fn parse_non_empty(s: &[u8]) -> Result<usize, InvalidUri> {
if s.is_empty() {
return Err(ErrorKind::Empty.into());
}
Authority::parse(s)
}
#[inline]
pub fn host(&self) -> &str {
host(self.as_str())
}
pub fn port(&self) -> Option<Port<&str>> {
let bytes = self.as_str();
bytes
.rfind(":")
.and_then(|i| Port::from_str(&bytes[i + 1..]).ok())
}
pub fn port_u16(&self) -> Option<u16> {
self.port().and_then(|p| Some(p.as_u16()))
}
#[inline]
pub fn as_str(&self) -> &str {
&self.data[..]
}
}
impl AsRef<str> for Authority {
fn as_ref(&self) -> &str {
self.as_str()
}
}
impl PartialEq for Authority {
fn eq(&self, other: &Authority) -> bool {
self.data.eq_ignore_ascii_case(&other.data)
}
}
impl Eq for Authority {}
impl PartialEq<str> for Authority {
fn eq(&self, other: &str) -> bool {
self.data.eq_ignore_ascii_case(other)
}
}
impl PartialEq<Authority> for str {
fn eq(&self, other: &Authority) -> bool {
self.eq_ignore_ascii_case(other.as_str())
}
}
impl<'a> PartialEq<Authority> for &'a str {
fn eq(&self, other: &Authority) -> bool {
self.eq_ignore_ascii_case(other.as_str())
}
}
impl<'a> PartialEq<&'a str> for Authority {
fn eq(&self, other: &&'a str) -> bool {
self.data.eq_ignore_ascii_case(other)
}
}
impl PartialEq<String> for Authority {
fn eq(&self, other: &String) -> bool {
self.data.eq_ignore_ascii_case(other.as_str())
}
}
impl PartialEq<Authority> for String {
fn eq(&self, other: &Authority) -> bool {
self.as_str().eq_ignore_ascii_case(other.as_str())
}
}
impl PartialOrd for Authority {
fn partial_cmp(&self, other: &Authority) -> Option<cmp::Ordering> {
let left = self.data.as_bytes().iter().map(|b| b.to_ascii_lowercase());
let right = other.data.as_bytes().iter().map(|b| b.to_ascii_lowercase());
left.partial_cmp(right)
}
}
impl PartialOrd<str> for Authority {
fn partial_cmp(&self, other: &str) -> Option<cmp::Ordering> {
let left = self.data.as_bytes().iter().map(|b| b.to_ascii_lowercase());
let right = other.as_bytes().iter().map(|b| b.to_ascii_lowercase());
left.partial_cmp(right)
}
}
impl PartialOrd<Authority> for str {
fn partial_cmp(&self, other: &Authority) -> Option<cmp::Ordering> {
let left = self.as_bytes().iter().map(|b| b.to_ascii_lowercase());
let right = other.data.as_bytes().iter().map(|b| b.to_ascii_lowercase());
left.partial_cmp(right)
}
}
impl<'a> PartialOrd<Authority> for &'a str {
fn partial_cmp(&self, other: &Authority) -> Option<cmp::Ordering> {
let left = self.as_bytes().iter().map(|b| b.to_ascii_lowercase());
let right = other.data.as_bytes().iter().map(|b| b.to_ascii_lowercase());
left.partial_cmp(right)
}
}
impl<'a> PartialOrd<&'a str> for Authority {
fn partial_cmp(&self, other: &&'a str) -> Option<cmp::Ordering> {
let left = self.data.as_bytes().iter().map(|b| b.to_ascii_lowercase());
let right = other.as_bytes().iter().map(|b| b.to_ascii_lowercase());
left.partial_cmp(right)
}
}
impl PartialOrd<String> for Authority {
fn partial_cmp(&self, other: &String) -> Option<cmp::Ordering> {
let left = self.data.as_bytes().iter().map(|b| b.to_ascii_lowercase());
let right = other.as_bytes().iter().map(|b| b.to_ascii_lowercase());
left.partial_cmp(right)
}
}
impl PartialOrd<Authority> for String {
fn partial_cmp(&self, other: &Authority) -> Option<cmp::Ordering> {
let left = self.as_bytes().iter().map(|b| b.to_ascii_lowercase());
let right = other.data.as_bytes().iter().map(|b| b.to_ascii_lowercase());
left.partial_cmp(right)
}
}
impl Hash for Authority {
fn hash<H>(&self, state: &mut H)
where
H: Hasher,
{
self.data.len().hash(state);
for &b in self.data.as_bytes() {
state.write_u8(b.to_ascii_lowercase());
}
}
}
impl<'a> TryFrom<&'a [u8]> for Authority {
type Error = InvalidUri;
#[inline]
fn try_from(s: &'a [u8]) -> Result<Self, Self::Error> {
let end = Authority::parse_non_empty(s)?;
if end != s.len() {
return Err(ErrorKind::InvalidAuthority.into());
}
Ok(Authority {
data: unsafe {
ByteStr::from_utf8_unchecked(Bytes::copy_from_slice(s))
},
})
}
}
impl<'a> TryFrom<&'a str> for Authority {
type Error = InvalidUri;
#[inline]
fn try_from(s: &'a str) -> Result<Self, Self::Error> {
TryFrom::try_from(s.as_bytes())
}
}
impl FromStr for Authority {
type Err = InvalidUri;
fn from_str(s: &str) -> Result<Self, InvalidUri> {
TryFrom::try_from(s)
}
}
impl fmt::Debug for Authority {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
impl fmt::Display for Authority {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
fn host(auth: &str) -> &str {
let host_port = auth
.rsplitn(2, '@')
.next()
.expect("split always has at least 1 item");
if host_port.as_bytes()[0] == b'[' {
let i = host_port
.find(']')
.expect("parsing should validate brackets");
&host_port[0..i + 1]
} else {
host_port
.split(':')
.next()
.expect("split always has at least 1 item")
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse_empty_string_is_error() {
let err = Authority::parse_non_empty(b"").unwrap_err();
assert_eq!(err.0, ErrorKind::Empty);
}
#[test]
fn equal_to_self_of_same_authority() {
let authority1: Authority = "example.com".parse().unwrap();
let authority2: Authority = "EXAMPLE.COM".parse().unwrap();
assert_eq!(authority1, authority2);
assert_eq!(authority2, authority1);
}
#[test]
fn not_equal_to_self_of_different_authority() {
let authority1: Authority = "example.com".parse().unwrap();
let authority2: Authority = "test.com".parse().unwrap();
assert_ne!(authority1, authority2);
assert_ne!(authority2, authority1);
}
#[test]
fn equates_with_a_str() {
let authority: Authority = "example.com".parse().unwrap();
assert_eq!(&authority, "EXAMPLE.com");
assert_eq!("EXAMPLE.com", &authority);
assert_eq!(authority, "EXAMPLE.com");
assert_eq!("EXAMPLE.com", authority);
}
#[test]
fn not_equal_with_a_str_of_a_different_authority() {
let authority: Authority = "example.com".parse().unwrap();
assert_ne!(&authority, "test.com");
assert_ne!("test.com", &authority);
assert_ne!(authority, "test.com");
assert_ne!("test.com", authority);
}
#[test]
fn equates_with_a_string() {
let authority: Authority = "example.com".parse().unwrap();
assert_eq!(authority, "EXAMPLE.com".to_string());
assert_eq!("EXAMPLE.com".to_string(), authority);
}
#[test]
fn equates_with_a_string_of_a_different_authority() {
let authority: Authority = "example.com".parse().unwrap();
assert_ne!(authority, "test.com".to_string());
assert_ne!("test.com".to_string(), authority);
}
#[test]
fn compares_to_self() {
let authority1: Authority = "abc.com".parse().unwrap();
let authority2: Authority = "def.com".parse().unwrap();
assert!(authority1 < authority2);
assert!(authority2 > authority1);
}
#[test]
fn compares_with_a_str() {
let authority: Authority = "def.com".parse().unwrap();
assert!(&authority < "ghi.com");
assert!("ghi.com" > &authority);
assert!(&authority > "abc.com");
assert!("abc.com" < &authority);
assert!(authority < "ghi.com");
assert!("ghi.com" > authority);
assert!(authority > "abc.com");
assert!("abc.com" < authority);
}
#[test]
fn compares_with_a_string() {
let authority: Authority = "def.com".parse().unwrap();
assert!(authority < "ghi.com".to_string());
assert!("ghi.com".to_string() > authority);
assert!(authority > "abc.com".to_string());
assert!("abc.com".to_string() < authority);
}
#[test]
fn allows_percent_in_userinfo() {
let authority_str = "a%2f:b%2f@example.com";
let authority: Authority = authority_str.parse().unwrap();
assert_eq!(authority, authority_str);
}
#[test]
fn rejects_percent_in_hostname() {
let err = Authority::parse_non_empty(b"example%2f.com").unwrap_err();
assert_eq!(err.0, ErrorKind::InvalidAuthority);
let err = Authority::parse_non_empty(b"a%2f:b%2f@example%2f.com").unwrap_err();
assert_eq!(err.0, ErrorKind::InvalidAuthority);
}
#[test]
fn allows_percent_in_ipv6_address() {
let authority_str = "[fe80::1:2:3:4%25eth0]";
let result: Authority = authority_str.parse().unwrap();
assert_eq!(result, authority_str);
}
#[test]
fn rejects_percent_outside_ipv6_address() {
let err = Authority::parse_non_empty(b"1234%20[fe80::1:2:3:4]").unwrap_err();
assert_eq!(err.0, ErrorKind::InvalidAuthority);
let err = Authority::parse_non_empty(b"[fe80::1:2:3:4]%20").unwrap_err();
assert_eq!(err.0, ErrorKind::InvalidAuthority);
}
}