use alloc::{
string::{String, ToString},
vec::Vec,
};
#[derive(Clone, Debug)]
pub struct PathLevel {
pub name: String,
pub index: usize,
}
#[derive(Clone, Debug, Default)]
pub struct Leveler {
pub levels: Vec<PathLevel>,
}
impl Leveler {
pub fn new(path: &str) -> Leveler {
Leveler {
levels: path
.split('/')
.enumerate()
.map(|(index, path)| PathLevel {
name: path.to_string(),
index,
})
.collect::<Vec<PathLevel>>(),
}
}
pub fn pop_one(&mut self) -> bool {
self.levels.pop().is_some()
}
pub fn to_string(&self) -> String {
self.levels
.iter()
.map(|level| level.name.clone())
.collect::<Vec<_>>()
.join("/")
}
pub fn join(&mut self, path: &str) -> i8 {
for command in path.split('/').collect::<Vec<&str>>() {
if command.starts_with("..") {
if !self.pop_one() {
return 1;
}
} else if command == "." {
continue;
} else {
self.levels.push(PathLevel {
name: command.to_string(),
index: self.levels.len(),
});
}
}
0
}
}
pub fn parse_module_import(path: &str, identifier: &str) -> Result<String, u8> {
let mut base = Leveler::new(path);
if base.levels.len() == 1 {
Err(1)
} else if base.pop_one() {
base.join(identifier);
Ok(base.to_string())
} else {
unreachable!()
}
}