Skip to main content

php_std/url/
rfc3986.rs

1//! `Uri\Rfc3986\Uri` from the PHP 8.5 URI extension.
2//!
3//! PHP parses with uriparser 1.0 (`uriParseSingleUriExMmA`, the RFC 3986
4//! `URI-reference` grammar), keeps the parsed URI for the `getRaw*()`
5//! getters, and reads the normalized getters (`getScheme()`, `getHost()`)
6//! from a copy passed through `uriNormalizeSyntaxExMmA` with every
7//! normalization enabled. This module ports the parser state machine
8//! (`UriParse.c`) and the scheme and host normalization (`UriNormalize.c`,
9//! `UriCommon.c`) byte for byte, including their quirks:
10//!
11//! - host lowercasing stops at a `%` in the last three bytes of the host;
12//! - a port longer than 20 digits or above `PHP_INT_MAX` makes `parse()`
13//!   return `null` (PHP's own check).
14//!
15//! The normalized user info, path, port, query and fragment getters,
16//! `toString()`/`toRawString()`, base URIs (`parse($uri, $baseUrl)`),
17//! `resolve()` and the `with*()` modifiers are not ported: no Utopia library
18//! uses them.
19
20use std::borrow::Cow;
21use std::ops::Range;
22
23/// A URI parsed by `Uri\Rfc3986\Uri::parse()`.
24#[derive(Debug, Clone, PartialEq, Eq)]
25pub struct Uri<'a> {
26    input: &'a [u8],
27    scheme: Option<Range<usize>>,
28    user_info: Option<Range<usize>>,
29    host: Option<Host>,
30    port: Option<Range<usize>>,
31    segments: Vec<Range<usize>>,
32    absolute_path: bool,
33    query: Option<Range<usize>>,
34    fragment: Option<Range<usize>>,
35}
36
37/// The host of an authority. `text` excludes the brackets of IP literals.
38#[derive(Debug, Clone, PartialEq, Eq)]
39struct Host {
40    text: Range<usize>,
41    kind: HostKind,
42}
43
44#[derive(Debug, Clone, PartialEq, Eq)]
45enum HostKind {
46    /// A reg-name (possibly empty) or an IPv4 address: both recompose to
47    /// their text (uriparser's IPv4 grammar is strict `dec-octet`).
48    Name,
49    Ip6([u8; 16]),
50    IpFuture,
51}
52
53impl<'a> Uri<'a> {
54    /// `Uri\Rfc3986\Uri::parse($uri)`: `None` where PHP returns `null`.
55    pub fn parse(input: &'a [u8]) -> Option<Self> {
56        let mut p = Parser::new(input);
57        let end = p.uri_reference(0)?;
58        if end != input.len() {
59            return None;
60        }
61        let uri = p.finish();
62        // ext/uri: a port that does not fit in a PHP integer is rejected.
63        if let Some(port) = &uri.port
64            && !port.is_empty()
65            && port_value(&input[port.clone()]).is_none()
66        {
67            return None;
68        }
69        Some(uri)
70    }
71
72    fn slice(&self, r: &Range<usize>) -> &'a [u8] {
73        &self.input[r.clone()]
74    }
75
76    fn opt(&self, r: &Option<Range<usize>>) -> Option<&'a [u8]> {
77        r.as_ref().map(|r| self.slice(r))
78    }
79
80    /// `getRawScheme()`
81    pub fn raw_scheme(&self) -> Option<Cow<'a, [u8]>> {
82        self.opt(&self.scheme).map(Cow::Borrowed)
83    }
84
85    /// `getScheme()`: lowercased.
86    pub fn scheme(&self) -> Option<Cow<'a, [u8]>> {
87        self.opt(&self.scheme).map(lowercase)
88    }
89
90    /// `getRawUserInfo()`
91    pub fn raw_user_info(&self) -> Option<Cow<'a, [u8]>> {
92        self.opt(&self.user_info).map(Cow::Borrowed)
93    }
94
95    /// `getRawUsername()`
96    pub fn raw_username(&self) -> Option<Cow<'a, [u8]>> {
97        self.raw_user_info().map(username)
98    }
99
100    /// `getRawPassword()`
101    pub fn raw_password(&self) -> Option<Cow<'a, [u8]>> {
102        self.raw_user_info().map(password)
103    }
104
105    /// `getRawHost()`: IP literals keep their brackets.
106    pub fn raw_host(&self) -> Option<Cow<'a, [u8]>> {
107        let host = self.host.as_ref()?;
108        let text = self.slice(&host.text);
109        Some(match host.kind {
110            HostKind::Name => Cow::Borrowed(text),
111            _ => Cow::Owned(bracketed(text)),
112        })
113    }
114
115    /// `getHost()`: lowercased and percent-encoding normalized.
116    pub fn host(&self) -> Option<Cow<'a, [u8]>> {
117        let host = self.host.as_ref()?;
118        let text = self.normalized_host_text(host);
119        Some(match host.kind {
120            HostKind::Name => text,
121            _ => Cow::Owned(bracketed(&text)),
122        })
123    }
124
125    fn normalized_host_text(&self, host: &Host) -> Cow<'a, [u8]> {
126        let text = self.slice(&host.text);
127        match host.kind {
128            HostKind::IpFuture => lowercase(text),
129            _ => {
130                let mut fixed = fix_percent_encoding(text);
131                if fixed.iter().any(u8::is_ascii_uppercase) {
132                    lowercase_except_percent_encoding(fixed.to_mut());
133                }
134                fixed
135            }
136        }
137    }
138
139    /// `getRawPath()`
140    pub fn raw_path(&self) -> Cow<'a, [u8]> {
141        let segments: Vec<Cow<'a, [u8]>> = self.segments.iter().map(|r| Cow::Borrowed(self.slice(r))).collect();
142        Cow::Owned(self.join_path(&segments, self.absolute_path))
143    }
144
145    /// `getRawQuery()`
146    pub fn raw_query(&self) -> Option<Cow<'a, [u8]>> {
147        self.opt(&self.query).map(Cow::Borrowed)
148    }
149
150    fn has_host(&self) -> bool {
151        self.host.is_some()
152    }
153
154    /// `php_uri_parser_rfc3986_path_read`.
155    fn join_path(&self, segments: &[Cow<'a, [u8]>], absolute: bool) -> Vec<u8> {
156        let mut out = Vec::new();
157        if !segments.is_empty() {
158            if absolute || self.has_host() {
159                out.push(b'/');
160            }
161            join_segments(&mut out, segments);
162        } else if absolute {
163            out.push(b'/');
164        }
165        out
166    }
167}
168
169const HEX_UPPER: &[u8; 16] = b"0123456789ABCDEF";
170
171fn join_segments(out: &mut Vec<u8>, segments: &[Cow<'_, [u8]>]) {
172    for (i, s) in segments.iter().enumerate() {
173        if i > 0 {
174            out.push(b'/');
175        }
176        out.extend_from_slice(s);
177    }
178}
179
180fn bracketed(text: &[u8]) -> Vec<u8> {
181    let mut v = Vec::with_capacity(text.len() + 2);
182    v.push(b'[');
183    v.extend_from_slice(text);
184    v.push(b']');
185    v
186}
187
188/// `php_uri_parser_rfc3986_username_read`.
189fn username(user_info: Cow<'_, [u8]>) -> Cow<'_, [u8]> {
190    match user_info.iter().position(|&b| b == b':') {
191        None => user_info,
192        Some(c) => match user_info {
193            Cow::Borrowed(b) => Cow::Borrowed(&b[..c]),
194            Cow::Owned(mut v) => {
195                v.truncate(c);
196                Cow::Owned(v)
197            }
198        },
199    }
200}
201
202/// `php_uri_parser_rfc3986_password_read`: empty when there is no `:`.
203fn password(user_info: Cow<'_, [u8]>) -> Cow<'_, [u8]> {
204    match user_info.iter().position(|&b| b == b':') {
205        None => Cow::Borrowed(&[]),
206        Some(c) => match user_info {
207            Cow::Borrowed(b) => Cow::Borrowed(&b[c + 1..]),
208            Cow::Owned(v) => Cow::Owned(v[c + 1..].to_vec()),
209        },
210    }
211}
212
213/// `port_str_to_zend_long_checked`: `strtoul` of the digits, rejected above
214/// 20 digits or `PHP_INT_MAX`.
215fn port_value(digits: &[u8]) -> Option<i64> {
216    if digits.len() > 20 {
217        return None;
218    }
219    let mut v: u64 = 0;
220    for &b in digits {
221        v = v.saturating_mul(10).saturating_add(u64::from(b - b'0'));
222    }
223    i64::try_from(v).ok()
224}
225
226fn lowercase(s: &[u8]) -> Cow<'_, [u8]> {
227    if s.iter().any(u8::is_ascii_uppercase) { Cow::Owned(s.to_ascii_lowercase()) } else { Cow::Borrowed(s) }
228}
229
230/// `LowercaseInplaceExceptPercentEncoding`, including its early return when a
231/// `%` sits in the last three bytes.
232fn lowercase_except_percent_encoding(s: &mut [u8]) {
233    let mut i = 0;
234    while i < s.len() {
235        if s[i].is_ascii_uppercase() {
236            s[i] = s[i].to_ascii_lowercase();
237        } else if s[i] == b'%' {
238            if i + 3 >= s.len() {
239                return;
240            }
241            i += 2;
242        }
243        i += 1;
244    }
245}
246
247fn is_unreserved(b: u8) -> bool {
248    b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~')
249}
250
251fn is_sub_delim(b: u8) -> bool {
252    matches!(b, b'!' | b'$' | b'&' | b'\'' | b'(' | b')' | b'*' | b'+' | b',' | b';' | b'=')
253}
254
255/// `URI_SET_PCHAR`: unreserved, sub-delims, `:`, `@` and `%`.
256fn is_pchar(b: u8) -> bool {
257    is_unreserved(b) || is_sub_delim(b) || matches!(b, b':' | b'@' | b'%')
258}
259
260fn hex_value(b: u8) -> u8 {
261    match b {
262        b'0'..=b'9' => b - b'0',
263        b'a'..=b'f' => b - b'a' + 10,
264        b'A'..=b'F' => b - b'A' + 10,
265        _ => 0,
266    }
267}
268
269/// `FixPercentEncodingEngine`: decodes `%XX` of unreserved characters and
270/// uppercases the hex digits of the others.
271fn fix_percent_encoding(s: &[u8]) -> Cow<'_, [u8]> {
272    let needs = s.windows(3).any(|w| w[0] == b'%');
273    if !needs {
274        return Cow::Borrowed(s);
275    }
276    let mut out = Vec::with_capacity(s.len());
277    let mut i = 0;
278    while i + 2 < s.len() {
279        if s[i] != b'%' {
280            out.push(s[i]);
281        } else {
282            let (left, right) = (hex_value(s[i + 1]), hex_value(s[i + 2]));
283            let code = 16 * left + right;
284            if is_unreserved(code) {
285                out.push(code);
286            } else {
287                out.extend_from_slice(&[b'%', HEX_UPPER[usize::from(left)], HEX_UPPER[usize::from(right)]]);
288            }
289            i += 2;
290        }
291        i += 1;
292    }
293    out.extend_from_slice(&s[i..]);
294    Cow::Owned(out)
295}
296
297/// The uriparser state machine (`UriParse.c`), positions instead of pointers.
298/// Every `fn` returns the position after what it consumed, or `None` for a
299/// syntax error.
300struct Parser<'a> {
301    s: &'a [u8],
302    seg_start: usize,
303    scheme: Option<Range<usize>>,
304    user_info_first: usize,
305    user_info: Option<Range<usize>>,
306    host_first: usize,
307    host_end: Option<usize>,
308    host: Option<Host>,
309    port_first: Option<usize>,
310    port: Option<Range<usize>>,
311    ip6: Option<[u8; 16]>,
312    ip_future: bool,
313    segments: Vec<Range<usize>>,
314    absolute_path: bool,
315    query: Option<Range<usize>>,
316    fragment: Option<Range<usize>>,
317}
318
319impl<'a> Parser<'a> {
320    fn new(s: &'a [u8]) -> Self {
321        Parser {
322            s,
323            seg_start: 0,
324            scheme: None,
325            user_info_first: 0,
326            user_info: None,
327            host_first: 0,
328            host_end: None,
329            host: None,
330            port_first: None,
331            port: None,
332            ip6: None,
333            ip_future: false,
334            segments: Vec::new(),
335            absolute_path: false,
336            query: None,
337            fragment: None,
338        }
339    }
340
341    fn finish(self) -> Uri<'a> {
342        Uri {
343            input: self.s,
344            scheme: self.scheme,
345            user_info: self.user_info,
346            host: self.host,
347            port: self.port,
348            segments: self.segments,
349            absolute_path: self.absolute_path,
350            query: self.query,
351            fragment: self.fragment,
352        }
353    }
354
355    fn end(&self) -> usize {
356        self.s.len()
357    }
358
359    fn at(&self, i: usize) -> u8 {
360        self.s[i]
361    }
362
363    fn push(&mut self, r: Range<usize>) {
364        self.segments.push(r);
365    }
366
367    fn set_name_host(&mut self, r: Range<usize>) {
368        let kind = match (self.ip6.take(), std::mem::take(&mut self.ip_future)) {
369            (Some(bytes), _) => HostKind::Ip6(bytes),
370            (None, true) => HostKind::IpFuture,
371            _ => HostKind::Name,
372        };
373        self.host = Some(Host { text: r, kind });
374    }
375
376    /// `[uriReference]`
377    fn uri_reference(&mut self, first: usize) -> Option<usize> {
378        if first >= self.end() {
379            return Some(self.end());
380        }
381        let c = self.at(first);
382        match c {
383            _ if c.is_ascii_alphabetic() => {
384                self.seg_start = first;
385                self.segment_nz_nc_or_scheme2(first + 1)
386            }
387            _ if c.is_ascii_digit() || is_sub_delim(c) || matches!(c, b'.' | b'_' | b'~' | b'-' | b'@') => {
388                self.seg_start = first;
389                self.must_be_segment_nz_nc(first + 1)
390            }
391            b'%' => {
392                let after = self.pct_encoded(first)?;
393                self.seg_start = first;
394                self.must_be_segment_nz_nc(after)
395            }
396            b'/' => {
397                let after = self.part_helper_two(first + 1)?;
398                self.uri_tail(after)
399            }
400            _ => self.uri_tail(first),
401        }
402    }
403
404    /// `[segmentNzNcOrScheme2]`
405    fn segment_nz_nc_or_scheme2(&mut self, mut first: usize) -> Option<usize> {
406        loop {
407            if first >= self.end() {
408                self.push(self.seg_start..first);
409                return Some(self.end());
410            }
411            let c = self.at(first);
412            match c {
413                b'.' | b'+' | b'-' => first += 1,
414                _ if c.is_ascii_alphanumeric() => first += 1,
415                b'%' => {
416                    let after = self.pct_encoded(first)?;
417                    return self.must_be_segment_nz_nc(after);
418                }
419                b'!' | b'$' | b'&' | b'(' | b')' | b'*' | b',' | b';' | b'@' | b'_' | b'~' | b'=' | b'\'' => {
420                    return self.must_be_segment_nz_nc(first + 1);
421                }
422                b'/' => {
423                    let after_segment = self.segment(first + 1)?;
424                    self.push(self.seg_start..first);
425                    self.push(first + 1..after_segment);
426                    let after = self.zero_more_slash_segs(after_segment)?;
427                    return self.uri_tail(after);
428                }
429                b':' => {
430                    let after_hier = self.hier_part(first + 1)?;
431                    self.scheme = Some(self.seg_start..first);
432                    return self.uri_tail(after_hier);
433                }
434                _ => {
435                    self.push(self.seg_start..first);
436                    return self.uri_tail(first);
437                }
438            }
439        }
440    }
441
442    /// `[mustBeSegmentNzNc]`
443    fn must_be_segment_nz_nc(&mut self, mut first: usize) -> Option<usize> {
444        loop {
445            if first >= self.end() {
446                self.push(self.seg_start..first);
447                return Some(self.end());
448            }
449            let c = self.at(first);
450            match c {
451                b'%' => first = self.pct_encoded(first)?,
452                _ if c == b'@' || is_sub_delim(c) || is_unreserved(c) => first += 1,
453                b'/' => {
454                    self.push(self.seg_start..first);
455                    let after_segment = self.segment(first + 1)?;
456                    self.push(first + 1..after_segment);
457                    let after = self.zero_more_slash_segs(after_segment)?;
458                    return self.uri_tail(after);
459                }
460                _ => {
461                    self.push(self.seg_start..first);
462                    return self.uri_tail(first);
463                }
464            }
465        }
466    }
467
468    /// `[uriTail]`
469    fn uri_tail(&mut self, first: usize) -> Option<usize> {
470        if first >= self.end() {
471            return Some(self.end());
472        }
473        match self.at(first) {
474            b'#' => {
475                let after = self.query_frag(first + 1)?;
476                self.fragment = Some(first + 1..after);
477                Some(after)
478            }
479            b'?' => {
480                let after = self.query_frag(first + 1)?;
481                self.query = Some(first + 1..after);
482                if after < self.end() && self.at(after) == b'#' {
483                    let after_fragment = self.query_frag(after + 1)?;
484                    self.fragment = Some(after + 1..after_fragment);
485                    return Some(after_fragment);
486                }
487                Some(after)
488            }
489            _ => Some(first),
490        }
491    }
492
493    /// `[queryFrag]`
494    fn query_frag(&mut self, mut first: usize) -> Option<usize> {
495        loop {
496            if first >= self.end() {
497                return Some(self.end());
498            }
499            let c = self.at(first);
500            if is_pchar(c) {
501                first = self.pchar(first)?;
502            } else if c == b'/' || c == b'?' {
503                first += 1;
504            } else {
505                return Some(first);
506            }
507        }
508    }
509
510    /// `[hierPart]`
511    fn hier_part(&mut self, first: usize) -> Option<usize> {
512        if first >= self.end() {
513            return Some(self.end());
514        }
515        let c = self.at(first);
516        if is_pchar(c) {
517            self.path_rootless(first)
518        } else if c == b'/' {
519            self.part_helper_two(first + 1)
520        } else {
521            Some(first)
522        }
523    }
524
525    /// `[partHelperTwo]`
526    fn part_helper_two(&mut self, first: usize) -> Option<usize> {
527        if first >= self.end() {
528            self.absolute_path = true;
529            return Some(self.end());
530        }
531        if self.at(first) == b'/' {
532            let after_authority = self.authority(first + 1)?;
533            self.path_abs_empty(after_authority)
534        } else {
535            self.absolute_path = true;
536            self.path_abs_no_lead_slash(first)
537        }
538    }
539
540    /// `[pathAbsEmpty]`, also `[zeroMoreSlashSegs]`.
541    fn path_abs_empty(&mut self, mut first: usize) -> Option<usize> {
542        while first < self.end() && self.at(first) == b'/' {
543            let after = self.segment(first + 1)?;
544            self.push(first + 1..after);
545            first = after;
546        }
547        Some(first)
548    }
549
550    fn zero_more_slash_segs(&mut self, first: usize) -> Option<usize> {
551        self.path_abs_empty(first)
552    }
553
554    /// `[pathAbsNoLeadSlash]`
555    fn path_abs_no_lead_slash(&mut self, first: usize) -> Option<usize> {
556        if first >= self.end() {
557            return Some(self.end());
558        }
559        if is_pchar(self.at(first)) {
560            let after = self.segment_nz(first)?;
561            self.push(first..after);
562            self.zero_more_slash_segs(after)
563        } else {
564            Some(first)
565        }
566    }
567
568    /// `[pathRootless]`
569    fn path_rootless(&mut self, first: usize) -> Option<usize> {
570        let after = self.segment_nz(first)?;
571        self.push(first..after);
572        self.zero_more_slash_segs(after)
573    }
574
575    /// `[segmentNz]`
576    fn segment_nz(&mut self, first: usize) -> Option<usize> {
577        let after = self.pchar(first)?;
578        self.segment(after)
579    }
580
581    /// `[segment]`
582    fn segment(&mut self, mut first: usize) -> Option<usize> {
583        while first < self.end() && is_pchar(self.at(first)) {
584            first = self.pchar(first)?;
585        }
586        Some(first)
587    }
588
589    /// `[pchar]`
590    fn pchar(&mut self, first: usize) -> Option<usize> {
591        if first >= self.end() {
592            return None;
593        }
594        match self.at(first) {
595            b'%' => self.pct_encoded(first),
596            c if is_pchar(c) => Some(first + 1),
597            _ => None,
598        }
599    }
600
601    /// `[pctEncoded]`
602    fn pct_encoded(&self, first: usize) -> Option<usize> {
603        if self.end() - first < 3 {
604            return None;
605        }
606        (self.at(first + 1).is_ascii_hexdigit() && self.at(first + 2).is_ascii_hexdigit()).then_some(first + 3)
607    }
608
609    /// `[pctSubUnres]`
610    fn pct_sub_unres(&self, first: usize) -> Option<usize> {
611        if first >= self.end() {
612            return None;
613        }
614        match self.at(first) {
615            b'%' => self.pct_encoded(first),
616            c if is_sub_delim(c) || is_unreserved(c) => Some(first + 1),
617            _ => None,
618        }
619    }
620
621    /// `[authority]`
622    fn authority(&mut self, first: usize) -> Option<usize> {
623        if first >= self.end() {
624            self.set_name_host(first..first);
625            return Some(self.end());
626        }
627        let c = self.at(first);
628        if c == b'[' {
629            let after = self.ip_lit2(first + 1)?;
630            self.authority_two(after)
631        } else if is_pchar(c) {
632            self.user_info_first = first;
633            self.own_host_user_info_nz(first)
634        } else {
635            self.set_name_host(first..first);
636            Some(first)
637        }
638    }
639
640    /// `[authorityTwo]`
641    fn authority_two(&mut self, first: usize) -> Option<usize> {
642        if first < self.end() && self.at(first) == b':' {
643            let mut after = first + 1;
644            while after < self.end() && self.at(after).is_ascii_digit() {
645                after += 1;
646            }
647            self.port = Some(first + 1..after);
648            return Some(after);
649        }
650        Some(first)
651    }
652
653    /// `[ownHostUserInfoNz]`
654    fn own_host_user_info_nz(&mut self, mut first: usize) -> Option<usize> {
655        let original = first;
656        while first < self.end() {
657            let c = self.at(first);
658            if c == b'%' || is_sub_delim(c) || is_unreserved(c) {
659                first = self.pct_sub_unres(first)?;
660            } else {
661                break;
662            }
663        }
664        if first < self.end() {
665            match self.at(first) {
666                b':' => {
667                    self.host_end = Some(first);
668                    self.port_first = Some(first + 1);
669                    return self.own_port_user_info(first + 1);
670                }
671                b'@' => {
672                    self.user_info = Some(self.user_info_first..first);
673                    self.host_first = first + 1;
674                    return self.own_host(first + 1);
675                }
676                _ => {}
677            }
678        }
679        if first == original {
680            return None;
681        }
682        self.set_name_host(self.user_info_first..first);
683        Some(first)
684    }
685
686    fn on_exit_own_port_user_info(&mut self, first: usize) {
687        let host_end = self.host_end.unwrap_or(first);
688        self.set_name_host(self.user_info_first..host_end);
689        let port_first = self.port_first.unwrap_or(first);
690        self.port = Some(port_first..first);
691    }
692
693    /// `[ownPortUserInfo]`
694    fn own_port_user_info(&mut self, mut first: usize) -> Option<usize> {
695        loop {
696            if first >= self.end() {
697                self.on_exit_own_port_user_info(first);
698                return Some(self.end());
699            }
700            let c = self.at(first);
701            match c {
702                _ if is_sub_delim(c) || matches!(c, b'-' | b'.' | b'_' | b'~' | b':') || c.is_ascii_alphabetic() => {
703                    self.host_end = None;
704                    self.port_first = None;
705                    return self.own_user_info(first + 1);
706                }
707                _ if c.is_ascii_digit() => first += 1,
708                b'%' => {
709                    self.port_first = None;
710                    let after = self.pct_encoded(first)?;
711                    return self.own_user_info(after);
712                }
713                b'@' => {
714                    self.host_end = None;
715                    self.port_first = None;
716                    self.user_info = Some(self.user_info_first..first);
717                    self.host_first = first + 1;
718                    return self.own_host(first + 1);
719                }
720                _ => {
721                    self.on_exit_own_port_user_info(first);
722                    return Some(first);
723                }
724            }
725        }
726    }
727
728    /// `[ownUserInfo]`
729    fn own_user_info(&mut self, mut first: usize) -> Option<usize> {
730        loop {
731            if first >= self.end() {
732                return None;
733            }
734            let c = self.at(first);
735            match c {
736                b':' => first += 1,
737                b'@' => {
738                    self.user_info = Some(self.user_info_first..first);
739                    self.host_first = first + 1;
740                    return self.own_host(first + 1);
741                }
742                _ if c == b'%' || is_sub_delim(c) || is_unreserved(c) => first = self.pct_sub_unres(first)?,
743                _ => return None,
744            }
745        }
746    }
747
748    /// `[ownHost]`
749    fn own_host(&mut self, first: usize) -> Option<usize> {
750        if first >= self.end() {
751            self.set_name_host(self.host_first..self.end());
752            return Some(self.end());
753        }
754        if self.at(first) == b'[' {
755            let after = self.ip_lit2(first + 1)?;
756            return self.authority_two(after);
757        }
758        self.own_host2(first)
759    }
760
761    /// `[ownHost2]`
762    fn own_host2(&mut self, mut first: usize) -> Option<usize> {
763        loop {
764            if first >= self.end() {
765                self.set_name_host(self.host_first..self.end());
766                return Some(self.end());
767            }
768            let c = self.at(first);
769            if c == b'%' || is_sub_delim(c) || is_unreserved(c) {
770                first = self.pct_sub_unres(first)?;
771            } else {
772                self.set_name_host(self.host_first..first);
773                return self.authority_two(first);
774            }
775        }
776    }
777
778    /// `[ipLit2]`: `first` is after `[`.
779    fn ip_lit2(&mut self, first: usize) -> Option<usize> {
780        if first >= self.end() {
781            return None;
782        }
783        let c = self.at(first);
784        match c {
785            b'v' | b'V' => {
786                let after = self.ip_future(first)?;
787                if after >= self.end() || self.at(after) != b']' {
788                    return None;
789                }
790                self.ip_future = true;
791                self.set_name_host(first..after);
792                Some(after + 1)
793            }
794            b':' | b']' => self.ipv6_address2(first),
795            _ if c.is_ascii_hexdigit() => self.ipv6_address2(first),
796            _ => None,
797        }
798    }
799
800    /// `[ipFuture]`: `v` 1*HEXDIG `.` 1*(unreserved / sub-delims / `:`).
801    fn ip_future(&mut self, first: usize) -> Option<usize> {
802        if self.end() - first < 2 || !self.at(first + 1).is_ascii_hexdigit() {
803            return None;
804        }
805        let mut p = first + 2;
806        while p < self.end() && self.at(p).is_ascii_hexdigit() {
807            p += 1;
808        }
809        if p >= self.end() || self.at(p) != b'.' {
810            return None;
811        }
812        let start = p + 1;
813        let mut q = start;
814        while q < self.end() {
815            let c = self.at(q);
816            if c == b':' || is_sub_delim(c) || is_unreserved(c) {
817                q += 1;
818            } else {
819                break;
820            }
821        }
822        (q != start).then_some(q)
823    }
824
825    /// `[IPv6address2]`: everything up to and including `]`.
826    fn ipv6_address2(&mut self, mut first: usize) -> Option<usize> {
827        let start = first;
828        let mut data = [0u8; 16];
829        let mut zipper_ever = false;
830        let mut quads_done = 0usize;
831        let mut digit_count = 0usize;
832        let mut digits = [0u8; 4];
833        let mut ip4_octets_done = 0usize;
834        let mut after_zipper = [0u8; 14];
835        let mut after_zipper_count = 0usize;
836
837        let octet_ok = |digits: &[u8; 4], count: usize| -> bool {
838            !((count > 1 && digits[0] == 0)
839                || (count == 3 && 100 * u32::from(digits[0]) + 10 * u32::from(digits[1]) + u32::from(digits[2]) > 255))
840        };
841        let octet = |digits: &[u8; 4], count: usize| -> u8 {
842            digits[..count].iter().fold(0u32, |acc, &d| acc * 10 + u32::from(d)) as u8
843        };
844        let write_quad = |digits: &[u8; 4], count: usize, out: &mut [u8]| match count {
845            1 => {
846                out[0] = 0;
847                out[1] = digits[0];
848            }
849            2 => {
850                out[0] = 0;
851                out[1] = 16 * digits[0] + digits[1];
852            }
853            3 => {
854                out[0] = digits[0];
855                out[1] = 16 * digits[1] + digits[2];
856            }
857            _ => {
858                out[0] = 16 * digits[0] + digits[1];
859                out[1] = 16 * digits[2] + digits[3];
860            }
861        };
862
863        loop {
864            if first >= self.end() {
865                return None;
866            }
867            if ip4_octets_done > 0 {
868                loop {
869                    let c = self.at(first);
870                    match c {
871                        b'0'..=b'9' => {
872                            if digit_count == 4 {
873                                return None;
874                            }
875                            digits[digit_count] = c - b'0';
876                            digit_count += 1;
877                        }
878                        b'.' => {
879                            if ip4_octets_done == 4 || digit_count == 0 || digit_count == 4 {
880                                return None;
881                            }
882                            if !octet_ok(&digits, digit_count) {
883                                return None;
884                            }
885                            data[16 - 4 + ip4_octets_done] = octet(&digits, digit_count);
886                            digit_count = 0;
887                            ip4_octets_done += 1;
888                        }
889                        b']' => {
890                            if ip4_octets_done != 3 || digit_count == 0 || digit_count == 4 {
891                                return None;
892                            }
893                            if !octet_ok(&digits, digit_count) {
894                                return None;
895                            }
896                            let n = 2 * after_zipper_count;
897                            data[16 - 4 - n..16 - 4].copy_from_slice(&after_zipper[..n]);
898                            data[16 - 4 + 3] = octet(&digits, digit_count);
899                            self.ip6 = Some(data);
900                            self.set_name_host(start..first);
901                            return Some(first + 1);
902                        }
903                        _ => return None,
904                    }
905                    first += 1;
906                    if first >= self.end() {
907                        return None;
908                    }
909                }
910            }
911            let mut letter_among = false;
912            loop {
913                let c = self.at(first);
914                match c {
915                    b'a'..=b'f' | b'A'..=b'F' | b'0'..=b'9' => {
916                        if !c.is_ascii_digit() {
917                            letter_among = true;
918                        }
919                        if digit_count == 4 {
920                            return None;
921                        }
922                        digits[digit_count] = hex_value(c);
923                        digit_count += 1;
924                    }
925                    b':' => {
926                        let mut set_zipper = false;
927                        if digit_count > 0 {
928                            if zipper_ever {
929                                write_quad(
930                                    &digits,
931                                    digit_count,
932                                    &mut after_zipper[2 * after_zipper_count..2 * after_zipper_count + 2],
933                                );
934                                after_zipper_count += 1;
935                            } else {
936                                write_quad(&digits, digit_count, &mut data[2 * quads_done..2 * quads_done + 2]);
937                            }
938                            quads_done += 1;
939                            digit_count = 0;
940                        }
941                        letter_among = false;
942                        if quads_done >= 8 - usize::from(zipper_ever) {
943                            return None;
944                        }
945                        if self.end() - first < 2 {
946                            return None;
947                        }
948                        if self.at(first + 1) == b':' {
949                            let reset = 2 * quads_done;
950                            first += 1;
951                            if zipper_ever {
952                                return None;
953                            }
954                            data[reset..].fill(0);
955                            set_zipper = true;
956                            if self.end() - first < 2 || self.at(first + 1) == b':' {
957                                return None;
958                            }
959                        } else if quads_done == 0 || self.at(first + 1) == b']' {
960                            return None;
961                        }
962                        if set_zipper {
963                            zipper_ever = true;
964                        }
965                    }
966                    b'.' => {
967                        if quads_done + usize::from(zipper_ever) > 6
968                            || (!zipper_ever && quads_done < 6)
969                            || letter_among
970                            || digit_count == 0
971                            || digit_count == 4
972                        {
973                            return None;
974                        }
975                        if !octet_ok(&digits, digit_count) {
976                            return None;
977                        }
978                        data[16 - 4] = octet(&digits, digit_count);
979                        digit_count = 0;
980                        ip4_octets_done = 1;
981                        first += 1;
982                        break;
983                    }
984                    b']' => {
985                        if !(zipper_ever || (quads_done == 7 && digit_count > 0)) {
986                            return None;
987                        }
988                        if digit_count > 0 {
989                            if zipper_ever {
990                                if quads_done >= 7 {
991                                    return None;
992                                }
993                                write_quad(
994                                    &digits,
995                                    digit_count,
996                                    &mut after_zipper[2 * after_zipper_count..2 * after_zipper_count + 2],
997                                );
998                                after_zipper_count += 1;
999                            } else {
1000                                write_quad(&digits, digit_count, &mut data[2 * quads_done..2 * quads_done + 2]);
1001                            }
1002                        }
1003                        let n = 2 * after_zipper_count;
1004                        data[16 - n..].copy_from_slice(&after_zipper[..n]);
1005                        self.ip6 = Some(data);
1006                        self.set_name_host(start..first);
1007                        return Some(first + 1);
1008                    }
1009                    _ => return None,
1010                }
1011                first += 1;
1012                if first >= self.end() {
1013                    return None;
1014                }
1015            }
1016        }
1017    }
1018}
1019
1020#[cfg(test)]
1021mod tests {
1022    use super::*;
1023
1024    fn s(v: Option<Cow<'_, [u8]>>) -> Option<String> {
1025        v.map(|v| String::from_utf8(v.into_owned()).unwrap())
1026    }
1027
1028    #[test]
1029    fn parses_and_normalizes() {
1030        let u = Uri::parse(b"HTTP://User:P%41ss@EXAMPLE.com:0080/A/./b/../%7e%2f?Q%41#F%61").unwrap();
1031        assert_eq!(s(u.scheme()).unwrap(), "http");
1032        assert_eq!(s(u.raw_scheme()).unwrap(), "HTTP");
1033        assert_eq!(s(u.host()).unwrap(), "example.com");
1034    }
1035
1036    #[test]
1037    fn rejects() {
1038        assert!(Uri::parse(b"http://a@b@c").is_none());
1039        assert!(Uri::parse(b"http://h:99999999999999999999").is_none());
1040        assert!(Uri::parse(b"a b").is_none());
1041        assert!(Uri::parse(b"").is_some());
1042    }
1043}