Skip to main content

engine/filesystem/
path.rs

1//! Virtual paths.
2//!
3//! A [`VirtualPath`] is an absolute, normalized path within the Engine
4//! filesystem. It is independent of any host platform path conventions.
5
6use std::fmt;
7use std::str::FromStr;
8
9use crate::core::metadata::Name;
10use crate::error::Error;
11
12/// The path separator of the virtual filesystem.
13pub const SEPARATOR: char = '/';
14
15/// An absolute, normalized virtual path.
16///
17/// Paths always start at the filesystem root. Repeated separators, `.`
18/// components, and `..` components are resolved during parsing (`..` clamps
19/// at the root). The root path displays as `/`.
20#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
21pub struct VirtualPath {
22    segments: Vec<String>,
23}
24
25impl VirtualPath {
26    /// The root path (`/`).
27    pub fn root() -> Self {
28        Self {
29            segments: Vec::new(),
30        }
31    }
32
33    /// Returns `true` for the root path.
34    pub fn is_root(&self) -> bool {
35        self.segments.is_empty()
36    }
37
38    /// The parent path, or `None` for the root.
39    pub fn parent(&self) -> Option<Self> {
40        if self.segments.is_empty() {
41            None
42        } else {
43            Some(Self {
44                segments: self.segments[..self.segments.len() - 1].to_vec(),
45            })
46        }
47    }
48
49    /// The final path component (the object name), if any.
50    pub fn name(&self) -> Option<&str> {
51        self.segments.last().map(String::as_str)
52    }
53
54    /// The normalized path components.
55    pub fn segments(&self) -> &[String] {
56        &self.segments
57    }
58
59    /// Appends a name component.
60    pub fn join(&self, name: &Name) -> Self {
61        let mut segments = self.segments.clone();
62        segments.push(name.as_str().to_owned());
63        Self { segments }
64    }
65
66    /// Returns `true` if `other` is a prefix of this path.
67    pub fn starts_with(&self, other: &Self) -> bool {
68        other.segments.len() <= self.segments.len()
69            && other
70                .segments
71                .iter()
72                .zip(&self.segments)
73                .all(|(a, b)| a == b)
74    }
75}
76
77impl FromStr for VirtualPath {
78    type Err = Error;
79
80    fn from_str(path: &str) -> Result<Self, Self::Err> {
81        if !path.starts_with(SEPARATOR) {
82            return Err(Error::InvalidPath(path.to_owned()));
83        }
84        if path.contains('\0') {
85            return Err(Error::InvalidPath(path.to_owned()));
86        }
87        let mut segments: Vec<String> = Vec::new();
88        for component in path.split(SEPARATOR) {
89            match component {
90                "" | "." => (),
91                ".." => {
92                    segments.pop();
93                }
94                name => {
95                    Name::new(name)?;
96                    segments.push(name.to_owned());
97                }
98            }
99        }
100        Ok(Self { segments })
101    }
102}
103
104impl fmt::Display for VirtualPath {
105    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
106        if self.segments.is_empty() {
107            write!(f, "{SEPARATOR}")
108        } else {
109            for segment in &self.segments {
110                write!(f, "{SEPARATOR}{segment}")?;
111            }
112            Ok(())
113        }
114    }
115}
116
117#[cfg(test)]
118mod tests {
119    use super::*;
120
121    fn parse(path: &str) -> VirtualPath {
122        path.parse()
123            .unwrap_or_else(|e| panic!("failed to parse {path:?}: {e}"))
124    }
125
126    #[test]
127    fn root_parses() {
128        let path = parse("/");
129        assert!(path.is_root());
130        assert_eq!(path.to_string(), "/");
131        assert_eq!(path.parent(), None);
132        assert_eq!(path.name(), None);
133    }
134
135    #[test]
136    fn simple_path_parses() {
137        let path = parse("/usr/bin/ls");
138        assert_eq!(path.segments(), ["usr", "bin", "ls"]);
139        assert_eq!(path.name(), Some("ls"));
140        assert_eq!(path.parent(), Some(parse("/usr/bin")));
141        assert_eq!(path.to_string(), "/usr/bin/ls");
142    }
143
144    #[test]
145    fn repeated_separators_are_collapsed() {
146        assert_eq!(parse("//usr///bin//").segments(), ["usr", "bin"]);
147    }
148
149    #[test]
150    fn dot_components_are_resolved() {
151        assert_eq!(parse("/a/./b").segments(), ["a", "b"]);
152    }
153
154    #[test]
155    fn dotdot_components_are_resolved() {
156        assert_eq!(parse("/a/b/../c").segments(), ["a", "c"]);
157    }
158
159    #[test]
160    fn dotdot_clamps_at_root() {
161        assert_eq!(parse("/../a").segments(), ["a"]);
162        assert!(parse("/..").is_root());
163    }
164
165    #[test]
166    fn relative_paths_are_rejected() {
167        assert!(matches!(
168            "usr/bin".parse::<VirtualPath>(),
169            Err(Error::InvalidPath(_))
170        ));
171    }
172
173    #[test]
174    fn nul_bytes_are_rejected() {
175        assert!(matches!(
176            "/a\0b".parse::<VirtualPath>(),
177            Err(Error::InvalidPath(_))
178        ));
179    }
180
181    #[test]
182    fn join_appends_a_component() {
183        assert_eq!(
184            parse("/usr").join(&Name::new("bin").unwrap()),
185            parse("/usr/bin")
186        );
187    }
188
189    #[test]
190    fn starts_with_is_prefix_aware() {
191        assert!(parse("/a/b/c").starts_with(&parse("/a/b")));
192        assert!(parse("/a/b").starts_with(&parse("/a/b")));
193        assert!(!parse("/a/bc").starts_with(&parse("/a/b")));
194        assert!(!parse("/a").starts_with(&parse("/a/b")));
195    }
196}