validate path on string parse

feat/vaults
Tomáš Mládek 2020-09-13 19:20:32 +02:00
parent d505653866
commit 2b92a1ad67
1 changed files with 26 additions and 12 deletions

View File

@ -35,13 +35,13 @@ const TOP_SEPARATOR: &str = "//";
impl std::str::FromStr for UPath {
type Err = anyhow::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
if s.len() == 0 {
fn from_str(string: &str) -> Result<Self, Self::Err> {
if string.len() == 0 {
Ok(UPath(vec![]))
} else {
match s.find(TOP_SEPARATOR) {
let result = match string.find(TOP_SEPARATOR) {
Some(head_idx) => {
let (head, rest) = s.split_at(head_idx);
let (head, rest) = string.split_at(head_idx);
let mut result: Vec<UDirectory> = Vec::new();
result.push(UDirectory {
name: String::from(head),
@ -55,16 +55,24 @@ impl std::str::FromStr for UPath {
.collect::<Vec<UDirectory>>()
.as_mut(),
);
Ok(UPath(result))
result
}
None => string
.split("/")
.map(|part| UDirectory {
name: String::from(part),
})
.collect(),
};
for directory in &result {
if directory.name.len() == 0 {
return Err(anyhow!("INVALID PATH: Directory name cannot be empty!"));
}
None => Ok(UPath(
s.split("/")
.map(|part| UDirectory {
name: String::from(part),
})
.collect(),
)),
}
Ok(UPath(result))
}
}
}
@ -339,4 +347,10 @@ mod tests {
assert_eq!(path, decoded_path.unwrap());
}
#[test]
fn test_validation() {
let invalid_path: Result<UPath> = "a//b/c//d/e/f///g".parse();
assert!(invalid_path.is_err())
}
}