iri-rs-core 3.4.0

Core types, parser, resolver and normalizer for URIs/IRIs (RFC 3986/3987). Borrowed and owned, allocation-conscious, SIMD/SWAR-accelerated.
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
//! Hand-rolled grammar validators — oxiri port with `is_iri` flag for URI vs IRI flavors.
use std::{net::Ipv6Addr, str::FromStr};

use crate::{
    error::{IriParseError, IriParseErrorKind},
    parse::Positions,
};

// --- char-class tables -------------------------------------------------------

pub(crate) const fn set_alpha(a: &mut [bool; 256]) {
    let mut i = b'a';
    while i <= b'z' {
        a[i as usize] = true;
        i += 1;
    }
    let mut i = b'A';
    while i <= b'Z' {
        a[i as usize] = true;
        i += 1;
    }
}
pub(crate) const fn set_digit(a: &mut [bool; 256]) {
    let mut i = b'0';
    while i <= b'9' {
        a[i as usize] = true;
        i += 1;
    }
}
pub(crate) const fn set_unreserved(a: &mut [bool; 256]) {
    set_alpha(a);
    set_digit(a);
    a[b'-' as usize] = true;
    a[b'.' as usize] = true;
    a[b'_' as usize] = true;
    a[b'~' as usize] = true;
}
pub(crate) const fn set_sub_delims(a: &mut [bool; 256]) {
    a[b'!' as usize] = true;
    a[b'$' as usize] = true;
    a[b'&' as usize] = true;
    a[b'\'' as usize] = true;
    a[b'(' as usize] = true;
    a[b')' as usize] = true;
    a[b'*' as usize] = true;
    a[b'+' as usize] = true;
    a[b',' as usize] = true;
    a[b';' as usize] = true;
    a[b'=' as usize] = true;
}
pub(crate) const fn set_pchar(a: &mut [bool; 256]) {
    set_unreserved(a);
    set_sub_delims(a);
    a[b':' as usize] = true;
    a[b'@' as usize] = true;
}

pub const SCHEME_CHAR: [bool; 256] = {
    let mut a = [false; 256];
    set_alpha(&mut a);
    set_digit(&mut a);
    a[b'+' as usize] = true;
    a[b'-' as usize] = true;
    a[b'.' as usize] = true;
    a
};
pub const UNRESERVED_SUB_DELIMS: [bool; 256] = {
    let mut a = [false; 256];
    set_unreserved(&mut a);
    set_sub_delims(&mut a);
    a
};
pub const UNRESERVED_SUB_DELIMS_COLON: [bool; 256] = {
    let mut a = [false; 256];
    set_unreserved(&mut a);
    set_sub_delims(&mut a);
    a[b':' as usize] = true;
    a
};
pub const PCHAR: [bool; 256] = {
    let mut a = [false; 256];
    set_pchar(&mut a);
    a
};
pub const PCHAR_OR_SLASH: [bool; 256] = {
    let mut a = [false; 256];
    set_pchar(&mut a);
    a[b'/' as usize] = true;
    a
};
pub const PCHAR_OR_SLASH_OR_QUESTION: [bool; 256] = {
    let mut a = [false; 256];
    set_pchar(&mut a);
    a[b'/' as usize] = true;
    a[b'?' as usize] = true;
    a
};

#[inline]
#[must_use]
pub fn is_ucschar(c: char) -> bool {
    matches!(c,
        '\u{A0}'..='\u{D7FF}'
        | '\u{F900}'..='\u{FDCF}'
        | '\u{FDF0}'..='\u{FFEF}'
        | '\u{10000}'..='\u{1FFFD}'
        | '\u{20000}'..='\u{2FFFD}'
        | '\u{30000}'..='\u{3FFFD}'
        | '\u{40000}'..='\u{4FFFD}'
        | '\u{50000}'..='\u{5FFFD}'
        | '\u{60000}'..='\u{6FFFD}'
        | '\u{70000}'..='\u{7FFFD}'
        | '\u{80000}'..='\u{8FFFD}'
        | '\u{90000}'..='\u{9FFFD}'
        | '\u{A0000}'..='\u{AFFFD}'
        | '\u{B0000}'..='\u{BFFFD}'
        | '\u{C0000}'..='\u{CFFFD}'
        | '\u{D0000}'..='\u{DFFFD}'
        | '\u{E1000}'..='\u{EFFFD}')
}

#[inline]
#[must_use]
pub fn is_iprivate(c: char) -> bool {
    matches!(c, '\u{E000}'..='\u{F8FF}' | '\u{F0000}'..='\u{FFFFD}' | '\u{100000}'..='\u{10FFFD}')
}

/// # Errors
///
/// Returns an error when the scheme is empty, does not start with an ASCII letter, or holds a character outside `ALPHA / DIGIT / "+" / "-" / "."`.
pub fn validate_scheme(scheme: &str) -> Result<(), IriParseError> {
    let bytes = scheme.as_bytes();
    let first = *bytes.first().ok_or(IriParseErrorKind::EmptyScheme)?;
    if !first.is_ascii_alphabetic() {
        return Err(IriParseErrorKind::InvalidSchemeCharacter(scheme.chars().next().unwrap_or_default()).into());
    }
    if let Some(i) = bytes[1..].iter().position(|&c| !SCHEME_CHAR[c as usize]) {
        return Err(IriParseErrorKind::InvalidSchemeCharacter(scheme[i + 1..].chars().next().unwrap_or_default()).into());
    }
    Ok(())
}

/// # Errors
///
/// Returns an error when the userinfo, host or port part of the authority is not valid.
pub fn validate_authority(authority: &str, is_iri: bool) -> Result<(), IriParseError> {
    let Some(body) = authority.strip_prefix("//") else {
        return Err(IriParseErrorKind::InvalidHostCharacter(authority.chars().next().unwrap_or_default()).into());
    };
    validate_authority_body(body, is_iri)
}

pub(crate) fn validate_authority_body(body: &str, is_iri: bool) -> Result<(), IriParseError> {
    let mut remaining = body;
    if let Some(username_index) = memchr::memchr(b'@', remaining.as_bytes()) {
        let username = &remaining[..username_index];
        remaining = &remaining[username_index + 1..];
        validate_code_point_or_echar(username, UNRESERVED_SUB_DELIMS_COLON, is_iri, false)?;
    }
    if let Some(rest) = remaining.strip_prefix('[') {
        let Some(end) = memchr::memchr(b']', rest.as_bytes()) else {
            return Err(IriParseErrorKind::UnmatchedHostBracket.into());
        };
        validate_ip(&rest[..end])?;
        let rest = &rest[end + 1..];
        if !rest.is_empty() {
            let Some(port) = rest.strip_prefix(':') else {
                return Err(IriParseErrorKind::InvalidHostCharacter(rest.chars().next().unwrap()).into());
            };
            validate_port(port)?;
        }
    } else {
        if let Some(port_i) = memchr::memchr(b':', remaining.as_bytes()) {
            validate_port(&remaining[port_i + 1..])?;
            remaining = &remaining[..port_i];
        }
        validate_code_point_or_echar(remaining, UNRESERVED_SUB_DELIMS, is_iri, false)?;
    }
    Ok(())
}

/// # Errors
///
/// Returns an error when the host is neither a valid IP-literal nor a valid reg-name.
pub fn validate_host(host: &str, is_iri: bool) -> Result<(), IriParseError> {
    if let Some(ip) = host.strip_prefix('[') {
        let Some(end) = memchr::memchr(b']', ip.as_bytes()) else {
            return Err(IriParseErrorKind::UnmatchedHostBracket.into());
        };
        validate_ip(&ip[..end])?;
        if end + 1 != ip.len() {
            return Err(IriParseErrorKind::InvalidHostCharacter(ip[end + 1..].chars().next().unwrap_or_default()).into());
        }
        Ok(())
    } else {
        validate_code_point_or_echar(host, UNRESERVED_SUB_DELIMS, is_iri, false)
    }
}

/// # Errors
///
/// Returns an error at the first character not allowed in userinfo, or on a malformed percent-encoding.
pub fn validate_userinfo(s: &str, is_iri: bool) -> Result<(), IriParseError> {
    validate_code_point_or_echar(s, UNRESERVED_SUB_DELIMS_COLON, is_iri, false)
}

/// # Errors
///
/// Returns an error when the bracketed literal is neither an IPv6 address nor an `IPvFuture` form.
pub fn validate_ip(ip: &str) -> Result<(), IriParseError> {
    if ip.starts_with(['v', 'V']) {
        validate_ip_v_future(ip)
    } else {
        Ipv6Addr::from_str(ip).map(|_| ()).map_err(|e| IriParseErrorKind::InvalidHostIp(e).into())
    }
}

/// # Errors
///
/// Returns an error when the `vHEX.` prefix is missing or malformed, or the remainder holds a character not allowed in an `IPvFuture` address.
pub fn validate_ip_v_future(ip: &str) -> Result<(), IriParseError> {
    let Some(rest) = ip.strip_prefix(['v', 'V']) else {
        return Err(IriParseErrorKind::InvalidHostCharacter(ip.chars().next().unwrap_or_default()).into());
    };
    let version_size = rest.as_bytes().iter().position(|c| !c.is_ascii_hexdigit()).unwrap_or(rest.len());
    if version_size == 0 {
        return Err(IriParseErrorKind::InvalidHostCharacter(rest.chars().next().unwrap_or_default()).into());
    }
    let rest = &rest[version_size..];
    let Some(rest) = rest.strip_prefix('.') else {
        return Err(IriParseErrorKind::InvalidHostCharacter(rest.chars().next().unwrap_or_default()).into());
    };
    if rest.is_empty() {
        return Err(IriParseErrorKind::InvalidHostCharacter(']').into());
    }
    if let Some(i) = rest.as_bytes().iter().position(|&c| !UNRESERVED_SUB_DELIMS_COLON[c as usize]) {
        return Err(IriParseErrorKind::InvalidHostCharacter(rest[i..].chars().next().unwrap_or_default()).into());
    }
    Ok(())
}

/// # Errors
///
/// Returns an error when the port holds anything other than ASCII digits.
pub fn validate_port(port: &str) -> Result<(), IriParseError> {
    if let Some(i) = port.as_bytes().iter().position(|c| !c.is_ascii_digit()) {
        return Err(IriParseErrorKind::InvalidPortCharacter(port[i..].chars().next().unwrap_or_default()).into());
    }
    Ok(())
}

/// # Errors
///
/// Returns an error at the first character not allowed in a path, or on a malformed percent-encoding.
pub fn validate_path(path: &str, is_iri: bool) -> Result<(), IriParseError> {
    validate_code_point_or_echar(path, PCHAR_OR_SLASH, is_iri, false)
}

/// # Errors
///
/// Returns an error at the first character not allowed in a path segment, or on a malformed percent-encoding.
pub fn validate_segment(seg: &str, is_iri: bool) -> Result<(), IriParseError> {
    validate_code_point_or_echar(seg, PCHAR, is_iri, false)
}

/// # Errors
///
/// Returns an error at the first character not allowed in a query, or on a malformed percent-encoding.
pub fn validate_query(query: &str, is_iri: bool) -> Result<(), IriParseError> {
    validate_code_point_or_echar(query, PCHAR_OR_SLASH_OR_QUESTION, is_iri, true)
}

/// # Errors
///
/// Returns an error at the first character not allowed in a fragment, or on a malformed percent-encoding.
pub fn validate_fragment(fragment: &str, is_iri: bool) -> Result<(), IriParseError> {
    validate_code_point_or_echar(fragment, PCHAR_OR_SLASH_OR_QUESTION, is_iri, false)
}

/// # Errors
///
/// Returns an error at the first character the validator rejects, or on a percent-encoding that is not two hex digits.
///
/// # Panics
///
/// Cannot panic. `i` only ever advances by whole characters, so it is always a
/// char boundary below `input.len()` where the non-ASCII branch slices; the
/// `unwrap` there records that invariant rather than guarding a real case.
#[inline]
pub fn validate_code_point_or_echar(input: &str, ascii_validator: [bool; 256], is_iri: bool, allow_iprivate: bool) -> Result<(), IriParseError> {
    let bytes = input.as_bytes();
    let mut i = 0;
    while i < bytes.len() {
        let b = bytes[i];
        if b < 0x80 {
            if ascii_validator[b as usize] {
                i += 1;
            } else if b == b'%' {
                let c1 = bytes.get(i + 1).copied();
                let c2 = bytes.get(i + 2).copied();
                match (c1, c2) {
                    (Some(h1), Some(h2)) if h1.is_ascii_hexdigit() && h2.is_ascii_hexdigit() => {
                        i += 3;
                    }
                    _ => {
                        return Err(IriParseErrorKind::InvalidPercentEncoding([Some('%'), c1.map(|c| c as char), c2.map(|c| c as char)]).into());
                    }
                }
            } else {
                return Err(IriParseErrorKind::InvalidIriCodePoint(b as char).into());
            }
        } else if !is_iri {
            return Err(IriParseErrorKind::NonAsciiInUri.into());
        } else {
            let c = input[i..].chars().next().unwrap();
            if is_ucschar(c) || (allow_iprivate && is_iprivate(c)) {
                i += c.len_utf8();
            } else {
                return Err(IriParseErrorKind::InvalidIriCodePoint(c).into());
            }
        }
    }
    Ok(())
}

/// # Errors
///
/// Returns an error when any component delimited by `p` is invalid.
pub fn validate_iri_ref(iri: &str, p: Positions, is_iri: bool) -> Result<(), IriParseError> {
    if p.scheme_end > 0 {
        validate_scheme(&iri[..p.scheme_end - 1])?;
    }
    if p.authority_end > p.scheme_end {
        validate_authority(&iri[p.scheme_end..p.authority_end], is_iri)?;
    }
    validate_path(&iri[p.authority_end..p.path_end], is_iri)?;
    if p.query_end > p.path_end {
        validate_query(&iri[p.path_end + 1..p.query_end], is_iri)?;
    }
    if iri.len() > p.query_end {
        validate_fragment(&iri[p.query_end + 1..], is_iri)?;
    }
    Ok(())
}

/// # Errors
///
/// Returns an error when any component delimited by `p` is invalid, or when the scheme is absent, which an absolute IRI requires.
pub fn validate_iri(iri: &str, p: Positions, is_iri: bool) -> Result<(), IriParseError> {
    if p.scheme_end == 0 {
        return Err(IriParseErrorKind::NoScheme.into());
    }
    validate_iri_ref(iri, p, is_iri)
}

/// # Errors
///
/// Returns an error when the path is not valid for the authority it was resolved against: a path with no authority may not begin with `//`, and a relative reference may not hold a `:` in its first segment.
pub fn validate_resolved_path(iri: &str, p: Positions) -> Result<(), IriParseError> {
    if p.scheme_end == p.authority_end && iri[p.authority_end..].starts_with("//") {
        return Err(IriParseErrorKind::PathStartingWithTwoSlashes.into());
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn good_iri() {
        let s = "https://example.com/foo?q#f";
        let p = crate::parse::find_iri_positions(s);
        validate_iri(s, p, true).unwrap();
    }

    #[test]
    fn bad_scheme_empty() {
        assert!(validate_scheme("").is_err());
    }

    #[test]
    fn bad_scheme_digit_start() {
        assert!(validate_scheme("1ab").is_err());
    }

    #[test]
    fn pct_encoding_ok() {
        validate_path("/a%2Fb", false).unwrap();
    }

    #[test]
    fn pct_encoding_bad() {
        assert!(validate_path("/a%GG", false).is_err());
    }

    #[test]
    fn uri_rejects_unicode() {
        assert!(validate_path("/\u{00E9}", false).is_err());
    }

    #[test]
    fn iri_accepts_ucschar() {
        validate_path("/\u{00E9}", true).unwrap();
    }

    #[test]
    fn ipv6_host() {
        validate_host("[::1]", false).unwrap();
    }

    #[test]
    fn ipv6_host_bad() {
        assert!(validate_host("[::zzz]", false).is_err());
    }

    #[test]
    fn ipvfuture() {
        validate_host("[v1.abc]", false).unwrap();
    }

    #[test]
    fn iri_ref_relative() {
        let s = "../a/b";
        let p = crate::parse::find_iri_ref_positions(s);
        validate_iri_ref(s, p, true).unwrap();
    }

    #[test]
    fn query_iprivate_iri() {
        let s = "http://x/?\u{E000}";
        let p = crate::parse::find_iri_positions(s);
        validate_iri(s, p, true).unwrap();
    }

    fn iri_ref_is_valid(s: &str) -> bool {
        validate_iri_ref(s, crate::parse::find_iri_ref_positions(s), true).is_ok()
    }

    #[test]
    fn malformed_references_are_rejected() {
        for input in [
            "http://host name",      // space in host
            "http://host\0name",     // null byte
            "http://[::1",           // unclosed bracket
            "http://ho st/path",     // space in authority
            "htt p://host",          // space in scheme
            "http://host/pa th",     // space in path
            "http://host?qu ery",    // space in query
            "http://host#fra gment", // space in fragment
        ] {
            assert!(!iri_ref_is_valid(input), "should reject `{input}`");
        }
    }

    #[test]
    fn relative_reference_forms_are_accepted() {
        for input in [
            "",            // empty
            "/path",       // absolute path
            "../..",       // relative reference
            "?query",      // query only
            "#fragment",   // fragment only
            "//authority", // authority without scheme
        ] {
            assert!(iri_ref_is_valid(input), "should accept `{input}`");
        }
    }
}