Skip to main content

urly/
url.rs

1use std::any::Any;
2use std::borrow::{Borrow, Cow};
3use std::ops::{Add, AddAssign, Div};
4use std::str::FromStr;
5
6use ntex_bytes::{ByteString, Bytes, BytesMut};
7use simdutf8::compat::{Utf8Error, from_utf8};
8
9use crate::authority::{self, Authority, Port, UserInfo};
10use crate::error::{ErrorKind, InvalidUrl};
11use crate::path::{Path, PathAndQuery};
12use crate::query::{self, Fragment, Query, split_pair};
13use crate::quoting::{Component, quote, requote, unquote};
14use crate::{chars::lowercase, host::normalize_host, parse, scheme::Scheme};
15
16/// URL reference, normalized by the general-purpose parsers.
17///
18/// The URL is stored in a single shared [`ByteString`]; accessors return
19/// borrowed, percent-encoded components. Parsing is lenient and normalizes the
20/// input the same way Python's `yarl` does:
21///
22/// * leading and trailing whitespace and C0 controls, tabs and newlines are removed
23/// * scheme and host are lowercased, non-ASCII hosts are punycode-encoded
24/// * percent-encoding is normalized: invalid characters are encoded, escapes of
25///   unreserved characters are decoded, hex digits are uppercased
26/// * dot segments are removed from absolute paths
27/// * an empty path of `http`, `https`, `ws` and `wss` URLs becomes `/`
28/// * the default port of the scheme is removed, as in `https://h:443/`
29///
30/// The normalized URL always passes strict [`Url::validate`].
31/// [`Url::parse_target`] and [`Url::from_target_parts`] instead preserve unvalidated
32/// HTTP request-target components. Use [`Url::validate_target`] before
33/// [`Url::normalize`] to reject malformed targets rather than repair them.
34///
35/// ```
36/// use urly::Url;
37///
38/// let url: Url = "HTTPS://[email protected]:8443/a/./b/../c d?q=1#frag".parse().unwrap();
39/// assert_eq!(url, "https://[email protected]:8443/a/c%20d?q=1#frag");
40/// assert_eq!(url.scheme_str(), Some("https"));
41/// assert_eq!(url.host(), Some("example.com"));
42/// assert_eq!(url.port_u16(), Some(8443));
43/// assert_eq!(url.path(), "/a/c%20d");
44/// assert_eq!(url.path().decode(), "/a/c d");
45/// assert_eq!(url.query().unwrap().get("q").unwrap(), "1");
46/// assert_eq!(url.fragment().unwrap(), "frag");
47/// ```
48///
49/// URLs are limited to 65535 bytes; operations that can't return an error panic if
50/// the result exceeds the limit.
51#[derive(Clone)]
52pub struct Url {
53    data: ByteString,
54    // index of ':', 0 if there is no scheme
55    scheme_end: u16,
56    // index after "//", 0 if there is no authority
57    auth_start: u16,
58    path_start: u16,
59    path_end: u16,
60    query_end: u16,
61    // host range within the authority, both 0 if there is no authority
62    host_start: u16,
63    host_end: u16,
64}
65
66/// Borrowed URL components, used to assemble a new URL.
67#[derive(Copy, Clone, Default)]
68pub(crate) struct Components<'a> {
69    pub(crate) scheme: Option<&'a str>,
70    pub(crate) authority: Option<&'a str>,
71    pub(crate) path: &'a str,
72    pub(crate) query: Option<&'a str>,
73    pub(crate) fragment: Option<&'a str>,
74}
75
76/// Assembles components into a URL.
77///
78/// The path is adjusted so the result can be parsed back unambiguously. `orig`
79/// is reused if it is equal to the result.
80pub(crate) fn assemble(c: &Components<'_>, orig: Option<&ByteString>) -> Result<Url, InvalidUrl> {
81    assemble_inner(c, orig, false)
82}
83
84pub(crate) fn assemble_target(
85    c: &Components<'_>,
86    orig: Option<&ByteString>,
87) -> Result<Url, InvalidUrl> {
88    assemble_inner(c, orig, true)
89}
90
91/// Builds an origin-form request-target, a path not starting with `//` and an
92/// optional query, without copying `data`.
93///
94/// `query` is the position of the first `?` in `data`, if known.
95///
96/// Produces the same URL as [`assemble_target`] with the split components.
97pub(crate) fn origin_form(data: ByteString, query: Option<Option<usize>>) -> Url {
98    debug_assert!(data.starts_with('/') && !data.starts_with("//"));
99    debug_assert!(data.len() <= parse::MAX_LEN);
100    let query = match query {
101        Some(None) => None,
102        // only an actual `?` is a char boundary
103        Some(Some(i)) if data.as_bytes().get(i) == Some(&b'?') => Some(i),
104        _ => data.find('?'),
105    };
106    debug_assert_eq!(query, data.find('?'), "{data:?}");
107    let len = data.len() as u16;
108    let path_end = query.map_or(len, |i| i as u16);
109    Url {
110        data,
111        scheme_end: 0,
112        auth_start: 0,
113        path_start: 0,
114        path_end,
115        query_end: len,
116        host_start: 0,
117        host_end: 0,
118    }
119}
120
121/// Builds an absolute-form request-target `scheme://authority/path[?query]`
122/// with a single copy.
123///
124/// Produces the same URL as [`assemble_target`] with the split components.
125fn absolute_target(scheme: &str, authority: &str, path_and_query: &str) -> Result<Url, InvalidUrl> {
126    debug_assert!(!scheme.is_empty() && path_and_query.starts_with('/'));
127    let auth_start = scheme.len() + 3;
128    let path_start = auth_start + authority.len();
129    let len = path_start + path_and_query.len();
130    if len > parse::MAX_LEN {
131        return Err(InvalidUrl::new(ErrorKind::TooLong));
132    }
133    let data = concat(&[scheme, "://", authority, path_and_query], len);
134
135    let path_end = path_start
136        + crate::chars::find_byte(path_and_query.as_bytes(), b'?').unwrap_or(path_and_query.len());
137    let host = authority::split(authority).1;
138    let host_start = auth_start + authority::offset(authority, host);
139    // all indexes are at most `len`, which fits
140    Ok(Url {
141        data,
142        scheme_end: scheme.len() as u16,
143        auth_start: auth_start as u16,
144        path_start: path_start as u16,
145        path_end: path_end as u16,
146        query_end: len as u16,
147        host_start: host_start as u16,
148        host_end: (host_start + host.len()) as u16,
149    })
150}
151
152fn assemble_inner(
153    c: &Components<'_>,
154    orig: Option<&ByteString>,
155    target: bool,
156) -> Result<Url, InvalidUrl> {
157    let stripped;
158    let c = match c.authority {
159        Some(a) if !target => {
160            stripped = Components {
161                authority: Some(strip_default_port(c.scheme, a)),
162                ..*c
163            };
164            &stripped
165        }
166        _ => c,
167    };
168    let prefix = if c.authority.is_some() {
169        if c.path.is_empty() {
170            let special = c
171                .scheme
172                .is_some_and(|s| Scheme::from_str_unchecked(s).is_special());
173            if special { "/" } else { "" }
174        } else if c.path.starts_with('/') || target {
175            ""
176        } else {
177            "/"
178        }
179    } else if c.path.starts_with("//") {
180        "/."
181    } else if c.scheme.is_none() && c.path.split('/').next().is_some_and(|s| s.contains(':')) {
182        "./"
183    } else {
184        ""
185    };
186
187    let pieces = [
188        c.scheme.unwrap_or(""),
189        if c.scheme.is_some() { ":" } else { "" },
190        if c.authority.is_some() { "//" } else { "" },
191        c.authority.unwrap_or(""),
192        prefix,
193        c.path,
194        if c.query.is_some() { "?" } else { "" },
195        c.query.unwrap_or(""),
196        if c.fragment.is_some() { "#" } else { "" },
197        c.fragment.unwrap_or(""),
198    ];
199    let len: usize = pieces.iter().map(|p| p.len()).sum();
200    if len > parse::MAX_LEN {
201        return Err(InvalidUrl::new(ErrorKind::TooLong));
202    }
203
204    let reuse = orig.filter(|orig| {
205        orig.len() == len && {
206            // the lengths add up to `len`, indexing can't panic. most pieces are
207            // empty, and comparing empty slices is surprisingly slow
208            let orig = orig.as_str().as_bytes();
209            let mut pos = 0;
210            pieces.iter().all(|p| {
211                let start = pos;
212                pos += p.len();
213                p.is_empty() || orig[start..pos] == *p.as_bytes()
214            })
215        }
216    });
217    let data = match reuse {
218        Some(orig) => orig.clone(),
219        None => concat(&pieces, len),
220    };
221
222    // all lengths fit, the total is at most `MAX_LEN`
223    let lens = pieces.map(|p| p.len() as u16);
224    let scheme_end = lens[0];
225    let auth_start = if c.authority.is_some() {
226        lens[0] + lens[1] + lens[2]
227    } else {
228        0
229    };
230    // the `/.` prefix of an authority-less `//` path is not part of the path
231    let hidden = if prefix == "/." { lens[4] } else { 0 };
232    let path_start = lens[..4].iter().sum::<u16>() + hidden;
233    let path_end = lens[..6].iter().sum::<u16>();
234    let query_end = path_end + lens[6] + lens[7];
235    let (host_start, host_end) = match c.authority {
236        Some(a) => {
237            let host = authority::split(a).1;
238            let start = auth_start + authority::offset(a, host) as u16;
239            (start, start + host.len() as u16)
240        }
241        None => (0, 0),
242    };
243    Ok(Url {
244        data,
245        scheme_end,
246        auth_start,
247        path_start,
248        path_end,
249        query_end,
250        host_start,
251        host_end,
252    })
253}
254
255/// Removes the port from `authority` if it is the default port of `scheme`.
256fn strip_default_port<'a>(scheme: Option<&str>, authority: &'a str) -> &'a str {
257    // a port ends the authority with a digit
258    if !authority.as_bytes().last().is_some_and(u8::is_ascii_digit) {
259        return authority;
260    }
261    let Some(default) = scheme.and_then(|s| Scheme::from_str_unchecked(s).default_port()) else {
262        return authority;
263    };
264    let (_, host, port) = authority::split(authority);
265    if port.and_then(|p| authority::parse_port(p).ok()) == Some(default) {
266        &authority[..authority::offset(authority, host) + host.len()]
267    } else {
268        authority
269    }
270}
271
272/// Concatenates `pieces` of total length `len` with a single copy.
273// inlining unrolls the copies for the constant number of pieces
274#[inline(always)]
275fn concat(pieces: &[&str], len: usize) -> ByteString {
276    // short urls are stored inline in `Bytes`, without allocation
277    const INLINE: usize = 23;
278
279    let bytes = if len <= INLINE {
280        let mut buf = [0u8; INLINE];
281        let mut pos = 0;
282        for p in pieces {
283            buf[pos..pos + p.len()].copy_from_slice(p.as_bytes());
284            pos += p.len();
285        }
286        Bytes::copy_from_slice(&buf[..len])
287    } else {
288        let mut buf = BytesMut::with_capacity(len);
289        let mut dst = buf.spare_writer(len);
290        for p in pieces {
291            dst.extend_from_slice(p.as_bytes());
292        }
293        drop(dst);
294        debug_assert_eq!(buf.len(), len);
295        buf.freeze()
296    };
297    // SAFETY: a concatenation of strings is valid UTF-8
298    unsafe { ByteString::from_bytes_unchecked(bytes) }
299}
300
301fn too_long<T>(res: Result<T, InvalidUrl>) -> T {
302    match res {
303        Ok(v) => v,
304        Err(e) => panic!("{e}"),
305    }
306}
307
308impl Url {
309    /// Returns the relative URL `/`.
310    pub const fn new() -> Url {
311        Url {
312            data: ByteString::from_static("/"),
313            scheme_end: 0,
314            auth_start: 0,
315            path_start: 0,
316            path_end: 1,
317            query_end: 1,
318            host_start: 0,
319            host_end: 0,
320        }
321    }
322
323    /// Parses and normalizes an authority-form `[userinfo@]host[:port]`, like
324    /// `http::Uri` does for a string without a scheme or a leading `/`.
325    ///
326    /// The result is a network-path reference without a path. Use
327    /// [`Url::parse_ref`] to parse any URL reference, it treats such a string
328    /// as a relative path.
329    ///
330    /// ```
331    /// use urly::Url;
332    ///
333    /// let url = Url::parse("Custom.Domain:8080").unwrap();
334    /// assert_eq!(url, "//custom.domain:8080");
335    /// assert_eq!(url.host(), Some("custom.domain"));
336    /// assert_eq!(url.port_u16(), Some(8080));
337    /// assert_eq!(url.path(), "");
338    ///
339    /// assert!(Url::parse("custom.domain/path").is_err());
340    /// assert_eq!(Url::parse_ref("custom.domain").unwrap().host(), None);
341    /// ```
342    pub fn parse<T: AsRef<str>>(src: T) -> Result<Url, InvalidUrl> {
343        parse::parse_authority(src.as_ref())
344    }
345
346    /// Parses and normalizes a URL reference.
347    ///
348    /// Same as `Url::try_from()` and `str::parse()`.
349    pub fn parse_ref<T: AsRef<str>>(src: T) -> Result<Url, InvalidUrl> {
350        parse::parse(src.as_ref(), None)
351    }
352
353    /// Parses an HTTP request-target without validating or normalizing its components.
354    ///
355    /// Supports origin-form (including paths starting with `//`), absolute-form,
356    /// authority-form and `*`. The caller must check that the form is appropriate
357    /// for the request method and protocol.
358    ///
359    /// Preserves case, percent escapes, dot segments and browser-compatible
360    /// unescaped path/query characters such as brackets and braces. Only UTF-8,
361    /// nonempty input and the representation's length limit are checked.
362    /// Use [`Url::validate_target`] before normalization to reject malformed
363    /// targets instead of repairing them.
364    ///
365    /// The input buffer is reused except when URL-reference serialization
366    /// requires a prefix (`//` for an authority, `/.` for an origin path starting
367    /// with `//`) or an empty absolute HTTP path needs `/`.
368    /// Use [`Url::normalize`] to opt into the usual normalization.
369    ///
370    /// ```
371    /// use urly::Url;
372    ///
373    /// let mut url = Url::parse_target("/a/../%7euser?q=%41").unwrap();
374    /// assert_eq!(url.path_and_query(), "/a/../%7euser?q=%41");
375    /// url.validate_target().unwrap();
376    /// url.normalize().unwrap();
377    /// assert_eq!(url.path_and_query(), "/~user?q=A");
378    /// ```
379    pub fn parse_target(src: impl Into<Bytes>) -> Result<Url, InvalidUrl> {
380        parse::parse_target(src.into())
381    }
382
383    /// Parses an HTTP request-target that is already UTF-8.
384    ///
385    /// Same as [`Url::parse_target`] without the UTF-8 check, for callers
386    /// whose parser has already established that the target is ASCII or UTF-8.
387    ///
388    /// `query` is the position of the first `?` in `src`, `None` if `src` has
389    /// no `?`, as found by the caller's parser, so the target is not searched
390    /// again. A position that is not a `?` is ignored.
391    ///
392    /// ```
393    /// use ntex_bytes::ByteString;
394    /// use urly::Url;
395    ///
396    /// let url = Url::parse_target_str(ByteString::from_static("/a?b=1"), Some(2)).unwrap();
397    /// assert_eq!(url.path(), "/a");
398    /// assert_eq!(url.query().unwrap(), "b=1");
399    /// ```
400    pub fn parse_target_str(
401        src: impl Into<ByteString>,
402        query: Option<usize>,
403    ) -> Result<Url, InvalidUrl> {
404        parse::parse_target_str(src.into(), Some(query))
405    }
406
407    /// Builds an unvalidated request-target from HTTP/2 pseudo-header components.
408    ///
409    /// Preserves component boundaries even when a value contains delimiters or
410    /// a path does not start with `/`. Such values must not be validated by
411    /// reparsing [`Url::as_str`], which can interpret their boundaries differently.
412    /// Use [`Url::validate_target`] and check the method/protocol form instead.
413    ///
414    /// ```
415    /// use urly::Url;
416    ///
417    /// let url = Url::from_target_parts(Some("https"), Some("host/invalid"), "/path").unwrap();
418    /// assert_eq!(url.authority().unwrap(), "host/invalid");
419    /// assert_eq!(url.path(), "/path");
420    /// assert!(url.validate_target().is_err());
421    /// ```
422    pub fn from_target_parts(
423        scheme: Option<&str>,
424        authority: Option<&str>,
425        path_and_query: &str,
426    ) -> Result<Url, InvalidUrl> {
427        if scheme == Some("") {
428            return Err(InvalidUrl::new(ErrorKind::InvalidScheme));
429        }
430        if let (Some(scheme), Some(authority)) = (scheme, authority)
431            && path_and_query.starts_with('/')
432        {
433            return absolute_target(scheme, authority, path_and_query);
434        }
435        let (path, query) = crate::chars::split_at_char(path_and_query, b'?');
436        assemble_target(
437            &Components {
438                scheme,
439                authority,
440                path,
441                query,
442                fragment: None,
443            },
444            None,
445        )
446    }
447
448    /// Validates request-target characters, scheme and authority without rewriting them.
449    ///
450    /// Rejects malformed escapes, fragments, non-ASCII, whitespace, controls,
451    /// `"`, `<`, `>`, `\`, encoded NULs before the query, userinfo and invalid
452    /// or empty hosts. Browser-compatible unescaped path/query characters such
453    /// as brackets and braces are accepted. The caller must check the method
454    /// and protocol's target-form rules. Error positions refer to [`Url::as_str`].
455    pub fn validate_target(&self) -> Result<(), InvalidUrl> {
456        parse::validate_target(self)
457    }
458
459    /// Normalizes all components in place using the general-purpose parsing rules.
460    ///
461    /// The buffer is reused if unchanged. On failure, such as exceeding the
462    /// length limit after percent-encoding, the original URL is left unchanged.
463    /// This is lenient normalization, not HTTP validation; use [`Url::validate_target`]
464    /// first when malformed request-targets must be rejected.
465    pub fn normalize(&mut self) -> Result<(), InvalidUrl> {
466        let url = parse::normalize(&self.components(), Some(&self.data))?;
467        *self = url;
468        Ok(())
469    }
470
471    /// Strictly validates a URI reference according to RFC 3986.
472    ///
473    /// Unlike parsing, validation does not normalize: whitespace, non-ASCII
474    /// characters and invalid escapes are errors. The error position is a byte
475    /// offset into `src`. Input that is not valid UTF-8 is rejected with
476    /// [`ErrorKind::InvalidChar`](crate::ErrorKind::InvalidChar) at its first
477    /// non-ASCII byte.
478    ///
479    /// ```
480    /// use urly::{ErrorKind, Url};
481    ///
482    /// assert!(Url::validate("https://example.com/a%20b?q#f").is_ok());
483    /// assert!(Url::validate(b"/path?q").is_ok());
484    ///
485    /// let err = Url::validate("http://ex ample.com").unwrap_err();
486    /// assert_eq!(err.kind(), ErrorKind::InvalidChar(' '));
487    /// assert_eq!(err.position(), Some(9));
488    ///
489    /// let err = Url::validate(b"/a\xff").unwrap_err();
490    /// assert_eq!(err.kind(), ErrorKind::InvalidChar(char::REPLACEMENT_CHARACTER));
491    /// assert_eq!(err.position(), Some(2));
492    /// ```
493    pub fn validate<T: AsRef<[u8]>>(src: T) -> Result<(), InvalidUrl> {
494        let src = src.as_ref();
495        if let Ok(s) = from_utf8(src) {
496            return parse::validate(s);
497        }
498        let i = src.iter().position(|b| !b.is_ascii()).unwrap_or_default();
499        let c = src[i..]
500            .utf8_chunks()
501            .next()
502            .and_then(|chunk| chunk.valid().chars().next())
503            .unwrap_or(char::REPLACEMENT_CHARACTER);
504        Err(InvalidUrl::at(ErrorKind::InvalidChar(c), i))
505    }
506
507    /// Converts a static string to a URL. The string is not copied if it is
508    /// already normalized.
509    ///
510    /// # Panics
511    ///
512    /// Panics if the URL is not valid.
513    pub fn from_static(src: &'static str) -> Url {
514        match parse::parse(src, Some(&ByteString::from_static(src))) {
515            Ok(url) => url,
516            Err(e) => panic!("invalid static url {src:?}: {e}"),
517        }
518    }
519
520    /// Converts a `Bytes`, `String`, `Vec<u8>` or any other
521    /// byte buffer to a URL, reusing the buffer if possible.
522    pub fn from_maybe_shared<T>(src: T) -> Result<Url, InvalidUrl>
523    where
524        T: AsRef<[u8]> + 'static,
525    {
526        let mut src = Some(src);
527        let any = &mut src as &mut dyn Any;
528        if let Some(src) = any.downcast_mut::<Option<Bytes>>() {
529            return Url::try_from(src.take().unwrap());
530        }
531        if let Some(src) = any.downcast_mut::<Option<String>>() {
532            return Url::try_from(src.take().unwrap());
533        }
534        if let Some(src) = any.downcast_mut::<Option<Vec<u8>>>() {
535            return Url::try_from(Bytes::from(src.take().unwrap()));
536        }
537        Url::try_from(src.unwrap().as_ref())
538    }
539
540    /// Returns a new [`Builder`](crate::Builder).
541    pub fn builder() -> crate::Builder {
542        crate::Builder::new()
543    }
544
545    pub(crate) fn empty() -> Url {
546        Url {
547            data: ByteString::new(),
548            scheme_end: 0,
549            auth_start: 0,
550            path_start: 0,
551            path_end: 0,
552            query_end: 0,
553            host_start: 0,
554            host_end: 0,
555        }
556    }
557
558    fn components(&self) -> Components<'_> {
559        Components {
560            scheme: self.scheme_str(),
561            authority: self.authority().map(Authority::as_str),
562            path: self.path().as_str(),
563            query: self.query().map(Query::as_str),
564            fragment: self.fragment().map(Fragment::as_str),
565        }
566    }
567
568    #[inline]
569    fn range(&self, start: u16, end: u16) -> &str {
570        let (start, end) = (start as usize, end as usize);
571        debug_assert!(self.data.get(start..end).is_some(), "{start}..{end}");
572        // SAFETY: constructors set all indexes to char boundaries within
573        // `data`, callers pass them in order
574        unsafe { self.data.get_unchecked(start..end) }
575    }
576
577    // ===== accessors =====
578
579    /// Returns the URL as a string.
580    #[inline]
581    pub fn as_str(&self) -> &str {
582        &self.data
583    }
584
585    /// Returns the URL as bytes.
586    #[inline]
587    pub fn as_bytes(&self) -> &[u8] {
588        self.data.as_bytes()
589    }
590
591    /// Returns the underlying buffer.
592    #[inline]
593    pub fn as_byte_string(&self) -> &ByteString {
594        &self.data
595    }
596
597    /// Returns the scheme, if present.
598    #[inline]
599    pub fn scheme(&self) -> Option<&Scheme> {
600        self.scheme_str().map(Scheme::from_str_unchecked)
601    }
602
603    /// Returns the scheme as a string, if present.
604    #[inline]
605    pub fn scheme_str(&self) -> Option<&str> {
606        (self.scheme_end > 0).then(|| self.range(0, self.scheme_end))
607    }
608
609    /// Returns the authority, if present.
610    #[inline]
611    pub fn authority(&self) -> Option<&Authority> {
612        (self.auth_start > 0)
613            .then(|| Authority::from_str_unchecked(self.range(self.auth_start, self.path_start)))
614    }
615
616    /// Returns the userinfo, if present.
617    pub fn userinfo(&self) -> Option<&UserInfo> {
618        (self.host_start > self.auth_start)
619            .then(|| UserInfo::from_str_unchecked(self.range(self.auth_start, self.host_start - 1)))
620    }
621
622    /// Returns the decoded user name, if present.
623    pub fn username(&self) -> Option<Cow<'_, str>> {
624        self.userinfo().map(UserInfo::decoded_username)
625    }
626
627    /// Returns the decoded password, if present.
628    pub fn password(&self) -> Option<Cow<'_, str>> {
629        self.userinfo()?.decoded_password()
630    }
631
632    /// Returns the host, if present and not empty. IPv6 addresses include the
633    /// brackets. General-purpose parsers punycode-encode non-ASCII domains;
634    /// raw request-targets preserve their original spelling.
635    #[inline]
636    pub fn host(&self) -> Option<&str> {
637        (self.host_end > self.host_start).then(|| self.range(self.host_start, self.host_end))
638    }
639
640    /// Returns the parsed host, if present and not empty.
641    ///
642    /// ```
643    /// use std::net::Ipv4Addr;
644    /// use urly::{Host, Url};
645    ///
646    /// let url = Url::from_static("http://127.0.0.1/");
647    /// assert_eq!(url.host_parsed(), Some(Host::Ipv4(Ipv4Addr::LOCALHOST)));
648    ///
649    /// let url = Url::from_static("http://münchen.de/");
650    /// assert_eq!(url.host(), Some("xn--mnchen-3ya.de"));
651    /// assert_eq!(url.host_parsed().unwrap().to_unicode(), "münchen.de");
652    /// ```
653    pub fn host_parsed(&self) -> Option<crate::Host<'_>> {
654        self.host().map(crate::Host::classify)
655    }
656
657    /// Returns the explicit port, if present.
658    ///
659    /// The default port of the scheme is removed during normalization, so it
660    /// is not returned for a normalized URL; use [`Url::port_or_known_default`].
661    pub fn port(&self) -> Option<Port<&str>> {
662        if self.auth_start > 0 && self.host_end < self.path_start {
663            Port::parse(self.range(self.host_end + 1, self.path_start))
664        } else {
665            None
666        }
667    }
668
669    /// Returns the explicit port as a number, if present.
670    pub fn port_u16(&self) -> Option<u16> {
671        self.port().map(|p| p.as_u16())
672    }
673
674    /// Returns the explicit port, or the default port of the scheme.
675    pub fn port_or_known_default(&self) -> Option<u16> {
676        self.port_u16().or_else(|| self.scheme()?.default_port())
677    }
678
679    /// Returns the percent-encoded path.
680    ///
681    /// A path starting with `//` in a URL without authority is serialized with a
682    /// `/.` prefix, which is not part of the path.
683    ///
684    /// ```
685    /// use urly::Url;
686    ///
687    /// let url = Url::from_static("/.//a?q");
688    /// assert_eq!(url.path(), "//a");
689    /// assert_eq!(url.path_and_query(), "//a?q");
690    /// ```
691    #[inline]
692    pub fn path(&self) -> &Path {
693        Path::from_str_unchecked(self.range(self.path_start, self.path_end))
694    }
695
696    /// Returns the percent-encoded query, if present.
697    #[inline]
698    pub fn query(&self) -> Option<&Query> {
699        (self.query_end > self.path_end)
700            .then(|| Query::from_str_unchecked(self.range(self.path_end + 1, self.query_end)))
701    }
702
703    /// Returns the path and query.
704    #[inline]
705    pub fn path_and_query(&self) -> &PathAndQuery {
706        PathAndQuery::from_str_unchecked(self.range(self.path_start, self.query_end))
707    }
708
709    /// Returns the percent-encoded fragment, if present.
710    pub fn fragment(&self) -> Option<&Fragment> {
711        ((self.query_end as usize) < self.data.len())
712            .then(|| Fragment::from_str_unchecked(&self.data[self.query_end as usize + 1..]))
713    }
714
715    /// Returns `true` if the URL has a scheme.
716    #[inline]
717    pub fn is_absolute(&self) -> bool {
718        self.scheme_end > 0
719    }
720
721    /// Returns `true` if the port is absent or is the default port of the scheme.
722    pub fn is_default_port(&self) -> bool {
723        match self.port_u16() {
724            None => true,
725            Some(port) => self.scheme().and_then(Scheme::default_port) == Some(port),
726        }
727    }
728
729    // ===== derived urls =====
730
731    /// Returns the origin: scheme, host and port.
732    ///
733    /// ```
734    /// use urly::Url;
735    ///
736    /// let url = Url::from_static("https://user:[email protected]:8443/a?b#c");
737    /// assert_eq!(url.origin().unwrap(), "https://example.com:8443/");
738    /// assert!(Url::from_static("/a").origin().is_none());
739    /// ```
740    pub fn origin(&self) -> Option<Url> {
741        let scheme = self.scheme_str()?;
742        let authority = self.authority()?;
743        if authority.host().is_empty() {
744            return None;
745        }
746        Some(self.derive(|c| {
747            *c = Components {
748                scheme: Some(scheme),
749                authority: Some(authority.host_port()),
750                ..Components::default()
751            };
752        }))
753    }
754
755    /// Returns the relative part of the URL: path, query and fragment.
756    ///
757    /// ```
758    /// use urly::Url;
759    ///
760    /// let url = Url::from_static("https://example.com/a?b#c");
761    /// assert_eq!(url.relative(), "/a?b#c");
762    /// ```
763    pub fn relative(&self) -> Url {
764        self.derive(|c| {
765            c.scheme = None;
766            c.authority = None;
767        })
768    }
769
770    /// Returns the URL with the last path segment removed, without query and
771    /// fragment.
772    ///
773    /// ```
774    /// use urly::Url;
775    ///
776    /// assert_eq!(Url::from_static("http://h/a/b?q").parent(), "http://h/a");
777    /// assert_eq!(Url::from_static("http://h/a/b/").parent(), "http://h/a");
778    /// assert_eq!(Url::from_static("http://h/a").parent(), "http://h/");
779    /// assert_eq!(Url::from_static("http://h/").parent(), "http://h/");
780    /// ```
781    pub fn parent(&self) -> Url {
782        let path = self.path().as_str();
783        let trimmed = path.trim_end_matches('/');
784        let parent = match trimmed.rfind('/') {
785            Some(0) => "/",
786            Some(i) => &trimmed[..i],
787            None if path.starts_with('/') => "/",
788            None => "",
789        };
790        self.with_path(parent)
791    }
792
793    /// Appends literal path segments, without query and fragment.
794    ///
795    /// Segments are percent-encoded; `/` is kept and a leading `/` is ignored.
796    /// `.` and `..` segments are resolved within the appended segments, so they
797    /// never remove a segment of this URL's path. The same operation is
798    /// available as the `/` operator.
799    ///
800    /// ```
801    /// use urly::Url;
802    ///
803    /// let url = Url::from_static("http://h/api?q");
804    /// assert_eq!(url.push_segments(["v1", "a b"]), "http://h/api/v1/a%20b");
805    /// assert_eq!(&url / "users/" / "1", "http://h/api/users/1");
806    /// assert_eq!(&url / "../admin", "http://h/api/admin");
807    /// assert_eq!(&url / "v1/../v2", "http://h/api/v2");
808    /// ```
809    pub fn push_segments<I, S>(&self, segments: I) -> Url
810    where
811        I: IntoIterator<Item = S>,
812        S: AsRef<str>,
813    {
814        // appended segments, relative to a virtual root
815        let mut rel = String::from("/");
816        let mut pushed = false;
817        for segment in segments {
818            let segment = segment.as_ref();
819            let segment = segment.strip_prefix('/').unwrap_or(segment);
820            if !rel.ends_with('/') {
821                rel.push('/');
822            }
823            rel.push_str(&quote(segment, Component::Path));
824            pushed = true;
825        }
826        if !pushed {
827            return self.with_path(self.path().as_str());
828        }
829        if parse::has_dot_segments(&rel) {
830            rel = parse::remove_dot_segments(&rel);
831        }
832        let mut path = self.path().as_str().to_string();
833        if !path.is_empty() && !path.ends_with('/') {
834            path.push('/');
835        }
836        path.push_str(&rel[1..]);
837        self.with_path(&path)
838    }
839
840    /// Resolves a reference against this URL, RFC 3986 section 5.2.
841    ///
842    /// ```
843    /// use urly::Url;
844    ///
845    /// let base = Url::from_static("http://a/b/c/d;p?q");
846    /// assert_eq!(base.join("../g").unwrap(), "http://a/b/g");
847    /// assert_eq!(base.join("//g/x").unwrap(), "http://g/x");
848    /// assert_eq!(base.join("?y").unwrap(), "http://a/b/c/d;p?y");
849    /// ```
850    pub fn join(&self, reference: &str) -> Result<Url, InvalidUrl> {
851        if reference.trim_matches(|c: char| c <= ' ').is_empty() {
852            return self.rebuild(|c| c.fragment = None);
853        }
854        Ok(self.join_url(&Url::parse_ref(reference)?))
855    }
856
857    /// Resolves a parsed reference against this URL, RFC 3986 section 5.2.2.
858    ///
859    /// The `+` and `+=` operators are equivalent.
860    ///
861    /// ```
862    /// use urly::Url;
863    ///
864    /// let base = Url::from_static("http://a/b/c/d;p?q");
865    /// let r = Url::from_static("../g");
866    /// assert_eq!(base.join_url(&r), "http://a/b/g");
867    /// assert_eq!(&base + &r, "http://a/b/g");
868    ///
869    /// let mut url = base.clone();
870    /// url += r;
871    /// assert_eq!(url, "http://a/b/g");
872    /// ```
873    pub fn join_url(&self, r: &Url) -> Url {
874        let base = self.components();
875        let r = r.components();
876        let resolved = |path| Cow::Owned(parse::remove_dot_segments(path));
877        let (scheme, authority, path, query) = if r.scheme.is_some() {
878            (r.scheme, r.authority, resolved(r.path), r.query)
879        } else if r.authority.is_some() {
880            (base.scheme, r.authority, resolved(r.path), r.query)
881        } else if r.path.is_empty() {
882            let query = r.query.or(base.query);
883            (base.scheme, base.authority, Cow::Borrowed(base.path), query)
884        } else if r.path.starts_with('/') {
885            (base.scheme, base.authority, resolved(r.path), r.query)
886        } else {
887            let dir = if base.authority.is_some() && base.path.is_empty() {
888                "/"
889            } else {
890                dir(base.path)
891            };
892            let path = resolved(&format!("{dir}{}", r.path));
893            (base.scheme, base.authority, path, r.query)
894        };
895        self.derive(|c| {
896            *c = Components {
897                scheme,
898                authority,
899                path: &path,
900                query,
901                fragment: r.fragment,
902            };
903        })
904    }
905
906    // ===== setters =====
907
908    /// Assembles a URL from modified components, reusing the buffer if
909    /// nothing changed.
910    fn rebuild<'a>(&'a self, f: impl FnOnce(&mut Components<'a>)) -> Result<Url, InvalidUrl> {
911        let mut c = self.components();
912        f(&mut c);
913        assemble(&c, Some(&self.data))
914    }
915
916    fn derive<'a>(&'a self, f: impl FnOnce(&mut Components<'a>)) -> Url {
917        too_long(self.rebuild(f))
918    }
919
920    /// Returns the URL with a new path, without query and fragment.
921    fn with_path(&self, path: &str) -> Url {
922        self.derive(|c| {
923            c.path = path;
924            c.query = None;
925            c.fragment = None;
926        })
927    }
928
929    /// Sets the scheme.
930    pub fn set_scheme(&mut self, scheme: &str) -> Result<(), InvalidUrl> {
931        let scheme = lowercase(Scheme::new(scheme)?.as_str().into());
932        self.rebuild(|c| c.scheme = Some(&scheme))
933            .map(|url| *self = url)
934    }
935
936    /// Sets or removes the raw authority: `[userinfo "@"] host [":" port]`.
937    pub fn set_authority(&mut self, authority: Option<&str>) -> Result<(), InvalidUrl> {
938        let authority = authority.map(parse::normalize_authority).transpose()?;
939        self.rebuild(|c| c.authority = authority.as_deref())
940            .map(|url| *self = url)
941    }
942
943    fn with_authority(
944        &self,
945        userinfo: Option<&str>,
946        host: &str,
947        port: Option<u16>,
948    ) -> Result<Url, InvalidUrl> {
949        let authority = parse::join_authority(userinfo, host, port);
950        self.rebuild(|c| c.authority = Some(&authority))
951    }
952
953    fn host_parts(&self) -> Result<(Option<&str>, &str, Option<u16>), InvalidUrl> {
954        let authority = self
955            .authority()
956            .ok_or(InvalidUrl::new(ErrorKind::AuthorityMissing))?;
957        let (userinfo, host, _) = authority::split(authority.as_str());
958        if host.is_empty() {
959            return Err(InvalidUrl::new(ErrorKind::InvalidHost));
960        }
961        Ok((userinfo, host, authority.port_u16()))
962    }
963
964    /// Sets or removes the literal user name and password.
965    ///
966    /// ```
967    /// use urly::Url;
968    ///
969    /// let mut url = Url::from_static("http://example.com/");
970    /// url.set_userinfo(Some("us@r"), Some("p:w")).unwrap();
971    /// assert_eq!(url, "http://us%40r:p%[email protected]/");
972    /// assert_eq!(url.password().unwrap(), "p:w");
973    /// ```
974    pub fn set_userinfo(
975        &mut self,
976        username: Option<&str>,
977        password: Option<&str>,
978    ) -> Result<(), InvalidUrl> {
979        let (_, host, port) = self.host_parts()?;
980        let userinfo = match (username, password) {
981            (None, None) => None,
982            (user, None) => Some(quote(user.unwrap_or(""), Component::UserInfo)),
983            (user, Some(password)) => Some(Cow::Owned(format!(
984                "{}:{}",
985                quote(user.unwrap_or(""), Component::UserInfo),
986                quote(password, Component::UserInfo)
987            ))),
988        };
989        self.with_authority(userinfo.as_deref(), host, port)
990            .map(|url| *self = url)
991    }
992
993    /// Sets the host. Escapes are decoded, non-ASCII domains are
994    /// punycode-encoded, IPv6 addresses may be given without brackets.
995    ///
996    /// An authority is added if the URL doesn't have one.
997    ///
998    /// ```
999    /// use urly::Url;
1000    ///
1001    /// let mut url = Url::from_static("http://[email protected]:8080/a");
1002    /// url.set_host("::1").unwrap();
1003    /// assert_eq!(url, "http://user@[::1]:8080/a");
1004    /// url.set_host("Bücher.example").unwrap();
1005    /// assert_eq!(url, "http://[email protected]:8080/a");
1006    /// ```
1007    pub fn set_host(&mut self, host: &str) -> Result<(), InvalidUrl> {
1008        let bracketed;
1009        let host = if host.contains(':') && !host.starts_with('[') {
1010            bracketed = format!("[{host}]");
1011            &bracketed
1012        } else {
1013            host
1014        };
1015        let host = normalize_host(host)?;
1016        if host.is_empty() {
1017            return Err(InvalidUrl::new(ErrorKind::InvalidHost));
1018        }
1019        let (userinfo, port) = match self.authority() {
1020            Some(a) => (a.userinfo().map(UserInfo::as_str), a.port_u16()),
1021            None => (None, None),
1022        };
1023        self.with_authority(userinfo, &host, port)
1024            .map(|url| *self = url)
1025    }
1026
1027    /// Sets or removes the port.
1028    pub fn set_port(&mut self, port: Option<u16>) -> Result<(), InvalidUrl> {
1029        let (userinfo, host, _) = self.host_parts()?;
1030        self.with_authority(userinfo, host, port)
1031            .map(|url| *self = url)
1032    }
1033
1034    /// Sets the percent-encoded path, keeping query and fragment.
1035    ///
1036    /// Invalid characters are encoded and dot segments are removed.
1037    ///
1038    /// ```
1039    /// use urly::Url;
1040    ///
1041    /// let mut url = Url::from_static("http://h/a?q");
1042    /// url.set_path("/b/../c d");
1043    /// assert_eq!(url, "http://h/c%20d?q");
1044    /// ```
1045    pub fn set_path(&mut self, path: &str) {
1046        too_long(self.try_set_path(path));
1047    }
1048
1049    pub(crate) fn try_set_path(&mut self, path: &str) -> Result<(), InvalidUrl> {
1050        let prefixed;
1051        let path = if self.auth_start != 0 && !path.is_empty() && !path.starts_with('/') {
1052            prefixed = format!("/{path}");
1053            &prefixed
1054        } else {
1055            path
1056        };
1057        let path = parse::normalize_path(path);
1058        self.rebuild(|c| c.path = &path).map(|url| *self = url)
1059    }
1060
1061    /// Replaces the last path segment with a literal file name.
1062    ///
1063    /// ```
1064    /// use urly::Url;
1065    ///
1066    /// let mut url = Url::from_static("http://h/a/b.txt?q");
1067    /// url.set_file_name("c d.html").unwrap();
1068    /// assert_eq!(url, "http://h/a/c%20d.html?q");
1069    /// ```
1070    pub fn set_file_name(&mut self, name: &str) -> Result<(), InvalidUrl> {
1071        if name.contains('/') || name == "." || name == ".." {
1072            return Err(InvalidUrl::new(ErrorKind::InvalidPath));
1073        }
1074        self.with_file_name(&quote(name, Component::Path))
1075            .map(|url| *self = url)
1076    }
1077
1078    /// Replaces the last path segment with an encoded file name.
1079    fn with_file_name(&self, name: &str) -> Result<Url, InvalidUrl> {
1080        let path = format!("{}{name}", dir(self.path().as_str()));
1081        self.rebuild(|c| c.path = &path)
1082    }
1083
1084    /// Replaces the extension of the file name; an empty extension removes it.
1085    ///
1086    /// ```
1087    /// use urly::Url;
1088    ///
1089    /// let mut url = Url::from_static("http://h/a/b.txt");
1090    /// url.set_extension("tar.gz").unwrap();
1091    /// assert_eq!(url, "http://h/a/b.tar.gz");
1092    /// url.set_extension("").unwrap();
1093    /// assert_eq!(url, "http://h/a/b.tar");
1094    /// ```
1095    pub fn set_extension(&mut self, extension: &str) -> Result<(), InvalidUrl> {
1096        let stem = self
1097            .path()
1098            .file_stem()
1099            .ok_or(InvalidUrl::new(ErrorKind::InvalidPath))?;
1100        if extension.contains('/') {
1101            return Err(InvalidUrl::new(ErrorKind::InvalidPath));
1102        }
1103        let name = if extension.is_empty() {
1104            Cow::Borrowed(stem)
1105        } else {
1106            let extension = quote(extension, Component::Path);
1107            Cow::Owned(format!("{stem}.{extension}"))
1108        };
1109        self.with_file_name(&name).map(|url| *self = url)
1110    }
1111
1112    /// Sets or removes the percent-encoded query.
1113    ///
1114    /// ```
1115    /// use urly::Url;
1116    ///
1117    /// let mut url = Url::from_static("http://h/#f");
1118    /// url.set_query(Some("a=b c&d"));
1119    /// assert_eq!(url, "http://h/?a=b+c&d#f");
1120    /// ```
1121    pub fn set_query(&mut self, query: Option<&str>) {
1122        too_long(self.try_set_query(query));
1123    }
1124
1125    pub(crate) fn try_set_query(&mut self, query: Option<&str>) -> Result<(), InvalidUrl> {
1126        let query = query.map(|q| requote(q, Component::Query));
1127        self.rebuild(|c| c.query = query.as_deref())
1128            .map(|url| *self = url)
1129    }
1130
1131    /// Keeps existing pairs whose decoded key passes `keep` and appends literal
1132    /// `pairs`. An empty result removes the query.
1133    fn edit_query_pairs<I, K, V>(
1134        &mut self,
1135        keep: impl Fn(&str) -> bool,
1136        pairs: I,
1137    ) -> Result<(), InvalidUrl>
1138    where
1139        I: IntoIterator<Item = (K, V)>,
1140        K: AsRef<str>,
1141        V: AsRef<str>,
1142    {
1143        let existing = self.query().map_or("", Query::as_str);
1144        let pieces: Vec<Cow<'_, str>> = query::pieces(existing)
1145            .filter(|piece| keep(&unquote(split_pair(piece).0, Component::QueryPart)))
1146            .map(Cow::Borrowed)
1147            .chain(pairs.into_iter().map(|(k, v)| {
1148                let (k, v) = (k.as_ref(), v.as_ref());
1149                let (k, v) = (
1150                    quote(k, Component::QueryPart),
1151                    quote(v, Component::QueryPart),
1152                );
1153                Cow::Owned(format!("{k}={v}"))
1154            }))
1155            .collect();
1156        let query = pieces.join("&");
1157        self.rebuild(|c| c.query = (!query.is_empty()).then_some(query.as_str()))
1158            .map(|url| *self = url)
1159    }
1160
1161    /// Replaces the query with literal key-value pairs. Empty pairs remove the query.
1162    ///
1163    /// ```
1164    /// use urly::Url;
1165    ///
1166    /// let mut url = Url::from_static("http://h/?old");
1167    /// url.set_query_pairs([("a", "1 2"), ("b&", "=")]);
1168    /// assert_eq!(url, "http://h/?a=1+2&b%26=%3D");
1169    /// ```
1170    pub fn set_query_pairs<I, K, V>(&mut self, pairs: I)
1171    where
1172        I: IntoIterator<Item = (K, V)>,
1173        K: AsRef<str>,
1174        V: AsRef<str>,
1175    {
1176        too_long(self.edit_query_pairs(|_| false, pairs));
1177    }
1178
1179    /// Appends literal key-value pairs to the query.
1180    pub fn extend_query_pairs<I, K, V>(&mut self, pairs: I)
1181    where
1182        I: IntoIterator<Item = (K, V)>,
1183        K: AsRef<str>,
1184        V: AsRef<str>,
1185    {
1186        too_long(self.try_extend_query_pairs(pairs));
1187    }
1188
1189    pub(crate) fn try_extend_query_pairs<I, K, V>(&mut self, pairs: I) -> Result<(), InvalidUrl>
1190    where
1191        I: IntoIterator<Item = (K, V)>,
1192        K: AsRef<str>,
1193        V: AsRef<str>,
1194    {
1195        self.edit_query_pairs(|_| true, pairs)
1196    }
1197
1198    /// Replaces all values of the given keys, appending the new pairs.
1199    ///
1200    /// ```
1201    /// use urly::Url;
1202    ///
1203    /// let mut url = Url::from_static("http://h/?a=1&b=2&a=3");
1204    /// url.update_query_pairs([("a", "4")]);
1205    /// assert_eq!(url, "http://h/?b=2&a=4");
1206    /// ```
1207    pub fn update_query_pairs<I, K, V>(&mut self, pairs: I)
1208    where
1209        I: IntoIterator<Item = (K, V)>,
1210        K: AsRef<str>,
1211        V: AsRef<str>,
1212    {
1213        let pairs: Vec<(K, V)> = pairs.into_iter().collect();
1214        let keep = |key: &str| !pairs.iter().any(|(k, _)| k.as_ref() == key);
1215        too_long(self.edit_query_pairs(keep, pairs.iter().map(|(k, v)| (k.as_ref(), v.as_ref()))));
1216    }
1217
1218    /// Removes all pairs with the given keys from the query.
1219    ///
1220    /// ```
1221    /// use urly::Url;
1222    ///
1223    /// let mut url = Url::from_static("http://h/?a=1&b=2&a=3");
1224    /// url.remove_query_params(["a"]);
1225    /// assert_eq!(url, "http://h/?b=2");
1226    /// url.remove_query_params(["b"]);
1227    /// assert_eq!(url, "http://h/");
1228    /// ```
1229    pub fn remove_query_params<I, K>(&mut self, keys: I)
1230    where
1231        I: IntoIterator<Item = K>,
1232        K: AsRef<str>,
1233    {
1234        let keys: Vec<K> = keys.into_iter().collect();
1235        let keep = |key: &str| !keys.iter().any(|k| k.as_ref() == key);
1236        too_long(self.edit_query_pairs(keep, std::iter::empty::<(&str, &str)>()));
1237    }
1238
1239    /// Sets or removes the percent-encoded fragment.
1240    pub fn set_fragment(&mut self, fragment: Option<&str>) {
1241        too_long(self.try_set_fragment(fragment));
1242    }
1243
1244    pub(crate) fn try_set_fragment(&mut self, fragment: Option<&str>) -> Result<(), InvalidUrl> {
1245        let fragment = fragment.map(|f| requote(f, Component::Fragment));
1246        self.rebuild(|c| c.fragment = fragment.as_deref())
1247            .map(|url| *self = url)
1248    }
1249
1250    /// Splits the URL into its parts.
1251    pub fn into_parts(self) -> crate::Parts {
1252        let slice = |start: u16, end: usize| self.data.slice(start as usize..end);
1253        crate::Parts {
1254            scheme: self.scheme().map(|_| slice(0, self.scheme_end as usize)),
1255            authority: self
1256                .authority()
1257                .map(|_| slice(self.auth_start, self.path_start as usize)),
1258            path_and_query: slice(self.path_start, self.query_end as usize),
1259            fragment: self
1260                .fragment()
1261                .map(|_| slice(self.query_end + 1, self.data.len())),
1262        }
1263    }
1264
1265    /// Converts the URL into its buffer.
1266    pub fn into_byte_string(self) -> ByteString {
1267        self.data
1268    }
1269}
1270
1271/// Returns the path up to and including the last `/`.
1272fn dir(path: &str) -> &str {
1273    path.rfind('/').map_or("", |i| &path[..=i])
1274}
1275
1276// ===== trait impls =====
1277
1278str_fmt!(Url);
1279str_eq!(Url);
1280
1281/// Returns the relative URL `/`, like `http::Uri::default()`.
1282impl Default for Url {
1283    fn default() -> Url {
1284        Url::new()
1285    }
1286}
1287
1288impl FromStr for Url {
1289    type Err = InvalidUrl;
1290
1291    fn from_str(s: &str) -> Result<Url, InvalidUrl> {
1292        parse::parse(s, None)
1293    }
1294}
1295
1296macro_rules! try_from {
1297    ($($ty:ty => |$s:ident| $conv:expr;)*) => {$(
1298        impl TryFrom<$ty> for Url {
1299            type Error = InvalidUrl;
1300
1301            fn try_from($s: $ty) -> Result<Url, InvalidUrl> {
1302                $conv
1303            }
1304        }
1305    )*};
1306}
1307
1308try_from! {
1309    &str => |s| parse::parse(s, None);
1310    &String => |s| parse::parse(s, None);
1311    // `ByteString::from(String)` copies, assembling copies only once
1312    String => |s| parse::parse(&s, None);
1313    ByteString => |s| parse::parse(&s, Some(&s));
1314    &ByteString => |s| parse::parse(s, Some(s));
1315    &[u8] => |s| parse::parse(from_utf8(s).map_err(utf8_error)?, None);
1316    Bytes => |s| {
1317        from_utf8(&s).map_err(utf8_error)?;
1318        // SAFETY: validated above
1319        Url::try_from(unsafe { ByteString::from_bytes_unchecked(s) })
1320    };
1321}
1322
1323#[allow(clippy::needless_pass_by_value)]
1324pub(crate) fn utf8_error(e: Utf8Error) -> InvalidUrl {
1325    InvalidUrl::at(ErrorKind::InvalidChar('\u{FFFD}'), e.valid_up_to())
1326}
1327
1328impl From<Url> for ByteString {
1329    fn from(url: Url) -> ByteString {
1330        url.data
1331    }
1332}
1333
1334impl From<Url> for String {
1335    fn from(url: Url) -> String {
1336        url.as_str().to_string()
1337    }
1338}
1339
1340impl<S: AsRef<str>> Div<S> for &Url {
1341    type Output = Url;
1342
1343    fn div(self, segment: S) -> Url {
1344        self.push_segments([segment])
1345    }
1346}
1347
1348impl<S: AsRef<str>> Div<S> for Url {
1349    type Output = Url;
1350
1351    fn div(self, segment: S) -> Url {
1352        self.push_segments([segment])
1353    }
1354}
1355
1356impl<U: Borrow<Url>> Add<U> for &Url {
1357    type Output = Url;
1358
1359    fn add(self, reference: U) -> Url {
1360        self.join_url(reference.borrow())
1361    }
1362}
1363
1364impl<U: Borrow<Url>> Add<U> for Url {
1365    type Output = Url;
1366
1367    fn add(self, reference: U) -> Url {
1368        self.join_url(reference.borrow())
1369    }
1370}
1371
1372impl<U: Borrow<Url>> AddAssign<U> for Url {
1373    fn add_assign(&mut self, reference: U) {
1374        *self = self.join_url(reference.borrow());
1375    }
1376}
1377
1378#[cfg(feature = "http")]
1379mod http_impls {
1380    use http::uri::{InvalidUri, Uri};
1381
1382    use super::Url;
1383    use crate::error::InvalidUrl;
1384
1385    impl TryFrom<&Uri> for Url {
1386        type Error = InvalidUrl;
1387
1388        fn try_from(uri: &Uri) -> Result<Url, InvalidUrl> {
1389            if uri.scheme().is_none()
1390                && let Some(authority) = uri.authority()
1391            {
1392                return Url::parse(authority.as_str());
1393            }
1394            let uri = uri.to_string();
1395            // an origin-form path starting with `//` is not an authority
1396            if uri.starts_with("//") {
1397                Url::try_from(format!("/.{uri}"))
1398            } else {
1399                Url::try_from(uri)
1400            }
1401        }
1402    }
1403
1404    impl TryFrom<Uri> for Url {
1405        type Error = InvalidUrl;
1406
1407        fn try_from(uri: Uri) -> Result<Url, InvalidUrl> {
1408            Url::try_from(&uri)
1409        }
1410    }
1411
1412    /// The fragment is removed, `Uri` doesn't support it. A network-path
1413    /// reference converts to authority-form, it fails if it has a path or
1414    /// query.
1415    impl TryFrom<&Url> for Uri {
1416        type Error = InvalidUri;
1417
1418        fn try_from(url: &Url) -> Result<Uri, InvalidUri> {
1419            // `Uri` parses a relative reference as origin-form, without the `/.`
1420            // prefix, and a reference without scheme and `//` as authority-form
1421            let start = match (url.scheme_end, url.auth_start) {
1422                (0, 0) => url.path_start,
1423                (0, auth_start) => auth_start,
1424                _ => 0,
1425            };
1426            Uri::try_from(url.range(start, url.query_end))
1427        }
1428    }
1429
1430    /// The fragment is removed, `Uri` doesn't support it.
1431    impl TryFrom<Url> for Uri {
1432        type Error = InvalidUri;
1433
1434        fn try_from(url: Url) -> Result<Uri, InvalidUri> {
1435            Uri::try_from(&url)
1436        }
1437    }
1438}
1439
1440#[cfg(feature = "serde")]
1441mod serde_impls {
1442    use std::fmt;
1443
1444    use serde::de::{self, Deserialize, Deserializer, Visitor};
1445    use serde::{Serialize, Serializer};
1446
1447    use super::Url;
1448
1449    impl Serialize for Url {
1450        fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1451            serializer.serialize_str(self.as_str())
1452        }
1453    }
1454
1455    struct UrlVisitor;
1456
1457    impl Visitor<'_> for UrlVisitor {
1458        type Value = Url;
1459
1460        fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1461            f.write_str("a url")
1462        }
1463
1464        fn visit_str<E: de::Error>(self, v: &str) -> Result<Url, E> {
1465            Url::try_from(v).map_err(E::custom)
1466        }
1467
1468        fn visit_string<E: de::Error>(self, v: String) -> Result<Url, E> {
1469            Url::try_from(v).map_err(E::custom)
1470        }
1471    }
1472
1473    impl<'de> Deserialize<'de> for Url {
1474        fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Url, D::Error> {
1475            deserializer.deserialize_str(UrlVisitor)
1476        }
1477    }
1478}
1479
1480#[cfg(test)]
1481mod tests {
1482    use super::*;
1483
1484    /// STATEMENT: `Url::new` is usable in `const`, equals `Url::default`, and has the same
1485    /// layout as a parsed `/`.
1486    ///
1487    /// HOW:
1488    /// - Compare a `const` `Url::new()` with `Url::default()`.
1489    /// - Compare every offset field with `Url::from_static("/")`.
1490    /// - Expect path `/`, no query and a relative URL.
1491    #[test]
1492    fn default() {
1493        const URL: Url = Url::new();
1494        assert_eq!(URL, Url::default());
1495        let (url, p) = (Url::default(), Url::from_static("/"));
1496        assert_eq!(url.scheme_end, p.scheme_end);
1497        assert_eq!(url.auth_start, p.auth_start);
1498        assert_eq!(url.path_start, p.path_start);
1499        assert_eq!(url.path_end, p.path_end);
1500        assert_eq!(url.query_end, p.query_end);
1501        assert_eq!((url.host_start, url.host_end), (p.host_start, p.host_end));
1502        assert_eq!(url, "/");
1503        assert_eq!(url.path(), "/");
1504        assert!(url.query().is_none());
1505        assert!(!url.is_absolute());
1506    }
1507
1508    /// STATEMENT: The cached host offsets give the same userinfo, host and port as parsing the
1509    /// authority, and survive `set_path`.
1510    ///
1511    /// HOW:
1512    /// - For URLs with and without userinfo, IPv6 host, port and authority, compare
1513    ///   `userinfo`, `host` and `port_u16` with the listed values and the `Authority` getters.
1514    /// - Change the path of a clone; expect the same host and port.
1515    #[test]
1516    fn cached_host() {
1517        let cases = [
1518            (
1519                "http://u:p@[::1]:8080/a",
1520                Some("u:p"),
1521                Some("[::1]"),
1522                Some(8080),
1523            ),
1524            ("http://@h/", Some(""), Some("h"), None),
1525            ("http://h:0/", None, Some("h"), Some(0)),
1526            ("file:///etc", None, None, None),
1527            ("//h", None, Some("h"), None),
1528            ("/a", None, None, None),
1529        ];
1530        for (src, userinfo, host, port) in cases {
1531            let url = Url::from_static(src);
1532            let auth = url.authority();
1533            assert_eq!(url.userinfo().map(UserInfo::as_str), userinfo, "{src}");
1534            assert_eq!(url.host(), host, "{src}");
1535            assert_eq!(url.port_u16(), port, "{src}");
1536            assert_eq!(
1537                auth.and_then(|a| a.userinfo()).map(UserInfo::as_str),
1538                userinfo
1539            );
1540            assert_eq!(auth.map(Authority::host).filter(|h| !h.is_empty()), host);
1541            assert_eq!(auth.and_then(Authority::port_u16), port);
1542            let mut copy = url.clone();
1543            copy.set_path("/x");
1544            assert_eq!((copy.host(), copy.port_u16()), (host, port), "{src}");
1545        }
1546    }
1547
1548    /// STATEMENT: A path starting with `//` without an authority is kept unambiguous with a
1549    /// `/.` prefix, and the prefix is added or removed as the authority changes.
1550    ///
1551    /// HOW:
1552    /// - Parse `/.//a/../b`; expect `/.//b` serialized and `//b` as the path, through
1553    ///   `from_parts` and `join`.
1554    /// - Set `//p` on an empty URL; expect `/.//p`.
1555    /// - Remove and restore the authority of `http://h//p`; expect the prefix to appear and go.
1556    /// - Build from `Parts` with path `//p`; expect path `//p`.
1557    #[test]
1558    fn double_slash_path() {
1559        let url = Url::from_static("/.//a/../b?q#f");
1560        assert_eq!(url, "/.//b?q#f");
1561        assert_eq!(url.path(), "//b");
1562        assert_eq!(url.path_and_query(), "//b?q");
1563        assert!(url.authority().is_none());
1564        assert_eq!(Url::from_parts(url.clone().into_parts()).unwrap(), url);
1565        assert_eq!(url.join("c").unwrap().path(), "//c");
1566
1567        let mut url = Url::default();
1568        url.set_path("//p");
1569        assert_eq!(url, "/.//p");
1570        assert_eq!(url.path(), "//p");
1571
1572        let mut url = Url::from_static("http://h//p?q");
1573        assert_eq!(url.path(), "//p");
1574        url.set_authority(None).unwrap();
1575        assert_eq!(url, "http:/.//p?q");
1576        assert_eq!(url.path(), "//p");
1577        url.set_authority(Some("h")).unwrap();
1578        assert_eq!(url, "http://h//p?q");
1579
1580        let parts = crate::Parts {
1581            path_and_query: "//p?q".into(),
1582            ..crate::Parts::default()
1583        };
1584        assert_eq!(Url::from_parts(parts).unwrap().path(), "//p");
1585    }
1586
1587    /// STATEMENT: The absolute-form fast path of `Url::from_target_parts` builds exactly the
1588    /// URL and offsets that generic target assembly builds.
1589    ///
1590    /// HOW:
1591    /// - Build inline and heap-sized targets with and without query, repeated `?`, userinfo,
1592    ///   ports, IPv6 and broken IPv6 hosts, empty or delimiter-laden authorities, `//` and
1593    ///   non-ASCII paths, with `absolute_target` and with `assemble_target`.
1594    /// - Compare the serialization and every offset field.
1595    /// - Build targets of exactly the maximum length and one byte longer; expect the same
1596    ///   success and `TooLong` error from both.
1597    #[test]
1598    fn absolute_target_matches_assemble() {
1599        fn fields(res: Result<Url, InvalidUrl>) -> Result<(String, [u16; 7]), ErrorKind> {
1600            res.map(|u| {
1601                let offsets = [
1602                    u.scheme_end,
1603                    u.auth_start,
1604                    u.path_start,
1605                    u.path_end,
1606                    u.query_end,
1607                    u.host_start,
1608                    u.host_end,
1609                ];
1610                (u.as_str().to_owned(), offsets)
1611            })
1612            .map_err(|e| e.kind())
1613        }
1614        let limit = format!("/{}", "a".repeat(parse::MAX_LEN - "http://h/".len()));
1615        let too_long = format!("{limit}a");
1616        let cases = [
1617            ("http", "localhost:8082", "/baseline2?a=1&b=1"),
1618            ("https", "ex.com", "/"),
1619            ("http", "h", "/a?"),
1620            ("http", "h", "/a??b?c"),
1621            ("http", "u:p@h:1", "/"),
1622            ("http", "@h", "/"),
1623            ("http", "[::1]:8080", "/p?q"),
1624            ("http", "[::1]", "/p"),
1625            ("http", "[::1", "/p"),
1626            ("http", "h:443", "/"),
1627            ("http", "", "/"),
1628            ("ht/tp", "host/x?y#z:", "/p#f"),
1629            ("http", "h", "//p?q"),
1630            ("http", "münchen.de:1", "/ü?ä=ö"),
1631            ("http", "h", limit.as_str()),
1632            ("http", "h", too_long.as_str()),
1633        ];
1634        for (scheme, authority, pq) in cases {
1635            let (path, query) = crate::chars::split_at_char(pq, b'?');
1636            let c = Components {
1637                scheme: Some(scheme),
1638                authority: Some(authority),
1639                path,
1640                query,
1641                fragment: None,
1642            };
1643            let fast = fields(absolute_target(scheme, authority, pq));
1644            let generic = fields(assemble_target(&c, None));
1645            assert_eq!(fast, generic, "{scheme} {authority} {:.40}", pq);
1646        }
1647        assert!(fields(absolute_target("http", "h", &limit)).is_ok());
1648        assert_eq!(
1649            fields(absolute_target("http", "h", &too_long)),
1650            Err(ErrorKind::TooLong)
1651        );
1652    }
1653}