1#[derive(Debug, Clone, PartialEq, Eq)]
13pub struct NormalizedUrl {
14 scheme: String,
15 host: String,
16 port: Option<u16>,
17 path: String,
18}
19
20impl NormalizedUrl {
21 pub fn parse(raw: &str) -> Option<Self> {
23 let url = url::Url::parse(raw.trim()).ok()?;
24 let host = url.host_str()?.trim_end_matches('.').to_ascii_lowercase();
25 if host.is_empty() {
26 return None;
27 }
28 let scheme = websocket_as_http(url.scheme()).to_string();
29 let port = url
30 .port_or_known_default()
31 .filter(|p| Some(*p) != default_port(&scheme));
32 Some(Self {
33 scheme,
34 host,
35 port,
36 path: normalize_escapes(url.path()),
37 })
38 }
39
40 pub fn scheme(&self) -> &str {
41 &self.scheme
42 }
43
44 pub fn host(&self) -> &str {
45 &self.host
46 }
47
48 pub fn port(&self) -> Option<u16> {
49 self.port
50 }
51
52 pub fn without_trailing_slash(mut self) -> Self {
55 let trimmed = self.path.trim_end_matches('/').len();
56 self.path.truncate(trimmed);
57 self
58 }
59
60 pub fn path_or_root(&self) -> &str {
61 if self.path.is_empty() {
62 "/"
63 } else {
64 &self.path
65 }
66 }
67}
68
69impl std::fmt::Display for NormalizedUrl {
70 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
71 write!(f, "{}://{}", self.scheme, self.host)?;
72 if let Some(port) = self.port {
73 write!(f, ":{port}")?;
74 }
75 f.write_str(&self.path)
76 }
77}
78
79pub fn normalize_escapes(path: &str) -> String {
82 let mut out = String::with_capacity(path.len());
83 let mut rest = path;
84 while let Some(c) = rest.chars().next() {
85 let escaped = rest
86 .strip_prefix('%')
87 .and_then(|r| r.get(..2))
88 .filter(|hex| hex.bytes().all(|b| b.is_ascii_hexdigit()))
89 .and_then(|hex| u8::from_str_radix(hex, 16).ok());
90 match escaped {
91 Some(b) if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~') => {
92 out.push(b as char);
93 rest = &rest[3..];
94 }
95 Some(b) => {
96 out.push_str(&format!("%{b:02X}"));
97 rest = &rest[3..];
98 }
99 None => {
100 out.push(c);
101 rest = &rest[c.len_utf8()..];
102 }
103 }
104 }
105 out
106}
107
108pub fn websocket_as_http(scheme: &str) -> &str {
109 match scheme {
110 "ws" => "http",
111 "wss" => "https",
112 other => other,
113 }
114}
115
116pub fn default_port(scheme: &str) -> Option<u16> {
117 match scheme {
118 "http" => Some(80),
119 "https" => Some(443),
120 _ => None,
121 }
122}
123
124#[cfg(test)]
125mod tests {
126 use super::*;
127
128 #[test]
129 fn a_normalized_url_is_written_one_way() {
130 let u = NormalizedUrl::parse("WSS://User@Corp.Example.:443/a/?q#f").unwrap();
131 assert_eq!(u.to_string(), "https://corp.example/a/");
132 assert_eq!(
133 u.without_trailing_slash().to_string(),
134 "https://corp.example/a"
135 );
136 assert_eq!(
137 NormalizedUrl::parse("http://h.example:8080")
138 .unwrap()
139 .to_string(),
140 "http://h.example:8080/"
141 );
142 }
143}