use std::fmt::{self, Write as _};
use std::net::Ipv6Addr;
#[derive(Clone, PartialEq, Eq, Debug)]
#[must_use]
pub struct Url {
scheme: String,
authority: Option<Authority>,
path: String,
query: Option<String>,
fragment: Option<String>,
}
#[derive(Clone, PartialEq, Eq, Debug)]
struct Authority {
userinfo: Option<String>,
host: String,
port: Option<String>,
}
struct Reference {
scheme: Option<String>,
authority: Option<Authority>,
path: String,
query: Option<String>,
fragment: Option<String>,
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum Part {
Userinfo,
Host,
Path,
Query,
}
impl Url {
pub fn parse(text: &str) -> Option<Url> {
let reference = reference(text)?;
let scheme = reference.scheme?;
Some(Url::finish(
scheme,
reference.authority,
&reference.path,
reference.query,
reference.fragment,
))
}
fn finish(
scheme: String,
authority: Option<Authority>,
path: &str,
query: Option<String>,
fragment: Option<String>,
) -> Url {
let mut path = remove_dot_segments(path);
if authority.is_some() && path.is_empty() {
path.push('/');
} else if authority.is_none() && path.starts_with("//") {
path.insert_str(0, "/.");
}
Url {
scheme,
authority,
path,
query,
fragment,
}
}
pub fn resolve(&self, reference: &str) -> Option<Url> {
let r = self::reference(reference)?;
let (scheme, authority, path, query) = if let Some(scheme) = r.scheme {
(scheme, r.authority, r.path, r.query)
} else if r.authority.is_some() {
(self.scheme.clone(), r.authority, r.path, r.query)
} else if r.path.is_empty() {
(
self.scheme.clone(),
self.authority.clone(),
self.path.clone(),
r.query.or_else(|| self.query.clone()),
)
} else if r.path.starts_with('/') {
(self.scheme.clone(), self.authority.clone(), r.path, r.query)
} else {
(
self.scheme.clone(),
self.authority.clone(),
self.merge(&r.path),
r.query,
)
};
Some(Url::finish(scheme, authority, &path, query, r.fragment))
}
fn merge(&self, relative: &str) -> String {
match self.path.rfind('/') {
Some(at) => format!("{}{relative}", &self.path[..=at]),
None => relative.to_owned(),
}
}
pub fn scheme(&self) -> &str {
&self.scheme
}
pub fn userinfo(&self) -> Option<&str> {
self.authority.as_ref()?.userinfo.as_deref()
}
pub fn host(&self) -> Option<&str> {
Some(&self.authority.as_ref()?.host)
}
pub fn port(&self) -> Option<&str> {
self.authority.as_ref()?.port.as_deref()
}
pub fn path(&self) -> &str {
&self.path
}
pub fn query(&self) -> Option<&str> {
self.query.as_deref()
}
pub fn fragment(&self) -> Option<&str> {
self.fragment.as_deref()
}
pub fn query_pairs(&self) -> Option<Vec<(String, String)>> {
let Some(query) = &self.query else {
return Some(Vec::new());
};
query
.split('&')
.filter(|part| !part.is_empty())
.map(|part| {
let (name, value) = part.split_once('=').unwrap_or((part, ""));
Some((form_decode(name)?, form_decode(value)?))
})
.collect()
}
pub fn with_query(&self, pairs: &[(&str, &str)]) -> Url {
let query = (!pairs.is_empty()).then(|| {
let mut query = String::new();
for (at, (name, value)) in pairs.iter().enumerate() {
if at > 0 {
query.push('&');
}
encode_into(&mut query, name, is_unreserved);
query.push('=');
encode_into(&mut query, value, is_unreserved);
}
query
});
Url {
query,
..self.clone()
}
}
pub fn with_fragment(&self, fragment: Option<&str>) -> Url {
let fragment = fragment.map(|fragment| {
let mut encoded = String::new();
encode_into(&mut encoded, fragment, |byte| allowed(Part::Query, byte));
encoded
});
Url {
fragment,
..self.clone()
}
}
pub fn with_path(&self, path: &str) -> Option<Url> {
let fits = if self.authority.is_some() {
path.is_empty() || path.starts_with('/')
} else {
!path.starts_with("//")
};
if !fits {
return None;
}
let path = component(path, Part::Path)?;
Some(Url::finish(
self.scheme.clone(),
self.authority.clone(),
&path,
self.query.clone(),
self.fragment.clone(),
))
}
}
impl fmt::Display for Url {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}:", self.scheme)?;
if let Some(authority) = &self.authority {
f.write_str("//")?;
if let Some(userinfo) = &authority.userinfo {
write!(f, "{userinfo}@")?;
}
f.write_str(&authority.host)?;
if let Some(port) = &authority.port {
write!(f, ":{port}")?;
}
}
f.write_str(&self.path)?;
if let Some(query) = &self.query {
write!(f, "?{query}")?;
}
if let Some(fragment) = &self.fragment {
write!(f, "#{fragment}")?;
}
Ok(())
}
}
pub fn normal_url(text: &str) -> Option<String> {
Url::parse(text).map(|url| url.to_string())
}
fn reference(text: &str) -> Option<Reference> {
let (rest, fragment) = match text.split_once('#') {
Some((rest, fragment)) => (rest, Some(component(fragment, Part::Query)?)),
None => (text, None),
};
let (rest, query) = match rest.split_once('?') {
Some((rest, query)) => (rest, Some(component(query, Part::Query)?)),
None => (rest, None),
};
let (scheme, rest) = match rest.find([':', '/']) {
Some(at) if rest.as_bytes()[at] == b':' => {
let scheme = &rest[..at];
if !is_scheme(scheme) {
return None;
}
(Some(scheme.to_ascii_lowercase()), &rest[at + 1..])
}
_ => (None, rest),
};
let (authority, path) = match rest.strip_prefix("//") {
Some(after) => {
let end = after.find('/').unwrap_or(after.len());
(Some(authority(&after[..end])?), &after[end..])
}
None => (None, rest),
};
Some(Reference {
scheme,
authority,
path: component(path, Part::Path)?,
query,
fragment,
})
}
fn is_scheme(text: &str) -> bool {
let mut bytes = text.bytes();
bytes
.next()
.is_some_and(|first| first.is_ascii_alphabetic())
&& bytes.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'+' | b'-' | b'.'))
}
fn authority(text: &str) -> Option<Authority> {
let (userinfo, rest) = match text.split_once('@') {
Some((userinfo, rest)) => (Some(component(userinfo, Part::Userinfo)?), rest),
None => (None, text),
};
let (host, port) = if rest.starts_with('[') {
let end = rest.find(']')?;
let (literal, after) = rest.split_at(end + 1);
let port = match after {
"" => None,
_ => Some(after.strip_prefix(':')?),
};
(ip_literal(literal)?, port)
} else {
match rest.rsplit_once(':') {
Some((host, port)) => (component(host, Part::Host)?, Some(port)),
None => (component(rest, Part::Host)?, None),
}
};
if !port.is_none_or(|port| port.bytes().all(|byte| byte.is_ascii_digit())) {
return None;
}
Some(Authority {
userinfo,
host,
port: port.filter(|port| !port.is_empty()).map(str::to_owned),
})
}
fn ip_literal(literal: &str) -> Option<String> {
let inner = &literal[1..literal.len() - 1];
let valid = match inner.strip_prefix(['v', 'V']) {
Some(future) => future.split_once('.').is_some_and(|(version, rest)| {
!version.is_empty()
&& version.bytes().all(|byte| byte.is_ascii_hexdigit())
&& !rest.is_empty()
&& rest.bytes().all(|byte| allowed(Part::Userinfo, byte))
}),
None => inner.parse::<Ipv6Addr>().is_ok(),
};
valid.then(|| literal.to_ascii_lowercase())
}
fn is_unreserved(byte: u8) -> bool {
byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~')
}
fn allowed(part: Part, byte: u8) -> bool {
let sub_delim = matches!(
byte,
b'!' | b'$' | b'&' | b'\'' | b'(' | b')' | b'*' | b'+' | b',' | b';' | b'='
);
is_unreserved(byte)
|| sub_delim
|| match part {
Part::Host => false,
Part::Userinfo => byte == b':',
Part::Path => matches!(byte, b':' | b'@' | b'/'),
Part::Query => matches!(byte, b':' | b'@' | b'/' | b'?'),
}
}
fn component(text: &str, part: Part) -> Option<String> {
let mut out = String::with_capacity(text.len());
let bytes = text.as_bytes();
let mut at = 0;
while at < bytes.len() {
let byte = bytes[at];
if byte == b'%' {
let high = hex(*bytes.get(at + 1)?)?;
let low = hex(*bytes.get(at + 2)?)?;
let decoded = high << 4 | low;
if is_unreserved(decoded) {
out.push(char::from(decoded));
} else {
push_encoded(&mut out, decoded);
}
at += 3;
} else if byte.is_ascii() {
if !allowed(part, byte) {
return None;
}
out.push(char::from(byte));
at += 1;
} else {
if part == Part::Host {
return None;
}
let ch = text[at..].chars().next().expect("a character starts here");
let mut buffer = [0; 4];
for byte in ch.encode_utf8(&mut buffer).bytes() {
push_encoded(&mut out, byte);
}
at += ch.len_utf8();
}
}
if part == Part::Host {
let mut lowered = String::with_capacity(out.len());
let mut escape = 0;
for ch in out.chars() {
if ch == '%' {
escape = 3;
}
if escape > 0 {
escape -= 1;
lowered.push(ch);
} else {
lowered.push(ch.to_ascii_lowercase());
}
}
out = lowered;
}
Some(out)
}
fn hex(byte: u8) -> Option<u8> {
char::from(byte)
.to_digit(16)
.map(|digit| u8::try_from(digit).expect("a hex digit"))
}
fn push_encoded(out: &mut String, byte: u8) {
write!(out, "%{byte:02X}").expect("writing to a String");
}
fn encode_into(out: &mut String, text: &str, keep: impl Fn(u8) -> bool) {
for byte in text.bytes() {
if byte.is_ascii() && byte != b'%' && keep(byte) {
out.push(char::from(byte));
} else {
push_encoded(out, byte);
}
}
}
fn form_decode(text: &str) -> Option<String> {
let bytes = text.as_bytes();
let mut decoded = Vec::with_capacity(bytes.len());
let mut at = 0;
while at < bytes.len() {
match bytes[at] {
b'+' => decoded.push(b' '),
b'%' => {
let high = hex(bytes[at + 1]).expect("a normal percent-encoding");
let low = hex(bytes[at + 2]).expect("a normal percent-encoding");
decoded.push(high << 4 | low);
at += 2;
}
byte => decoded.push(byte),
}
at += 1;
}
String::from_utf8(decoded).ok()
}
fn remove_dot_segments(path: &str) -> String {
let mut input = path;
let mut output = String::with_capacity(path.len());
while !input.is_empty() {
if let Some(rest) = input.strip_prefix("../") {
input = rest;
} else if let Some(rest) = input.strip_prefix("./") {
input = rest;
} else if input.starts_with("/./") {
input = &input[2..];
} else if input == "/." {
input = "/";
} else if input.starts_with("/../") || input == "/.." {
input = if input == "/.." { "/" } else { &input[3..] };
let cut = output.rfind('/').unwrap_or(0);
output.truncate(cut);
} else if input == "." || input == ".." {
input = "";
} else {
let start = usize::from(input.starts_with('/'));
let end = input[start..]
.find('/')
.map_or(input.len(), |at| at + start);
output.push_str(&input[..end]);
input = &input[end..];
}
}
output
}
#[cfg(test)]
#[cfg_attr(coverage, coverage(off))]
mod tests {
use super::*;
#[test]
fn dot_segments_are_removed_as_rfc_3986_section_5_2_4_does() {
for (path, removed) in [
("/a/b/c/./../../g", "/a/g"),
("mid/content=5/../6", "mid/6"),
("/..", "/"),
("/.", "/"),
("..", ""),
(".", ""),
("../a", "a"),
("./a", "a"),
("a/..", "/"),
("x/../../y", "/y"),
("", ""),
] {
assert_eq!(remove_dot_segments(path), removed, "{path:?}");
}
}
}