1use std::fmt::{self, Write as _};
13use std::net::Ipv6Addr;
14
15#[derive(Clone, PartialEq, Eq, Debug)]
17#[must_use]
18pub struct Url {
19 scheme: String,
20 authority: Option<Authority>,
21 path: String,
22 query: Option<String>,
23 fragment: Option<String>,
24}
25
26#[derive(Clone, PartialEq, Eq, Debug)]
27struct Authority {
28 userinfo: Option<String>,
29 host: String,
30 port: Option<String>,
32}
33
34struct Reference {
38 scheme: Option<String>,
39 authority: Option<Authority>,
40 path: String,
41 query: Option<String>,
42 fragment: Option<String>,
43}
44
45#[derive(Clone, Copy, PartialEq, Eq)]
47enum Part {
48 Userinfo,
49 Host,
50 Path,
51 Query,
53}
54
55impl Url {
56 pub fn parse(text: &str) -> Option<Url> {
65 let reference = reference(text)?;
66 let scheme = reference.scheme?;
67 Some(Url::finish(
68 scheme,
69 reference.authority,
70 &reference.path,
71 reference.query,
72 reference.fragment,
73 ))
74 }
75
76 fn finish(
79 scheme: String,
80 authority: Option<Authority>,
81 path: &str,
82 query: Option<String>,
83 fragment: Option<String>,
84 ) -> Url {
85 let mut path = remove_dot_segments(path);
86 if authority.is_some() && path.is_empty() {
87 path.push('/');
88 } else if authority.is_none() && path.starts_with("//") {
89 path.insert_str(0, "/.");
93 }
94 Url {
95 scheme,
96 authority,
97 path,
98 query,
99 fragment,
100 }
101 }
102
103 pub fn resolve(&self, reference: &str) -> Option<Url> {
106 let r = self::reference(reference)?;
107 let (scheme, authority, path, query) = if let Some(scheme) = r.scheme {
108 (scheme, r.authority, r.path, r.query)
109 } else if r.authority.is_some() {
110 (self.scheme.clone(), r.authority, r.path, r.query)
111 } else if r.path.is_empty() {
112 (
113 self.scheme.clone(),
114 self.authority.clone(),
115 self.path.clone(),
116 r.query.or_else(|| self.query.clone()),
117 )
118 } else if r.path.starts_with('/') {
119 (self.scheme.clone(), self.authority.clone(), r.path, r.query)
120 } else {
121 (
122 self.scheme.clone(),
123 self.authority.clone(),
124 self.merge(&r.path),
125 r.query,
126 )
127 };
128 Some(Url::finish(scheme, authority, &path, query, r.fragment))
129 }
130
131 fn merge(&self, relative: &str) -> String {
135 match self.path.rfind('/') {
136 Some(at) => format!("{}{relative}", &self.path[..=at]),
137 None => relative.to_owned(),
138 }
139 }
140
141 pub fn scheme(&self) -> &str {
143 &self.scheme
144 }
145
146 pub fn userinfo(&self) -> Option<&str> {
148 self.authority.as_ref()?.userinfo.as_deref()
149 }
150
151 pub fn host(&self) -> Option<&str> {
154 Some(&self.authority.as_ref()?.host)
155 }
156
157 pub fn port(&self) -> Option<&str> {
159 self.authority.as_ref()?.port.as_deref()
160 }
161
162 pub fn path(&self) -> &str {
164 &self.path
165 }
166
167 pub fn query(&self) -> Option<&str> {
169 self.query.as_deref()
170 }
171
172 pub fn fragment(&self) -> Option<&str> {
174 self.fragment.as_deref()
175 }
176
177 pub fn query_pairs(&self) -> Option<Vec<(String, String)>> {
182 let Some(query) = &self.query else {
183 return Some(Vec::new());
184 };
185 query
186 .split('&')
187 .filter(|part| !part.is_empty())
188 .map(|part| {
189 let (name, value) = part.split_once('=').unwrap_or((part, ""));
190 Some((form_decode(name)?, form_decode(value)?))
191 })
192 .collect()
193 }
194
195 pub fn with_query(&self, pairs: &[(&str, &str)]) -> Url {
198 let query = (!pairs.is_empty()).then(|| {
199 let mut query = String::new();
200 for (at, (name, value)) in pairs.iter().enumerate() {
201 if at > 0 {
202 query.push('&');
203 }
204 encode_into(&mut query, name, is_unreserved);
205 query.push('=');
206 encode_into(&mut query, value, is_unreserved);
207 }
208 query
209 });
210 Url {
211 query,
212 ..self.clone()
213 }
214 }
215
216 pub fn with_fragment(&self, fragment: Option<&str>) -> Url {
219 let fragment = fragment.map(|fragment| {
220 let mut encoded = String::new();
221 encode_into(&mut encoded, fragment, |byte| allowed(Part::Query, byte));
222 encoded
223 });
224 Url {
225 fragment,
226 ..self.clone()
227 }
228 }
229
230 pub fn with_path(&self, path: &str) -> Option<Url> {
233 let fits = if self.authority.is_some() {
234 path.is_empty() || path.starts_with('/')
235 } else {
236 !path.starts_with("//")
237 };
238 if !fits {
239 return None;
240 }
241 let path = component(path, Part::Path)?;
242 Some(Url::finish(
243 self.scheme.clone(),
244 self.authority.clone(),
245 &path,
246 self.query.clone(),
247 self.fragment.clone(),
248 ))
249 }
250}
251
252impl fmt::Display for Url {
253 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
254 write!(f, "{}:", self.scheme)?;
255 if let Some(authority) = &self.authority {
256 f.write_str("//")?;
257 if let Some(userinfo) = &authority.userinfo {
258 write!(f, "{userinfo}@")?;
259 }
260 f.write_str(&authority.host)?;
261 if let Some(port) = &authority.port {
262 write!(f, ":{port}")?;
263 }
264 }
265 f.write_str(&self.path)?;
266 if let Some(query) = &self.query {
267 write!(f, "?{query}")?;
268 }
269 if let Some(fragment) = &self.fragment {
270 write!(f, "#{fragment}")?;
271 }
272 Ok(())
273 }
274}
275
276pub fn normal_url(text: &str) -> Option<String> {
278 Url::parse(text).map(|url| url.to_string())
279}
280
281fn reference(text: &str) -> Option<Reference> {
283 let (rest, fragment) = match text.split_once('#') {
284 Some((rest, fragment)) => (rest, Some(component(fragment, Part::Query)?)),
285 None => (text, None),
286 };
287 let (rest, query) = match rest.split_once('?') {
288 Some((rest, query)) => (rest, Some(component(query, Part::Query)?)),
289 None => (rest, None),
290 };
291 let (scheme, rest) = match rest.find([':', '/']) {
294 Some(at) if rest.as_bytes()[at] == b':' => {
295 let scheme = &rest[..at];
296 if !is_scheme(scheme) {
297 return None;
298 }
299 (Some(scheme.to_ascii_lowercase()), &rest[at + 1..])
300 }
301 _ => (None, rest),
302 };
303 let (authority, path) = match rest.strip_prefix("//") {
304 Some(after) => {
305 let end = after.find('/').unwrap_or(after.len());
306 (Some(authority(&after[..end])?), &after[end..])
307 }
308 None => (None, rest),
309 };
310 Some(Reference {
311 scheme,
312 authority,
313 path: component(path, Part::Path)?,
314 query,
315 fragment,
316 })
317}
318
319fn is_scheme(text: &str) -> bool {
321 let mut bytes = text.bytes();
322 bytes
323 .next()
324 .is_some_and(|first| first.is_ascii_alphabetic())
325 && bytes.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'+' | b'-' | b'.'))
326}
327
328fn authority(text: &str) -> Option<Authority> {
330 let (userinfo, rest) = match text.split_once('@') {
331 Some((userinfo, rest)) => (Some(component(userinfo, Part::Userinfo)?), rest),
332 None => (None, text),
333 };
334 let (host, port) = if rest.starts_with('[') {
335 let end = rest.find(']')?;
336 let (literal, after) = rest.split_at(end + 1);
337 let port = match after {
338 "" => None,
339 _ => Some(after.strip_prefix(':')?),
340 };
341 (ip_literal(literal)?, port)
342 } else {
343 match rest.rsplit_once(':') {
344 Some((host, port)) => (component(host, Part::Host)?, Some(port)),
345 None => (component(rest, Part::Host)?, None),
346 }
347 };
348 if !port.is_none_or(|port| port.bytes().all(|byte| byte.is_ascii_digit())) {
349 return None;
350 }
351 Some(Authority {
352 userinfo,
353 host,
354 port: port.filter(|port| !port.is_empty()).map(str::to_owned),
355 })
356}
357
358fn ip_literal(literal: &str) -> Option<String> {
360 let inner = &literal[1..literal.len() - 1];
361 let valid = match inner.strip_prefix(['v', 'V']) {
362 Some(future) => future.split_once('.').is_some_and(|(version, rest)| {
364 !version.is_empty()
365 && version.bytes().all(|byte| byte.is_ascii_hexdigit())
366 && !rest.is_empty()
367 && rest.bytes().all(|byte| allowed(Part::Userinfo, byte))
368 }),
369 None => inner.parse::<Ipv6Addr>().is_ok(),
370 };
371 valid.then(|| literal.to_ascii_lowercase())
372}
373
374fn is_unreserved(byte: u8) -> bool {
376 byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~')
377}
378
379fn allowed(part: Part, byte: u8) -> bool {
381 let sub_delim = matches!(
382 byte,
383 b'!' | b'$' | b'&' | b'\'' | b'(' | b')' | b'*' | b'+' | b',' | b';' | b'='
384 );
385 is_unreserved(byte)
386 || sub_delim
387 || match part {
388 Part::Host => false,
389 Part::Userinfo => byte == b':',
390 Part::Path => matches!(byte, b':' | b'@' | b'/'),
391 Part::Query => matches!(byte, b':' | b'@' | b'/' | b'?'),
392 }
393}
394
395fn component(text: &str, part: Part) -> Option<String> {
398 let mut out = String::with_capacity(text.len());
399 let bytes = text.as_bytes();
400 let mut at = 0;
401 while at < bytes.len() {
402 let byte = bytes[at];
403 if byte == b'%' {
404 let high = hex(*bytes.get(at + 1)?)?;
405 let low = hex(*bytes.get(at + 2)?)?;
406 let decoded = high << 4 | low;
407 if is_unreserved(decoded) {
408 out.push(char::from(decoded));
409 } else {
410 push_encoded(&mut out, decoded);
411 }
412 at += 3;
413 } else if byte.is_ascii() {
414 if !allowed(part, byte) {
415 return None;
416 }
417 out.push(char::from(byte));
418 at += 1;
419 } else {
420 if part == Part::Host {
423 return None;
424 }
425 let ch = text[at..].chars().next().expect("a character starts here");
426 let mut buffer = [0; 4];
427 for byte in ch.encode_utf8(&mut buffer).bytes() {
428 push_encoded(&mut out, byte);
429 }
430 at += ch.len_utf8();
431 }
432 }
433 if part == Part::Host {
434 let mut lowered = String::with_capacity(out.len());
436 let mut escape = 0;
437 for ch in out.chars() {
438 if ch == '%' {
439 escape = 3;
440 }
441 if escape > 0 {
442 escape -= 1;
443 lowered.push(ch);
444 } else {
445 lowered.push(ch.to_ascii_lowercase());
446 }
447 }
448 out = lowered;
449 }
450 Some(out)
451}
452
453fn hex(byte: u8) -> Option<u8> {
454 char::from(byte)
455 .to_digit(16)
456 .map(|digit| u8::try_from(digit).expect("a hex digit"))
457}
458
459fn push_encoded(out: &mut String, byte: u8) {
460 write!(out, "%{byte:02X}").expect("writing to a String");
461}
462
463fn encode_into(out: &mut String, text: &str, keep: impl Fn(u8) -> bool) {
465 for byte in text.bytes() {
466 if byte.is_ascii() && byte != b'%' && keep(byte) {
467 out.push(char::from(byte));
468 } else {
469 push_encoded(out, byte);
470 }
471 }
472}
473
474fn form_decode(text: &str) -> Option<String> {
477 let bytes = text.as_bytes();
478 let mut decoded = Vec::with_capacity(bytes.len());
479 let mut at = 0;
480 while at < bytes.len() {
481 match bytes[at] {
482 b'+' => decoded.push(b' '),
483 b'%' => {
484 let high = hex(bytes[at + 1]).expect("a normal percent-encoding");
486 let low = hex(bytes[at + 2]).expect("a normal percent-encoding");
487 decoded.push(high << 4 | low);
488 at += 2;
489 }
490 byte => decoded.push(byte),
491 }
492 at += 1;
493 }
494 String::from_utf8(decoded).ok()
495}
496
497fn remove_dot_segments(path: &str) -> String {
499 let mut input = path;
500 let mut output = String::with_capacity(path.len());
501 while !input.is_empty() {
502 if let Some(rest) = input.strip_prefix("../") {
503 input = rest;
504 } else if let Some(rest) = input.strip_prefix("./") {
505 input = rest;
506 } else if input.starts_with("/./") {
507 input = &input[2..];
508 } else if input == "/." {
509 input = "/";
510 } else if input.starts_with("/../") || input == "/.." {
511 input = if input == "/.." { "/" } else { &input[3..] };
512 let cut = output.rfind('/').unwrap_or(0);
513 output.truncate(cut);
514 } else if input == "." || input == ".." {
515 input = "";
516 } else {
517 let start = usize::from(input.starts_with('/'));
518 let end = input[start..]
519 .find('/')
520 .map_or(input.len(), |at| at + start);
521 output.push_str(&input[..end]);
522 input = &input[end..];
523 }
524 }
525 output
526}
527
528#[cfg(test)]
529#[cfg_attr(coverage, coverage(off))]
530mod tests {
531 use super::*;
532
533 #[test]
534 fn dot_segments_are_removed_as_rfc_3986_section_5_2_4_does() {
535 for (path, removed) in [
537 ("/a/b/c/./../../g", "/a/g"),
538 ("mid/content=5/../6", "mid/6"),
539 ("/..", "/"),
540 ("/.", "/"),
541 ("..", ""),
542 (".", ""),
543 ("../a", "a"),
544 ("./a", "a"),
545 ("a/..", "/"),
546 ("x/../../y", "/y"),
547 ("", ""),
548 ] {
549 assert_eq!(remove_dot_segments(path), removed, "{path:?}");
550 }
551 }
552}