pub const PATH: &str = "/yog/register/";
const HTTPS: u16 = 443;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Offer {
pub host: String,
pub port: u16,
pub code: String,
}
impl Offer {
pub fn host(&self) -> String {
if self.host.contains(':') {
format!("[{}]", self.host)
} else {
self.host.clone()
}
}
pub fn authority(&self) -> String {
if self.port == HTTPS {
self.host()
} else {
format!("{}:{}", self.host(), self.port)
}
}
pub fn path(&self) -> String {
format!("{PATH}{}", self.code)
}
}
pub fn parse(url: &str) -> Result<Offer, String> {
read(url.trim()).ok_or_else(|| {
format!(
"{url:?} is not a registration URL — one looks like \
https://<host>{PATH}<code>, exactly as the offer showed it"
)
})
}
fn read(url: &str) -> Option<Offer> {
let (authority, code) = url.strip_prefix("https://")?.split_once(PATH)?;
let (host, port) = match authority.strip_prefix('[') {
Some(bracketed) => {
let (host, tail) = bracketed.split_once(']')?;
if tail.is_empty() {
(host, None)
} else {
(host, Some(tail.strip_prefix(':')?))
}
}
None => match authority.split_once(':') {
Some((host, port)) => (host, Some(port)),
None => (authority, None),
},
};
let port = match port {
Some(stated) => stated.parse().ok()?,
None => HTTPS,
};
let plain = |text: &str, also: &str| {
!text.is_empty()
&& text
.chars()
.all(|c| c.is_ascii_alphanumeric() || also.contains(c))
};
(plain(host, ".-:") && plain(code, "")).then(|| Offer {
host: host.to_owned(),
port,
code: code.to_owned(),
})
}
#[cfg(test)]
mod tests;