use std::fmt::Display;
use std::fmt::Formatter;
use std::fmt::Result as FmtResult;
use crate::error::FsError;
use crate::error::FsOperation;
use crate::error::FsResult;
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct RelativePath(
String,
);
impl RelativePath {
pub fn parse(text: &str) -> FsResult<Self> {
if text.is_empty() || text.starts_with('/') || text.contains('\0') {
return Err(invalid_relative());
}
let mut components = Vec::new();
for component in text.split('/') {
match component {
"" | "." => {}
".." => {
if components.pop().is_none() {
return Err(invalid_relative());
}
}
value => components.push(value),
}
}
if components.is_empty() {
return Err(invalid_relative());
}
Ok(Self(components.join("/")))
}
#[inline]
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
}
impl Display for RelativePath {
#[inline]
fn fmt(&self, formatter: &mut Formatter<'_>) -> FmtResult {
formatter.write_str(self.as_str())
}
}
fn invalid_relative() -> FsError {
FsError::invalid_path(
FsOperation::ParsePath,
"relative path must identify a descendant without escaping its base",
)
}