1pub 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}