Skip to main content

atmos/os_lib/web_apis/builtins/
url_parser.rs

1//! WHATWG URL Standard のパーサ(基本パーサの状態機械・ホスト解析・シリアライズ・セッター)。
2//! `new URL()` / `URL.canParse()` / URL のセッターの実体。DOM にもカーネルにも依存しない純粋なロジック。
3//! IDNA は UTS46 の完全な対応表を持たず、小文字化・全角 ASCII・句点・無視される文字・Punycode だけを扱う。
4
5use alloc::string::String;
6use alloc::vec::Vec;
7
8#[derive(Clone, Default, Debug)]
9pub struct Url {
10    pub scheme: String,
11    pub username: String,
12    pub password: String,
13    pub host: Option<String>,
14    pub port: Option<u16>,
15    pub path: Vec<String>,
16    pub opaque: Option<String>,
17    pub query: Option<String>,
18    pub fragment: Option<String>,
19}
20
21#[derive(Clone, Copy, PartialEq, Eq, Debug)]
22pub enum St {
23    SchemeStart,
24    Scheme,
25    NoScheme,
26    SpecialRelOrAuth,
27    PathOrAuth,
28    Relative,
29    RelativeSlash,
30    SpecialAuthSlashes,
31    SpecialAuthIgnoreSlashes,
32    Authority,
33    Host,
34    Hostname,
35    Port,
36    File,
37    FileSlash,
38    FileHost,
39    PathStart,
40    Path,
41    OpaquePath,
42    Query,
43    Fragment,
44}
45
46pub fn is_special(s: &str) -> bool {
47    matches!(s, "ftp" | "file" | "http" | "https" | "ws" | "wss")
48}
49fn default_port(s: &str) -> Option<u16> {
50    match s {
51        "ftp" => Some(21),
52        "http" | "ws" => Some(80),
53        "https" | "wss" => Some(443),
54        _ => None,
55    }
56}
57
58fn c0(c: char) -> bool {
59    (c as u32) < 0x20 || (c as u32) > 0x7e
60}
61fn set_fragment(c: char) -> bool {
62    c0(c) || matches!(c, ' ' | '"' | '<' | '>' | '`')
63}
64fn set_query(c: char) -> bool {
65    c0(c) || matches!(c, ' ' | '"' | '#' | '<' | '>')
66}
67fn set_special_query(c: char) -> bool {
68    set_query(c) || c == '\''
69}
70fn set_path(c: char) -> bool {
71    set_query(c) || matches!(c, '?' | '^' | '`' | '{' | '}')
72}
73fn set_userinfo(c: char) -> bool {
74    set_path(c) || matches!(c, '/' | ':' | ';' | '=' | '@' | '[' | '\\' | ']' | '|')
75}
76
77fn push_hex(out: &mut String, b: u8) {
78    const H: &[u8; 16] = b"0123456789ABCDEF";
79    out.push('%');
80    out.push(H[(b >> 4) as usize] as char);
81    out.push(H[(b & 15) as usize] as char);
82}
83fn enc_char(out: &mut String, c: char, set: fn(char) -> bool) {
84    if set(c) {
85        let mut b = [0u8; 4];
86        for x in c.encode_utf8(&mut b).as_bytes() {
87            push_hex(out, *x);
88        }
89    } else {
90        out.push(c);
91    }
92}
93pub fn encode_with(s: &str, set: fn(char) -> bool) -> String {
94    let mut o = String::new();
95    for c in s.chars() {
96        enc_char(&mut o, c, set);
97    }
98    o
99}
100pub fn encode_userinfo(s: &str) -> String {
101    encode_with(s, set_userinfo)
102}
103
104fn hexval(b: u8) -> Option<u8> {
105    match b {
106        b'0'..=b'9' => Some(b - b'0'),
107        b'a'..=b'f' => Some(b - b'a' + 10),
108        b'A'..=b'F' => Some(b - b'A' + 10),
109        _ => None,
110    }
111}
112fn percent_decode_bytes(s: &str) -> Vec<u8> {
113    let b = s.as_bytes();
114    let mut o = Vec::with_capacity(b.len());
115    let mut i = 0;
116    while i < b.len() {
117        if b[i] == b'%' && i + 2 < b.len() {
118            if let (Some(h), Some(l)) = (hexval(b[i + 1]), hexval(b[i + 2])) {
119                o.push(h * 16 + l);
120                i += 3;
121                continue;
122            }
123        }
124        o.push(b[i]);
125        i += 1;
126    }
127    o
128}
129
130fn is_wdl(s: &str) -> bool {
131    let mut it = s.chars();
132    match (it.next(), it.next(), it.next()) {
133        (Some(a), Some(b), None) => a.is_ascii_alphabetic() && (b == ':' || b == '|'),
134        _ => false,
135    }
136}
137fn is_normalized_wdl(s: &str) -> bool {
138    is_wdl(s) && s.ends_with(':')
139}
140fn starts_with_wdl(rest: &[char]) -> bool {
141    if rest.len() < 2 || !rest[0].is_ascii_alphabetic() || !(rest[1] == ':' || rest[1] == '|') {
142        return false;
143    }
144    rest.len() == 2 || matches!(rest[2], '/' | '\\' | '?' | '#')
145}
146
147fn is_single_dot(s: &str) -> bool {
148    s == "." || s.eq_ignore_ascii_case("%2e")
149}
150fn is_double_dot(s: &str) -> bool {
151    s == ".." || s.eq_ignore_ascii_case(".%2e") || s.eq_ignore_ascii_case("%2e.") || s.eq_ignore_ascii_case("%2e%2e")
152}
153
154fn shorten(url: &mut Url) {
155    if url.scheme == "file" && url.path.len() == 1 && is_normalized_wdl(&url.path[0]) {
156        return;
157    }
158    url.path.pop();
159}
160
161fn has_creds_or_port(u: &Url) -> bool {
162    !u.username.is_empty() || !u.password.is_empty() || u.port.is_some()
163}
164
165/// 基本 URL パーサ。`url_in` と `ov`(state override)を渡すとセッター用の動き。
166pub fn basic_parse(input: &str, base: Option<&Url>, url_in: Option<Url>, ov: Option<St>) -> Result<Url, ()> {
167    let fresh = url_in.is_none();
168    let mut url = url_in.unwrap_or_default();
169    let mut chars: Vec<char> = input.chars().collect();
170    if fresh {
171        let is_c0s = |c: &char| (*c as u32) <= 0x20;
172        while chars.first().is_some_and(is_c0s) {
173            chars.remove(0);
174        }
175        while chars.last().is_some_and(is_c0s) {
176            chars.pop();
177        }
178    }
179    chars.retain(|c| !matches!(c, '\t' | '\n' | '\r'));
180    let len = chars.len() as isize;
181    let mut state = ov.unwrap_or(St::SchemeStart);
182    let mut buf = String::new();
183    let (mut at_seen, mut inbr, mut pw_seen) = (false, false, false);
184    let mut p: isize = 0;
185    loop {
186        let c: Option<char> = if p >= 0 && p < len { Some(chars[p as usize]) } else { None };
187        let rem_start = (p + 1).clamp(0, len) as usize;
188        let remaining: &[char] = &chars[rem_start..];
189        let special = is_special(&url.scheme);
190        match state {
191            St::SchemeStart => match c {
192                Some(ch) if ch.is_ascii_alphabetic() => {
193                    buf.push(ch.to_ascii_lowercase());
194                    state = St::Scheme;
195                }
196                _ => {
197                    if ov.is_none() {
198                        state = St::NoScheme;
199                        p -= 1;
200                    } else {
201                        return Err(());
202                    }
203                }
204            },
205            St::Scheme => match c {
206                Some(ch) if ch.is_ascii_alphanumeric() || matches!(ch, '+' | '-' | '.') => buf.push(ch.to_ascii_lowercase()),
207                Some(':') => {
208                    if ov.is_some() {
209                        if is_special(&url.scheme) != is_special(&buf) {
210                            return Ok(url);
211                        }
212                        if (has_creds_or_port(&url)) && buf == "file" {
213                            return Ok(url);
214                        }
215                        if url.scheme == "file" && url.host.as_deref() == Some("") {
216                            return Ok(url);
217                        }
218                    }
219                    url.scheme = core::mem::take(&mut buf);
220                    if ov.is_some() {
221                        if default_port(&url.scheme) == url.port {
222                            url.port = None;
223                        }
224                        return Ok(url);
225                    }
226                    let special = is_special(&url.scheme);
227                    if url.scheme == "file" {
228                        state = St::File;
229                    } else if special && base.is_some_and(|b| b.scheme == url.scheme) {
230                        state = St::SpecialRelOrAuth;
231                    } else if special {
232                        state = St::SpecialAuthSlashes;
233                    } else if remaining.first() == Some(&'/') {
234                        state = St::PathOrAuth;
235                        p += 1;
236                    } else {
237                        url.opaque = Some(String::new());
238                        state = St::OpaquePath;
239                    }
240                }
241                _ => {
242                    if ov.is_none() {
243                        buf.clear();
244                        state = St::NoScheme;
245                        p = -1;
246                    } else {
247                        return Err(());
248                    }
249                }
250            },
251            St::NoScheme => {
252                let b = match base {
253                    Some(b) => b,
254                    None => return Err(()),
255                };
256                if b.opaque.is_some() && c != Some('#') {
257                    return Err(());
258                }
259                if b.opaque.is_some() {
260                    url.scheme = b.scheme.clone();
261                    url.path = b.path.clone();
262                    url.opaque = b.opaque.clone();
263                    url.query = b.query.clone();
264                    url.fragment = Some(String::new());
265                    state = St::Fragment;
266                } else if b.scheme != "file" {
267                    state = St::Relative;
268                    p -= 1;
269                } else {
270                    state = St::File;
271                    p -= 1;
272                }
273            }
274            St::SpecialRelOrAuth => {
275                if c == Some('/') && remaining.first() == Some(&'/') {
276                    state = St::SpecialAuthIgnoreSlashes;
277                    p += 1;
278                } else {
279                    state = St::Relative;
280                    p -= 1;
281                }
282            }
283            St::PathOrAuth => {
284                if c == Some('/') {
285                    state = St::Authority;
286                } else {
287                    state = St::Path;
288                    p -= 1;
289                }
290            }
291            St::Relative => {
292                let b = base.ok_or(())?;
293                url.scheme = b.scheme.clone();
294                let special = is_special(&url.scheme);
295                if c == Some('/') || (special && c == Some('\\')) {
296                    state = St::RelativeSlash;
297                } else {
298                    url.username = b.username.clone();
299                    url.password = b.password.clone();
300                    url.host = b.host.clone();
301                    url.port = b.port;
302                    url.path = b.path.clone();
303                    url.query = b.query.clone();
304                    if c == Some('?') {
305                        url.query = Some(String::new());
306                        state = St::Query;
307                    } else if c == Some('#') {
308                        url.fragment = Some(String::new());
309                        state = St::Fragment;
310                    } else if c.is_some() {
311                        url.query = None;
312                        shorten(&mut url);
313                        state = St::Path;
314                        p -= 1;
315                    }
316                }
317            }
318            St::RelativeSlash => {
319                if special && (c == Some('/') || c == Some('\\')) {
320                    state = St::SpecialAuthIgnoreSlashes;
321                } else if c == Some('/') {
322                    state = St::Authority;
323                } else {
324                    let b = base.ok_or(())?;
325                    url.username = b.username.clone();
326                    url.password = b.password.clone();
327                    url.host = b.host.clone();
328                    url.port = b.port;
329                    state = St::Path;
330                    p -= 1;
331                }
332            }
333            St::SpecialAuthSlashes => {
334                state = St::SpecialAuthIgnoreSlashes;
335                if c == Some('/') && remaining.first() == Some(&'/') {
336                    p += 1;
337                } else {
338                    p -= 1;
339                }
340            }
341            St::SpecialAuthIgnoreSlashes => {
342                if c != Some('/') && c != Some('\\') {
343                    state = St::Authority;
344                    p -= 1;
345                }
346            }
347            St::Authority => {
348                if c == Some('@') {
349                    if at_seen {
350                        buf.insert_str(0, "%40");
351                    }
352                    at_seen = true;
353                    for cp in buf.chars() {
354                        if cp == ':' && !pw_seen {
355                            pw_seen = true;
356                            continue;
357                        }
358                        if pw_seen {
359                            enc_char(&mut url.password, cp, set_userinfo);
360                        } else {
361                            enc_char(&mut url.username, cp, set_userinfo);
362                        }
363                    }
364                    buf.clear();
365                } else if c.is_none() || matches!(c, Some('/') | Some('?') | Some('#')) || (special && c == Some('\\')) {
366                    if at_seen && buf.is_empty() {
367                        return Err(());
368                    }
369                    p -= buf.chars().count() as isize + 1;
370                    buf.clear();
371                    state = St::Host;
372                } else if let Some(ch) = c {
373                    buf.push(ch);
374                }
375            }
376            St::Host | St::Hostname => {
377                if ov.is_some() && url.scheme == "file" {
378                    p -= 1;
379                    state = St::FileHost;
380                } else if c == Some(':') && !inbr {
381                    if buf.is_empty() {
382                        return Err(());
383                    }
384                    if ov == Some(St::Hostname) {
385                        return Err(());
386                    }
387                    let h = host_parse(&buf, !special)?;
388                    url.host = Some(h);
389                    buf.clear();
390                    state = St::Port;
391                } else if c.is_none() || matches!(c, Some('/') | Some('?') | Some('#')) || (special && c == Some('\\')) {
392                    p -= 1;
393                    if (special && buf.is_empty()) || (ov.is_some() && buf.is_empty() && has_creds_or_port(&url)) {
394                        return Err(());
395                    }
396                    let h = host_parse(&buf, !special)?;
397                    url.host = Some(h);
398                    buf.clear();
399                    state = St::PathStart;
400                    if ov.is_some() {
401                        return Ok(url);
402                    }
403                } else if let Some(ch) = c {
404                    if ch == '[' {
405                        inbr = true;
406                    }
407                    if ch == ']' {
408                        inbr = false;
409                    }
410                    buf.push(ch);
411                }
412            }
413            St::Port => {
414                if let Some(ch) = c.filter(|ch| ch.is_ascii_digit()) {
415                    buf.push(ch);
416                } else if c.is_none() || matches!(c, Some('/') | Some('?') | Some('#')) || (special && c == Some('\\')) || ov.is_some() {
417                    if !buf.is_empty() {
418                        let mut n: u32 = 0;
419                        for d in buf.chars() {
420                            n = n.saturating_mul(10).saturating_add(d as u32 - '0' as u32);
421                            if n > 65535 {
422                                return Err(());
423                            }
424                        }
425                        url.port = if default_port(&url.scheme) == Some(n as u16) { None } else { Some(n as u16) };
426                        buf.clear();
427                        if ov.is_some() {
428                            return Ok(url);
429                        }
430                    }
431                    if ov.is_some() {
432                        return Err(());
433                    }
434                    state = St::PathStart;
435                    p -= 1;
436                } else {
437                    return Err(());
438                }
439            }
440            St::File => {
441                url.scheme = String::from("file");
442                url.host = Some(String::new());
443                if c == Some('/') || c == Some('\\') {
444                    state = St::FileSlash;
445                } else if let Some(b) = base.filter(|b| b.scheme == "file") {
446                    url.host = b.host.clone();
447                    url.path = b.path.clone();
448                    url.query = b.query.clone();
449                    if c == Some('?') {
450                        url.query = Some(String::new());
451                        state = St::Query;
452                    } else if c == Some('#') {
453                        url.fragment = Some(String::new());
454                        state = St::Fragment;
455                    } else if c.is_some() {
456                        url.query = None;
457                        let cur: &[char] = &chars[p as usize..];
458                        if !starts_with_wdl(cur) {
459                            shorten(&mut url);
460                        } else {
461                            url.path.clear();
462                        }
463                        state = St::Path;
464                        p -= 1;
465                    }
466                } else {
467                    state = St::Path;
468                    p -= 1;
469                }
470            }
471            St::FileSlash => {
472                if c == Some('/') || c == Some('\\') {
473                    state = St::FileHost;
474                } else {
475                    if let Some(b) = base.filter(|b| b.scheme == "file") {
476                        url.host = b.host.clone();
477                        let cur: &[char] = &chars[(p.max(0) as usize).min(chars.len())..];
478                        if !starts_with_wdl(cur) {
479                            if let Some(f) = b.path.first() {
480                                if is_normalized_wdl(f) {
481                                    url.path.push(f.clone());
482                                }
483                            }
484                        }
485                    }
486                    state = St::Path;
487                    p -= 1;
488                }
489            }
490            St::FileHost => {
491                if c.is_none() || matches!(c, Some('/') | Some('\\') | Some('?') | Some('#')) {
492                    p -= 1;
493                    if ov.is_none() && is_wdl(&buf) {
494                        state = St::Path;
495                    } else if buf.is_empty() {
496                        url.host = Some(String::new());
497                        if ov.is_some() {
498                            return Ok(url);
499                        }
500                        state = St::PathStart;
501                    } else {
502                        let mut h = host_parse(&buf, !special)?;
503                        if h == "localhost" {
504                            h.clear();
505                        }
506                        url.host = Some(h);
507                        if ov.is_some() {
508                            return Ok(url);
509                        }
510                        buf.clear();
511                        state = St::PathStart;
512                    }
513                } else if let Some(ch) = c {
514                    buf.push(ch);
515                }
516            }
517            St::PathStart => {
518                if special {
519                    state = St::Path;
520                    if c != Some('/') && c != Some('\\') {
521                        p -= 1;
522                    }
523                } else if ov.is_none() && c == Some('?') {
524                    url.query = Some(String::new());
525                    state = St::Query;
526                } else if ov.is_none() && c == Some('#') {
527                    url.fragment = Some(String::new());
528                    state = St::Fragment;
529                } else if c.is_some() {
530                    state = St::Path;
531                    if c != Some('/') {
532                        p -= 1;
533                    }
534                } else if ov.is_some() && url.host.is_none() {
535                    url.path.push(String::new());
536                }
537            }
538            St::Path => {
539                let slash = c == Some('/') || (special && c == Some('\\'));
540                if c.is_none() || slash || (ov.is_none() && matches!(c, Some('?') | Some('#'))) {
541                    if is_double_dot(&buf) {
542                        shorten(&mut url);
543                        if !slash {
544                            url.path.push(String::new());
545                        }
546                    } else if is_single_dot(&buf) && !slash {
547                        url.path.push(String::new());
548                    } else if !is_single_dot(&buf) {
549                        if url.scheme == "file" && url.path.is_empty() && is_wdl(&buf) {
550                            if url.host.as_deref().is_some_and(|h| !h.is_empty()) {
551                                url.host = Some(String::new());
552                            }
553                            let first = buf.chars().next().unwrap_or('c');
554                            buf = alloc::format!("{}:", first);
555                        }
556                        url.path.push(core::mem::take(&mut buf));
557                    }
558                    buf.clear();
559                    if c == Some('?') {
560                        url.query = Some(String::new());
561                        state = St::Query;
562                    }
563                    if c == Some('#') {
564                        url.fragment = Some(String::new());
565                        state = St::Fragment;
566                    }
567                } else if let Some(ch) = c {
568                    enc_char(&mut buf, ch, set_path);
569                }
570            }
571            St::OpaquePath => {
572                if c == Some('?') {
573                    url.query = Some(String::new());
574                    state = St::Query;
575                } else if c == Some('#') {
576                    url.fragment = Some(String::new());
577                    state = St::Fragment;
578                } else if let Some(ch) = c {
579                    let o = url.opaque.get_or_insert_with(String::new);
580                    if ch == ' ' {
581                        if matches!(remaining.first(), Some('?') | Some('#')) {
582                            o.push_str("%20");
583                        } else {
584                            o.push(' ');
585                        }
586                    } else {
587                        enc_char(o, ch, c0);
588                    }
589                }
590            }
591            St::Query => {
592                if (ov.is_none() && c == Some('#')) || c.is_none() {
593                    let set: fn(char) -> bool = if special { set_special_query } else { set_query };
594                    let enc = encode_with(&buf, set);
595                    url.query.get_or_insert_with(String::new).push_str(&enc);
596                    buf.clear();
597                    if c == Some('#') {
598                        url.fragment = Some(String::new());
599                        state = St::Fragment;
600                    }
601                } else if let Some(ch) = c {
602                    buf.push(ch);
603                }
604            }
605            St::Fragment => {
606                if let Some(ch) = c {
607                    let f = url.fragment.get_or_insert_with(String::new);
608                    enc_char(f, ch, set_fragment);
609                }
610            }
611        }
612        if p >= len {
613            break;
614        }
615        p += 1;
616    }
617    Ok(url)
618}
619
620pub fn parse(input: &str, base: Option<&str>) -> Option<Url> {
621    let b = match base {
622        Some(b) => Some(basic_parse(b, None, None, None).ok()?),
623        None => None,
624    };
625    basic_parse(input, b.as_ref(), None, None).ok()
626}
627
628// ===== ホスト =====
629
630fn forbidden_host(c: char) -> bool {
631    matches!(c, '\0' | '\t' | '\n' | '\r' | ' ' | '#' | '/' | ':' | '<' | '>' | '?' | '@' | '[' | '\\' | ']' | '^' | '|')
632}
633fn forbidden_domain(c: char) -> bool {
634    forbidden_host(c) || (c as u32) <= 0x1f || c == '%' || c == '\u{7f}'
635}
636
637pub fn host_parse(input: &str, opaque: bool) -> Result<String, ()> {
638    if let Some(rest) = input.strip_prefix('[') {
639        let inner = rest.strip_suffix(']').ok_or(())?;
640        let a = ipv6_parse(inner)?;
641        return Ok(alloc::format!("[{}]", ipv6_serialize(&a)));
642    }
643    if opaque {
644        if input.chars().any(forbidden_host) {
645            return Err(());
646        }
647        return Ok(encode_with(input, c0));
648    }
649    let bytes = percent_decode_bytes(input);
650    let domain = String::from_utf8_lossy(&bytes).into_owned();
651    let ascii = domain_to_ascii(&domain)?;
652    if ascii.is_empty() || ascii.chars().any(forbidden_domain) {
653        return Err(());
654    }
655    if ends_in_number(&ascii) {
656        let v = ipv4_parse(&ascii)?;
657        return Ok(alloc::format!("{}.{}.{}.{}", v >> 24, (v >> 16) & 255, (v >> 8) & 255, v & 255));
658    }
659    Ok(ascii)
660}
661
662fn ends_in_number(s: &str) -> bool {
663    let mut parts: Vec<&str> = s.split('.').collect();
664    if parts.last() == Some(&"") {
665        if parts.len() == 1 {
666            return false;
667        }
668        parts.pop();
669    }
670    let last = parts.last().copied().unwrap_or("");
671    if !last.is_empty() && last.bytes().all(|b| b.is_ascii_digit()) {
672        return true;
673    }
674    ipv4_number(last).is_ok()
675}
676
677fn ipv4_number(s: &str) -> Result<u64, ()> {
678    if s.is_empty() {
679        return Err(());
680    }
681    let (digits, radix) = if let Some(r) = s.strip_prefix("0x").or_else(|| s.strip_prefix("0X")) {
682        (r, 16)
683    } else if s.len() >= 2 && s.starts_with('0') {
684        (s.get(1..).unwrap_or(""), 8)
685    } else {
686        (s, 10)
687    };
688    if digits.is_empty() {
689        return Ok(0);
690    }
691    let mut n: u64 = 0;
692    for ch in digits.chars() {
693        let d = ch.to_digit(radix).ok_or(())? as u64;
694        n = n.saturating_mul(radix as u64).saturating_add(d);
695    }
696    Ok(n)
697}
698
699fn ipv4_parse(s: &str) -> Result<u32, ()> {
700    let mut parts: Vec<&str> = s.split('.').collect();
701    if parts.last() == Some(&"") && parts.len() > 1 {
702        parts.pop();
703    }
704    if parts.len() > 4 {
705        return Err(());
706    }
707    let mut nums = Vec::new();
708    for p in &parts {
709        nums.push(ipv4_number(p)?);
710    }
711    let n = nums.len();
712    for v in nums.iter().take(n - 1) {
713        if *v > 255 {
714            return Err(());
715        }
716    }
717    let last = nums[n - 1];
718    if last >= 256u64.pow((5 - n) as u32) {
719        return Err(());
720    }
721    let mut ip = last;
722    for (i, v) in nums.iter().take(n - 1).enumerate() {
723        ip += v * 256u64.pow((3 - i) as u32);
724    }
725    Ok(ip as u32)
726}
727
728fn ipv6_parse(input: &str) -> Result<[u16; 8], ()> {
729    let c: Vec<char> = input.chars().collect();
730    let mut addr = [0u16; 8];
731    let mut piece = 0usize;
732    let mut compress: Option<usize> = None;
733    let mut p = 0usize;
734    let at = |i: usize| c.get(i).copied();
735    if at(p) == Some(':') {
736        if at(p + 1) != Some(':') {
737            return Err(());
738        }
739        p += 2;
740        piece += 1;
741        compress = Some(piece);
742    }
743    while p < c.len() {
744        if piece == 8 {
745            return Err(());
746        }
747        if at(p) == Some(':') {
748            if compress.is_some() {
749                return Err(());
750            }
751            p += 1;
752            piece += 1;
753            compress = Some(piece);
754            continue;
755        }
756        let (mut value, mut length) = (0u32, 0);
757        while length < 4 {
758            match at(p).and_then(|ch| ch.to_digit(16)) {
759                Some(d) => {
760                    value = value * 16 + d;
761                    p += 1;
762                    length += 1;
763                }
764                None => break,
765            }
766        }
767        if at(p) == Some('.') {
768            if length == 0 {
769                return Err(());
770            }
771            p -= length;
772            if piece > 6 {
773                return Err(());
774            }
775            let mut seen = 0;
776            while p < c.len() {
777                let mut v4: Option<u32> = None;
778                if seen > 0 {
779                    if at(p) == Some('.') && seen < 4 {
780                        p += 1;
781                    } else {
782                        return Err(());
783                    }
784                }
785                if !at(p).is_some_and(|ch| ch.is_ascii_digit()) {
786                    return Err(());
787                }
788                while let Some(d) = at(p).and_then(|ch| ch.to_digit(10)) {
789                    match v4 {
790                        None => v4 = Some(d),
791                        Some(0) => return Err(()),
792                        Some(v) => v4 = Some(v * 10 + d),
793                    }
794                    if v4.unwrap_or(0) > 255 {
795                        return Err(());
796                    }
797                    p += 1;
798                }
799                addr[piece] = (addr[piece] as u32 * 0x100 + v4.unwrap_or(0)) as u16;
800                seen += 1;
801                if seen == 2 || seen == 4 {
802                    piece += 1;
803                }
804            }
805            if seen != 4 {
806                return Err(());
807            }
808            break;
809        } else if at(p) == Some(':') {
810            p += 1;
811            if p >= c.len() {
812                return Err(());
813            }
814        } else if p < c.len() {
815            return Err(());
816        }
817        addr[piece] = value as u16;
818        piece += 1;
819    }
820    if let Some(cm) = compress {
821        let mut swaps = piece - cm;
822        piece = 7;
823        while piece != 0 && swaps > 0 {
824            addr.swap(piece, cm + swaps - 1);
825            piece -= 1;
826            swaps -= 1;
827        }
828    } else if piece != 8 {
829        return Err(());
830    }
831    Ok(addr)
832}
833
834fn ipv6_serialize(a: &[u16; 8]) -> String {
835    let (mut best, mut best_len, mut i) = (usize::MAX, 0usize, 0usize);
836    while i < 8 {
837        if a[i] == 0 {
838            let s = i;
839            while i < 8 && a[i] == 0 {
840                i += 1;
841            }
842            if i - s > best_len && i - s > 1 {
843                best = s;
844                best_len = i - s;
845            }
846        } else {
847            i += 1;
848        }
849    }
850    let mut out = String::new();
851    let mut ignore0 = false;
852    for (idx, v) in a.iter().enumerate() {
853        if ignore0 && *v == 0 {
854            continue;
855        }
856        ignore0 = false;
857        if best == idx {
858            out.push_str(if idx == 0 { "::" } else { ":" });
859            ignore0 = true;
860            continue;
861        }
862        out.push_str(&alloc::format!("{:x}", v));
863        if idx != 7 {
864            out.push(':');
865        }
866    }
867    out
868}
869
870// ===== IDNA(簡易)と Punycode =====
871
872pub fn domain_to_ascii(s: &str) -> Result<String, ()> {
873    let mut mapped = String::new();
874    for ch in s.chars() {
875        let u = ch as u32;
876        match u {
877            0xAD | 0x200B | 0x2060 | 0xFEFF | 0x34F | 0x180B..=0x180D | 0xFE00..=0xFE0F => {}
878            0x3002 | 0xFF0E | 0xFF61 => mapped.push('.'),
879            0xFF01..=0xFF5E => {
880                if let Some(a) = char::from_u32(u - 0xFEE0) {
881                    mapped.push(a.to_ascii_lowercase());
882                }
883            }
884            _ => {
885                for l in ch.to_lowercase() {
886                    mapped.push(l);
887                }
888            }
889        }
890    }
891    let mut out = String::new();
892    for (i, label) in mapped.split('.').enumerate() {
893        if i > 0 {
894            out.push('.');
895        }
896        if label.is_ascii() {
897            if let Some(rest) = label.strip_prefix("xn--") {
898                let dec = punycode_decode(rest).ok_or(())?;
899                if dec.is_empty() || dec.is_ascii() {
900                    return Err(());
901                }
902                let re = punycode_encode(&dec).ok_or(())?;
903                if re != rest {
904                    return Err(());
905                }
906            }
907            out.push_str(label);
908        } else {
909            out.push_str("xn--");
910            out.push_str(&punycode_encode(label).ok_or(())?);
911        }
912    }
913    Ok(out)
914}
915
916fn adapt(mut delta: u32, num: u32, first: bool) -> u32 {
917    delta = if first { delta / 700 } else { delta / 2 };
918    delta += delta / num;
919    let mut k = 0;
920    while delta > ((36 - 1) * 26) / 2 {
921        delta /= 36 - 1;
922        k += 36;
923    }
924    k + (36 * delta) / (delta + 38)
925}
926fn digit_char(d: u32) -> char {
927    if d < 26 {
928        (b'a' + d as u8) as char
929    } else {
930        (b'0' + (d - 26) as u8) as char
931    }
932}
933fn punycode_encode(s: &str) -> Option<String> {
934    let cps: Vec<u32> = s.chars().map(|c| c as u32).collect();
935    let mut out = String::new();
936    for &c in &cps {
937        if c < 128 {
938            out.push(c as u8 as char);
939        }
940    }
941    let b = out.len() as u32;
942    let mut h = b;
943    if b > 0 {
944        out.push('-');
945    }
946    let (mut n, mut delta, mut bias) = (128u32, 0u32, 72u32);
947    while (h as usize) < cps.len() {
948        let m = cps.iter().copied().filter(|&c| c >= n).min()?;
949        delta = delta.checked_add((m - n).checked_mul(h + 1)?)?;
950        n = m;
951        for &c in &cps {
952            if c < n {
953                delta = delta.checked_add(1)?;
954            }
955            if c == n {
956                let mut q = delta;
957                let mut k = 36;
958                loop {
959                    let t = if k <= bias { 1 } else if k >= bias + 26 { 26 } else { k - bias };
960                    if q < t {
961                        break;
962                    }
963                    out.push(digit_char(t + (q - t) % (36 - t)));
964                    q = (q - t) / (36 - t);
965                    k += 36;
966                }
967                out.push(digit_char(q));
968                bias = adapt(delta, h + 1, h == b);
969                delta = 0;
970                h += 1;
971            }
972        }
973        delta += 1;
974        n += 1;
975    }
976    Some(out)
977}
978fn punycode_decode(s: &str) -> Option<String> {
979    let (basic, ext) = match s.rfind('-') {
980        Some(i) => (s.get(..i)?, s.get(i + 1..)?),
981        None => ("", s),
982    };
983    let mut out: Vec<u32> = basic.chars().map(|c| c as u32).collect();
984    if !basic.is_ascii() {
985        return None;
986    }
987    let (mut n, mut i, mut bias) = (128u32, 0u32, 72u32);
988    let e: Vec<char> = ext.chars().collect();
989    let mut p = 0;
990    while p < e.len() {
991        let oldi = i;
992        let mut w = 1u32;
993        let mut k = 36;
994        loop {
995            let ch = *e.get(p)?;
996            p += 1;
997            let d = match ch {
998                'a'..='z' => ch as u32 - 'a' as u32,
999                'A'..='Z' => ch as u32 - 'A' as u32,
1000                '0'..='9' => ch as u32 - '0' as u32 + 26,
1001                _ => return None,
1002            };
1003            i = i.checked_add(d.checked_mul(w)?)?;
1004            let t = if k <= bias { 1 } else if k >= bias + 26 { 26 } else { k - bias };
1005            if d < t {
1006                break;
1007            }
1008            w = w.checked_mul(36 - t)?;
1009            k += 36;
1010        }
1011        let len = out.len() as u32 + 1;
1012        bias = adapt(i - oldi, len, oldi == 0);
1013        n = n.checked_add(i / len)?;
1014        i %= len;
1015        out.insert(i as usize, n);
1016        i += 1;
1017    }
1018    out.into_iter().map(char::from_u32).collect()
1019}
1020
1021// ===== シリアライズ =====
1022
1023pub fn path_string(u: &Url) -> String {
1024    if let Some(o) = &u.opaque {
1025        return o.clone();
1026    }
1027    let mut s = String::new();
1028    for seg in &u.path {
1029        s.push('/');
1030        s.push_str(seg);
1031    }
1032    s
1033}
1034
1035pub fn serialize(u: &Url, exclude_fragment: bool) -> String {
1036    let mut o = String::new();
1037    o.push_str(&u.scheme);
1038    o.push(':');
1039    if let Some(h) = &u.host {
1040        o.push_str("//");
1041        if !u.username.is_empty() || !u.password.is_empty() {
1042            o.push_str(&u.username);
1043            if !u.password.is_empty() {
1044                o.push(':');
1045                o.push_str(&u.password);
1046            }
1047            o.push('@');
1048        }
1049        o.push_str(h);
1050        if let Some(p) = u.port {
1051            o.push(':');
1052            o.push_str(&alloc::format!("{}", p));
1053        }
1054    } else if u.opaque.is_none() && u.path.len() > 1 && u.path[0].is_empty() {
1055        o.push_str("/.");
1056    }
1057    o.push_str(&path_string(u));
1058    if let Some(q) = &u.query {
1059        o.push('?');
1060        o.push_str(q);
1061    }
1062    if !exclude_fragment {
1063        if let Some(f) = &u.fragment {
1064            o.push('#');
1065            o.push_str(f);
1066        }
1067    }
1068    o
1069}
1070
1071pub fn origin(u: &Url) -> String {
1072    match u.scheme.as_str() {
1073        "http" | "https" | "ws" | "wss" | "ftp" => {
1074            let mut s = alloc::format!("{}://{}", u.scheme, u.host.clone().unwrap_or_default());
1075            if let Some(p) = u.port {
1076                s.push_str(&alloc::format!(":{}", p));
1077            }
1078            s
1079        }
1080        "blob" => match parse(&path_string(u), None) {
1081            Some(inner) if matches!(inner.scheme.as_str(), "http" | "https") => origin(&inner),
1082            _ => String::from("null"),
1083        },
1084        _ => String::from("null"),
1085    }
1086}
1087
1088// ===== セッター(URL Standard の API の節)=====
1089
1090fn strip_trailing_spaces_opaque(u: &mut Url) {
1091    if u.fragment.is_some() || u.query.is_some() {
1092        return;
1093    }
1094    if let Some(o) = &mut u.opaque {
1095        while o.ends_with(' ') {
1096            o.pop();
1097        }
1098    }
1099}
1100
1101/// `name` は "protocol" "username" "password" "host" "hostname" "port" "pathname" "search" "hash"。
1102pub fn apply_setter(u: &mut Url, name: &str, v: &str) {
1103    match name {
1104        "protocol" => {
1105            let mut s = String::from(v);
1106            s.push(':');
1107            if let Ok(n) = basic_parse(&s, None, Some(u.clone()), Some(St::SchemeStart)) {
1108                *u = n;
1109            }
1110        }
1111        "username" | "password" => {
1112            if u.host.as_deref().is_none_or(|h| h.is_empty()) || u.scheme == "file" {
1113                return;
1114            }
1115            let e = encode_userinfo(v);
1116            if name == "username" {
1117                u.username = e;
1118            } else {
1119                u.password = e;
1120            }
1121        }
1122        "host" | "hostname" => {
1123            if u.opaque.is_some() {
1124                return;
1125            }
1126            let st = if name == "host" { St::Host } else { St::Hostname };
1127            if let Ok(n) = basic_parse(v, None, Some(u.clone()), Some(st)) {
1128                *u = n;
1129            }
1130        }
1131        "port" => {
1132            if u.host.as_deref().is_none_or(|h| h.is_empty()) || u.scheme == "file" {
1133                return;
1134            }
1135            if v.is_empty() {
1136                u.port = None;
1137            } else if let Ok(n) = basic_parse(v, None, Some(u.clone()), Some(St::Port)) {
1138                *u = n;
1139            }
1140        }
1141        "pathname" => {
1142            if u.opaque.is_some() {
1143                return;
1144            }
1145            let mut c = u.clone();
1146            c.path.clear();
1147            if let Ok(n) = basic_parse(v, None, Some(c), Some(St::PathStart)) {
1148                *u = n;
1149            }
1150        }
1151        "search" => {
1152            if v.is_empty() {
1153                u.query = None;
1154                strip_trailing_spaces_opaque(u);
1155                return;
1156            }
1157            let input = v.strip_prefix('?').unwrap_or(v);
1158            let mut c = u.clone();
1159            c.query = Some(String::new());
1160            if let Ok(n) = basic_parse(input, None, Some(c), Some(St::Query)) {
1161                *u = n;
1162            }
1163        }
1164        "hash" => {
1165            if v.is_empty() {
1166                u.fragment = None;
1167                strip_trailing_spaces_opaque(u);
1168                return;
1169            }
1170            let input = v.strip_prefix('#').unwrap_or(v);
1171            let mut c = u.clone();
1172            c.fragment = Some(String::new());
1173            if let Ok(n) = basic_parse(input, None, Some(c), Some(St::Fragment)) {
1174                *u = n;
1175            }
1176        }
1177        _ => {}
1178    }
1179}