use std::fmt;
use std::str::FromStr;
use crate::core::metadata::Name;
use crate::error::Error;
pub const SEPARATOR: char = '/';
#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
pub struct VirtualPath {
segments: Vec<String>,
}
impl VirtualPath {
pub fn root() -> Self {
Self {
segments: Vec::new(),
}
}
pub fn is_root(&self) -> bool {
self.segments.is_empty()
}
pub fn parent(&self) -> Option<Self> {
if self.segments.is_empty() {
None
} else {
Some(Self {
segments: self.segments[..self.segments.len() - 1].to_vec(),
})
}
}
pub fn name(&self) -> Option<&str> {
self.segments.last().map(String::as_str)
}
pub fn segments(&self) -> &[String] {
&self.segments
}
pub fn join(&self, name: &Name) -> Self {
let mut segments = self.segments.clone();
segments.push(name.as_str().to_owned());
Self { segments }
}
pub fn starts_with(&self, other: &Self) -> bool {
other.segments.len() <= self.segments.len()
&& other
.segments
.iter()
.zip(&self.segments)
.all(|(a, b)| a == b)
}
}
impl FromStr for VirtualPath {
type Err = Error;
fn from_str(path: &str) -> Result<Self, Self::Err> {
if !path.starts_with(SEPARATOR) {
return Err(Error::InvalidPath(path.to_owned()));
}
if path.contains('\0') {
return Err(Error::InvalidPath(path.to_owned()));
}
let mut segments: Vec<String> = Vec::new();
for component in path.split(SEPARATOR) {
match component {
"" | "." => (),
".." => {
segments.pop();
}
name => {
Name::new(name)?;
segments.push(name.to_owned());
}
}
}
Ok(Self { segments })
}
}
impl fmt::Display for VirtualPath {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.segments.is_empty() {
write!(f, "{SEPARATOR}")
} else {
for segment in &self.segments {
write!(f, "{SEPARATOR}{segment}")?;
}
Ok(())
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn parse(path: &str) -> VirtualPath {
path.parse()
.unwrap_or_else(|e| panic!("failed to parse {path:?}: {e}"))
}
#[test]
fn root_parses() {
let path = parse("/");
assert!(path.is_root());
assert_eq!(path.to_string(), "/");
assert_eq!(path.parent(), None);
assert_eq!(path.name(), None);
}
#[test]
fn simple_path_parses() {
let path = parse("/usr/bin/ls");
assert_eq!(path.segments(), ["usr", "bin", "ls"]);
assert_eq!(path.name(), Some("ls"));
assert_eq!(path.parent(), Some(parse("/usr/bin")));
assert_eq!(path.to_string(), "/usr/bin/ls");
}
#[test]
fn repeated_separators_are_collapsed() {
assert_eq!(parse("//usr///bin//").segments(), ["usr", "bin"]);
}
#[test]
fn dot_components_are_resolved() {
assert_eq!(parse("/a/./b").segments(), ["a", "b"]);
}
#[test]
fn dotdot_components_are_resolved() {
assert_eq!(parse("/a/b/../c").segments(), ["a", "c"]);
}
#[test]
fn dotdot_clamps_at_root() {
assert_eq!(parse("/../a").segments(), ["a"]);
assert!(parse("/..").is_root());
}
#[test]
fn relative_paths_are_rejected() {
assert!(matches!(
"usr/bin".parse::<VirtualPath>(),
Err(Error::InvalidPath(_))
));
}
#[test]
fn nul_bytes_are_rejected() {
assert!(matches!(
"/a\0b".parse::<VirtualPath>(),
Err(Error::InvalidPath(_))
));
}
#[test]
fn join_appends_a_component() {
assert_eq!(
parse("/usr").join(&Name::new("bin").unwrap()),
parse("/usr/bin")
);
}
#[test]
fn starts_with_is_prefix_aware() {
assert!(parse("/a/b/c").starts_with(&parse("/a/b")));
assert!(parse("/a/b").starts_with(&parse("/a/b")));
assert!(!parse("/a/bc").starts_with(&parse("/a/b")));
assert!(!parse("/a").starts_with(&parse("/a/b")));
}
}