pub fn canonical_path_len(path: &str) -> usize {
let mut len: usize = 0;
let mut skip: usize = 0;
for segment in path[1..].rsplit('/') {
match segment {
"." => {}
".." => skip += 1,
segment => {
if skip != 0 {
skip -= 1;
} else {
len += 1 + segment.len();
}
}
}
}
len + (ends_with_dot_segment(path) as usize)
}
pub fn write_canonical_path(path: &str, url: &mut String) {
let start: usize = url.len();
for segment in path[1..].split('/') {
match segment {
"." => {}
".." => {
if let Some(index) = url[start..].rfind('/') {
url.truncate(start + index);
}
}
segment => {
url.push('/');
url.push_str(segment);
}
}
}
if ends_with_dot_segment(path) {
url.push('/');
}
}
fn ends_with_dot_segment(path: &str) -> bool {
path.ends_with("/.") || path.ends_with("/..")
}
#[cfg(test)]
mod tests {
use crate::parse::{canonical_path_len, write_canonical_path};
#[test]
fn fn_write_canonical_path() {
let test_cases: &[(&str, &str)] = &[
("/", "/"),
("//", "//"),
("/a", "/a"),
("/a/", "/a/"),
("/a/b", "/a/b"),
("/.", "/"),
("/./", "/"),
("/a/.", "/a/"),
("/a/./b", "/a/b"),
("/..", "/"),
("/../", "/"),
("/a/..", "/"),
("/a/../", "/"),
("/a/b/..", "/a/"),
("/a/b/../c", "/a/c"),
("/a/b/../../c", "/c"),
("/a//../b", "/a/b"),
("/../a", "/a"),
("/../../a", "/a"),
("/a/../..", "/"),
("/..a", "/..a"),
("/a..", "/a.."),
("/.a/..", "/"),
("/%2e%2e", "/%2e%2e"),
("/a/%2e%2e", "/a/%2e%2e"),
];
for (path, expected) in test_cases {
let mut result: String = String::new();
write_canonical_path(path, &mut result);
assert_eq!(result, *expected, "path={}", path);
assert_eq!(canonical_path_len(path), result.len(), "path={}", path);
let mut again: String = String::new();
write_canonical_path(result.as_str(), &mut again);
assert_eq!(again, result, "path={}", path);
}
}
#[test]
fn fn_write_canonical_path_appends() {
let mut result: String = String::from("https://host");
write_canonical_path("/a/../../b", &mut result);
assert_eq!(result, "https://host/b");
}
}