iri-rs-core 3.3.7

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
//! Mutation methods on owning buffer types (`IriBuf`, `IriRefBuf`, `UriBuf`, `UriRefBuf`).

use crate::{
    components::first_segment_has_colon,
    error::{InvalidIri, InvalidUri, IriParseError},
    parse::find_iri_ref_positions,
    resolve::resolve,
    types::{Iri, IriBuf, IriRef, IriRefBuf, Uri, UriBuf, UriRef, UriRefBuf},
    validate::{validate_authority_body, validate_fragment, validate_iri_ref, validate_path, validate_query, validate_resolved_path, validate_scheme},
};

impl IriRefBuf {
    pub fn set_scheme(&mut self, scheme: Option<&str>) -> Result<(), IriParseError> {
        if let Some(s) = scheme {
            validate_scheme(s)?;
        }
        rebuild(self, Edit::Scheme(scheme.map(str::to_string)), true)
    }

    pub fn set_authority(&mut self, authority: Option<&str>) -> Result<(), IriParseError> {
        if let Some(a) = authority {
            validate_authority_body(a, true)?;
        }
        rebuild(self, Edit::Authority(authority.map(str::to_string)), true)
    }

    pub fn set_path(&mut self, path: &str) -> Result<(), IriParseError> {
        validate_path(path, true)?;
        rebuild(self, Edit::Path(path.to_string()), true)
    }

    pub fn set_query(&mut self, query: Option<&str>) -> Result<(), IriParseError> {
        if let Some(q) = query {
            validate_query(q, true)?;
        }
        rebuild(self, Edit::Query(query.map(str::to_string)), true)
    }

    pub fn set_fragment(&mut self, fragment: Option<&str>) -> Result<(), IriParseError> {
        if let Some(f) = fragment {
            validate_fragment(f, true)?;
        }
        rebuild(self, Edit::Fragment(fragment.map(str::to_string)), true)
    }

    pub fn resolve<T: std::ops::Deref<Target = str>>(&mut self, base: &Iri<T>) -> Result<(), IriParseError> {
        let mut out = String::with_capacity(self.as_str().len() + base.as_str().len());
        let pos = resolve((base.as_str(), base.positions()), (self.as_str(), self.positions), &mut out);
        validate_resolved_path(&out, pos)?;
        *self = IriRefBuf::from_raw_parts(out, pos);
        Ok(())
    }

    pub fn try_into_iri(self) -> Result<IriBuf, InvalidIri<IriRefBuf>> {
        if self.is_absolute() {
            let p = self.positions;
            Ok(Iri::from_raw_parts(self.into_inner(), p))
        } else {
            Err(InvalidIri(self))
        }
    }

    pub fn as_iri(&self) -> Option<Iri<&str>> {
        if self.is_absolute() {
            Some(Iri::from_raw_parts(self.as_str(), self.positions))
        } else {
            None
        }
    }
}

impl Default for IriRefBuf {
    fn default() -> Self {
        Self::parse_unchecked(String::new())
    }
}

impl Default for UriRefBuf {
    fn default() -> Self {
        Self::parse_unchecked(String::new())
    }
}

impl IriBuf {
    pub fn set_scheme(&mut self, scheme: &str) -> Result<(), IriParseError> {
        validate_scheme(scheme)?;
        let p = self.positions();
        let iri = std::mem::take(&mut self.0.iri);
        let mut r = IriRefBuf::from_raw_parts(iri, p);
        rebuild(&mut r, Edit::Scheme(Some(scheme.to_string())), true)?;
        *self = Iri::from_raw_parts(r.iri, r.positions);
        Ok(())
    }

    pub fn set_authority(&mut self, authority: Option<&str>) -> Result<(), IriParseError> {
        let p = self.positions();
        let iri = std::mem::take(&mut self.0.iri);
        let mut r = IriRefBuf::from_raw_parts(iri, p);
        r.set_authority(authority)?;
        *self = Iri::from_raw_parts(r.iri, r.positions);
        Ok(())
    }

    pub fn set_path(&mut self, path: &str) -> Result<(), IriParseError> {
        let p = self.positions();
        let iri = std::mem::take(&mut self.0.iri);
        let mut r = IriRefBuf::from_raw_parts(iri, p);
        r.set_path(path)?;
        *self = Iri::from_raw_parts(r.iri, r.positions);
        Ok(())
    }

    pub fn set_query(&mut self, query: Option<&str>) -> Result<(), IriParseError> {
        let p = self.positions();
        let iri = std::mem::take(&mut self.0.iri);
        let mut r = IriRefBuf::from_raw_parts(iri, p);
        r.set_query(query)?;
        *self = Iri::from_raw_parts(r.iri, r.positions);
        Ok(())
    }

    pub fn set_fragment(&mut self, fragment: Option<&str>) -> Result<(), IriParseError> {
        let p = self.positions();
        let iri = std::mem::take(&mut self.0.iri);
        let mut r = IriRefBuf::from_raw_parts(iri, p);
        r.set_fragment(fragment)?;
        *self = Iri::from_raw_parts(r.iri, r.positions);
        Ok(())
    }
}

impl UriRefBuf {
    pub fn set_scheme(&mut self, scheme: Option<&str>) -> Result<(), IriParseError> {
        if let Some(s) = scheme {
            validate_scheme(s)?;
        }
        rebuild_uri(self, Edit::Scheme(scheme.map(str::to_string)))
    }
    pub fn set_authority(&mut self, authority: Option<&str>) -> Result<(), IriParseError> {
        if let Some(a) = authority {
            validate_authority_body(a, false)?;
        }
        rebuild_uri(self, Edit::Authority(authority.map(str::to_string)))
    }
    pub fn set_path(&mut self, path: &str) -> Result<(), IriParseError> {
        validate_path(path, false)?;
        rebuild_uri(self, Edit::Path(path.to_string()))
    }
    pub fn set_query(&mut self, query: Option<&str>) -> Result<(), IriParseError> {
        if let Some(q) = query {
            validate_query(q, false)?;
        }
        rebuild_uri(self, Edit::Query(query.map(str::to_string)))
    }
    pub fn set_fragment(&mut self, fragment: Option<&str>) -> Result<(), IriParseError> {
        if let Some(f) = fragment {
            validate_fragment(f, false)?;
        }
        rebuild_uri(self, Edit::Fragment(fragment.map(str::to_string)))
    }
    pub fn resolve<T: std::ops::Deref<Target = str>>(&mut self, base: &Uri<T>) -> Result<(), IriParseError> {
        let mut out = String::with_capacity(self.as_str().len() + base.as_str().len());
        let pos = resolve((base.as_str(), base.positions()), (self.as_str(), self.positions), &mut out);
        validate_resolved_path(&out, pos)?;
        *self = UriRefBuf::from_raw_parts(out, pos);
        Ok(())
    }

    pub fn try_into_uri(self) -> Result<UriBuf, InvalidUri<UriRefBuf>> {
        if self.is_absolute() {
            let p = self.positions;
            Ok(Uri::from_raw_parts(self.into_inner(), p))
        } else {
            Err(InvalidUri(self))
        }
    }

    pub fn as_uri(&self) -> Option<Uri<&str>> {
        if self.is_absolute() {
            Some(Uri::from_raw_parts(self.as_str(), self.positions))
        } else {
            None
        }
    }
}

impl UriBuf {
    pub fn set_scheme(&mut self, scheme: &str) -> Result<(), IriParseError> {
        let p = self.positions();
        let uri = std::mem::take(&mut self.0.uri);
        let mut r = UriRefBuf::from_raw_parts(uri, p);
        r.set_scheme(Some(scheme))?;
        *self = Uri::from_raw_parts(r.uri, r.positions);
        Ok(())
    }
    pub fn set_authority(&mut self, authority: Option<&str>) -> Result<(), IriParseError> {
        let p = self.positions();
        let uri = std::mem::take(&mut self.0.uri);
        let mut r = UriRefBuf::from_raw_parts(uri, p);
        r.set_authority(authority)?;
        *self = Uri::from_raw_parts(r.uri, r.positions);
        Ok(())
    }
    pub fn set_path(&mut self, path: &str) -> Result<(), IriParseError> {
        let p = self.positions();
        let uri = std::mem::take(&mut self.0.uri);
        let mut r = UriRefBuf::from_raw_parts(uri, p);
        r.set_path(path)?;
        *self = Uri::from_raw_parts(r.uri, r.positions);
        Ok(())
    }
    pub fn set_query(&mut self, query: Option<&str>) -> Result<(), IriParseError> {
        let p = self.positions();
        let uri = std::mem::take(&mut self.0.uri);
        let mut r = UriRefBuf::from_raw_parts(uri, p);
        r.set_query(query)?;
        *self = Uri::from_raw_parts(r.uri, r.positions);
        Ok(())
    }
    pub fn set_fragment(&mut self, fragment: Option<&str>) -> Result<(), IriParseError> {
        let p = self.positions();
        let uri = std::mem::take(&mut self.0.uri);
        let mut r = UriRefBuf::from_raw_parts(uri, p);
        r.set_fragment(fragment)?;
        *self = Uri::from_raw_parts(r.uri, r.positions);
        Ok(())
    }
}

enum Edit {
    Scheme(Option<String>),
    Authority(Option<String>),
    Path(String),
    Query(Option<String>),
    Fragment(Option<String>),
}

fn rebuild(buf: &mut IriRefBuf, edit: Edit, is_iri: bool) -> Result<(), IriParseError> {
    let out = {
        let s = buf.as_str();
        let (scheme, authority, path, query, fragment) = destructure(s, buf.positions);
        let mut out = String::with_capacity(s.len() + 8);
        match &edit {
            Edit::Scheme(new) => write_iri(&mut out, new.as_deref(), authority, path, query, fragment),
            Edit::Authority(new) => write_iri(&mut out, scheme, new.as_deref(), path, query, fragment),
            Edit::Path(new) => write_iri(&mut out, scheme, authority, new, query, fragment),
            Edit::Query(new) => write_iri(&mut out, scheme, authority, path, new.as_deref(), fragment),
            Edit::Fragment(new) => write_iri(&mut out, scheme, authority, path, query, new.as_deref()),
        }
        out
    };
    let positions = find_iri_ref_positions(&out);
    validate_iri_ref(&out, positions, is_iri)?;
    *buf = IriRef::from_raw_parts(out, positions);
    Ok(())
}

fn write_iri(out: &mut String, scheme: Option<&str>, authority: Option<&str>, path: &str, query: Option<&str>, fragment: Option<&str>) {
    if let Some(s) = scheme {
        out.push_str(s);
        out.push(':');
    }
    if let Some(a) = authority {
        out.push_str("//");
        out.push_str(a);
    } else {
        // Removing a component can leave the path looking like the component
        // that is now gone. Both cases are recoverable with a dot segment,
        // which denotes the same path but cannot be misread on the way back in.
        if path.starts_with("//") {
            // RFC 3986 §3.3: with no authority, a path may not begin with `//`.
            out.push_str("/.");
        } else if scheme.is_none() && first_segment_has_colon(path) {
            // RFC 3986 §4.2: the first segment of a relative-path reference
            // may not hold a `:`, or it reads as a scheme.
            out.push_str("./");
        }
    }
    out.push_str(path);
    if let Some(q) = query {
        out.push('?');
        out.push_str(q);
    }
    if let Some(f) = fragment {
        out.push('#');
        out.push_str(f);
    }
}

fn rebuild_uri(buf: &mut UriRefBuf, edit: Edit) -> Result<(), IriParseError> {
    let mut tmp: IriRefBuf = IriRef::from_raw_parts(buf.as_str().to_string(), buf.positions);
    rebuild(&mut tmp, edit, false)?;
    let p = tmp.positions;
    *buf = UriRef::from_raw_parts(tmp.iri, p);
    Ok(())
}

fn destructure(s: &str, p: crate::parse::Positions) -> (Option<&str>, Option<&str>, &str, Option<&str>, Option<&str>) {
    let scheme = if p.scheme_end > 0 { Some(&s[..p.scheme_end - 1]) } else { None };
    let authority = if p.authority_end > p.scheme_end + 2
        || (p.authority_end == p.scheme_end + 2 && p.scheme_end + 2 <= s.len() && &s[p.scheme_end..p.scheme_end + 2] == "//")
    {
        Some(&s[p.scheme_end + 2..p.authority_end])
    } else {
        None
    };
    let path = &s[p.authority_end..p.path_end];
    let query = if p.query_end > p.path_end {
        Some(&s[p.path_end + 1..p.query_end])
    } else {
        None
    };
    let fragment = if s.len() > p.query_end { Some(&s[p.query_end + 1..]) } else { None };
    (scheme, authority, path, query, fragment)
}

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

    fn iri_ref(s: &str) -> IriRefBuf {
        IriRef::parse(s.to_owned()).unwrap()
    }

    /// Removing a scheme can leave the first path segment holding a `:`, which
    /// would be read back as a scheme of its own (RFC 3986 §4.2).
    #[test]
    fn removing_a_scheme_disambiguates_a_first_segment_with_a_colon() {
        let mut buf = iri_ref("scheme:a:b/c");
        buf.set_scheme(None).unwrap();

        assert_eq!(buf.as_str(), "./a:b/c");
        assert_eq!(buf.scheme(), None, "the path must not be read back as a scheme");
        assert_eq!(buf.path(), "./a:b/c");
    }

    /// Removing an authority can leave the path starting with `//`, which
    /// would be read back as an authority (RFC 3986 §3.3).
    #[test]
    fn removing_an_authority_disambiguates_a_path_starting_with_two_slashes() {
        let mut buf = iri_ref("//host//path");
        buf.set_authority(None).unwrap();

        assert_eq!(buf.as_str(), "/.//path");
        assert_eq!(buf.authority(), None, "the path must not be read back as an authority");
        assert_eq!(buf.path(), "/.//path");
    }

    #[test]
    fn removing_an_authority_disambiguates_under_a_scheme_too() {
        let mut buf = iri_ref("http://host//path");
        buf.set_authority(None).unwrap();

        assert_eq!(buf.as_str(), "http:/.//path");
        assert_eq!(buf.scheme(), Some("http"));
        assert_eq!(buf.authority(), None);
        assert_eq!(buf.path(), "/.//path");
    }

    #[test]
    fn setting_an_ambiguous_path_disambiguates_it() {
        let mut buf = iri_ref("http:x");
        buf.set_path("//foo").unwrap();
        assert_eq!(buf.as_str(), "http:/.//foo");
        assert_eq!(buf.authority(), None);

        let mut buf = iri_ref("x");
        buf.set_path("a:b").unwrap();
        assert_eq!(buf.as_str(), "./a:b");
        assert_eq!(buf.scheme(), None);
    }

    #[test]
    fn unambiguous_removals_gain_no_dot_segment() {
        let mut buf = iri_ref("http://host/path");
        buf.set_authority(None).unwrap();
        assert_eq!(buf.as_str(), "http:/path");

        let mut buf = iri_ref("scheme:/a/b");
        buf.set_scheme(None).unwrap();
        assert_eq!(buf.as_str(), "/a/b");

        // Only the *first* segment may not hold a `:`.
        let mut buf = iri_ref("scheme:a/b:c");
        buf.set_scheme(None).unwrap();
        assert_eq!(buf.as_str(), "a/b:c");

        // With an authority present the `//` is unambiguous.
        let mut buf = iri_ref("http://host//path");
        buf.set_scheme(None).unwrap();
        assert_eq!(buf.as_str(), "//host//path");
    }

    #[test]
    fn uri_buffers_disambiguate_the_same_way() {
        let mut buf: UriRefBuf = UriRef::parse("//host//path".to_owned()).unwrap();
        buf.set_authority(None).unwrap();
        assert_eq!(buf.as_str(), "/.//path");
        assert_eq!(buf.authority(), None);

        let mut buf: UriRefBuf = UriRef::parse("scheme:a:b/c".to_owned()).unwrap();
        buf.set_scheme(None).unwrap();
        assert_eq!(buf.as_str(), "./a:b/c");
        assert_eq!(buf.scheme(), None);
    }

    /// Upstream `iref` 4.0.1 fixed panics and silent corruption when a
    /// percent-encoded value reached a `set_*` method: it sized buffers with
    /// the decoded character count instead of the encoded byte length. This
    /// recomposes the whole string rather than splicing bytes, so the bug
    /// cannot occur — which stays true only as long as that holds.
    #[test]
    fn percent_encoded_values_survive_mutation() {
        let mut buf = iri_ref("scheme://user:pass@example.com:8080/path");
        buf.set_authority(Some("%6Eew_long_host.org")).unwrap();
        assert_eq!(buf.as_str(), "scheme://%6Eew_long_host.org/path");
        assert_eq!(buf.authority(), Some("%6Eew_long_host.org"));

        let mut buf = iri_ref("scheme://%65xample.com:8080/path");
        buf.set_authority(Some("example.com")).unwrap();
        assert_eq!(buf.authority(), Some("example.com"));

        let mut buf = iri_ref("scheme://authority/path");
        buf.set_query(Some("%71uery")).unwrap();
        buf.set_fragment(Some("%66rag")).unwrap();
        assert_eq!(buf.as_str(), "scheme://authority/path?%71uery#%66rag");
        assert_eq!(buf.query(), Some("%71uery"));
        assert_eq!(buf.fragment(), Some("%66rag"));

        buf.set_fragment(None).unwrap();
        assert_eq!(buf.as_str(), "scheme://authority/path?%71uery");
    }

    /// The inserted dot segments denote the same path, so resolving the result
    /// against a base reproduces the components the edit intended.
    #[test]
    fn disambiguated_results_resolve_to_the_intended_path() {
        let mut buf = iri_ref("//host//path");
        buf.set_authority(None).unwrap();

        let base = Iri::parse("http://example.org/a/b").unwrap();
        let resolved = buf.resolved(&base).unwrap();
        assert_eq!(resolved.as_str(), "http://example.org//path");
        assert_eq!(resolved.authority(), Some("example.org"));
        assert_eq!(resolved.path(), "//path");
    }
}