flow-abi 0.1.0-rc.5

The host boundary's value encoding: the binary encoding and the JSON form, the canonical form and its hash, JSON Schemas, Tool signatures, and the answers a Tool call passes.
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
//! std's `url.Url` (`stdlib.md`, *`url`*): a URI by RFC 3986's `URI` rule,
//! held in the normal form of its §6.2.2, which `url.parse` makes and
//! decoding holds a `Url` to (`abi.md`, *Decoding*).
//!
//! Parsing splits the text at its ASCII delimiters, then reads each
//! component in one pass that refuses a character the component cannot hold,
//! writes a character that is not ASCII as its percent-encoded UTF-8 bytes
//! (and refuses one in the host), writes a percent-encoded unreserved
//! character as itself and every other percent-encoding in uppercase. Dot
//! segments are removed last, by §5.2.4. Each step is linear in the text.

use std::fmt::{self, Write as _};
use std::net::Ipv6Addr;

/// A URI by RFC 3986 in its normal form. Its text is [`fmt::Display`].
#[derive(Clone, PartialEq, Eq, Debug)]
#[must_use]
pub struct Url {
    scheme: String,
    authority: Option<Authority>,
    path: String,
    query: Option<String>,
    fragment: Option<String>,
}

#[derive(Clone, PartialEq, Eq, Debug)]
struct Authority {
    userinfo: Option<String>,
    host: String,
    /// Its digits as written; an empty port is dropped.
    port: Option<String>,
}

/// A URI reference (§4.1): a URI, or a relative reference, which has no
/// scheme. Each component is already in its normal spelling, but the path
/// keeps its dot segments.
struct Reference {
    scheme: Option<String>,
    authority: Option<Authority>,
    path: String,
    query: Option<String>,
    fragment: Option<String>,
}

/// The component a character stands in, which fixes what it may be.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Part {
    Userinfo,
    Host,
    Path,
    /// A query or a fragment, which hold the same characters.
    Query,
}

impl Url {
    /// The URL `text` spells, in its normal form, or `None` when it spells
    /// none: a relative reference is not a URL.
    ///
    /// ```
    /// let url = flow_abi::Url::parse("HTTP://Example.COM/a/./b/../%7euser?q=%c3%a9").unwrap();
    /// assert_eq!(url.to_string(), "http://example.com/a/~user?q=%C3%A9");
    /// assert!(flow_abi::Url::parse("/a/b").is_none());
    /// ```
    pub fn parse(text: &str) -> Option<Url> {
        let reference = reference(text)?;
        let scheme = reference.scheme?;
        Some(Url::finish(
            scheme,
            reference.authority,
            &reference.path,
            reference.query,
            reference.fragment,
        ))
    }

    /// The URL with these components, its dot segments removed and its path
    /// made one it can hold as itself.
    fn finish(
        scheme: String,
        authority: Option<Authority>,
        path: &str,
        query: Option<String>,
        fragment: Option<String>,
    ) -> Url {
        let mut path = remove_dot_segments(path);
        if authority.is_some() && path.is_empty() {
            path.push('/');
        } else if authority.is_none() && path.starts_with("//") {
            // Without an authority, a path cannot start with `//`, which
            // would read as one; `/.` keeps the path it was (§5.2.4 does
            // not remove a dot segment it would need to add back).
            path.insert_str(0, "/.");
        }
        Url {
            scheme,
            authority,
            path,
            query,
            fragment,
        }
    }

    /// `reference` resolved against this URL by RFC 3986 §5.2, or `None`
    /// when `reference` is not a URI reference.
    pub fn resolve(&self, reference: &str) -> Option<Url> {
        let r = self::reference(reference)?;
        let (scheme, authority, path, query) = if let Some(scheme) = r.scheme {
            (scheme, r.authority, r.path, r.query)
        } else if r.authority.is_some() {
            (self.scheme.clone(), r.authority, r.path, r.query)
        } else if r.path.is_empty() {
            (
                self.scheme.clone(),
                self.authority.clone(),
                self.path.clone(),
                r.query.or_else(|| self.query.clone()),
            )
        } else if r.path.starts_with('/') {
            (self.scheme.clone(), self.authority.clone(), r.path, r.query)
        } else {
            (
                self.scheme.clone(),
                self.authority.clone(),
                self.merge(&r.path),
                r.query,
            )
        };
        Some(Url::finish(scheme, authority, &path, query, r.fragment))
    }

    /// The path `relative` is relative to this URL's (§5.2.3). A URL with
    /// an authority has a path of at least `/` in its normal form, so the
    /// section's case of an empty one never arises.
    fn merge(&self, relative: &str) -> String {
        match self.path.rfind('/') {
            Some(at) => format!("{}{relative}", &self.path[..=at]),
            None => relative.to_owned(),
        }
    }

    /// Its scheme, in lowercase.
    pub fn scheme(&self) -> &str {
        &self.scheme
    }

    /// Its user information, `None` without an authority or without `@`.
    pub fn userinfo(&self) -> Option<&str> {
        self.authority.as_ref()?.userinfo.as_deref()
    }

    /// Its host, `None` without an authority; an IP literal keeps its
    /// brackets.
    pub fn host(&self) -> Option<&str> {
        Some(&self.authority.as_ref()?.host)
    }

    /// Its port's digits as written, `None` without one.
    pub fn port(&self) -> Option<&str> {
        self.authority.as_ref()?.port.as_deref()
    }

    /// Its path, percent-encoded as written.
    pub fn path(&self) -> &str {
        &self.path
    }

    /// Its query, percent-encoded, without the `?`.
    pub fn query(&self) -> Option<&str> {
        self.query.as_deref()
    }

    /// Its fragment, percent-encoded, without the `#`.
    pub fn fragment(&self) -> Option<&str> {
        self.fragment.as_deref()
    }

    /// Its query as name and value pairs: split on `&`, each non-empty part
    /// split at its first `=`, or paired with `""` without one, each side
    /// percent-decoded with `+` read as a space; `None` when a decoded side
    /// is not UTF-8.
    pub fn query_pairs(&self) -> Option<Vec<(String, String)>> {
        let Some(query) = &self.query else {
            return Some(Vec::new());
        };
        query
            .split('&')
            .filter(|part| !part.is_empty())
            .map(|part| {
                let (name, value) = part.split_once('=').unwrap_or((part, ""));
                Some((form_decode(name)?, form_decode(value)?))
            })
            .collect()
    }

    /// This URL with the query these pairs make, each side percent-encoded
    /// as UTF-8 except its unreserved characters; no pairs remove the query.
    pub fn with_query(&self, pairs: &[(&str, &str)]) -> Url {
        let query = (!pairs.is_empty()).then(|| {
            let mut query = String::new();
            for (at, (name, value)) in pairs.iter().enumerate() {
                if at > 0 {
                    query.push('&');
                }
                encode_into(&mut query, name, is_unreserved);
                query.push('=');
                encode_into(&mut query, value, is_unreserved);
            }
            query
        });
        Url {
            query,
            ..self.clone()
        }
    }

    /// This URL with the fragment `fragment`, each character a fragment
    /// cannot hold as itself, and `%`, percent-encoded; `None` removes it.
    pub fn with_fragment(&self, fragment: Option<&str>) -> Url {
        let fragment = fragment.map(|fragment| {
            let mut encoded = String::new();
            encode_into(&mut encoded, fragment, |byte| allowed(Part::Query, byte));
            encoded
        });
        Url {
            fragment,
            ..self.clone()
        }
    }

    /// This URL with the path `path`, written as [`Url::path`] reads, or
    /// `None` when it cannot hold `path` as its path.
    pub fn with_path(&self, path: &str) -> Option<Url> {
        let fits = if self.authority.is_some() {
            path.is_empty() || path.starts_with('/')
        } else {
            !path.starts_with("//")
        };
        if !fits {
            return None;
        }
        let path = component(path, Part::Path)?;
        Some(Url::finish(
            self.scheme.clone(),
            self.authority.clone(),
            &path,
            self.query.clone(),
            self.fragment.clone(),
        ))
    }
}

impl fmt::Display for Url {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}:", self.scheme)?;
        if let Some(authority) = &self.authority {
            f.write_str("//")?;
            if let Some(userinfo) = &authority.userinfo {
                write!(f, "{userinfo}@")?;
            }
            f.write_str(&authority.host)?;
            if let Some(port) = &authority.port {
                write!(f, ":{port}")?;
            }
        }
        f.write_str(&self.path)?;
        if let Some(query) = &self.query {
            write!(f, "?{query}")?;
        }
        if let Some(fragment) = &self.fragment {
            write!(f, "#{fragment}")?;
        }
        Ok(())
    }
}

/// The normal text of the URL `text` spells, or `None` when it spells none.
pub fn normal_url(text: &str) -> Option<String> {
    Url::parse(text).map(|url| url.to_string())
}

/// Reads the URI reference `text`, or `None` when it is not one.
fn reference(text: &str) -> Option<Reference> {
    let (rest, fragment) = match text.split_once('#') {
        Some((rest, fragment)) => (rest, Some(component(fragment, Part::Query)?)),
        None => (text, None),
    };
    let (rest, query) = match rest.split_once('?') {
        Some((rest, query)) => (rest, Some(component(query, Part::Query)?)),
        None => (rest, None),
    };
    // A `:` before any `/` ends a scheme; a first segment holding one is
    // otherwise no relative reference (§4.2).
    let (scheme, rest) = match rest.find([':', '/']) {
        Some(at) if rest.as_bytes()[at] == b':' => {
            let scheme = &rest[..at];
            if !is_scheme(scheme) {
                return None;
            }
            (Some(scheme.to_ascii_lowercase()), &rest[at + 1..])
        }
        _ => (None, rest),
    };
    let (authority, path) = match rest.strip_prefix("//") {
        Some(after) => {
            let end = after.find('/').unwrap_or(after.len());
            (Some(authority(&after[..end])?), &after[end..])
        }
        None => (None, rest),
    };
    Some(Reference {
        scheme,
        authority,
        path: component(path, Part::Path)?,
        query,
        fragment,
    })
}

/// `ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )`.
fn is_scheme(text: &str) -> bool {
    let mut bytes = text.bytes();
    bytes
        .next()
        .is_some_and(|first| first.is_ascii_alphabetic())
        && bytes.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'+' | b'-' | b'.'))
}

/// `[ userinfo "@" ] host [ ":" port ]`.
fn authority(text: &str) -> Option<Authority> {
    let (userinfo, rest) = match text.split_once('@') {
        Some((userinfo, rest)) => (Some(component(userinfo, Part::Userinfo)?), rest),
        None => (None, text),
    };
    let (host, port) = if rest.starts_with('[') {
        let end = rest.find(']')?;
        let (literal, after) = rest.split_at(end + 1);
        let port = match after {
            "" => None,
            _ => Some(after.strip_prefix(':')?),
        };
        (ip_literal(literal)?, port)
    } else {
        match rest.rsplit_once(':') {
            Some((host, port)) => (component(host, Part::Host)?, Some(port)),
            None => (component(rest, Part::Host)?, None),
        }
    };
    if !port.is_none_or(|port| port.bytes().all(|byte| byte.is_ascii_digit())) {
        return None;
    }
    Some(Authority {
        userinfo,
        host,
        port: port.filter(|port| !port.is_empty()).map(str::to_owned),
    })
}

/// `"[" ( IPv6address / IPvFuture ) "]"`, in lowercase.
fn ip_literal(literal: &str) -> Option<String> {
    let inner = &literal[1..literal.len() - 1];
    let valid = match inner.strip_prefix(['v', 'V']) {
        // `"v" 1*HEXDIG "." 1*( unreserved / sub-delims / ":" )`
        Some(future) => future.split_once('.').is_some_and(|(version, rest)| {
            !version.is_empty()
                && version.bytes().all(|byte| byte.is_ascii_hexdigit())
                && !rest.is_empty()
                && rest.bytes().all(|byte| allowed(Part::Userinfo, byte))
        }),
        None => inner.parse::<Ipv6Addr>().is_ok(),
    };
    valid.then(|| literal.to_ascii_lowercase())
}

/// Whether `byte` is RFC 3986's `unreserved`.
fn is_unreserved(byte: u8) -> bool {
    byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~')
}

/// Whether the ASCII `byte` may stand as itself in `part`.
fn allowed(part: Part, byte: u8) -> bool {
    let sub_delim = matches!(
        byte,
        b'!' | b'$' | b'&' | b'\'' | b'(' | b')' | b'*' | b'+' | b',' | b';' | b'='
    );
    is_unreserved(byte)
        || sub_delim
        || match part {
            Part::Host => false,
            Part::Userinfo => byte == b':',
            Part::Path => matches!(byte, b':' | b'@' | b'/'),
            Part::Query => matches!(byte, b':' | b'@' | b'/' | b'?'),
        }
}

/// `text` as `part` in its normal spelling, or `None` when `part` cannot
/// hold it.
fn component(text: &str, part: Part) -> Option<String> {
    let mut out = String::with_capacity(text.len());
    let bytes = text.as_bytes();
    let mut at = 0;
    while at < bytes.len() {
        let byte = bytes[at];
        if byte == b'%' {
            let high = hex(*bytes.get(at + 1)?)?;
            let low = hex(*bytes.get(at + 2)?)?;
            let decoded = high << 4 | low;
            if is_unreserved(decoded) {
                out.push(char::from(decoded));
            } else {
                push_encoded(&mut out, decoded);
            }
            at += 3;
        } else if byte.is_ascii() {
            if !allowed(part, byte) {
                return None;
            }
            out.push(char::from(byte));
            at += 1;
        } else {
            // A character that is not ASCII stands for its UTF-8 bytes
            // (RFC 3987 §3.1), except in the host.
            if part == Part::Host {
                return None;
            }
            let ch = text[at..].chars().next().expect("a character starts here");
            let mut buffer = [0; 4];
            for byte in ch.encode_utf8(&mut buffer).bytes() {
                push_encoded(&mut out, byte);
            }
            at += ch.len_utf8();
        }
    }
    if part == Part::Host {
        // Lowercase outside its percent-encodings, whose digits stay upper.
        let mut lowered = String::with_capacity(out.len());
        let mut escape = 0;
        for ch in out.chars() {
            if ch == '%' {
                escape = 3;
            }
            if escape > 0 {
                escape -= 1;
                lowered.push(ch);
            } else {
                lowered.push(ch.to_ascii_lowercase());
            }
        }
        out = lowered;
    }
    Some(out)
}

fn hex(byte: u8) -> Option<u8> {
    char::from(byte)
        .to_digit(16)
        .map(|digit| u8::try_from(digit).expect("a hex digit"))
}

fn push_encoded(out: &mut String, byte: u8) {
    write!(out, "%{byte:02X}").expect("writing to a String");
}

/// Writes `text`'s UTF-8, each byte `keep` refuses percent-encoded.
fn encode_into(out: &mut String, text: &str, keep: impl Fn(u8) -> bool) {
    for byte in text.bytes() {
        if byte.is_ascii() && byte != b'%' && keep(byte) {
            out.push(char::from(byte));
        } else {
            push_encoded(out, byte);
        }
    }
}

/// A query name or value decoded: `+` is a space and each percent-encoding
/// its byte, and each byte that does not fit UTF-8 is U+FFFD.
fn form_decode(text: &str) -> Option<String> {
    let bytes = text.as_bytes();
    let mut decoded = Vec::with_capacity(bytes.len());
    let mut at = 0;
    while at < bytes.len() {
        match bytes[at] {
            b'+' => decoded.push(b' '),
            b'%' => {
                // A normal query holds only whole percent-encodings.
                let high = hex(bytes[at + 1]).expect("a normal percent-encoding");
                let low = hex(bytes[at + 2]).expect("a normal percent-encoding");
                decoded.push(high << 4 | low);
                at += 2;
            }
            byte => decoded.push(byte),
        }
        at += 1;
    }
    String::from_utf8(decoded).ok()
}

/// RFC 3986 §5.2.4.
fn remove_dot_segments(path: &str) -> String {
    let mut input = path;
    let mut output = String::with_capacity(path.len());
    while !input.is_empty() {
        if let Some(rest) = input.strip_prefix("../") {
            input = rest;
        } else if let Some(rest) = input.strip_prefix("./") {
            input = rest;
        } else if input.starts_with("/./") {
            input = &input[2..];
        } else if input == "/." {
            input = "/";
        } else if input.starts_with("/../") || input == "/.." {
            input = if input == "/.." { "/" } else { &input[3..] };
            let cut = output.rfind('/').unwrap_or(0);
            output.truncate(cut);
        } else if input == "." || input == ".." {
            input = "";
        } else {
            let start = usize::from(input.starts_with('/'));
            let end = input[start..]
                .find('/')
                .map_or(input.len(), |at| at + start);
            output.push_str(&input[..end]);
            input = &input[end..];
        }
    }
    output
}

#[cfg(test)]
#[cfg_attr(coverage, coverage(off))]
mod tests {
    use super::*;

    #[test]
    fn dot_segments_are_removed_as_rfc_3986_section_5_2_4_does() {
        // RFC 3986 §5.2.4's own examples, and the edges of its loop.
        for (path, removed) in [
            ("/a/b/c/./../../g", "/a/g"),
            ("mid/content=5/../6", "mid/6"),
            ("/..", "/"),
            ("/.", "/"),
            ("..", ""),
            (".", ""),
            ("../a", "a"),
            ("./a", "a"),
            ("a/..", "/"),
            ("x/../../y", "/y"),
            ("", ""),
        ] {
            assert_eq!(remove_dot_segments(path), removed, "{path:?}");
        }
    }
}