Skip to main content

url/
parser.rs

1// Copyright 2013-2016 The rust-url developers.
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
6// option. This file may not be copied, modified, or distributed
7// except according to those terms.
8
9use alloc::borrow::Cow;
10use alloc::string::String;
11use core::fmt::{self, Formatter, Write};
12use core::str;
13
14use crate::host::{Host, HostInternal};
15use crate::Url;
16use form_urlencoded::EncodingOverride;
17use percent_encoding::{percent_encode, utf8_percent_encode, AsciiSet, CONTROLS};
18
19/// https://url.spec.whatwg.org/#fragment-percent-encode-set
20const FRAGMENT: &AsciiSet = &CONTROLS.add(b' ').add(b'"').add(b'<').add(b'>').add(b'`');
21
22/// https://url.spec.whatwg.org/#query-percent-encode-set
23const QUERY: &AsciiSet = &CONTROLS.add(b' ').add(b'"').add(b'#').add(b'<').add(b'>');
24const SPECIAL_QUERY: &AsciiSet = &QUERY.add(b'\'');
25
26/// https://url.spec.whatwg.org/#path-percent-encode-set
27const PATH: &AsciiSet = &QUERY.add(b'?').add(b'^').add(b'`').add(b'{').add(b'}');
28
29/// https://url.spec.whatwg.org/#userinfo-percent-encode-set
30pub(crate) const USERINFO: &AsciiSet = &PATH
31    .add(b'/')
32    .add(b':')
33    .add(b';')
34    .add(b'=')
35    .add(b'@')
36    .add(b'[')
37    .add(b'\\')
38    .add(b']')
39    .add(b'|');
40
41pub(crate) const PATH_SEGMENT: &AsciiSet = &PATH.add(b'/').add(b'%');
42
43// The backslash (\) character is treated as a path separator in special URLs
44// so it needs to be additionally escaped in that case.
45pub(crate) const SPECIAL_PATH_SEGMENT: &AsciiSet = &PATH_SEGMENT.add(b'\\');
46
47pub type ParseResult<T> = Result<T, ParseError>;
48
49macro_rules! simple_enum_error {
50    ($($name: ident => $description: expr,)+) => {
51        /// Errors that can occur during parsing.
52        ///
53        /// This may be extended in the future so exhaustive matching is
54        /// forbidden.
55        #[derive(PartialEq, Eq, Clone, Copy, Debug)]
56        #[non_exhaustive]
57        pub enum ParseError {
58            $(
59                $name,
60            )+
61        }
62
63        impl fmt::Display for ParseError {
64            fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
65                match *self {
66                    $(
67                        ParseError::$name => fmt.write_str($description),
68                    )+
69                }
70            }
71        }
72    }
73}
74
75macro_rules! ascii_tab_or_new_line_pattern {
76    () => {
77        '\t' | '\n' | '\r'
78    };
79}
80
81#[cfg(feature = "std")]
82impl std::error::Error for ParseError {}
83
84#[cfg(not(feature = "std"))]
85impl core::error::Error for ParseError {}
86
87/// Errors that can occur during parsing.
///
/// This may be extended in the future so exhaustive matching is
/// forbidden.
#[non_exhaustive]
pub enum ParseError {
    EmptyHost,
    IdnaError,
    InvalidPort,
    InvalidIpv4Address,
    InvalidIpv6Address,
    InvalidDomainCharacter,
    RelativeUrlWithoutBase,
    RelativeUrlWithCannotBeABaseBase,
    SetHostOnCannotBeABaseUrl,
    Overflow,
}
#[automatically_derived]impl ::core::marker::StructuralPartialEq for
    ParseError {
}
#[automatically_derived]impl ::core::cmp::PartialEq for ParseError {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}
#[automatically_derived]impl ::core::cmp::Eq for ParseError { }
#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for ParseError {
}
#[automatically_derived]impl ::core::clone::Clone for ParseError {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self { *self }
}
#[automatically_derived]impl ::core::marker::Copy for ParseError { }
#[automatically_derived]impl ::core::fmt::Debug for ParseError {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_c_like_enum_write_str(f,
            "EmptyHost IdnaError InvalidPort InvalidIpv4Address InvalidIpv6Address InvalidDomainCharacter RelativeUrlWithoutBase RelativeUrlWithCannotBeABaseBase SetHostOnCannotBeABaseUrl Overflow",
            match self {
                ParseError::EmptyHost => 0usize,
                ParseError::IdnaError => 10usize,
                ParseError::InvalidPort => 20usize,
                ParseError::InvalidIpv4Address => 32usize,
                ParseError::InvalidIpv6Address => 51usize,
                ParseError::InvalidDomainCharacter => 70usize,
                ParseError::RelativeUrlWithoutBase => 93usize,
                ParseError::RelativeUrlWithCannotBeABaseBase => 116usize,
                ParseError::SetHostOnCannotBeABaseUrl => 149usize,
                ParseError::Overflow => 175usize,
            })
    }
}
impl fmt::Display for ParseError {
    fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
        match *self {
            ParseError::EmptyHost => fmt.write_str("empty host"),
            ParseError::IdnaError =>
                fmt.write_str("invalid international domain name"),
            ParseError::InvalidPort => fmt.write_str("invalid port number"),
            ParseError::InvalidIpv4Address =>
                fmt.write_str("invalid IPv4 address"),
            ParseError::InvalidIpv6Address =>
                fmt.write_str("invalid IPv6 address"),
            ParseError::InvalidDomainCharacter =>
                fmt.write_str("invalid domain character"),
            ParseError::RelativeUrlWithoutBase =>
                fmt.write_str("relative URL without a base"),
            ParseError::RelativeUrlWithCannotBeABaseBase =>
                fmt.write_str("relative URL with a cannot-be-a-base base"),
            ParseError::SetHostOnCannotBeABaseUrl =>
                fmt.write_str("a cannot-be-a-base URL doesn’t have a host to set"),
            ParseError::Overflow =>
                fmt.write_str("URLs more than 4 GB are not supported"),
        }
    }
}simple_enum_error! {
88    EmptyHost => "empty host",
89    IdnaError => "invalid international domain name",
90    InvalidPort => "invalid port number",
91    InvalidIpv4Address => "invalid IPv4 address",
92    InvalidIpv6Address => "invalid IPv6 address",
93    InvalidDomainCharacter => "invalid domain character",
94    RelativeUrlWithoutBase => "relative URL without a base",
95    RelativeUrlWithCannotBeABaseBase => "relative URL with a cannot-be-a-base base",
96    SetHostOnCannotBeABaseUrl => "a cannot-be-a-base URL doesn’t have a host to set",
97    Overflow => "URLs more than 4 GB are not supported",
98}
99
100impl From<::idna::Errors> for ParseError {
101    fn from(_: ::idna::Errors) -> Self {
102        Self::IdnaError
103    }
104}
105
106macro_rules! syntax_violation_enum {
107    ($($name: ident => $description: literal,)+) => {
108        /// Non-fatal syntax violations that can occur during parsing.
109        ///
110        /// This may be extended in the future so exhaustive matching is
111        /// forbidden.
112        #[derive(PartialEq, Eq, Clone, Copy, Debug)]
113        #[non_exhaustive]
114        pub enum SyntaxViolation {
115            $(
116                /// ```text
117                #[doc = $description]
118                /// ```
119                $name,
120            )+
121        }
122
123        impl SyntaxViolation {
124            pub fn description(&self) -> &'static str {
125                match *self {
126                    $(
127                        SyntaxViolation::$name => $description,
128                    )+
129                }
130            }
131        }
132    }
133}
134
135/// Non-fatal syntax violations that can occur during parsing.
///
/// This may be extended in the future so exhaustive matching is
/// forbidden.
#[non_exhaustive]
pub enum SyntaxViolation {

    /// ```text
    #[doc = "backslash"]
    /// ```
    Backslash,

    /// ```text
    #[doc =
    "leading or trailing control or space character are ignored in URLs"]
    /// ```
    C0SpaceIgnored,

    /// ```text
    #[doc =
    "embedding authentication information (username or password) \
         in an URL is not recommended"]
    /// ```
    EmbeddedCredentials,

    /// ```text
    #[doc = "expected //"]
    /// ```
    ExpectedDoubleSlash,

    /// ```text
    #[doc = "expected // after file:"]
    /// ```
    ExpectedFileDoubleSlash,

    /// ```text
    #[doc = "file: with host and Windows drive letter"]
    /// ```
    FileWithHostAndWindowsDrive,

    /// ```text
    #[doc = "non-URL code point"]
    /// ```
    NonUrlCodePoint,

    /// ```text
    #[doc = "NULL characters are ignored in URL fragment identifiers"]
    /// ```
    NullInFragment,

    /// ```text
    #[doc = "expected 2 hex digits after %"]
    /// ```
    PercentDecode,

    /// ```text
    #[doc = "tabs or newlines are ignored in URLs"]
    /// ```
    TabOrNewlineIgnored,

    /// ```text
    #[doc = "unencoded @ sign in username or password"]
    /// ```
    UnencodedAtSign,
}
#[automatically_derived]impl ::core::marker::StructuralPartialEq for
    SyntaxViolation {
}
#[automatically_derived]impl ::core::cmp::PartialEq for SyntaxViolation {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}
#[automatically_derived]impl ::core::cmp::Eq for SyntaxViolation { }
#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for SyntaxViolation {
}
#[automatically_derived]impl ::core::clone::Clone for SyntaxViolation {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self { *self }
}
#[automatically_derived]impl ::core::marker::Copy for SyntaxViolation { }
#[automatically_derived]impl ::core::fmt::Debug for SyntaxViolation {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_c_like_enum_write_str(f,
            "Backslash C0SpaceIgnored EmbeddedCredentials ExpectedDoubleSlash ExpectedFileDoubleSlash FileWithHostAndWindowsDrive NonUrlCodePoint NullInFragment PercentDecode TabOrNewlineIgnored UnencodedAtSign",
            match self {
                SyntaxViolation::Backslash => 0usize,
                SyntaxViolation::C0SpaceIgnored => 10usize,
                SyntaxViolation::EmbeddedCredentials => 25usize,
                SyntaxViolation::ExpectedDoubleSlash => 45usize,
                SyntaxViolation::ExpectedFileDoubleSlash => 65usize,
                SyntaxViolation::FileWithHostAndWindowsDrive => 89usize,
                SyntaxViolation::NonUrlCodePoint => 117usize,
                SyntaxViolation::NullInFragment => 133usize,
                SyntaxViolation::PercentDecode => 148usize,
                SyntaxViolation::TabOrNewlineIgnored => 162usize,
                SyntaxViolation::UnencodedAtSign => 182usize,
            })
    }
}
impl SyntaxViolation {
    pub fn description(&self) -> &'static str {
        match *self {
            SyntaxViolation::Backslash => "backslash",
            SyntaxViolation::C0SpaceIgnored =>
                "leading or trailing control or space character are ignored in URLs",
            SyntaxViolation::EmbeddedCredentials =>
                "embedding authentication information (username or password) \
         in an URL is not recommended",
            SyntaxViolation::ExpectedDoubleSlash => "expected //",
            SyntaxViolation::ExpectedFileDoubleSlash =>
                "expected // after file:",
            SyntaxViolation::FileWithHostAndWindowsDrive =>
                "file: with host and Windows drive letter",
            SyntaxViolation::NonUrlCodePoint => "non-URL code point",
            SyntaxViolation::NullInFragment =>
                "NULL characters are ignored in URL fragment identifiers",
            SyntaxViolation::PercentDecode => "expected 2 hex digits after %",
            SyntaxViolation::TabOrNewlineIgnored =>
                "tabs or newlines are ignored in URLs",
            SyntaxViolation::UnencodedAtSign =>
                "unencoded @ sign in username or password",
        }
    }
}syntax_violation_enum! {
136    Backslash => "backslash",
137    C0SpaceIgnored =>
138        "leading or trailing control or space character are ignored in URLs",
139    EmbeddedCredentials =>
140        "embedding authentication information (username or password) \
141         in an URL is not recommended",
142    ExpectedDoubleSlash => "expected //",
143    ExpectedFileDoubleSlash => "expected // after file:",
144    FileWithHostAndWindowsDrive => "file: with host and Windows drive letter",
145    NonUrlCodePoint => "non-URL code point",
146    NullInFragment => "NULL characters are ignored in URL fragment identifiers",
147    PercentDecode => "expected 2 hex digits after %",
148    TabOrNewlineIgnored => "tabs or newlines are ignored in URLs",
149    UnencodedAtSign => "unencoded @ sign in username or password",
150}
151
152impl fmt::Display for SyntaxViolation {
153    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
154        fmt::Display::fmt(self.description(), f)
155    }
156}
157
158#[derive(#[automatically_derived]impl ::core::marker::Copy for SchemeType { }Copy, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for SchemeType {
}
#[automatically_derived]impl ::core::clone::Clone for SchemeType {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    SchemeType {
}
#[automatically_derived]impl ::core::cmp::PartialEq for SchemeType {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for SchemeType { }Eq)]
159pub enum SchemeType {
160    File,
161    SpecialNotFile,
162    NotSpecial,
163}
164
165impl SchemeType {
166    pub fn is_special(&self) -> bool {
167        !#[allow(non_exhaustive_omitted_patterns)] match *self {
    Self::NotSpecial => true,
    _ => false,
}matches!(*self, Self::NotSpecial)
168    }
169
170    pub fn is_file(&self) -> bool {
171        #[allow(non_exhaustive_omitted_patterns)] match *self {
    Self::File => true,
    _ => false,
}matches!(*self, Self::File)
172    }
173}
174
175impl<T: AsRef<str>> From<T> for SchemeType {
176    fn from(s: T) -> Self {
177        match s.as_ref() {
178            "http" | "https" | "ws" | "wss" | "ftp" => Self::SpecialNotFile,
179            "file" => Self::File,
180            _ => Self::NotSpecial,
181        }
182    }
183}
184
185pub fn default_port(scheme: &str) -> Option<u16> {
186    match scheme {
187        "http" | "ws" => Some(80),
188        "https" | "wss" => Some(443),
189        "ftp" => Some(21),
190        _ => None,
191    }
192}
193
194#[derive(#[automatically_derived]impl<'i> ::core::clone::Clone for Input<'i> {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        Input { chars: ::core::clone::Clone::clone(&self.chars) }
    }
}Clone, #[automatically_derived]impl<'i> ::core::fmt::Debug for Input<'i> {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field1_finish(f, "Input chars",
            &&self.chars)
    }
}Debug)]
195pub struct Input<'i> {
196    chars: str::Chars<'i>,
197}
198
199impl<'i> Input<'i> {
200    pub fn new_no_trim(input: &'i str) -> Self {
201        Input {
202            chars: input.chars(),
203        }
204    }
205
206    pub fn new_trim_tab_and_newlines(
207        original_input: &'i str,
208        vfn: Option<&dyn Fn(SyntaxViolation)>,
209    ) -> Self {
210        let input = original_input.trim_matches(ascii_tab_or_new_line);
211        if let Some(vfn) = vfn {
212            if input.len() < original_input.len() {
213                vfn(SyntaxViolation::C0SpaceIgnored)
214            }
215            if input.chars().any(ascii_tab_or_new_line) {
216                vfn(SyntaxViolation::TabOrNewlineIgnored)
217            }
218        }
219        Input {
220            chars: input.chars(),
221        }
222    }
223
224    pub fn new_trim_c0_control_and_space(
225        original_input: &'i str,
226        vfn: Option<&dyn Fn(SyntaxViolation)>,
227    ) -> Self {
228        let input = original_input.trim_matches(c0_control_or_space);
229        if let Some(vfn) = vfn {
230            if input.len() < original_input.len() {
231                vfn(SyntaxViolation::C0SpaceIgnored)
232            }
233            if input.chars().any(ascii_tab_or_new_line) {
234                vfn(SyntaxViolation::TabOrNewlineIgnored)
235            }
236        }
237        Input {
238            chars: input.chars(),
239        }
240    }
241
242    #[inline]
243    pub fn is_empty(&self) -> bool {
244        self.clone().next().is_none()
245    }
246
247    #[inline]
248    pub fn starts_with<P: Pattern>(&self, p: P) -> bool {
249        p.split_prefix(&mut self.clone())
250    }
251
252    #[inline]
253    pub fn split_prefix<P: Pattern>(&self, p: P) -> Option<Self> {
254        let mut remaining = self.clone();
255        if p.split_prefix(&mut remaining) {
256            Some(remaining)
257        } else {
258            None
259        }
260    }
261
262    #[inline]
263    fn split_first(&self) -> (Option<char>, Self) {
264        let mut remaining = self.clone();
265        (remaining.next(), remaining)
266    }
267
268    #[inline]
269    fn count_matching<F: Fn(char) -> bool>(&self, f: F) -> (u32, Self) {
270        let mut count = 0;
271        let mut remaining = self.clone();
272        loop {
273            let mut input = remaining.clone();
274            if #[allow(non_exhaustive_omitted_patterns)] match input.next() {
    Some(c) if f(c) => true,
    _ => false,
}matches!(input.next(), Some(c) if f(c)) {
275                remaining = input;
276                count += 1;
277            } else {
278                return (count, remaining);
279            }
280        }
281    }
282
283    #[inline]
284    fn next_utf8(&mut self) -> Option<(char, &'i str)> {
285        loop {
286            let utf8 = self.chars.as_str();
287            let c = self.chars.next()?;
288            if !ascii_tab_or_new_line(c) {
289                return Some((c, &utf8[..c.len_utf8()]));
290            }
291        }
292    }
293}
294
295pub trait Pattern {
296    fn split_prefix(self, input: &mut Input) -> bool;
297}
298
299impl Pattern for char {
300    fn split_prefix(self, input: &mut Input) -> bool {
301        input.next() == Some(self)
302    }
303}
304
305impl Pattern for &str {
306    fn split_prefix(self, input: &mut Input) -> bool {
307        for c in self.chars() {
308            if input.next() != Some(c) {
309                return false;
310            }
311        }
312        true
313    }
314}
315
316impl<F: FnMut(char) -> bool> Pattern for F {
317    fn split_prefix(self, input: &mut Input) -> bool {
318        input.next().map_or(false, self)
319    }
320}
321
322impl Iterator for Input<'_> {
323    type Item = char;
324    fn next(&mut self) -> Option<char> {
325        self.chars.by_ref().find(|&c| !ascii_tab_or_new_line(c))
326    }
327
328    fn size_hint(&self) -> (usize, Option<usize>) {
329        (0, Some(self.chars.as_str().len()))
330    }
331}
332
333pub struct Parser<'a> {
334    pub serialization: String,
335    pub base_url: Option<&'a Url>,
336    pub query_encoding_override: EncodingOverride<'a>,
337    pub violation_fn: Option<&'a dyn Fn(SyntaxViolation)>,
338    pub context: Context,
339}
340
341#[derive(#[automatically_derived]impl ::core::marker::StructuralPartialEq for Context {
}
#[automatically_derived]impl ::core::cmp::PartialEq for Context {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for Context { }Eq, #[automatically_derived]impl ::core::marker::Copy for Context { }Copy, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for Context {
}
#[automatically_derived]impl ::core::clone::Clone for Context {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self { *self }
}Clone)]
342pub enum Context {
343    UrlParser,
344    Setter,
345    PathSegmentSetter,
346}
347
348impl Parser<'_> {
349    fn log_violation(&self, v: SyntaxViolation) {
350        if let Some(f) = self.violation_fn {
351            f(v)
352        }
353    }
354
355    fn log_violation_if(&self, v: SyntaxViolation, test: impl FnOnce() -> bool) {
356        if let Some(f) = self.violation_fn {
357            if test() {
358                f(v)
359            }
360        }
361    }
362
363    pub fn for_setter(serialization: String) -> Self {
364        Parser {
365            serialization,
366            base_url: None,
367            query_encoding_override: None,
368            violation_fn: None,
369            context: Context::Setter,
370        }
371    }
372
373    /// https://url.spec.whatwg.org/#concept-basic-url-parser
374    pub fn parse_url(mut self, input: &str) -> ParseResult<Url> {
375        let input = Input::new_trim_c0_control_and_space(input, self.violation_fn);
376        if let Ok(remaining) = self.parse_scheme(input.clone()) {
377            return self.parse_with_scheme(remaining);
378        }
379
380        // No-scheme state
381        if let Some(base_url) = self.base_url {
382            if input.starts_with('#') {
383                self.fragment_only(base_url, input)
384            } else if base_url.cannot_be_a_base() {
385                Err(ParseError::RelativeUrlWithCannotBeABaseBase)
386            } else {
387                let scheme_type = SchemeType::from(base_url.scheme());
388                if scheme_type.is_file() {
389                    self.parse_file(input, scheme_type, Some(base_url))
390                } else {
391                    self.parse_relative(input, scheme_type, base_url)
392                }
393            }
394        } else {
395            Err(ParseError::RelativeUrlWithoutBase)
396        }
397    }
398
399    pub fn parse_scheme<'i>(&mut self, mut input: Input<'i>) -> Result<Input<'i>, ()> {
400        // starts_with will also fail for empty strings so we can skip that comparison for perf
401        if !input.starts_with(ascii_alpha) {
402            return Err(());
403        }
404        if true {
    if !self.serialization.is_empty() {
        ::core::panicking::panic("assertion failed: self.serialization.is_empty()")
    };
};debug_assert!(self.serialization.is_empty());
405        while let Some(c) = input.next() {
406            match c {
407                'a'..='z' | '0'..='9' | '+' | '-' | '.' => self.serialization.push(c),
408                'A'..='Z' => self.serialization.push(c.to_ascii_lowercase()),
409                ':' => return Ok(input),
410                _ => {
411                    self.serialization.clear();
412                    return Err(());
413                }
414            }
415        }
416        // EOF before ':'
417        if self.context == Context::Setter {
418            Ok(input)
419        } else {
420            self.serialization.clear();
421            Err(())
422        }
423    }
424
425    fn parse_with_scheme(mut self, input: Input<'_>) -> ParseResult<Url> {
426        use crate::SyntaxViolation::{ExpectedDoubleSlash, ExpectedFileDoubleSlash};
427        let scheme_end = to_u32(self.serialization.len())?;
428        let scheme_type = SchemeType::from(&self.serialization);
429        self.serialization.push(':');
430        match scheme_type {
431            SchemeType::File => {
432                self.log_violation_if(ExpectedFileDoubleSlash, || !input.starts_with("//"));
433                let base_file_url = self.base_url.filter(|base| base.scheme() == "file");
434                self.serialization.clear();
435                self.parse_file(input, scheme_type, base_file_url)
436            }
437            SchemeType::SpecialNotFile => {
438                // special relative or authority state
439                let (slashes_count, remaining) = input.count_matching(|c| #[allow(non_exhaustive_omitted_patterns)] match c {
    '/' | '\\' => true,
    _ => false,
}matches!(c, '/' | '\\'));
440                if let Some(base_url) = self.base_url {
441                    if slashes_count < 2
442                        && base_url.scheme() == &self.serialization[..scheme_end as usize]
443                    {
444                        // "Cannot-be-a-base" URLs only happen with "not special" schemes.
445                        if true {
    if !!base_url.cannot_be_a_base() {
        ::core::panicking::panic("assertion failed: !base_url.cannot_be_a_base()")
    };
};debug_assert!(!base_url.cannot_be_a_base());
446                        self.serialization.clear();
447                        return self.parse_relative(input, scheme_type, base_url);
448                    }
449                }
450                // special authority slashes state
451                self.log_violation_if(ExpectedDoubleSlash, || {
452                    input
453                        .clone()
454                        .take_while(|&c| #[allow(non_exhaustive_omitted_patterns)] match c {
    '/' | '\\' => true,
    _ => false,
}matches!(c, '/' | '\\'))
455                        .collect::<String>()
456                        != "//"
457                });
458                self.after_double_slash(remaining, scheme_type, scheme_end)
459            }
460            SchemeType::NotSpecial => self.parse_non_special(input, scheme_type, scheme_end),
461        }
462    }
463
464    /// Scheme other than file, http, https, ws, ws, ftp.
465    fn parse_non_special(
466        mut self,
467        input: Input<'_>,
468        scheme_type: SchemeType,
469        scheme_end: u32,
470    ) -> ParseResult<Url> {
471        // path or authority state (
472        if let Some(input) = input.split_prefix("//") {
473            return self.after_double_slash(input, scheme_type, scheme_end);
474        }
475        // Anarchist URL (no authority)
476        let path_start = to_u32(self.serialization.len())?;
477        let username_end = path_start;
478        let host_start = path_start;
479        let host_end = path_start;
480        let host = HostInternal::None;
481        let port = None;
482        let remaining = if let Some(input) = input.split_prefix('/') {
483            self.serialization.push('/');
484            self.parse_path(scheme_type, &mut false, path_start as usize, input)
485        } else {
486            self.parse_cannot_be_a_base_path(input)
487        };
488        self.with_query_and_fragment(
489            scheme_type,
490            scheme_end,
491            username_end,
492            host_start,
493            host_end,
494            host,
495            port,
496            path_start,
497            remaining,
498        )
499    }
500
501    fn parse_file(
502        mut self,
503        input: Input<'_>,
504        scheme_type: SchemeType,
505        base_file_url: Option<&Url>,
506    ) -> ParseResult<Url> {
507        use crate::SyntaxViolation::Backslash;
508        // file state
509        if true {
    if !self.serialization.is_empty() {
        ::core::panicking::panic("assertion failed: self.serialization.is_empty()")
    };
};debug_assert!(self.serialization.is_empty());
510        let (first_char, input_after_first_char) = input.split_first();
511        if #[allow(non_exhaustive_omitted_patterns)] match first_char {
    Some('/') | Some('\\') => true,
    _ => false,
}matches!(first_char, Some('/') | Some('\\')) {
512            self.log_violation_if(SyntaxViolation::Backslash, || first_char == Some('\\'));
513            // file slash state
514            let (next_char, input_after_next_char) = input_after_first_char.split_first();
515            if #[allow(non_exhaustive_omitted_patterns)] match next_char {
    Some('/') | Some('\\') => true,
    _ => false,
}matches!(next_char, Some('/') | Some('\\')) {
516                self.log_violation_if(Backslash, || next_char == Some('\\'));
517                // file host state
518                self.serialization.push_str("file://");
519                let scheme_end = "file".len() as u32;
520                let host_start = "file://".len() as u32;
521                let (path_start, host, remaining) = self.parse_file_host(input_after_next_char)?;
522                let host_end = to_u32(self.serialization.len())?;
523                let mut has_host = !#[allow(non_exhaustive_omitted_patterns)] match host {
    HostInternal::None => true,
    _ => false,
}matches!(host, HostInternal::None);
524                let remaining = if path_start {
525                    self.parse_path_start(SchemeType::File, &mut has_host, remaining)
526                } else {
527                    let path_start = self.serialization.len();
528                    self.serialization.push('/');
529                    self.parse_path(SchemeType::File, &mut has_host, path_start, remaining)
530                };
531
532                let (query_start, fragment_start) =
533                    self.parse_query_and_fragment(scheme_type, scheme_end, remaining)?;
534                return Ok(Url {
535                    serialization: self.serialization,
536                    scheme_end,
537                    username_end: host_start,
538                    host_start,
539                    host_end,
540                    host,
541                    port: None,
542                    path_start: host_end,
543                    query_start,
544                    fragment_start,
545                });
546            } else {
547                self.serialization.push_str("file://");
548                let scheme_end = "file".len() as u32;
549                let host_start = "file://".len();
550                let mut host_end = host_start;
551                let mut host = HostInternal::None;
552                if !starts_with_windows_drive_letter_segment(&input_after_first_char) {
553                    if let Some(base_url) = base_file_url {
554                        let first_segment = base_url.path_segments().unwrap().next().unwrap();
555                        if is_normalized_windows_drive_letter(first_segment) {
556                            self.serialization.push('/');
557                            self.serialization.push_str(first_segment);
558                        } else if let Some(host_str) = base_url.host_str() {
559                            self.serialization.push_str(host_str);
560                            host_end = self.serialization.len();
561                            host = base_url.host;
562                        }
563                    }
564                }
565                // If c is the EOF code point, U+002F (/), U+005C (\), U+003F (?), or U+0023 (#), then decrease pointer by one
566                let parse_path_input = if let Some(c) = first_char {
567                    if c == '/' || c == '\\' || c == '?' || c == '#' {
568                        input
569                    } else {
570                        input_after_first_char
571                    }
572                } else {
573                    input_after_first_char
574                };
575
576                let remaining =
577                    self.parse_path(SchemeType::File, &mut false, host_end, parse_path_input);
578
579                let host_start = host_start as u32;
580
581                let (query_start, fragment_start) =
582                    self.parse_query_and_fragment(scheme_type, scheme_end, remaining)?;
583
584                let host_end = host_end as u32;
585                return Ok(Url {
586                    serialization: self.serialization,
587                    scheme_end,
588                    username_end: host_start,
589                    host_start,
590                    host_end,
591                    host,
592                    port: None,
593                    path_start: host_end,
594                    query_start,
595                    fragment_start,
596                });
597            }
598        }
599        if let Some(base_url) = base_file_url {
600            match first_char {
601                None => {
602                    // Copy everything except the fragment
603                    let before_fragment = match base_url.fragment_start {
604                        Some(i) => &base_url.serialization[..i as usize],
605                        None => &*base_url.serialization,
606                    };
607                    self.serialization.push_str(before_fragment);
608                    Ok(Url {
609                        serialization: self.serialization,
610                        fragment_start: None,
611                        ..*base_url
612                    })
613                }
614                Some('?') => {
615                    // Copy everything up to the query string
616                    let before_query = match (base_url.query_start, base_url.fragment_start) {
617                        (None, None) => &*base_url.serialization,
618                        (Some(i), _) | (None, Some(i)) => base_url.slice(..i),
619                    };
620                    self.serialization.push_str(before_query);
621                    let (query_start, fragment_start) =
622                        self.parse_query_and_fragment(scheme_type, base_url.scheme_end, input)?;
623                    Ok(Url {
624                        serialization: self.serialization,
625                        query_start,
626                        fragment_start,
627                        ..*base_url
628                    })
629                }
630                Some('#') => self.fragment_only(base_url, input),
631                _ => {
632                    if !starts_with_windows_drive_letter_segment(&input) {
633                        let before_query = match (base_url.query_start, base_url.fragment_start) {
634                            (None, None) => &*base_url.serialization,
635                            (Some(i), _) | (None, Some(i)) => base_url.slice(..i),
636                        };
637                        self.serialization.push_str(before_query);
638                        self.shorten_path(SchemeType::File, base_url.path_start as usize);
639                        let remaining = self.parse_path(
640                            SchemeType::File,
641                            &mut true,
642                            base_url.path_start as usize,
643                            input,
644                        );
645                        self.with_query_and_fragment(
646                            SchemeType::File,
647                            base_url.scheme_end,
648                            base_url.username_end,
649                            base_url.host_start,
650                            base_url.host_end,
651                            base_url.host,
652                            base_url.port,
653                            base_url.path_start,
654                            remaining,
655                        )
656                    } else {
657                        self.serialization.push_str("file:///");
658                        let scheme_end = "file".len() as u32;
659                        let path_start = "file://".len();
660                        let remaining =
661                            self.parse_path(SchemeType::File, &mut false, path_start, input);
662                        let (query_start, fragment_start) =
663                            self.parse_query_and_fragment(SchemeType::File, scheme_end, remaining)?;
664                        let path_start = path_start as u32;
665                        Ok(Url {
666                            serialization: self.serialization,
667                            scheme_end,
668                            username_end: path_start,
669                            host_start: path_start,
670                            host_end: path_start,
671                            host: HostInternal::None,
672                            port: None,
673                            path_start,
674                            query_start,
675                            fragment_start,
676                        })
677                    }
678                }
679            }
680        } else {
681            self.serialization.push_str("file:///");
682            let scheme_end = "file".len() as u32;
683            let path_start = "file://".len();
684            let remaining = self.parse_path(SchemeType::File, &mut false, path_start, input);
685            let (query_start, fragment_start) =
686                self.parse_query_and_fragment(SchemeType::File, scheme_end, remaining)?;
687            let path_start = path_start as u32;
688            Ok(Url {
689                serialization: self.serialization,
690                scheme_end,
691                username_end: path_start,
692                host_start: path_start,
693                host_end: path_start,
694                host: HostInternal::None,
695                port: None,
696                path_start,
697                query_start,
698                fragment_start,
699            })
700        }
701    }
702
703    fn parse_relative(
704        mut self,
705        input: Input<'_>,
706        scheme_type: SchemeType,
707        base_url: &Url,
708    ) -> ParseResult<Url> {
709        // relative state
710        if true {
    if !self.serialization.is_empty() {
        ::core::panicking::panic("assertion failed: self.serialization.is_empty()")
    };
};debug_assert!(self.serialization.is_empty());
711        let (first_char, input_after_first_char) = input.split_first();
712        match first_char {
713            None => {
714                // Copy everything except the fragment
715                let before_fragment = match base_url.fragment_start {
716                    Some(i) => &base_url.serialization[..i as usize],
717                    None => &*base_url.serialization,
718                };
719                self.serialization.push_str(before_fragment);
720                Ok(Url {
721                    serialization: self.serialization,
722                    fragment_start: None,
723                    ..*base_url
724                })
725            }
726            Some('?') => {
727                // Copy everything up to the query string
728                let before_query = match (base_url.query_start, base_url.fragment_start) {
729                    (None, None) => &*base_url.serialization,
730                    (Some(i), _) | (None, Some(i)) => base_url.slice(..i),
731                };
732                self.serialization.push_str(before_query);
733                let (query_start, fragment_start) =
734                    self.parse_query_and_fragment(scheme_type, base_url.scheme_end, input)?;
735                Ok(Url {
736                    serialization: self.serialization,
737                    query_start,
738                    fragment_start,
739                    ..*base_url
740                })
741            }
742            Some('#') => self.fragment_only(base_url, input),
743            Some('/') | Some('\\') => {
744                let (slashes_count, remaining) = input.count_matching(|c| #[allow(non_exhaustive_omitted_patterns)] match c {
    '/' | '\\' => true,
    _ => false,
}matches!(c, '/' | '\\'));
745                if slashes_count >= 2 {
746                    self.log_violation_if(SyntaxViolation::ExpectedDoubleSlash, || {
747                        input
748                            .clone()
749                            .take_while(|&c| #[allow(non_exhaustive_omitted_patterns)] match c {
    '/' | '\\' => true,
    _ => false,
}matches!(c, '/' | '\\'))
750                            .collect::<String>()
751                            != "//"
752                    });
753                    let scheme_end = base_url.scheme_end;
754                    if true {
    if !(base_url.byte_at(scheme_end) == b':') {
        ::core::panicking::panic("assertion failed: base_url.byte_at(scheme_end) == b\':\'")
    };
};debug_assert!(base_url.byte_at(scheme_end) == b':');
755                    self.serialization
756                        .push_str(base_url.slice(..scheme_end + 1));
757                    if let Some(after_prefix) = input.split_prefix("//") {
758                        return self.after_double_slash(after_prefix, scheme_type, scheme_end);
759                    }
760                    return self.after_double_slash(remaining, scheme_type, scheme_end);
761                }
762                let path_start = base_url.path_start;
763                self.serialization.push_str(base_url.slice(..path_start));
764                self.serialization.push('/');
765                let remaining = self.parse_path(
766                    scheme_type,
767                    &mut true,
768                    path_start as usize,
769                    input_after_first_char,
770                );
771                self.with_query_and_fragment(
772                    scheme_type,
773                    base_url.scheme_end,
774                    base_url.username_end,
775                    base_url.host_start,
776                    base_url.host_end,
777                    base_url.host,
778                    base_url.port,
779                    base_url.path_start,
780                    remaining,
781                )
782            }
783            _ => {
784                let before_query = match (base_url.query_start, base_url.fragment_start) {
785                    (None, None) => &*base_url.serialization,
786                    (Some(i), _) | (None, Some(i)) => base_url.slice(..i),
787                };
788                self.serialization.push_str(before_query);
789                // FIXME spec says just "remove last entry", not the "pop" algorithm
790                self.pop_path(scheme_type, base_url.path_start as usize);
791                // A special url always has a path.
792                // A path always starts with '/'
793                if self.serialization.len() == base_url.path_start as usize
794                    && (SchemeType::from(base_url.scheme()).is_special() || !input.is_empty())
795                {
796                    self.serialization.push('/');
797                }
798                let remaining = match input.split_first() {
799                    (Some('/'), remaining) => self.parse_path(
800                        scheme_type,
801                        &mut true,
802                        base_url.path_start as usize,
803                        remaining,
804                    ),
805                    _ => {
806                        self.parse_path(scheme_type, &mut true, base_url.path_start as usize, input)
807                    }
808                };
809                self.with_query_and_fragment(
810                    scheme_type,
811                    base_url.scheme_end,
812                    base_url.username_end,
813                    base_url.host_start,
814                    base_url.host_end,
815                    base_url.host,
816                    base_url.port,
817                    base_url.path_start,
818                    remaining,
819                )
820            }
821        }
822    }
823
824    fn after_double_slash(
825        mut self,
826        input: Input<'_>,
827        scheme_type: SchemeType,
828        scheme_end: u32,
829    ) -> ParseResult<Url> {
830        self.serialization.push('/');
831        self.serialization.push('/');
832        // authority state
833        let before_authority = self.serialization.len();
834        let (username_end, remaining) = self.parse_userinfo(input, scheme_type)?;
835        let has_authority = before_authority != self.serialization.len();
836        // host state
837        let host_start = to_u32(self.serialization.len())?;
838        let (host_end, host, port, remaining) =
839            self.parse_host_and_port(remaining, scheme_end, scheme_type)?;
840        if host == HostInternal::None && has_authority {
841            return Err(ParseError::EmptyHost);
842        }
843        // path state
844        let path_start = to_u32(self.serialization.len())?;
845        let remaining = self.parse_path_start(scheme_type, &mut true, remaining);
846        self.with_query_and_fragment(
847            scheme_type,
848            scheme_end,
849            username_end,
850            host_start,
851            host_end,
852            host,
853            port,
854            path_start,
855            remaining,
856        )
857    }
858
859    /// Return (username_end, remaining)
860    fn parse_userinfo<'i>(
861        &mut self,
862        mut input: Input<'i>,
863        scheme_type: SchemeType,
864    ) -> ParseResult<(u32, Input<'i>)> {
865        let mut last_at = None;
866        let mut remaining = input.clone();
867        let mut char_count = 0;
868        while let Some(c) = remaining.next() {
869            match c {
870                '@' => {
871                    if last_at.is_some() {
872                        self.log_violation(SyntaxViolation::UnencodedAtSign)
873                    } else {
874                        self.log_violation(SyntaxViolation::EmbeddedCredentials)
875                    }
876                    last_at = Some((char_count, remaining.clone()))
877                }
878                '/' | '?' | '#' => break,
879                '\\' if scheme_type.is_special() => break,
880                _ => (),
881            }
882            char_count += 1;
883        }
884        let (mut userinfo_char_count, remaining) = match last_at {
885            None => return Ok((to_u32(self.serialization.len())?, input)),
886            Some((0, remaining)) => {
887                // Otherwise, if one of the following is true
888                // c is the EOF code point, U+002F (/), U+003F (?), or U+0023 (#)
889                // url is special and c is U+005C (\)
890                // If @ flag is set and buffer is the empty string, validation error, return failure.
891                if let (Some(c), _) = remaining.split_first() {
892                    if c == '/' || c == '?' || c == '#' || (scheme_type.is_special() && c == '\\') {
893                        return Err(ParseError::EmptyHost);
894                    }
895                }
896                return Ok((to_u32(self.serialization.len())?, remaining));
897            }
898            Some(x) => x,
899        };
900
901        let mut username_end = None;
902        let mut has_password = false;
903        let mut has_username = false;
904        while userinfo_char_count > 0 {
905            let (c, utf8_c) = input.next_utf8().unwrap();
906            userinfo_char_count -= 1;
907            if c == ':' && username_end.is_none() {
908                // Start parsing password
909                username_end = Some(to_u32(self.serialization.len())?);
910                // We don't add a colon if the password is empty
911                if userinfo_char_count > 0 {
912                    self.serialization.push(':');
913                    has_password = true;
914                }
915            } else {
916                if !has_password {
917                    has_username = true;
918                }
919                self.check_url_code_point(c, &input);
920                self.serialization
921                    .extend(utf8_percent_encode(utf8_c, USERINFO));
922            }
923        }
924        let username_end = match username_end {
925            Some(i) => i,
926            None => to_u32(self.serialization.len())?,
927        };
928        if has_username || has_password {
929            self.serialization.push('@');
930        }
931        Ok((username_end, remaining))
932    }
933
934    fn parse_host_and_port<'i>(
935        &mut self,
936        input: Input<'i>,
937        scheme_end: u32,
938        scheme_type: SchemeType,
939    ) -> ParseResult<(u32, HostInternal, Option<u16>, Input<'i>)> {
940        let (host, remaining) = Parser::parse_host(input, scheme_type)?;
941        (&mut self.serialization).write_fmt(format_args!("{0}", host))write!(&mut self.serialization, "{host}").unwrap();
942        let host_end = to_u32(self.serialization.len())?;
943        if let Host::Domain(h) = &host {
944            if h.is_empty() {
945                // Port with an empty host
946                if remaining.starts_with(":") {
947                    return Err(ParseError::EmptyHost);
948                }
949                if scheme_type.is_special() {
950                    return Err(ParseError::EmptyHost);
951                }
952            }
953        };
954
955        let (port, remaining) = if let Some(remaining) = remaining.split_prefix(':') {
956            let scheme = || default_port(&self.serialization[..scheme_end as usize]);
957            let (port, remaining) = Parser::parse_port(remaining, scheme, self.context)?;
958            if let Some(port) = port {
959                self.serialization.push(':');
960                let mut buffer = [0u8; 5];
961                let port_str = fast_u16_to_str(&mut buffer, port);
962                self.serialization.push_str(port_str);
963            }
964            (port, remaining)
965        } else {
966            (None, remaining)
967        };
968        Ok((host_end, host.into(), port, remaining))
969    }
970
971    pub fn parse_host(
972        mut input: Input<'_>,
973        scheme_type: SchemeType,
974    ) -> ParseResult<(Host<Cow<'_, str>>, Input<'_>)> {
975        if scheme_type.is_file() {
976            return Parser::get_file_host(input);
977        }
978        // Undo the Input abstraction here to avoid allocating in the common case
979        // where the host part of the input does not contain any tab or newline
980        let input_str = input.chars.as_str();
981        let mut inside_square_brackets = false;
982        let mut has_ignored_chars = false;
983        let mut non_ignored_chars = 0;
984        let mut bytes = 0;
985        for c in input_str.chars() {
986            match c {
987                ':' if !inside_square_brackets => break,
988                '\\' if scheme_type.is_special() => break,
989                '/' | '?' | '#' => break,
990                '\t' | '\n' | '\r'ascii_tab_or_new_line_pattern!() => {
991                    has_ignored_chars = true;
992                }
993                '[' => {
994                    inside_square_brackets = true;
995                    non_ignored_chars += 1
996                }
997                ']' => {
998                    inside_square_brackets = false;
999                    non_ignored_chars += 1
1000                }
1001                _ => non_ignored_chars += 1,
1002            }
1003            bytes += c.len_utf8();
1004        }
1005        let host_str;
1006        {
1007            let host_input = input.by_ref().take(non_ignored_chars);
1008            if has_ignored_chars {
1009                host_str = Cow::Owned(host_input.collect());
1010            } else {
1011                for _ in host_input {}
1012                host_str = Cow::Borrowed(&input_str[..bytes]);
1013            }
1014        }
1015        if scheme_type == SchemeType::SpecialNotFile && host_str.is_empty() {
1016            return Err(ParseError::EmptyHost);
1017        }
1018        if !scheme_type.is_special() {
1019            let host = Host::parse_opaque_cow(host_str)?;
1020            return Ok((host, input));
1021        }
1022        let host = Host::parse_cow(host_str)?;
1023        Ok((host, input))
1024    }
1025
1026    fn get_file_host(input: Input<'_>) -> ParseResult<(Host<Cow<'_, str>>, Input<'_>)> {
1027        let (_, host_str, remaining) = Parser::file_host(input)?;
1028        let host = match Host::parse(&host_str)? {
1029            Host::Domain(ref d) if d == "localhost" => Host::Domain(Cow::Borrowed("")),
1030            Host::Domain(s) => Host::Domain(Cow::Owned(s)),
1031            Host::Ipv4(ip) => Host::Ipv4(ip),
1032            Host::Ipv6(ip) => Host::Ipv6(ip),
1033        };
1034        Ok((host, remaining))
1035    }
1036
1037    fn parse_file_host<'i>(
1038        &mut self,
1039        input: Input<'i>,
1040    ) -> ParseResult<(bool, HostInternal, Input<'i>)> {
1041        let has_host;
1042        let (_, host_str, remaining) = Parser::file_host(input)?;
1043        let host = if host_str.is_empty() {
1044            has_host = false;
1045            HostInternal::None
1046        } else {
1047            match Host::parse_cow(host_str)? {
1048                Host::Domain(ref d) if d == "localhost" => {
1049                    has_host = false;
1050                    HostInternal::None
1051                }
1052                host => {
1053                    (&mut self.serialization).write_fmt(format_args!("{0}", host))write!(&mut self.serialization, "{host}").unwrap();
1054                    has_host = true;
1055                    host.into()
1056                }
1057            }
1058        };
1059        Ok((has_host, host, remaining))
1060    }
1061
1062    pub fn file_host(input: Input<'_>) -> ParseResult<(bool, Cow<'_, str>, Input<'_>)> {
1063        // Undo the Input abstraction here to avoid allocating in the common case
1064        // where the host part of the input does not contain any tab or newline
1065        let input_str = input.chars.as_str();
1066        let mut has_ignored_chars = false;
1067        let mut non_ignored_chars = 0;
1068        let mut bytes = 0;
1069        for c in input_str.chars() {
1070            match c {
1071                '/' | '\\' | '?' | '#' => break,
1072                '\t' | '\n' | '\r'ascii_tab_or_new_line_pattern!() => has_ignored_chars = true,
1073                _ => non_ignored_chars += 1,
1074            }
1075            bytes += c.len_utf8();
1076        }
1077        let host_str;
1078        let mut remaining = input.clone();
1079        {
1080            let host_input = remaining.by_ref().take(non_ignored_chars);
1081            if has_ignored_chars {
1082                host_str = Cow::Owned(host_input.collect());
1083            } else {
1084                for _ in host_input {}
1085                host_str = Cow::Borrowed(&input_str[..bytes]);
1086            }
1087        }
1088        if is_windows_drive_letter(&host_str) {
1089            return Ok((false, "".into(), input));
1090        }
1091        Ok((true, host_str, remaining))
1092    }
1093
1094    pub fn parse_port<P>(
1095        mut input: Input<'_>,
1096        default_port: P,
1097        context: Context,
1098    ) -> ParseResult<(Option<u16>, Input<'_>)>
1099    where
1100        P: Fn() -> Option<u16>,
1101    {
1102        let mut port: u32 = 0;
1103        let mut has_any_digit = false;
1104        while let (Some(c), remaining) = input.split_first() {
1105            if let Some(digit) = c.to_digit(10) {
1106                port = port * 10 + digit;
1107                if port > u16::MAX as u32 {
1108                    return Err(ParseError::InvalidPort);
1109                }
1110                has_any_digit = true;
1111            } else if context == Context::UrlParser
1112                && !#[allow(non_exhaustive_omitted_patterns)] match c {
    '/' | '?' | '#' => true,
    _ => false,
}matches!(c, '/' | '?' | '#')
1113                && !(c == '\\' && default_port().is_some())
1114            {
1115                return Err(ParseError::InvalidPort);
1116            } else {
1117                break;
1118            }
1119            input = remaining;
1120        }
1121
1122        if !has_any_digit && context == Context::Setter && !input.is_empty() {
1123            return Err(ParseError::InvalidPort);
1124        }
1125
1126        let mut opt_port = Some(port as u16);
1127        if !has_any_digit || opt_port == default_port() {
1128            opt_port = None;
1129        }
1130        Ok((opt_port, input))
1131    }
1132
1133    pub fn parse_path_start<'i>(
1134        &mut self,
1135        scheme_type: SchemeType,
1136        has_host: &mut bool,
1137        input: Input<'i>,
1138    ) -> Input<'i> {
1139        let path_start = self.serialization.len();
1140        let (maybe_c, remaining) = input.split_first();
1141        // If url is special, then:
1142        if scheme_type.is_special() {
1143            if maybe_c == Some('\\') {
1144                // If c is U+005C (\), validation error.
1145                self.log_violation(SyntaxViolation::Backslash);
1146            }
1147            // A special URL always has a non-empty path.
1148            if !self.serialization.ends_with('/') {
1149                self.serialization.push('/');
1150                // We have already made sure the forward slash is present.
1151                if maybe_c == Some('/') || maybe_c == Some('\\') {
1152                    return self.parse_path(scheme_type, has_host, path_start, remaining);
1153                }
1154            }
1155            return self.parse_path(scheme_type, has_host, path_start, input);
1156        } else if maybe_c == Some('?') || maybe_c == Some('#') {
1157            // Otherwise, if state override is not given and c is U+003F (?),
1158            // set url’s query to the empty string and state to query state.
1159            // Otherwise, if state override is not given and c is U+0023 (#),
1160            // set url’s fragment to the empty string and state to fragment state.
1161            // The query and path states will be handled by the caller.
1162            return input;
1163        }
1164
1165        if maybe_c.is_some() && maybe_c != Some('/') {
1166            self.serialization.push('/');
1167        }
1168        // Otherwise, if c is not the EOF code point:
1169        self.parse_path(scheme_type, has_host, path_start, input)
1170    }
1171
1172    pub fn parse_path<'i>(
1173        &mut self,
1174        scheme_type: SchemeType,
1175        has_host: &mut bool,
1176        path_start: usize,
1177        mut input: Input<'i>,
1178    ) -> Input<'i> {
1179        // it's much faster to call utf8_percent_encode in bulk
1180        fn push_pending(
1181            serialization: &mut String,
1182            start_str: &str,
1183            remaining_len: usize,
1184            context: Context,
1185            scheme_type: SchemeType,
1186        ) {
1187            let text = &start_str[..start_str.len() - remaining_len];
1188            if text.is_empty() {
1189                return;
1190            }
1191            if context == Context::PathSegmentSetter {
1192                if scheme_type.is_special() {
1193                    serialization.extend(utf8_percent_encode(text, SPECIAL_PATH_SEGMENT));
1194                } else {
1195                    serialization.extend(utf8_percent_encode(text, PATH_SEGMENT));
1196                }
1197            } else {
1198                serialization.extend(utf8_percent_encode(text, PATH));
1199            }
1200        }
1201
1202        // Relative path state
1203        loop {
1204            let mut segment_start = self.serialization.len();
1205            let mut ends_with_slash = false;
1206            let mut start_str = input.chars.as_str();
1207            loop {
1208                let input_before_c = input.clone();
1209                // bypass input.next() and manually handle ascii_tab_or_new_line
1210                // in order to encode string slices in bulk
1211                let c = if let Some(c) = input.chars.next() {
1212                    c
1213                } else {
1214                    push_pending(
1215                        &mut self.serialization,
1216                        start_str,
1217                        0,
1218                        self.context,
1219                        scheme_type,
1220                    );
1221                    break;
1222                };
1223                match c {
1224                    '\t' | '\n' | '\r'ascii_tab_or_new_line_pattern!() => {
1225                        push_pending(
1226                            &mut self.serialization,
1227                            start_str,
1228                            input_before_c.chars.as_str().len(),
1229                            self.context,
1230                            scheme_type,
1231                        );
1232                        start_str = input.chars.as_str();
1233                    }
1234                    '/' if self.context != Context::PathSegmentSetter => {
1235                        push_pending(
1236                            &mut self.serialization,
1237                            start_str,
1238                            input_before_c.chars.as_str().len(),
1239                            self.context,
1240                            scheme_type,
1241                        );
1242                        self.serialization.push(c);
1243                        ends_with_slash = true;
1244                        break;
1245                    }
1246                    '\\' if self.context != Context::PathSegmentSetter
1247                        && scheme_type.is_special() =>
1248                    {
1249                        push_pending(
1250                            &mut self.serialization,
1251                            start_str,
1252                            input_before_c.chars.as_str().len(),
1253                            self.context,
1254                            scheme_type,
1255                        );
1256                        self.log_violation(SyntaxViolation::Backslash);
1257                        self.serialization.push('/');
1258                        ends_with_slash = true;
1259                        break;
1260                    }
1261                    '?' | '#' if self.context == Context::UrlParser => {
1262                        push_pending(
1263                            &mut self.serialization,
1264                            start_str,
1265                            input_before_c.chars.as_str().len(),
1266                            self.context,
1267                            scheme_type,
1268                        );
1269                        input = input_before_c;
1270                        break;
1271                    }
1272                    _ => {
1273                        self.check_url_code_point(c, &input);
1274                        if scheme_type.is_file()
1275                            && self.serialization.len() > path_start
1276                            && is_normalized_windows_drive_letter(
1277                                &self.serialization[path_start + 1..],
1278                            )
1279                        {
1280                            push_pending(
1281                                &mut self.serialization,
1282                                start_str,
1283                                input_before_c.chars.as_str().len(),
1284                                self.context,
1285                                scheme_type,
1286                            );
1287                            start_str = input_before_c.chars.as_str();
1288                            self.serialization.push('/');
1289                            segment_start += 1;
1290                        }
1291                    }
1292                }
1293            }
1294
1295            let segment_before_slash = if ends_with_slash {
1296                &self.serialization[segment_start..self.serialization.len() - 1]
1297            } else {
1298                &self.serialization[segment_start..self.serialization.len()]
1299            };
1300            match segment_before_slash {
1301                // If buffer is a double-dot path segment, shorten url’s path,
1302                ".." | "%2e%2e" | "%2e%2E" | "%2E%2e" | "%2E%2E" | "%2e." | "%2E." | ".%2e"
1303                | ".%2E" => {
1304                    if true {
    if !(self.serialization.as_bytes()[segment_start - 1] == b'/') {
        ::core::panicking::panic("assertion failed: self.serialization.as_bytes()[segment_start - 1] == b\'/\'")
    };
};debug_assert!(self.serialization.as_bytes()[segment_start - 1] == b'/');
1305                    self.serialization.truncate(segment_start);
1306                    if self.serialization.ends_with('/')
1307                        && Parser::last_slash_can_be_removed(&self.serialization, path_start)
1308                    {
1309                        self.serialization.pop();
1310                    }
1311                    self.shorten_path(scheme_type, path_start);
1312
1313                    // and then if neither c is U+002F (/), nor url is special and c is U+005C (\), append the empty string to url’s path.
1314                    if ends_with_slash && !self.serialization.ends_with('/') {
1315                        self.serialization.push('/');
1316                    }
1317                }
1318                // Otherwise, if buffer is a single-dot path segment and if neither c is U+002F (/),
1319                // nor url is special and c is U+005C (\), append the empty string to url’s path.
1320                "." | "%2e" | "%2E" => {
1321                    self.serialization.truncate(segment_start);
1322                    if !self.serialization.ends_with('/') {
1323                        self.serialization.push('/');
1324                    }
1325                }
1326                _ => {
1327                    // If url’s scheme is "file", url’s path is empty, and buffer is a Windows drive letter, then
1328                    if scheme_type.is_file()
1329                        && segment_start == path_start + 1
1330                        && is_windows_drive_letter(segment_before_slash)
1331                    {
1332                        // Replace the second code point in buffer with U+003A (:).
1333                        if let Some(c) = segment_before_slash.chars().next() {
1334                            self.serialization.truncate(segment_start);
1335                            self.serialization.push(c);
1336                            self.serialization.push(':');
1337                            if ends_with_slash {
1338                                self.serialization.push('/');
1339                            }
1340                        }
1341                        // If url’s host is neither the empty string nor null,
1342                        // validation error, set url’s host to the empty string.
1343                        if *has_host {
1344                            self.log_violation(SyntaxViolation::FileWithHostAndWindowsDrive);
1345                            *has_host = false; // FIXME account for this in callers
1346                        }
1347                    }
1348                }
1349            }
1350            if !ends_with_slash {
1351                break;
1352            }
1353        }
1354        if scheme_type.is_file() {
1355            // while url’s path’s size is greater than 1
1356            // and url’s path[0] is the empty string,
1357            // validation error, remove the first item from url’s path.
1358            //FIXME: log violation
1359            let path = self.serialization.split_off(path_start);
1360            self.serialization.push('/');
1361            self.serialization.push_str(path.trim_start_matches('/'));
1362        }
1363
1364        input
1365    }
1366
1367    fn last_slash_can_be_removed(serialization: &str, path_start: usize) -> bool {
1368        let last_slash = serialization.len() - 1;
1369        // Do not remove the root slash, or the slash that ends `file://`.
1370        // The path is still empty there when a setter parses into it.
1371        if last_slash <= path_start {
1372            return false;
1373        }
1374        // The slash before the last one is searched for in the path only.
1375        // Parsing is quadratic when every double-dot segment at the root
1376        // searches the scheme and the authority too.
1377        match serialization[path_start..last_slash].rfind('/') {
1378            // Do not remove a windows drive letter slash
1379            Some(slash) => {
1380                !path_starts_with_windows_drive_letter(&serialization[path_start + slash..])
1381            }
1382            None => false,
1383        }
1384    }
1385
1386    /// https://url.spec.whatwg.org/#shorten-a-urls-path
1387    fn shorten_path(&mut self, scheme_type: SchemeType, path_start: usize) {
1388        // If path is empty, then return.
1389        if self.serialization.len() == path_start {
1390            return;
1391        }
1392        // If url’s scheme is "file", path’s size is 1, and path[0] is a normalized Windows drive letter, then return.
1393        if scheme_type.is_file()
1394            && is_normalized_windows_drive_letter(&self.serialization[path_start..])
1395        {
1396            return;
1397        }
1398        // Remove path’s last item.
1399        self.pop_path(scheme_type, path_start);
1400    }
1401
1402    /// https://url.spec.whatwg.org/#pop-a-urls-path
1403    fn pop_path(&mut self, scheme_type: SchemeType, path_start: usize) {
1404        if self.serialization.len() > path_start {
1405            let slash_position = self.serialization[path_start..].rfind('/').unwrap();
1406            // + 1 since rfind returns the position before the slash.
1407            let segment_start = path_start + slash_position + 1;
1408            // Don’t pop a Windows drive letter
1409            if !(scheme_type.is_file()
1410                && is_normalized_windows_drive_letter(&self.serialization[segment_start..]))
1411            {
1412                self.serialization.truncate(segment_start);
1413            }
1414        }
1415    }
1416
1417    pub fn parse_cannot_be_a_base_path<'i>(&mut self, mut input: Input<'i>) -> Input<'i> {
1418        loop {
1419            let input_before_c = input.clone();
1420            match input.next_utf8() {
1421                Some(('?', _)) | Some(('#', _)) if self.context == Context::UrlParser => {
1422                    return input_before_c
1423                }
1424                Some((c, utf8_c)) => {
1425                    self.check_url_code_point(c, &input);
1426                    self.serialization
1427                        .extend(utf8_percent_encode(utf8_c, CONTROLS));
1428                }
1429                None => return input,
1430            }
1431        }
1432    }
1433
1434    #[allow(clippy::too_many_arguments)]
1435    fn with_query_and_fragment(
1436        mut self,
1437        scheme_type: SchemeType,
1438        scheme_end: u32,
1439        username_end: u32,
1440        host_start: u32,
1441        host_end: u32,
1442        host: HostInternal,
1443        port: Option<u16>,
1444        mut path_start: u32,
1445        remaining: Input<'_>,
1446    ) -> ParseResult<Url> {
1447        // Special case for anarchist URL's with a leading empty path segment
1448        // This prevents web+demo:/.//not-a-host/ or web+demo:/path/..//not-a-host/,
1449        // when parsed and then serialized, from ending up as web+demo://not-a-host/
1450        // (they end up as web+demo:/.//not-a-host/).
1451        //
1452        // If url’s host is null, url does not have an opaque path,
1453        // url’s path’s size is greater than 1, and url’s path[0] is the empty string,
1454        // then append U+002F (/) followed by U+002E (.) to output.
1455        let scheme_end_as_usize = scheme_end as usize;
1456        let path_start_as_usize = path_start as usize;
1457        if path_start_as_usize == scheme_end_as_usize + 1 {
1458            // Anarchist URL
1459            if self.serialization[path_start_as_usize..].starts_with("//") {
1460                // Case 1: The base URL did not have an empty path segment, but the resulting one does
1461                // Insert the "/." prefix
1462                self.serialization.insert_str(path_start_as_usize, "/.");
1463                path_start += 2;
1464            }
1465            if !!self.serialization[scheme_end_as_usize..].starts_with("://") {
    ::core::panicking::panic("assertion failed: !self.serialization[scheme_end_as_usize..].starts_with(\"://\")")
};assert!(!self.serialization[scheme_end_as_usize..].starts_with("://"));
1466        } else if path_start_as_usize == scheme_end_as_usize + 3
1467            && &self.serialization[scheme_end_as_usize..path_start_as_usize] == ":/."
1468        {
1469            // Anarchist URL with leading empty path segment
1470            // The base URL has a "/." between the host and the path
1471            {
    match (&self.serialization.as_bytes()[path_start_as_usize], &b'/') {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(self.serialization.as_bytes()[path_start_as_usize], b'/');
1472            if self
1473                .serialization
1474                .as_bytes()
1475                .get(path_start_as_usize + 1)
1476                .copied()
1477                != Some(b'/')
1478            {
1479                // Case 2: The base URL had an empty path segment, but the resulting one does not
1480                // Remove the "/." prefix
1481                self.serialization
1482                    .replace_range(scheme_end_as_usize..path_start_as_usize, ":");
1483                path_start -= 2;
1484            }
1485            if !!self.serialization[scheme_end_as_usize..].starts_with("://") {
    ::core::panicking::panic("assertion failed: !self.serialization[scheme_end_as_usize..].starts_with(\"://\")")
};assert!(!self.serialization[scheme_end_as_usize..].starts_with("://"));
1486        }
1487
1488        let (query_start, fragment_start) =
1489            self.parse_query_and_fragment(scheme_type, scheme_end, remaining)?;
1490        Ok(Url {
1491            serialization: self.serialization,
1492            scheme_end,
1493            username_end,
1494            host_start,
1495            host_end,
1496            host,
1497            port,
1498            path_start,
1499            query_start,
1500            fragment_start,
1501        })
1502    }
1503
1504    /// Return (query_start, fragment_start)
1505    fn parse_query_and_fragment(
1506        &mut self,
1507        scheme_type: SchemeType,
1508        scheme_end: u32,
1509        mut input: Input<'_>,
1510    ) -> ParseResult<(Option<u32>, Option<u32>)> {
1511        let mut query_start = None;
1512        match input.next() {
1513            Some('#') => {}
1514            Some('?') => {
1515                query_start = Some(to_u32(self.serialization.len())?);
1516                self.serialization.push('?');
1517                let remaining = self.parse_query(scheme_type, scheme_end, input);
1518                if let Some(remaining) = remaining {
1519                    input = remaining
1520                } else {
1521                    return Ok((query_start, None));
1522                }
1523            }
1524            None => return Ok((None, None)),
1525            _ => ::core::panicking::panic("Programming error. parse_query_and_fragment() called without ? or #")panic!("Programming error. parse_query_and_fragment() called without ? or #"),
1526        }
1527
1528        let fragment_start = to_u32(self.serialization.len())?;
1529        self.serialization.push('#');
1530        self.parse_fragment(input);
1531        Ok((query_start, Some(fragment_start)))
1532    }
1533
1534    pub fn parse_query<'i>(
1535        &mut self,
1536        scheme_type: SchemeType,
1537        scheme_end: u32,
1538        input: Input<'i>,
1539    ) -> Option<Input<'i>> {
1540        struct QueryPartIter<'i, 'p> {
1541            is_url_parser: bool,
1542            input: Input<'i>,
1543            violation_fn: Option<&'p dyn Fn(SyntaxViolation)>,
1544        }
1545
1546        impl<'i> Iterator for QueryPartIter<'i, '_> {
1547            type Item = (&'i str, bool);
1548
1549            fn next(&mut self) -> Option<Self::Item> {
1550                let start = self.input.chars.as_str();
1551                // bypass self.input.next() in order to get string slices
1552                // which are faster to operate on
1553                while let Some(c) = self.input.chars.next() {
1554                    match c {
1555                        '\t' | '\n' | '\r'ascii_tab_or_new_line_pattern!() => {
1556                            return Some((
1557                                &start[..start.len() - self.input.chars.as_str().len() - 1],
1558                                false,
1559                            ));
1560                        }
1561                        '#' if self.is_url_parser => {
1562                            return Some((
1563                                &start[..start.len() - self.input.chars.as_str().len() - 1],
1564                                true,
1565                            ));
1566                        }
1567                        c => {
1568                            if let Some(vfn) = &self.violation_fn {
1569                                check_url_code_point(vfn, c, &self.input);
1570                            }
1571                        }
1572                    }
1573                }
1574                if start.is_empty() {
1575                    None
1576                } else {
1577                    Some((start, false))
1578                }
1579            }
1580        }
1581
1582        let mut part_iter = QueryPartIter {
1583            is_url_parser: self.context == Context::UrlParser,
1584            input,
1585            violation_fn: self.violation_fn,
1586        };
1587        let set = if scheme_type.is_special() {
1588            SPECIAL_QUERY
1589        } else {
1590            QUERY
1591        };
1592        let query_encoding_override = self.query_encoding_override.filter(|_| {
1593            #[allow(non_exhaustive_omitted_patterns)] match &self.serialization[..scheme_end
                    as usize] {
    "http" | "https" | "file" | "ftp" => true,
    _ => false,
}matches!(
1594                &self.serialization[..scheme_end as usize],
1595                "http" | "https" | "file" | "ftp"
1596            )
1597        });
1598
1599        while let Some((part, is_finished)) = part_iter.next() {
1600            match query_encoding_override {
1601                // slightly faster to be repetitive and not convert text to Cow
1602                Some(o) => self.serialization.extend(percent_encode(&o(part), set)),
1603                None => self
1604                    .serialization
1605                    .extend(percent_encode(part.as_bytes(), set)),
1606            }
1607            if is_finished {
1608                return Some(part_iter.input);
1609            }
1610        }
1611
1612        None
1613    }
1614
1615    fn fragment_only(mut self, base_url: &Url, mut input: Input<'_>) -> ParseResult<Url> {
1616        let before_fragment = match base_url.fragment_start {
1617            Some(i) => base_url.slice(..i),
1618            None => &*base_url.serialization,
1619        };
1620        if true {
    if !self.serialization.is_empty() {
        ::core::panicking::panic("assertion failed: self.serialization.is_empty()")
    };
};debug_assert!(self.serialization.is_empty());
1621        self.serialization
1622            .reserve(before_fragment.len() + input.chars.as_str().len());
1623        self.serialization.push_str(before_fragment);
1624        self.serialization.push('#');
1625        let next = input.next();
1626        if true {
    if !(next == Some('#')) {
        ::core::panicking::panic("assertion failed: next == Some(\'#\')")
    };
};debug_assert!(next == Some('#'));
1627        self.parse_fragment(input);
1628        Ok(Url {
1629            serialization: self.serialization,
1630            fragment_start: Some(to_u32(before_fragment.len())?),
1631            ..*base_url
1632        })
1633    }
1634
1635    pub fn parse_fragment(&mut self, input: Input<'_>) {
1636        struct FragmentPartIter<'i, 'p> {
1637            input: Input<'i>,
1638            violation_fn: Option<&'p dyn Fn(SyntaxViolation)>,
1639        }
1640
1641        impl<'i> Iterator for FragmentPartIter<'i, '_> {
1642            type Item = &'i str;
1643
1644            fn next(&mut self) -> Option<Self::Item> {
1645                let start = self.input.chars.as_str();
1646                // bypass self.input.next() in order to get string slices
1647                // which are faster to operate on
1648                while let Some(c) = self.input.chars.next() {
1649                    match c {
1650                        '\t' | '\n' | '\r'ascii_tab_or_new_line_pattern!() => {
1651                            return Some(
1652                                &start[..start.len() - self.input.chars.as_str().len() - 1],
1653                            );
1654                        }
1655                        '\0' => {
1656                            if let Some(vfn) = &self.violation_fn {
1657                                vfn(SyntaxViolation::NullInFragment);
1658                            }
1659                        }
1660                        c => {
1661                            if let Some(vfn) = &self.violation_fn {
1662                                check_url_code_point(vfn, c, &self.input);
1663                            }
1664                        }
1665                    }
1666                }
1667                if start.is_empty() {
1668                    None
1669                } else {
1670                    Some(start)
1671                }
1672            }
1673        }
1674
1675        let part_iter = FragmentPartIter {
1676            input,
1677            violation_fn: self.violation_fn,
1678        };
1679
1680        for part in part_iter {
1681            self.serialization
1682                .extend(utf8_percent_encode(part, FRAGMENT));
1683        }
1684    }
1685
1686    #[inline]
1687    fn check_url_code_point(&self, c: char, input: &Input<'_>) {
1688        if let Some(vfn) = self.violation_fn {
1689            check_url_code_point(vfn, c, input)
1690        }
1691    }
1692}
1693
1694fn check_url_code_point(vfn: &dyn Fn(SyntaxViolation), c: char, input: &Input<'_>) {
1695    if c == '%' {
1696        let mut input = input.clone();
1697        if !#[allow(non_exhaustive_omitted_patterns)] match (input.next(), input.next()) {
    (Some(a), Some(b)) if a.is_ascii_hexdigit() && b.is_ascii_hexdigit() =>
        true,
    _ => false,
}matches!((input.next(), input.next()), (Some(a), Some(b))
1698                             if a.is_ascii_hexdigit() && b.is_ascii_hexdigit())
1699        {
1700            vfn(SyntaxViolation::PercentDecode)
1701        }
1702    } else if !is_url_code_point(c) {
1703        vfn(SyntaxViolation::NonUrlCodePoint)
1704    }
1705}
1706
1707// Non URL code points:
1708// U+0000 to U+0020 (space)
1709// " # % < > [ \ ] ^ ` { | }
1710// U+007F to U+009F
1711// surrogates
1712// U+FDD0 to U+FDEF
1713// Last two of each plane: U+__FFFE to U+__FFFF for __ in 00 to 10 hex
1714#[inline]
1715fn is_url_code_point(c: char) -> bool {
1716    #[allow(non_exhaustive_omitted_patterns)] match c {
    'a'..='z' | 'A'..='Z' | '0'..='9' | '!' | '$' | '&' | '\'' | '(' | ')' |
        '*' | '+' | ',' | '-' | '.' | '/' | ':' | ';' | '=' | '?' | '@' | '_'
        | '~' | '\u{A0}'..='\u{D7FF}' | '\u{E000}'..='\u{FDCF}' |
        '\u{FDF0}'..='\u{FFFD}' | '\u{10000}'..='\u{1FFFD}' |
        '\u{20000}'..='\u{2FFFD}' | '\u{30000}'..='\u{3FFFD}' |
        '\u{40000}'..='\u{4FFFD}' | '\u{50000}'..='\u{5FFFD}' |
        '\u{60000}'..='\u{6FFFD}' | '\u{70000}'..='\u{7FFFD}' |
        '\u{80000}'..='\u{8FFFD}' | '\u{90000}'..='\u{9FFFD}' |
        '\u{A0000}'..='\u{AFFFD}' | '\u{B0000}'..='\u{BFFFD}' |
        '\u{C0000}'..='\u{CFFFD}' | '\u{D0000}'..='\u{DFFFD}' |
        '\u{E1000}'..='\u{EFFFD}' | '\u{F0000}'..='\u{FFFFD}' |
        '\u{100000}'..='\u{10FFFD}' => true,
    _ => false,
}matches!(c,
1717        'a'..='z' |
1718        'A'..='Z' |
1719        '0'..='9' |
1720        '!' | '$' | '&' | '\'' | '(' | ')' | '*' | '+' | ',' | '-' |
1721        '.' | '/' | ':' | ';' | '=' | '?' | '@' | '_' | '~' |
1722        '\u{A0}'..='\u{D7FF}' | '\u{E000}'..='\u{FDCF}' | '\u{FDF0}'..='\u{FFFD}' |
1723        '\u{10000}'..='\u{1FFFD}' | '\u{20000}'..='\u{2FFFD}' |
1724        '\u{30000}'..='\u{3FFFD}' | '\u{40000}'..='\u{4FFFD}' |
1725        '\u{50000}'..='\u{5FFFD}' | '\u{60000}'..='\u{6FFFD}' |
1726        '\u{70000}'..='\u{7FFFD}' | '\u{80000}'..='\u{8FFFD}' |
1727        '\u{90000}'..='\u{9FFFD}' | '\u{A0000}'..='\u{AFFFD}' |
1728        '\u{B0000}'..='\u{BFFFD}' | '\u{C0000}'..='\u{CFFFD}' |
1729        '\u{D0000}'..='\u{DFFFD}' | '\u{E1000}'..='\u{EFFFD}' |
1730        '\u{F0000}'..='\u{FFFFD}' | '\u{100000}'..='\u{10FFFD}')
1731}
1732
1733/// https://infra.spec.whatwg.org/#c0-control-or-space
1734#[inline]
1735fn c0_control_or_space(ch: char) -> bool {
1736    ch <= ' ' // U+0000 to U+0020
1737}
1738
1739/// https://infra.spec.whatwg.org/#ascii-tab-or-newline
1740#[inline]
1741fn ascii_tab_or_new_line(ch: char) -> bool {
1742    #[allow(non_exhaustive_omitted_patterns)] match ch {
    '\t' | '\n' | '\r' => true,
    _ => false,
}matches!(ch, ascii_tab_or_new_line_pattern!())
1743}
1744
1745/// https://url.spec.whatwg.org/#ascii-alpha
1746#[inline]
1747pub fn ascii_alpha(ch: char) -> bool {
1748    ch.is_ascii_alphabetic()
1749}
1750
1751#[inline]
1752pub fn to_u32(i: usize) -> ParseResult<u32> {
1753    if i <= u32::MAX as usize {
1754        Ok(i as u32)
1755    } else {
1756        Err(ParseError::Overflow)
1757    }
1758}
1759
1760fn is_normalized_windows_drive_letter(segment: &str) -> bool {
1761    is_windows_drive_letter(segment) && segment.as_bytes()[1] == b':'
1762}
1763
1764/// Whether the scheme is file:, the path has a single segment, and that segment
1765/// is a Windows drive letter
1766#[inline]
1767pub fn is_windows_drive_letter(segment: &str) -> bool {
1768    segment.len() == 2 && starts_with_windows_drive_letter(segment)
1769}
1770
1771/// Whether path starts with a root slash
1772/// and a windows drive letter eg: "/c:" or "/a:/"
1773fn path_starts_with_windows_drive_letter(s: &str) -> bool {
1774    if let Some(c) = s.as_bytes().first() {
1775        #[allow(non_exhaustive_omitted_patterns)] match c {
    b'/' | b'\\' | b'?' | b'#' => true,
    _ => false,
}matches!(c, b'/' | b'\\' | b'?' | b'#') && starts_with_windows_drive_letter(&s[1..])
1776    } else {
1777        false
1778    }
1779}
1780
1781fn starts_with_windows_drive_letter(s: &str) -> bool {
1782    s.len() >= 2
1783        && ascii_alpha(s.as_bytes()[0] as char)
1784        && #[allow(non_exhaustive_omitted_patterns)] match s.as_bytes()[1] {
    b':' | b'|' => true,
    _ => false,
}matches!(s.as_bytes()[1], b':' | b'|')
1785        && (s.len() == 2 || #[allow(non_exhaustive_omitted_patterns)] match s.as_bytes()[2] {
    b'/' | b'\\' | b'?' | b'#' => true,
    _ => false,
}matches!(s.as_bytes()[2], b'/' | b'\\' | b'?' | b'#'))
1786}
1787
1788/// https://url.spec.whatwg.org/#start-with-a-windows-drive-letter
1789fn starts_with_windows_drive_letter_segment(input: &Input<'_>) -> bool {
1790    let mut input = input.clone();
1791    match (input.next(), input.next(), input.next()) {
1792        // its first two code points are a Windows drive letter
1793        // its third code point is U+002F (/), U+005C (\), U+003F (?), or U+0023 (#).
1794        (Some(a), Some(b), Some(c))
1795            if ascii_alpha(a) && #[allow(non_exhaustive_omitted_patterns)] match b {
    ':' | '|' => true,
    _ => false,
}matches!(b, ':' | '|') && #[allow(non_exhaustive_omitted_patterns)] match c {
    '/' | '\\' | '?' | '#' => true,
    _ => false,
}matches!(c, '/' | '\\' | '?' | '#') =>
1796        {
1797            true
1798        }
1799        // its first two code points are a Windows drive letter
1800        // its length is 2
1801        (Some(a), Some(b), None) if ascii_alpha(a) && #[allow(non_exhaustive_omitted_patterns)] match b {
    ':' | '|' => true,
    _ => false,
}matches!(b, ':' | '|') => true,
1802        _ => false,
1803    }
1804}
1805
1806#[inline]
1807fn fast_u16_to_str(
1808    // max 5 digits for u16 (65535)
1809    buffer: &mut [u8; 5],
1810    mut value: u16,
1811) -> &str {
1812    let mut index = buffer.len();
1813
1814    loop {
1815        index -= 1;
1816        buffer[index] = b'0' + (value % 10) as u8;
1817        value /= 10;
1818        if value == 0 {
1819            break;
1820        }
1821    }
1822
1823    // SAFETY: we know the values in the buffer from the
1824    // current index on will be a number
1825    unsafe { core::str::from_utf8_unchecked(&buffer[index..]) }
1826}