Skip to main content

flow_abi/
url.rs

1//! std's `url.Url` (`stdlib.md`, *`url`*): a URI by RFC 3986's `URI` rule,
2//! held in the normal form of its §6.2.2, which `url.parse` makes and
3//! decoding holds a `Url` to (`abi.md`, *Decoding*).
4//!
5//! Parsing splits the text at its ASCII delimiters, then reads each
6//! component in one pass that refuses a character the component cannot hold,
7//! writes a character that is not ASCII as its percent-encoded UTF-8 bytes
8//! (and refuses one in the host), writes a percent-encoded unreserved
9//! character as itself and every other percent-encoding in uppercase. Dot
10//! segments are removed last, by §5.2.4. Each step is linear in the text.
11
12use std::fmt::{self, Write as _};
13use std::net::Ipv6Addr;
14
15/// A URI by RFC 3986 in its normal form. Its text is [`fmt::Display`].
16#[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    /// Its digits as written; an empty port is dropped.
31    port: Option<String>,
32}
33
34/// A URI reference (§4.1): a URI, or a relative reference, which has no
35/// scheme. Each component is already in its normal spelling, but the path
36/// keeps its dot segments.
37struct Reference {
38    scheme: Option<String>,
39    authority: Option<Authority>,
40    path: String,
41    query: Option<String>,
42    fragment: Option<String>,
43}
44
45/// The component a character stands in, which fixes what it may be.
46#[derive(Clone, Copy, PartialEq, Eq)]
47enum Part {
48    Userinfo,
49    Host,
50    Path,
51    /// A query or a fragment, which hold the same characters.
52    Query,
53}
54
55impl Url {
56    /// The URL `text` spells, in its normal form, or `None` when it spells
57    /// none: a relative reference is not a URL.
58    ///
59    /// ```
60    /// let url = flow_abi::Url::parse("HTTP://Example.COM/a/./b/../%7euser?q=%c3%a9").unwrap();
61    /// assert_eq!(url.to_string(), "http://example.com/a/~user?q=%C3%A9");
62    /// assert!(flow_abi::Url::parse("/a/b").is_none());
63    /// ```
64    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    /// The URL with these components, its dot segments removed and its path
77    /// made one it can hold as itself.
78    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            // Without an authority, a path cannot start with `//`, which
90            // would read as one; `/.` keeps the path it was (§5.2.4 does
91            // not remove a dot segment it would need to add back).
92            path.insert_str(0, "/.");
93        }
94        Url {
95            scheme,
96            authority,
97            path,
98            query,
99            fragment,
100        }
101    }
102
103    /// `reference` resolved against this URL by RFC 3986 §5.2, or `None`
104    /// when `reference` is not a URI reference.
105    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    /// The path `relative` is relative to this URL's (§5.2.3). A URL with
132    /// an authority has a path of at least `/` in its normal form, so the
133    /// section's case of an empty one never arises.
134    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    /// Its scheme, in lowercase.
142    pub fn scheme(&self) -> &str {
143        &self.scheme
144    }
145
146    /// Its user information, `None` without an authority or without `@`.
147    pub fn userinfo(&self) -> Option<&str> {
148        self.authority.as_ref()?.userinfo.as_deref()
149    }
150
151    /// Its host, `None` without an authority; an IP literal keeps its
152    /// brackets.
153    pub fn host(&self) -> Option<&str> {
154        Some(&self.authority.as_ref()?.host)
155    }
156
157    /// Its port's digits as written, `None` without one.
158    pub fn port(&self) -> Option<&str> {
159        self.authority.as_ref()?.port.as_deref()
160    }
161
162    /// Its path, percent-encoded as written.
163    pub fn path(&self) -> &str {
164        &self.path
165    }
166
167    /// Its query, percent-encoded, without the `?`.
168    pub fn query(&self) -> Option<&str> {
169        self.query.as_deref()
170    }
171
172    /// Its fragment, percent-encoded, without the `#`.
173    pub fn fragment(&self) -> Option<&str> {
174        self.fragment.as_deref()
175    }
176
177    /// Its query as name and value pairs: split on `&`, each non-empty part
178    /// split at its first `=`, or paired with `""` without one, each side
179    /// percent-decoded with `+` read as a space; `None` when a decoded side
180    /// is not UTF-8.
181    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    /// This URL with the query these pairs make, each side percent-encoded
196    /// as UTF-8 except its unreserved characters; no pairs remove the query.
197    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    /// This URL with the fragment `fragment`, each character a fragment
217    /// cannot hold as itself, and `%`, percent-encoded; `None` removes it.
218    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    /// This URL with the path `path`, written as [`Url::path`] reads, or
231    /// `None` when it cannot hold `path` as its path.
232    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
276/// The normal text of the URL `text` spells, or `None` when it spells none.
277pub fn normal_url(text: &str) -> Option<String> {
278    Url::parse(text).map(|url| url.to_string())
279}
280
281/// Reads the URI reference `text`, or `None` when it is not one.
282fn 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    // A `:` before any `/` ends a scheme; a first segment holding one is
292    // otherwise no relative reference (§4.2).
293    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
319/// `ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )`.
320fn 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
328/// `[ userinfo "@" ] host [ ":" port ]`.
329fn 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
358/// `"[" ( IPv6address / IPvFuture ) "]"`, in lowercase.
359fn ip_literal(literal: &str) -> Option<String> {
360    let inner = &literal[1..literal.len() - 1];
361    let valid = match inner.strip_prefix(['v', 'V']) {
362        // `"v" 1*HEXDIG "." 1*( unreserved / sub-delims / ":" )`
363        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
374/// Whether `byte` is RFC 3986's `unreserved`.
375fn is_unreserved(byte: u8) -> bool {
376    byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~')
377}
378
379/// Whether the ASCII `byte` may stand as itself in `part`.
380fn 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
395/// `text` as `part` in its normal spelling, or `None` when `part` cannot
396/// hold it.
397fn 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            // A character that is not ASCII stands for its UTF-8 bytes
421            // (RFC 3987 §3.1), except in the host.
422            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        // Lowercase outside its percent-encodings, whose digits stay upper.
435        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
463/// Writes `text`'s UTF-8, each byte `keep` refuses percent-encoded.
464fn 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
474/// A query name or value decoded: `+` is a space and each percent-encoding
475/// its byte, and each byte that does not fit UTF-8 is U+FFFD.
476fn 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                // A normal query holds only whole percent-encodings.
485                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
497/// RFC 3986 §5.2.4.
498fn 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        // RFC 3986 §5.2.4's own examples, and the edges of its loop.
536        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}