use std::{fmt, str::FromStr};
use http::Uri;
use crate::{
common::{Error, Result},
error::ConnectionError,
};
#[derive(Clone, Hash, PartialEq, Eq, Default)]
pub struct Address {
uri: Uri,
}
impl Address {
const DEFAULT_SCHEME: &'static str = "http";
pub(crate) fn into_uri(self) -> Uri {
self.uri
}
pub(crate) fn uri_scheme(&self) -> Option<&http::uri::Scheme> {
self.uri.scheme()
}
pub(crate) fn is_https(&self) -> bool {
self.uri_scheme() == Some(&http::uri::Scheme::HTTPS)
}
}
impl FromStr for Address {
type Err = Error;
fn from_str(address: &str) -> Result<Self> {
let uri = if address.contains("://") {
address.parse::<Uri>()?
} else {
format!("{}://{}", Self::DEFAULT_SCHEME, address).parse::<Uri>()?
};
if uri.port().is_none() {
return Err(Error::Connection(ConnectionError::MissingPort { address: address.to_owned() }));
}
Ok(Self { uri })
}
}
impl fmt::Display for Address {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.uri.authority().unwrap())
}
}
impl fmt::Debug for Address {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:?}", self.uri)
}
}