#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum PathState {
Start,
Slash,
SingleDot,
DoubleDot,
PathComp,
}
pub fn normalize_path(path: &str) -> String {
let bytes = path.as_bytes();
let len = bytes.len();
if len == 0 {
return String::new();
}
let mut state = PathState::Start;
let mut start_with_slash = false;
let mut range: Vec<usize> = Vec::with_capacity(32);
for (i, &b) in bytes.iter().enumerate() {
let ch = b as char;
state = match state {
PathState::Start => match ch {
'.' => {
range.push(i);
PathState::SingleDot
}
'/' => {
start_with_slash = true;
PathState::Slash
}
_ => {
range.push(i);
PathState::PathComp
}
},
PathState::Slash => match ch {
'.' => {
range.push(i);
PathState::SingleDot
}
'/' => {
PathState::Slash
}
_ => {
range.push(i);
PathState::PathComp
}
},
PathState::SingleDot => match ch {
'.' => PathState::DoubleDot,
'/' => {
range.pop();
PathState::Slash
}
_ => PathState::PathComp,
},
PathState::DoubleDot => match ch {
'/' => {
for _ in 0..3 {
range.pop();
}
PathState::Slash
}
_ => PathState::PathComp,
},
PathState::PathComp => {
if ch == '/' {
range.push(i + 1);
PathState::Slash
} else {
PathState::PathComp
}
}
};
}
match state {
PathState::SingleDot => {
range.pop();
}
PathState::DoubleDot => {
for _ in 0..3 {
range.pop();
}
}
PathState::PathComp => {
range.push(len);
}
_ => {}
}
let mut out = Vec::with_capacity(len);
if start_with_slash {
out.push(b'/');
}
let mut i = 0;
while i + 1 < range.len() {
let a = range[i];
let b = range[i + 1];
out.extend_from_slice(&bytes[a..b]);
i += 2;
}
String::from_utf8(out).unwrap_or_default()
}
pub fn join_path(base_path: &str, new_path: &str) -> String {
join_path_inner(base_path, new_path)
}
fn join_path_inner(base_path: &str, new_path: &str) -> String {
if new_path.is_empty() {
return base_path.to_owned();
}
if base_path.is_empty() || new_path.starts_with('/') {
return normalize_path(new_path);
}
let combined = if base_path.ends_with('/') {
format!("{}{}", base_path, new_path)
} else {
format!("{}/{}", base_path, new_path)
};
normalize_path(&combined)
}