Skip to main content

flow_types/
path.rs

1//! The normal form of std's `path.Path` (`stdlib.md`, *`path`*), which
2//! `path.of` makes and decoding holds a `Path` to (`abi.md`, *Decoding*).
3
4/// The normal text of the path `text` names: `text` split on `/`, without
5/// its empty and `.` components and keeping every `..`, joined by `/` after
6/// a `/` when `text` starts with one; `.`, or `/` when absolute, when no
7/// component is left. Every text names a path, so this never fails.
8///
9/// ```
10/// assert_eq!(flow_types::normal_path("a//b/./c/"), "a/b/c");
11/// assert_eq!(flow_types::normal_path("/../x"), "/../x");
12/// assert_eq!(flow_types::normal_path(""), ".");
13/// ```
14pub fn normal_path(text: &str) -> String {
15    let absolute = text.starts_with('/');
16    let parts: Vec<&str> = text
17        .split('/')
18        .filter(|part| !part.is_empty() && *part != ".")
19        .collect();
20    let joined = parts.join("/");
21    match (absolute, joined.is_empty()) {
22        (true, _) => format!("/{joined}"),
23        (false, true) => ".".to_owned(),
24        (false, false) => joined,
25    }
26}
27
28#[cfg(test)]
29#[cfg_attr(coverage, coverage(off))]
30mod tests {
31    use super::*;
32
33    #[test]
34    fn the_normal_form_drops_empty_and_dot_components_and_keeps_every_dot_dot() {
35        for (text, normal) in [
36            ("a//b/./c/", "a/b/c"),
37            ("", "."),
38            (".", "."),
39            ("/", "/"),
40            ("//./", "/"),
41            ("/../x", "/../x"),
42            ("a/../b", "a/../b"),
43            ("a\0b", "a\0b"),
44        ] {
45            assert_eq!(normal_path(text), normal, "{text:?}");
46            assert_eq!(normal_path(normal), normal, "{normal:?}");
47        }
48        for spelled in ["a//b", "", "a/"] {
49            assert_ne!(normal_path(spelled), spelled, "{spelled:?}");
50        }
51    }
52}