prost-protovalidate 0.6.0

Runtime validation for Protocol Buffer messages using buf.validate rules
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
//! Format validators for well-known string constraints.
//!
//! Pure `&str -> bool` checks (email, hostname, IP, URI, UUID, ULID, host
//! and port, HTTP headers, CIDR prefixes) shared by three consumers: the
//! `string` rule evaluator, the public [`crate::validators`] facade used by
//! generated code, and the CEL standard-function shims.

use std::net::{Ipv4Addr, Ipv6Addr};
use std::str::FromStr;
use std::sync::LazyLock;

use regex::Regex;

static EMAIL_REGEX: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new("^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$")
        .expect("email regex must compile")
});
static ULID_REGEX: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new("^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$").expect("ulid regex must compile")
});

/// Strict HTTP header name: token chars per RFC 7230's `token` rule.
/// Allowed characters: `!#$%&'*+-.0-9A-Za-z^_``|~`, with optional `:` prefix for pseudo-headers.
pub(crate) fn is_valid_http_header_name_strict(s: &str) -> bool {
    if s.is_empty() {
        return false;
    }
    // Only ASCII
    let bytes = s.as_bytes();
    // Optional leading colon (pseudo-header), but `:` alone is not valid
    let start = usize::from(bytes[0] == b':');
    if start >= bytes.len() {
        return false;
    }
    // Trailing colon is not allowed
    if bytes[bytes.len() - 1] == b':' {
        return false;
    }
    for &b in &bytes[start..] {
        if !is_token_char(b) {
            return false;
        }
    }
    true
}

/// Token characters per RFC 7230 ยง3.2.6
fn is_token_char(b: u8) -> bool {
    matches!(b,
        b'!' | b'#' | b'$' | b'%' | b'&' | b'\'' | b'*' | b'+' | b'-' | b'.' |
        b'0'..=b'9' |
        b'A'..=b'Z' |
        b'^' | b'_' | b'`' |
        b'a'..=b'z' |
        b'|' | b'~'
    )
}

/// Loose HTTP header name: any non-empty string without NUL, CR, or LF.
pub(crate) fn is_valid_http_header_name_loose(s: &str) -> bool {
    if s.is_empty() {
        return false;
    }
    !s.bytes().any(|b| b == 0x00 || b == 0x0A || b == 0x0D)
}

/// Strict HTTP header value: no NUL, control chars (0x00-0x08, 0x0A-0x1F), or DEL (0x7F).
/// HT (0x09) IS allowed per RFC 7230.
pub(crate) fn is_valid_http_header_value_strict(s: &str) -> bool {
    !s.bytes()
        .any(|b| matches!(b, 0x00..=0x08 | 0x0A..=0x1F | 0x7F))
}

/// Loose HTTP header value: no NUL, CR, or LF.
pub(crate) fn is_valid_http_header_value_loose(s: &str) -> bool {
    !s.bytes().any(|b| b == 0x00 || b == 0x0A || b == 0x0D)
}

pub(crate) fn is_email(s: &str) -> bool {
    if s != s.trim() || s.contains(char::is_whitespace) {
        return false;
    }
    if !s.is_ascii() {
        return false;
    }
    let Some((local, domain)) = s.split_once('@') else {
        return false;
    };
    if local.is_empty() || domain.is_empty() {
        return false;
    }
    // Reject quoted strings, comments, and mailbox format
    if local.contains('"') || local.contains('(') || local.contains('<') {
        return false;
    }
    // Local part: only unreserved characters
    if !EMAIL_REGEX.is_match(s) {
        return false;
    }
    // Domain must be a valid hostname (not IP literal)
    if domain.starts_with('[') {
        return false;
    }
    // Reject trailing dot in domain
    if domain.ends_with('.') {
        return false;
    }
    // Email domain: valid labels but no "last label must not be all digits" rule
    is_email_domain(domain)
}

pub(crate) fn is_hostname(s: &str) -> bool {
    if s != s.trim() {
        return false;
    }
    if !s.is_ascii() {
        return false;
    }
    let s = s.strip_suffix('.').unwrap_or(s);
    if s.is_empty() || s.len() > 253 {
        return false;
    }
    let labels: Vec<&str> = s.split('.').collect();
    if labels.is_empty() {
        return false;
    }
    for label in &labels {
        if label.is_empty() || label.len() > 63 {
            return false;
        }
        if label.starts_with('-') || label.ends_with('-') {
            return false;
        }
        if !label.chars().all(|c| c.is_ascii_alphanumeric() || c == '-') {
            return false;
        }
    }
    // Right-most label must not be all digits
    if let Some(last) = labels.last() {
        if last.chars().all(|c| c.is_ascii_digit()) {
            return false;
        }
    }
    true
}

/// Validate hostname labels for email domain (no "last label must not be all digits" rule).
fn is_email_domain(s: &str) -> bool {
    if s.is_empty() || s.len() > 253 {
        return false;
    }
    for label in s.split('.') {
        if label.is_empty() || label.len() > 63 {
            return false;
        }
        if label.starts_with('-') || label.ends_with('-') {
            return false;
        }
        if !label.chars().all(|c| c.is_ascii_alphanumeric() || c == '-') {
            return false;
        }
    }
    true
}

pub(crate) fn is_ip(s: &str) -> bool {
    if s.is_empty() || s != s.trim() {
        return false;
    }
    is_ipv4_strict(s) || is_ipv6_any(s)
}

pub(crate) fn is_ipv4_strict(s: &str) -> bool {
    if s != s.trim() {
        return false;
    }
    Ipv4Addr::from_str(s).is_ok()
}

/// Parse IPv6, accepting zone IDs (e.g., `fe80::1%eth0`).
fn is_ipv6_any(s: &str) -> bool {
    if s != s.trim() {
        return false;
    }
    // Split off zone ID
    let (addr, zone) = match s.find('%') {
        Some(idx) => (&s[..idx], Some(&s[idx + 1..])),
        None => (s, None),
    };
    // Reject empty zone IDs
    if let Some(z) = zone {
        if z.is_empty() {
            return false;
        }
    }
    Ipv6Addr::from_str(addr).is_ok()
}

/// Strict IPv6 without zone IDs.
#[cfg(feature = "cel")]
fn is_ipv6_strict(s: &str) -> bool {
    if s != s.trim() || s.contains('%') {
        return false;
    }
    Ipv6Addr::from_str(s).is_ok()
}

pub(crate) fn is_ipv6(s: &str) -> bool {
    is_ipv6_any(s)
}

pub(crate) fn is_uri(s: &str) -> bool {
    if !is_valid_uri_chars(s) {
        return false;
    }
    // Try parsing directly first.
    if let Ok(uri) = fluent_uri::Uri::parse(s) {
        return is_valid_uri_host(&uri);
    }
    // fluent_uri doesn't support RFC 6874 IPv6 zone IDs.
    // Strip the zone ID and retry.
    if let Some(stripped) = strip_ipv6_zone_id(s) {
        if let Ok(uri) = fluent_uri::Uri::parse(stripped.as_str()) {
            return is_valid_uri_host(&uri);
        }
    }
    false
}

pub(crate) fn is_uri_ref(s: &str) -> bool {
    if !is_valid_uri_chars(s) {
        return false;
    }
    if let Ok(uri) = fluent_uri::UriRef::parse(s) {
        return is_valid_uri_ref_host(&uri);
    }
    if let Some(stripped) = strip_ipv6_zone_id(s) {
        if let Ok(uri) = fluent_uri::UriRef::parse(stripped.as_str()) {
            return is_valid_uri_ref_host(&uri);
        }
    }
    false
}

/// Check that a parsed URI's host reg-name (if present) has valid pct-encoded UTF-8.
fn is_valid_uri_host(uri: &fluent_uri::Uri<&str>) -> bool {
    let Some(authority) = uri.authority() else {
        return true;
    };
    is_valid_reg_name_utf8(authority.host())
}

/// Check that a parsed URI-reference's host reg-name has valid pct-encoded UTF-8.
fn is_valid_uri_ref_host(uri: &fluent_uri::UriRef<&str>) -> bool {
    let Some(authority) = uri.authority() else {
        return true;
    };
    is_valid_reg_name_utf8(authority.host())
}

/// Validate that pct-decoded bytes in a reg-name host form valid UTF-8.
/// IP-literal hosts (starting with `[`) are not checked.
fn is_valid_reg_name_utf8(host: &str) -> bool {
    // IP-literals are enclosed in brackets โ€” skip UTF-8 check.
    if host.starts_with('[') {
        return true;
    }
    let decoded = pct_decode_bytes(host);
    std::str::from_utf8(&decoded).is_ok()
}

/// Decode percent-encoded bytes in a string. Non-pct-encoded ASCII bytes
/// are passed through unchanged.
fn pct_decode_bytes(s: &str) -> Vec<u8> {
    let bytes = s.as_bytes();
    let mut out = Vec::with_capacity(bytes.len());
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i] == b'%' && i + 2 < bytes.len() {
            if let (Some(hi), Some(lo)) =
                (hex_digit_value(bytes[i + 1]), hex_digit_value(bytes[i + 2]))
            {
                out.push(hi << 4 | lo);
                i += 3;
                continue;
            }
        }
        out.push(bytes[i]);
        i += 1;
    }
    out
}

fn hex_digit_value(b: u8) -> Option<u8> {
    match b {
        b'0'..=b'9' => Some(b - b'0'),
        b'a'..=b'f' => Some(b - b'a' + 10),
        b'A'..=b'F' => Some(b - b'A' + 10),
        _ => None,
    }
}

/// Strip an IPv6 zone ID (RFC 6874) from a URI string.
/// Zone IDs appear as `%25<zone>` inside `[...]` IP-literal hosts.
/// Returns `None` if no zone ID is found, the zone ID is empty, or the
/// zone ID contains invalid characters / invalid pct-encoded UTF-8.
fn strip_ipv6_zone_id(s: &str) -> Option<String> {
    let bracket_open = s.find('[')?;
    let bracket_close = s[bracket_open..].find(']').map(|i| bracket_open + i)?;
    let host_inner = &s[bracket_open + 1..bracket_close];
    let zone_offset = host_inner.find("%25")?;
    let zone_id = &host_inner[zone_offset + 3..];
    // Reject empty zone IDs.
    if zone_id.is_empty() {
        return None;
    }
    // Validate zone ID characters: unreserved chars and valid pct-encoding.
    if !is_valid_zone_id(zone_id) {
        return None;
    }
    // Validate that pct-decoded zone ID is valid UTF-8.
    if std::str::from_utf8(&pct_decode_bytes(zone_id)).is_err() {
        return None;
    }
    // Reconstruct without the zone ID.
    let mut result = String::with_capacity(s.len());
    result.push_str(&s[..bracket_open + 1 + zone_offset]);
    result.push(']');
    result.push_str(&s[bracket_close + 1..]);
    Some(result)
}

/// Validate zone ID characters per RFC 6874:
/// `ZoneID = 1*( unreserved / pct-encoded )`
fn is_valid_zone_id(s: &str) -> bool {
    let bytes = s.as_bytes();
    let mut i = 0;
    while i < bytes.len() {
        let b = bytes[i];
        if b == b'%' {
            // Must be valid pct-encoding.
            if i + 2 >= bytes.len() {
                return false;
            }
            if !bytes[i + 1].is_ascii_hexdigit() || !bytes[i + 2].is_ascii_hexdigit() {
                return false;
            }
            i += 3;
        } else if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~') {
            // unreserved
            i += 1;
        } else {
            return false;
        }
    }
    true
}

/// Pre-validate URI characters per RFC 3986.
/// Reject control characters, spaces, carets, and invalid percent-encoding.
fn is_valid_uri_chars(s: &str) -> bool {
    if s != s.trim() {
        return false;
    }
    let bytes = s.as_bytes();
    let mut i = 0;
    while i < bytes.len() {
        let b = bytes[i];
        // Reject control characters (0x00-0x1F, 0x7F)
        if b <= 0x1F || b == 0x7F {
            return false;
        }
        // Reject space
        if b == b' ' {
            return false;
        }
        // Reject caret, backslash, backtick, curly braces, pipe
        if matches!(b, b'^' | b'\\' | b'{' | b'}' | b'|') {
            return false;
        }
        // Validate percent-encoding
        if b == b'%' {
            if i + 2 >= bytes.len() {
                return false;
            }
            if !bytes[i + 1].is_ascii_hexdigit() || !bytes[i + 2].is_ascii_hexdigit() {
                return false;
            }
            i += 3;
            continue;
        }
        // Reject non-ASCII
        if b > 0x7E {
            return false;
        }
        i += 1;
    }
    true
}

pub(crate) fn is_uuid(s: &str) -> bool {
    // UUID format: 8-4-4-4-12 hex digits
    if s.len() != 36 {
        return false;
    }
    let parts: Vec<&str> = s.split('-').collect();
    if parts.len() != 5 {
        return false;
    }
    let expected_lens = [8, 4, 4, 4, 12];
    for (part, &expected) in parts.iter().zip(&expected_lens) {
        if part.len() != expected || !part.chars().all(|c| c.is_ascii_hexdigit()) {
            return false;
        }
    }
    true
}

pub(crate) fn is_tuuid(s: &str) -> bool {
    s.len() == 32 && s.chars().all(|c| c.is_ascii_hexdigit())
}

pub(crate) fn is_ulid(s: &str) -> bool {
    ULID_REGEX.is_match(s)
}

/// Whether `s` is a single Protobuf identifier: `[A-Za-z_][A-Za-z0-9_]*`.
fn is_protobuf_ident(id: &str) -> bool {
    let mut chars = id.chars();
    match chars.next() {
        Some(c) if c == '_' || c.is_ascii_alphabetic() => {}
        _ => return false,
    }
    chars.all(|c| c == '_' || c.is_ascii_alphanumeric())
}

/// Whether `s` is a valid Protobuf fully-qualified name โ€” dot-separated
/// identifiers (`[A-Za-z_][A-Za-z0-9_]*`) โ€” optionally requiring a leading dot.
/// Mirrors protovalidate's `string.protobuf_fqn` / `string.protobuf_dot_fqn`
/// regexes. The empty string is handled by the caller's `_empty` rule, so this
/// returns `false` for it.
fn is_protobuf_name(s: &str, leading_dot: bool) -> bool {
    let body = if leading_dot {
        match s.strip_prefix('.') {
            Some(rest) => rest,
            None => return false,
        }
    } else if s.starts_with('.') {
        return false;
    } else {
        s
    };
    !body.is_empty() && body.split('.').all(is_protobuf_ident)
}

/// Whether `s` is a valid Protobuf fully-qualified name without a leading dot
/// (e.g. `foo.bar.Baz`).
pub(crate) fn is_protobuf_fqn(s: &str) -> bool {
    is_protobuf_name(s, false)
}

/// Whether `s` is a valid Protobuf fully-qualified name with a leading dot
/// (e.g. `.foo.bar.Baz`).
pub(crate) fn is_protobuf_dot_fqn(s: &str) -> bool {
    is_protobuf_name(s, true)
}

#[derive(Clone, Copy)]
#[cfg_attr(not(feature = "reflect"), allow(dead_code))]
pub(crate) enum IpVersion {
    Any,
    V4,
    V6,
}

#[cfg(feature = "cel")]
pub(crate) fn is_ip_with_version(s: &str, version: i64) -> bool {
    match version {
        0 => is_ip(s),
        4 => is_ipv4_strict(s),
        6 => is_ipv6_strict(s),
        _ => false,
    }
}

#[cfg(feature = "cel")]
pub(crate) fn is_ip_prefix_with_options(s: &str, version: i64, strict: bool) -> bool {
    let version = match version {
        0 => IpVersion::Any,
        4 => IpVersion::V4,
        6 => IpVersion::V6,
        _ => return false,
    };
    is_ip_prefix(s, version, strict)
}

#[cfg_attr(not(feature = "reflect"), allow(dead_code))]
pub(crate) fn is_ip_prefix(s: &str, version: IpVersion, strict: bool) -> bool {
    match version {
        IpVersion::Any => {
            is_ip_prefix(s, IpVersion::V4, strict) || is_ip_prefix(s, IpVersion::V6, strict)
        }
        IpVersion::V4 => is_ipv4_prefix(s, strict),
        IpVersion::V6 => is_ipv6_prefix(s, strict),
    }
}

pub(crate) fn is_ipv4_prefix(s: &str, strict: bool) -> bool {
    if s != s.trim() {
        return false;
    }
    let Some((address, prefix_len)) = split_prefix(s) else {
        return false;
    };
    if prefix_len > 32 {
        return false;
    }
    let Ok(ip) = Ipv4Addr::from_str(address) else {
        return false;
    };
    !strict || ipv4_is_prefix_only(ip, prefix_len)
}

pub(crate) fn is_ipv6_prefix(s: &str, strict: bool) -> bool {
    if s != s.trim() {
        return false;
    }
    let Some((address, prefix_len)) = split_prefix(s) else {
        return false;
    };
    if prefix_len > 128 {
        return false;
    }
    // Reject zone IDs in prefix notation
    if address.contains('%') {
        return false;
    }
    let Ok(ip) = Ipv6Addr::from_str(address) else {
        return false;
    };
    !strict || ipv6_is_prefix_only(ip, prefix_len)
}

fn split_prefix(s: &str) -> Option<(&str, u8)> {
    let (address, prefix) = s.split_once('/')?;
    if address.is_empty() || prefix.is_empty() {
        return None;
    }
    if prefix.len() > 1 && prefix.starts_with('0') {
        return None;
    }
    if !prefix.bytes().all(|byte| byte.is_ascii_digit()) {
        return None;
    }
    let parsed = prefix.parse::<u8>().ok()?;
    Some((address, parsed))
}

fn ipv4_is_prefix_only(ip: Ipv4Addr, prefix_len: u8) -> bool {
    let bits = u32::from(ip);
    let mask = if prefix_len == 0 {
        0
    } else {
        u32::MAX << (32 - u32::from(prefix_len))
    };
    bits == (bits & mask)
}

fn ipv6_is_prefix_only(ip: Ipv6Addr, prefix_len: u8) -> bool {
    let bits = u128::from(ip);
    let mask = if prefix_len == 0 {
        0
    } else {
        u128::MAX << (128 - u32::from(prefix_len))
    };
    bits == (bits & mask)
}

pub(crate) fn is_host_and_port(s: &str, port_required: bool) -> bool {
    if s.is_empty() || s != s.trim() {
        return false;
    }

    if s.starts_with('[') {
        let Some(bracket_end) = s.rfind(']') else {
            return false;
        };
        let host = &s[1..bracket_end];
        let after_host = &s[bracket_end + 1..];
        if after_host.is_empty() {
            return !port_required && is_ipv6_any(host);
        }
        let Some(port) = after_host.strip_prefix(':') else {
            return false;
        };
        return is_ipv6_any(host) && is_port(port);
    }

    // Reject bare names in brackets
    if s.contains('[') || s.contains(']') {
        return false;
    }

    let Some(split_idx) = s.rfind(':') else {
        return !port_required && (is_hostname(s) || is_ipv4_strict(s));
    };
    let host = &s[..split_idx];
    let port = &s[split_idx + 1..];
    (is_hostname(host) || is_ipv4_strict(host)) && is_port(port)
}

fn is_port(s: &str) -> bool {
    if s.is_empty() {
        return false;
    }
    if s.len() > 1 && s.starts_with('0') {
        return false;
    }
    if !s.bytes().all(|byte| byte.is_ascii_digit()) {
        return false;
    }
    s.parse::<u16>().is_ok()
}

#[cfg(test)]
mod tests {
    use pretty_assertions::assert_eq;

    use super::{
        IpVersion, hex_digit_value, is_host_and_port, is_ip_prefix, is_tuuid, is_ulid, is_uri,
        is_uri_ref, is_valid_reg_name_utf8, is_valid_zone_id, pct_decode_bytes, strip_ipv6_zone_id,
    };

    #[test]
    fn uri_ref_rejects_invalid_sequences() {
        assert!(is_uri_ref("https://example.com/path?q=1#f"));
        assert!(is_uri_ref("./foo/bar?baz=quux"));
        assert!(!is_uri_ref("http://exa mple.com"));
    }

    #[test]
    fn ip_prefix_strictness_matches_rule_modes() {
        assert!(is_ip_prefix("192.168.1.1/24", IpVersion::V4, false));
        assert!(!is_ip_prefix("192.168.1.1/24", IpVersion::V4, true));
        assert!(is_ip_prefix("192.168.1.0/24", IpVersion::V4, true));
        assert!(is_ip_prefix("2001:db8::1/64", IpVersion::V6, false));
        assert!(!is_ip_prefix("2001:db8::1/64", IpVersion::V6, true));
    }

    #[test]
    fn host_and_port_requires_valid_host_and_canonical_port() {
        assert!(is_host_and_port("example.com:8080", true));
        assert!(is_host_and_port("[2001:db8::1]:443", true));
        assert!(!is_host_and_port("not a host:80", true));
        assert!(!is_host_and_port("example.com:080", true));
        assert!(!is_host_and_port("[2001:db8::1]443", true));
    }

    #[test]
    fn additional_well_known_string_formats_validate() {
        assert!(is_tuuid("550e8400e29b41d4a716446655440000"));
        assert!(!is_tuuid("550e8400-e29b-41d4-a716-446655440000"));

        assert!(is_ulid("01ARZ3NDEKTSV4RRFFQ69G5FAV"));
        assert!(!is_ulid("81ARZ3NDEKTSV4RRFFQ69G5FAV"));
    }

    #[test]
    fn uri_helpers_never_panic_on_malformed_inputs() {
        let panic_inputs = [
            ".foo://example.com",
            "-foo://example.com",
            ":foo://example.com",
            "foo%20bar://example.com",
        ];

        for input in panic_inputs {
            assert!(!is_uri(input), "is_uri must be panic-safe for {input:?}");
            assert!(
                !is_uri_ref(input),
                "is_uri_ref must be panic-safe for {input:?}"
            );
        }
    }

    #[test]
    fn hex_digit_value_maps_ascii_hex_chars() {
        assert_eq!(hex_digit_value(b'0'), Some(0));
        assert_eq!(hex_digit_value(b'9'), Some(9));
        assert_eq!(hex_digit_value(b'a'), Some(10));
        assert_eq!(hex_digit_value(b'f'), Some(15));
        assert_eq!(hex_digit_value(b'A'), Some(10));
        assert_eq!(hex_digit_value(b'F'), Some(15));
        assert_eq!(hex_digit_value(b'g'), None);
        assert_eq!(hex_digit_value(b'G'), None);
        assert_eq!(hex_digit_value(b' '), None);
        assert_eq!(hex_digit_value(b'%'), None);
    }

    #[test]
    fn pct_decode_bytes_decodes_valid_sequences() {
        assert_eq!(pct_decode_bytes("hello"), b"hello");
        assert_eq!(pct_decode_bytes("%20"), b" ");
        assert_eq!(pct_decode_bytes("a%20b"), b"a b");
        assert_eq!(pct_decode_bytes("%C3%96"), b"\xC3\x96"); // ร– in UTF-8
    }

    #[test]
    fn pct_decode_bytes_passes_through_malformed_sequences() {
        // Incomplete pct-encoding at end
        assert_eq!(pct_decode_bytes("%2"), b"%2");
        assert_eq!(pct_decode_bytes("%"), b"%");
        // Invalid hex digits
        assert_eq!(pct_decode_bytes("%GG"), b"%GG");
        // Empty string
        assert_eq!(pct_decode_bytes(""), b"");
    }

    #[test]
    fn is_valid_zone_id_accepts_unreserved_and_pct_encoded() {
        assert!(is_valid_zone_id("eth0"));
        assert!(is_valid_zone_id("en-0"));
        assert!(is_valid_zone_id("my.iface"));
        assert!(is_valid_zone_id("iface_1"));
        assert!(is_valid_zone_id("a~b"));
        assert!(is_valid_zone_id("%25")); // pct-encoded '%'
        assert!(is_valid_zone_id("eth%250"));
    }

    #[test]
    fn is_valid_zone_id_rejects_invalid_chars() {
        // Note: empty string vacuously passes char validation;
        // the empty check is in strip_ipv6_zone_id.
        assert!(!is_valid_zone_id("eth 0")); // space
        assert!(!is_valid_zone_id("eth[0")); // bracket
        assert!(!is_valid_zone_id("eth/0")); // slash
        assert!(!is_valid_zone_id("%G0")); // invalid hex
        assert!(!is_valid_zone_id("%2")); // incomplete pct-encoding
        assert!(!is_valid_zone_id("%")); // bare percent
    }

    #[test]
    fn is_valid_reg_name_utf8_accepts_valid_hosts() {
        assert!(is_valid_reg_name_utf8("example.com"));
        assert!(is_valid_reg_name_utf8("[::1]")); // IP-literal skipped
        assert!(is_valid_reg_name_utf8("foo%C3%96bar")); // valid UTF-8 pct-encoded
        assert!(is_valid_reg_name_utf8("")); // empty reg-name is valid
    }

    #[test]
    fn is_valid_reg_name_utf8_rejects_invalid_utf8() {
        // %C3 alone is an incomplete UTF-8 sequence, but followed by 'x' (not valid continuation)
        assert!(!is_valid_reg_name_utf8("foo%c3x%96"));
        // Lone high byte
        assert!(!is_valid_reg_name_utf8("%FF"));
    }

    #[test]
    fn strip_ipv6_zone_id_removes_valid_zone() {
        let input = "http://[fe80::1%25eth0]:8080/path";
        let result = strip_ipv6_zone_id(input);
        assert_eq!(result.as_deref(), Some("http://[fe80::1]:8080/path"));
    }

    #[test]
    fn strip_ipv6_zone_id_returns_none_when_no_zone() {
        assert!(strip_ipv6_zone_id("http://[::1]:80/path").is_none());
        assert!(strip_ipv6_zone_id("http://example.com").is_none());
        assert!(strip_ipv6_zone_id("no-brackets").is_none());
    }

    #[test]
    fn strip_ipv6_zone_id_rejects_empty_zone() {
        // %25 with nothing after it
        assert!(strip_ipv6_zone_id("http://[fe80::1%25]:80/").is_none());
    }

    #[test]
    fn strip_ipv6_zone_id_rejects_invalid_zone_chars() {
        // Space in zone ID
        assert!(strip_ipv6_zone_id("http://[fe80::1%25eth 0]:80/").is_none());
    }

    #[test]
    fn strip_ipv6_zone_id_rejects_invalid_zone_utf8() {
        // Zone ID with invalid UTF-8 pct-encoding
        assert!(strip_ipv6_zone_id("http://[fe80::1%25%FF]:80/").is_none());
    }

    #[test]
    fn uri_accepts_ipv6_with_valid_zone_id() {
        assert!(is_uri("http://[fe80::1%25eth0]:8080/path"));
        assert!(is_uri("http://[fe80::a%25en1]/"));
    }

    #[test]
    fn uri_rejects_ipv6_with_empty_zone_id() {
        assert!(!is_uri("http://[fe80::1%25]:8080/path"));
    }

    #[test]
    fn uri_rejects_invalid_reg_name_utf8() {
        assert!(!is_uri("https://foo%c3x%96/path"));
    }
}