use std::fmt;
use crate::error::{PathError, PathErrorKind};
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct NormalizedPath(String);
impl NormalizedPath {
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
#[must_use]
pub fn into_string(self) -> String {
self.0
}
}
impl fmt::Display for NormalizedPath {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl AsRef<str> for NormalizedPath {
fn as_ref(&self) -> &str {
&self.0
}
}
pub fn validate_path(declared: &str) -> Result<NormalizedPath, PathError> {
if declared.is_empty() {
return Err(PathError::new(
PathErrorKind::Empty,
declared.to_string(),
"the path is empty".to_string(),
));
}
let bytes = declared.as_bytes();
if declared.starts_with('/')
|| (bytes.len() >= 2 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':')
{
return Err(PathError::new(
PathErrorKind::Absolute,
declared.to_string(),
"the path is absolute; sandbox paths are relative".to_string(),
));
}
if declared.contains('\\') {
return Err(PathError::new(
PathErrorKind::BackslashSeparator,
declared.to_string(),
"the path contains a backslash; the forward slash is the only separator spelling"
.to_string(),
));
}
let mut components: Vec<&str> = Vec::new();
for component in declared.split('/') {
match component {
"" | "." => {}
".." => {
return Err(PathError::new(
PathErrorKind::ParentTraversal,
declared.to_string(),
"the path contains a parent component".to_string(),
));
}
_ => components.push(component),
}
}
if components.is_empty() {
return Err(PathError::new(
PathErrorKind::Empty,
declared.to_string(),
"the path names no file after normalization".to_string(),
));
}
Ok(NormalizedPath(components.join("/")))
}