use crate::error::ConnectError;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ConnectTarget {
host: String,
port: u16,
}
impl ConnectTarget {
pub fn new(host: impl Into<String>, port: u16) -> Result<Self, ConnectError> {
let host = host.into();
validate_host(&host)?;
Ok(Self { host, port })
}
#[must_use]
pub fn host(&self) -> &str {
&self.host
}
#[must_use]
pub fn port(&self) -> u16 {
self.port
}
#[must_use]
pub fn authority(&self) -> String {
authority_form(&self.host, self.port)
}
}
fn authority_form(host: &str, port: u16) -> String {
if let Some(inner) = strip_brackets(host) {
format!("[{inner}]:{port}")
} else if host.contains(':') {
format!("[{host}]:{port}")
} else {
format!("{host}:{port}")
}
}
fn strip_brackets(host: &str) -> Option<&str> {
if host.starts_with('[') && host.ends_with(']') && host.len() >= 2 {
Some(&host[1..host.len() - 1])
} else {
None
}
}
fn validate_host(host: &str) -> Result<(), ConnectError> {
if host.is_empty() {
return Err(ConnectError::InvalidTarget);
}
if host.contains('[') || host.contains(']') {
let Some(inner) = strip_brackets(host) else {
return Err(ConnectError::InvalidTarget);
};
if inner.is_empty() || inner.contains('[') || inner.contains(']') {
return Err(ConnectError::InvalidTarget);
}
validate_host_inner(inner)?;
return Ok(());
}
validate_host_inner(host)
}
fn validate_host_inner(host: &str) -> Result<(), ConnectError> {
if host.is_empty() {
return Err(ConnectError::InvalidTarget);
}
for c in host.chars() {
if c == '\r' || c == '\n' || c.is_control() || c == ' ' || c == '\u{7f}' {
return Err(ConnectError::InvalidTarget);
}
}
Ok(())
}