vce-engine 0.1.1

The generic state substrate of the Virtual Computing Engine (VCE)
Documentation
//! Virtual paths.
//!
//! A [`VirtualPath`] is an absolute, normalized path within the Engine
//! filesystem. It is independent of any host platform path conventions.

use std::fmt;
use std::str::FromStr;

use crate::core::metadata::Name;
use crate::error::Error;

/// The path separator of the virtual filesystem.
pub const SEPARATOR: char = '/';

/// An absolute, normalized virtual path.
///
/// Paths always start at the filesystem root. Repeated separators, `.`
/// components, and `..` components are resolved during parsing (`..` clamps
/// at the root). The root path displays as `/`.
#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
pub struct VirtualPath {
    segments: Vec<String>,
}

impl VirtualPath {
    /// The root path (`/`).
    pub fn root() -> Self {
        Self {
            segments: Vec::new(),
        }
    }

    /// Returns `true` for the root path.
    pub fn is_root(&self) -> bool {
        self.segments.is_empty()
    }

    /// The parent path, or `None` for the root.
    pub fn parent(&self) -> Option<Self> {
        if self.segments.is_empty() {
            None
        } else {
            Some(Self {
                segments: self.segments[..self.segments.len() - 1].to_vec(),
            })
        }
    }

    /// The final path component (the object name), if any.
    pub fn name(&self) -> Option<&str> {
        self.segments.last().map(String::as_str)
    }

    /// The normalized path components.
    pub fn segments(&self) -> &[String] {
        &self.segments
    }

    /// Appends a name component.
    pub fn join(&self, name: &Name) -> Self {
        let mut segments = self.segments.clone();
        segments.push(name.as_str().to_owned());
        Self { segments }
    }

    /// Returns `true` if `other` is a prefix of this path.
    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")));
    }
}