#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NormalizedUrl {
scheme: String,
host: String,
port: Option<u16>,
path: String,
}
impl NormalizedUrl {
pub fn parse(raw: &str) -> Option<Self> {
let url = url::Url::parse(raw.trim()).ok()?;
let host = url.host_str()?.trim_end_matches('.').to_ascii_lowercase();
if host.is_empty() {
return None;
}
let scheme = websocket_as_http(url.scheme()).to_string();
let port = url
.port_or_known_default()
.filter(|p| Some(*p) != default_port(&scheme));
Some(Self {
scheme,
host,
port,
path: normalize_escapes(url.path()),
})
}
pub fn scheme(&self) -> &str {
&self.scheme
}
pub fn host(&self) -> &str {
&self.host
}
pub fn port(&self) -> Option<u16> {
self.port
}
pub fn without_trailing_slash(mut self) -> Self {
let trimmed = self.path.trim_end_matches('/').len();
self.path.truncate(trimmed);
self
}
pub fn path_or_root(&self) -> &str {
if self.path.is_empty() {
"/"
} else {
&self.path
}
}
}
impl std::fmt::Display for NormalizedUrl {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}://{}", self.scheme, self.host)?;
if let Some(port) = self.port {
write!(f, ":{port}")?;
}
f.write_str(&self.path)
}
}
pub fn normalize_escapes(path: &str) -> String {
let mut out = String::with_capacity(path.len());
let mut rest = path;
while let Some(c) = rest.chars().next() {
let escaped = rest
.strip_prefix('%')
.and_then(|r| r.get(..2))
.filter(|hex| hex.bytes().all(|b| b.is_ascii_hexdigit()))
.and_then(|hex| u8::from_str_radix(hex, 16).ok());
match escaped {
Some(b) if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~') => {
out.push(b as char);
rest = &rest[3..];
}
Some(b) => {
out.push_str(&format!("%{b:02X}"));
rest = &rest[3..];
}
None => {
out.push(c);
rest = &rest[c.len_utf8()..];
}
}
}
out
}
pub fn websocket_as_http(scheme: &str) -> &str {
match scheme {
"ws" => "http",
"wss" => "https",
other => other,
}
}
pub fn default_port(scheme: &str) -> Option<u16> {
match scheme {
"http" => Some(80),
"https" => Some(443),
_ => None,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_normalized_url_is_written_one_way() {
let u = NormalizedUrl::parse("WSS://User@Corp.Example.:443/a/?q#f").unwrap();
assert_eq!(u.to_string(), "https://corp.example/a/");
assert_eq!(
u.without_trailing_slash().to_string(),
"https://corp.example/a"
);
assert_eq!(
NormalizedUrl::parse("http://h.example:8080")
.unwrap()
.to_string(),
"http://h.example:8080/"
);
}
}